code
stringlengths
1
2.08M
language
stringclasses
1 value
// 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 Event Manager. * * Provides an abstracted interface to the browsers' event * systems. This uses an indirect lookup of listener functions to avoid circular * references between DOM (in IE) or XPCOM (in Mozilla) objects which leak * memory. This makes it easier to write OO Javascript/DOM code. * * It simulates capture & bubble in Internet Explorer. * * The listeners will also automagically have their event objects patched, so * your handlers don't need to worry about the browser. * * Example usage: * <pre> * goog.events.listen(myNode, 'click', function(e) { alert('woo') }); * goog.events.listen(myNode, 'mouseover', mouseHandler, true); * goog.events.unlisten(myNode, 'mouseover', mouseHandler, true); * goog.events.removeAll(myNode); * goog.events.removeAll(); * </pre> * * in IE and event object patching] * * @supported IE6+, FF1.5+, WebKit, Opera. * @see ../demos/events.html * @see ../demos/event-propagation.html * @see ../demos/stopevent.html */ // This uses 3 lookup tables/trees. // listenerTree_ is a tree of type -> capture -> src uid -> [Listener] // listeners_ is a map of key -> [Listener] // // The key is a field of the Listener. The Listener class also has the type, // capture and the src so one can always trace back in the tree // // sources_: src uid -> [Listener] goog.provide('goog.events'); goog.provide('goog.events.Key'); goog.provide('goog.events.ListenableType'); goog.require('goog.array'); /** @suppress {extraRequire} */ goog.require('goog.debug.entryPointRegistry'); goog.require('goog.events.BrowserEvent'); goog.require('goog.events.BrowserFeature'); goog.require('goog.events.Event'); goog.require('goog.events.Listenable'); goog.require('goog.events.Listener'); goog.require('goog.object'); /** * @typedef {number|goog.events.ListenableKey} */ goog.events.Key; /** * @typedef {EventTarget|goog.events.Listenable|goog.events.EventTarget} */ goog.events.ListenableType; /** * Whether to be strict with custom event targets. When set to true, * listening/dispatching on un-initialized event targets will fail. * An event target may be un-initialized if you forgot to call * goog.events.EventTarget constructor in the custom event target * constructor. * @type {boolean} */ goog.events.STRICT_EVENT_TARGET = false; /** * Container for storing event listeners and their proxies * @private * @type {Object.<goog.events.ListenableKey>} */ goog.events.listeners_ = {}; /** * The root of the listener tree * @private * @type {Object} */ goog.events.listenerTree_ = {}; /** * Lookup for mapping source UIDs to listeners. * @private * @type {Object} */ goog.events.sources_ = {}; /** * String used to prepend to IE event types. Not a constant so that it is not * inlined. * @type {string} * @private */ goog.events.onString_ = 'on'; /** * Map of computed on strings for IE event types. Caching this removes an extra * object allocation in goog.events.listen which improves IE6 performance. * @type {Object} * @private */ goog.events.onStringMap_ = {}; /** * Separator used to split up the various parts of an event key, to help avoid * the possibilities of collisions. * @type {string} * @private */ goog.events.keySeparator_ = '_'; /** * Adds an event listener for a specific event on a DOM Node or an * object that has implemented {@link goog.events.EventTarget}. 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 {goog.events.ListenableType} src The node to listen to * events on. * @param {string|Array.<string>} type Event type or array of event types. * @param {Function|Object} listener Callback method, or an object with a * handleEvent function. * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to * false). * @param {Object=} opt_handler Element in whose scope to call the listener. * @return {goog.events.Key} Unique key for the listener. */ goog.events.listen = function(src, type, listener, opt_capt, opt_handler) { if (goog.isArray(type)) { for (var i = 0; i < type.length; i++) { goog.events.listen(src, type[i], listener, opt_capt, opt_handler); } return null; } var listenableKey; if (goog.events.Listenable.USE_LISTENABLE_INTERFACE && goog.events.Listenable.isImplementedBy(src)) { listenableKey = src.listen( /** @type {string} */ (type), goog.events.wrapListener_(listener), opt_capt, opt_handler); } else { listenableKey = goog.events.listen_( /** @type {EventTarget|goog.events.EventTarget} */ (src), type, listener, /* callOnce */ false, opt_capt, opt_handler); } var key = listenableKey.key; goog.events.listeners_[key] = listenableKey; return key; }; /** * Property name that indicates that an object is a * goog.events.EventTarget. * @type {string} * @const */ goog.events.CUSTOM_EVENT_ATTR = 'customEvent_'; /** * Adds an event listener for a specific event on a DOM Node or an object that * has implemented {@link goog.events.EventTarget}. 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 {EventTarget|goog.events.EventTarget} src The node to listen to * events on. * @param {?string} type Event type or array of event types. * @param {Function|Object} listener Callback method, or an object with a * handleEvent function. * @param {boolean} callOnce Whether the listener is a one-off * listener or otherwise. * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to * false). * @param {Object=} opt_handler Element in whose scope to call the listener. * @return {goog.events.ListenableKey} Unique key for the listener. * @private */ goog.events.listen_ = function( src, type, listener, callOnce, opt_capt, opt_handler) { if (!type) { throw Error('Invalid event type'); } var capture = !!opt_capt; var map = goog.events.listenerTree_; if (!(type in map)) { map[type] = {count_: 0, remaining_: 0}; } map = map[type]; if (!(capture in map)) { map[capture] = {count_: 0, remaining_: 0}; map.count_++; } map = map[capture]; var srcUid = goog.getUid(src); var listenerArray, listenerObj; // The remaining_ property is used to be able to short circuit the iteration // of the event listeners. // // Increment the remaining event listeners to call even if this event might // already have been fired. At this point we do not know if the event has // been fired and it is too expensive to find out. By incrementing it we are // guaranteed that we will not skip any event listeners. map.remaining_++; // Do not use srcUid in map here since that will cast the number to a // string which will allocate one string object. if (!map[srcUid]) { listenerArray = map[srcUid] = []; map.count_++; } else { listenerArray = map[srcUid]; // Ensure that the listeners do not already contain the current listener for (var i = 0; i < listenerArray.length; i++) { listenerObj = listenerArray[i]; if (listenerObj.listener == listener && listenerObj.handler == opt_handler) { // If this listener has been removed we should not return its key. It // is OK that we create new listenerObj below since the removed one // will be cleaned up later. if (listenerObj.removed) { break; } if (!callOnce) { // Ensure that, if there is an existing callOnce listener, it is no // longer a callOnce listener. listenerArray[i].callOnce = false; } // We already have this listener. Return its key. return listenerArray[i]; } } } var proxy = goog.events.getProxy(); listenerObj = new goog.events.Listener(); listenerObj.init(listener, proxy, src, type, capture, opt_handler); listenerObj.callOnce = callOnce; proxy.src = src; proxy.listener = listenerObj; listenerArray.push(listenerObj); if (!goog.events.sources_[srcUid]) { goog.events.sources_[srcUid] = []; } goog.events.sources_[srcUid].push(listenerObj); // Attach the proxy through the browser's API if (src.addEventListener) { if (src == goog.global || !src[goog.events.CUSTOM_EVENT_ATTR]) { src.addEventListener(type, proxy, capture); } else if (goog.events.STRICT_EVENT_TARGET) { src.assertInitialized(); } } else { // The else above used to be else if (src.attachEvent) and then there was // another else statement that threw an exception warning the developer // they made a mistake. This resulted in an extra object allocation in IE6 // due to a wrapper object that had to be implemented around the element // and so was removed. src.attachEvent(goog.events.getOnString_(type), proxy); } return listenerObj; }; /** * Helper function for returning a proxy function. * @return {Function} A new or reused function object. */ goog.events.getProxy = function() { var proxyCallbackFunction = goog.events.handleBrowserEvent_; // Use a local var f to prevent one allocation. var f = goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT ? function(eventObject) { return proxyCallbackFunction.call(f.src, f.listener, eventObject); } : function(eventObject) { var v = proxyCallbackFunction.call(f.src, f.listener, eventObject); // NOTE(user): In IE, we hack in a capture phase. However, if // there is inline event handler which tries to prevent default (for // example <a href="..." onclick="return false">...</a>) in a // descendant element, the prevent default will be overridden // by this listener if this listener were to return true. Hence, we // return undefined. if (!v) return v; }; return f; }; /** * Adds an event listener for a specific event on a DomNode or an object that * has implemented {@link goog.events.EventTarget}. After the event has fired * the event listener is removed from the target. * * 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 {goog.events.ListenableType} src The node to listen to * events on. * @param {string|Array.<string>} type Event type or array of event types. * @param {Function|Object} listener Callback method. * @param {boolean=} opt_capt Fire in capture phase?. * @param {Object=} opt_handler Element in whose scope to call the listener. * @return {goog.events.Key} Unique key for the listener. */ goog.events.listenOnce = function(src, type, listener, opt_capt, opt_handler) { if (goog.isArray(type)) { for (var i = 0; i < type.length; i++) { goog.events.listenOnce(src, type[i], listener, opt_capt, opt_handler); } return null; } var listenableKey; if (goog.events.Listenable.USE_LISTENABLE_INTERFACE && goog.events.Listenable.isImplementedBy(src)) { listenableKey = src.listenOnce( /** @type {string} */ (type), goog.events.wrapListener_(listener), opt_capt, opt_handler); } else { listenableKey = goog.events.listen_( /** @type {EventTarget|goog.events.EventTarget} */ (src), type, listener, /* callOnce */ true, opt_capt, opt_handler); } var key = listenableKey.key; goog.events.listeners_[key] = listenableKey; return key; }; /** * Adds an event listener with a specific event wrapper on a DOM Node or an * object that has implemented {@link goog.events.EventTarget}. A listener can * only be added once to an object. * * @param {EventTarget|goog.events.EventTarget} src The node to listen to * events on. * @param {goog.events.EventWrapper} wrapper Event wrapper to use. * @param {Function|Object} listener Callback method, or an object with a * handleEvent function. * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to * false). * @param {Object=} opt_handler Element in whose scope to call the listener. */ goog.events.listenWithWrapper = function(src, wrapper, listener, opt_capt, opt_handler) { wrapper.listen(src, listener, opt_capt, opt_handler); }; /** * Removes an event listener which was added with listen(). * * @param {goog.events.ListenableType} src The target to stop * listening to events on. * @param {string|Array.<string>} type The name of the event without the 'on' * prefix. * @param {Function|Object} listener The listener function to remove. * @param {boolean=} opt_capt In DOM-compliant browsers, this determines * whether the listener is fired during the capture or bubble phase of the * event. * @param {Object=} opt_handler Element in whose scope to call the listener. * @return {?boolean} indicating whether the listener was there to remove. */ goog.events.unlisten = function(src, type, listener, opt_capt, opt_handler) { if (goog.isArray(type)) { for (var i = 0; i < type.length; i++) { goog.events.unlisten(src, type[i], listener, opt_capt, opt_handler); } return null; } if (goog.events.Listenable.USE_LISTENABLE_INTERFACE && goog.events.Listenable.isImplementedBy(src)) { return src.unlisten( /** @type {string} */ (type), goog.events.wrapListener_(listener), opt_capt, opt_handler); } var capture = !!opt_capt; var listenerArray = goog.events.getListeners_(src, type, capture); if (!listenerArray) { return false; } for (var i = 0; i < listenerArray.length; i++) { if (listenerArray[i].listener == listener && listenerArray[i].capture == capture && listenerArray[i].handler == opt_handler) { return goog.events.unlistenByKey(listenerArray[i].key); } } return false; }; /** * Removes an event listener which was added with listen() by the key * returned by listen(). * * @param {goog.events.Key} key The key returned by listen() for this * event listener. * @return {boolean} indicating whether the listener was there to remove. */ goog.events.unlistenByKey = function(key) { // TODO(user): When we flip goog.events.Key to be ListenableKey, // we need to change this. var listener = goog.events.listeners_[key]; if (!listener) { return false; } if (listener.removed) { return false; } var src = listener.src; if (goog.events.Listenable.USE_LISTENABLE_INTERFACE && goog.events.Listenable.isImplementedBy(src)) { return src.unlistenByKey(listener); } var type = listener.type; var proxy = listener.proxy; var capture = listener.capture; if (src.removeEventListener) { // EventTarget calls unlisten so we need to ensure that the source is not // an event target to prevent re-entry. // TODO(arv): What is this goog.global for? Why would anyone listen to // events on the [[Global]] object? Is it supposed to be window? Why would // we not want to allow removing event listeners on the window? if (src == goog.global || !src[goog.events.CUSTOM_EVENT_ATTR]) { src.removeEventListener(type, proxy, capture); } } else if (src.detachEvent) { src.detachEvent(goog.events.getOnString_(type), proxy); } var srcUid = goog.getUid(src); // In a perfect implementation we would decrement the remaining_ field here // but then we would need to know if the listener has already been fired or // not. We therefore skip doing this and in this uncommon case the entire // ancestor chain will need to be traversed as before. // Remove from sources_ if (goog.events.sources_[srcUid]) { var sourcesArray = goog.events.sources_[srcUid]; goog.array.remove(sourcesArray, listener); if (sourcesArray.length == 0) { delete goog.events.sources_[srcUid]; } } listener.removed = true; // There are some esoteric situations where the hash code of an object // can change, and we won't be able to find the listenerArray anymore. // For example, if you're listening on a window, and the user navigates to // a different window, the UID will disappear. // // It should be impossible to ever find the original listenerArray, so it // doesn't really matter if we can't clean it up in this case. var listenerArray = goog.events.listenerTree_[type][capture][srcUid]; if (listenerArray) { listenerArray.needsCleanup_ = true; goog.events.cleanUp_(type, capture, srcUid, listenerArray); } delete goog.events.listeners_[key]; return true; }; /** * Removes an event listener which was added with listenWithWrapper(). * * @param {EventTarget|goog.events.EventTarget} src The target to stop * listening to events on. * @param {goog.events.EventWrapper} wrapper Event wrapper to use. * @param {Function|Object} listener The listener function to remove. * @param {boolean=} opt_capt In DOM-compliant browsers, this determines * whether the listener is fired during the capture or bubble phase of the * event. * @param {Object=} opt_handler Element in whose scope to call the listener. */ goog.events.unlistenWithWrapper = function(src, wrapper, listener, opt_capt, opt_handler) { wrapper.unlisten(src, listener, opt_capt, opt_handler); }; /** * Cleans up goog.events internal data structure. This should be * called by all implementations of goog.events.Listenable when * removing listeners. * * TODO(user): Once we remove numeric key support from * goog.events.listen and friend, we will be able to remove this * requirement. * * @param {goog.events.ListenableKey} listenableKey The key to clean up. */ goog.events.cleanUp = function(listenableKey) { delete goog.events.listeners_[listenableKey.key]; }; /** * Cleans up the listener array as well as the listener tree * @param {string} type The type of the event. * @param {boolean} capture Whether to clean up capture phase listeners instead * bubble phase listeners. * @param {number} srcUid The unique ID of the source. * @param {Array.<goog.events.Listener>} listenerArray The array being cleaned. * @private */ goog.events.cleanUp_ = function(type, capture, srcUid, listenerArray) { // The listener array gets locked during the dispatch phase so that removals // of listeners during this phase does not screw up the indeces. This method // is called after we have removed a listener as well as after the dispatch // phase in case any listeners were removed. if (!listenerArray.locked_) { // catches both 0 and not set if (listenerArray.needsCleanup_) { // Loop over the listener array and remove listeners that have removed set // to true. This could have been done with filter or something similar but // we want to change the array in place and we want to minimize // allocations. Adding a listener during this phase adds to the end of the // array so that works fine as long as the length is rechecked every in // iteration. for (var oldIndex = 0, newIndex = 0; oldIndex < listenerArray.length; oldIndex++) { if (listenerArray[oldIndex].removed) { var proxy = listenerArray[oldIndex].proxy; proxy.src = null; continue; } if (oldIndex != newIndex) { listenerArray[newIndex] = listenerArray[oldIndex]; } newIndex++; } listenerArray.length = newIndex; listenerArray.needsCleanup_ = false; // In case the length is now zero we release the object. if (newIndex == 0) { delete goog.events.listenerTree_[type][capture][srcUid]; goog.events.listenerTree_[type][capture].count_--; if (goog.events.listenerTree_[type][capture].count_ == 0) { delete goog.events.listenerTree_[type][capture]; goog.events.listenerTree_[type].count_--; } if (goog.events.listenerTree_[type].count_ == 0) { delete goog.events.listenerTree_[type]; } } } } }; /** * Removes all listeners from an object. You can also optionally * remove listeners of a particular type. * * @param {Object=} opt_obj Object to remove listeners from. Not * specifying opt_obj is now DEPRECATED (it used to remove all * registered listeners). * @param {string=} opt_type Type of event to, default is all types. * @return {number} Number of listeners removed. */ goog.events.removeAll = function(opt_obj, opt_type) { var count = 0; var noObj = opt_obj == null; var noType = opt_type == null; if (!noObj) { if (goog.events.Listenable.USE_LISTENABLE_INTERFACE && opt_obj && goog.events.Listenable.isImplementedBy(opt_obj)) { return opt_obj.removeAllListeners(opt_type); } var srcUid = goog.getUid(/** @type {Object} */ (opt_obj)); if (goog.events.sources_[srcUid]) { var sourcesArray = goog.events.sources_[srcUid]; for (var i = sourcesArray.length - 1; i >= 0; i--) { var listener = sourcesArray[i]; if (noType || opt_type == listener.type) { goog.events.unlistenByKey(listener.key); count++; } } } } else { goog.object.forEach(goog.events.listeners_, function(listener, key) { goog.events.unlistenByKey(key); count++; }); } return count; }; /** * Removes all native listeners registered via goog.events. Native * listeners are listeners on native browser objects (such as DOM * elements). In particular, goog.events.Listenable and * goog.events.EventTarget listeners will NOT be removed. * @return {number} Number of listeners removed. */ goog.events.removeAllNativeListeners = function() { var count = 0; goog.object.forEach(goog.events.listeners_, function(listener, key) { var src = listener.src; // Only remove the listener if it is not on custom event target. if (!goog.events.Listenable.isImplementedBy(src) && !src[goog.events.CUSTOM_EVENT_ATTR]) { goog.events.unlistenByKey(key); count++; } }); return count; }; /** * Gets the listeners for a given object, type and capture phase. * * @param {Object} obj Object to get listeners for. * @param {string} type Event type. * @param {boolean} capture Capture phase?. * @return {Array.<goog.events.Listener>} Array of listener objects. */ goog.events.getListeners = function(obj, type, capture) { if (goog.events.Listenable.USE_LISTENABLE_INTERFACE && goog.events.Listenable.isImplementedBy(obj)) { return obj.getListeners(type, capture); } else { return goog.events.getListeners_(obj, type, capture) || []; } }; /** * Gets the listeners for a given object, type and capture phase. * * @param {Object} obj Object to get listeners for. * @param {?string} type Event type. * @param {boolean} capture Capture phase?. * @return {Array.<goog.events.Listener>?} Array of listener objects. * Returns null if object has no listeners of that type. * @private */ goog.events.getListeners_ = function(obj, type, capture) { var map = goog.events.listenerTree_; if (type in map) { map = map[type]; if (capture in map) { map = map[capture]; var objUid = goog.getUid(obj); if (map[objUid]) { return map[objUid]; } } } return null; }; /** * Gets the goog.events.Listener for the event or null if no such listener is * in use. * * @param {EventTarget|goog.events.EventTarget} src The node from which to get * listeners. * @param {?string} type The name of the event without the 'on' prefix. * @param {Function|Object} listener The listener function to get. * @param {boolean=} opt_capt In DOM-compliant browsers, this determines * whether the listener is fired during the * capture or bubble phase of the event. * @param {Object=} opt_handler Element in whose scope to call the listener. * @return {goog.events.ListenableKey} the found listener or null if not found. */ goog.events.getListener = function(src, type, listener, opt_capt, opt_handler) { var capture = !!opt_capt; if (goog.events.Listenable.USE_LISTENABLE_INTERFACE && goog.events.Listenable.isImplementedBy(src)) { return src.getListener( /** @type {string} */ (type), goog.events.wrapListener_(listener), capture, opt_handler); } var listenerArray = goog.events.getListeners_(src, type, capture); if (listenerArray) { for (var i = 0; i < listenerArray.length; i++) { // If goog.events.unlistenByKey is called during an event dispatch // then the listener array won't get cleaned up and there might be // 'removed' listeners in the list. Ignore those. if (!listenerArray[i].removed && listenerArray[i].listener == listener && listenerArray[i].capture == capture && listenerArray[i].handler == opt_handler) { // We already have this listener. Return its key. return listenerArray[i]; } } } return null; }; /** * Returns whether an event target has 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 {EventTarget|goog.events.EventTarget} obj Target to get listeners for. * @param {string=} opt_type Event type. * @param {boolean=} opt_capture Whether to check for capture or bubble-phase * listeners. * @return {boolean} Whether an event target has one or more listeners matching * the requested type and/or capture phase. */ goog.events.hasListener = function(obj, opt_type, opt_capture) { if (goog.events.Listenable.USE_LISTENABLE_INTERFACE && goog.events.Listenable.isImplementedBy(obj)) { return obj.hasListener(opt_type, opt_capture); } var objUid = goog.getUid(obj); var listeners = goog.events.sources_[objUid]; if (listeners) { var hasType = goog.isDef(opt_type); var hasCapture = goog.isDef(opt_capture); if (hasType && hasCapture) { // Lookup in the listener tree whether the specified listener exists. var map = goog.events.listenerTree_[opt_type]; return !!map && !!map[opt_capture] && objUid in map[opt_capture]; } else if (!(hasType || hasCapture)) { // Simple check for whether the event target has any listeners at all. return true; } else { // Iterate through the listeners for the event target to find a match. return goog.array.some(listeners, function(listener) { return (hasType && listener.type == opt_type) || (hasCapture && listener.capture == opt_capture); }); } } return false; }; /** * Provides a nice string showing the normalized event objects public members * @param {Object} e Event Object. * @return {string} String of the public members of the normalized event object. */ goog.events.expose = function(e) { var str = []; for (var key in e) { if (e[key] && e[key].id) { str.push(key + ' = ' + e[key] + ' (' + e[key].id + ')'); } else { str.push(key + ' = ' + e[key]); } } return str.join('\n'); }; /** * Returns a string wth on prepended to the specified type. This is used for IE * which expects "on" to be prepended. This function caches the string in order * to avoid extra allocations in steady state. * @param {string} type Event type strng. * @return {string} The type string with 'on' prepended. * @private */ goog.events.getOnString_ = function(type) { if (type in goog.events.onStringMap_) { return goog.events.onStringMap_[type]; } return goog.events.onStringMap_[type] = goog.events.onString_ + type; }; /** * Fires an object's listeners of a particular type and phase * * @param {Object} obj Object whose listeners to call. * @param {string} type Event type. * @param {boolean} capture Which event phase. * @param {Object} eventObject Event object to be passed to listener. * @return {boolean} True if all listeners returned true else false. */ goog.events.fireListeners = function(obj, type, capture, eventObject) { if (goog.events.Listenable.USE_LISTENABLE_INTERFACE && goog.events.Listenable.isImplementedBy(obj)) { return obj.fireListeners(type, capture, eventObject); } var map = goog.events.listenerTree_; if (type in map) { map = map[type]; if (capture in map) { return goog.events.fireListeners_(map[capture], obj, type, capture, eventObject); } } return true; }; /** * Fires an object's listeners of a particular type and phase. * * @param {Object} map Object with listeners in it. * @param {Object} obj Object whose listeners to call. * @param {string} type Event type. * @param {boolean} capture Which event phase. * @param {Object} eventObject Event object to be passed to listener. * @return {boolean} True if all listeners returned true else false. * @private */ goog.events.fireListeners_ = function(map, obj, type, capture, eventObject) { var retval = 1; var objUid = goog.getUid(obj); if (map[objUid]) { var remaining = --map.remaining_; var listenerArray = map[objUid]; // If locked_ is not set (and if already 0) initialize it to 1. if (!listenerArray.locked_) { listenerArray.locked_ = 1; } else { listenerArray.locked_++; } try { // Events added in the dispatch phase should not be dispatched in // the current dispatch phase. They will be included in the next // dispatch phase though. var length = listenerArray.length; for (var i = 0; i < length; i++) { var listener = listenerArray[i]; // We might not have a listener if the listener was removed. if (listener && !listener.removed) { retval &= goog.events.fireListener(listener, eventObject) !== false; } } } finally { // Allow the count of targets remaining to increase (if perhaps we have // added listeners) but do not allow it to decrease if we have reentered // this method through a listener dispatching the same event type, // resetting and exhausted the remaining count. map.remaining_ = Math.max(remaining, map.remaining_); listenerArray.locked_--; goog.events.cleanUp_(type, capture, objUid, listenerArray); } } return Boolean(retval); }; /** * Fires a listener with a set of arguments * * @param {goog.events.Listener} listener The listener object to call. * @param {Object} eventObject The event object to pass to the listener. * @return {boolean} Result of listener. */ goog.events.fireListener = function(listener, eventObject) { if (listener.callOnce) { goog.events.unlistenByKey(listener.key); } return listener.handleEvent(eventObject); }; /** * Gets the total number of listeners currently in the system. * @return {number} Number of listeners. */ goog.events.getTotalListenerCount = function() { return goog.object.getCount(goog.events.listeners_); }; /** * 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.Listenable|goog.events.EventTarget} src The * event target. * @param {goog.events.EventLike} e Event object. * @return {boolean} If anyone called preventDefault on the event object (or * if any of the handlers returns false) this will also return false. * If there are no handlers, or if all handlers return true, this returns * true. */ goog.events.dispatchEvent = function(src, e) { if (goog.events.Listenable.USE_LISTENABLE_INTERFACE) { if (goog.events.STRICT_EVENT_TARGET) { goog.asserts.assert( goog.events.Listenable.isImplementedBy(src), 'Can not use goog.events.dispatchEvent with ' + 'non-goog.events.Listenable instance.'); } return src.dispatchEvent(e); } if (goog.events.STRICT_EVENT_TARGET) { goog.asserts.assert( goog.events.STRICT_EVENT_TARGET && src[goog.events.CUSTOM_EVENT_ATTR], 'Can not use goog.events.dispatchEvent with ' + 'non-goog.events.EventTarget instance.'); src.assertInitialized(); } var type = e.type || e; var map = goog.events.listenerTree_; if (!(type in map)) { return true; } // 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, src); } else if (!(e instanceof goog.events.Event)) { var oldEvent = e; e = new goog.events.Event(/** @type {string} */ (type), src); goog.object.extend(e, oldEvent); } else { e.target = e.target || src; } var rv = 1, ancestors; map = map[type]; var hasCapture = true in map; var targetsMap; if (hasCapture) { // Build ancestors now ancestors = []; for (var parent = src; parent; parent = parent.getParentEventTarget()) { ancestors.push(parent); } targetsMap = map[true]; targetsMap.remaining_ = targetsMap.count_; // Call capture listeners for (var i = ancestors.length - 1; !e.propagationStopped_ && i >= 0 && targetsMap.remaining_; i--) { e.currentTarget = ancestors[i]; rv &= goog.events.fireListeners_(targetsMap, ancestors[i], e.type, true, e) && e.returnValue_ != false; } } var hasBubble = false in map; if (hasBubble) { targetsMap = map[false]; targetsMap.remaining_ = targetsMap.count_; if (hasCapture) { // We have the ancestors. // Call bubble listeners for (var i = 0; !e.propagationStopped_ && i < ancestors.length && targetsMap.remaining_; i++) { e.currentTarget = ancestors[i]; rv &= goog.events.fireListeners_(targetsMap, ancestors[i], e.type, false, e) && e.returnValue_ != false; } } else { // In case we don't have capture we don't have to build up the // ancestors array. for (var current = src; !e.propagationStopped_ && current && targetsMap.remaining_; current = current.getParentEventTarget()) { e.currentTarget = current; rv &= goog.events.fireListeners_(targetsMap, current, e.type, false, e) && e.returnValue_ != false; } } } return Boolean(rv); }; /** * Installs exception protection for the browser event entry point using the * given error handler. * * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to * protect the entry point. */ goog.events.protectBrowserEventEntryPoint = function(errorHandler) { goog.events.handleBrowserEvent_ = errorHandler.protectEntryPoint( goog.events.handleBrowserEvent_); }; /** * Handles an event and dispatches it to the correct listeners. This * function is a proxy for the real listener the user specified. * * @param {goog.events.Listener} listener The listener object. * @param {Event=} opt_evt Optional event object that gets passed in via the * native event handlers. * @return {boolean} Result of the event handler. * @this {goog.events.EventTarget|Object} The object or Element that * fired the event. * @private */ goog.events.handleBrowserEvent_ = function(listener, opt_evt) { if (listener.removed) { return true; } var type = listener.type; var map = goog.events.listenerTree_; if (!(type in map)) { return true; } map = map[type]; var retval, targetsMap; // Synthesize event propagation if the browser does not support W3C // event model. if (!goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT) { var ieEvent = opt_evt || /** @type {Event} */ (goog.getObjectByName('window.event')); // Check if we have any capturing event listeners for this type. var hasCapture = true in map; var hasBubble = false in map; if (hasCapture) { if (goog.events.isMarkedIeEvent_(ieEvent)) { return true; } goog.events.markIeEvent_(ieEvent); } var evt = new goog.events.BrowserEvent(); // TODO(user): update @this for this function evt.init(ieEvent, /** @type {EventTarget} */ (this)); retval = true; try { if (hasCapture) { var ancestors = []; for (var parent = evt.currentTarget; parent; parent = parent.parentNode) { ancestors.push(parent); } targetsMap = map[true]; targetsMap.remaining_ = targetsMap.count_; // Call capture listeners for (var i = ancestors.length - 1; !evt.propagationStopped_ && i >= 0 && targetsMap.remaining_; i--) { evt.currentTarget = ancestors[i]; retval &= goog.events.fireListeners_(targetsMap, ancestors[i], type, true, evt); } if (hasBubble) { targetsMap = map[false]; targetsMap.remaining_ = targetsMap.count_; // Call bubble listeners for (var i = 0; !evt.propagationStopped_ && i < ancestors.length && targetsMap.remaining_; i++) { evt.currentTarget = ancestors[i]; retval &= goog.events.fireListeners_(targetsMap, ancestors[i], type, false, evt); } } } else { // Bubbling, let IE handle the propagation. retval = goog.events.fireListener(listener, evt); } } finally { if (ancestors) { ancestors.length = 0; } } return retval; } // IE // Caught a non-IE DOM event. 1 additional argument which is the event object var be = new goog.events.BrowserEvent( opt_evt, /** @type {EventTarget} */ (this)); retval = goog.events.fireListener(listener, be); return retval; }; /** * This is used to mark the IE event object so we do not do the Closure pass * twice for a bubbling event. * @param {Event} e The IE browser event. * @private */ goog.events.markIeEvent_ = function(e) { // Only the keyCode and the returnValue can be changed. We use keyCode for // non keyboard events. // event.returnValue is a bit more tricky. It is undefined by default. A // boolean false prevents the default action. In a window.onbeforeunload and // the returnValue is non undefined it will be alerted. However, we will only // modify the returnValue for keyboard events. We can get a problem if non // closure events sets the keyCode or the returnValue var useReturnValue = false; if (e.keyCode == 0) { // We cannot change the keyCode in case that srcElement is input[type=file]. // We could test that that is the case but that would allocate 3 objects. // If we use try/catch we will only allocate extra objects in the case of a // failure. /** @preserveTry */ try { e.keyCode = -1; return; } catch (ex) { useReturnValue = true; } } if (useReturnValue || /** @type {boolean|undefined} */ (e.returnValue) == undefined) { e.returnValue = true; } }; /** * This is used to check if an IE event has already been handled by the Closure * system so we do not do the Closure pass twice for a bubbling event. * @param {Event} e The IE browser event. * @return {boolean} True if the event object has been marked. * @private */ goog.events.isMarkedIeEvent_ = function(e) { return e.keyCode < 0 || e.returnValue != undefined; }; /** * Counter to create unique event ids. * @type {number} * @private */ goog.events.uniqueIdCounter_ = 0; /** * Creates a unique event id. * * @param {string} identifier The identifier. * @return {string} A unique identifier. */ goog.events.getUniqueId = function(identifier) { return identifier + '_' + goog.events.uniqueIdCounter_++; }; /** * Expando property for listener function wrapper for Object with * handleEvent. * @type {string} * @private */ goog.events.LISTENER_WRAPPER_PROP_ = '__closure_events_fn_' + ((Math.random() * 1e9) >>> 0); /** * @param {Object|Function} listener The listener function or an * object that contains handleEvent method. * @return {!Function} Either the original function or a function that * calls obj.handleEvent. If the same listener is passed to this * function more than once, the same function is guaranteed to be * returned. * @private */ goog.events.wrapListener_ = function(listener) { if (goog.isFunction(listener)) { return listener; } return listener[goog.events.LISTENER_WRAPPER_PROP_] || (listener[goog.events.LISTENER_WRAPPER_PROP_] = function(e) { return listener.handleEvent(e); }); }; // Register the browser event handler as an entry point, so that // it can be monitored for exception handling, etc. goog.debug.entryPointRegistry.register( /** * @param {function(!Function): !Function} transformer The transforming * function. */ function(transformer) { goog.events.handleBrowserEvent_ = transformer( goog.events.handleBrowserEvent_); });
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides a files drag and drop event detector. It works on * HTML5 browsers. * * @see ../demos/filedrophandler.html */ goog.provide('goog.events.FileDropHandler'); goog.provide('goog.events.FileDropHandler.EventType'); goog.require('goog.array'); goog.require('goog.debug.Logger'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.events.BrowserEvent'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventTarget'); goog.require('goog.events.EventType'); /** * A files drag and drop event detector. Gets an {@code element} as parameter * and fires {@code goog.events.FileDropHandler.EventType.DROP} event when files * are dropped in the {@code element}. * * @param {Element|Document} element The element or document to listen on. * @param {boolean=} opt_preventDropOutside Whether to prevent a drop on the * area outside the {@code element}. Default false. * @constructor * @extends {goog.events.EventTarget} */ goog.events.FileDropHandler = function(element, opt_preventDropOutside) { goog.events.EventTarget.call(this); /** * Handler for drag/drop events. * @type {!goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); var doc = element; if (opt_preventDropOutside) { doc = goog.dom.getOwnerDocument(element); } // Add dragenter listener to the owner document of the element. this.eventHandler_.listen(doc, goog.events.EventType.DRAGENTER, this.onDocDragEnter_); // Add dragover listener to the owner document of the element only if the // document is not the element itself. if (doc != element) { this.eventHandler_.listen(doc, goog.events.EventType.DRAGOVER, this.onDocDragOver_); } // Add dragover and drop listeners to the element. this.eventHandler_.listen(element, goog.events.EventType.DRAGOVER, this.onElemDragOver_); this.eventHandler_.listen(element, goog.events.EventType.DROP, this.onElemDrop_); }; goog.inherits(goog.events.FileDropHandler, goog.events.EventTarget); /** * Whether the drag event contains files. It is initialized only in the * dragenter event. It is used in all the drag events to prevent default actions * only if the drag contains files. Preventing default actions is necessary to * go from dragenter to dragover and from dragover to drop. However we do not * always want to prevent default actions, e.g. when the user drags text or * links on a text area we should not prevent the browser default action that * inserts the text in the text area. It is also necessary to stop propagation * when handling drag events on the element to prevent them from propagating * to the document. * @private * @type {boolean} */ goog.events.FileDropHandler.prototype.dndContainsFiles_ = false; /** * A logger, used to help us debug the algorithm. * @type {goog.debug.Logger} * @private */ goog.events.FileDropHandler.prototype.logger_ = goog.debug.Logger.getLogger('goog.events.FileDropHandler'); /** * The types of events fired by this class. * @enum {string} */ goog.events.FileDropHandler.EventType = { DROP: goog.events.EventType.DROP }; /** @override */ goog.events.FileDropHandler.prototype.disposeInternal = function() { goog.events.FileDropHandler.superClass_.disposeInternal.call(this); this.eventHandler_.dispose(); }; /** * Dispatches the DROP event. * @param {goog.events.BrowserEvent} e The underlying browser event. * @private */ goog.events.FileDropHandler.prototype.dispatch_ = function(e) { this.logger_.fine('Firing DROP event...'); var event = new goog.events.BrowserEvent(e.getBrowserEvent()); event.type = goog.events.FileDropHandler.EventType.DROP; this.dispatchEvent(event); }; /** * Handles dragenter on the document. * @param {goog.events.BrowserEvent} e The dragenter event. * @private */ goog.events.FileDropHandler.prototype.onDocDragEnter_ = function(e) { this.logger_.finer('"' + e.target.id + '" (' + e.target + ') dispatched: ' + e.type); var dt = e.getBrowserEvent().dataTransfer; // Check whether the drag event contains files. this.dndContainsFiles_ = !!(dt && ((dt.types && (goog.array.contains(dt.types, 'Files') || goog.array.contains(dt.types, 'public.file-url'))) || (dt.files && dt.files.length > 0))); // If it does if (this.dndContainsFiles_) { // Prevent default actions. e.preventDefault(); } this.logger_.finer('dndContainsFiles_: ' + this.dndContainsFiles_); }; /** * Handles dragging something over the document. * @param {goog.events.BrowserEvent} e The dragover event. * @private */ goog.events.FileDropHandler.prototype.onDocDragOver_ = function(e) { this.logger_.finest('"' + e.target.id + '" (' + e.target + ') dispatched: ' + e.type); if (this.dndContainsFiles_) { // Prevent default actions. e.preventDefault(); // Disable the drop on the document outside the drop zone. var dt = e.getBrowserEvent().dataTransfer; dt.dropEffect = 'none'; } }; /** * Handles dragging something over the element (drop zone). * @param {goog.events.BrowserEvent} e The dragover event. * @private */ goog.events.FileDropHandler.prototype.onElemDragOver_ = function(e) { this.logger_.finest('"' + e.target.id + '" (' + e.target + ') dispatched: ' + e.type); if (this.dndContainsFiles_) { // Prevent default actions and stop the event from propagating further to // the document. Both lines are needed! (See comment above). e.preventDefault(); e.stopPropagation(); // Allow the drop on the drop zone. var dt = e.getBrowserEvent().dataTransfer; dt.effectAllowed = 'all'; dt.dropEffect = 'copy'; } }; /** * Handles dropping something onto the element (drop zone). * @param {goog.events.BrowserEvent} e The drop event. * @private */ goog.events.FileDropHandler.prototype.onElemDrop_ = function(e) { this.logger_.finer('"' + e.target.id + '" (' + e.target + ') dispatched: ' + e.type); // If the drag and drop event contains files. if (this.dndContainsFiles_) { // Prevent default actions and stop the event from propagating further to // the document. Both lines are needed! (See comment above). e.preventDefault(); e.stopPropagation(); // Dispatch DROP event. this.dispatch_(e); } };
JavaScript
// Copyright 2005 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Listener object. * @see ../demos/events.html */ goog.provide('goog.events.Listener'); goog.require('goog.events.ListenableKey'); /** * Simple class that stores information about a listener * @implements {goog.events.ListenableKey} * @constructor */ goog.events.Listener = function() { if (goog.events.Listener.ENABLE_MONITORING) { this.creationStack = new Error().stack; } }; /** * @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.events.Listener.ENABLE_MONITORING = false; /** * Whether the listener is a function or an object that implements handleEvent. * @type {boolean} * @private */ goog.events.Listener.prototype.isFunctionListener_; /** * Call back function or an object with a handleEvent function. * @type {Function|Object|null} */ goog.events.Listener.prototype.listener; /** * Proxy for callback that passes through {@link goog.events#HandleEvent_} * @type {Function} */ goog.events.Listener.prototype.proxy; /** * Object or node that callback is listening to * @type {Object|goog.events.Listenable|goog.events.EventTarget} */ goog.events.Listener.prototype.src; /** * Type of event * @type {string} */ goog.events.Listener.prototype.type; /** * Whether the listener is being called in the capture or bubble phase * @type {boolean} */ goog.events.Listener.prototype.capture; /** * Optional object whose context to execute the listener in * @type {Object|undefined} */ goog.events.Listener.prototype.handler; /** * The key of the listener. * @type {number} * @override */ goog.events.Listener.prototype.key = 0; /** * Whether the listener has been removed. * @type {boolean} */ goog.events.Listener.prototype.removed = false; /** * Whether to remove the listener after it has been called. * @type {boolean} */ goog.events.Listener.prototype.callOnce = 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; /** * Initializes the listener. * @param {Function|Object} listener Callback function, or an object with a * handleEvent function. * @param {Function} proxy Wrapper for the listener that patches the event. * @param {Object} 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. */ goog.events.Listener.prototype.init = function(listener, proxy, src, type, capture, opt_handler) { // we do the test of the listener here so that we do not need to // continiously do this inside handleEvent if (goog.isFunction(listener)) { this.isFunctionListener_ = true; } else if (listener && listener.handleEvent && goog.isFunction(listener.handleEvent)) { this.isFunctionListener_ = false; } else { throw Error('Invalid listener argument'); } this.listener = listener; this.proxy = proxy; this.src = src; this.type = type; this.capture = !!capture; this.handler = opt_handler; this.callOnce = false; this.key = goog.events.ListenableKey.reserveKey(); this.removed = false; }; /** * Calls the internal listener * @param {Object} eventObject Event object to be passed to listener. * @return {boolean} The result of the internal listener call. */ goog.events.Listener.prototype.handleEvent = function(eventObject) { if (this.isFunctionListener_) { return this.listener.call(this.handler || this.src, eventObject); } return this.listener.handleEvent.call(this.listener, eventObject); };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Constant declarations for common key codes. * * @author eae@google.com (Emil A Eklund) * @see ../demos/keyhandler.html */ goog.provide('goog.events.KeyCodes'); goog.require('goog.userAgent'); /** * Key codes for common characters. * * This list is not localized and therefore some of the key codes are not * correct for non US keyboard layouts. See comments below. * * @enum {number} */ goog.events.KeyCodes = { WIN_KEY_FF_LINUX: 0, MAC_ENTER: 3, BACKSPACE: 8, TAB: 9, NUM_CENTER: 12, // NUMLOCK on FF/Safari Mac ENTER: 13, SHIFT: 16, CTRL: 17, ALT: 18, PAUSE: 19, CAPS_LOCK: 20, ESC: 27, SPACE: 32, PAGE_UP: 33, // also NUM_NORTH_EAST PAGE_DOWN: 34, // also NUM_SOUTH_EAST END: 35, // also NUM_SOUTH_WEST HOME: 36, // also NUM_NORTH_WEST LEFT: 37, // also NUM_WEST UP: 38, // also NUM_NORTH RIGHT: 39, // also NUM_EAST DOWN: 40, // also NUM_SOUTH PRINT_SCREEN: 44, INSERT: 45, // also NUM_INSERT DELETE: 46, // also NUM_DELETE ZERO: 48, ONE: 49, TWO: 50, THREE: 51, FOUR: 52, FIVE: 53, SIX: 54, SEVEN: 55, EIGHT: 56, NINE: 57, FF_SEMICOLON: 59, // Firefox (Gecko) fires this for semicolon instead of 186 FF_EQUALS: 61, // Firefox (Gecko) fires this for equals instead of 187 QUESTION_MARK: 63, // needs localization A: 65, B: 66, C: 67, D: 68, E: 69, F: 70, G: 71, H: 72, I: 73, J: 74, K: 75, L: 76, M: 77, N: 78, O: 79, P: 80, Q: 81, R: 82, S: 83, T: 84, U: 85, V: 86, W: 87, X: 88, Y: 89, Z: 90, META: 91, // WIN_KEY_LEFT WIN_KEY_RIGHT: 92, CONTEXT_MENU: 93, NUM_ZERO: 96, NUM_ONE: 97, NUM_TWO: 98, NUM_THREE: 99, NUM_FOUR: 100, NUM_FIVE: 101, NUM_SIX: 102, NUM_SEVEN: 103, NUM_EIGHT: 104, NUM_NINE: 105, NUM_MULTIPLY: 106, NUM_PLUS: 107, NUM_MINUS: 109, NUM_PERIOD: 110, NUM_DIVISION: 111, F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123, NUMLOCK: 144, SCROLL_LOCK: 145, // OS-specific media keys like volume controls and browser controls. FIRST_MEDIA_KEY: 166, LAST_MEDIA_KEY: 183, SEMICOLON: 186, // needs localization DASH: 189, // needs localization EQUALS: 187, // needs localization COMMA: 188, // needs localization PERIOD: 190, // needs localization SLASH: 191, // needs localization APOSTROPHE: 192, // needs localization TILDE: 192, // needs localization SINGLE_QUOTE: 222, // needs localization OPEN_SQUARE_BRACKET: 219, // needs localization BACKSLASH: 220, // needs localization CLOSE_SQUARE_BRACKET: 221, // needs localization WIN_KEY: 224, MAC_FF_META: 224, // Firefox (Gecko) fires this for the meta key instead of 91 WIN_IME: 229, // We've seen users whose machines fire this keycode at regular one // second intervals. The common thread among these users is that // they're all using Dell Inspiron laptops, so we suspect that this // indicates a hardware/bios problem. // http://en.community.dell.com/support-forums/laptop/f/3518/p/19285957/19523128.aspx PHANTOM: 255 }; /** * Returns true if the event contains a text modifying key. * @param {goog.events.BrowserEvent} e A key event. * @return {boolean} Whether it's a text modifying key. */ goog.events.KeyCodes.isTextModifyingKeyEvent = function(e) { if (e.altKey && !e.ctrlKey || e.metaKey || // Function keys don't generate text e.keyCode >= goog.events.KeyCodes.F1 && e.keyCode <= goog.events.KeyCodes.F12) { return false; } // The following keys are quite harmless, even in combination with // CTRL, ALT or SHIFT. switch (e.keyCode) { case goog.events.KeyCodes.ALT: case goog.events.KeyCodes.CAPS_LOCK: case goog.events.KeyCodes.CONTEXT_MENU: case goog.events.KeyCodes.CTRL: case goog.events.KeyCodes.DOWN: case goog.events.KeyCodes.END: case goog.events.KeyCodes.ESC: case goog.events.KeyCodes.HOME: case goog.events.KeyCodes.INSERT: case goog.events.KeyCodes.LEFT: case goog.events.KeyCodes.MAC_FF_META: case goog.events.KeyCodes.META: case goog.events.KeyCodes.NUMLOCK: case goog.events.KeyCodes.NUM_CENTER: case goog.events.KeyCodes.PAGE_DOWN: case goog.events.KeyCodes.PAGE_UP: case goog.events.KeyCodes.PAUSE: case goog.events.KeyCodes.PHANTOM: case goog.events.KeyCodes.PRINT_SCREEN: case goog.events.KeyCodes.RIGHT: case goog.events.KeyCodes.SCROLL_LOCK: case goog.events.KeyCodes.SHIFT: case goog.events.KeyCodes.UP: case goog.events.KeyCodes.WIN_KEY: case goog.events.KeyCodes.WIN_KEY_RIGHT: return false; case goog.events.KeyCodes.WIN_KEY_FF_LINUX: return !goog.userAgent.GECKO; default: return e.keyCode < goog.events.KeyCodes.FIRST_MEDIA_KEY || e.keyCode > goog.events.KeyCodes.LAST_MEDIA_KEY; } }; /** * Returns true if the key fires a keypress event in the current browser. * * Accoridng to MSDN [1] IE only fires keypress events for the following keys: * - Letters: A - Z (uppercase and lowercase) * - Numerals: 0 - 9 * - Symbols: ! @ # $ % ^ & * ( ) _ - + = < [ ] { } , . / ? \ | ' ` " ~ * - System: ESC, SPACEBAR, ENTER * * That's not entirely correct though, for instance there's no distinction * between upper and lower case letters. * * [1] http://msdn2.microsoft.com/en-us/library/ms536939(VS.85).aspx) * * Safari is similar to IE, but does not fire keypress for ESC. * * Additionally, IE6 does not fire keydown or keypress events for letters when * the control or alt keys are held down and the shift key is not. IE7 does * fire keydown in these cases, though, but not keypress. * * @param {number} keyCode A key code. * @param {number=} opt_heldKeyCode Key code of a currently-held key. * @param {boolean=} opt_shiftKey Whether the shift key is held down. * @param {boolean=} opt_ctrlKey Whether the control key is held down. * @param {boolean=} opt_altKey Whether the alt key is held down. * @return {boolean} Whether it's a key that fires a keypress event. */ goog.events.KeyCodes.firesKeyPressEvent = function(keyCode, opt_heldKeyCode, opt_shiftKey, opt_ctrlKey, opt_altKey) { if (!goog.userAgent.IE && !(goog.userAgent.WEBKIT && goog.userAgent.isVersion('525'))) { return true; } if (goog.userAgent.MAC && opt_altKey) { return goog.events.KeyCodes.isCharacterKey(keyCode); } // Alt but not AltGr which is represented as Alt+Ctrl. if (opt_altKey && !opt_ctrlKey) { return false; } // Saves Ctrl or Alt + key for IE and WebKit 525+, which won't fire keypress. // Non-IE browsers and WebKit prior to 525 won't get this far so no need to // check the user agent. if (!opt_shiftKey && (opt_heldKeyCode == goog.events.KeyCodes.CTRL || opt_heldKeyCode == goog.events.KeyCodes.ALT || goog.userAgent.MAC && opt_heldKeyCode == goog.events.KeyCodes.META)) { return false; } // Some keys with Ctrl/Shift do not issue keypress in WEBKIT. if (goog.userAgent.WEBKIT && opt_ctrlKey && opt_shiftKey) { switch (keyCode) { case goog.events.KeyCodes.BACKSLASH: case goog.events.KeyCodes.OPEN_SQUARE_BRACKET: case goog.events.KeyCodes.CLOSE_SQUARE_BRACKET: case goog.events.KeyCodes.TILDE: case goog.events.KeyCodes.SEMICOLON: case goog.events.KeyCodes.DASH: case goog.events.KeyCodes.EQUALS: case goog.events.KeyCodes.COMMA: case goog.events.KeyCodes.PERIOD: case goog.events.KeyCodes.SLASH: case goog.events.KeyCodes.APOSTROPHE: case goog.events.KeyCodes.SINGLE_QUOTE: return false; } } // When Ctrl+<somekey> is held in IE, it only fires a keypress once, but it // continues to fire keydown events as the event repeats. if (goog.userAgent.IE && opt_ctrlKey && opt_heldKeyCode == keyCode) { return false; } switch (keyCode) { case goog.events.KeyCodes.ENTER: // IE9 does not fire KEYPRESS on ENTER. return !(goog.userAgent.IE && goog.userAgent.isDocumentMode(9)); case goog.events.KeyCodes.ESC: return !goog.userAgent.WEBKIT; } return goog.events.KeyCodes.isCharacterKey(keyCode); }; /** * Returns true if the key produces a character. * This does not cover characters on non-US keyboards (Russian, Hebrew, etc.). * * @param {number} keyCode A key code. * @return {boolean} Whether it's a character key. */ goog.events.KeyCodes.isCharacterKey = function(keyCode) { if (keyCode >= goog.events.KeyCodes.ZERO && keyCode <= goog.events.KeyCodes.NINE) { return true; } if (keyCode >= goog.events.KeyCodes.NUM_ZERO && keyCode <= goog.events.KeyCodes.NUM_MULTIPLY) { return true; } if (keyCode >= goog.events.KeyCodes.A && keyCode <= goog.events.KeyCodes.Z) { return true; } // Safari sends zero key code for non-latin characters. if (goog.userAgent.WEBKIT && keyCode == 0) { return true; } switch (keyCode) { case goog.events.KeyCodes.SPACE: case goog.events.KeyCodes.QUESTION_MARK: case goog.events.KeyCodes.NUM_PLUS: case goog.events.KeyCodes.NUM_MINUS: case goog.events.KeyCodes.NUM_PERIOD: case goog.events.KeyCodes.NUM_DIVISION: case goog.events.KeyCodes.SEMICOLON: case goog.events.KeyCodes.FF_SEMICOLON: case goog.events.KeyCodes.DASH: case goog.events.KeyCodes.EQUALS: case goog.events.KeyCodes.FF_EQUALS: case goog.events.KeyCodes.COMMA: case goog.events.KeyCodes.PERIOD: case goog.events.KeyCodes.SLASH: case goog.events.KeyCodes.APOSTROPHE: case goog.events.KeyCodes.SINGLE_QUOTE: case goog.events.KeyCodes.OPEN_SQUARE_BRACKET: case goog.events.KeyCodes.BACKSLASH: case goog.events.KeyCodes.CLOSE_SQUARE_BRACKET: return true; default: return false; } }; /** * Normalizes key codes from their Gecko-specific value to the general one. * @param {number} keyCode The native key code. * @return {number} The normalized key code. */ goog.events.KeyCodes.normalizeGeckoKeyCode = function(keyCode) { switch (keyCode) { case goog.events.KeyCodes.FF_EQUALS: return goog.events.KeyCodes.EQUALS; case goog.events.KeyCodes.FF_SEMICOLON: return goog.events.KeyCodes.SEMICOLON; case goog.events.KeyCodes.MAC_FF_META: return goog.events.KeyCodes.META; case goog.events.KeyCodes.WIN_KEY_FF_LINUX: return goog.events.KeyCodes.WIN_KEY; default: return keyCode; } };
JavaScript
// Copyright 2005 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Class to create objects which want to handle multiple events * and have their listeners easily cleaned up via a dispose method. * * Example: * <pre> * function Something() { * goog.base(this); * * ... set up object ... * * // Add event listeners * this.listen(this.starEl, goog.events.EventType.CLICK, this.handleStar); * this.listen(this.headerEl, goog.events.EventType.CLICK, this.expand); * this.listen(this.collapseEl, goog.events.EventType.CLICK, this.collapse); * this.listen(this.infoEl, goog.events.EventType.MOUSEOVER, this.showHover); * this.listen(this.infoEl, goog.events.EventType.MOUSEOUT, this.hideHover); * } * goog.inherits(Something, goog.events.EventHandler); * * Something.prototype.disposeInternal = function() { * goog.base(this, 'disposeInternal'); * goog.dom.removeNode(this.container); * }; * * * // Then elsewhere: * * var activeSomething = null; * function openSomething() { * activeSomething = new Something(); * } * * function closeSomething() { * if (activeSomething) { * activeSomething.dispose(); // Remove event listeners * activeSomething = null; * } * } * </pre> * */ goog.provide('goog.events.EventHandler'); goog.require('goog.Disposable'); goog.require('goog.array'); goog.require('goog.events'); goog.require('goog.events.EventWrapper'); /** * Super class for objects that want to easily manage a number of event * listeners. It allows a short cut to listen and also provides a quick way * to remove all events listeners belonging to this object. * @param {Object=} opt_handler Object in whose scope to call the listeners. * @constructor * @extends {goog.Disposable} */ goog.events.EventHandler = function(opt_handler) { goog.Disposable.call(this); this.handler_ = opt_handler; /** * Keys for events that are being listened to. * @type {Array.<number>} * @private */ this.keys_ = []; }; goog.inherits(goog.events.EventHandler, goog.Disposable); /** * Utility array used to unify the cases of listening for an array of types * and listening for a single event, without using recursion or allocating * an array each time. * @type {Array.<string>} * @private */ goog.events.EventHandler.typeArray_ = []; /** * Listen to an event on a DOM node or EventTarget. If the function is omitted * then the EventHandler's handleEvent method will be used. * @param {goog.events.EventTarget|EventTarget} src Event source. * @param {string|Array.<string>} type Event type to listen for or array of * event types. * @param {Function|Object=} opt_fn Optional callback function to be used as the * listener or an object with handleEvent function. * @param {boolean=} opt_capture Optional whether to use capture phase. * @param {Object=} opt_handler Object in whose scope to call the listener. * @return {goog.events.EventHandler} This object, allowing for chaining of * calls. */ goog.events.EventHandler.prototype.listen = function(src, type, opt_fn, opt_capture, opt_handler) { if (!goog.isArray(type)) { goog.events.EventHandler.typeArray_[0] = /** @type {string} */(type); type = goog.events.EventHandler.typeArray_; } for (var i = 0; i < type.length; i++) { // goog.events.listen generates unique keys so we don't have to check their // presence in the this.keys_ array. var key = /** @type {number} */ ( goog.events.listen(src, type[i], opt_fn || this, opt_capture || false, opt_handler || this.handler_ || this)); this.keys_.push(key); } return this; }; /** * Listen to an event on a DOM node or EventTarget. If the function is omitted * then the EventHandler's handleEvent method will be used. After the event has * fired the event listener is removed from the target. If an array of event * types is provided, each event type will be listened to once. * @param {goog.events.EventTarget|EventTarget} src Event source. * @param {string|Array.<string>} type Event type to listen for or array of * event types. * @param {Function|Object=} opt_fn Optional callback function to be used as the * listener or an object with handleEvent function. * @param {boolean=} opt_capture Optional whether to use capture phase. * @param {Object=} opt_handler Object in whose scope to call the listener. * @return {goog.events.EventHandler} This object, allowing for chaining of * calls. */ goog.events.EventHandler.prototype.listenOnce = function(src, type, opt_fn, opt_capture, opt_handler) { if (goog.isArray(type)) { for (var i = 0; i < type.length; i++) { this.listenOnce(src, type[i], opt_fn, opt_capture, opt_handler); } } else { var key = /** @type {number} */ ( goog.events.listenOnce(src, type, opt_fn || this, opt_capture, opt_handler || this.handler_ || this)); this.keys_.push(key); } return this; }; /** * Adds an event listener with a specific event wrapper on a DOM Node or an * object that has implemented {@link goog.events.EventTarget}. A listener can * only be added once to an object. * * @param {EventTarget|goog.events.EventTarget} src The node to listen to * events on. * @param {goog.events.EventWrapper} wrapper Event wrapper to use. * @param {Function|Object} listener Callback method, or an object with a * handleEvent function. * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to * false). * @param {Object=} opt_handler Element in whose scope to call the listener. * @return {goog.events.EventHandler} This object, allowing for chaining of * calls. */ goog.events.EventHandler.prototype.listenWithWrapper = function(src, wrapper, listener, opt_capt, opt_handler) { wrapper.listen(src, listener, opt_capt, opt_handler || this.handler_ || this, this); return this; }; /** * @return {number} Number of listeners registered by this handler. */ goog.events.EventHandler.prototype.getListenerCount = function() { return this.keys_.length; }; /** * Unlistens on an event. * @param {goog.events.EventTarget|EventTarget} src Event source. * @param {string|Array.<string>} type Event type to listen for. * @param {Function|Object=} opt_fn Optional callback function to be used as the * listener or an object with handleEvent function. * @param {boolean=} opt_capture Optional whether to use capture phase. * @param {Object=} opt_handler Object in whose scope to call the listener. * @return {goog.events.EventHandler} This object, allowing for chaining of * calls. */ goog.events.EventHandler.prototype.unlisten = function(src, type, opt_fn, opt_capture, opt_handler) { if (goog.isArray(type)) { for (var i = 0; i < type.length; i++) { this.unlisten(src, type[i], opt_fn, opt_capture, opt_handler); } } else { var listener = goog.events.getListener(src, type, opt_fn || this, opt_capture, opt_handler || this.handler_ || this); if (listener) { var key = listener.key; goog.events.unlistenByKey(key); goog.array.remove(this.keys_, key); } } return this; }; /** * Removes an event listener which was added with listenWithWrapper(). * * @param {EventTarget|goog.events.EventTarget} src The target to stop * listening to events on. * @param {goog.events.EventWrapper} wrapper Event wrapper to use. * @param {Function|Object} listener The listener function to remove. * @param {boolean=} opt_capt In DOM-compliant browsers, this determines * whether the listener is fired during the capture or bubble phase of the * event. * @param {Object=} opt_handler Element in whose scope to call the listener. * @return {goog.events.EventHandler} This object, allowing for chaining of * calls. */ goog.events.EventHandler.prototype.unlistenWithWrapper = function(src, wrapper, listener, opt_capt, opt_handler) { wrapper.unlisten(src, listener, opt_capt, opt_handler || this.handler_ || this, this); return this; }; /** * Unlistens to all events. */ goog.events.EventHandler.prototype.removeAll = function() { goog.array.forEach(this.keys_, goog.events.unlistenByKey); this.keys_.length = 0; }; /** * Disposes of this EventHandler and removes all listeners that it registered. * @override * @protected */ goog.events.EventHandler.prototype.disposeInternal = function() { goog.events.EventHandler.superClass_.disposeInternal.call(this); this.removeAll(); }; /** * Default event handler * @param {goog.events.Event} e Event object. */ goog.events.EventHandler.prototype.handleEvent = function(e) { throw Error('EventHandler.handleEvent not implemented'); };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This event handler will dispatch events when * {@code navigator.onLine} changes. HTML5 defines two events, online and * offline that is fired on the window. As of today 3 browsers support these * events: Firefox 3 (Gecko 1.9), Opera 9.5, and IE8. If we have any of these * we listen to the 'online' and 'offline' events on the current window * object. Otherwise we poll the navigator.onLine property to detect changes. * * Note that this class only reflects what the browser tells us and this usually * only reflects changes to the File -> Work Offline menu item. * * @author arv@google.com (Erik Arvidsson) * @see ../demos/onlinehandler.html */ // TODO(arv): We should probably implement some kind of polling service and/or // a poll for changes event handler that can be used to fire events when a state // changes. goog.provide('goog.events.OnlineHandler'); goog.provide('goog.events.OnlineHandler.EventType'); goog.require('goog.Timer'); goog.require('goog.events.BrowserFeature'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventTarget'); goog.require('goog.events.EventType'); goog.require('goog.net.NetworkStatusMonitor'); goog.require('goog.userAgent'); /** * Basic object for detecting whether the online state changes. * @constructor * @extends {goog.net.NetworkStatusMonitor} */ goog.events.OnlineHandler = function() { goog.base(this); this.eventHandler_ = new goog.events.EventHandler(this); // Some browsers do not support navigator.onLine and therefore we don't // bother setting up events or timers. if (!goog.events.BrowserFeature.HAS_NAVIGATOR_ONLINE_PROPERTY) { return; } if (goog.events.BrowserFeature.HAS_HTML5_NETWORK_EVENT_SUPPORT) { var target = goog.events.BrowserFeature.HTML5_NETWORK_EVENTS_FIRE_ON_BODY ? document.body : window; this.eventHandler_.listen(target, [goog.events.EventType.ONLINE, goog.events.EventType.OFFLINE], this.handleChange_); } else { this.online_ = this.isOnline(); this.timer_ = new goog.Timer(goog.events.OnlineHandler.POLL_INTERVAL_); this.eventHandler_.listen(this.timer_, goog.Timer.TICK, this.handleTick_); this.timer_.start(); } }; goog.inherits(goog.events.OnlineHandler, goog.net.NetworkStatusMonitor); /** * Enum for the events dispatched by the OnlineHandler. * @enum {string} */ goog.events.OnlineHandler.EventType = goog.net.NetworkStatusMonitor.EventType; /** * The time to wait before checking the {@code navigator.onLine} again. * @type {number} * @private */ goog.events.OnlineHandler.POLL_INTERVAL_ = 250; /** * Stores the last value of the online state so we can detect if this has * changed. * @type {boolean} * @private */ goog.events.OnlineHandler.prototype.online_; /** * The timer object used to poll the online state. * @type {goog.Timer} * @private */ goog.events.OnlineHandler.prototype.timer_; /** * Event handler to simplify event listening. * @type {goog.events.EventHandler} * @private */ goog.events.OnlineHandler.prototype.eventHandler_; /** @override */ goog.events.OnlineHandler.prototype.isOnline = function() { return goog.events.BrowserFeature.HAS_NAVIGATOR_ONLINE_PROPERTY ? navigator.onLine : true; }; /** * Called every time the timer ticks to see if the state has changed and when * the online state changes the method handleChange_ is called. * @param {goog.events.Event} e The event object. * @private */ goog.events.OnlineHandler.prototype.handleTick_ = function(e) { var online = this.isOnline(); if (online != this.online_) { this.online_ = online; this.handleChange_(e); } }; /** * Called when the online state changes. This dispatches the * {@code ONLINE} and {@code OFFLINE} events respectively. * @param {goog.events.Event} e The event object. * @private */ goog.events.OnlineHandler.prototype.handleChange_ = function(e) { var type = this.isOnline() ? goog.net.NetworkStatusMonitor.EventType.ONLINE : goog.net.NetworkStatusMonitor.EventType.OFFLINE; this.dispatchEvent(type); }; /** @override */ goog.events.OnlineHandler.prototype.disposeInternal = function() { goog.events.OnlineHandler.superClass_.disposeInternal.call(this); this.eventHandler_.dispose(); delete this.eventHandler_; if (this.timer_) { this.timer_.dispose(); delete this.timer_; } };
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Event Types. * * @author arv@google.com (Erik Arvidsson) * @author mirkov@google.com (Mirko Visontai) */ goog.provide('goog.events.EventType'); goog.require('goog.userAgent'); /** * Constants for event names. * @enum {string} */ goog.events.EventType = { // Mouse events CLICK: 'click', DBLCLICK: 'dblclick', MOUSEDOWN: 'mousedown', MOUSEUP: 'mouseup', MOUSEOVER: 'mouseover', MOUSEOUT: 'mouseout', MOUSEMOVE: 'mousemove', SELECTSTART: 'selectstart', // IE, Safari, Chrome // 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', 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', // WebKit touch events. TOUCHSTART: 'touchstart', TOUCHMOVE: 'touchmove', TOUCHEND: 'touchend', TOUCHCANCEL: 'touchcancel', // Misc BEFOREUNLOAD: 'beforeunload', CONTEXTMENU: 'contextmenu', ERROR: 'error', HELP: 'help', LOAD: 'load', LOSECAPTURE: 'losecapture', READYSTATECHANGE: 'readystatechange', RESIZE: 'resize', SCROLL: 'scroll', UNLOAD: 'unload', // HTML 5 History events // See http://www.w3.org/TR/html5/history.html#event-definitions 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', // CSS transition events. Based on the browser support described at: // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility TRANSITIONEND: goog.userAgent.WEBKIT ? 'webkitTransitionEnd' : (goog.userAgent.OPERA ? 'oTransitionEnd' : 'transitionend'), // IE specific events. // See http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx MSGESTURECHANGE: 'MSGestureChange', MSGESTUREEND: 'MSGestureEnd', MSGESTUREHOLD: 'MSGestureHold', MSGESTURESTART: 'MSGestureStart', MSGESTURETAP: 'MSGestureTap', MSGOTPOINTERCAPTURE: 'MSGotPointerCapture', MSINERTIASTART: 'MSInertiaStart', MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture', MSPOINTERCANCEL: 'MSPointerCancel', MSPOINTERDOWN: 'MSPointerDown', MSPOINTERMOVE: 'MSPointerMove', MSPOINTEROVER: 'MSPointerOver', MSPOINTEROUT: 'MSPointerOut', MSPOINTERUP: 'MSPointerUp', // Native IMEs/input tools events. TEXTINPUT: 'textinput', COMPOSITIONSTART: 'compositionstart', COMPOSITIONUPDATE: 'compositionupdate', COMPOSITIONEND: 'compositionend' };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This event handler allows you to catch focusin and focusout * events on descendants. Unlike the "focus" and "blur" events which do not * propagate consistently, and therefore must be added to the element that is * focused, this allows you to attach one listener to an ancester and you will * be notified when the focus state changes of ony of its descendants. * @author arv@google.com (Erik Arvidsson) * @see ../demos/focushandler.html */ goog.provide('goog.events.FocusHandler'); goog.provide('goog.events.FocusHandler.EventType'); goog.require('goog.events'); goog.require('goog.events.BrowserEvent'); goog.require('goog.events.EventTarget'); goog.require('goog.userAgent'); /** * This event handler allows you to catch focus events when descendants gain or * loses focus. * @param {Element|Document} element The node to listen on. * @constructor * @extends {goog.events.EventTarget} */ goog.events.FocusHandler = function(element) { goog.events.EventTarget.call(this); /** * This is the element that we will listen to the real focus events on. * @type {Element|Document} * @private */ this.element_ = element; // In IE we use focusin/focusout and in other browsers we use a capturing // listner for focus/blur var typeIn = goog.userAgent.IE ? 'focusin' : 'focus'; var typeOut = goog.userAgent.IE ? 'focusout' : 'blur'; /** * Store the listen key so it easier to unlisten in dispose. * @private * @type {goog.events.Key} */ this.listenKeyIn_ = goog.events.listen(this.element_, typeIn, this, !goog.userAgent.IE); /** * Store the listen key so it easier to unlisten in dispose. * @private * @type {goog.events.Key} */ this.listenKeyOut_ = goog.events.listen(this.element_, typeOut, this, !goog.userAgent.IE); }; goog.inherits(goog.events.FocusHandler, goog.events.EventTarget); /** * Enum type for the events fired by the focus handler * @enum {string} */ goog.events.FocusHandler.EventType = { FOCUSIN: 'focusin', FOCUSOUT: 'focusout' }; /** * This handles the underlying events and dispatches a new event. * @param {goog.events.BrowserEvent} e The underlying browser event. */ goog.events.FocusHandler.prototype.handleEvent = function(e) { var be = e.getBrowserEvent(); var event = new goog.events.BrowserEvent(be); event.type = e.type == 'focusin' || e.type == 'focus' ? goog.events.FocusHandler.EventType.FOCUSIN : goog.events.FocusHandler.EventType.FOCUSOUT; this.dispatchEvent(event); }; /** @override */ goog.events.FocusHandler.prototype.disposeInternal = function() { goog.events.FocusHandler.superClass_.disposeInternal.call(this); goog.events.unlistenByKey(this.listenKeyIn_); goog.events.unlistenByKey(this.listenKeyOut_); delete this.element_; };
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Browser capability checks for the events package. * */ goog.provide('goog.events.BrowserFeature'); goog.require('goog.userAgent'); /** * 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.isDocumentMode(9), /** * Whether the browser supports full W3C event model. */ HAS_W3C_EVENT_SUPPORT: !goog.userAgent.IE || goog.userAgent.isDocumentMode(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.isVersion('9'), /** * Whether the {@code navigator.onLine} property is supported. */ HAS_NAVIGATOR_ONLINE_PROPERTY: !goog.userAgent.WEBKIT || goog.userAgent.isVersion('528'), /** * Whether HTML5 network online/offline events are supported. */ HAS_HTML5_NETWORK_EVENT_SUPPORT: goog.userAgent.GECKO && goog.userAgent.isVersion('1.9b') || goog.userAgent.IE && goog.userAgent.isVersion('8') || goog.userAgent.OPERA && goog.userAgent.isVersion('9.5') || goog.userAgent.WEBKIT && goog.userAgent.isVersion('528'), /** * Whether HTML5 network events fire on document.body, or otherwise the * window. */ HTML5_NETWORK_EVENTS_FIRE_ON_BODY: goog.userAgent.GECKO && !goog.userAgent.isVersion('8') || goog.userAgent.IE && !goog.userAgent.isVersion('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'])) };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview goog.events.EventTarget tester. */ goog.provide('goog.events.eventTargetTester'); goog.setTestOnly('goog.events.eventTargetTester'); goog.provide('goog.events.eventTargetTester.KeyType'); goog.setTestOnly('goog.events.eventTargetTester.KeyType'); goog.provide('goog.events.eventTargetTester.UnlistenReturnType'); goog.setTestOnly('goog.events.eventTargetTester.UnlistenReturnType'); goog.require('goog.events.Event'); goog.require('goog.events.EventTarget'); goog.require('goog.testing.asserts'); goog.require('goog.testing.recordFunction'); /** * Setup step for the test functions. This needs to be called from the * test setUp. * @param {Function} listenFn Function that, given the same signature * as goog.events.listen, will add listener to the given event * target. * @param {Function} unlistenFn Function that, given the same * signature as goog.events.unlisten, will remove listener from * the given event target. * @param {Function} unlistenByKeyFn Function that, given 2 * parameters: src and key, will remove the corresponding * listener. * @param {Function} listenOnceFn Function that, given the same * signature as goog.events.listenOnce, will add a one-time * listener to the given event target. * @param {Function} dispatchEventFn Function that, given the same * signature as goog.events.dispatchEvent, will dispatch the event * on the given event target. * @param {Function} removeAllFn Function that, given the same * signature as goog.events.removeAll, will remove all listeners * according to the contract of goog.events.removeAll. * @param {Function} getListenersFn Function that, given the same * signature as goog.events.getListeners, will retrieve listeners. * @param {Function} getListenerFn Function that, given the same * signature as goog.events.getListener, will retrieve the * listener object. * @param {Function} hasListenerFn Function that, given the same * signature as goog.events.hasListener, will determine whether * listeners exist. * @param {goog.events.eventTargetTester.KeyType} listenKeyType The * key type returned by listen call. * @param {goog.events.eventTargetTester.UnlistenReturnType} * unlistenFnReturnType * Whether we should check return value from * unlisten call. If unlisten does not return a value, this should * be set to false. */ goog.events.eventTargetTester.setUp = function( listenFn, unlistenFn, unlistenByKeyFn, listenOnceFn, dispatchEventFn, removeAllFn, getListenersFn, getListenerFn, hasListenerFn, listenKeyType, unlistenFnReturnType) { listen = listenFn; unlisten = unlistenFn; unlistenByKey = unlistenByKeyFn; listenOnce = listenOnceFn; dispatchEvent = dispatchEventFn; removeAll = removeAllFn; getListeners = getListenersFn; getListener = getListenerFn; hasListener = hasListenerFn; keyType = listenKeyType; unlistenReturnType = unlistenFnReturnType; listeners = []; for (var i = 0; i < goog.events.eventTargetTester.MAX_; i++) { listeners[i] = createListener(); } eventTargets = []; for (i = 0; i < goog.events.eventTargetTester.MAX_; i++) { eventTargets[i] = new goog.events.EventTarget(); } }; /** * Teardown step for the test functions. This needs to be called from * test teardown. */ goog.events.eventTargetTester.tearDown = function() { for (var i = 0; i < goog.events.eventTargetTester.MAX_; i++) { goog.dispose(eventTargets[i]); } }; /** * The type of key returned by key-returning functions (listen). * @enum {number} */ goog.events.eventTargetTester.KeyType = { /** * Returns number for key. */ NUMBER: 0, /** * Returns undefined (no return value). */ UNDEFINED: 1 }; /** * The type of unlisten function's return value. */ goog.events.eventTargetTester.UnlistenReturnType = { /** * Returns boolean indicating whether unlisten is successful. */ BOOLEAN: 0, /** * Returns undefind (no return value). */ UNDEFINED: 1 }; /** * Expando property used on "listener" function to determine if a * listener has already been checked. This is what allows us to * implement assertNoOtherListenerIsCalled. * @type {string} */ goog.events.eventTargetTester.ALREADY_CHECKED_PROP = '__alreadyChecked'; /** * Expando property used on "listener" function to record the number * of times it has been called the last time assertListenerIsCalled is * done. This allows us to verify that it has not been called more * times in assertNoOtherListenerIsCalled. */ goog.events.eventTargetTester.NUM_CALLED_PROP = '__numCalled'; /** * The maximum number of initialized event targets (in eventTargets * array) and listeners (in listeners array). * @type {number} * @private */ goog.events.eventTargetTester.MAX_ = 10; /** * Contains test event types. * @enum {string} */ var EventType = { A: goog.events.getUniqueId('a'), B: goog.events.getUniqueId('b'), C: goog.events.getUniqueId('c') }; var listen, unlisten, unlistenByKey, listenOnce, dispatchEvent; var removeAll, getListeners, getListener, hasListener; var keyType, unlistenReturnType; var eventTargets, listeners; /** * Custom event object for testing. * @constructor * @extends {goog.events.Event} */ var TestEvent = function() { goog.base(this, EventType.A); }; goog.inherits(TestEvent, goog.events.Event); /** * Creates a listener that executes the given function (optional). * @param {!Function=} opt_listenerFn The optional function to execute. * @return {!Function} The listener function. */ function createListener(opt_listenerFn) { return goog.testing.recordFunction(opt_listenerFn); } /** * Asserts that the given listener is called numCount number of times. * @param {!Function} listener The listener to check. * @param {number} numCount The number of times. See also the times() * function below. */ function assertListenerIsCalled(listener, numCount) { assertEquals('Listeners is not called the correct number of times.', numCount, listener.getCallCount()); listener[goog.events.eventTargetTester.ALREADY_CHECKED_PROP] = true; listener[goog.events.eventTargetTester.NUM_CALLED_PROP] = numCount; } /** * Asserts that no other listeners, other than those verified via * assertListenerIsCalled, have been called since the last * resetListeners(). */ function assertNoOtherListenerIsCalled() { goog.array.forEach(listeners, function(l, index) { if (!l[goog.events.eventTargetTester.ALREADY_CHECKED_PROP]) { assertEquals( 'Listeners ' + index + ' is unexpectedly called.', 0, l.getCallCount()); } else { assertEquals( 'Listeners ' + index + ' is unexpectedly called.', l[goog.events.eventTargetTester.NUM_CALLED_PROP], l.getCallCount()); } }); } /** * Resets all listeners call count to 0. */ function resetListeners() { goog.array.forEach(listeners, function(l) { l.reset(); l[goog.events.eventTargetTester.ALREADY_CHECKED_PROP] = false; }); } /** * The number of times a listener should have been executed. This * exists to make assertListenerIsCalled more readable. This is used * like so: assertListenerIsCalled(listener, times(2)); * @param {number} n The number of times a listener should have been * executed. * @return {number} The number n. */ function times(n) { return n; } function testNoListener() { dispatchEvent(eventTargets[0], EventType.A); assertNoOtherListenerIsCalled(); } function testOneListener() { listen(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertNoOtherListenerIsCalled(); resetListeners(); dispatchEvent(eventTargets[0], EventType.B); dispatchEvent(eventTargets[0], EventType.C); assertNoOtherListenerIsCalled(); } function testTwoListenersOfSameType() { var key1 = listen(eventTargets[0], EventType.A, listeners[0]); var key2 = listen(eventTargets[0], EventType.A, listeners[1]); if (keyType == goog.events.eventTargetTester.KeyType.NUMBER) { assertNotEquals(key1, key2); } else { assertUndefined(key1); assertUndefined(key2); } dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertNoOtherListenerIsCalled(); } function testInstallingSameListeners() { var key1 = listen(eventTargets[0], EventType.A, listeners[0]); var key2 = listen(eventTargets[0], EventType.A, listeners[0]); var key3 = listen(eventTargets[0], EventType.B, listeners[0]); if (keyType == goog.events.eventTargetTester.KeyType.NUMBER) { assertEquals(key1, key2); assertNotEquals(key1, key3); } else { assertUndefined(key1); assertUndefined(key2); assertUndefined(key3); } dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); dispatchEvent(eventTargets[0], EventType.B); assertListenerIsCalled(listeners[0], times(2)); assertNoOtherListenerIsCalled(); } function testScope() { listeners[0] = createListener(function(e) { assertEquals('Wrong scope with undefined scope', eventTargets[0], this); }); listeners[1] = createListener(function(e) { assertEquals('Wrong scope with null scope', eventTargets[0], this); }); var scope = {}; listeners[2] = createListener(function(e) { assertEquals('Wrong scope with specific scope object', scope, this); }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1], false, null); listen(eventTargets[0], EventType.A, listeners[2], false, scope); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(1)); } function testDispatchEventDoesNotThrowWithDisposedEventTarget() { goog.dispose(eventTargets[0]); assertTrue(dispatchEvent(eventTargets[0], EventType.A)); } function testDispatchEventWithObjectLiteral() { listen(eventTargets[0], EventType.A, listeners[0]); assertTrue(dispatchEvent(eventTargets[0], {type: EventType.A})); assertListenerIsCalled(listeners[0], times(1)); assertNoOtherListenerIsCalled(); } function testDispatchEventWithCustomEventObject() { listen(eventTargets[0], EventType.A, listeners[0]); var e = new TestEvent(); assertTrue(dispatchEvent(eventTargets[0], e)); assertListenerIsCalled(listeners[0], times(1)); assertNoOtherListenerIsCalled(); var actualEvent = listeners[0].getLastCall().getArgument(0); assertEquals(e, actualEvent); assertEquals(eventTargets[0], actualEvent.target); } function testDisposingEventTargetRemovesListeners() { listen(eventTargets[0], EventType.A, listeners[0]); goog.dispose(eventTargets[0]); dispatchEvent(eventTargets[0], EventType.A); assertNoOtherListenerIsCalled(); } /** * Unlisten/unlistenByKey should still work after disposal. There are * many circumstances when this is actually necessary. For example, a * user may have listened to an event target and stored the key * (e.g. in a goog.events.EventHandler) and only unlisten after the * target has been disposed. */ function testUnlistenWorksAfterDisposal() { var key = listen(eventTargets[0], EventType.A, listeners[0]); goog.dispose(eventTargets[0]); unlisten(eventTargets[0], EventType.A, listeners[1]); if (unlistenByKey) { unlistenByKey(eventTargets[0], key); } } function testRemovingListener() { var ret1 = unlisten(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[0]); var ret2 = unlisten(eventTargets[0], EventType.A, listeners[1]); var ret3 = unlisten(eventTargets[0], EventType.B, listeners[0]); var ret4 = unlisten(eventTargets[1], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); var ret5 = unlisten(eventTargets[0], EventType.A, listeners[0]); var ret6 = unlisten(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertNoOtherListenerIsCalled(); if (unlistenReturnType == goog.events.eventTargetTester.UnlistenReturnType.BOOLEAN) { assertFalse(ret1); assertFalse(ret2); assertFalse(ret3); assertFalse(ret4); assertTrue(ret5); assertFalse(ret6); } else { assertUndefined(ret1); assertUndefined(ret2); assertUndefined(ret3); assertUndefined(ret4); assertUndefined(ret5); assertUndefined(ret6); } } function testCapture() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); eventTargets[9].setParentEventTarget(eventTargets[0]); var ordering = 0; listeners[0] = createListener( function(e) { assertEquals(eventTargets[2], e.currentTarget); assertEquals(eventTargets[0], e.target); assertEquals('First capture listener is not called first', 0, ordering); ordering++; }); listeners[1] = createListener( function(e) { assertEquals(eventTargets[1], e.currentTarget); assertEquals(eventTargets[0], e.target); assertEquals('2nd capture listener is not called 2nd', 1, ordering); ordering++; }); listeners[2] = createListener( function(e) { assertEquals(eventTargets[0], e.currentTarget); assertEquals(eventTargets[0], e.target); assertEquals('3rd capture listener is not called 3rd', 2, ordering); ordering++; }); listen(eventTargets[2], EventType.A, listeners[0], true); listen(eventTargets[1], EventType.A, listeners[1], true); listen(eventTargets[0], EventType.A, listeners[2], true); // These should not be called. listen(eventTargets[3], EventType.A, listeners[3], true); listen(eventTargets[0], EventType.B, listeners[4], true); listen(eventTargets[0], EventType.C, listeners[5], true); listen(eventTargets[1], EventType.B, listeners[6], true); listen(eventTargets[1], EventType.C, listeners[7], true); listen(eventTargets[2], EventType.B, listeners[8], true); listen(eventTargets[2], EventType.C, listeners[9], true); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(1)); assertNoOtherListenerIsCalled(); } function testBubble() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); eventTargets[9].setParentEventTarget(eventTargets[0]); var ordering = 0; listeners[0] = createListener( function(e) { assertEquals(eventTargets[0], e.currentTarget); assertEquals(eventTargets[0], e.target); assertEquals('First bubble listener is not called first', 0, ordering); ordering++; }); listeners[1] = createListener( function(e) { assertEquals(eventTargets[1], e.currentTarget); assertEquals(eventTargets[0], e.target); assertEquals('2nd bubble listener is not called 2nd', 1, ordering); ordering++; }); listeners[2] = createListener( function(e) { assertEquals(eventTargets[2], e.currentTarget); assertEquals(eventTargets[0], e.target); assertEquals('3rd bubble listener is not called 3rd', 2, ordering); ordering++; }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[1], EventType.A, listeners[1]); listen(eventTargets[2], EventType.A, listeners[2]); // These should not be called. listen(eventTargets[3], EventType.A, listeners[3]); listen(eventTargets[0], EventType.B, listeners[4]); listen(eventTargets[0], EventType.C, listeners[5]); listen(eventTargets[1], EventType.B, listeners[6]); listen(eventTargets[1], EventType.C, listeners[7]); listen(eventTargets[2], EventType.B, listeners[8]); listen(eventTargets[2], EventType.C, listeners[9]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(1)); assertNoOtherListenerIsCalled(); } function testCaptureAndBubble() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); listen(eventTargets[0], EventType.A, listeners[0], true); listen(eventTargets[1], EventType.A, listeners[1], true); listen(eventTargets[2], EventType.A, listeners[2], true); listen(eventTargets[0], EventType.A, listeners[3]); listen(eventTargets[1], EventType.A, listeners[4]); listen(eventTargets[2], EventType.A, listeners[5]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(1)); assertListenerIsCalled(listeners[3], times(1)); assertListenerIsCalled(listeners[4], times(1)); assertListenerIsCalled(listeners[5], times(1)); assertNoOtherListenerIsCalled(); } function testPreventDefaultByReturningFalse() { listeners[0] = createListener(function(e) { return false; }); listeners[1] = createListener(function(e) { return true; }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1]); var result = dispatchEvent(eventTargets[0], EventType.A); assertFalse(result); } function testPreventDefault() { listeners[0] = createListener(function(e) { e.preventDefault(); }); listeners[1] = createListener(function(e) { return true; }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1]); var result = dispatchEvent(eventTargets[0], EventType.A); assertFalse(result); } function testPreventDefaultAtCapture() { listeners[0] = createListener(function(e) { e.preventDefault(); }); listeners[1] = createListener(function(e) { return true; }); listen(eventTargets[0], EventType.A, listeners[0], true); listen(eventTargets[0], EventType.A, listeners[1], true); var result = dispatchEvent(eventTargets[0], EventType.A); assertFalse(result); } function testStopPropagation() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); listeners[0] = createListener(function(e) { e.stopPropagation(); }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1]); listen(eventTargets[1], EventType.A, listeners[2]); listen(eventTargets[2], EventType.A, listeners[3]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertNoOtherListenerIsCalled(); } function testStopPropagation2() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); listeners[1] = createListener(function(e) { e.stopPropagation(); }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1]); listen(eventTargets[1], EventType.A, listeners[2]); listen(eventTargets[2], EventType.A, listeners[3]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertNoOtherListenerIsCalled(); } function testStopPropagation3() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); listeners[2] = createListener(function(e) { e.stopPropagation(); }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1]); listen(eventTargets[1], EventType.A, listeners[2]); listen(eventTargets[2], EventType.A, listeners[3]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(1)); assertNoOtherListenerIsCalled(); } function testStopPropagationAtCapture() { eventTargets[0].setParentEventTarget(eventTargets[1]); eventTargets[1].setParentEventTarget(eventTargets[2]); listeners[0] = createListener(function(e) { e.stopPropagation(); }); listen(eventTargets[2], EventType.A, listeners[0], true); listen(eventTargets[1], EventType.A, listeners[1], true); listen(eventTargets[0], EventType.A, listeners[2], true); listen(eventTargets[0], EventType.A, listeners[3]); listen(eventTargets[1], EventType.A, listeners[4]); listen(eventTargets[2], EventType.A, listeners[5]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertNoOtherListenerIsCalled(); } function testHandleEvent() { var obj = {}; obj.handleEvent = goog.testing.recordFunction(); listen(eventTargets[0], EventType.A, obj); dispatchEvent(eventTargets[0], EventType.A); assertEquals(1, obj.handleEvent.getCallCount()); } function testListenOnce() { if (!listenOnce) { return; } listenOnce(eventTargets[0], EventType.A, listeners[0], true); listenOnce(eventTargets[0], EventType.A, listeners[1]); listenOnce(eventTargets[0], EventType.B, listeners[2]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(0)); assertNoOtherListenerIsCalled(); resetListeners(); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(0)); assertListenerIsCalled(listeners[1], times(0)); assertListenerIsCalled(listeners[2], times(0)); dispatchEvent(eventTargets[0], EventType.B); assertListenerIsCalled(listeners[2], times(1)); assertNoOtherListenerIsCalled(); } function testUnlistenInListen() { listeners[1] = createListener( function(e) { unlisten(eventTargets[0], EventType.A, listeners[1]); unlisten(eventTargets[0], EventType.A, listeners[2]); }); listen(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[1]); listen(eventTargets[0], EventType.A, listeners[2]); listen(eventTargets[0], EventType.A, listeners[3]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(0)); assertListenerIsCalled(listeners[3], times(1)); assertNoOtherListenerIsCalled(); resetListeners(); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(0)); assertListenerIsCalled(listeners[2], times(0)); assertListenerIsCalled(listeners[3], times(1)); assertNoOtherListenerIsCalled(); } function testUnlistenByKeyInListen() { if (!unlistenByKey) { return; } var key1, key2; listeners[1] = createListener( function(e) { unlistenByKey(eventTargets[0], key1); unlistenByKey(eventTargets[0], key2); }); listen(eventTargets[0], EventType.A, listeners[0]); key1 = listen(eventTargets[0], EventType.A, listeners[1]); key2 = listen(eventTargets[0], EventType.A, listeners[2]); listen(eventTargets[0], EventType.A, listeners[3]); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(0)); assertListenerIsCalled(listeners[3], times(1)); assertNoOtherListenerIsCalled(); resetListeners(); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(0)); assertListenerIsCalled(listeners[2], times(0)); assertListenerIsCalled(listeners[3], times(1)); assertNoOtherListenerIsCalled(); } function testSetParentEventTarget() { assertNull(eventTargets[0].getParentEventTarget()); eventTargets[0].setParentEventTarget(eventTargets[1]); assertEquals(eventTargets[1], eventTargets[0].getParentEventTarget()); assertNull(eventTargets[1].getParentEventTarget()); eventTargets[0].setParentEventTarget(null); assertNull(eventTargets[0].getParentEventTarget()); } function testListenOnceAfterListenDoesNotChangeExistingListener() { if (!listenOnce) { return; } listen(eventTargets[0], EventType.A, listeners[0]); listenOnce(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(3)); assertNoOtherListenerIsCalled(); } function testListenOnceAfterListenOnceDoesNotChangeExistingListener() { if (!listenOnce) { return; } listenOnce(eventTargets[0], EventType.A, listeners[0]); listenOnce(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(1)); assertNoOtherListenerIsCalled(); } function testListenAfterListenOnceRemoveOnceness() { if (!listenOnce) { return; } listenOnce(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.A); assertListenerIsCalled(listeners[0], times(3)); assertNoOtherListenerIsCalled(); } function testUnlistenAfterListenOnce() { if (!listenOnce) { return; } listenOnce(eventTargets[0], EventType.A, listeners[0]); unlisten(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); listen(eventTargets[0], EventType.A, listeners[0]); listenOnce(eventTargets[0], EventType.A, listeners[0]); unlisten(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); listenOnce(eventTargets[0], EventType.A, listeners[0]); listen(eventTargets[0], EventType.A, listeners[0]); unlisten(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); listenOnce(eventTargets[0], EventType.A, listeners[0]); listenOnce(eventTargets[0], EventType.A, listeners[0]); unlisten(eventTargets[0], EventType.A, listeners[0]); dispatchEvent(eventTargets[0], EventType.A); assertNoOtherListenerIsCalled(); } function testRemoveAllWithType() { if (!removeAll) { return; } listen(eventTargets[0], EventType.A, listeners[0], true); listen(eventTargets[0], EventType.A, listeners[1]); listen(eventTargets[0], EventType.C, listeners[2], true); listen(eventTargets[0], EventType.C, listeners[3]); listen(eventTargets[0], EventType.B, listeners[4], true); listen(eventTargets[0], EventType.B, listeners[5], true); listen(eventTargets[0], EventType.B, listeners[6]); listen(eventTargets[0], EventType.B, listeners[7]); assertEquals(4, removeAll(eventTargets[0], EventType.B)); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.B); dispatchEvent(eventTargets[0], EventType.C); assertListenerIsCalled(listeners[0], times(1)); assertListenerIsCalled(listeners[1], times(1)); assertListenerIsCalled(listeners[2], times(1)); assertListenerIsCalled(listeners[3], times(1)); assertNoOtherListenerIsCalled(); } function testRemoveAll() { if (!removeAll) { return; } listen(eventTargets[0], EventType.A, listeners[0], true); listen(eventTargets[0], EventType.A, listeners[1]); listen(eventTargets[0], EventType.C, listeners[2], true); listen(eventTargets[0], EventType.C, listeners[3]); listen(eventTargets[0], EventType.B, listeners[4], true); listen(eventTargets[0], EventType.B, listeners[5], true); listen(eventTargets[0], EventType.B, listeners[6]); listen(eventTargets[0], EventType.B, listeners[7]); assertEquals(8, removeAll(eventTargets[0])); dispatchEvent(eventTargets[0], EventType.A); dispatchEvent(eventTargets[0], EventType.B); dispatchEvent(eventTargets[0], EventType.C); assertNoOtherListenerIsCalled(); } function testGetListeners() { if (!getListeners) { return; } listen(eventTargets[0], EventType.A, listeners[0], true); listen(eventTargets[0], EventType.A, listeners[1], true); listen(eventTargets[0], EventType.A, listeners[2]); listen(eventTargets[0], EventType.A, listeners[3]); var l = getListeners(eventTargets[0], EventType.A, true); assertEquals(2, l.length); assertEquals(listeners[0], l[0].listener); assertEquals(listeners[1], l[1].listener); l = getListeners(eventTargets[0], EventType.A, false); assertEquals(2, l.length); assertEquals(listeners[2], l[0].listener); assertEquals(listeners[3], l[1].listener); l = getListeners(eventTargets[0], EventType.B, true); assertEquals(0, l.length); } function testGetListener() { if (!getListener) { return; } listen(eventTargets[0], EventType.A, listeners[0], true); assertNotNull(getListener(eventTargets[0], EventType.A, listeners[0], true)); assertNull( getListener(eventTargets[0], EventType.A, listeners[0], true, {})); assertNull(getListener(eventTargets[1], EventType.A, listeners[0], true)); assertNull(getListener(eventTargets[0], EventType.B, listeners[0], true)); assertNull(getListener(eventTargets[0], EventType.A, listeners[1], true)); } function testHasListener() { if (!hasListener) { return; } assertFalse(hasListener(eventTargets[0])); listen(eventTargets[0], EventType.A, listeners[0], true); assertTrue(hasListener(eventTargets[0])); assertTrue(hasListener(eventTargets[0], EventType.A)); assertTrue(hasListener(eventTargets[0], EventType.A, true)); assertTrue(hasListener(eventTargets[0], undefined, true)); assertFalse(hasListener(eventTargets[0], EventType.A, false)); assertFalse(hasListener(eventTargets[0], undefined, false)); assertFalse(hasListener(eventTargets[0], EventType.B)); assertFalse(hasListener(eventTargets[0], EventType.B, true)); assertFalse(hasListener(eventTargets[1])); } function testFiringEventBeforeDisposeInternalWorks() { /** * @extends {goog.events.EventTarget} * @constructor */ var MockTarget = function() { goog.base(this); }; goog.inherits(MockTarget, goog.events.EventTarget); MockTarget.prototype.disposeInternal = function() { dispatchEvent(this, EventType.A); goog.base(this, 'disposeInternal'); }; var t = new MockTarget(); try { listen(t, EventType.A, listeners[0]); t.dispose(); assertListenerIsCalled(listeners[0], times(1)); } catch (e) { goog.dispose(t); } } function testLoopDetection() { // In the old event target API, parent-target loops would get short-circuited // by the targetMap.remaining_ optimization. In the new API, we need some // other mechanism to detect loops. var target = new goog.events.EventTarget(); target.setParentEventTarget(target); if (goog.events.Listenable.USE_LISTENABLE_INTERFACE) { try { target.dispatchEvent('string'); fail('expected error'); } catch (e) { assertContains('infinite', e.message); } } else { target.dispatchEvent('string'); // No error. } }
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview An object that encapsulates text changed events for textareas * and input element of type text and password. The event occurs after the value * has been changed. The event does not occur if value was changed * programmatically.<br> * <br> * Note: this does not guarantee the correctness of {@code keyCode} or * {@code charCode}, or attempt to unify them across browsers. See * {@code goog.events.KeyHandler} for that functionality.<br> * <br> * Known issues: * <ul> * <li>Does not trigger for drop events on Opera due to browser bug. * <li>IE doesn't have native support for input event. WebKit before version 531 * doesn't have support for textareas. For those browsers an emulation mode * based on key, clipboard and drop events is used. Thus this event won't * trigger in emulation mode if text was modified by context menu commands * such as 'Undo' and 'Delete'. * </ul> * @author arv@google.com (Erik Arvidsson) * @see ../demos/inputhandler.html */ goog.provide('goog.events.InputHandler'); goog.provide('goog.events.InputHandler.EventType'); goog.require('goog.Timer'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.events.BrowserEvent'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventTarget'); goog.require('goog.events.KeyCodes'); goog.require('goog.userAgent'); /** * This event handler will dispatch events when the user types into a text * input, password input or a textarea * @param {Element} element The element that you want to listen for input * events on. * @constructor * @extends {goog.events.EventTarget} */ goog.events.InputHandler = function(element) { goog.base(this); /** * The element that you want to listen for input events on. * @type {Element} * @private */ this.element_ = element; // Determine whether input event should be emulated. // IE8 doesn't support input events. We could use property change events but // they are broken in many ways: // - Fire even if value was changed programmatically. // - Aren't always delivered. For example, if you change value or even width // of input programmatically, next value change made by user won't fire an // event. // IE9 supports input events when characters are inserted, but not deleted. // WebKit before version 531 did not support input events for textareas. var emulateInputEvents = goog.userAgent.IE || (goog.userAgent.WEBKIT && !goog.userAgent.isVersion('531') && element.tagName == 'TEXTAREA'); /** * @type {goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); // Even if input event emulation is enabled, still listen for input events // since they may be partially supported by the browser (such as IE9). // If the input event does fire, we will be able to dispatch synchronously. // (InputHandler events being asynchronous for IE is a common issue for // cases like auto-grow textareas where they result in a quick flash of // scrollbars between the textarea content growing and it being resized to // fit.) this.eventHandler_.listen( this.element_, emulateInputEvents ? ['keydown', 'paste', 'cut', 'drop', 'input'] : 'input', this); }; goog.inherits(goog.events.InputHandler, goog.events.EventTarget); /** * Enum type for the events fired by the input handler * @enum {string} */ goog.events.InputHandler.EventType = { INPUT: 'input' }; /** * Id of a timer used to postpone firing input event in emulation mode. * @type {?number} * @private */ goog.events.InputHandler.prototype.timer_ = null; /** * This handles the underlying events and dispatches a new event as needed. * @param {goog.events.BrowserEvent} e The underlying browser event. */ goog.events.InputHandler.prototype.handleEvent = function(e) { if (e.type == 'input') { // This event happens after all the other events we listen to, so cancel // an asynchronous event dispatch if we have it queued up. Otherwise, we // will end up firing an extra event. this.cancelTimerIfSet_(); // Unlike other browsers, Opera fires an extra input event when an element // is blurred after the user has input into it. Since Opera doesn't fire // input event on drop, it's enough to check whether element still has focus // to suppress bogus notification. if (!goog.userAgent.OPERA || this.element_ == goog.dom.getOwnerDocument(this.element_).activeElement) { this.dispatchEvent(this.createInputEvent_(e)); } } else { // Filter out key events that don't modify text. if (e.type == 'keydown' && !goog.events.KeyCodes.isTextModifyingKeyEvent(e)) { return; } // It is still possible that pressed key won't modify the value of an // element. Storing old value will help us to detect modification but is // also a little bit dangerous. If value is changed programmatically in // another key down handler, we will detect it as user-initiated change. var valueBeforeKey = e.type == 'keydown' ? this.element_.value : null; // In IE on XP, IME the element's value has already changed when we get // keydown events when the user is using an IME. In this case, we can't // check the current value normally, so we assume that it's a modifying key // event. This means that ENTER when used to commit will fire a spurious // input event, but it's better to have a false positive than let some input // slip through the cracks. if (goog.userAgent.IE && e.keyCode == goog.events.KeyCodes.WIN_IME) { valueBeforeKey = null; } // Create an input event now, because when we fire it on timer, the // underlying event will already be disposed. var inputEvent = this.createInputEvent_(e); // Since key down, paste, cut and drop events are fired before actual value // of the element has changed, we need to postpone dispatching input event // until value is updated. this.cancelTimerIfSet_(); this.timer_ = goog.Timer.callOnce(function() { this.timer_ = null; if (this.element_.value != valueBeforeKey) { this.dispatchEvent(inputEvent); } }, 0, this); } }; /** * Cancels timer if it is set, does nothing otherwise. * @private */ goog.events.InputHandler.prototype.cancelTimerIfSet_ = function() { if (this.timer_ != null) { goog.Timer.clear(this.timer_); this.timer_ = null; } }; /** * Creates an input event from the browser event. * @param {goog.events.BrowserEvent} be A browser event. * @return {goog.events.BrowserEvent} An input event. * @private */ goog.events.InputHandler.prototype.createInputEvent_ = function(be) { var e = new goog.events.BrowserEvent(be.getBrowserEvent()); e.type = goog.events.InputHandler.EventType.INPUT; return e; }; /** @override */ goog.events.InputHandler.prototype.disposeInternal = function() { goog.base(this, 'disposeInternal'); this.eventHandler_.dispose(); this.cancelTimerIfSet_(); delete this.element_; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Defines a class for parsing JSON using the browser's built in * JSON library. */ goog.provide('goog.json.NativeJsonProcessor'); goog.require('goog.asserts'); goog.require('goog.json'); goog.require('goog.json.Processor'); /** * A class that parses and stringifies JSON using the browser's built-in JSON * library, if it is avaliable. * * Note that the native JSON api has subtle differences across browsers, so * use this implementation with care. See json_test#assertSerialize * for details on the differences from goog.json. * * This implementation is signficantly faster than goog.json, at least on * Chrome. See json_perf.html for a perf test showing the difference. * * @param {?goog.json.Replacer=} opt_replacer An optional replacer to use during * serialization. * @param {?goog.json.Reviver=} opt_reviver An optional reviver to use during * parsing. * @constructor * @implements {goog.json.Processor} */ goog.json.NativeJsonProcessor = function(opt_replacer, opt_reviver) { goog.asserts.assert(goog.isDef(goog.global['JSON']), 'JSON not defined'); /** * @type {goog.json.Replacer|null|undefined} * @private */ this.replacer_ = opt_replacer; /** * @type {goog.json.Reviver|null|undefined} * @private */ this.reviver_ = opt_reviver; }; /** @override */ goog.json.NativeJsonProcessor.prototype.stringify = function(object) { return goog.global['JSON'].stringify(object, this.replacer_); }; /** @override */ goog.json.NativeJsonProcessor.prototype.parse = function(s) { return goog.global['JSON'].parse(s, this.reviver_); };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Defines a class for parsing JSON using eval. */ goog.provide('goog.json.EvalJsonProcessor'); goog.require('goog.json'); goog.require('goog.json.Processor'); goog.require('goog.json.Serializer'); /** * A class that parses and stringifies JSON using eval (as implemented in * goog.json). * Adapts {@code goog.json} to the {@code goog.json.Processor} interface. * * @param {?goog.json.Replacer=} opt_replacer An optional replacer to use during * serialization. * @param {?boolean=} opt_useUnsafeParsing Whether to use goog.json.unsafeParse * for parsing. Safe parsing is very slow on large strings. On the other * hand, unsafe parsing uses eval() without checking whether the string is * valid, so it should only be used if you trust the source of the string. * @constructor * @implements {goog.json.Processor} */ goog.json.EvalJsonProcessor = function(opt_replacer, opt_useUnsafeParsing) { /** * @type {goog.json.Serializer} * @private */ this.serializer_ = new goog.json.Serializer(opt_replacer); /** * @type {function(string): *} * @private */ this.parser_ = opt_useUnsafeParsing ? goog.json.unsafeParse : goog.json.parse; }; /** @override */ goog.json.EvalJsonProcessor.prototype.stringify = function(object) { return this.serializer_.serialize(object); }; /** @override */ goog.json.EvalJsonProcessor.prototype.parse = function(s) { return this.parser_(s); };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Defines an interface for JSON parsing and serialization. */ goog.provide('goog.json.Processor'); goog.require('goog.string.Parser'); goog.require('goog.string.Stringifier'); /** * An interface for JSON parsing and serialization. * @interface * @extends {goog.string.Parser} * @extends {goog.string.Stringifier} */ goog.json.Processor = function() {};
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview JSON utility functions. * @author arv@google.com (Erik Arvidsson) */ goog.provide('goog.json'); goog.provide('goog.json.Serializer'); /** * Tests if a string is an invalid JSON string. This only ensures that we are * not using any invalid characters * @param {string} s The string to test. * @return {boolean} True if the input is a valid JSON string. * @private */ goog.json.isValid_ = function(s) { // All empty whitespace is not valid. if (/^\s*$/.test(s)) { return false; } // This is taken from http://www.json.org/json2.js which is released to the // public domain. // Changes: We dissallow \u2028 Line separator and \u2029 Paragraph separator // inside strings. We also treat \u2028 and \u2029 as whitespace which they // are in the RFC but IE and Safari does not match \s to these so we need to // include them in the reg exps in all places where whitespace is allowed. // We allowed \x7f inside strings because some tools don't escape it, // e.g. http://www.json.org/java/org/json/JSONObject.java // Parsing happens in three stages. In the first stage, we run the text // against regular expressions that look for non-JSON patterns. We are // especially concerned with '()' and 'new' because they can cause invocation, // and '=' because it can cause mutation. But just to be safe, we want to // reject all unexpected forms. // We split the first stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace all backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. // Don't make these static since they have the global flag. var backslashesRe = /\\["\\\/bfnrtu]/g; var simpleValuesRe = /"[^"\\\n\r\u2028\u2029\x00-\x08\x0a-\x1f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; var openBracketsRe = /(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g; var remainderRe = /^[\],:{}\s\u2028\u2029]*$/; return remainderRe.test(s.replace(backslashesRe, '@'). replace(simpleValuesRe, ']'). replace(openBracketsRe, '')); }; /** * Parses a JSON string and returns the result. This throws an exception if * the string is an invalid JSON string. * * Note that this is very slow on large strings. If you trust the source of * the string then you should use unsafeParse instead. * * @param {*} s The JSON string to parse. * @return {Object} The object generated from the JSON string. */ goog.json.parse = function(s) { var o = String(s); if (goog.json.isValid_(o)) { /** @preserveTry */ try { return /** @type {Object} */ (eval('(' + o + ')')); } catch (ex) { } } throw Error('Invalid JSON string: ' + o); }; /** * Parses a JSON string and returns the result. This uses eval so it is open * to security issues and it should only be used if you trust the source. * * @param {string} s The JSON string to parse. * @return {Object} The object generated from the JSON string. */ goog.json.unsafeParse = function(s) { return /** @type {Object} */ (eval('(' + s + ')')); }; /** * JSON replacer, as defined in Section 15.12.3 of the ES5 spec. * * TODO(nicksantos): Array should also be a valid replacer. * * @typedef {function(this:Object, string, *): *} */ goog.json.Replacer; /** * JSON reviver, as defined in Section 15.12.2 of the ES5 spec. * * @typedef {function(this:Object, string, *): *} */ goog.json.Reviver; /** * Serializes an object or a value to a JSON string. * * @param {*} object The object to serialize. * @param {?goog.json.Replacer=} opt_replacer A replacer function * called for each (key, value) pair that determines how the value * should be serialized. By defult, this just returns the value * and allows default serialization to kick in. * @throws Error if there are loops in the object graph. * @return {string} A JSON string representation of the input. */ goog.json.serialize = function(object, opt_replacer) { // NOTE(nicksantos): Currently, we never use JSON.stringify. // // The last time I evaluated this, JSON.stringify had subtle bugs and behavior // differences on all browsers, and the performance win was not large enough // to justify all the issues. This may change in the future as browser // implementations get better. // // assertSerialize in json_test contains if branches for the cases // that fail. return new goog.json.Serializer(opt_replacer).serialize(object); }; /** * Class that is used to serialize JSON objects to a string. * @param {?goog.json.Replacer=} opt_replacer Replacer. * @constructor */ goog.json.Serializer = function(opt_replacer) { /** * @type {goog.json.Replacer|null|undefined} * @private */ this.replacer_ = opt_replacer; }; /** * Serializes an object or a value to a JSON string. * * @param {*} object The object to serialize. * @throws Error if there are loops in the object graph. * @return {string} A JSON string representation of the input. */ goog.json.Serializer.prototype.serialize = function(object) { var sb = []; this.serialize_(object, sb); return sb.join(''); }; /** * Serializes a generic value to a JSON string * @private * @param {*} object The object to serialize. * @param {Array} sb Array used as a string builder. * @throws Error if there are loops in the object graph. */ goog.json.Serializer.prototype.serialize_ = function(object, sb) { switch (typeof object) { case 'string': this.serializeString_(/** @type {string} */ (object), sb); break; case 'number': this.serializeNumber_(/** @type {number} */ (object), sb); break; case 'boolean': sb.push(object); break; case 'undefined': sb.push('null'); break; case 'object': if (object == null) { sb.push('null'); break; } if (goog.isArray(object)) { this.serializeArray(/** @type {!Array} */ (object), sb); break; } // should we allow new String, new Number and new Boolean to be treated // as string, number and boolean? Most implementations do not and the // need is not very big this.serializeObject_(/** @type {Object} */ (object), sb); break; case 'function': // Skip functions. // TODO(user) Should we return something here? break; default: throw Error('Unknown type: ' + typeof object); } }; /** * Character mappings used internally for goog.string.quote * @private * @type {Object} */ goog.json.Serializer.charToJsonCharCache_ = { '\"': '\\"', '\\': '\\\\', '/': '\\/', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', '\x0B': '\\u000b' // '\v' is not supported in JScript }; /** * Regular expression used to match characters that need to be replaced. * The S60 browser has a bug where unicode characters are not matched by * regular expressions. The condition below detects such behaviour and * adjusts the regular expression accordingly. * @private * @type {RegExp} */ goog.json.Serializer.charsToReplace_ = /\uffff/.test('\uffff') ? /[\\\"\x00-\x1f\x7f-\uffff]/g : /[\\\"\x00-\x1f\x7f-\xff]/g; /** * Serializes a string to a JSON string * @private * @param {string} s The string to serialize. * @param {Array} sb Array used as a string builder. */ goog.json.Serializer.prototype.serializeString_ = function(s, sb) { // The official JSON implementation does not work with international // characters. sb.push('"', s.replace(goog.json.Serializer.charsToReplace_, function(c) { // caching the result improves performance by a factor 2-3 if (c in goog.json.Serializer.charToJsonCharCache_) { return goog.json.Serializer.charToJsonCharCache_[c]; } var cc = c.charCodeAt(0); var rv = '\\u'; if (cc < 16) { rv += '000'; } else if (cc < 256) { rv += '00'; } else if (cc < 4096) { // \u1000 rv += '0'; } return goog.json.Serializer.charToJsonCharCache_[c] = rv + cc.toString(16); }), '"'); }; /** * Serializes a number to a JSON string * @private * @param {number} n The number to serialize. * @param {Array} sb Array used as a string builder. */ goog.json.Serializer.prototype.serializeNumber_ = function(n, sb) { sb.push(isFinite(n) && !isNaN(n) ? n : 'null'); }; /** * Serializes an array to a JSON string * @param {Array} arr The array to serialize. * @param {Array} sb Array used as a string builder. * @protected */ goog.json.Serializer.prototype.serializeArray = function(arr, sb) { var l = arr.length; sb.push('['); var sep = ''; for (var i = 0; i < l; i++) { sb.push(sep); var value = arr[i]; this.serialize_( this.replacer_ ? this.replacer_.call(arr, String(i), value) : value, sb); sep = ','; } sb.push(']'); }; /** * Serializes an object to a JSON string * @private * @param {Object} obj The object to serialize. * @param {Array} sb Array used as a string builder. */ goog.json.Serializer.prototype.serializeObject_ = function(obj, sb) { sb.push('{'); var sep = ''; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var value = obj[key]; // Skip functions. // TODO(ptucker) Should we return something for function properties? if (typeof value != 'function') { sb.push(sep); this.serializeString_(key, sb); sb.push(':'); this.serialize_( this.replacer_ ? this.replacer_.call(obj, key, value) : value, sb); sep = ','; } } } sb.push('}'); };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A basic statistics tracker. * */ goog.provide('goog.stats.BasicStat'); goog.require('goog.array'); goog.require('goog.debug.Logger'); goog.require('goog.iter'); goog.require('goog.object'); goog.require('goog.string.format'); goog.require('goog.structs.CircularBuffer'); /** * Tracks basic statistics over a specified time interval. * * Statistics are kept in a fixed number of slots, each representing * an equal portion of the time interval. * * Most methods optionally allow passing in the current time, so that * higher level stats can synchronize operations on multiple child * objects. Under normal usage, the default of goog.now() should be * sufficient. * * @param {number} interval The stat interval, in milliseconds. * @constructor */ goog.stats.BasicStat = function(interval) { goog.asserts.assert(interval > 50); /** * The time interval that this statistic aggregates over. * @type {number} * @private */ this.interval_ = interval; /** * The number of milliseconds in each slot. * @type {number} * @private */ this.slotInterval_ = Math.floor(interval / goog.stats.BasicStat.NUM_SLOTS_); /** * The array of slots. * @type {goog.structs.CircularBuffer} * @private */ this.slots_ = new goog.structs.CircularBuffer(goog.stats.BasicStat.NUM_SLOTS_); }; /** * The number of slots. This value limits the accuracy of the get() * method to (this.interval_ / NUM_SLOTS). A 1-minute statistic would * be accurate to within 2 seconds. * @type {number} * @private */ goog.stats.BasicStat.NUM_SLOTS_ = 50; /** * @type {goog.debug.Logger} * @private */ goog.stats.BasicStat.prototype.logger_ = goog.debug.Logger.getLogger('goog.stats.BasicStat'); /** * @return {number} The interval which over statistics are being * accumulated, in milliseconds. */ goog.stats.BasicStat.prototype.getInterval = function() { return this.interval_; }; /** * Increments the count of this statistic by the specified amount. * * @param {number} amt The amount to increase the count by. * @param {number=} opt_now The time, in milliseconds, to be treated * as the "current" time. The current time must always be greater * than or equal to the last time recorded by this stat tracker. */ goog.stats.BasicStat.prototype.incBy = function(amt, opt_now) { var now = opt_now ? opt_now : goog.now(); this.checkForTimeTravel_(now); var slot = /** @type {goog.stats.BasicStat.Slot_} */ (this.slots_.getLast()); if (!slot || now >= slot.end) { slot = new goog.stats.BasicStat.Slot_(this.getSlotBoundary_(now)); this.slots_.add(slot); } slot.count += amt; slot.min = Math.min(amt, slot.min); slot.max = Math.max(amt, slot.max); }; /** * Returns the count of the statistic over its configured time * interval. * @param {number=} opt_now The time, in milliseconds, to be treated * as the "current" time. The current time must always be greater * than or equal to the last time recorded by this stat tracker. * @return {number} The total count over the tracked interval. */ goog.stats.BasicStat.prototype.get = function(opt_now) { return this.reduceSlots_(opt_now, function(sum, slot) { return sum + slot.count; }, 0); }; /** * Returns the magnitute of the largest atomic increment that occurred * during the watched time interval. * @param {number=} opt_now The time, in milliseconds, to be treated * as the "current" time. The current time must always be greater * than or equal to the last time recorded by this stat tracker. * @return {number} The maximum count of this statistic. */ goog.stats.BasicStat.prototype.getMax = function(opt_now) { return this.reduceSlots_(opt_now, function(max, slot) { return Math.max(max, slot.max); }, Number.MIN_VALUE); }; /** * Returns the magnitute of the smallest atomic increment that * occurred during the watched time interval. * @param {number=} opt_now The time, in milliseconds, to be treated * as the "current" time. The current time must always be greater * than or equal to the last time recorded by this stat tracker. * @return {number} The minimum count of this statistic. */ goog.stats.BasicStat.prototype.getMin = function(opt_now) { return this.reduceSlots_(opt_now, function(min, slot) { return Math.min(min, slot.min); }, Number.MAX_VALUE); }; /** * Passes each active slot into a function and accumulates the result. * * @param {number|undefined} now The current time, in milliseconds. * @param {function(number, goog.stats.BasicStat.Slot_): number} func * The function to call for every active slot. This function * takes two arguments: the previous result and the new slot to * include in the reduction. * @param {number} val The initial value for the reduction. * @return {number} The result of the reduction. * @private */ goog.stats.BasicStat.prototype.reduceSlots_ = function(now, func, val) { now = now || goog.now(); this.checkForTimeTravel_(now); var rval = val; var start = this.getSlotBoundary_(now) - this.interval_; for (var i = this.slots_.getCount() - 1; i >= 0; --i) { var slot = /** @type {goog.stats.BasicStat.Slot_} */ (this.slots_.get(i)); if (slot.end <= start) { break; } rval = func(rval, slot); } return rval; }; /** * Computes the end time for the slot that should contain the count * around the given time. This method ensures that every bucket is * aligned on a "this.slotInterval_" millisecond boundary. * @param {number} time The time to compute a boundary for. * @return {number} The computed boundary. * @private */ goog.stats.BasicStat.prototype.getSlotBoundary_ = function(time) { return this.slotInterval_ * (Math.floor(time / this.slotInterval_) + 1); }; /** * Checks that time never goes backwards. If it does (for example, * the user changes their system clock), the object state is cleared. * @param {number} now The current time, in milliseconds. * @private */ goog.stats.BasicStat.prototype.checkForTimeTravel_ = function(now) { var slot = /** @type {goog.stats.BasicStat.Slot_} */ (this.slots_.getLast()); if (slot) { var slotStart = slot.end - this.slotInterval_; if (now < slotStart) { this.logger_.warning(goog.string.format( 'Went backwards in time: now=%d, slotStart=%d. Resetting state.', now, slotStart)); this.reset_(); } } }; /** * Clears any statistics tracked by this object, as though it were * freshly created. * @private */ goog.stats.BasicStat.prototype.reset_ = function() { this.slots_.clear(); }; /** * A struct containing information for each sub-interval. * @param {number} end The end time for this slot, in milliseconds. * @constructor * @private */ goog.stats.BasicStat.Slot_ = function(end) { /** * End time of this slot, exclusive. * @type {number} */ this.end = end; }; /** * Aggregated count within this slot. * @type {number} */ goog.stats.BasicStat.Slot_.prototype.count = 0; /** * The smallest atomic increment of the count within this slot. * @type {number} */ goog.stats.BasicStat.Slot_.prototype.min = Number.MAX_VALUE; /** * The largest atomic increment of the count within this slot. * @type {number} */ goog.stats.BasicStat.Slot_.prototype.max = Number.MIN_VALUE;
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview tmpnetwork.js contains some temporary networking functions * for browserchannel which will be moved at a later date. */ /** * Namespace for BrowserChannel */ goog.provide('goog.net.tmpnetwork'); goog.require('goog.Uri'); goog.require('goog.net.ChannelDebug'); /** * Default timeout to allow for google.com pings. * @type {number} */ goog.net.tmpnetwork.GOOGLECOM_TIMEOUT = 10000; /** * Pings the network to check if an error is a server error or user's network * error. * * @param {Function} callback The function to call back with results. * @param {goog.Uri?=} opt_imageUri The URI of an image to use for the network * test. You *must* provide an image URI; the default behavior is provided * for compatibility with existing code, but the search team does not want * people using images served off of google.com for this purpose. The * default will go away when all usages have been changed. */ goog.net.tmpnetwork.testGoogleCom = function(callback, opt_imageUri) { // We need to add a 'rand' to make sure the response is not fulfilled // by browser cache. var uri = opt_imageUri; if (!uri) { uri = new goog.Uri('//www.google.com/images/cleardot.gif'); uri.makeUnique(); } goog.net.tmpnetwork.testLoadImage(uri.toString(), goog.net.tmpnetwork.GOOGLECOM_TIMEOUT, callback); }; /** * Test loading the given image, retrying if necessary. * @param {string} url URL to the iamge. * @param {number} timeout Milliseconds before giving up. * @param {Function} callback Function to call with results. * @param {number} retries The number of times to retry. * @param {number=} opt_pauseBetweenRetriesMS Optional number of milliseconds * between retries - defaults to 0. */ goog.net.tmpnetwork.testLoadImageWithRetries = function(url, timeout, callback, retries, opt_pauseBetweenRetriesMS) { var channelDebug = new goog.net.ChannelDebug(); channelDebug.debug('TestLoadImageWithRetries: ' + opt_pauseBetweenRetriesMS); if (retries == 0) { // no more retries, give up callback(false); return; } var pauseBetweenRetries = opt_pauseBetweenRetriesMS || 0; retries--; goog.net.tmpnetwork.testLoadImage(url, timeout, function(succeeded) { if (succeeded) { callback(true); } else { // try again goog.global.setTimeout(function() { goog.net.tmpnetwork.testLoadImageWithRetries(url, timeout, callback, retries, pauseBetweenRetries); }, pauseBetweenRetries); } }); }; /** * Test loading the given image. * @param {string} url URL to the iamge. * @param {number} timeout Milliseconds before giving up. * @param {Function} callback Function to call with results. */ goog.net.tmpnetwork.testLoadImage = function(url, timeout, callback) { var channelDebug = new goog.net.ChannelDebug(); channelDebug.debug('TestLoadImage: loading ' + url); var img = new Image(); img.onload = function() { try { channelDebug.debug('TestLoadImage: loaded'); goog.net.tmpnetwork.clearImageCallbacks_(img); callback(true); } catch (e) { channelDebug.dumpException(e); } }; img.onerror = function() { try { channelDebug.debug('TestLoadImage: error'); goog.net.tmpnetwork.clearImageCallbacks_(img); callback(false); } catch (e) { channelDebug.dumpException(e); } }; img.onabort = function() { try { channelDebug.debug('TestLoadImage: abort'); goog.net.tmpnetwork.clearImageCallbacks_(img); callback(false); } catch (e) { channelDebug.dumpException(e); } }; img.ontimeout = function() { try { channelDebug.debug('TestLoadImage: timeout'); goog.net.tmpnetwork.clearImageCallbacks_(img); callback(false); } catch (e) { channelDebug.dumpException(e); } }; goog.global.setTimeout(function() { if (img.ontimeout) { img.ontimeout(); } }, timeout); img.src = url; }; /** * Clear handlers to avoid memory leaks. * @param {Image} img The image to clear handlers from. * @private */ goog.net.tmpnetwork.clearImageCallbacks_ = function(img) { // NOTE(user): Nullified individually to avoid compiler warnings // (BUG 658126) img.onload = null; img.onerror = null; img.onabort = null; img.ontimeout = null; };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Class for managing requests via iFrames. Supports a number of * methods of transfer. * * Gets and Posts can be performed and the resultant page read in as text, * JSON, or from the HTML DOM. * * Using an iframe causes the throbber to spin, this is good for providing * feedback to the user that an action has occurred. * * Requests do not affect the history stack, see goog.History if you require * this behavior. * * The responseText and responseJson methods assume the response is plain, * text. You can access the Iframe's DOM through responseXml if you need * access to the raw HTML. * * Tested: * + FF2.0 (Win Linux) * + IE6, IE7 * + Opera 9.1, * + Chrome * - Opera 8.5 fails because of no textContent and buggy innerText support * * NOTE: Safari doesn't fire the onload handler when loading plain text files * * This has been tested with Drip in IE to ensure memory usage is as constant * as possible. When making making thousands of requests, memory usage stays * constant for a while but then starts increasing (<500k for 2000 * requests) -- this hasn't yet been tracked down yet, though it is cleared up * after a refresh. * * * BACKGROUND FILE UPLOAD: * By posting an arbitrary form through an IframeIo object, it is possible to * implement background file uploads. Here's how to do it: * * - Create a form: * <pre> * &lt;form id="form" enctype="multipart/form-data" method="POST"&gt; * &lt;input name="userfile" type="file" /&gt; * &lt;/form&gt; * </pre> * * - Have the user click the file input * - Create an IframeIo instance * <pre> * var io = new goog.net.IframeIo; * goog.events.listen(io, goog.net.EventType.COMPLETE, * function() { alert('Sent'); }); * io.sendFromForm(document.getElementById('form')); * </pre> * * * INCREMENTAL LOADING: * Gmail sends down multiple script blocks which get executed as they are * received by the client. This allows incremental rendering of the thread * list and conversations. * * This requires collaboration with the server that is sending the requested * page back. To set incremental loading up, you should: * * A) In the application code there should be an externed reference to * <code>handleIncrementalData()</code>. e.g. * goog.exportSymbol('GG_iframeFn', goog.net.IframeIo.handleIncrementalData); * * B) The response page should them call this method directly, an example * response would look something like this: * <pre> * &lt;html&gt; * &lt;head&gt; * &lt;meta content="text/html;charset=UTF-8" http-equiv="content-type"&gt; * &lt;/head&gt; * &lt;body&gt; * &lt;script&gt; * D = top.P ? function(d) { top.GG_iframeFn(window, d) } : function() {}; * &lt;/script&gt; * * &lt;script&gt;D([1, 2, 3, 4, 5]);&lt;/script&gt; * &lt;script&gt;D([6, 7, 8, 9, 10]);&lt;/script&gt; * &lt;script&gt;D([11, 12, 13, 14, 15]);&lt;/script&gt; * &lt;/body&gt; * &lt;/html&gt; * </pre> * * Your application should then listen, on the IframeIo instance, to the event * goog.net.EventType.INCREMENTAL_DATA. The event object contains a * 'data' member which is the content from the D() calls above. * * NOTE: There can be problems if you save a reference to the data object in IE. * If you save an array, and the iframe is dispose, then the array looses its * prototype and thus array methods like .join(). You can get around this by * creating arrays using the parent window's Array constructor, or you can * clone the array. * * * EVENT MODEL: * The various send methods work asynchronously. You can be notified about * the current status of the request (completed, success or error) by * listening for events on the IframeIo object itself. The following events * will be sent: * - goog.net.EventType.COMPLETE: when the request is completed * (either sucessfully or unsuccessfully). You can find out about the result * using the isSuccess() and getLastError * methods. * - goog.net.EventType.SUCCESS</code>: when the request was completed * successfully * - goog.net.EventType.ERROR: when the request failed * - goog.net.EventType.ABORT: when the request has been aborted * * Example: * <pre> * var io = new goog.net.IframeIo(); * goog.events.listen(io, goog.net.EventType.COMPLETE, * function() { alert('request complete'); }); * io.sendFromForm(...); * </pre> * */ goog.provide('goog.net.IframeIo'); goog.provide('goog.net.IframeIo.IncrementalDataEvent'); goog.require('goog.Timer'); goog.require('goog.Uri'); goog.require('goog.debug'); goog.require('goog.debug.Logger'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.events.Event'); goog.require('goog.events.EventTarget'); goog.require('goog.events.EventType'); goog.require('goog.json'); goog.require('goog.net.ErrorCode'); goog.require('goog.net.EventType'); goog.require('goog.reflect'); goog.require('goog.string'); goog.require('goog.structs'); goog.require('goog.userAgent'); /** * Class for managing requests via iFrames. * @constructor * @extends {goog.events.EventTarget} */ goog.net.IframeIo = function() { goog.base(this); /** * Name for this IframeIo and frame * @type {string} * @private */ this.name_ = goog.net.IframeIo.getNextName_(); /** * An array of iframes that have been finished with. We need them to be * disposed async, so we don't confuse the browser (see below). * @type {Array.<Element>} * @private */ this.iframesForDisposal_ = []; // Create a lookup from names to instances of IframeIo. This is a helper // function to be used in conjunction with goog.net.IframeIo.getInstanceByName // to find the IframeIo object associated with a particular iframe. Used in // incremental scripts etc. goog.net.IframeIo.instances_[this.name_] = this; }; goog.inherits(goog.net.IframeIo, goog.events.EventTarget); /** * Object used as a map to lookup instances of IframeIo objects by name. * @type {Object} * @private */ goog.net.IframeIo.instances_ = {}; /** * Prefix for frame names * @type {string} */ goog.net.IframeIo.FRAME_NAME_PREFIX = 'closure_frame'; /** * Suffix that is added to inner frames used for sending requests in non-IE * browsers * @type {string} */ goog.net.IframeIo.INNER_FRAME_SUFFIX = '_inner'; /** * The number of milliseconds after a request is completed to dispose the * iframes. This can be done lazily so we wait long enough for any processing * that occurred as a result of the response to finish. * @type {number} */ goog.net.IframeIo.IFRAME_DISPOSE_DELAY_MS = 2000; /** * Counter used when creating iframes * @type {number} * @private */ goog.net.IframeIo.counter_ = 0; /** * Form element to post to. * @type {HTMLFormElement} * @private */ goog.net.IframeIo.form_; /** * Static send that creates a short lived instance of IframeIo to send the * request. * @param {goog.Uri|string} uri Uri of the request, it is up the caller to * manage query string params. * @param {Function=} opt_callback Event handler for when request is completed. * @param {string=} opt_method Default is GET, POST uses a form to submit the * request. * @param {boolean=} opt_noCache Append a timestamp to the request to avoid * caching. * @param {Object|goog.structs.Map=} opt_data Map of key-value pairs that * will be posted to the server via the iframe's form. */ goog.net.IframeIo.send = function( uri, opt_callback, opt_method, opt_noCache, opt_data) { var io = new goog.net.IframeIo(); goog.events.listen(io, goog.net.EventType.READY, io.dispose, false, io); if (opt_callback) { goog.events.listen(io, goog.net.EventType.COMPLETE, opt_callback); } io.send(uri, opt_method, opt_noCache, opt_data); }; /** * Find an iframe by name (assumes the context is goog.global since that is * where IframeIo's iframes are kept). * @param {string} fname The name to find. * @return {HTMLIFrameElement} The iframe element with that name. */ goog.net.IframeIo.getIframeByName = function(fname) { return window.frames[fname]; }; /** * Find an instance of the IframeIo object by name. * @param {string} fname The name to find. * @return {goog.net.IframeIo} The instance of IframeIo. */ goog.net.IframeIo.getInstanceByName = function(fname) { return goog.net.IframeIo.instances_[fname]; }; /** * Handles incremental data and routes it to the correct iframeIo instance. * The HTML page requested by the IframeIo instance should contain script blocks * that call an externed reference to this method. * @param {Window} win The window object. * @param {Object} data The data object. */ goog.net.IframeIo.handleIncrementalData = function(win, data) { // If this is the inner-frame, then we need to use the parent instead. var iframeName = goog.string.endsWith(win.name, goog.net.IframeIo.INNER_FRAME_SUFFIX) ? win.parent.name : win.name; var iframeIoName = iframeName.substring(0, iframeName.lastIndexOf('_')); var iframeIo = goog.net.IframeIo.getInstanceByName(iframeIoName); if (iframeIo && iframeName == iframeIo.iframeName_) { iframeIo.handleIncrementalData_(data); } else { goog.debug.Logger.getLogger('goog.net.IframeIo').info( 'Incremental iframe data routed for unknown iframe'); } }; /** * @return {string} The next iframe name. * @private */ goog.net.IframeIo.getNextName_ = function() { return goog.net.IframeIo.FRAME_NAME_PREFIX + goog.net.IframeIo.counter_++; }; /** * Gets a static form, one for all instances of IframeIo since IE6 leaks form * nodes that are created/removed from the document. * @return {HTMLFormElement} The static form. * @private */ goog.net.IframeIo.getForm_ = function() { if (!goog.net.IframeIo.form_) { goog.net.IframeIo.form_ = /** @type {HTMLFormElement} */(goog.dom.createDom('form')); goog.net.IframeIo.form_.acceptCharset = 'utf-8'; // Hide the form and move it off screen var s = goog.net.IframeIo.form_.style; s.position = 'absolute'; s.visibility = 'hidden'; s.top = s.left = '-10px'; s.width = s.height = '10px'; s.overflow = 'hidden'; goog.dom.getDocument().body.appendChild(goog.net.IframeIo.form_); } return goog.net.IframeIo.form_; }; /** * Adds the key value pairs from a map like data structure to a form * @param {HTMLFormElement} form The form to add to. * @param {Object|goog.structs.Map|goog.Uri.QueryData} data The data to add. * @private */ goog.net.IframeIo.addFormInputs_ = function(form, data) { var helper = goog.dom.getDomHelper(form); goog.structs.forEach(data, function(value, key) { var inp = helper.createDom('input', {'type': 'hidden', 'name': key, 'value': value}); form.appendChild(inp); }); }; /** * Reference to a logger for the IframeIo objects * @type {goog.debug.Logger} * @private */ goog.net.IframeIo.prototype.logger_ = goog.debug.Logger.getLogger('goog.net.IframeIo'); /** * Reference to form element that gets reused for requests to the iframe. * @type {HTMLFormElement} * @private */ goog.net.IframeIo.prototype.form_ = null; /** * Reference to the iframe being used for the current request, or null if no * request is currently active. * @type {HTMLIFrameElement} * @private */ goog.net.IframeIo.prototype.iframe_ = null; /** * Name of the iframe being used for the current request, or null if no * request is currently active. * @type {?string} * @private */ goog.net.IframeIo.prototype.iframeName_ = null; /** * Next id so that iframe names are unique. * @type {number} * @private */ goog.net.IframeIo.prototype.nextIframeId_ = 0; /** * Whether the object is currently active with a request. * @type {boolean} * @private */ goog.net.IframeIo.prototype.active_ = false; /** * Whether the last request is complete. * @type {boolean} * @private */ goog.net.IframeIo.prototype.complete_ = false; /** * Whether the last request was a success. * @type {boolean} * @private */ goog.net.IframeIo.prototype.success_ = false; /** * The URI for the last request. * @type {goog.Uri} * @private */ goog.net.IframeIo.prototype.lastUri_ = null; /** * The text content of the last request. * @type {?string} * @private */ goog.net.IframeIo.prototype.lastContent_ = null; /** * Last error code * @type {goog.net.ErrorCode} * @private */ goog.net.IframeIo.prototype.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; /** * Number of milliseconds after which an incomplete request will be aborted and * a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout is set. * @type {number} * @private */ goog.net.IframeIo.prototype.timeoutInterval_ = 0; /** * Window timeout ID used to cancel the timeout event handler if the request * completes successfully. * @type {?number} * @private */ goog.net.IframeIo.prototype.timeoutId_ = null; /** * Window timeout ID used to detect when firefox silently fails. * @type {?number} * @private */ goog.net.IframeIo.prototype.firefoxSilentErrorTimeout_ = null; /** * Window timeout ID used by the timer that disposes the iframes. * @type {?number} * @private */ goog.net.IframeIo.prototype.iframeDisposalTimer_ = null; /** * This is used to ensure that we don't handle errors twice for the same error. * We can reach the {@link #handleError_} method twice in IE if the form is * submitted while IE is offline and the URL is not available. * @type {boolean} * @private */ goog.net.IframeIo.prototype.errorHandled_; /** * Whether to suppress the listeners that determine when the iframe loads. * @type {boolean} * @private */ goog.net.IframeIo.prototype.ignoreResponse_ = false; /** * Sends a request via an iframe. * * A HTML form is used and submitted to the iframe, this simplifies the * difference between GET and POST requests. The iframe needs to be created and * destroyed for each request otherwise the request will contribute to the * history stack. * * sendFromForm does some clever trickery (thanks jlim) in non-IE browsers to * stop a history entry being added for POST requests. * * @param {goog.Uri|string} uri Uri of the request. * @param {string=} opt_method Default is GET, POST uses a form to submit the * request. * @param {boolean=} opt_noCache Append a timestamp to the request to avoid * caching. * @param {Object|goog.structs.Map=} opt_data Map of key-value pairs. */ goog.net.IframeIo.prototype.send = function( uri, opt_method, opt_noCache, opt_data) { if (this.active_) { throw Error('[goog.net.IframeIo] Unable to send, already active.'); } var uriObj = new goog.Uri(uri); this.lastUri_ = uriObj; var method = opt_method ? opt_method.toUpperCase() : 'GET'; if (opt_noCache) { uriObj.makeUnique(); } this.logger_.info('Sending iframe request: ' + uriObj + ' [' + method + ']'); // Build a form for this request this.form_ = goog.net.IframeIo.getForm_(); if (method == 'GET') { // For GET requests, we assume that the caller didn't want the queryparams // already specified in the URI to be clobbered by the form, so we add the // params here. goog.net.IframeIo.addFormInputs_(this.form_, uriObj.getQueryData()); } if (opt_data) { // Create form fields for each of the data values goog.net.IframeIo.addFormInputs_(this.form_, opt_data); } // Set the URI that the form will be posted this.form_.action = uriObj.toString(); this.form_.method = method; this.sendFormInternal_(); }; /** * Sends the data stored in an existing form to the server. The HTTP method * should be specified on the form, the action can also be specified but can * be overridden by the optional URI param. * * This can be used in conjunction will a file-upload input to upload a file in * the background without affecting history. * * Example form: * <pre> * &lt;form action="/server/" enctype="multipart/form-data" method="POST"&gt; * &lt;input name="userfile" type="file"&gt; * &lt;/form&gt; * </pre> * * @param {HTMLFormElement} form Form element used to send the request to the * server. * @param {string=} opt_uri Uri to set for the destination of the request, by * default the uri will come from the form. * @param {boolean=} opt_noCache Append a timestamp to the request to avoid * caching. */ goog.net.IframeIo.prototype.sendFromForm = function(form, opt_uri, opt_noCache) { if (this.active_) { throw Error('[goog.net.IframeIo] Unable to send, already active.'); } var uri = new goog.Uri(opt_uri || form.action); if (opt_noCache) { uri.makeUnique(); } this.logger_.info('Sending iframe request from form: ' + uri); this.lastUri_ = uri; this.form_ = form; this.form_.action = uri.toString(); this.sendFormInternal_(); }; /** * Abort the current Iframe request * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use - * defaults to ABORT. */ goog.net.IframeIo.prototype.abort = function(opt_failureCode) { if (this.active_) { this.logger_.info('Request aborted'); goog.events.removeAll(this.getRequestIframe()); this.complete_ = false; this.active_ = false; this.success_ = false; this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT; this.dispatchEvent(goog.net.EventType.ABORT); this.makeReady_(); } }; /** @override */ goog.net.IframeIo.prototype.disposeInternal = function() { this.logger_.fine('Disposing iframeIo instance'); // If there is an active request, abort it if (this.active_) { this.logger_.fine('Aborting active request'); this.abort(); } // Call super-classes implementation (remove listeners) goog.net.IframeIo.superClass_.disposeInternal.call(this); // Add the current iframe to the list of iframes for disposal. if (this.iframe_) { this.scheduleIframeDisposal_(); } // Disposes of the form this.disposeForm_(); // Nullify anything that might cause problems and clear state delete this.errorChecker_; this.form_ = null; this.lastCustomError_ = this.lastContent_ = this.lastContentHtml_ = null; this.lastUri_ = null; this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; delete goog.net.IframeIo.instances_[this.name_]; }; /** * @return {boolean} True if transfer is complete. */ goog.net.IframeIo.prototype.isComplete = function() { return this.complete_; }; /** * @return {boolean} True if transfer was successful. */ goog.net.IframeIo.prototype.isSuccess = function() { return this.success_; }; /** * @return {boolean} True if a transfer is in progress. */ goog.net.IframeIo.prototype.isActive = function() { return this.active_; }; /** * Returns the last response text (i.e. the text content of the iframe). * Assumes plain text! * @return {?string} Result from the server. */ goog.net.IframeIo.prototype.getResponseText = function() { return this.lastContent_; }; /** * Returns the last response html (i.e. the innerHtml of the iframe). * @return {?string} Result from the server. */ goog.net.IframeIo.prototype.getResponseHtml = function() { return this.lastContentHtml_; }; /** * Parses the content as JSON. This is a safe parse and may throw an error * if the response is malformed. * Use goog.json.unsafeparse(this.getResponseText()) if you are sure of the * state of the returned content. * @return {Object} The parsed content. */ goog.net.IframeIo.prototype.getResponseJson = function() { return goog.json.parse(this.lastContent_); }; /** * Returns the document object from the last request. Not truely XML, but * used to mirror the XhrIo interface. * @return {HTMLDocument} The document object from the last request. */ goog.net.IframeIo.prototype.getResponseXml = function() { if (!this.iframe_) return null; return this.getContentDocument_(); }; /** * Get the uri of the last request. * @return {goog.Uri} Uri of last request. */ goog.net.IframeIo.prototype.getLastUri = function() { return this.lastUri_; }; /** * Gets the last error code. * @return {goog.net.ErrorCode} Last error code. */ goog.net.IframeIo.prototype.getLastErrorCode = function() { return this.lastErrorCode_; }; /** * Gets the last error message. * @return {string} Last error message. */ goog.net.IframeIo.prototype.getLastError = function() { return goog.net.ErrorCode.getDebugMessage(this.lastErrorCode_); }; /** * Gets the last custom error. * @return {Object} Last custom error. */ goog.net.IframeIo.prototype.getLastCustomError = function() { return this.lastCustomError_; }; /** * Sets the callback function used to check if a loaded IFrame is in an error * state. * @param {Function} fn Callback that expects a document object as it's single * argument. */ goog.net.IframeIo.prototype.setErrorChecker = function(fn) { this.errorChecker_ = fn; }; /** * Gets the callback function used to check if a loaded IFrame is in an error * state. * @return {Function} A callback that expects a document object as it's single * argument. */ goog.net.IframeIo.prototype.getErrorChecker = function() { return this.errorChecker_; }; /** * Returns the number of milliseconds after which an incomplete request will be * aborted, or 0 if no timeout is set. * @return {number} Timeout interval in milliseconds. */ goog.net.IframeIo.prototype.getTimeoutInterval = function() { return this.timeoutInterval_; }; /** * Sets the number of milliseconds after which an incomplete request will be * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no * timeout is set. * @param {number} ms Timeout interval in milliseconds; 0 means none. */ goog.net.IframeIo.prototype.setTimeoutInterval = function(ms) { // TODO (pupius) - never used - doesn't look like timeouts were implemented this.timeoutInterval_ = Math.max(0, ms); }; /** * @return {boolean} Whether the server response is being ignored. */ goog.net.IframeIo.prototype.isIgnoringResponse = function() { return this.ignoreResponse_; }; /** * Sets whether to ignore the response from the server by not adding any event * handlers to fire when the iframe loads. This is necessary when using IframeIo * to submit to a server on another domain, to avoid same-origin violations when * trying to access the response. If this is set to true, the IframeIo instance * will be a single-use instance that is only usable for one request. It will * only clean up its resources (iframes and forms) when it is disposed. * @param {boolean} ignore Whether to ignore the server response. */ goog.net.IframeIo.prototype.setIgnoreResponse = function(ignore) { this.ignoreResponse_ = ignore; }; /** * Submits the internal form to the iframe. * @private */ goog.net.IframeIo.prototype.sendFormInternal_ = function() { this.active_ = true; this.complete_ = false; this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; // Make Iframe this.createIframe_(); if (goog.userAgent.IE) { // In IE we simply create the frame, wait until it is ready, then post the // form to the iframe and wait for the readystate to change to 'complete' // Set the target to the iframe's name this.form_.target = this.iframeName_ || ''; this.appendIframe_(); if (!this.ignoreResponse_) { goog.events.listen(this.iframe_, goog.events.EventType.READYSTATECHANGE, this.onIeReadyStateChange_, false, this); } /** @preserveTry */ try { this.errorHandled_ = false; this.form_.submit(); } catch (e) { // If submit threw an exception then it probably means the page that the // code is running on the local file system and the form's action was // pointing to a file that doesn't exist, causing the browser to fire an // exception. IE also throws an exception when it is working offline and // the URL is not available. if (!this.ignoreResponse_) { goog.events.unlisten( this.iframe_, goog.events.EventType.READYSTATECHANGE, this.onIeReadyStateChange_, false, this); } this.handleError_(goog.net.ErrorCode.ACCESS_DENIED); } } else { // For all other browsers we do some trickery to ensure that there is no // entry on the history stack. Thanks go to jlim for the prototype for this this.logger_.fine('Setting up iframes and cloning form'); this.appendIframe_(); var innerFrameName = this.iframeName_ + goog.net.IframeIo.INNER_FRAME_SUFFIX; // Open and document.write another iframe into the iframe var doc = goog.dom.getFrameContentDocument(this.iframe_); var html = '<body><iframe id=' + innerFrameName + ' name=' + innerFrameName + '></iframe>'; if (document.baseURI) { // On Safari 4 and 5 the new iframe doesn't inherit the current baseURI. html = '<head><base href="' + goog.string.htmlEscape(document.baseURI) + '"></head>' + html; } if (goog.userAgent.OPERA) { // Opera adds a history entry when document.write is used. // Change the innerHTML of the page instead. doc.documentElement.innerHTML = html; } else { doc.write(html); } // Listen for the iframe's load if (!this.ignoreResponse_) { goog.events.listen(doc.getElementById(innerFrameName), goog.events.EventType.LOAD, this.onIframeLoaded_, false, this); } // Fix text areas, since importNode won't clone changes to the value var textareas = this.form_.getElementsByTagName('textarea'); for (var i = 0, n = textareas.length; i < n; i++) { // The childnodes represent the initial child nodes for the text area // appending a text node essentially resets the initial value ready for // it to be clones - while maintaining HTML escaping. var value = textareas[i].value; if (goog.dom.getRawTextContent(textareas[i]) != value) { goog.dom.setTextContent(textareas[i], value); textareas[i].value = value; } } // Append a cloned form to the iframe var clone = doc.importNode(this.form_, true); clone.target = innerFrameName; // Work around crbug.com/66987 clone.action = this.form_.action; doc.body.appendChild(clone); // Fix select boxes, importNode won't override the default value var selects = this.form_.getElementsByTagName('select'); var clones = clone.getElementsByTagName('select'); for (var i = 0, n = selects.length; i < n; i++) { var selectsOptions = selects[i].getElementsByTagName('option'); var clonesOptions = clones[i].getElementsByTagName('option'); for (var j = 0, m = selectsOptions.length; j < m; j++) { clonesOptions[j].selected = selectsOptions[j].selected; } } // Some versions of Firefox (1.5 - 1.5.07?) fail to clone the value // attribute for <input type="file"> nodes, which results in an empty // upload if the clone is submitted. Check, and if the clone failed, submit // using the original form instead. var inputs = this.form_.getElementsByTagName('input'); var inputClones = clone.getElementsByTagName('input'); for (var i = 0, n = inputs.length; i < n; i++) { if (inputs[i].type == 'file') { if (inputs[i].value != inputClones[i].value) { this.logger_.fine('File input value not cloned properly. Will ' + 'submit using original form.'); this.form_.target = innerFrameName; clone = this.form_; break; } } } this.logger_.fine('Submitting form'); /** @preserveTry */ try { this.errorHandled_ = false; clone.submit(); doc.close(); if (goog.userAgent.GECKO) { // This tests if firefox silently fails, this can happen, for example, // when the server resets the connection because of a large file upload this.firefoxSilentErrorTimeout_ = goog.Timer.callOnce(this.testForFirefoxSilentError_, 250, this); } } catch (e) { // If submit threw an exception then it probably means the page that the // code is running on the local file system and the form's action was // pointing to a file that doesn't exist, causing the browser to fire an // exception. this.logger_.severe( 'Error when submitting form: ' + goog.debug.exposeException(e)); if (!this.ignoreResponse_) { goog.events.unlisten(doc.getElementById(innerFrameName), goog.events.EventType.LOAD, this.onIframeLoaded_, false, this); } doc.close(); this.handleError_(goog.net.ErrorCode.FILE_NOT_FOUND); } } }; /** * Handles the load event of the iframe for IE, determines if the request was * successful or not, handles clean up and dispatching of appropriate events. * @param {goog.events.BrowserEvent} e The browser event. * @private */ goog.net.IframeIo.prototype.onIeReadyStateChange_ = function(e) { if (this.iframe_.readyState == 'complete') { goog.events.unlisten(this.iframe_, goog.events.EventType.READYSTATECHANGE, this.onIeReadyStateChange_, false, this); var doc; /** @preserveTry */ try { doc = goog.dom.getFrameContentDocument(this.iframe_); // IE serves about:blank when it cannot load the resource while offline. if (goog.userAgent.IE && doc.location == 'about:blank' && !navigator.onLine) { this.handleError_(goog.net.ErrorCode.OFFLINE); return; } } catch (ex) { this.handleError_(goog.net.ErrorCode.ACCESS_DENIED); return; } this.handleLoad_(/** @type {HTMLDocument} */(doc)); } }; /** * Handles the load event of the iframe for non-IE browsers. * @param {goog.events.BrowserEvent} e The browser event. * @private */ goog.net.IframeIo.prototype.onIframeLoaded_ = function(e) { // In Opera, the default "about:blank" page of iframes fires an onload // event that we'd like to ignore. if (goog.userAgent.OPERA && this.getContentDocument_().location == 'about:blank') { return; } goog.events.unlisten(this.getRequestIframe(), goog.events.EventType.LOAD, this.onIframeLoaded_, false, this); this.handleLoad_(this.getContentDocument_()); }; /** * Handles generic post-load * @param {HTMLDocument} contentDocument The frame's document. * @private */ goog.net.IframeIo.prototype.handleLoad_ = function(contentDocument) { this.logger_.fine('Iframe loaded'); this.complete_ = true; this.active_ = false; var errorCode; // Try to get the innerHTML. If this fails then it can be an access denied // error or the document may just not have a body, typical case is if there // is an IE's default 404. /** @preserveTry */ try { var body = contentDocument.body; this.lastContent_ = body.textContent || body.innerText; this.lastContentHtml_ = body.innerHTML; } catch (ex) { errorCode = goog.net.ErrorCode.ACCESS_DENIED; } // Use a callback function, defined by the application, to analyse the // contentDocument and determine if it is an error page. Applications // may send down markers in the document, define JS vars, or some other test. var customError; if (!errorCode && typeof this.errorChecker_ == 'function') { customError = this.errorChecker_(contentDocument); if (customError) { errorCode = goog.net.ErrorCode.CUSTOM_ERROR; } } this.logger_.finer('Last content: ' + this.lastContent_); this.logger_.finer('Last uri: ' + this.lastUri_); if (errorCode) { this.logger_.fine('Load event occurred but failed'); this.handleError_(errorCode, customError); } else { this.logger_.fine('Load succeeded'); this.success_ = true; this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.SUCCESS); this.makeReady_(); } }; /** * Handles errors. * @param {goog.net.ErrorCode} errorCode Error code. * @param {Object=} opt_customError If error is CUSTOM_ERROR, this is the * client-provided custom error. * @private */ goog.net.IframeIo.prototype.handleError_ = function(errorCode, opt_customError) { if (!this.errorHandled_) { this.success_ = false; this.active_ = false; this.complete_ = true; this.lastErrorCode_ = errorCode; if (errorCode == goog.net.ErrorCode.CUSTOM_ERROR) { this.lastCustomError_ = opt_customError; } this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.ERROR); this.makeReady_(); this.errorHandled_ = true; } }; /** * Dispatches an event indicating that the IframeIo instance has received a data * packet via incremental loading. The event object has a 'data' member. * @param {Object} data Data. * @private */ goog.net.IframeIo.prototype.handleIncrementalData_ = function(data) { this.dispatchEvent(new goog.net.IframeIo.IncrementalDataEvent(data)); }; /** * Finalizes the request, schedules the iframe for disposal, and maybe disposes * the form. * @private */ goog.net.IframeIo.prototype.makeReady_ = function() { this.logger_.info('Ready for new requests'); var iframe = this.iframe_; this.scheduleIframeDisposal_(); this.disposeForm_(); this.dispatchEvent(goog.net.EventType.READY); }; /** * Creates an iframe to be used with a request. We use a new iframe for each * request so that requests don't create history entries. * @private */ goog.net.IframeIo.prototype.createIframe_ = function() { this.logger_.fine('Creating iframe'); this.iframeName_ = this.name_ + '_' + (this.nextIframeId_++).toString(36); var iframeAttributes = {'name': this.iframeName_, 'id': this.iframeName_}; // Setting the source to javascript:"" is a fix to remove IE6 mixed content // warnings when being used in an https page. if (goog.userAgent.IE && goog.userAgent.VERSION < 7) { iframeAttributes.src = 'javascript:""'; } this.iframe_ = /** @type {HTMLIFrameElement} */( goog.dom.getDomHelper(this.form_).createDom('iframe', iframeAttributes)); var s = this.iframe_.style; s.visibility = 'hidden'; s.width = s.height = '10px'; // Chrome sometimes shows scrollbars when visibility is hidden, but not when // display is none. s.display = 'none'; // There are reports that safari 2.0.3 has a bug where absolutely positioned // iframes can't have their src set. if (!goog.userAgent.WEBKIT) { s.position = 'absolute'; s.top = s.left = '-10px'; } else { s.marginTop = s.marginLeft = '-10px'; } }; /** * Appends the Iframe to the document body. * @private */ goog.net.IframeIo.prototype.appendIframe_ = function() { goog.dom.getDomHelper(this.form_).getDocument().body.appendChild( this.iframe_); }; /** * Schedules an iframe for disposal, async. We can't remove the iframes in the * same execution context as the response, otherwise some versions of Firefox * will not detect that the response has correctly finished and the loading bar * will stay active forever. * @private */ goog.net.IframeIo.prototype.scheduleIframeDisposal_ = function() { var iframe = this.iframe_; // There shouldn't be a case where the iframe is null and we get to this // stage, but the error reports in http://b/909448 indicate it is possible. if (iframe) { // NOTE(user): Stops Internet Explorer leaking the iframe object. This // shouldn't be needed, since the events have all been removed, which // should in theory clean up references. Oh well... iframe.onreadystatechange = null; iframe.onload = null; iframe.onerror = null; this.iframesForDisposal_.push(iframe); } if (this.iframeDisposalTimer_) { goog.Timer.clear(this.iframeDisposalTimer_); this.iframeDisposalTimer_ = null; } if (goog.userAgent.GECKO || goog.userAgent.OPERA) { // For FF and Opera, we must dispose the iframe async, // but it doesn't need to be done as soon as possible. // We therefore schedule it for 2s out, so as not to // affect any other actions that may have been triggered by the request. this.iframeDisposalTimer_ = goog.Timer.callOnce( this.disposeIframes_, goog.net.IframeIo.IFRAME_DISPOSE_DELAY_MS, this); } else { // For non-Gecko browsers we dispose straight away. this.disposeIframes_(); } // Nullify reference this.iframe_ = null; this.iframeName_ = null; }; /** * Disposes any iframes. * @private */ goog.net.IframeIo.prototype.disposeIframes_ = function() { if (this.iframeDisposalTimer_) { // Clear the timer goog.Timer.clear(this.iframeDisposalTimer_); this.iframeDisposalTimer_ = null; } while (this.iframesForDisposal_.length != 0) { var iframe = this.iframesForDisposal_.pop(); this.logger_.info('Disposing iframe'); goog.dom.removeNode(iframe); } }; /** * Disposes of the Form. Since IE6 leaks form nodes, this just cleans up the * DOM and nullifies the instances reference so the form can be used for another * request. * @private */ goog.net.IframeIo.prototype.disposeForm_ = function() { if (this.form_ && this.form_ == goog.net.IframeIo.form_) { goog.dom.removeChildren(this.form_); } this.form_ = null; }; /** * @return {HTMLDocument} The appropriate content document. * @private */ goog.net.IframeIo.prototype.getContentDocument_ = function() { if (this.iframe_) { return /** @type {HTMLDocument} */(goog.dom.getFrameContentDocument( this.getRequestIframe())); } return null; }; /** * @return {HTMLIFrameElement} The appropriate iframe to use for requests * (created in sendForm_). */ goog.net.IframeIo.prototype.getRequestIframe = function() { if (this.iframe_) { return /** @type {HTMLIFrameElement} */(goog.userAgent.IE ? this.iframe_ : goog.dom.getFrameContentDocument(this.iframe_).getElementById( this.iframeName_ + goog.net.IframeIo.INNER_FRAME_SUFFIX)); } return null; }; /** * Tests for a silent failure by firefox that can occur when the connection is * reset by the server or is made to an illegal URL. * @private */ goog.net.IframeIo.prototype.testForFirefoxSilentError_ = function() { if (this.active_) { var doc = this.getContentDocument_(); // This is a hack to test of the document has loaded with a page that // we can't access, such as a network error, that won't report onload // or onerror events. if (doc && !goog.reflect.canAccessProperty(doc, 'documentUri')) { if (!this.ignoreResponse_) { goog.events.unlisten(this.getRequestIframe(), goog.events.EventType.LOAD, this.onIframeLoaded_, false, this); } if (navigator.onLine) { this.logger_.warning('Silent Firefox error detected'); this.handleError_(goog.net.ErrorCode.FF_SILENT_ERROR); } else { this.logger_.warning('Firefox is offline so report offline error ' + 'instead of silent error'); this.handleError_(goog.net.ErrorCode.OFFLINE); } return; } this.firefoxSilentErrorTimeout_ = goog.Timer.callOnce(this.testForFirefoxSilentError_, 250, this); } }; /** * Class for representing incremental data events. * @param {Object} data The data associated with the event. * @extends {goog.events.Event} * @constructor */ goog.net.IframeIo.IncrementalDataEvent = function(data) { goog.events.Event.call(this, goog.net.EventType.INCREMENTAL_DATA); /** * The data associated with the event. * @type {Object} */ this.data = data; }; goog.inherits(goog.net.IframeIo.IncrementalDataEvent, goog.events.Event);
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Loads a list of URIs in bulk. All requests must be a success * in order for the load to be considered a success. * */ goog.provide('goog.net.BulkLoader'); goog.require('goog.debug.Logger'); goog.require('goog.events.Event'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventTarget'); goog.require('goog.net.BulkLoaderHelper'); goog.require('goog.net.EventType'); goog.require('goog.net.XhrIo'); /** * Class used to load multiple URIs. * @param {Array.<string|goog.Uri>} uris The URIs to load. * @constructor * @extends {goog.events.EventTarget} */ goog.net.BulkLoader = function(uris) { goog.events.EventTarget.call(this); /** * The bulk loader helper. * @type {goog.net.BulkLoaderHelper} * @private */ this.helper_ = new goog.net.BulkLoaderHelper(uris); /** * The handler for managing events. * @type {goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); }; goog.inherits(goog.net.BulkLoader, goog.events.EventTarget); /** * A logger. * @type {goog.debug.Logger} * @private */ goog.net.BulkLoader.prototype.logger_ = goog.debug.Logger.getLogger('goog.net.BulkLoader'); /** * Gets the response texts, in order. * @return {Array.<string>} The response texts. */ goog.net.BulkLoader.prototype.getResponseTexts = function() { return this.helper_.getResponseTexts(); }; /** * Gets the request Uris. * @return {Array.<string>} The request URIs, in order. */ goog.net.BulkLoader.prototype.getRequestUris = function() { return this.helper_.getUris(); }; /** * Starts the process of loading the URIs. */ goog.net.BulkLoader.prototype.load = function() { var eventHandler = this.eventHandler_; var uris = this.helper_.getUris(); this.logger_.info('Starting load of code with ' + uris.length + ' uris.'); for (var i = 0; i < uris.length; i++) { var xhrIo = new goog.net.XhrIo(); eventHandler.listen(xhrIo, goog.net.EventType.COMPLETE, goog.bind(this.handleEvent_, this, i)); xhrIo.send(uris[i]); } }; /** * Handles all events fired by the XhrManager. * @param {number} id The id of the request. * @param {goog.events.Event} e The event. * @private */ goog.net.BulkLoader.prototype.handleEvent_ = function(id, e) { this.logger_.info('Received event "' + e.type + '" for id ' + id + ' with uri ' + this.helper_.getUri(id)); var xhrIo = /** @type {goog.net.XhrIo} */ (e.target); if (xhrIo.isSuccess()) { this.handleSuccess_(id, xhrIo); } else { this.handleError_(id, xhrIo); } }; /** * Handles when a request is successful (i.e., completed and response received). * Stores thhe responseText and checks if loading is complete. * @param {number} id The id of the request. * @param {goog.net.XhrIo} xhrIo The XhrIo objects that was used. * @private */ goog.net.BulkLoader.prototype.handleSuccess_ = function( id, xhrIo) { // Save the response text. this.helper_.setResponseText(id, xhrIo.getResponseText()); // Check if all response texts have been received. if (this.helper_.isLoadComplete()) { this.finishLoad_(); } xhrIo.dispose(); }; /** * Handles when a request has ended in error (i.e., all retries completed and * none were successful). Cancels loading of the URI's. * @param {number|string} id The id of the request. * @param {goog.net.XhrIo} xhrIo The XhrIo objects that was used. * @private */ goog.net.BulkLoader.prototype.handleError_ = function( id, xhrIo) { // TODO(user): Abort all pending requests. // Dispatch the ERROR event. this.dispatchEvent(goog.net.EventType.ERROR); xhrIo.dispose(); }; /** * Finishes the load of the URI's. Dispatches the SUCCESS event. * @private */ goog.net.BulkLoader.prototype.finishLoad_ = function() { this.logger_.info('All uris loaded.'); // Dispatch the SUCCESS event. this.dispatchEvent(goog.net.EventType.SUCCESS); }; /** @override */ goog.net.BulkLoader.prototype.disposeInternal = function() { goog.net.BulkLoader.superClass_.disposeInternal.call(this); this.eventHandler_.dispose(); this.eventHandler_ = null; this.helper_.dispose(); this.helper_ = null; };
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Interface for a factory for creating XMLHttpRequest objects * and metadata about them. * @author dbk@google.com (David Barrett-Kahn) */ goog.provide('goog.net.XmlHttpFactory'); /** * Abstract base class for an XmlHttpRequest factory. * @constructor */ goog.net.XmlHttpFactory = function() { }; /** * Cache of options - we only actually call internalGetOptions once. * @type {Object} * @private */ goog.net.XmlHttpFactory.prototype.cachedOptions_ = null; /** * @return {!(XMLHttpRequest|GearsHttpRequest)} A new XMLHttpRequest instance. */ goog.net.XmlHttpFactory.prototype.createInstance = goog.abstractMethod; /** * @return {Object} Options describing how xhr objects obtained from this * factory should be used. */ goog.net.XmlHttpFactory.prototype.getOptions = function() { return this.cachedOptions_ || (this.cachedOptions_ = this.internalGetOptions()); }; /** * Override this method in subclasses to preserve the caching offered by * getOptions(). * @return {Object} Options describing how xhr objects obtained from this * factory should be used. * @protected */ goog.net.XmlHttpFactory.prototype.internalGetOptions = goog.abstractMethod;
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Definition of the ChannelRequest class. The ChannelRequest * object encapsulates the logic for making a single request, either for the * forward channel, back channel, or test channel, to the server. It contains * the logic for the three types of transports we use in the BrowserChannel: * XMLHTTP, Trident ActiveX (ie only), and Image request. It provides timeout * detection. This class is part of the BrowserChannel implementation and is not * for use by normal application code. * */ goog.provide('goog.net.ChannelRequest'); goog.provide('goog.net.ChannelRequest.Error'); goog.require('goog.Timer'); goog.require('goog.async.Throttle'); goog.require('goog.events'); goog.require('goog.events.EventHandler'); goog.require('goog.net.EventType'); goog.require('goog.net.XmlHttp.ReadyState'); goog.require('goog.object'); goog.require('goog.userAgent'); /** * Creates a ChannelRequest object which encapsulates a request to the server. * A new ChannelRequest is created for each request to the server. * * @param {goog.net.BrowserChannel|goog.net.BrowserTestChannel} channel * The BrowserChannel that owns this request. * @param {goog.net.ChannelDebug} channelDebug A ChannelDebug to use for * logging. * @param {string=} opt_sessionId The session id for the channel. * @param {string|number=} opt_requestId The request id for this request. * @param {number=} opt_retryId The retry id for this request. * @constructor */ goog.net.ChannelRequest = function(channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) { /** * The BrowserChannel object that owns the request. * @type {goog.net.BrowserChannel|goog.net.BrowserTestChannel} * @private */ this.channel_ = channel; /** * The channel debug to use for logging * @type {goog.net.ChannelDebug} * @private */ this.channelDebug_ = channelDebug; /** * The Session ID for the channel. * @type {string|undefined} * @private */ this.sid_ = opt_sessionId; /** * The RID (request ID) for the request. * @type {string|number|undefined} * @private */ this.rid_ = opt_requestId; /** * The attempt number of the current request. * @type {number} * @private */ this.retryId_ = opt_retryId || 1; /** * The timeout in ms before failing the request. * @type {number} * @private */ this.timeout_ = goog.net.ChannelRequest.TIMEOUT_MS; /** * An object to keep track of the channel request event listeners. * @type {!goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); /** * A timer for polling responseText in browsers that don't fire * onreadystatechange during incremental loading of responseText. * @type {goog.Timer} * @private */ this.pollingTimer_ = new goog.Timer(); this.pollingTimer_.setInterval(goog.net.ChannelRequest.POLLING_INTERVAL_MS); }; /** * Extra HTTP headers to add to all the requests sent to the server. * @type {Object} * @private */ goog.net.ChannelRequest.prototype.extraHeaders_ = null; /** * Whether the request was successful. This is only set to true after the * request successfuly completes. * @type {boolean} * @private */ goog.net.ChannelRequest.prototype.successful_ = false; /** * The TimerID of the timer used to detect if the request has timed-out. * @type {?number} * @private */ goog.net.ChannelRequest.prototype.watchDogTimerId_ = null; /** * The time in the future when the request will timeout. * @type {?number} * @private */ goog.net.ChannelRequest.prototype.watchDogTimeoutTime_ = null; /** * The time the request started. * @type {?number} * @private */ goog.net.ChannelRequest.prototype.requestStartTime_ = null; /** * The type of request (XMLHTTP, IMG, Trident) * @type {?number} * @private */ goog.net.ChannelRequest.prototype.type_ = null; /** * The base Uri for the request. The includes all the parameters except the * one that indicates the retry number. * @type {goog.Uri?} * @private */ goog.net.ChannelRequest.prototype.baseUri_ = null; /** * The request Uri that was actually used for the most recent request attempt. * @type {goog.Uri?} * @private */ goog.net.ChannelRequest.prototype.requestUri_ = null; /** * The post data, if the request is a post. * @type {?string} * @private */ goog.net.ChannelRequest.prototype.postData_ = null; /** * The XhrLte request if the request is using XMLHTTP * @type {goog.net.XhrIo} * @private */ goog.net.ChannelRequest.prototype.xmlHttp_ = null; /** * The position of where the next unprocessed chunk starts in the response * text. * @type {number} * @private */ goog.net.ChannelRequest.prototype.xmlHttpChunkStart_ = 0; /** * The Trident instance if the request is using Trident. * @type {ActiveXObject} * @private */ goog.net.ChannelRequest.prototype.trident_ = null; /** * The verb (Get or Post) for the request. * @type {?string} * @private */ goog.net.ChannelRequest.prototype.verb_ = null; /** * The last error if the request failed. * @type {?goog.net.ChannelRequest.Error} * @private */ goog.net.ChannelRequest.prototype.lastError_ = null; /** * The last status code received. * @type {number} * @private */ goog.net.ChannelRequest.prototype.lastStatusCode_ = -1; /** * Whether to send the Connection:close header as part of the request. * @type {boolean} * @private */ goog.net.ChannelRequest.prototype.sendClose_ = true; /** * Whether the request has been cancelled due to a call to cancel. * @type {boolean} * @private */ goog.net.ChannelRequest.prototype.cancelled_ = false; /** * A throttle time in ms for readystatechange events for the backchannel. * Useful for throttling when ready state is INTERACTIVE (partial data). * If set to zero no throttle is used. * * @see goog.net.BrowserChannel.prototype.readyStateChangeThrottleMs_ * * @type {number} * @private */ goog.net.ChannelRequest.prototype.readyStateChangeThrottleMs_ = 0; /** * The throttle for readystatechange events for the current request, or null * if there is none. * @type {goog.async.Throttle} * @private */ goog.net.ChannelRequest.prototype.readyStateChangeThrottle_ = null; /** * Default timeout in MS for a request. The server must return data within this * time limit for the request to not timeout. * @type {number} */ goog.net.ChannelRequest.TIMEOUT_MS = 45 * 1000; /** * How often to poll (in MS) for changes to responseText in browsers that don't * fire onreadystatechange during incremental loading of responseText. * @type {number} */ goog.net.ChannelRequest.POLLING_INTERVAL_MS = 250; /** * Minimum version of Safari that receives a non-null responseText in ready * state interactive. * @type {string} * @private */ goog.net.ChannelRequest.MIN_WEBKIT_FOR_INTERACTIVE_ = '420+'; /** * Enum for channel requests type * @enum {number} * @private */ goog.net.ChannelRequest.Type_ = { /** * XMLHTTP requests. */ XML_HTTP: 1, /** * IMG requests. */ IMG: 2, /** * Requests that use the MSHTML ActiveX control. */ TRIDENT: 3 }; /** * Enum type for identifying a ChannelRequest error. * @enum {number} */ goog.net.ChannelRequest.Error = { /** * Errors due to a non-200 status code. */ STATUS: 0, /** * Errors due to no data being returned. */ NO_DATA: 1, /** * Errors due to a timeout. */ TIMEOUT: 2, /** * Errors due to the server returning an unknown. */ UNKNOWN_SESSION_ID: 3, /** * Errors due to bad data being received. */ BAD_DATA: 4, /** * Errors due to the handler throwing an exception. */ HANDLER_EXCEPTION: 5, /** * The browser declared itself offline during the request. */ BROWSER_OFFLINE: 6, /** * IE is blocking ActiveX streaming. */ ACTIVE_X_BLOCKED: 7 }; /** * Returns a useful error string for debugging based on the specified error * code. * @param {goog.net.ChannelRequest.Error} errorCode The error code. * @param {number} statusCode The HTTP status code. * @return {string} The error string for the given code combination. */ goog.net.ChannelRequest.errorStringFromCode = function(errorCode, statusCode) { switch (errorCode) { case goog.net.ChannelRequest.Error.STATUS: return 'Non-200 return code (' + statusCode + ')'; case goog.net.ChannelRequest.Error.NO_DATA: return 'XMLHTTP failure (no data)'; case goog.net.ChannelRequest.Error.TIMEOUT: return 'HttpConnection timeout'; default: return 'Unknown error'; } }; /** * Sentinel value used to indicate an invalid chunk in a multi-chunk response. * @type {Object} * @private */ goog.net.ChannelRequest.INVALID_CHUNK_ = {}; /** * Sentinel value used to indicate an incomplete chunk in a multi-chunk * response. * @type {Object} * @private */ goog.net.ChannelRequest.INCOMPLETE_CHUNK_ = {}; /** * Returns whether XHR streaming is supported on this browser. * * If XHR streaming is not supported, we will try to use an ActiveXObject * to create a Forever IFrame. * * @return {boolean} Whether XHR streaming is supported. * @see http://code.google.com/p/closure-library/issues/detail?id=346 */ goog.net.ChannelRequest.supportsXhrStreaming = function() { return !goog.userAgent.IE || goog.userAgent.isDocumentMode(10); }; /** * Sets extra HTTP headers to add to all the requests sent to the server. * * @param {Object} extraHeaders The HTTP headers. */ goog.net.ChannelRequest.prototype.setExtraHeaders = function(extraHeaders) { this.extraHeaders_ = extraHeaders; }; /** * Sets the timeout for a request * * @param {number} timeout The timeout in MS for when we fail the request. */ goog.net.ChannelRequest.prototype.setTimeout = function(timeout) { this.timeout_ = timeout; }; /** * Sets the throttle for handling onreadystatechange events for the request. * * @param {number} throttle The throttle in ms. A value of zero indicates * no throttle. */ goog.net.ChannelRequest.prototype.setReadyStateChangeThrottle = function( throttle) { this.readyStateChangeThrottleMs_ = throttle; }; /** * Uses XMLHTTP to send an HTTP POST to the server. * * @param {goog.Uri} uri The uri of the request. * @param {string} postData The data for the post body. * @param {boolean} decodeChunks Whether to the result is expected to be * encoded for chunking and thus requires decoding. */ goog.net.ChannelRequest.prototype.xmlHttpPost = function(uri, postData, decodeChunks) { this.type_ = goog.net.ChannelRequest.Type_.XML_HTTP; this.baseUri_ = uri.clone().makeUnique(); this.postData_ = postData; this.decodeChunks_ = decodeChunks; this.sendXmlHttp_(null /* hostPrefix */); }; /** * Uses XMLHTTP to send an HTTP GET to the server. * * @param {goog.Uri} uri The uri of the request. * @param {boolean} decodeChunks Whether to the result is expected to be * encoded for chunking and thus requires decoding. * @param {?string} hostPrefix The host prefix, if we might be using a * secondary domain. Note that it should also be in the URL, adding this * won't cause it to be added to the URL. * @param {boolean=} opt_noClose Whether to request that the tcp/ip connection * should be closed. */ goog.net.ChannelRequest.prototype.xmlHttpGet = function(uri, decodeChunks, hostPrefix, opt_noClose) { this.type_ = goog.net.ChannelRequest.Type_.XML_HTTP; this.baseUri_ = uri.clone().makeUnique(); this.postData_ = null; this.decodeChunks_ = decodeChunks; if (opt_noClose) { this.sendClose_ = false; } this.sendXmlHttp_(hostPrefix); }; /** * Sends a request via XMLHTTP according to the current state of the * ChannelRequest object. * * @param {?string} hostPrefix The host prefix, if we might be using a secondary * domain. * @private */ goog.net.ChannelRequest.prototype.sendXmlHttp_ = function(hostPrefix) { this.requestStartTime_ = goog.now(); this.ensureWatchDogTimer_(); // clone the base URI to create the request URI. The request uri has the // attempt number as a parameter which helps in debugging. this.requestUri_ = this.baseUri_.clone(); this.requestUri_.setParameterValues('t', this.retryId_); // send the request either as a POST or GET this.xmlHttpChunkStart_ = 0; var useSecondaryDomains = this.channel_.shouldUseSecondaryDomains(); this.xmlHttp_ = this.channel_.createXhrIo(useSecondaryDomains ? hostPrefix : null); if (this.readyStateChangeThrottleMs_ > 0) { this.readyStateChangeThrottle_ = new goog.async.Throttle( goog.bind(this.xmlHttpHandler_, this, this.xmlHttp_), this.readyStateChangeThrottleMs_); } this.eventHandler_.listen(this.xmlHttp_, goog.net.EventType.READY_STATE_CHANGE, this.readyStateChangeHandler_); var headers = this.extraHeaders_ ? goog.object.clone(this.extraHeaders_) : {}; if (this.postData_) { // todo (jonp) - use POST constant when Dan defines it this.verb_ = 'POST'; headers['Content-Type'] = 'application/x-www-form-urlencoded'; this.xmlHttp_.send(this.requestUri_, this.verb_, this.postData_, headers); } else { // todo (jonp) - use GET constant when Dan defines it this.verb_ = 'GET'; // If the user agent is webkit, we cannot send the close header since it is // disallowed by the browser. If we attempt to set the "Connection: close" // header in WEBKIT browser, it will actually causes an error message. if (this.sendClose_ && !goog.userAgent.WEBKIT) { headers['Connection'] = 'close'; } this.xmlHttp_.send(this.requestUri_, this.verb_, null, headers); } this.channel_.notifyServerReachabilityEvent( goog.net.BrowserChannel.ServerReachability.REQUEST_MADE); this.channelDebug_.xmlHttpChannelRequest(this.verb_, this.requestUri_, this.rid_, this.retryId_, this.postData_); }; /** * Handles a readystatechange event. * @param {goog.events.Event} evt The event. * @private */ goog.net.ChannelRequest.prototype.readyStateChangeHandler_ = function(evt) { var xhr = /** @type {goog.net.XhrIo} */ (evt.target); var throttle = this.readyStateChangeThrottle_; if (throttle && xhr.getReadyState() == goog.net.XmlHttp.ReadyState.INTERACTIVE) { // Only throttle in the partial data case. this.channelDebug_.debug('Throttling readystatechange.'); throttle.fire(); } else { // If we haven't throttled, just handle response directly. this.xmlHttpHandler_(xhr); } }; /** * XmlHttp handler * @param {goog.net.XhrIo} xmlhttp The XhrIo object for the current request. * @private */ goog.net.ChannelRequest.prototype.xmlHttpHandler_ = function(xmlhttp) { goog.net.BrowserChannel.onStartExecution(); /** @preserveTry */ try { if (xmlhttp == this.xmlHttp_) { this.onXmlHttpReadyStateChanged_(); } else { this.channelDebug_.warning('Called back with an ' + 'unexpected xmlhttp'); } } catch (ex) { this.channelDebug_.debug('Failed call to OnXmlHttpReadyStateChanged_'); if (this.xmlHttp_ && this.xmlHttp_.getResponseText()) { this.channelDebug_.dumpException(ex, 'ResponseText: ' + this.xmlHttp_.getResponseText()); } else { this.channelDebug_.dumpException(ex, 'No response text'); } } finally { goog.net.BrowserChannel.onEndExecution(); } }; /** * Called by the readystate handler for XMLHTTP requests. * * @private */ goog.net.ChannelRequest.prototype.onXmlHttpReadyStateChanged_ = function() { var readyState = this.xmlHttp_.getReadyState(); var errorCode = this.xmlHttp_.getLastErrorCode(); var statusCode = this.xmlHttp_.getStatus(); // If it is Safari less than 420+, there is a bug that causes null to be // in the responseText on ready state interactive so we must wait for // ready state complete. if (!goog.net.ChannelRequest.supportsXhrStreaming() || (goog.userAgent.WEBKIT && !goog.userAgent.isVersion( goog.net.ChannelRequest.MIN_WEBKIT_FOR_INTERACTIVE_))) { if (readyState < goog.net.XmlHttp.ReadyState.COMPLETE) { // not yet ready return; } } else { // we get partial results in browsers that support ready state interactive. // We also make sure that getResponseText is not null in interactive mode // before we continue. However, we don't do it in Opera because it only // fire readyState == INTERACTIVE once. We need the following code to poll if (readyState < goog.net.XmlHttp.ReadyState.INTERACTIVE || readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE && !goog.userAgent.OPERA && !this.xmlHttp_.getResponseText()) { // not yet ready return; } } // Dispatch any appropriate network events. if (!this.cancelled_ && readyState == goog.net.XmlHttp.ReadyState.COMPLETE && errorCode != goog.net.ErrorCode.ABORT) { // Pretty conservative, these are the only known scenarios which we'd // consider indicative of a truly non-functional network connection. if (errorCode == goog.net.ErrorCode.TIMEOUT || statusCode <= 0) { this.channel_.notifyServerReachabilityEvent( goog.net.BrowserChannel.ServerReachability.REQUEST_FAILED); } else { this.channel_.notifyServerReachabilityEvent( goog.net.BrowserChannel.ServerReachability.REQUEST_SUCCEEDED); } } // got some data so cancel the watchdog timer this.cancelWatchDogTimer_(); var status = this.xmlHttp_.getStatus(); this.lastStatusCode_ = status; var responseText = this.xmlHttp_.getResponseText(); if (!responseText) { this.channelDebug_.debug('No response text for uri ' + this.requestUri_ + ' status ' + status); } this.successful_ = (status == 200); this.channelDebug_.xmlHttpChannelResponseMetaData( /** @type {string} */ (this.verb_), this.requestUri_, this.rid_, this.retryId_, readyState, status); if (!this.successful_) { if (status == 400 && responseText.indexOf('Unknown SID') > 0) { // the server error string will include 'Unknown SID' which indicates the // server doesn't know about the session (maybe it got restarted, maybe // the user got moved to another server, etc.,). Handlers can special // case this error this.lastError_ = goog.net.ChannelRequest.Error.UNKNOWN_SESSION_ID; goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.REQUEST_UNKNOWN_SESSION_ID); this.channelDebug_.warning('XMLHTTP Unknown SID (' + this.rid_ + ')'); } else { this.lastError_ = goog.net.ChannelRequest.Error.STATUS; goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.REQUEST_BAD_STATUS); this.channelDebug_.warning( 'XMLHTTP Bad status ' + status + ' (' + this.rid_ + ')'); } this.cleanup_(); this.dispatchFailure_(); return; } if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) { this.cleanup_(); } if (this.decodeChunks_) { this.decodeNextChunks_(readyState, responseText); if (goog.userAgent.OPERA && readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE) { this.startPolling_(); } } else { this.channelDebug_.xmlHttpChannelResponseText( this.rid_, responseText, null); this.safeOnRequestData_(responseText); } if (!this.successful_) { return; } if (!this.cancelled_) { if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) { this.channel_.onRequestComplete(this); } else { // The default is false, the result from this callback shouldn't carry // over to the next callback, otherwise the request looks successful if // the watchdog timer gets called this.successful_ = false; this.ensureWatchDogTimer_(); } } }; /** * Decodes the next set of available chunks in the response. * @param {number} readyState The value of readyState. * @param {string} responseText The value of responseText. * @private */ goog.net.ChannelRequest.prototype.decodeNextChunks_ = function(readyState, responseText) { var decodeNextChunksSuccessful = true; while (!this.cancelled_ && this.xmlHttpChunkStart_ < responseText.length) { var chunkText = this.getNextChunk_(responseText); if (chunkText == goog.net.ChannelRequest.INCOMPLETE_CHUNK_) { if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) { // should have consumed entire response when the request is done this.lastError_ = goog.net.ChannelRequest.Error.BAD_DATA; goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.REQUEST_INCOMPLETE_DATA); decodeNextChunksSuccessful = false; } this.channelDebug_.xmlHttpChannelResponseText( this.rid_, null, '[Incomplete Response]'); break; } else if (chunkText == goog.net.ChannelRequest.INVALID_CHUNK_) { this.lastError_ = goog.net.ChannelRequest.Error.BAD_DATA; goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.REQUEST_BAD_DATA); this.channelDebug_.xmlHttpChannelResponseText( this.rid_, responseText, '[Invalid Chunk]'); decodeNextChunksSuccessful = false; break; } else { this.channelDebug_.xmlHttpChannelResponseText( this.rid_, /** @type {string} */ (chunkText), null); this.safeOnRequestData_(/** @type {string} */ (chunkText)); } } if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE && responseText.length == 0) { // also an error if we didn't get any response this.lastError_ = goog.net.ChannelRequest.Error.NO_DATA; goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.REQUEST_NO_DATA); decodeNextChunksSuccessful = false; } this.successful_ = this.successful_ && decodeNextChunksSuccessful; if (!decodeNextChunksSuccessful) { // malformed response - we make this trigger retry logic this.channelDebug_.xmlHttpChannelResponseText( this.rid_, responseText, '[Invalid Chunked Response]'); this.cleanup_(); this.dispatchFailure_(); } }; /** * Polls the response for new data. * @private */ goog.net.ChannelRequest.prototype.pollResponse_ = function() { var readyState = this.xmlHttp_.getReadyState(); var responseText = this.xmlHttp_.getResponseText(); if (this.xmlHttpChunkStart_ < responseText.length) { this.cancelWatchDogTimer_(); this.decodeNextChunks_(readyState, responseText); if (this.successful_ && readyState != goog.net.XmlHttp.ReadyState.COMPLETE) { this.ensureWatchDogTimer_(); } } }; /** * Starts a polling interval for changes to responseText of the * XMLHttpRequest, for browsers that don't fire onreadystatechange * as data comes in incrementally. This timer is disabled in * cleanup_(). * @private */ goog.net.ChannelRequest.prototype.startPolling_ = function() { this.eventHandler_.listen(this.pollingTimer_, goog.Timer.TICK, this.pollResponse_); this.pollingTimer_.start(); }; /** * Called when the browser declares itself offline at the start of a request or * during its lifetime. Abandons that request. * @private */ goog.net.ChannelRequest.prototype.cancelRequestAsBrowserIsOffline_ = function() { if (this.successful_) { // Should never happen. this.channelDebug_.severe( 'Received browser offline event even though request completed ' + 'successfully'); } this.channelDebug_.browserOfflineResponse(this.requestUri_); this.cleanup_(); // set error and dispatch failure this.lastError_ = goog.net.ChannelRequest.Error.BROWSER_OFFLINE; goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.BROWSER_OFFLINE); this.dispatchFailure_(); }; /** * Returns the next chunk of a chunk-encoded response. This is not standard * HTTP chunked encoding because browsers don't expose the chunk boundaries to * the application through XMLHTTP. So we have an additional chunk encoding at * the application level that lets us tell where the beginning and end of * individual responses are so that we can only try to eval a complete JS array. * * The encoding is the size of the chunk encoded as a decimal string followed * by a newline followed by the data. * * @param {string} responseText The response text from the XMLHTTP response. * @return {string|Object} The next chunk string or a sentinel object * indicating a special condition. * @private */ goog.net.ChannelRequest.prototype.getNextChunk_ = function(responseText) { var sizeStartIndex = this.xmlHttpChunkStart_; var sizeEndIndex = responseText.indexOf('\n', sizeStartIndex); if (sizeEndIndex == -1) { return goog.net.ChannelRequest.INCOMPLETE_CHUNK_; } var sizeAsString = responseText.substring(sizeStartIndex, sizeEndIndex); var size = Number(sizeAsString); if (isNaN(size)) { return goog.net.ChannelRequest.INVALID_CHUNK_; } var chunkStartIndex = sizeEndIndex + 1; if (chunkStartIndex + size > responseText.length) { return goog.net.ChannelRequest.INCOMPLETE_CHUNK_; } var chunkText = responseText.substr(chunkStartIndex, size); this.xmlHttpChunkStart_ = chunkStartIndex + size; return chunkText; }; /** * Uses the Trident htmlfile ActiveX control to send a GET request in IE. This * is the innovation discovered that lets us get intermediate results in * Internet Explorer. Thanks to http://go/kev * @param {goog.Uri} uri The uri to request from. * @param {boolean} usingSecondaryDomain Whether to use a secondary domain. */ goog.net.ChannelRequest.prototype.tridentGet = function(uri, usingSecondaryDomain) { this.type_ = goog.net.ChannelRequest.Type_.TRIDENT; this.baseUri_ = uri.clone().makeUnique(); this.tridentGet_(usingSecondaryDomain); }; /** * Starts the Trident request. * @param {boolean} usingSecondaryDomain Whether to use a secondary domain. * @private */ goog.net.ChannelRequest.prototype.tridentGet_ = function(usingSecondaryDomain) { this.requestStartTime_ = goog.now(); this.ensureWatchDogTimer_(); var hostname = usingSecondaryDomain ? window.location.hostname : ''; this.requestUri_ = this.baseUri_.clone(); this.requestUri_.setParameterValue('DOMAIN', hostname); this.requestUri_.setParameterValue('t', this.retryId_); try { this.trident_ = new ActiveXObject('htmlfile'); } catch (e) { this.channelDebug_.severe('ActiveX blocked'); this.cleanup_(); this.lastError_ = goog.net.ChannelRequest.Error.ACTIVE_X_BLOCKED; goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.ACTIVE_X_BLOCKED); this.dispatchFailure_(); return; } var body = '<html><body>'; if (usingSecondaryDomain) { body += '<script>document.domain="' + hostname + '"</scr' + 'ipt>'; } body += '</body></html>'; this.trident_.open(); this.trident_.write(body); this.trident_.close(); this.trident_.parentWindow['m'] = goog.bind(this.onTridentRpcMessage_, this); this.trident_.parentWindow['d'] = goog.bind(this.onTridentDone_, this, true); this.trident_.parentWindow['rpcClose'] = goog.bind(this.onTridentDone_, this, false); var div = this.trident_.createElement('div'); this.trident_.parentWindow.document.body.appendChild(div); div.innerHTML = '<iframe src="' + this.requestUri_ + '"></iframe>'; this.channelDebug_.tridentChannelRequest('GET', this.requestUri_, this.rid_, this.retryId_); this.channel_.notifyServerReachabilityEvent( goog.net.BrowserChannel.ServerReachability.REQUEST_MADE); }; /** * Callback from the Trident htmlfile ActiveX control for when a new message * is received. * * @param {string} msg The data payload. * @private */ goog.net.ChannelRequest.prototype.onTridentRpcMessage_ = function(msg) { // need to do async b/c this gets called off of the context of the ActiveX goog.net.BrowserChannel.setTimeout( goog.bind(this.onTridentRpcMessageAsync_, this, msg), 0); }; /** * Callback from the Trident htmlfile ActiveX control for when a new message * is received. * * @param {string} msg The data payload. * @private */ goog.net.ChannelRequest.prototype.onTridentRpcMessageAsync_ = function(msg) { if (this.cancelled_) { return; } this.channelDebug_.tridentChannelResponseText(this.rid_, msg); this.cancelWatchDogTimer_(); this.safeOnRequestData_(msg); this.ensureWatchDogTimer_(); }; /** * Callback from the Trident htmlfile ActiveX control for when the request * is complete * * @param {boolean} successful Whether the request successfully completed. * @private */ goog.net.ChannelRequest.prototype.onTridentDone_ = function(successful) { // need to do async b/c this gets called off of the context of the ActiveX goog.net.BrowserChannel.setTimeout( goog.bind(this.onTridentDoneAsync_, this, successful), 0); }; /** * Callback from the Trident htmlfile ActiveX control for when the request * is complete * * @param {boolean} successful Whether the request successfully completed. * @private */ goog.net.ChannelRequest.prototype.onTridentDoneAsync_ = function(successful) { if (this.cancelled_) { return; } this.channelDebug_.tridentChannelResponseDone( this.rid_, successful); this.cleanup_(); this.successful_ = successful; this.channel_.onRequestComplete(this); this.channel_.notifyServerReachabilityEvent( goog.net.BrowserChannel.ServerReachability.BACK_CHANNEL_ACTIVITY); }; /** * Uses an IMG tag to send an HTTP get to the server. This is only currently * used to terminate the connection, as an IMG tag is the most reliable way to * send something to the server while the page is getting torn down. * @param {goog.Uri} uri The uri to send a request to. */ goog.net.ChannelRequest.prototype.sendUsingImgTag = function(uri) { this.type_ = goog.net.ChannelRequest.Type_.IMG; this.baseUri_ = uri.clone().makeUnique(); this.imgTagGet_(); }; /** * Starts the IMG request. * * @private */ goog.net.ChannelRequest.prototype.imgTagGet_ = function() { var eltImg = new Image(); eltImg.src = this.baseUri_; this.requestStartTime_ = goog.now(); this.ensureWatchDogTimer_(); }; /** * Cancels the request no matter what the underlying transport is. */ goog.net.ChannelRequest.prototype.cancel = function() { this.cancelled_ = true; this.cleanup_(); }; /** * Ensures that there is watchdog timeout which is used to ensure that * the connection completes in time. * * @private */ goog.net.ChannelRequest.prototype.ensureWatchDogTimer_ = function() { this.watchDogTimeoutTime_ = goog.now() + this.timeout_; this.startWatchDogTimer_(this.timeout_); }; /** * Starts the watchdog timer which is used to ensure that the connection * completes in time. * @param {number} time The number of milliseconds to wait. * @private */ goog.net.ChannelRequest.prototype.startWatchDogTimer_ = function(time) { if (this.watchDogTimerId_ != null) { // assertion throw Error('WatchDog timer not null'); } this.watchDogTimerId_ = goog.net.BrowserChannel.setTimeout( goog.bind(this.onWatchDogTimeout_, this), time); }; /** * Cancels the watchdog timer if it has been started. * * @private */ goog.net.ChannelRequest.prototype.cancelWatchDogTimer_ = function() { if (this.watchDogTimerId_) { goog.global.clearTimeout(this.watchDogTimerId_); this.watchDogTimerId_ = null; } }; /** * Called when the watchdog timer is triggered. It also handles a case where it * is called too early which we suspect may be happening sometimes * (not sure why) * * @private */ goog.net.ChannelRequest.prototype.onWatchDogTimeout_ = function() { this.watchDogTimerId_ = null; var now = goog.now(); if (now - this.watchDogTimeoutTime_ >= 0) { this.handleTimeout_(); } else { // got called too early for some reason this.channelDebug_.warning('WatchDog timer called too early'); this.startWatchDogTimer_(this.watchDogTimeoutTime_ - now); } }; /** * Called when the request has actually timed out. Will cleanup and notify the * channel of the failure. * * @private */ goog.net.ChannelRequest.prototype.handleTimeout_ = function() { if (this.successful_) { // Should never happen. this.channelDebug_.severe( 'Received watchdog timeout even though request loaded successfully'); } this.channelDebug_.timeoutResponse(this.requestUri_); // IMG requests never notice if they were successful, and always 'time out'. // This fact says nothing about reachability. if (this.type_ != goog.net.ChannelRequest.Type_.IMG) { this.channel_.notifyServerReachabilityEvent( goog.net.BrowserChannel.ServerReachability.REQUEST_FAILED); } this.cleanup_(); // set error and dispatch failure this.lastError_ = goog.net.ChannelRequest.Error.TIMEOUT; goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.REQUEST_TIMEOUT); this.dispatchFailure_(); }; /** * Notifies the channel that this request failed. * @private */ goog.net.ChannelRequest.prototype.dispatchFailure_ = function() { if (this.channel_.isClosed() || this.cancelled_) { return; } this.channel_.onRequestComplete(this); }; /** * Cleans up the objects used to make the request. This function is * idempotent. * * @private */ goog.net.ChannelRequest.prototype.cleanup_ = function() { this.cancelWatchDogTimer_(); goog.dispose(this.readyStateChangeThrottle_); this.readyStateChangeThrottle_ = null; // Stop the polling timer, if necessary. this.pollingTimer_.stop(); // Unhook all event handlers. this.eventHandler_.removeAll(); if (this.xmlHttp_) { // clear out this.xmlHttp_ before aborting so we handle getting reentered // inside abort var xmlhttp = this.xmlHttp_; this.xmlHttp_ = null; xmlhttp.abort(); xmlhttp.dispose(); } if (this.trident_) { this.trident_ = null; } }; /** * Indicates whether the request was successful. Only valid after the handler * is called to indicate completion of the request. * * @return {boolean} True if the request succeeded. */ goog.net.ChannelRequest.prototype.getSuccess = function() { return this.successful_; }; /** * If the request was not successful, returns the reason. * * @return {?goog.net.ChannelRequest.Error} The last error. */ goog.net.ChannelRequest.prototype.getLastError = function() { return this.lastError_; }; /** * Returns the status code of the last request. * @return {number} The status code of the last request. */ goog.net.ChannelRequest.prototype.getLastStatusCode = function() { return this.lastStatusCode_; }; /** * Returns the session id for this channel. * * @return {string|undefined} The session ID. */ goog.net.ChannelRequest.prototype.getSessionId = function() { return this.sid_; }; /** * Returns the request id for this request. Each request has a unique request * id and the request IDs are a sequential increasing count. * * @return {string|number|undefined} The request ID. */ goog.net.ChannelRequest.prototype.getRequestId = function() { return this.rid_; }; /** * Returns the data for a post, if this request is a post. * * @return {?string} The POST data provided by the request initiator. */ goog.net.ChannelRequest.prototype.getPostData = function() { return this.postData_; }; /** * Returns the time that the request started, if it has started. * * @return {?number} The time the request started, as returned by goog.now(). */ goog.net.ChannelRequest.prototype.getRequestStartTime = function() { return this.requestStartTime_; }; /** * Helper to call the callback's onRequestData, which catches any * exception and cleans up the request. * @param {string} data The request data. * @private */ goog.net.ChannelRequest.prototype.safeOnRequestData_ = function(data) { /** @preserveTry */ try { this.channel_.onRequestData(this, data); this.channel_.notifyServerReachabilityEvent( goog.net.BrowserChannel.ServerReachability.BACK_CHANNEL_ACTIVITY); } catch (e) { // Dump debug info, but keep going without closing the channel. this.channelDebug_.dumpException( e, 'Error in httprequest callback'); } };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides the enum for the role of the CrossPageChannel. * */ goog.provide('goog.net.xpc.CrossPageChannelRole'); /** * The role of the peer. * @enum {number} */ goog.net.xpc.CrossPageChannelRole = { OUTER: 0, INNER: 1 };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Contains the frame element method transport for cross-domain * communication. It exploits the fact that FF lets a page in an * iframe call a method on the iframe-element it is contained in, even if the * containing page is from a different domain. * */ goog.provide('goog.net.xpc.FrameElementMethodTransport'); goog.require('goog.net.xpc'); goog.require('goog.net.xpc.CrossPageChannelRole'); goog.require('goog.net.xpc.Transport'); /** * Frame-element method transport. * * Firefox allows a document within an iframe to call methods on the * iframe-element added by the containing document. * NOTE(user): Tested in all FF versions starting from 1.0 * * @param {goog.net.xpc.CrossPageChannel} channel The channel this transport * belongs to. * @param {goog.dom.DomHelper=} opt_domHelper The dom helper to use for finding * the correct window. * @constructor * @extends {goog.net.xpc.Transport} */ goog.net.xpc.FrameElementMethodTransport = function(channel, opt_domHelper) { goog.base(this, opt_domHelper); /** * The channel this transport belongs to. * @type {goog.net.xpc.CrossPageChannel} * @private */ this.channel_ = channel; // To transfer messages, this transport basically uses normal function calls, // which are synchronous. To avoid endless recursion, the delivery has to // be artificially made asynchronous. /** * Array for queued messages. * @type {Array} * @private */ this.queue_ = []; /** * Callback function which wraps deliverQueued_. * @type {Function} * @private */ this.deliverQueuedCb_ = goog.bind(this.deliverQueued_, this); }; goog.inherits(goog.net.xpc.FrameElementMethodTransport, goog.net.xpc.Transport); /** * The transport type. * @type {number} * @protected * @override */ goog.net.xpc.FrameElementMethodTransport.prototype.transportType = goog.net.xpc.TransportTypes.FRAME_ELEMENT_METHOD; /** * Flag used to enforce asynchronous messaging semantics. * @type {boolean} * @private */ goog.net.xpc.FrameElementMethodTransport.prototype.recursive_ = false; /** * Timer used to enforce asynchronous message delivery. * @type {number} * @private */ goog.net.xpc.FrameElementMethodTransport.prototype.timer_ = 0; /** * Holds the function to send messages to the peer * (once it becomes available). * @type {Function} * @private */ goog.net.xpc.FrameElementMethodTransport.outgoing_ = null; /** * Connect this transport. * @override */ goog.net.xpc.FrameElementMethodTransport.prototype.connect = function() { if (this.channel_.getRole() == goog.net.xpc.CrossPageChannelRole.OUTER) { // get shortcut to iframe-element this.iframeElm_ = this.channel_.getIframeElement(); // add the gateway function to the iframe-element // (to be called by the peer) this.iframeElm_['XPC_toOuter'] = goog.bind(this.incoming_, this); // at this point we just have to wait for a notification from the peer... } else { this.attemptSetup_(); } }; /** * Only used from within an iframe. Attempts to attach the method * to be used for sending messages by the containing document. Has to * wait until the containing document has finished. Therefore calls * itself in a timeout if not successful. * @private */ goog.net.xpc.FrameElementMethodTransport.prototype.attemptSetup_ = function() { var retry = true; /** @preserveTry */ try { if (!this.iframeElm_) { // throws security exception when called too early this.iframeElm_ = this.getWindow().frameElement; } // check if iframe-element and the gateway-function to the // outer-frame are present // TODO(user) Make sure the following code doesn't throw any exceptions if (this.iframeElm_ && this.iframeElm_['XPC_toOuter']) { // get a reference to the gateway function this.outgoing_ = this.iframeElm_['XPC_toOuter']; // attach the gateway function the other document will use this.iframeElm_['XPC_toOuter']['XPC_toInner'] = goog.bind(this.incoming_, this); // stop retrying retry = false; // notify outer frame this.send(goog.net.xpc.TRANSPORT_SERVICE_, goog.net.xpc.SETUP_ACK_); // notify channel that the transport is ready this.channel_.notifyConnected(); } } catch (e) { goog.net.xpc.logger.severe( 'exception caught while attempting setup: ' + e); } // retry necessary? if (retry) { if (!this.attemptSetupCb_) { this.attemptSetupCb_ = goog.bind(this.attemptSetup_, this); } this.getWindow().setTimeout(this.attemptSetupCb_, 100); } }; /** * Handles transport service messages. * @param {string} payload The message content. * @override */ goog.net.xpc.FrameElementMethodTransport.prototype.transportServiceHandler = function(payload) { if (this.channel_.getRole() == goog.net.xpc.CrossPageChannelRole.OUTER && !this.channel_.isConnected() && payload == goog.net.xpc.SETUP_ACK_) { // get a reference to the gateway function this.outgoing_ = this.iframeElm_['XPC_toOuter']['XPC_toInner']; // notify the channel we're ready this.channel_.notifyConnected(); } else { throw Error('Got unexpected transport message.'); } }; /** * Process incoming message. * @param {string} serviceName The name of the service the message is to be * delivered to. * @param {string} payload The message to process. * @private */ goog.net.xpc.FrameElementMethodTransport.prototype.incoming_ = function(serviceName, payload) { if (!this.recursive_ && this.queue_.length == 0) { this.channel_.xpcDeliver(serviceName, payload); } else { this.queue_.push({serviceName: serviceName, payload: payload}); if (this.queue_.length == 1) { this.timer_ = this.getWindow().setTimeout(this.deliverQueuedCb_, 1); } } }; /** * Delivers queued messages. * @private */ goog.net.xpc.FrameElementMethodTransport.prototype.deliverQueued_ = function() { while (this.queue_.length) { var msg = this.queue_.shift(); this.channel_.xpcDeliver(msg.serviceName, msg.payload); } }; /** * Send a message * @param {string} service The name off the service the message is to be * delivered to. * @param {string} payload The message content. * @override */ goog.net.xpc.FrameElementMethodTransport.prototype.send = function(service, payload) { this.recursive_ = true; this.outgoing_(service, payload); this.recursive_ = false; }; /** @override */ goog.net.xpc.FrameElementMethodTransport.prototype.disposeInternal = function() { goog.net.xpc.FrameElementMethodTransport.superClass_.disposeInternal.call( this); this.outgoing_ = null; this.iframeElm_ = null; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides the namesspace for client-side communication * between pages originating from different domains (it works also * with pages from the same domain, but doing that is kinda * pointless). * * The only publicly visible class is goog.net.xpc.CrossPageChannel. * * Note: The preferred name for the main class would have been * CrossDomainChannel. But as there already is a class named like * that (which serves a different purpose) in the maps codebase, * CrossPageChannel was chosen to avoid confusion. * * CrossPageChannel abstracts the underlying transport mechanism to * provide a common interface in all browsers. * */ /* TODO(user) - resolve fastback issues in Safari (IframeRelayTransport) */ /** * Namespace for CrossPageChannel */ goog.provide('goog.net.xpc'); goog.provide('goog.net.xpc.CfgFields'); goog.provide('goog.net.xpc.ChannelStates'); goog.provide('goog.net.xpc.TransportNames'); goog.provide('goog.net.xpc.TransportTypes'); goog.provide('goog.net.xpc.UriCfgFields'); goog.require('goog.debug.Logger'); /** * Enum used to identify transport types. * @enum {number} */ goog.net.xpc.TransportTypes = { NATIVE_MESSAGING: 1, FRAME_ELEMENT_METHOD: 2, IFRAME_RELAY: 3, IFRAME_POLLING: 4, FLASH: 5, NIX: 6 }; /** * Enum containing transport names. These need to correspond to the * transport class names for createTransport_() to work. * @type {Object} */ goog.net.xpc.TransportNames = { '1': 'NativeMessagingTransport', '2': 'FrameElementMethodTransport', '3': 'IframeRelayTransport', '4': 'IframePollingTransport', '5': 'FlashTransport', '6': 'NixTransport' }; // TODO(user): Add auth token support to other methods. /** * Field names used on configuration object. * @type {Object} */ goog.net.xpc.CfgFields = { /** * Channel name identifier. * Both peers have to be initialized with * the same channel name. If not present, a channel name is * generated (which then has to transferred to the peer somehow). */ CHANNEL_NAME: 'cn', /** * Authorization token. If set, NIX will use this authorization token * to validate the setup. */ AUTH_TOKEN: 'at', /** * Remote party's authorization token. If set, NIX will validate this * authorization token against that sent by the other party. */ REMOTE_AUTH_TOKEN: 'rat', /** * The URI of the peer page. */ PEER_URI: 'pu', /** * Ifame-ID identifier. * The id of the iframe element the peer-document lives in. */ IFRAME_ID: 'ifrid', /** * Transport type identifier. * The transport type to use. Possible values are entries from * goog.net.xpc.TransportTypes. If not present, the transport is * determined automatically based on the useragent's capabilities. */ TRANSPORT: 'tp', /** * Local relay URI identifier (IframeRelayTransport-specific). * The URI (can't contain a fragment identifier) used by the peer to * relay data through. */ LOCAL_RELAY_URI: 'lru', /** * Peer relay URI identifier (IframeRelayTransport-specific). * The URI (can't contain a fragment identifier) used to relay data * to the peer. */ PEER_RELAY_URI: 'pru', /** * Local poll URI identifier (IframePollingTransport-specific). * The URI (can't contain a fragment identifier)which is polled * to receive data from the peer. */ LOCAL_POLL_URI: 'lpu', /** * Local poll URI identifier (IframePollingTransport-specific). * The URI (can't contain a fragment identifier) used to send data * to the peer. */ PEER_POLL_URI: 'ppu', /** * The hostname of the peer window, including protocol, domain, and port * (if specified). Used for security sensitive applications that make * use of NativeMessagingTransport (i.e. most applications). */ PEER_HOSTNAME: 'ph', /** * Usually both frames using a connection initially send a SETUP message to * each other, and each responds with a SETUP_ACK. A frame marks itself * connected when it receives that SETUP_ACK. If this parameter is true * however, the channel it is passed to will not send a SETUP, but rather will * wait for one from its peer and mark itself connected when that arrives. * Peer iframes created using such a channel will send SETUP however, and will * wait for SETUP_ACK before marking themselves connected. The goal is to * cope with a situation where the availability of the URL for the peer frame * cannot be relied on, eg when the application is offline. Without this * setting, the primary frame will attempt to send its SETUP message every * 100ms, forever. This floods the javascript console with uncatchable * security warnings, and fruitlessly burns CPU. There is one scenario this * mode will not support, and that is reconnection by the outer frame, ie the * creation of a new channel object to connect to a peer iframe which was * already communicating with a previous channel object of the same name. If * that behavior is needed, this mode should not be used. Reconnection by * inner frames is supported in this mode however. */ ONE_SIDED_HANDSHAKE: 'osh', /** * The frame role (inner or outer). Used to explicitly indicate the role for * each peer whenever the role cannot be reliably determined (e.g. the two * peer windows are not parent/child frames). If unspecified, the role will * be dynamically determined, assuming a parent/child frame setup. */ ROLE: 'role', /** * Which version of the native transport startup protocol should be used, the * default being '2'. Version 1 had various timing vulnerabilities, which * had to be compensated for by introducing delays, and is deprecated. V1 * and V2 are broadly compatible, although the more robust timing and lack * of delays is not gained unless both sides are using V2. The only * unsupported case of cross-protocol interoperation is where a connection * starts out with V2 at both ends, and one of the ends reconnects as a V1. * All other initial startup and reconnection scenarios are supported. */ NATIVE_TRANSPORT_PROTOCOL_VERSION: 'nativeProtocolVersion' }; /** * Config properties that need to be URL sanitized. * @type {Array}.<string> */ goog.net.xpc.UriCfgFields = [ goog.net.xpc.CfgFields.PEER_URI, goog.net.xpc.CfgFields.LOCAL_RELAY_URI, goog.net.xpc.CfgFields.PEER_RELAY_URI, goog.net.xpc.CfgFields.LOCAL_POLL_URI, goog.net.xpc.CfgFields.PEER_POLL_URI ]; /** * @enum {number} */ goog.net.xpc.ChannelStates = { NOT_CONNECTED: 1, CONNECTED: 2, CLOSED: 3 }; /** * The name of the transport service (used for internal signalling). * @type {string} * @suppress {underscore} */ goog.net.xpc.TRANSPORT_SERVICE_ = 'tp'; /** * Transport signaling message: setup. * @type {string} */ goog.net.xpc.SETUP = 'SETUP'; /** * Transport signaling message: setup for native transport protocol v2. * @type {string} */ goog.net.xpc.SETUP_NTPV2 = 'SETUP_NTPV2'; /** * Transport signaling message: setup acknowledgement. * @type {string} * @suppress {underscore} */ goog.net.xpc.SETUP_ACK_ = 'SETUP_ACK'; /** * Transport signaling message: setup acknowledgement. * @type {string} */ goog.net.xpc.SETUP_ACK_NTPV2 = 'SETUP_ACK_NTPV2'; /** * Object holding active channels. * Package private. Do not call from outside goog.net.xpc. * * @type {Object.<string, goog.net.xpc.CrossPageChannel>} */ goog.net.xpc.channels = {}; /** * Returns a random string. * @param {number} length How many characters the string shall contain. * @param {string=} opt_characters The characters used. * @return {string} The random string. */ goog.net.xpc.getRandomString = function(length, opt_characters) { var chars = opt_characters || goog.net.xpc.randomStringCharacters_; var charsLength = chars.length; var s = ''; while (length-- > 0) { s += chars.charAt(Math.floor(Math.random() * charsLength)); } return s; }; /** * The default characters used for random string generation. * @type {string} * @private */ goog.net.xpc.randomStringCharacters_ = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; /** * The logger. * @type {goog.debug.Logger} */ goog.net.xpc.logger = goog.debug.Logger.getLogger('goog.net.xpc');
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Contains the iframe polling transport. */ goog.provide('goog.net.xpc.IframePollingTransport'); goog.provide('goog.net.xpc.IframePollingTransport.Receiver'); goog.provide('goog.net.xpc.IframePollingTransport.Sender'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.net.xpc'); goog.require('goog.net.xpc.CrossPageChannelRole'); goog.require('goog.net.xpc.Transport'); goog.require('goog.userAgent'); /** * Iframe polling transport. Uses hidden iframes to transfer data * in the fragment identifier of the URL. The peer polls the iframe's location * for changes. * Unfortunately, in Safari this screws up the history, because Safari doesn't * allow to call location.replace() on a window containing a document from a * different domain (last version tested: 2.0.4). * * @param {goog.net.xpc.CrossPageChannel} channel The channel this * transport belongs to. * @param {goog.dom.DomHelper=} opt_domHelper The dom helper to use for finding * the correct window. * @constructor * @extends {goog.net.xpc.Transport} */ goog.net.xpc.IframePollingTransport = function(channel, opt_domHelper) { goog.base(this, opt_domHelper); /** * The channel this transport belongs to. * @type {goog.net.xpc.CrossPageChannel} * @private */ this.channel_ = channel; /** * The URI used to send messages. * @type {string} * @private */ this.sendUri_ = this.channel_.getConfig()[goog.net.xpc.CfgFields.PEER_POLL_URI]; /** * The URI which is polled for incoming messages. * @type {string} * @private */ this.rcvUri_ = this.channel_.getConfig()[goog.net.xpc.CfgFields.LOCAL_POLL_URI]; /** * The queue to hold messages which can't be sent immediately. * @type {Array} * @private */ this.sendQueue_ = []; }; goog.inherits(goog.net.xpc.IframePollingTransport, goog.net.xpc.Transport); /** * The number of times the inner frame will check for evidence of the outer * frame before it tries its reconnection sequence. These occur at 100ms * intervals, making this an effective max waiting period of 500ms. * @type {number} * @private */ goog.net.xpc.IframePollingTransport.prototype.pollsBeforeReconnect_ = 5; /** * The transport type. * @type {number} * @protected * @override */ goog.net.xpc.IframePollingTransport.prototype.transportType = goog.net.xpc.TransportTypes.IFRAME_POLLING; /** * Sequence counter. * @type {number} * @private */ goog.net.xpc.IframePollingTransport.prototype.sequence_ = 0; /** * Flag indicating whether we are waiting for an acknoledgement. * @type {boolean} * @private */ goog.net.xpc.IframePollingTransport.prototype.waitForAck_ = false; /** * Flag indicating if channel has been initialized. * @type {boolean} * @private */ goog.net.xpc.IframePollingTransport.prototype.initialized_ = false; /** * Reconnection iframe created by inner peer. * @type {Element} * @private */ goog.net.xpc.IframePollingTransport.prototype.reconnectFrame_ = null; /** * The string used to prefix all iframe names and IDs. * @type {string} */ goog.net.xpc.IframePollingTransport.IFRAME_PREFIX = 'googlexpc'; /** * Returns the name/ID of the message frame. * @return {string} Name of message frame. * @private */ goog.net.xpc.IframePollingTransport.prototype.getMsgFrameName_ = function() { return goog.net.xpc.IframePollingTransport.IFRAME_PREFIX + '_' + this.channel_.name + '_msg'; }; /** * Returns the name/ID of the ack frame. * @return {string} Name of ack frame. * @private */ goog.net.xpc.IframePollingTransport.prototype.getAckFrameName_ = function() { return goog.net.xpc.IframePollingTransport.IFRAME_PREFIX + '_' + this.channel_.name + '_ack'; }; /** * Determines whether the channel is still available. The channel is * unavailable if the transport was disposed or the peer is no longer * available. * @return {boolean} Whether the channel is available. */ goog.net.xpc.IframePollingTransport.prototype.isChannelAvailable = function() { return !this.isDisposed() && this.channel_.isPeerAvailable(); }; /** * Safely retrieves the frames from the peer window. If an error is thrown * (e.g. the window is closing) an empty frame object is returned. * @return {!Object.<!Window>} The frames from the peer window. * @private */ goog.net.xpc.IframePollingTransport.prototype.getPeerFrames_ = function() { try { if (this.isChannelAvailable()) { return this.channel_.getPeerWindowObject().frames || {}; } } catch (e) { // An error may be thrown if the window is closing. goog.net.xpc.logger.fine('error retrieving peer frames'); } return {}; }; /** * Safely retrieves the peer frame with the specified name. * @param {string} frameName The name of the peer frame to retrieve. * @return {Window} The peer frame with the specified name. * @private */ goog.net.xpc.IframePollingTransport.prototype.getPeerFrame_ = function( frameName) { return this.getPeerFrames_()[frameName]; }; /** * Connects this transport. * @override */ goog.net.xpc.IframePollingTransport.prototype.connect = function() { if (!this.isChannelAvailable()) { // When the channel is unavailable there is no peer to poll so stop trying // to connect. return; } goog.net.xpc.logger.fine('transport connect called'); if (!this.initialized_) { goog.net.xpc.logger.fine('initializing...'); this.constructSenderFrames_(); this.initialized_ = true; } this.checkForeignFramesReady_(); }; /** * Creates the iframes which are used to send messages (and acknowledgements) * to the peer. Sender iframes contain a document from a different origin and * therefore their content can't be accessed. * @private */ goog.net.xpc.IframePollingTransport.prototype.constructSenderFrames_ = function() { var name = this.getMsgFrameName_(); this.msgIframeElm_ = this.constructSenderFrame_(name); this.msgWinObj_ = this.getWindow().frames[name]; name = this.getAckFrameName_(); this.ackIframeElm_ = this.constructSenderFrame_(name); this.ackWinObj_ = this.getWindow().frames[name]; }; /** * Constructs a sending frame the the given id. * @param {string} id The id. * @return {Element} The constructed frame. * @private */ goog.net.xpc.IframePollingTransport.prototype.constructSenderFrame_ = function(id) { goog.net.xpc.logger.finest('constructing sender frame: ' + id); var ifr = goog.dom.createElement('iframe'); var s = ifr.style; s.position = 'absolute'; s.top = '-10px'; s.left = '10px'; s.width = '1px'; s.height = '1px'; ifr.id = ifr.name = id; ifr.src = this.sendUri_ + '#INITIAL'; this.getWindow().document.body.appendChild(ifr); return ifr; }; /** * The protocol for reconnecting is for the inner frame to change channel * names, and then communicate the new channel name to the outer peer. * The outer peer looks in a predefined location for the channel name * upate. It is important to use a completely new channel name, as this * will ensure that all messaging iframes are not in the bfcache. * Otherwise, Safari may pollute the history when modifying the location * of bfcached iframes. * @private */ goog.net.xpc.IframePollingTransport.prototype.maybeInnerPeerReconnect_ = function() { // Reconnection has been found to not function on some browsers (eg IE7), so // it's important that the mechanism only be triggered as a last resort. As // such, we poll a number of times to find the outer iframe before triggering // it. if (this.reconnectFrame_ || this.pollsBeforeReconnect_-- > 0) { return; } goog.net.xpc.logger.finest('Inner peer reconnect triggered.'); this.channel_.name = goog.net.xpc.getRandomString(10); goog.net.xpc.logger.finest('switching channels: ' + this.channel_.name); this.deconstructSenderFrames_(); this.initialized_ = false; // Communicate new channel name to outer peer. this.reconnectFrame_ = this.constructSenderFrame_( goog.net.xpc.IframePollingTransport.IFRAME_PREFIX + '_reconnect_' + this.channel_.name); }; /** * Scans inner peer for a reconnect message, which will be used to update * the outer peer's channel name. If a reconnect message is found, the * sender frames will be cleaned up to make way for the new sender frames. * Only called by the outer peer. * @private */ goog.net.xpc.IframePollingTransport.prototype.outerPeerReconnect_ = function() { goog.net.xpc.logger.finest('outerPeerReconnect called'); var frames = this.getPeerFrames_(); var length = frames.length; for (var i = 0; i < length; i++) { var frameName; try { if (frames[i] && frames[i].name) { frameName = frames[i].name; } } catch (e) { // Do nothing. } if (!frameName) { continue; } var message = frameName.split('_'); if (message.length == 3 && message[0] == goog.net.xpc.IframePollingTransport.IFRAME_PREFIX && message[1] == 'reconnect') { // This is a legitimate reconnect message from the peer. Start using // the peer provided channel name, and start a connection over from // scratch. this.channel_.name = message[2]; this.deconstructSenderFrames_(); this.initialized_ = false; break; } } }; /** * Cleans up the existing sender frames owned by this peer. Only called by * the outer peer. * @private */ goog.net.xpc.IframePollingTransport.prototype.deconstructSenderFrames_ = function() { goog.net.xpc.logger.finest('deconstructSenderFrames called'); if (this.msgIframeElm_) { this.msgIframeElm_.parentNode.removeChild(this.msgIframeElm_); this.msgIframeElm_ = null; this.msgWinObj_ = null; } if (this.ackIframeElm_) { this.ackIframeElm_.parentNode.removeChild(this.ackIframeElm_); this.ackIframeElm_ = null; this.ackWinObj_ = null; } }; /** * Checks if the frames in the peer's page are ready. These contain a * document from the own domain and are the ones messages are received through. * @private */ goog.net.xpc.IframePollingTransport.prototype.checkForeignFramesReady_ = function() { // check if the connected iframe ready if (!(this.isRcvFrameReady_(this.getMsgFrameName_()) && this.isRcvFrameReady_(this.getAckFrameName_()))) { goog.net.xpc.logger.finest('foreign frames not (yet) present'); if (this.channel_.getRole() == goog.net.xpc.CrossPageChannelRole.INNER) { // The outer peer might need a short time to get its frames ready, as // CrossPageChannel prevents them from getting created until the inner // peer's frame has thrown its loaded event. This method is a noop for // the first few times it's called, and then allows the reconnection // sequence to begin. this.maybeInnerPeerReconnect_(); } else if (this.channel_.getRole() == goog.net.xpc.CrossPageChannelRole.OUTER) { // The inner peer is either not loaded yet, or the receiving // frames are simply missing. Since we cannot discern the two cases, we // should scan for a reconnect message from the inner peer. this.outerPeerReconnect_(); } // start a timer to check again this.getWindow().setTimeout(goog.bind(this.connect, this), 100); } else { goog.net.xpc.logger.fine('foreign frames present'); // Create receivers. this.msgReceiver_ = new goog.net.xpc.IframePollingTransport.Receiver( this, this.getPeerFrame_(this.getMsgFrameName_()), goog.bind(this.processIncomingMsg, this)); this.ackReceiver_ = new goog.net.xpc.IframePollingTransport.Receiver( this, this.getPeerFrame_(this.getAckFrameName_()), goog.bind(this.processIncomingAck, this)); this.checkLocalFramesPresent_(); } }; /** * Checks if the receiving frame is ready. * @param {string} frameName Which receiving frame to check. * @return {boolean} Whether the receiving frame is ready. * @private */ goog.net.xpc.IframePollingTransport.prototype.isRcvFrameReady_ = function(frameName) { goog.net.xpc.logger.finest('checking for receive frame: ' + frameName); /** @preserveTry */ try { var winObj = this.getPeerFrame_(frameName); if (!winObj || winObj.location.href.indexOf(this.rcvUri_) != 0) { return false; } } catch (e) { return false; } return true; }; /** * Checks if the iframes created in the own document are ready. * @private */ goog.net.xpc.IframePollingTransport.prototype.checkLocalFramesPresent_ = function() { // Are the sender frames ready? // These contain a document from the peer's domain, therefore we can only // check if the frame itself is present. var frames = this.getPeerFrames_(); if (!(frames[this.getAckFrameName_()] && frames[this.getMsgFrameName_()])) { // start a timer to check again if (!this.checkLocalFramesPresentCb_) { this.checkLocalFramesPresentCb_ = goog.bind( this.checkLocalFramesPresent_, this); } this.getWindow().setTimeout(this.checkLocalFramesPresentCb_, 100); goog.net.xpc.logger.fine('local frames not (yet) present'); } else { // Create senders. this.msgSender_ = new goog.net.xpc.IframePollingTransport.Sender( this.sendUri_, this.msgWinObj_); this.ackSender_ = new goog.net.xpc.IframePollingTransport.Sender( this.sendUri_, this.ackWinObj_); goog.net.xpc.logger.fine('local frames ready'); this.getWindow().setTimeout(goog.bind(function() { this.msgSender_.send(goog.net.xpc.SETUP); this.sentConnectionSetup_ = true; this.waitForAck_ = true; goog.net.xpc.logger.fine('SETUP sent'); }, this), 100); } }; /** * Check if connection is ready. * @private */ goog.net.xpc.IframePollingTransport.prototype.checkIfConnected_ = function() { if (this.sentConnectionSetupAck_ && this.rcvdConnectionSetupAck_) { this.channel_.notifyConnected(); if (this.deliveryQueue_) { goog.net.xpc.logger.fine('delivering queued messages ' + '(' + this.deliveryQueue_.length + ')'); for (var i = 0, m; i < this.deliveryQueue_.length; i++) { m = this.deliveryQueue_[i]; this.channel_.xpcDeliver(m.service, m.payload); } delete this.deliveryQueue_; } } else { goog.net.xpc.logger.finest('checking if connected: ' + 'ack sent:' + this.sentConnectionSetupAck_ + ', ack rcvd: ' + this.rcvdConnectionSetupAck_); } }; /** * Processes an incoming message. * @param {string} raw The complete received string. */ goog.net.xpc.IframePollingTransport.prototype.processIncomingMsg = function(raw) { goog.net.xpc.logger.finest('msg received: ' + raw); if (raw == goog.net.xpc.SETUP) { if (!this.ackSender_) { // Got SETUP msg, but we can't send an ack. return; } this.ackSender_.send(goog.net.xpc.SETUP_ACK_); goog.net.xpc.logger.finest('SETUP_ACK sent'); this.sentConnectionSetupAck_ = true; this.checkIfConnected_(); } else if (this.channel_.isConnected() || this.sentConnectionSetupAck_) { var pos = raw.indexOf('|'); var head = raw.substring(0, pos); var frame = raw.substring(pos + 1); // check if it is a framed message pos = head.indexOf(','); if (pos == -1) { var seq = head; // send acknowledgement this.ackSender_.send('ACK:' + seq); this.deliverPayload_(frame); } else { var seq = head.substring(0, pos); // send acknowledgement this.ackSender_.send('ACK:' + seq); var partInfo = head.substring(pos + 1).split('/'); var part0 = parseInt(partInfo[0], 10); var part1 = parseInt(partInfo[1], 10); // create an array to accumulate the parts if this is the // first frame of a message if (part0 == 1) { this.parts_ = []; } this.parts_.push(frame); // deliver the message if this was the last frame of a message if (part0 == part1) { this.deliverPayload_(this.parts_.join('')); delete this.parts_; } } } else { goog.net.xpc.logger.warning('received msg, but channel is not connected'); } }; /** * Process an incoming acknowdedgement. * @param {string} msgStr The incoming ack string to process. */ goog.net.xpc.IframePollingTransport.prototype.processIncomingAck = function(msgStr) { goog.net.xpc.logger.finest('ack received: ' + msgStr); if (msgStr == goog.net.xpc.SETUP_ACK_) { this.waitForAck_ = false; this.rcvdConnectionSetupAck_ = true; // send the next frame this.checkIfConnected_(); } else if (this.channel_.isConnected()) { if (!this.waitForAck_) { goog.net.xpc.logger.warning('got unexpected ack'); return; } var seq = parseInt(msgStr.split(':')[1], 10); if (seq == this.sequence_) { this.waitForAck_ = false; this.sendNextFrame_(); } else { goog.net.xpc.logger.warning('got ack with wrong sequence'); } } else { goog.net.xpc.logger.warning('received ack, but channel not connected'); } }; /** * Sends a frame (message part). * @private */ goog.net.xpc.IframePollingTransport.prototype.sendNextFrame_ = function() { // do nothing if we are waiting for an acknowledgement or the // queue is emtpy if (this.waitForAck_ || !this.sendQueue_.length) { return; } var s = this.sendQueue_.shift(); ++this.sequence_; this.msgSender_.send(this.sequence_ + s); goog.net.xpc.logger.finest('msg sent: ' + this.sequence_ + s); this.waitForAck_ = true; }; /** * Delivers a message. * @param {string} s The complete message string ("<service_name>:<payload>"). * @private */ goog.net.xpc.IframePollingTransport.prototype.deliverPayload_ = function(s) { // determine the service name and the payload var pos = s.indexOf(':'); var service = s.substr(0, pos); var payload = s.substring(pos + 1); // deliver the message if (!this.channel_.isConnected()) { // as valid messages can come in before a SETUP_ACK has // been received (because subchannels for msgs and acks are independent), // delay delivery of early messages until after 'connect'-event (this.deliveryQueue_ || (this.deliveryQueue_ = [])). push({service: service, payload: payload}); goog.net.xpc.logger.finest('queued delivery'); } else { this.channel_.xpcDeliver(service, payload); } }; // ---- send message ---- /** * Maximal frame length. * @type {number} * @private */ goog.net.xpc.IframePollingTransport.prototype.MAX_FRAME_LENGTH_ = 3800; /** * Sends a message. Splits it in multiple frames if too long (exceeds IE's * URL-length maximum. * Wireformat: <seq>[,<frame_no>/<#frames>]|<frame_content> * * @param {string} service Name of service this the message has to be delivered. * @param {string} payload The message content. * @override */ goog.net.xpc.IframePollingTransport.prototype.send = function(service, payload) { var frame = service + ':' + payload; // put in queue if (!goog.userAgent.IE || payload.length <= this.MAX_FRAME_LENGTH_) { this.sendQueue_.push('|' + frame); } else { var l = payload.length; var num = Math.ceil(l / this.MAX_FRAME_LENGTH_); // number of frames var pos = 0; var i = 1; while (pos < l) { this.sendQueue_.push(',' + i + '/' + num + '|' + frame.substr(pos, this.MAX_FRAME_LENGTH_)); i++; pos += this.MAX_FRAME_LENGTH_; } } this.sendNextFrame_(); }; /** @override */ goog.net.xpc.IframePollingTransport.prototype.disposeInternal = function() { goog.base(this, 'disposeInternal'); var receivers = goog.net.xpc.IframePollingTransport.receivers_; goog.array.remove(receivers, this.msgReceiver_); goog.array.remove(receivers, this.ackReceiver_); this.msgReceiver_ = this.ackReceiver_ = null; goog.dom.removeNode(this.msgIframeElm_); goog.dom.removeNode(this.ackIframeElm_); this.msgIframeElm_ = this.ackIframeElm_ = null; this.msgWinObj_ = this.ackWinObj_ = null; }; /** * Array holding all Receiver-instances. * @type {Array.<goog.net.xpc.IframePollingTransport.Receiver>} * @private */ goog.net.xpc.IframePollingTransport.receivers_ = []; /** * Short polling interval. * @type {number} * @private */ goog.net.xpc.IframePollingTransport.TIME_POLL_SHORT_ = 10; /** * Long polling interval. * @type {number} * @private */ goog.net.xpc.IframePollingTransport.TIME_POLL_LONG_ = 100; /** * Period how long to use TIME_POLL_SHORT_ before raising polling-interval * to TIME_POLL_LONG_ after an activity. * @type {number} * @private */ goog.net.xpc.IframePollingTransport.TIME_SHORT_POLL_AFTER_ACTIVITY_ = 1000; /** * Polls all receivers. * @private */ goog.net.xpc.IframePollingTransport.receive_ = function() { var receivers = goog.net.xpc.IframePollingTransport.receivers_; var receiver; var rcvd = false; /** @preserveTry */ try { for (var i = 0; receiver = receivers[i]; i++) { rcvd = rcvd || receiver.receive(); } } catch (e) { goog.net.xpc.logger.info('receive_() failed: ' + e); // Notify the channel that the transport had an error. receiver.transport_.channel_.notifyTransportError(); // notifyTransportError() closes the channel and disposes the transport. // If there are no other channels present, this.receivers_ will now be empty // and there is no need to keep polling. if (!receivers.length) { return; } } var now = goog.now(); if (rcvd) { goog.net.xpc.IframePollingTransport.lastActivity_ = now; } // Schedule next check. var t = now - goog.net.xpc.IframePollingTransport.lastActivity_ < goog.net.xpc.IframePollingTransport.TIME_SHORT_POLL_AFTER_ACTIVITY_ ? goog.net.xpc.IframePollingTransport.TIME_POLL_SHORT_ : goog.net.xpc.IframePollingTransport.TIME_POLL_LONG_; goog.net.xpc.IframePollingTransport.rcvTimer_ = window.setTimeout( goog.net.xpc.IframePollingTransport.receiveCb_, t); }; /** * Callback that wraps receive_ to be used in timers. * @type {Function} * @private */ goog.net.xpc.IframePollingTransport.receiveCb_ = goog.bind( goog.net.xpc.IframePollingTransport.receive_, goog.net.xpc.IframePollingTransport); /** * Starts the polling loop. * @private */ goog.net.xpc.IframePollingTransport.startRcvTimer_ = function() { goog.net.xpc.logger.fine('starting receive-timer'); goog.net.xpc.IframePollingTransport.lastActivity_ = goog.now(); if (goog.net.xpc.IframePollingTransport.rcvTimer_) { window.clearTimeout(goog.net.xpc.IframePollingTransport.rcvTimer_); } goog.net.xpc.IframePollingTransport.rcvTimer_ = window.setTimeout( goog.net.xpc.IframePollingTransport.receiveCb_, goog.net.xpc.IframePollingTransport.TIME_POLL_SHORT_); }; /** * goog.net.xpc.IframePollingTransport.Sender * * Utility class to send message-parts to a document from a different origin. * * @constructor * @param {string} url The url the other document will use for polling. * @param {Object} windowObj The frame used for sending information to. */ goog.net.xpc.IframePollingTransport.Sender = function(url, windowObj) { /** * The URI used to sending messages. * @type {string} * @private */ this.sendUri_ = url; /** * The window object of the iframe used to send messages. * The script instantiating the Sender won't have access to * the content of sendFrame_. * @type {Object} * @private */ this.sendFrame_ = windowObj; /** * Cycle counter (used to make sure that sending two identical messages sent * in direct succession can be recognized as such by the receiver). * @type {number} * @private */ this.cycle_ = 0; }; /** * Sends a message-part (frame) to the peer. * The message-part is encoded and put in the fragment identifier * of the URL used for sending (and belongs to the origin/domain of the peer). * @param {string} payload The message to send. */ goog.net.xpc.IframePollingTransport.Sender.prototype.send = function(payload) { this.cycle_ = ++this.cycle_ % 2; var url = this.sendUri_ + '#' + this.cycle_ + encodeURIComponent(payload); // TODO(user) Find out if try/catch is still needed /** @preserveTry */ try { // safari doesn't allow to call location.replace() if (goog.userAgent.WEBKIT) { this.sendFrame_.location.href = url; } else { this.sendFrame_.location.replace(url); } } catch (e) { goog.net.xpc.logger.severe('sending failed', e); } // Restart receiver timer on short polling interval, to support use-cases // where we need to capture responses quickly. goog.net.xpc.IframePollingTransport.startRcvTimer_(); }; /** * goog.net.xpc.IframePollingTransport.Receiver * * @constructor * @param {goog.net.xpc.IframePollingTransport} transport The transport to * receive from. * @param {Object} windowObj The window-object to poll for location-changes. * @param {Function} callback The callback-function to be called when * location has changed. */ goog.net.xpc.IframePollingTransport.Receiver = function(transport, windowObj, callback) { /** * The transport to receive from. * @type {goog.net.xpc.IframePollingTransport} * @private */ this.transport_ = transport; this.rcvFrame_ = windowObj; this.cb_ = callback; this.currentLoc_ = this.rcvFrame_.location.href.split('#')[0] + '#INITIAL'; goog.net.xpc.IframePollingTransport.receivers_.push(this); goog.net.xpc.IframePollingTransport.startRcvTimer_(); }; /** * Polls the location of the receiver-frame for changes. * @return {boolean} Whether a change has been detected. */ goog.net.xpc.IframePollingTransport.Receiver.prototype.receive = function() { var loc = this.rcvFrame_.location.href; if (loc != this.currentLoc_) { this.currentLoc_ = loc; var payload = loc.split('#')[1]; if (payload) { payload = payload.substr(1); // discard first character (cycle) this.cb_(decodeURIComponent(payload)); } return true; } else { return false; } };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Contains the NIX (Native IE XDC) method transport for * cross-domain communication. It exploits the fact that Internet Explorer * allows a window that is the parent of an iframe to set said iframe window's * opener property to an object. This object can be a function that in turn * can be used to send a message despite same-origin constraints. Note that * this function, if a pure JavaScript object, opens up the possibilitiy of * gaining a hold of the context of the other window and in turn, attacking * it. This implementation therefore wraps the JavaScript objects used inside * a VBScript class. Since VBScript objects are passed in JavaScript as a COM * wrapper (like DOM objects), they are thus opaque to JavaScript * (except for the interface they expose). This therefore provides a safe * method of transport. * * * Initially based on FrameElementTransport which shares some similarities * to this method. */ goog.provide('goog.net.xpc.NixTransport'); goog.require('goog.net.xpc'); goog.require('goog.net.xpc.CrossPageChannelRole'); goog.require('goog.net.xpc.Transport'); goog.require('goog.reflect'); /** * NIX method transport. * * NOTE(user): NIX method tested in all IE versions starting from 6.0. * * @param {goog.net.xpc.CrossPageChannel} channel The channel this transport * belongs to. * @param {goog.dom.DomHelper=} opt_domHelper The dom helper to use for finding * the correct window. * @constructor * @extends {goog.net.xpc.Transport} */ goog.net.xpc.NixTransport = function(channel, opt_domHelper) { goog.base(this, opt_domHelper); /** * The channel this transport belongs to. * @type {goog.net.xpc.CrossPageChannel} * @private */ this.channel_ = channel; /** * The authorization token, if any, used by this transport. * @type {?string} * @private */ this.authToken_ = channel[goog.net.xpc.CfgFields.AUTH_TOKEN] || ''; /** * The authorization token, if any, that must be sent by the other party * for setup to occur. * @type {?string} * @private */ this.remoteAuthToken_ = channel[goog.net.xpc.CfgFields.REMOTE_AUTH_TOKEN] || ''; // Conduct the setup work for NIX in general, if need be. goog.net.xpc.NixTransport.conductGlobalSetup_(this.getWindow()); // Setup aliases so that VBScript can call these methods // on the transport class, even if they are renamed during // compression. this[goog.net.xpc.NixTransport.NIX_HANDLE_MESSAGE] = this.handleMessage_; this[goog.net.xpc.NixTransport.NIX_CREATE_CHANNEL] = this.createChannel_; }; goog.inherits(goog.net.xpc.NixTransport, goog.net.xpc.Transport); // Consts for NIX. VBScript doesn't allow items to start with _ for some // reason, so we need to make these names quite unique, as they will go into // the global namespace. /** * Global name of the Wrapper VBScript class. * Note that this class will be stored in the *global* * namespace (i.e. window in browsers). * @type {string} */ goog.net.xpc.NixTransport.NIX_WRAPPER = 'GCXPC____NIXVBS_wrapper'; /** * Global name of the GetWrapper VBScript function. This * constant is used by JavaScript to call this function. * Note that this function will be stored in the *global* * namespace (i.e. window in browsers). * @type {string} */ goog.net.xpc.NixTransport.NIX_GET_WRAPPER = 'GCXPC____NIXVBS_get_wrapper'; /** * The name of the handle message method used by the wrapper class * when calling the transport. * @type {string} */ goog.net.xpc.NixTransport.NIX_HANDLE_MESSAGE = 'GCXPC____NIXJS_handle_message'; /** * The name of the create channel method used by the wrapper class * when calling the transport. * @type {string} */ goog.net.xpc.NixTransport.NIX_CREATE_CHANNEL = 'GCXPC____NIXJS_create_channel'; /** * A "unique" identifier that is stored in the wrapper * class so that the wrapper can be distinguished from * other objects easily. * @type {string} */ goog.net.xpc.NixTransport.NIX_ID_FIELD = 'GCXPC____NIXVBS_container'; /** * Determines if the installed version of IE supports accessing window.opener * after it has been set to a non-Window/null value. NIX relies on this being * possible. * @return {boolean} Whether window.opener behavior is compatible with NIX. */ goog.net.xpc.NixTransport.isNixSupported = function() { var isSupported = false; try { var oldOpener = window.opener; // The compiler complains (as it should!) if we set window.opener to // something other than a window or null. window.opener = /** @type {Window} */ ({}); isSupported = goog.reflect.canAccessProperty(window, 'opener'); window.opener = oldOpener; } catch (e) { } return isSupported; }; /** * Conducts the global setup work for the NIX transport method. * This function creates and then injects into the page the * VBScript code necessary to create the NIX wrapper class. * Note that this method can be called multiple times, as * it internally checks whether the work is necessary before * proceeding. * @param {Window} listenWindow The window containing the affected page. * @private */ goog.net.xpc.NixTransport.conductGlobalSetup_ = function(listenWindow) { if (listenWindow['nix_setup_complete']) { return; } // Inject the VBScript code needed. var vbscript = // We create a class to act as a wrapper for // a Javascript call, to prevent a break in of // the context. 'Class ' + goog.net.xpc.NixTransport.NIX_WRAPPER + '\n ' + // An internal member for keeping track of the // transport for which this wrapper exists. 'Private m_Transport\n' + // An internal member for keeping track of the // auth token associated with the context that // created this wrapper. Used for validation // purposes. 'Private m_Auth\n' + // Method for internally setting the value // of the m_Transport property. We have the // isEmpty check to prevent the transport // from being overridden with an illicit // object by a malicious party. 'Public Sub SetTransport(transport)\n' + 'If isEmpty(m_Transport) Then\n' + 'Set m_Transport = transport\n' + 'End If\n' + 'End Sub\n' + // Method for internally setting the value // of the m_Auth property. We have the // isEmpty check to prevent the transport // from being overridden with an illicit // object by a malicious party. 'Public Sub SetAuth(auth)\n' + 'If isEmpty(m_Auth) Then\n' + 'm_Auth = auth\n' + 'End If\n' + 'End Sub\n' + // Returns the auth token to the gadget, so it can // confirm a match before initiating the connection 'Public Function GetAuthToken()\n ' + 'GetAuthToken = m_Auth\n' + 'End Function\n' + // A wrapper method which causes a // message to be sent to the other context. 'Public Sub SendMessage(service, payload)\n ' + 'Call m_Transport.' + goog.net.xpc.NixTransport.NIX_HANDLE_MESSAGE + '(service, payload)\n' + 'End Sub\n' + // Method for setting up the inner->outer // channel. 'Public Sub CreateChannel(channel)\n ' + 'Call m_Transport.' + goog.net.xpc.NixTransport.NIX_CREATE_CHANNEL + '(channel)\n' + 'End Sub\n' + // An empty field with a unique identifier to // prevent the code from confusing this wrapper // with a run-of-the-mill value found in window.opener. 'Public Sub ' + goog.net.xpc.NixTransport.NIX_ID_FIELD + '()\n ' + 'End Sub\n' + 'End Class\n ' + // Function to get a reference to the wrapper. 'Function ' + goog.net.xpc.NixTransport.NIX_GET_WRAPPER + '(transport, auth)\n' + 'Dim wrap\n' + 'Set wrap = New ' + goog.net.xpc.NixTransport.NIX_WRAPPER + '\n' + 'wrap.SetTransport transport\n' + 'wrap.SetAuth auth\n' + 'Set ' + goog.net.xpc.NixTransport.NIX_GET_WRAPPER + ' = wrap\n' + 'End Function'; try { listenWindow.execScript(vbscript, 'vbscript'); listenWindow['nix_setup_complete'] = true; } catch (e) { goog.net.xpc.logger.severe( 'exception caught while attempting global setup: ' + e); } }; /** * The transport type. * @type {number} * @protected * @override */ goog.net.xpc.NixTransport.prototype.transportType = goog.net.xpc.TransportTypes.NIX; /** * Keeps track of whether the local setup has completed (i.e. * the initial work towards setting the channel up has been * completed for this end). * @type {boolean} * @private */ goog.net.xpc.NixTransport.prototype.localSetupCompleted_ = false; /** * The NIX channel used to talk to the other page. This * object is in fact a reference to a VBScript class * (see above) and as such, is in fact a COM wrapper. * When using this object, make sure to not access methods * without calling them, otherwise a COM error will be thrown. * @type {Object} * @private */ goog.net.xpc.NixTransport.prototype.nixChannel_ = null; /** * Connect this transport. * @override */ goog.net.xpc.NixTransport.prototype.connect = function() { if (this.channel_.getRole() == goog.net.xpc.CrossPageChannelRole.OUTER) { this.attemptOuterSetup_(); } else { this.attemptInnerSetup_(); } }; /** * Attempts to setup the channel from the perspective * of the outer (read: container) page. This method * will attempt to create a NIX wrapper for this transport * and place it into the "opener" property of the inner * page's window object. If it fails, it will continue * to loop until it does so. * * @private */ goog.net.xpc.NixTransport.prototype.attemptOuterSetup_ = function() { if (this.localSetupCompleted_) { return; } // Get shortcut to iframe-element that contains the inner // page. var innerFrame = this.channel_.getIframeElement(); try { // Attempt to place the NIX wrapper object into the inner // frame's opener property. var theWindow = this.getWindow(); var getWrapper = theWindow[goog.net.xpc.NixTransport.NIX_GET_WRAPPER]; innerFrame.contentWindow.opener = getWrapper(this, this.authToken_); this.localSetupCompleted_ = true; } catch (e) { goog.net.xpc.logger.severe( 'exception caught while attempting setup: ' + e); } // If the retry is necessary, reattempt this setup. if (!this.localSetupCompleted_) { this.getWindow().setTimeout(goog.bind(this.attemptOuterSetup_, this), 100); } }; /** * Attempts to setup the channel from the perspective * of the inner (read: iframe) page. This method * will attempt to *read* the opener object from the * page's opener property. If it succeeds, this object * is saved into nixChannel_ and the channel is confirmed * with the container by calling CreateChannel with an instance * of a wrapper for *this* page. Note that if this method * fails, it will continue to loop until it succeeds. * * @private */ goog.net.xpc.NixTransport.prototype.attemptInnerSetup_ = function() { if (this.localSetupCompleted_) { return; } try { var opener = this.getWindow().opener; // Ensure that the object contained inside the opener // property is in fact a NIX wrapper. if (opener && goog.net.xpc.NixTransport.NIX_ID_FIELD in opener) { this.nixChannel_ = opener; // Ensure that the NIX channel given to use is valid. var remoteAuthToken = this.nixChannel_['GetAuthToken'](); if (remoteAuthToken != this.remoteAuthToken_) { goog.net.xpc.logger.severe('Invalid auth token from other party'); return; } // Complete the construction of the channel by sending our own // wrapper to the container via the channel they gave us. var theWindow = this.getWindow(); var getWrapper = theWindow[goog.net.xpc.NixTransport.NIX_GET_WRAPPER]; this.nixChannel_['CreateChannel'](getWrapper(this, this.authToken_)); this.localSetupCompleted_ = true; // Notify channel that the transport is ready. this.channel_.notifyConnected(); } } catch (e) { goog.net.xpc.logger.severe( 'exception caught while attempting setup: ' + e); return; } // If the retry is necessary, reattempt this setup. if (!this.localSetupCompleted_) { this.getWindow().setTimeout(goog.bind(this.attemptInnerSetup_, this), 100); } }; /** * Internal method called by the inner page, via the * NIX wrapper, to complete the setup of the channel. * * @param {Object} channel The NIX wrapper of the * inner page. * @private */ goog.net.xpc.NixTransport.prototype.createChannel_ = function(channel) { // Verify that the channel is in fact a NIX wrapper. if (typeof channel != 'unknown' || !(goog.net.xpc.NixTransport.NIX_ID_FIELD in channel)) { goog.net.xpc.logger.severe('Invalid NIX channel given to createChannel_'); } this.nixChannel_ = channel; // Ensure that the NIX channel given to use is valid. var remoteAuthToken = this.nixChannel_['GetAuthToken'](); if (remoteAuthToken != this.remoteAuthToken_) { goog.net.xpc.logger.severe('Invalid auth token from other party'); return; } // Indicate to the CrossPageChannel that the channel is setup // and ready to use. this.channel_.notifyConnected(); }; /** * Internal method called by the other page, via the NIX wrapper, * to deliver a message. * @param {string} serviceName The name of the service the message is to be * delivered to. * @param {string} payload The message to process. * @private */ goog.net.xpc.NixTransport.prototype.handleMessage_ = function(serviceName, payload) { /** @this {goog.net.xpc.NixTransport} */ var deliveryHandler = function() { this.channel_.xpcDeliver(serviceName, payload); }; this.getWindow().setTimeout(goog.bind(deliveryHandler, this), 1); }; /** * Sends a message. * @param {string} service The name of the service the message is to be * delivered to. * @param {string} payload The message content. * @override */ goog.net.xpc.NixTransport.prototype.send = function(service, payload) { // Verify that the NIX channel we have is valid. if (typeof(this.nixChannel_) !== 'unknown') { goog.net.xpc.logger.severe('NIX channel not connected'); } // Send the message via the NIX wrapper object. this.nixChannel_['SendMessage'](service, payload); }; /** @override */ goog.net.xpc.NixTransport.prototype.disposeInternal = function() { goog.base(this, 'disposeInternal'); this.nixChannel_ = null; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides the class CrossPageChannel, the main class in * goog.net.xpc. * * @see ../../demos/xpc/index.html */ goog.provide('goog.net.xpc.CrossPageChannel'); goog.require('goog.Disposable'); goog.require('goog.Uri'); goog.require('goog.async.Deferred'); goog.require('goog.async.Delay'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.events.EventHandler'); goog.require('goog.json'); goog.require('goog.messaging.AbstractChannel'); goog.require('goog.net.xpc'); goog.require('goog.net.xpc.CrossPageChannelRole'); goog.require('goog.net.xpc.FrameElementMethodTransport'); goog.require('goog.net.xpc.IframePollingTransport'); goog.require('goog.net.xpc.IframeRelayTransport'); goog.require('goog.net.xpc.NativeMessagingTransport'); goog.require('goog.net.xpc.NixTransport'); goog.require('goog.net.xpc.Transport'); goog.require('goog.userAgent'); /** * A communication channel between two documents from different domains. * Provides asynchronous messaging. * * @param {Object} cfg Channel configuration object. * @param {goog.dom.DomHelper=} opt_domHelper The optional dom helper to * use for looking up elements in the dom. * @constructor * @extends {goog.messaging.AbstractChannel} */ goog.net.xpc.CrossPageChannel = function(cfg, opt_domHelper) { goog.base(this); for (var i = 0, uriField; uriField = goog.net.xpc.UriCfgFields[i]; i++) { if (uriField in cfg && !/^https?:\/\//.test(cfg[uriField])) { throw Error('URI ' + cfg[uriField] + ' is invalid for field ' + uriField); } } /** * The configuration for this channel. * @type {Object} * @private */ this.cfg_ = cfg; /** * The name of the channel. * @type {string} */ this.name = this.cfg_[goog.net.xpc.CfgFields.CHANNEL_NAME] || goog.net.xpc.getRandomString(10); /** * The dom helper to use for accessing the dom. * @type {goog.dom.DomHelper} * @private */ this.domHelper_ = opt_domHelper || goog.dom.getDomHelper(); /** * Collects deferred function calls which will be made once the connection * has been fully set up. * @type {!Array.<function()>} * @private */ this.deferredDeliveries_ = []; /** * An event handler used to listen for load events on peer iframes. * @type {!goog.events.EventHandler} * @private */ this.peerLoadHandler_ = new goog.events.EventHandler(this); // If LOCAL_POLL_URI or PEER_POLL_URI is not available, try using // robots.txt from that host. cfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] = cfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] || goog.uri.utils.getHost(this.domHelper_.getWindow().location.href) + '/robots.txt'; // PEER_URI is sometimes undefined in tests. cfg[goog.net.xpc.CfgFields.PEER_POLL_URI] = cfg[goog.net.xpc.CfgFields.PEER_POLL_URI] || goog.uri.utils.getHost(cfg[goog.net.xpc.CfgFields.PEER_URI] || '') + '/robots.txt'; goog.net.xpc.channels[this.name] = this; goog.events.listen(window, 'unload', goog.net.xpc.CrossPageChannel.disposeAll_); goog.net.xpc.logger.info('CrossPageChannel created: ' + this.name); }; goog.inherits(goog.net.xpc.CrossPageChannel, goog.messaging.AbstractChannel); /** * Regexp for escaping service names. * @type {RegExp} * @private */ goog.net.xpc.CrossPageChannel.TRANSPORT_SERVICE_ESCAPE_RE_ = new RegExp('^%*' + goog.net.xpc.TRANSPORT_SERVICE_ + '$'); /** * Regexp for unescaping service names. * @type {RegExp} * @private */ goog.net.xpc.CrossPageChannel.TRANSPORT_SERVICE_UNESCAPE_RE_ = new RegExp('^%+' + goog.net.xpc.TRANSPORT_SERVICE_ + '$'); /** * A delay between the transport reporting as connected and the calling of the * connection callback. Sometimes used to paper over timing vulnerabilities. * @type {goog.async.Delay} * @private */ goog.net.xpc.CrossPageChannel.prototype.connectionDelay_ = null; /** * A deferred which is set to non-null while a peer iframe is being created * but has not yet thrown its load event, and which fires when that load event * arrives. * @type {goog.async.Deferred} * @private */ goog.net.xpc.CrossPageChannel.prototype.peerWindowDeferred_ = null; /** * The transport. * @type {goog.net.xpc.Transport?} * @private */ goog.net.xpc.CrossPageChannel.prototype.transport_ = null; /** * The channel state. * @type {number} * @private */ goog.net.xpc.CrossPageChannel.prototype.state_ = goog.net.xpc.ChannelStates.NOT_CONNECTED; /** * @override * @return {boolean} Whether the channel is connected. */ goog.net.xpc.CrossPageChannel.prototype.isConnected = function() { return this.state_ == goog.net.xpc.ChannelStates.CONNECTED; }; /** * Reference to the window-object of the peer page. * @type {Object} * @private */ goog.net.xpc.CrossPageChannel.prototype.peerWindowObject_ = null; /** * Reference to the iframe-element. * @type {Object} * @private */ goog.net.xpc.CrossPageChannel.prototype.iframeElement_ = null; /** * Returns the configuration object for this channel. * Package private. Do not call from outside goog.net.xpc. * * @return {Object} The configuration object for this channel. */ goog.net.xpc.CrossPageChannel.prototype.getConfig = function() { return this.cfg_; }; /** * Returns a reference to the iframe-element. * Package private. Do not call from outside goog.net.xpc. * * @return {Object} A reference to the iframe-element. */ goog.net.xpc.CrossPageChannel.prototype.getIframeElement = function() { return this.iframeElement_; }; /** * Sets the window object the foreign document resides in. * * @param {Object} peerWindowObject The window object of the peer. */ goog.net.xpc.CrossPageChannel.prototype.setPeerWindowObject = function(peerWindowObject) { this.peerWindowObject_ = peerWindowObject; }; /** * Returns the window object the foreign document resides in. * Package private. Do not call from outside goog.net.xpc. * * @return {Object} The window object of the peer. */ goog.net.xpc.CrossPageChannel.prototype.getPeerWindowObject = function() { return this.peerWindowObject_; }; /** * Determines whether the peer window is available (e.g. not closed). * Package private. Do not call from outside goog.net.xpc. * * @return {boolean} Whether the peer window is available. */ goog.net.xpc.CrossPageChannel.prototype.isPeerAvailable = function() { // NOTE(user): This check is not reliable in IE, where a document in an // iframe does not get unloaded when removing the iframe element from the DOM. // TODO(user): Find something that works in IE as well. // NOTE(user): "!this.peerWindowObject_.closed" evaluates to 'false' in IE9 // sometimes even though typeof(this.peerWindowObject_.closed) is boolean and // this.peerWindowObject_.closed evaluates to 'false'. Casting it to a Boolean // results in sane evaluation. When this happens, it's in the inner iframe // when querying its parent's 'closed' status. Note that this is a different // case than mibuerge@'s note above. try { return !!this.peerWindowObject_ && !Boolean(this.peerWindowObject_.closed); } catch (e) { // If the window is closing, an error may be thrown. return false; } }; /** * Determine which transport type to use for this channel / useragent. * @return {goog.net.xpc.TransportTypes|undefined} The best transport type. * @private */ goog.net.xpc.CrossPageChannel.prototype.determineTransportType_ = function() { var transportType; if (goog.isFunction(document.postMessage) || goog.isFunction(window.postMessage) || // IE8 supports window.postMessage, but // typeof window.postMessage returns "object" (goog.userAgent.IE && window.postMessage)) { transportType = goog.net.xpc.TransportTypes.NATIVE_MESSAGING; } else if (goog.userAgent.GECKO) { transportType = goog.net.xpc.TransportTypes.FRAME_ELEMENT_METHOD; } else if (goog.userAgent.IE && this.cfg_[goog.net.xpc.CfgFields.PEER_RELAY_URI]) { transportType = goog.net.xpc.TransportTypes.IFRAME_RELAY; } else if (goog.userAgent.IE && goog.net.xpc.NixTransport.isNixSupported()) { transportType = goog.net.xpc.TransportTypes.NIX; } else { transportType = goog.net.xpc.TransportTypes.IFRAME_POLLING; } return transportType; }; /** * Creates the transport for this channel. Chooses from the available * transport based on the user agent and the configuration. * @private */ goog.net.xpc.CrossPageChannel.prototype.createTransport_ = function() { // return, if the transport has already been created if (this.transport_) { return; } if (!this.cfg_[goog.net.xpc.CfgFields.TRANSPORT]) { this.cfg_[goog.net.xpc.CfgFields.TRANSPORT] = this.determineTransportType_(); } switch (this.cfg_[goog.net.xpc.CfgFields.TRANSPORT]) { case goog.net.xpc.TransportTypes.NATIVE_MESSAGING: var protocolVersion = this.cfg_[ goog.net.xpc.CfgFields.NATIVE_TRANSPORT_PROTOCOL_VERSION] || 2; this.transport_ = new goog.net.xpc.NativeMessagingTransport( this, this.cfg_[goog.net.xpc.CfgFields.PEER_HOSTNAME], this.domHelper_, !!this.cfg_[goog.net.xpc.CfgFields.ONE_SIDED_HANDSHAKE], protocolVersion); break; case goog.net.xpc.TransportTypes.NIX: this.transport_ = new goog.net.xpc.NixTransport(this, this.domHelper_); break; case goog.net.xpc.TransportTypes.FRAME_ELEMENT_METHOD: this.transport_ = new goog.net.xpc.FrameElementMethodTransport(this, this.domHelper_); break; case goog.net.xpc.TransportTypes.IFRAME_RELAY: this.transport_ = new goog.net.xpc.IframeRelayTransport(this, this.domHelper_); break; case goog.net.xpc.TransportTypes.IFRAME_POLLING: this.transport_ = new goog.net.xpc.IframePollingTransport(this, this.domHelper_); break; } if (this.transport_) { goog.net.xpc.logger.info('Transport created: ' + this.transport_.getName()); } else { throw Error('CrossPageChannel: No suitable transport found!'); } }; /** * Returns the transport type in use for this channel. * @return {number} Transport-type identifier. */ goog.net.xpc.CrossPageChannel.prototype.getTransportType = function() { return this.transport_.getType(); }; /** * Returns the tranport name in use for this channel. * @return {string} The transport name. */ goog.net.xpc.CrossPageChannel.prototype.getTransportName = function() { return this.transport_.getName(); }; /** * @return {Object} Configuration-object to be used by the peer to * initialize the channel. */ goog.net.xpc.CrossPageChannel.prototype.getPeerConfiguration = function() { var peerCfg = {}; peerCfg[goog.net.xpc.CfgFields.CHANNEL_NAME] = this.name; peerCfg[goog.net.xpc.CfgFields.TRANSPORT] = this.cfg_[goog.net.xpc.CfgFields.TRANSPORT]; peerCfg[goog.net.xpc.CfgFields.ONE_SIDED_HANDSHAKE] = this.cfg_[goog.net.xpc.CfgFields.ONE_SIDED_HANDSHAKE]; if (this.cfg_[goog.net.xpc.CfgFields.LOCAL_RELAY_URI]) { peerCfg[goog.net.xpc.CfgFields.PEER_RELAY_URI] = this.cfg_[goog.net.xpc.CfgFields.LOCAL_RELAY_URI]; } if (this.cfg_[goog.net.xpc.CfgFields.LOCAL_POLL_URI]) { peerCfg[goog.net.xpc.CfgFields.PEER_POLL_URI] = this.cfg_[goog.net.xpc.CfgFields.LOCAL_POLL_URI]; } if (this.cfg_[goog.net.xpc.CfgFields.PEER_POLL_URI]) { peerCfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] = this.cfg_[goog.net.xpc.CfgFields.PEER_POLL_URI]; } var role = this.cfg_[goog.net.xpc.CfgFields.ROLE]; if (role) { peerCfg[goog.net.xpc.CfgFields.ROLE] = role == goog.net.xpc.CrossPageChannelRole.INNER ? goog.net.xpc.CrossPageChannelRole.OUTER : goog.net.xpc.CrossPageChannelRole.INNER; } return peerCfg; }; /** * Creates the iframe containing the peer page in a specified parent element. * This method does not connect the channel, connect() still has to be called * separately. * * @param {!Element} parentElm The container element the iframe is appended to. * @param {Function=} opt_configureIframeCb If present, this function gets * called with the iframe element as parameter to allow setting properties * on it before it gets added to the DOM. If absent, the iframe's width and * height are set to '100%'. * @param {boolean=} opt_addCfgParam Whether to add the peer configuration as * URL parameter (default: true). * @return {!HTMLIFrameElement} The iframe element. */ goog.net.xpc.CrossPageChannel.prototype.createPeerIframe = function( parentElm, opt_configureIframeCb, opt_addCfgParam) { goog.net.xpc.logger.info('createPeerIframe()'); var iframeId = this.cfg_[goog.net.xpc.CfgFields.IFRAME_ID]; if (!iframeId) { // Create a randomized ID for the iframe element to avoid // bfcache-related issues. iframeId = this.cfg_[goog.net.xpc.CfgFields.IFRAME_ID] = 'xpcpeer' + goog.net.xpc.getRandomString(4); } // TODO(user) Opera creates a history-entry when creating an iframe // programmatically as follows. Find a way which avoids this. var iframeElm = goog.dom.getDomHelper(parentElm).createElement('IFRAME'); iframeElm.id = iframeElm.name = iframeId; if (opt_configureIframeCb) { opt_configureIframeCb(iframeElm); } else { iframeElm.style.width = iframeElm.style.height = '100%'; } this.cleanUpIncompleteConnection_(); this.peerWindowDeferred_ = new goog.async.Deferred(undefined, this); var peerUri = this.getPeerUri(opt_addCfgParam); this.peerLoadHandler_.listenOnce(iframeElm, 'load', this.peerWindowDeferred_.callback, false, this.peerWindowDeferred_); if (goog.userAgent.GECKO || goog.userAgent.WEBKIT) { // Appending the iframe in a timeout to avoid a weird fastback issue, which // is present in Safari and Gecko. window.setTimeout( goog.bind(function() { parentElm.appendChild(iframeElm); iframeElm.src = peerUri.toString(); goog.net.xpc.logger.info('peer iframe created (' + iframeId + ')'); }, this), 1); } else { iframeElm.src = peerUri.toString(); parentElm.appendChild(iframeElm); goog.net.xpc.logger.info('peer iframe created (' + iframeId + ')'); } return /** @type {!HTMLIFrameElement} */ (iframeElm); }; /** * Clean up after any incomplete attempt to establish and connect to a peer * iframe. * @private */ goog.net.xpc.CrossPageChannel.prototype.cleanUpIncompleteConnection_ = function() { if (this.peerWindowDeferred_) { this.peerWindowDeferred_.cancel(); this.peerWindowDeferred_ = null; } this.deferredDeliveries_.length = 0; this.peerLoadHandler_.removeAll(); }; /** * Returns the peer URI, with an optional URL parameter for configuring the peer * window. * * @param {boolean=} opt_addCfgParam Whether to add the peer configuration as * URL parameter (default: true). * @return {!goog.Uri} The peer URI. */ goog.net.xpc.CrossPageChannel.prototype.getPeerUri = function(opt_addCfgParam) { var peerUri = this.cfg_[goog.net.xpc.CfgFields.PEER_URI]; if (goog.isString(peerUri)) { peerUri = this.cfg_[goog.net.xpc.CfgFields.PEER_URI] = new goog.Uri(peerUri); } // Add the channel configuration used by the peer as URL parameter. if (opt_addCfgParam !== false) { peerUri.setParameterValue('xpc', goog.json.serialize( this.getPeerConfiguration())); } return peerUri; }; /** * Initiates connecting the channel. When this method is called, all the * information needed to connect the channel has to be available. * * @override * @param {Function=} opt_connectCb The function to be called when the * channel has been connected and is ready to be used. */ goog.net.xpc.CrossPageChannel.prototype.connect = function(opt_connectCb) { this.connectCb_ = opt_connectCb || goog.nullFunction; // If we know of a peer window whose creation has been requested but is not // complete, peerWindowDeferred_ will be non-null, and we should block on it. if (this.peerWindowDeferred_) { this.peerWindowDeferred_.addCallback(this.continueConnection_); } else { this.continueConnection_(); } }; /** * Continues the connection process once we're as sure as we can be that the * peer iframe has been created. * @private */ goog.net.xpc.CrossPageChannel.prototype.continueConnection_ = function() { goog.net.xpc.logger.info('continueConnection_()'); this.peerWindowDeferred_ = null; if (this.cfg_[goog.net.xpc.CfgFields.IFRAME_ID]) { this.iframeElement_ = this.domHelper_.getElement( this.cfg_[goog.net.xpc.CfgFields.IFRAME_ID]); } if (this.iframeElement_) { var winObj = this.iframeElement_.contentWindow; // accessing the window using contentWindow doesn't work in safari if (!winObj) { winObj = window.frames[this.cfg_[goog.net.xpc.CfgFields.IFRAME_ID]]; } this.setPeerWindowObject(winObj); } // if the peer window object has not been set at this point, we assume // being in an iframe and the channel is meant to be to the containing page if (!this.peerWindowObject_) { // throw an error if we are in the top window (== not in an iframe) if (window == window.top) { throw Error( "CrossPageChannel: Can't connect, peer window-object not set."); } else { this.setPeerWindowObject(window.parent); } } this.createTransport_(); this.transport_.connect(); // Now we run any deferred deliveries collected while connection was deferred. while (this.deferredDeliveries_.length > 0) { this.deferredDeliveries_.shift()(); } }; /** * Closes the channel. */ goog.net.xpc.CrossPageChannel.prototype.close = function() { this.cleanUpIncompleteConnection_(); this.state_ = goog.net.xpc.ChannelStates.CLOSED; goog.dispose(this.transport_); this.transport_ = null; this.connectCb_ = null; goog.dispose(this.connectionDelay_); this.connectionDelay_ = null; goog.net.xpc.logger.info('Channel "' + this.name + '" closed'); }; /** * Package-private. * Called by the transport when the channel is connected. * @param {number=} opt_delay Delay this number of milliseconds before calling * the connection callback. Usage is discouraged, but can be used to paper * over timing vulnerabilities when there is no alternative. */ goog.net.xpc.CrossPageChannel.prototype.notifyConnected = function(opt_delay) { if (this.isConnected() || (this.connectionDelay_ && this.connectionDelay_.isActive())) { return; } this.state_ = goog.net.xpc.ChannelStates.CONNECTED; goog.net.xpc.logger.info('Channel "' + this.name + '" connected'); goog.dispose(this.connectionDelay_); if (opt_delay) { this.connectionDelay_ = new goog.async.Delay(this.connectCb_, opt_delay); this.connectionDelay_.start(); } else { this.connectionDelay_ = null; this.connectCb_(); } }; /** * Alias for notifyConected, for backward compatibility reasons. * @private */ goog.net.xpc.CrossPageChannel.prototype.notifyConnected_ = goog.net.xpc.CrossPageChannel.prototype.notifyConnected; /** * Called by the transport in case of an unrecoverable failure. * Package private. Do not call from outside goog.net.xpc. */ goog.net.xpc.CrossPageChannel.prototype.notifyTransportError = function() { goog.net.xpc.logger.info('Transport Error'); this.close(); }; /** @override */ goog.net.xpc.CrossPageChannel.prototype.send = function(serviceName, payload) { if (!this.isConnected()) { goog.net.xpc.logger.severe('Can\'t send. Channel not connected.'); return; } // Check if the peer is still around. if (!this.isPeerAvailable()) { goog.net.xpc.logger.severe('Peer has disappeared.'); this.close(); return; } if (goog.isObject(payload)) { payload = goog.json.serialize(payload); } // Partially URL-encode the service name because some characters (: and |) are // used as delimiters for some transports, and we want to allow those // characters in service names. this.transport_.send(this.escapeServiceName_(serviceName), payload); }; /** * Delivers messages to the appropriate service-handler. Named xpcDeliver to * avoid name conflict with {@code deliver} function in superclass * goog.messaging.AbstractChannel. * * Package private. Do not call from outside goog.net.xpc. * * @param {string} serviceName The name of the port. * @param {string} payload The payload. * @param {string=} opt_origin An optional origin for the message, where the * underlying transport makes that available. If this is specified, and * the PEER_HOSTNAME parameter was provided, they must match or the message * will be rejected. */ goog.net.xpc.CrossPageChannel.prototype.xpcDeliver = function( serviceName, payload, opt_origin) { // This check covers the very rare (but producable) case where the inner frame // becomes ready and sends its setup message while the outer frame is // deferring its connect method waiting for the inner frame to be ready. The // resulting deferral ensures the message will not be processed until the // channel is fully configured. if (this.peerWindowDeferred_) { this.deferredDeliveries_.push( goog.bind(this.xpcDeliver, this, serviceName, payload, opt_origin)); return; } // Check whether the origin of the message is as expected. if (!this.isMessageOriginAcceptable_(opt_origin)) { goog.net.xpc.logger.warning('Message received from unapproved origin "' + opt_origin + '" - rejected.'); return; } if (this.isDisposed()) { goog.net.xpc.logger.warning('CrossPageChannel::xpcDeliver(): Disposed.'); } else if (!serviceName || serviceName == goog.net.xpc.TRANSPORT_SERVICE_) { this.transport_.transportServiceHandler(payload); } else { // only deliver messages if connected if (this.isConnected()) { this.deliver(this.unescapeServiceName_(serviceName), payload); } else { goog.net.xpc.logger.info( 'CrossPageChannel::xpcDeliver(): Not connected.'); } } }; /** * Escape the user-provided service name for sending across the channel. This * URL-encodes certain special characters so they don't conflict with delimiters * used by some of the transports, and adds a special prefix if the name * conflicts with the reserved transport service name. * * This is the opposite of {@link #unescapeServiceName_}. * * @param {string} name The name of the service to escape. * @return {string} The escaped service name. * @private */ goog.net.xpc.CrossPageChannel.prototype.escapeServiceName_ = function(name) { if (goog.net.xpc.CrossPageChannel.TRANSPORT_SERVICE_ESCAPE_RE_.test(name)) { name = '%' + name; } return name.replace(/[%:|]/g, encodeURIComponent); }; /** * Unescape the escaped service name that was sent across the channel. This is * the opposite of {@link #escapeServiceName_}. * * @param {string} name The name of the service to unescape. * @return {string} The unescaped service name. * @private */ goog.net.xpc.CrossPageChannel.prototype.unescapeServiceName_ = function(name) { name = name.replace(/%[0-9a-f]{2}/gi, decodeURIComponent); if (goog.net.xpc.CrossPageChannel.TRANSPORT_SERVICE_UNESCAPE_RE_.test(name)) { return name.substring(1); } else { return name; } }; /** * Returns the role of this channel (either inner or outer). * @return {number} The role of this channel. */ goog.net.xpc.CrossPageChannel.prototype.getRole = function() { var role = this.cfg_[goog.net.xpc.CfgFields.ROLE]; if (role) { return role; } else { return window.parent == this.peerWindowObject_ ? goog.net.xpc.CrossPageChannelRole.INNER : goog.net.xpc.CrossPageChannelRole.OUTER; } }; /** * Returns whether an incoming message with the given origin is acceptable. * If an incoming request comes with a specified (non-empty) origin, and the * PEER_HOSTNAME config parameter has also been provided, the two must match, * or the message is unacceptable. * @param {string=} opt_origin The origin associated with the incoming message. * @return {boolean} Whether the message is acceptable. * @private */ goog.net.xpc.CrossPageChannel.prototype.isMessageOriginAcceptable_ = function( opt_origin) { var peerHostname = this.cfg_[goog.net.xpc.CfgFields.PEER_HOSTNAME]; return goog.string.isEmptySafe(opt_origin) || goog.string.isEmptySafe(peerHostname) || opt_origin == this.cfg_[goog.net.xpc.CfgFields.PEER_HOSTNAME]; }; /** @override */ goog.net.xpc.CrossPageChannel.prototype.disposeInternal = function() { this.close(); this.peerWindowObject_ = null; this.iframeElement_ = null; delete goog.net.xpc.channels[this.name]; goog.dispose(this.peerLoadHandler_); delete this.peerLoadHandler_; goog.base(this, 'disposeInternal'); }; /** * Disposes all channels. * @private */ goog.net.xpc.CrossPageChannel.disposeAll_ = function() { for (var name in goog.net.xpc.channels) { goog.dispose(goog.net.xpc.channels[name]); } };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Contains the iframe relay tranport. */ goog.provide('goog.net.xpc.IframeRelayTransport'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.net.xpc'); goog.require('goog.net.xpc.Transport'); goog.require('goog.userAgent'); /** * Iframe relay transport. Creates hidden iframes containing a document * from the peer's origin. Data is transferred in the fragment identifier. * Therefore the document loaded in the iframes can be served from the * browser's cache. * * @param {goog.net.xpc.CrossPageChannel} channel The channel this * transport belongs to. * @param {goog.dom.DomHelper=} opt_domHelper The dom helper to use for finding * the correct window. * @constructor * @extends {goog.net.xpc.Transport} */ goog.net.xpc.IframeRelayTransport = function(channel, opt_domHelper) { goog.base(this, opt_domHelper); /** * The channel this transport belongs to. * @type {goog.net.xpc.CrossPageChannel} * @private */ this.channel_ = channel; /** * The URI used to relay data to the peer. * @type {string} * @private */ this.peerRelayUri_ = this.channel_.getConfig()[goog.net.xpc.CfgFields.PEER_RELAY_URI]; /** * The id of the iframe the peer page lives in. * @type {string} * @private */ this.peerIframeId_ = this.channel_.getConfig()[goog.net.xpc.CfgFields.IFRAME_ID]; if (goog.userAgent.WEBKIT) { goog.net.xpc.IframeRelayTransport.startCleanupTimer_(); } }; goog.inherits(goog.net.xpc.IframeRelayTransport, goog.net.xpc.Transport); if (goog.userAgent.WEBKIT) { /** * Array to keep references to the relay-iframes. Used only if * there is no way to detect when the iframes are loaded. In that * case the relay-iframes are removed after a timeout. * @type {Array.<Object>} * @private */ goog.net.xpc.IframeRelayTransport.iframeRefs_ = []; /** * Interval at which iframes are destroyed. * @type {number} * @private */ goog.net.xpc.IframeRelayTransport.CLEANUP_INTERVAL_ = 1000; /** * Time after which a relay-iframe is destroyed. * @type {number} * @private */ goog.net.xpc.IframeRelayTransport.IFRAME_MAX_AGE_ = 3000; /** * The cleanup timer id. * @type {number} * @private */ goog.net.xpc.IframeRelayTransport.cleanupTimer_ = 0; /** * Starts the cleanup timer. * @private */ goog.net.xpc.IframeRelayTransport.startCleanupTimer_ = function() { if (!goog.net.xpc.IframeRelayTransport.cleanupTimer_) { goog.net.xpc.IframeRelayTransport.cleanupTimer_ = window.setTimeout( function() { goog.net.xpc.IframeRelayTransport.cleanup_(); }, goog.net.xpc.IframeRelayTransport.CLEANUP_INTERVAL_); } }; /** * Remove all relay-iframes which are older than the maximal age. * @param {number=} opt_maxAge The maximal age in milliseconds. * @private */ goog.net.xpc.IframeRelayTransport.cleanup_ = function(opt_maxAge) { var now = goog.now(); var maxAge = opt_maxAge || goog.net.xpc.IframeRelayTransport.IFRAME_MAX_AGE_; while (goog.net.xpc.IframeRelayTransport.iframeRefs_.length && now - goog.net.xpc.IframeRelayTransport.iframeRefs_[0].timestamp >= maxAge) { var ifr = goog.net.xpc.IframeRelayTransport.iframeRefs_. shift().iframeElement; goog.dom.removeNode(ifr); goog.net.xpc.logger.finest('iframe removed'); } goog.net.xpc.IframeRelayTransport.cleanupTimer_ = window.setTimeout( goog.net.xpc.IframeRelayTransport.cleanupCb_, goog.net.xpc.IframeRelayTransport.CLEANUP_INTERVAL_); }; /** * Function which wraps cleanup_(). * @private */ goog.net.xpc.IframeRelayTransport.cleanupCb_ = function() { goog.net.xpc.IframeRelayTransport.cleanup_(); }; } /** * Maximum sendable size of a payload via a single iframe in IE. * @type {number} * @private */ goog.net.xpc.IframeRelayTransport.IE_PAYLOAD_MAX_SIZE_ = 1800; /** * @typedef {{fragments: !Array.<string>, received: number, expected: number}} */ goog.net.xpc.IframeRelayTransport.FragmentInfo; /** * Used to track incoming payload fragments. The implementation can process * incoming fragments from several channels at a time, even if data is * out-of-order or interleaved. * * @type {!Object.<string, !goog.net.xpc.IframeRelayTransport.FragmentInfo>} * @private */ goog.net.xpc.IframeRelayTransport.fragmentMap_ = {}; /** * The transport type. * @type {number} * @override */ goog.net.xpc.IframeRelayTransport.prototype.transportType = goog.net.xpc.TransportTypes.IFRAME_RELAY; /** * Connects this transport. * @override */ goog.net.xpc.IframeRelayTransport.prototype.connect = function() { if (!this.getWindow()['xpcRelay']) { this.getWindow()['xpcRelay'] = goog.net.xpc.IframeRelayTransport.receiveMessage_; } this.send(goog.net.xpc.TRANSPORT_SERVICE_, goog.net.xpc.SETUP); }; /** * Processes an incoming message. * * @param {string} channelName The name of the channel. * @param {string} frame The raw frame content. * @private */ goog.net.xpc.IframeRelayTransport.receiveMessage_ = function(channelName, frame) { var pos = frame.indexOf(':'); var header = frame.substr(0, pos); var payload = frame.substr(pos + 1); if (!goog.userAgent.IE || (pos = header.indexOf('|')) == -1) { // First, the easy case. var service = header; } else { // There was a fragment id in the header, so this is a message // fragment, not a whole message. var service = header.substr(0, pos); var fragmentIdStr = header.substr(pos + 1); // Separate the message id string and the fragment number. Note that // there may be a single leading + in the argument to parseInt, but // this is harmless. pos = fragmentIdStr.indexOf('+'); var messageIdStr = fragmentIdStr.substr(0, pos); var fragmentNum = parseInt(fragmentIdStr.substr(pos + 1), 10); var fragmentInfo = goog.net.xpc.IframeRelayTransport.fragmentMap_[messageIdStr]; if (!fragmentInfo) { fragmentInfo = goog.net.xpc.IframeRelayTransport.fragmentMap_[messageIdStr] = {fragments: [], received: 0, expected: 0}; } if (goog.string.contains(fragmentIdStr, '++')) { fragmentInfo.expected = fragmentNum + 1; } fragmentInfo.fragments[fragmentNum] = payload; fragmentInfo.received++; if (fragmentInfo.received != fragmentInfo.expected) { return; } // We've received all outstanding fragments; combine what we've received // into payload and fall out to the call to xpcDeliver. payload = fragmentInfo.fragments.join(''); delete goog.net.xpc.IframeRelayTransport.fragmentMap_[messageIdStr]; } goog.net.xpc.channels[channelName]. xpcDeliver(service, decodeURIComponent(payload)); }; /** * Handles transport service messages (internal signalling). * @param {string} payload The message content. * @override */ goog.net.xpc.IframeRelayTransport.prototype.transportServiceHandler = function(payload) { if (payload == goog.net.xpc.SETUP) { // TODO(user) Safari swallows the SETUP_ACK from the iframe to the // container after hitting reload. this.send(goog.net.xpc.TRANSPORT_SERVICE_, goog.net.xpc.SETUP_ACK_); this.channel_.notifyConnected(); } else if (payload == goog.net.xpc.SETUP_ACK_) { this.channel_.notifyConnected(); } }; /** * Sends a message. * * @param {string} service Name of service this the message has to be delivered. * @param {string} payload The message content. * @override */ goog.net.xpc.IframeRelayTransport.prototype.send = function(service, payload) { // If we're on IE and the post-encoding payload is large, split it // into multiple payloads and send each one separately. Otherwise, // just send the whole thing. var encodedPayload = encodeURIComponent(payload); var encodedLen = encodedPayload.length; var maxSize = goog.net.xpc.IframeRelayTransport.IE_PAYLOAD_MAX_SIZE_; if (goog.userAgent.IE && encodedLen > maxSize) { // A probabilistically-unique string used to link together all fragments // in this message. var messageIdStr = goog.string.getRandomString(); for (var startIndex = 0, fragmentNum = 0; startIndex < encodedLen; fragmentNum++) { var payloadFragment = encodedPayload.substr(startIndex, maxSize); startIndex += maxSize; var fragmentIdStr = messageIdStr + (startIndex >= encodedLen ? '++' : '+') + fragmentNum; this.send_(service, payloadFragment, fragmentIdStr); } } else { this.send_(service, encodedPayload); } }; /** * Sends an encoded message or message fragment. * @param {string} service Name of service this the message has to be delivered. * @param {string} encodedPayload The message content, URI encoded. * @param {string=} opt_fragmentIdStr If sending a fragment, a string that * identifies the fragment. * @private */ goog.net.xpc.IframeRelayTransport.prototype.send_ = function(service, encodedPayload, opt_fragmentIdStr) { // IE requires that we create the onload attribute inline, otherwise the // handler is not triggered if (goog.userAgent.IE) { var div = this.getWindow().document.createElement('div'); div.innerHTML = '<iframe onload="this.xpcOnload()"></iframe>'; var ifr = div.childNodes[0]; div = null; ifr['xpcOnload'] = goog.net.xpc.IframeRelayTransport.iframeLoadHandler_; } else { var ifr = this.getWindow().document.createElement('iframe'); if (goog.userAgent.WEBKIT) { // safari doesn't fire load-events on iframes. // keep a reference and remove after a timeout. goog.net.xpc.IframeRelayTransport.iframeRefs_.push({ timestamp: goog.now(), iframeElement: ifr }); } else { goog.events.listen(ifr, 'load', goog.net.xpc.IframeRelayTransport.iframeLoadHandler_); } } var style = ifr.style; style.visibility = 'hidden'; style.width = ifr.style.height = '0px'; style.position = 'absolute'; var url = this.peerRelayUri_; url += '#' + this.channel_.name; if (this.peerIframeId_) { url += ',' + this.peerIframeId_; } url += '|' + service; if (opt_fragmentIdStr) { url += '|' + opt_fragmentIdStr; } url += ':' + encodedPayload; ifr.src = url; this.getWindow().document.body.appendChild(ifr); goog.net.xpc.logger.finest('msg sent: ' + url); }; /** * The iframe load handler. Gets called as method on the iframe element. * @private * @this Element */ goog.net.xpc.IframeRelayTransport.iframeLoadHandler_ = function() { goog.net.xpc.logger.finest('iframe-load'); goog.dom.removeNode(this); this.xpcOnload = null; }; /** @override */ goog.net.xpc.IframeRelayTransport.prototype.disposeInternal = function() { goog.base(this, 'disposeInternal'); if (goog.userAgent.WEBKIT) { goog.net.xpc.IframeRelayTransport.cleanup_(0); } };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Contains the class which uses native messaging * facilities for cross domain communication. * */ goog.provide('goog.net.xpc.NativeMessagingTransport'); goog.require('goog.Timer'); goog.require('goog.asserts'); goog.require('goog.async.Deferred'); goog.require('goog.events'); goog.require('goog.events.EventHandler'); goog.require('goog.net.xpc'); goog.require('goog.net.xpc.CrossPageChannelRole'); goog.require('goog.net.xpc.Transport'); /** * The native messaging transport * * Uses document.postMessage() to send messages to other documents. * Receiving is done by listening on 'message'-events on the document. * * @param {goog.net.xpc.CrossPageChannel} channel The channel this * transport belongs to. * @param {string} peerHostname The hostname (protocol, domain, and port) of the * peer. * @param {goog.dom.DomHelper=} opt_domHelper The dom helper to use for * finding the correct window/document. * @param {boolean=} opt_oneSidedHandshake If this is true, only the outer * transport sends a SETUP message and expects a SETUP_ACK. The inner * transport goes connected when it receives the SETUP. * @param {number=} opt_protocolVersion Which version of its setup protocol the * transport should use. The default is '2'. * @constructor * @extends {goog.net.xpc.Transport} */ goog.net.xpc.NativeMessagingTransport = function(channel, peerHostname, opt_domHelper, opt_oneSidedHandshake, opt_protocolVersion) { goog.base(this, opt_domHelper); /** * The channel this transport belongs to. * @type {goog.net.xpc.CrossPageChannel} * @private */ this.channel_ = channel; /** * Which version of the transport's protocol should be used. * @type {number} * @private */ this.protocolVersion_ = opt_protocolVersion || 2; goog.asserts.assert(this.protocolVersion_ >= 1); goog.asserts.assert(this.protocolVersion_ <= 2); /** * The hostname of the peer. This parameterizes all calls to postMessage, and * should contain the precise protocol, domain, and port of the peer window. * @type {string} * @private */ this.peerHostname_ = peerHostname || '*'; /** * The event handler. * @type {!goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); /** * Timer for connection reattempts. * @type {!goog.Timer} * @private */ this.maybeAttemptToConnectTimer_ = new goog.Timer(100, this.getWindow()); /** * Whether one-sided handshakes are enabled. * @type {boolean} * @private */ this.oneSidedHandshake_ = !!opt_oneSidedHandshake; /** * Fires once we've received our SETUP_ACK message. * @type {!goog.async.Deferred} * @private */ this.setupAckReceived_ = new goog.async.Deferred(); /** * Fires once we've sent our SETUP_ACK message. * @type {!goog.async.Deferred} * @private */ this.setupAckSent_ = new goog.async.Deferred(); /** * Fires once we're marked connected. * @type {!goog.async.Deferred} * @private */ this.connected_ = new goog.async.Deferred(); /** * The unique ID of this side of the connection. Used to determine when a peer * is reloaded. * @type {string} * @private */ this.endpointId_ = goog.net.xpc.getRandomString(10); /** * The unique ID of the peer. If we get a message from a peer with an ID we * don't expect, we reset the connection. * @type {?string} * @private */ this.peerEndpointId_ = null; // We don't want to mark ourselves connected until we have sent whatever // message will cause our counterpart in the other frame to also declare // itself connected, if there is such a message. Otherwise we risk a user // message being sent in advance of that message, and it being discarded. if (this.oneSidedHandshake_) { if (this.channel_.getRole() == goog.net.xpc.CrossPageChannelRole.INNER) { // One sided handshake, inner frame: // SETUP_ACK must be received. this.connected_.awaitDeferred(this.setupAckReceived_); } else { // One sided handshake, outer frame: // SETUP_ACK must be sent. this.connected_.awaitDeferred(this.setupAckSent_); } } else { // Two sided handshake: // SETUP_ACK has to have been received, and sent. this.connected_.awaitDeferred(this.setupAckReceived_); if (this.protocolVersion_ == 2) { this.connected_.awaitDeferred(this.setupAckSent_); } } this.connected_.addCallback(this.notifyConnected_, this); this.connected_.callback(true); this.eventHandler_. listen(this.maybeAttemptToConnectTimer_, goog.Timer.TICK, this.maybeAttemptToConnect_); goog.net.xpc.logger.info('NativeMessagingTransport created. ' + 'protocolVersion=' + this.protocolVersion_ + ', oneSidedHandshake=' + this.oneSidedHandshake_ + ', role=' + this.channel_.getRole()); }; goog.inherits(goog.net.xpc.NativeMessagingTransport, goog.net.xpc.Transport); /** * Length of the delay in milliseconds between the channel being connected and * the connection callback being called, in cases where coverage of timing flaws * is required. * @type {number} * @private */ goog.net.xpc.NativeMessagingTransport.CONNECTION_DELAY_MS_ = 200; /** * Current determination of peer's protocol version, or null for unknown. * @type {?number} * @private */ goog.net.xpc.NativeMessagingTransport.prototype.peerProtocolVersion_ = null; /** * Flag indicating if this instance of the transport has been initialized. * @type {boolean} * @private */ goog.net.xpc.NativeMessagingTransport.prototype.initialized_ = false; /** * The transport type. * @type {number} * @override */ goog.net.xpc.NativeMessagingTransport.prototype.transportType = goog.net.xpc.TransportTypes.NATIVE_MESSAGING; /** * The delimiter used for transport service messages. * @type {string} * @private */ goog.net.xpc.NativeMessagingTransport.MESSAGE_DELIMITER_ = ','; /** * Tracks the number of NativeMessagingTransport channels that have been * initialized but not disposed yet in a map keyed by the UID of the window * object. This allows for multiple windows to be initiallized and listening * for messages. * @type {Object.<number>} * @private */ goog.net.xpc.NativeMessagingTransport.activeCount_ = {}; /** * Id of a timer user during postMessage sends. * @type {number} * @private */ goog.net.xpc.NativeMessagingTransport.sendTimerId_ = 0; /** * Checks whether the peer transport protocol version could be as indicated. * @param {number} version The version to check for. * @return {boolean} Whether the peer transport protocol version is as * indicated, or null. * @private */ goog.net.xpc.NativeMessagingTransport.prototype.couldPeerVersionBe_ = function(version) { return this.peerProtocolVersion_ == null || this.peerProtocolVersion_ == version; }; /** * Initializes this transport. Registers a listener for 'message'-events * on the document. * @param {Window} listenWindow The window to listen to events on. * @private */ goog.net.xpc.NativeMessagingTransport.initialize_ = function(listenWindow) { var uid = goog.getUid(listenWindow); var value = goog.net.xpc.NativeMessagingTransport.activeCount_[uid]; if (!goog.isNumber(value)) { value = 0; } if (value == 0) { // Listen for message-events. These are fired on window in FF3 and on // document in Opera. goog.events.listen( listenWindow.postMessage ? listenWindow : listenWindow.document, 'message', goog.net.xpc.NativeMessagingTransport.messageReceived_, false, goog.net.xpc.NativeMessagingTransport); } goog.net.xpc.NativeMessagingTransport.activeCount_[uid] = value + 1; }; /** * Processes an incoming message-event. * @param {goog.events.BrowserEvent} msgEvt The message event. * @return {boolean} True if message was successfully delivered to a channel. * @private */ goog.net.xpc.NativeMessagingTransport.messageReceived_ = function(msgEvt) { var data = msgEvt.getBrowserEvent().data; if (!goog.isString(data)) { return false; } var headDelim = data.indexOf('|'); var serviceDelim = data.indexOf(':'); // make sure we got something reasonable if (headDelim == -1 || serviceDelim == -1) { return false; } var channelName = data.substring(0, headDelim); var service = data.substring(headDelim + 1, serviceDelim); var payload = data.substring(serviceDelim + 1); goog.net.xpc.logger.fine('messageReceived: channel=' + channelName + ', service=' + service + ', payload=' + payload); // Attempt to deliver message to the channel. Keep in mind that it may not // exist for several reasons, including but not limited to: // - a malformed message // - the channel simply has not been created // - channel was created in a different namespace // - message was sent to the wrong window // - channel has become stale (e.g. caching iframes and back clicks) var channel = goog.net.xpc.channels[channelName]; if (channel) { channel.xpcDeliver(service, payload, msgEvt.getBrowserEvent().origin); return true; } var transportMessageType = goog.net.xpc.NativeMessagingTransport.parseTransportPayload_(payload)[0]; // Check if there are any stale channel names that can be updated. for (var staleChannelName in goog.net.xpc.channels) { var staleChannel = goog.net.xpc.channels[staleChannelName]; if (staleChannel.getRole() == goog.net.xpc.CrossPageChannelRole.INNER && !staleChannel.isConnected() && service == goog.net.xpc.TRANSPORT_SERVICE_ && (transportMessageType == goog.net.xpc.SETUP || transportMessageType == goog.net.xpc.SETUP_NTPV2)) { // Inner peer received SETUP message but channel names did not match. // Start using the channel name sent from outer peer. The channel name // of the inner peer can easily become out of date, as iframe's and their // JS state get cached in many browsers upon page reload or history // navigation (particularly Firefox 1.5+). We can trust the outer peer, // since we only accept postMessage messages from the same hostname that // originally setup the channel. goog.net.xpc.logger.fine('changing channel name to ' + channelName); staleChannel.name = channelName; // Remove old stale pointer to channel. delete goog.net.xpc.channels[staleChannelName]; // Create fresh pointer to channel. goog.net.xpc.channels[channelName] = staleChannel; staleChannel.xpcDeliver(service, payload); return true; } } // Failed to find a channel to deliver this message to, so simply ignore it. goog.net.xpc.logger.info('channel name mismatch; message ignored"'); return false; }; /** * Handles transport service messages. * @param {string} payload The message content. * @override */ goog.net.xpc.NativeMessagingTransport.prototype.transportServiceHandler = function(payload) { var transportParts = goog.net.xpc.NativeMessagingTransport.parseTransportPayload_(payload); var transportMessageType = transportParts[0]; var peerEndpointId = transportParts[1]; switch (transportMessageType) { case goog.net.xpc.SETUP_ACK_: this.setPeerProtocolVersion_(1); if (!this.setupAckReceived_.hasFired()) { this.setupAckReceived_.callback(true); } break; case goog.net.xpc.SETUP_ACK_NTPV2: if (this.protocolVersion_ == 2) { this.setPeerProtocolVersion_(2); if (!this.setupAckReceived_.hasFired()) { this.setupAckReceived_.callback(true); } } break; case goog.net.xpc.SETUP: this.setPeerProtocolVersion_(1); this.sendSetupAckMessage_(1); break; case goog.net.xpc.SETUP_NTPV2: if (this.protocolVersion_ == 2) { var prevPeerProtocolVersion = this.peerProtocolVersion_; this.setPeerProtocolVersion_(2); this.sendSetupAckMessage_(2); if ((prevPeerProtocolVersion == 1 || this.peerEndpointId_ != null) && this.peerEndpointId_ != peerEndpointId) { // Send a new SETUP message since the peer has been replaced. goog.net.xpc.logger.info('Sending SETUP and changing peer ID to: ' + peerEndpointId); this.sendSetupMessage_(); } this.peerEndpointId_ = peerEndpointId; } break; } }; /** * Sends a SETUP transport service message of the correct protocol number for * our current situation. * @private */ goog.net.xpc.NativeMessagingTransport.prototype.sendSetupMessage_ = function() { // 'real' (legacy) v1 transports don't know about there being v2 ones out // there, and we shouldn't either. goog.asserts.assert(!(this.protocolVersion_ == 1 && this.peerProtocolVersion_ == 2)); if (this.protocolVersion_ == 2 && this.couldPeerVersionBe_(2)) { var payload = goog.net.xpc.SETUP_NTPV2; payload += goog.net.xpc.NativeMessagingTransport.MESSAGE_DELIMITER_; payload += this.endpointId_; this.send(goog.net.xpc.TRANSPORT_SERVICE_, payload); } // For backward compatibility reasons, the V1 SETUP message can be sent by // both V1 and V2 transports. Once a V2 transport has 'heard' another V2 // transport it starts ignoring V1 messages, so the V2 message must be sent // first. if (this.couldPeerVersionBe_(1)) { this.send(goog.net.xpc.TRANSPORT_SERVICE_, goog.net.xpc.SETUP); } }; /** * Sends a SETUP_ACK transport service message of the correct protocol number * for our current situation. * @param {number} protocolVersion The protocol version of the SETUP message * which gave rise to this ack message. * @private */ goog.net.xpc.NativeMessagingTransport.prototype.sendSetupAckMessage_ = function(protocolVersion) { goog.asserts.assert(this.protocolVersion_ != 1 || protocolVersion != 2, 'Shouldn\'t try to send a v2 setup ack in v1 mode.'); if (this.protocolVersion_ == 2 && this.couldPeerVersionBe_(2) && protocolVersion == 2) { this.send(goog.net.xpc.TRANSPORT_SERVICE_, goog.net.xpc.SETUP_ACK_NTPV2); } else if (this.couldPeerVersionBe_(1) && protocolVersion == 1) { this.send(goog.net.xpc.TRANSPORT_SERVICE_, goog.net.xpc.SETUP_ACK_); } else { return; } if (!this.setupAckSent_.hasFired()) { this.setupAckSent_.callback(true); } }; /** * Attempts to set the peer protocol number. Downgrades from 2 to 1 are not * permitted. * @param {number} version The new protocol number. * @private */ goog.net.xpc.NativeMessagingTransport.prototype.setPeerProtocolVersion_ = function(version) { if (version > this.peerProtocolVersion_) { this.peerProtocolVersion_ = version; } if (this.peerProtocolVersion_ == 1) { if (!this.setupAckSent_.hasFired() && !this.oneSidedHandshake_) { this.setupAckSent_.callback(true); } this.peerEndpointId_ = null; } }; /** * Connects this transport. * @override */ goog.net.xpc.NativeMessagingTransport.prototype.connect = function() { goog.net.xpc.NativeMessagingTransport.initialize_(this.getWindow()); this.initialized_ = true; this.maybeAttemptToConnect_(); }; /** * Connects to other peer. In the case of the outer peer, the setup messages are * likely sent before the inner peer is ready to receive them. Therefore, this * function will continue trying to send the SETUP message until the inner peer * responds. In the case of the inner peer, it will occasionally have its * channel name fall out of sync with the outer peer, particularly during * soft-reloads and history navigations. * @private */ goog.net.xpc.NativeMessagingTransport.prototype.maybeAttemptToConnect_ = function() { // In a one-sided handshake, the outer frame does not send a SETUP message, // but the inner frame does. var outerFrame = this.channel_.getRole() == goog.net.xpc.CrossPageChannelRole.OUTER; if ((this.oneSidedHandshake_ && outerFrame) || this.channel_.isConnected() || this.isDisposed()) { this.maybeAttemptToConnectTimer_.stop(); return; } this.maybeAttemptToConnectTimer_.start(); this.sendSetupMessage_(); }; /** * Sends a message. * @param {string} service The name off the service the message is to be * delivered to. * @param {string} payload The message content. * @override */ goog.net.xpc.NativeMessagingTransport.prototype.send = function(service, payload) { var win = this.channel_.getPeerWindowObject(); if (!win) { goog.net.xpc.logger.fine('send(): window not ready'); return; } this.send = function(service, payload) { // In IE8 (and perhaps elsewhere), it seems like postMessage is sometimes // implemented as a synchronous call. That is, calling it synchronously // calls whatever listeners it has, and control is not returned to the // calling thread until those listeners are run. This produces different // ordering to all other browsers, and breaks this protocol. This timer // callback is introduced to produce standard behavior across all browsers. var transport = this; var channelName = this.channel_.name; var sendFunctor = function() { transport.sendTimerId_ = 0; try { // postMessage is a method of the window object, except in some // versions of Opera, where it is a method of the document object. It // also seems that the appearance of postMessage on the peer window // object can sometimes be delayed. var obj = win.postMessage ? win : win.document; if (!obj.postMessage) { goog.net.xpc.logger.warning('Peer window had no postMessage ' + 'function.'); return; } obj.postMessage(channelName + '|' + service + ':' + payload, transport.peerHostname_); goog.net.xpc.logger.fine('send(): service=' + service + ' payload=' + payload + ' to hostname=' + transport.peerHostname_); } catch (error) { // There is some evidence (not totally convincing) that postMessage can // be missing or throw errors during a narrow timing window during // startup. This protects against that. goog.net.xpc.logger.warning('Error performing postMessage, ignoring.', error); } }; this.sendTimerId_ = goog.Timer.callOnce(sendFunctor, 0); }; this.send(service, payload); }; /** * Notify the channel that this transport is connected. If either transport is * protocol v1, a short delay is required to paper over timing vulnerabilities * in that protocol version. * @private */ goog.net.xpc.NativeMessagingTransport.prototype.notifyConnected_ = function() { var delay = (this.protocolVersion_ == 1 || this.peerProtocolVersion_ == 1) ? goog.net.xpc.NativeMessagingTransport.CONNECTION_DELAY_MS_ : undefined; this.channel_.notifyConnected(delay); }; /** @override */ goog.net.xpc.NativeMessagingTransport.prototype.disposeInternal = function() { if (this.initialized_) { var listenWindow = this.getWindow(); var uid = goog.getUid(listenWindow); var value = goog.net.xpc.NativeMessagingTransport.activeCount_[uid]; goog.net.xpc.NativeMessagingTransport.activeCount_[uid] = value - 1; if (value == 1) { goog.events.unlisten( listenWindow.postMessage ? listenWindow : listenWindow.document, 'message', goog.net.xpc.NativeMessagingTransport.messageReceived_, false, goog.net.xpc.NativeMessagingTransport); } } if (this.sendTimerId_) { goog.Timer.clear(this.sendTimerId_); this.sendTimerId_ = 0; } goog.dispose(this.eventHandler_); delete this.eventHandler_; goog.dispose(this.maybeAttemptToConnectTimer_); delete this.maybeAttemptToConnectTimer_; this.setupAckReceived_.cancel(); delete this.setupAckReceived_; this.setupAckSent_.cancel(); delete this.setupAckSent_; this.connected_.cancel(); delete this.connected_; // Cleaning up this.send as it is an instance method, created in // goog.net.xpc.NativeMessagingTransport.prototype.send and has a closure over // this.channel_.peerWindowObject_. delete this.send; goog.base(this, 'disposeInternal'); }; /** * Parse a transport service payload message. For v1, it is simply expected to * be 'SETUP' or 'SETUP_ACK'. For v2, an example setup message is * 'SETUP_NTPV2,abc123', where the second part is the endpoint id. The v2 setup * ack message is simply 'SETUP_ACK_NTPV2'. * @param {string} payload The payload. * @return {!Array.<?string>} An array with the message type as the first member * and the endpoint id as the second, if one was sent, or null otherwise. * @private */ goog.net.xpc.NativeMessagingTransport.parseTransportPayload_ = function(payload) { var transportParts = /** @type {!Array.<?string>} */ (payload.split( goog.net.xpc.NativeMessagingTransport.MESSAGE_DELIMITER_)); transportParts[1] = transportParts[1] || null; return transportParts; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Contains the base class for transports. * */ goog.provide('goog.net.xpc.Transport'); goog.require('goog.Disposable'); goog.require('goog.dom'); goog.require('goog.net.xpc'); /** * The base class for transports. * @param {goog.dom.DomHelper=} opt_domHelper The dom helper to use for * finding the window objects. * @constructor * @extends {goog.Disposable}; */ goog.net.xpc.Transport = function(opt_domHelper) { goog.Disposable.call(this); /** * The dom helper to use for finding the window objects to reference. * @type {goog.dom.DomHelper} * @private */ this.domHelper_ = opt_domHelper || goog.dom.getDomHelper(); }; goog.inherits(goog.net.xpc.Transport, goog.Disposable); /** * The transport type. * @type {number} * @protected */ goog.net.xpc.Transport.prototype.transportType = 0; /** * @return {number} The transport type identifier. */ goog.net.xpc.Transport.prototype.getType = function() { return this.transportType; }; /** * Returns the window associated with this transport instance. * @return {Window} The window to use. */ goog.net.xpc.Transport.prototype.getWindow = function() { return this.domHelper_.getWindow(); }; /** * Return the transport name. * @return {string} the transport name. */ goog.net.xpc.Transport.prototype.getName = function() { return goog.net.xpc.TransportNames[this.transportType] || ''; }; /** * Handles transport service messages (internal signalling). * @param {string} payload The message content. */ goog.net.xpc.Transport.prototype.transportServiceHandler = goog.abstractMethod; /** * Connects this transport. * The transport implementation is expected to call * CrossPageChannel.prototype.notifyConnected when the channel is ready * to be used. */ goog.net.xpc.Transport.prototype.connect = goog.abstractMethod; /** * Sends a message. * @param {string} service The name off the service the message is to be * delivered to. * @param {string} payload The message content. */ goog.net.xpc.Transport.prototype.send = goog.abstractMethod;
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Standalone script to be included in the relay-document * used by goog.net.xpc.IframeRelayTransport. This script will decode the * fragment identifier, determine the target window object and deliver * the data to it. * */ goog.provide('goog.net.xpc.relay'); (function() { // Decode the fragement identifier. // location.href is expected to be structured as follows: // <url>#<channel_name>[,<iframe_id>]|<data> // Get the fragment identifier. var raw = window.location.hash; if (!raw) { return; } if (raw.charAt(0) == '#') { raw = raw.substring(1); } var pos = raw.indexOf('|'); var head = raw.substring(0, pos).split(','); var channelName = head[0]; var iframeId = head.length == 2 ? head[1] : null; var frame = raw.substring(pos + 1); // Find the window object of the peer. // // The general structure of the frames looks like this: // - peer1 // - relay2 // - peer2 // - relay1 // // We are either relay1 or relay2. var win; if (iframeId) { // We are relay2 and need to deliver the data to peer2. win = window.parent.frames[iframeId]; } else { // We are relay1 and need to deliver the data to peer1. win = window.parent.parent; } // Deliver the data. try { win['xpcRelay'](channelName, frame); } catch (e) { // Nothing useful can be done here. // It would be great to inform the sender the delivery of this message // failed, but this is not possible because we are already in the receiver's // domain at this point. } })();
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Class that can be used to determine when multiple iframes have * been loaded. Refactored from static APIs in IframeLoadMonitor. */ goog.provide('goog.net.MultiIframeLoadMonitor'); goog.require('goog.events'); goog.require('goog.net.IframeLoadMonitor'); /** * Provides a wrapper around IframeLoadMonitor, to allow the caller to wait for * multiple iframes to load. * * @param {Array.<HTMLIFrameElement>} iframes Array of iframe elements to * wait until they are loaded. * @param {function():void} callback The callback to invoke once the frames have * loaded. * @param {boolean=} opt_hasContent true if the monitor should wait until the * iframes have content (body.firstChild != null). * @constructor */ goog.net.MultiIframeLoadMonitor = function(iframes, callback, opt_hasContent) { /** * Array of IframeLoadMonitors we use to track the loaded status of any * currently unloaded iframes. * @type {Array.<goog.net.IframeLoadMonitor>} * @private */ this.pendingIframeLoadMonitors_ = []; /** * Callback which is invoked when all of the iframes are loaded. * @type {function():void} * @private */ this.callback_ = callback; for (var i = 0; i < iframes.length; i++) { var iframeLoadMonitor = new goog.net.IframeLoadMonitor( iframes[i], opt_hasContent); if (iframeLoadMonitor.isLoaded()) { // Already loaded - don't need to wait iframeLoadMonitor.dispose(); } else { // Iframe isn't loaded yet - register to be notified when it is // loaded, and track this monitor so we can dispose later as // required. this.pendingIframeLoadMonitors_.push(iframeLoadMonitor); goog.events.listen( iframeLoadMonitor, goog.net.IframeLoadMonitor.LOAD_EVENT, this); } } if (!this.pendingIframeLoadMonitors_.length) { // All frames were already loaded this.callback_(); } }; /** * Handles a pending iframe load monitor load event. * @param {goog.events.Event} e The goog.net.IframeLoadMonitor.LOAD_EVENT event. */ goog.net.MultiIframeLoadMonitor.prototype.handleEvent = function(e) { var iframeLoadMonitor = e.target; // iframeLoadMonitor is now loaded, remove it from the array of // pending iframe load monitors. for (var i = 0; i < this.pendingIframeLoadMonitors_.length; i++) { if (this.pendingIframeLoadMonitors_[i] == iframeLoadMonitor) { this.pendingIframeLoadMonitors_.splice(i, 1); break; } } // Disposes of the iframe load monitor. We created this iframe load monitor // and installed the single listener on it, so it is safe to dispose it // in the middle of this event handler. iframeLoadMonitor.dispose(); // If there are no more pending iframe load monitors, all the iframes // have loaded, and so we invoke the callback. if (!this.pendingIframeLoadMonitors_.length) { this.callback_(); } }; /** * Stops monitoring the iframes, cleaning up any associated resources. In * general, the object cleans up its own resources before invoking the * callback, so this API should only be used if the caller wants to stop the * monitoring before the iframes are loaded (for example, if the caller is * implementing a timeout). */ goog.net.MultiIframeLoadMonitor.prototype.stopMonitoring = function() { for (var i = 0; i < this.pendingIframeLoadMonitors_.length; i++) { this.pendingIframeLoadMonitors_[i].dispose(); } this.pendingIframeLoadMonitors_.length = 0; };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A utility to load JavaScript files via DOM script tags. * Refactored from goog.net.Jsonp. Works cross-domain. * */ goog.provide('goog.net.jsloader'); goog.provide('goog.net.jsloader.Error'); goog.require('goog.array'); goog.require('goog.async.Deferred'); goog.require('goog.debug.Error'); goog.require('goog.dom'); goog.require('goog.userAgent'); /** * The name of the property of goog.global under which the JavaScript * verification object is stored by the loaded script. * @type {string} * @private */ goog.net.jsloader.GLOBAL_VERIFY_OBJS_ = 'closure_verification'; /** * The default length of time, in milliseconds, we are prepared to wait for a * load request to complete. * @type {number} */ goog.net.jsloader.DEFAULT_TIMEOUT = 5000; /** * Optional parameters for goog.net.jsloader.send. * timeout: The length of time, in milliseconds, we are prepared to wait * for a load request to complete. Default it 5 seconds. * document: The HTML document under which to load the JavaScript. Default is * the current document. * cleanupWhenDone: If true clean up the script tag after script completes to * load. This is important if you just want to read data from the JavaScript * and then throw it away. Default is false. * * @typedef {{ * timeout: (number|undefined), * document: (HTMLDocument|undefined), * cleanupWhenDone: (boolean|undefined) * }} */ goog.net.jsloader.Options; /** * Scripts (URIs) waiting to be loaded. * @type {Array.<string>} * @private */ goog.net.jsloader.scriptsToLoad_ = []; /** * Loads and evaluates the JavaScript files at the specified URIs, guaranteeing * the order of script loads. * * Because we have to load the scripts in serial (load script 1, exec script 1, * load script 2, exec script 2, and so on), this will be slower than doing * the network fetches in parallel. * * If you need to load a large number of scripts but dependency order doesn't * matter, you should just call goog.net.jsloader.load N times. * * If you need to load a large number of scripts on the same domain, * you may want to use goog.module.ModuleLoader. * * @param {Array.<string>} uris The URIs to load. * @param {goog.net.jsloader.Options=} opt_options Optional parameters. See * goog.net.jsloader.options documentation for details. */ goog.net.jsloader.loadMany = function(uris, opt_options) { // Loading the scripts in serial introduces asynchronosity into the flow. // Therefore, there are race conditions where client A can kick off the load // sequence for client B, even though client A's scripts haven't all been // loaded yet. // // To work around this issue, all module loads share a queue. if (!uris.length) { return; } var isAnotherModuleLoading = goog.net.jsloader.scriptsToLoad_.length; goog.array.extend(goog.net.jsloader.scriptsToLoad_, uris); if (isAnotherModuleLoading) { // jsloader is still loading some other scripts. // In order to prevent the race condition noted above, we just add // these URIs to the end of the scripts' queue and return. return; } uris = goog.net.jsloader.scriptsToLoad_; var popAndLoadNextScript = function() { var uri = uris.shift(); var deferred = goog.net.jsloader.load(uri, opt_options); if (uris.length) { deferred.addBoth(popAndLoadNextScript); } }; popAndLoadNextScript(); }; /** * Loads and evaluates a JavaScript file. * When the script loads, a user callback is called. * It is the client's responsibility to verify that the script ran successfully. * * @param {string} uri The URI of the JavaScript. * @param {goog.net.jsloader.Options=} opt_options Optional parameters. See * goog.net.jsloader.Options documentation for details. * @return {!goog.async.Deferred} The deferred result, that may be used to add * callbacks and/or cancel the transmission. * The error callback will be called with a single goog.net.jsloader.Error * parameter. */ goog.net.jsloader.load = function(uri, opt_options) { var options = opt_options || {}; var doc = options.document || document; var script = goog.dom.createElement(goog.dom.TagName.SCRIPT); var request = {script_: script, timeout_: undefined}; var deferred = new goog.async.Deferred(goog.net.jsloader.cancel_, request); // Set a timeout. var timeout = null; var timeoutDuration = goog.isDefAndNotNull(options.timeout) ? options.timeout : goog.net.jsloader.DEFAULT_TIMEOUT; if (timeoutDuration > 0) { timeout = window.setTimeout(function() { goog.net.jsloader.cleanup_(script, true); deferred.errback(new goog.net.jsloader.Error( goog.net.jsloader.ErrorCode.TIMEOUT, 'Timeout reached for loading script ' + uri)); }, timeoutDuration); request.timeout_ = timeout; } // Hang the user callback to be called when the script completes to load. // NOTE(user): This callback will be called in IE even upon error. In any // case it is the client's responsibility to verify that the script ran // successfully. script.onload = script.onreadystatechange = function() { if (!script.readyState || script.readyState == 'loaded' || script.readyState == 'complete') { var removeScriptNode = options.cleanupWhenDone || false; goog.net.jsloader.cleanup_(script, removeScriptNode, timeout); deferred.callback(null); } }; // Add an error callback. // NOTE(user): Not supported in IE. script.onerror = function() { goog.net.jsloader.cleanup_(script, true, timeout); deferred.errback(new goog.net.jsloader.Error( goog.net.jsloader.ErrorCode.LOAD_ERROR, 'Error while loading script ' + uri)); }; // Add the script element to the document. goog.dom.setProperties(script, { 'type': 'text/javascript', 'charset': 'UTF-8', // NOTE(user): Safari never loads the script if we don't set // the src attribute before appending. 'src': uri }); var scriptParent = goog.net.jsloader.getScriptParentElement_(doc); scriptParent.appendChild(script); return deferred; }; /** * Loads a JavaScript file and verifies it was evaluated successfully, using a * verification object. * The verification object is set by the loaded JavaScript at the end of the * script. * We verify this object was set and return its value in the success callback. * If the object is not defined we trigger an error callback. * * @param {string} uri The URI of the JavaScript. * @param {string} verificationObjName The name of the verification object that * the loaded script should set. * @param {goog.net.jsloader.Options} options Optional parameters. See * goog.net.jsloader.Options documentation for details. * @return {!goog.async.Deferred} The deferred result, that may be used to add * callbacks and/or cancel the transmission. * The success callback will be called with a single parameter containing * the value of the verification object. * The error callback will be called with a single goog.net.jsloader.Error * parameter. */ goog.net.jsloader.loadAndVerify = function(uri, verificationObjName, options) { // Define the global objects variable. if (!goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_]) { goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_] = {}; } var verifyObjs = goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_]; // Verify that the expected object does not exist yet. if (goog.isDef(verifyObjs[verificationObjName])) { // TODO(user): Error or reset variable? return goog.async.Deferred.fail(new goog.net.jsloader.Error( goog.net.jsloader.ErrorCode.VERIFY_OBJECT_ALREADY_EXISTS, 'Verification object ' + verificationObjName + ' already defined.')); } // Send request to load the JavaScript. var sendDeferred = goog.net.jsloader.load(uri, options); // Create a deferred object wrapping the send result. var deferred = new goog.async.Deferred( goog.bind(sendDeferred.cancel, sendDeferred)); // Call user back with object that was set by the script. sendDeferred.addCallback(function() { var result = verifyObjs[verificationObjName]; if (goog.isDef(result)) { deferred.callback(result); delete verifyObjs[verificationObjName]; } else { // Error: script was not loaded properly. deferred.errback(new goog.net.jsloader.Error( goog.net.jsloader.ErrorCode.VERIFY_ERROR, 'Script ' + uri + ' loaded, but verification object ' + verificationObjName + ' was not defined.')); } }); // Pass error to new deferred object. sendDeferred.addErrback(function(error) { if (goog.isDef(verifyObjs[verificationObjName])) { delete verifyObjs[verificationObjName]; } deferred.errback(error); }); return deferred; }; /** * Gets the DOM element under which we should add new script elements. * How? Take the first head element, and if not found take doc.documentElement, * which always exists. * * @param {!HTMLDocument} doc The relevant document. * @return {!Element} The script parent element. * @private */ goog.net.jsloader.getScriptParentElement_ = function(doc) { var headElements = doc.getElementsByTagName(goog.dom.TagName.HEAD); if (!headElements || goog.array.isEmpty(headElements)) { return doc.documentElement; } else { return headElements[0]; } }; /** * Cancels a given request. * @this {{script_: Element, timeout_: number}} The request context. * @private */ goog.net.jsloader.cancel_ = function() { var request = this; if (request && request.script_) { var scriptNode = request.script_; if (scriptNode && scriptNode.tagName == 'SCRIPT') { goog.net.jsloader.cleanup_(scriptNode, true, request.timeout_); } } }; /** * Removes the script node and the timeout. * * @param {Node} scriptNode The node to be cleaned up. * @param {boolean} removeScriptNode If true completely remove the script node. * @param {?number=} opt_timeout The timeout handler to cleanup. * @private */ goog.net.jsloader.cleanup_ = function(scriptNode, removeScriptNode, opt_timeout) { if (goog.isDefAndNotNull(opt_timeout)) { goog.global.clearTimeout(opt_timeout); } scriptNode.onload = goog.nullFunction; scriptNode.onerror = goog.nullFunction; scriptNode.onreadystatechange = goog.nullFunction; // Do this after a delay (removing the script node of a running script can // confuse older IEs). if (removeScriptNode) { window.setTimeout(function() { goog.dom.removeNode(scriptNode); }, 0); } }; /** * Possible error codes for jsloader. * @enum {number} */ goog.net.jsloader.ErrorCode = { LOAD_ERROR: 0, TIMEOUT: 1, VERIFY_ERROR: 2, VERIFY_OBJECT_ALREADY_EXISTS: 3 }; /** * A jsloader error. * * @param {goog.net.jsloader.ErrorCode} code The error code. * @param {string=} opt_message Additional message. * @constructor * @extends {goog.debug.Error} */ goog.net.jsloader.Error = function(code, opt_message) { var msg = 'Jsloader error (code #' + code + ')'; if (opt_message) { msg += ': ' + opt_message; } goog.base(this, msg); /** * The code for this error. * * @type {goog.net.jsloader.ErrorCode} */ this.code = code; }; goog.inherits(goog.net.jsloader.Error, goog.debug.Error);
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // The original file lives here: http://go/cross_domain_channel.js /** * @fileoverview Implements a cross-domain communication channel. A * typical web page is prevented by browser security from sending * request, such as a XMLHttpRequest, to other servers than the ones * from which it came. The Jsonp class provides a workound, by * using dynamically generated script tags. Typical usage:. * * var jsonp = new goog.net.Jsonp(new goog.Uri('http://my.host.com/servlet')); * var payload = { 'foo': 1, 'bar': true }; * jsonp.send(payload, function(reply) { alert(reply) }); * * This script works in all browsers that are currently supported by * the Google Maps API, which is IE 6.0+, Firefox 0.8+, Safari 1.2.4+, * Netscape 7.1+, Mozilla 1.4+, Opera 8.02+. * */ goog.provide('goog.net.Jsonp'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.net.jsloader'); // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING // // This class allows us (Google) to send data from non-Google and thus // UNTRUSTED pages to our servers. Under NO CIRCUMSTANCES return // anything sensitive, such as session or cookie specific data. Return // only data that you want parties external to Google to have. Also // NEVER use this method to send data from web pages to untrusted // servers, or redirects to unknown servers (www.google.com/cache, // /q=xx&btnl, /url, www.googlepages.com, etc.) // // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING /** * Creates a new cross domain channel that sends data to the specified * host URL. By default, if no reply arrives within 5s, the channel * assumes the call failed to complete successfully. * * @param {goog.Uri|string} uri The Uri of the server side code that receives * data posted through this channel (e.g., * "http://maps.google.com/maps/geo"). * * @param {string=} opt_callbackParamName The parameter name that is used to * specify the callback. Defaults to "callback". * * @constructor */ goog.net.Jsonp = function(uri, opt_callbackParamName) { /** * The uri_ object will be used to encode the payload that is sent to the * server. * @type {goog.Uri} * @private */ this.uri_ = new goog.Uri(uri); /** * This is the callback parameter name that is added to the uri. * @type {string} * @private */ this.callbackParamName_ = opt_callbackParamName ? opt_callbackParamName : 'callback'; /** * The length of time, in milliseconds, this channel is prepared * to wait for for a request to complete. The default value is 5 seconds. * @type {number} * @private */ this.timeout_ = 5000; }; /** * The name of the property of goog.global under which the callback is * stored. */ goog.net.Jsonp.CALLBACKS = '_callbacks_'; /** * Used to generate unique callback IDs. The counter must be global because * all channels share a common callback object. * @private */ goog.net.Jsonp.scriptCounter_ = 0; /** * Sets the length of time, in milliseconds, this channel is prepared * to wait for for a request to complete. If the call is not competed * within the set time span, it is assumed to have failed. To wait * indefinitely for a request to complete set the timout to a negative * number. * * @param {number} timeout The length of time before calls are * interrupted. */ goog.net.Jsonp.prototype.setRequestTimeout = function(timeout) { this.timeout_ = timeout; }; /** * Returns the current timeout value, in milliseconds. * * @return {number} The timeout value. */ goog.net.Jsonp.prototype.getRequestTimeout = function() { return this.timeout_; }; /** * Sends the given payload to the URL specified at the construction * time. The reply is delivered to the given replyCallback. If the * errorCallback is specified and the reply does not arrive within the * timeout period set on this channel, the errorCallback is invoked * with the original payload. * * If no reply callback is specified, then the response is expected to * consist of calls to globally registered functions. No &callback= * URL parameter will be sent in the request, and the script element * will be cleaned up after the timeout. * * @param {Object=} opt_payload Name-value pairs. If given, these will be * added as parameters to the supplied URI as GET parameters to the * given server URI. * * @param {Function=} opt_replyCallback A function expecting one * argument, called when the reply arrives, with the response data. * * @param {Function=} opt_errorCallback A function expecting one * argument, called on timeout, with the payload (if given), otherwise * null. * * @param {string=} opt_callbackParamValue Value to be used as the * parameter value for the callback parameter (callbackParamName). * To be used when the value needs to be fixed by the client for a * particular request, to make use of the cached responses for the request. * NOTE: If multiple requests are made with the same * opt_callbackParamValue, only the last call will work whenever the * response comes back. * * @return {Object} A request descriptor that may be used to cancel this * transmission, or null, if the message may not be cancelled. */ goog.net.Jsonp.prototype.send = function(opt_payload, opt_replyCallback, opt_errorCallback, opt_callbackParamValue) { var payload = opt_payload || null; var id = opt_callbackParamValue || '_' + (goog.net.Jsonp.scriptCounter_++).toString(36) + goog.now().toString(36); if (!goog.global[goog.net.Jsonp.CALLBACKS]) { goog.global[goog.net.Jsonp.CALLBACKS] = {}; } // Create a new Uri object onto which this payload will be added var uri = this.uri_.clone(); if (payload) { goog.net.Jsonp.addPayloadToUri_(payload, uri); } if (opt_replyCallback) { var reply = goog.net.Jsonp.newReplyHandler_(id, opt_replyCallback); goog.global[goog.net.Jsonp.CALLBACKS][id] = reply; uri.setParameterValues(this.callbackParamName_, goog.net.Jsonp.CALLBACKS + '.' + id); } var deferred = goog.net.jsloader.load(uri.toString(), {timeout: this.timeout_, cleanupWhenDone: true}); var error = goog.net.Jsonp.newErrorHandler_(id, payload, opt_errorCallback); deferred.addErrback(error); return {id_: id, deferred_: deferred}; }; /** * Cancels a given request. The request must be exactly the object returned by * the send method. * * @param {Object} request The request object returned by the send method. */ goog.net.Jsonp.prototype.cancel = function(request) { if (request) { if (request.deferred_) { request.deferred_.cancel(); } if (request.id_) { goog.net.Jsonp.cleanup_(request.id_, false); } } }; /** * Creates a timeout callback that calls the given timeoutCallback with the * original payload. * * @param {string} id The id of the script node. * @param {Object} payload The payload that was sent to the server. * @param {Function=} opt_errorCallback The function called on timeout. * @return {!Function} A zero argument function that handles callback duties. * @private */ goog.net.Jsonp.newErrorHandler_ = function(id, payload, opt_errorCallback) { /** * When we call across domains with a request, this function is the * timeout handler. Once it's done executing the user-specified * error-handler, it removes the script node and original function. */ return function() { goog.net.Jsonp.cleanup_(id, false); if (opt_errorCallback) { opt_errorCallback(payload); } }; }; /** * Creates a reply callback that calls the given replyCallback with data * returned by the server. * * @param {string} id The id of the script node. * @param {Function} replyCallback The function called on reply. * @return {Function} A reply callback function. * @private */ goog.net.Jsonp.newReplyHandler_ = function(id, replyCallback) { /** * This function is the handler for the all-is-well response. It * clears the error timeout handler, calls the user's handler, then * removes the script node and itself. * * @param {...Object} var_args The response data sent from the server. */ return function(var_args) { goog.net.Jsonp.cleanup_(id, true); replyCallback.apply(undefined, arguments); }; }; /** * Removes the script node and reply handler with the given id. * * @param {string} id The id of the script node to be removed. * @param {boolean} deleteReplyHandler If true, delete the reply handler * instead of setting it to nullFunction (if we know the callback could * never be called again). * @private */ goog.net.Jsonp.cleanup_ = function(id, deleteReplyHandler) { if (goog.global[goog.net.Jsonp.CALLBACKS][id]) { if (deleteReplyHandler) { delete goog.global[goog.net.Jsonp.CALLBACKS][id]; } else { // Removing the script tag doesn't necessarily prevent the script // from firing, so we make the callback a noop. goog.global[goog.net.Jsonp.CALLBACKS][id] = goog.nullFunction; } } }; /** * Returns URL encoded payload. The payload should be a map of name-value * pairs, in the form {"foo": 1, "bar": true, ...}. If the map is empty, * the URI will be unchanged. * * <p>The method uses hasOwnProperty() to assure the properties are on the * object, not on its prototype. * * @param {!Object} payload A map of value name pairs to be encoded. * A value may be specified as an array, in which case a query parameter * will be created for each value, e.g.: * {"foo": [1,2]} will encode to "foo=1&foo=2". * * @param {!goog.Uri} uri A Uri object onto which the payload key value pairs * will be encoded. * * @return {!goog.Uri} A reference to the Uri sent as a parameter. * @private */ goog.net.Jsonp.addPayloadToUri_ = function(payload, uri) { for (var name in payload) { // NOTE(user): Safari/1.3 doesn't have hasOwnProperty(). In that // case, we iterate over all properties as a very lame workaround. if (!payload.hasOwnProperty || payload.hasOwnProperty(name)) { uri.setParameterValues(name, payload[name]); } } return uri; }; // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING // // This class allows us (Google) to send data from non-Google and thus // UNTRUSTED pages to our servers. Under NO CIRCUMSTANCES return // anything sensitive, such as session or cookie specific data. Return // only data that you want parties external to Google to have. Also // NEVER use this method to send data from web pages to untrusted // servers, or redirects to unknown servers (www.google.com/cache, // /q=xx&btnl, /url, www.googlepages.com, etc.) // // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Wrapper class for handling XmlHttpRequests. */ goog.provide('goog.net.XhrLite'); goog.require('goog.net.XhrIo'); /** * Basic class for handling XmlHttpRequests. * @deprecated Use goog.net.XhrIo instead. * @constructor */ goog.net.XhrLite = goog.net.XhrIo; // Statics are needed to avoid code removal. /** * Static send that creates a short lived instance of XhrIo to send the * request. * @see goog.net.XhrIo.cleanup * @param {string} url Uri to make request too. * @param {Function=} opt_callback Callback function for when request is * complete. * @param {string=} opt_method Send method, default: GET. * @param {string=} opt_content Post data. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the * request. * @param {number=} opt_timeoutInterval Number of milliseconds after which an * incomplete request will be aborted; 0 means no timeout is set. */ goog.net.XhrLite.send = goog.net.XhrIo.send; /** * Disposes all non-disposed instances of goog.net.XhrIo created by * {@link goog.net.XhrIo.send}. * {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance * it creates when the request completes or fails. However, if * the request never completes, then the goog.net.XhrIo is not disposed. * This can occur if the window is unloaded before the request completes. * We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo * it creates and make the client of {@link goog.net.XhrIo.send} be * responsible for disposing it in this case. However, this makes things * significantly more complicated for the client, and the whole point * of {@link goog.net.XhrIo.send} is that it's simple and easy to use. * Clients of {@link goog.net.XhrIo.send} should call * {@link goog.net.XhrIo.cleanup} when doing final * cleanup on window unload. */ goog.net.XhrLite.cleanup = goog.net.XhrIo.cleanup; /** * Installs exception protection for all entry point introduced by * goog.net.XhrIo instances which are not protected by * {@link goog.debug.ErrorHandler#protectWindowSetTimeout}, * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or * {@link goog.events.protectBrowserEventEntryPoint}. * * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to * protect the entry point(s). * @param {boolean=} opt_tracers Whether to install tracers around the entry * point. */ goog.net.XhrLite.protectEntryPoints = goog.net.XhrIo.protectEntryPoints; /** * Disposes of the specified goog.net.XhrIo created by * {@link goog.net.XhrIo.send} and removes it from * {@link goog.net.XhrIo.pendingStaticSendInstances_}. * @param {goog.net.XhrIo} XhrIo An XhrIo created by * {@link goog.net.XhrIo.send}. * @private */ goog.net.XhrLite.cleanupSend_ = goog.net.XhrIo.cleanupSend_; /** * The Content-Type HTTP header name * @type {string} */ goog.net.XhrLite.CONTENT_TYPE_HEADER = goog.net.XhrIo.CONTENT_TYPE_HEADER; /** * The Content-Type HTTP header value for a url-encoded form * @type {string} */ goog.net.XhrLite.FORM_CONTENT_TYPE = goog.net.XhrIo.FORM_CONTENT_TYPE; /** * All non-disposed instances of goog.net.XhrIo created * by {@link goog.net.XhrIo.send} are in this Array. * @see goog.net.XhrIo.cleanup * @type {Array.<goog.net.XhrIo>} * @private */ goog.net.XhrLite.sendInstances_ = goog.net.XhrIo.sendInstances_;
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains classes to handle IPv4 and IPv6 addresses. * This implementation is mostly based on Google's project: * http://code.google.com/p/ipaddr-py/. * */ goog.provide('goog.net.IpAddress'); goog.provide('goog.net.Ipv4Address'); goog.provide('goog.net.Ipv6Address'); goog.require('goog.array'); goog.require('goog.math.Integer'); goog.require('goog.object'); goog.require('goog.string'); /** * Abstract class defining an IP Address. * * Please use goog.net.IpAddress static methods or * goog.net.Ipv4Address/Ipv6Address classes. * * @param {!goog.math.Integer} address The Ip Address. * @param {number} version The version number (4, 6). * @constructor */ goog.net.IpAddress = function(address, version) { /** * The IP Address. * @type {!goog.math.Integer} * @private */ this.ip_ = address; /** * The IP Address version. * @type {number} * @private */ this.version_ = version; /** * The IPAddress, as string. * @type {string} * @private */ this.ipStr_ = ''; }; /** * @return {number} The IP Address version. */ goog.net.IpAddress.prototype.getVersion = function() { return this.version_; }; /** * @param {!goog.net.IpAddress} other The other IP Address. * @return {boolean} true if the IP Addresses are equal. */ goog.net.IpAddress.prototype.equals = function(other) { return (this.version_ == other.getVersion() && this.ip_.equals(other.toInteger())); }; /** * @return {goog.math.Integer} The IP Address, as an Integer. */ goog.net.IpAddress.prototype.toInteger = function() { return /** @type {goog.math.Integer} */ (goog.object.clone(this.ip_)); }; /** * @return {string} The IP Address, as an URI string following RFC 3986. */ goog.net.IpAddress.prototype.toUriString = goog.abstractMethod; /** * @return {string} The IP Address, as a string. * @override */ goog.net.IpAddress.prototype.toString = goog.abstractMethod; /** * Parses an IP Address in a string. * If the string is malformed, the function will simply return null * instead of raising an exception. * * @param {string} address The IP Address. * @see {goog.net.Ipv4Address} * @see {goog.net.Ipv6Address} * @return {goog.net.IpAddress} The IP Address or null. */ goog.net.IpAddress.fromString = function(address) { try { if (address.indexOf(':') != -1) { return new goog.net.Ipv6Address(address); } return new goog.net.Ipv4Address(address); } catch (e) { // Both constructors raise exception if the address is malformed (ie. // invalid). The user of this function should not care about catching // the exception, espcially if it's used to validate an user input. return null; } }; /** * Tries to parse a string represented as a host portion of an URI. * See RFC 3986 for more details on IPv6 addresses inside URI. * If the string is malformed, the function will simply return null * instead of raising an exception. * * @param {string} address A RFC 3986 encoded IP address. * @see {goog.net.Ipv4Address} * @see {goog.net.Ipv6Address} * @return {goog.net.IpAddress} The IP Address. */ goog.net.IpAddress.fromUriString = function(address) { try { if (goog.string.startsWith(address, '[') && goog.string.endsWith(address, ']')) { return new goog.net.Ipv6Address( address.substring(1, address.length - 1)); } return new goog.net.Ipv4Address(address); } catch (e) { // Both constructors raise exception if the address is malformed (ie. // invalid). The user of this function should not care about catching // the exception, espcially if it's used to validate an user input. return null; } }; /** * Takes a string or a number and returns a IPv4 Address. * * This constructor accepts strings and instance of goog.math.Integer. * If you pass a goog.math.Integer, make sure that its sign is set to positive. * @param {(string|!goog.math.Integer)} address The address to store. * @extends {goog.net.IpAddress} * @constructor */ goog.net.Ipv4Address = function(address) { var ip = goog.math.Integer.ZERO; if (address instanceof goog.math.Integer) { if (address.getSign() != 0 || address.lessThan(goog.math.Integer.ZERO) || address.greaterThan(goog.net.Ipv4Address.MAX_ADDRESS_)) { throw Error('The address does not look like an IPv4.'); } else { ip = goog.object.clone(address); } } else { if (!goog.net.Ipv4Address.REGEX_.test(address)) { throw Error(address + ' does not look like an IPv4 address.'); } var octets = address.split('.'); if (octets.length != 4) { throw Error(address + ' does not look like an IPv4 address.'); } for (var i = 0; i < octets.length; i++) { var parsedOctet = goog.string.toNumber(octets[i]); if (isNaN(parsedOctet) || parsedOctet < 0 || parsedOctet > 255 || (octets[i].length != 1 && goog.string.startsWith(octets[i], '0'))) { throw Error('In ' + address + ', octet ' + i + ' is not valid'); } var intOctet = goog.math.Integer.fromNumber(parsedOctet); ip = ip.shiftLeft(8).or(intOctet); } } goog.base(this, /** @type {!goog.math.Integer} */ (ip), 4); }; goog.inherits(goog.net.Ipv4Address, goog.net.IpAddress); /** * Regular expression matching all the allowed chars for IPv4. * @type {RegExp} * @private * @const */ goog.net.Ipv4Address.REGEX_ = /^[0-9.]*$/; /** * The Maximum length for a netmask (aka, the number of bits for IPv4). * @type {number} * @const */ goog.net.Ipv4Address.MAX_NETMASK_LENGTH = 32; /** * The Maximum address possible for IPv4. * @type {goog.math.Integer} * @private * @const */ goog.net.Ipv4Address.MAX_ADDRESS_ = goog.math.Integer.ONE.shiftLeft( goog.net.Ipv4Address.MAX_NETMASK_LENGTH).subtract(goog.math.Integer.ONE); /** * @override */ goog.net.Ipv4Address.prototype.toString = function() { if (this.ipStr_) { return this.ipStr_; } var ip = this.ip_.getBitsUnsigned(0); var octets = []; for (var i = 3; i >= 0; i--) { octets[i] = String((ip & 0xff)); ip = ip >>> 8; } this.ipStr_ = octets.join('.'); return this.ipStr_; }; /** * @override */ goog.net.Ipv4Address.prototype.toUriString = function() { return this.toString(); }; /** * Takes a string or a number and returns an IPv6 Address. * * This constructor accepts strings and instance of goog.math.Integer. * If you pass a goog.math.Integer, make sure that its sign is set to positive. * @param {(string|!goog.math.Integer)} address The address to store. * @constructor * @extends {goog.net.IpAddress} */ goog.net.Ipv6Address = function(address) { var ip = goog.math.Integer.ZERO; if (address instanceof goog.math.Integer) { if (address.getSign() != 0 || address.lessThan(goog.math.Integer.ZERO) || address.greaterThan(goog.net.Ipv6Address.MAX_ADDRESS_)) { throw Error('The address does not look like a valid IPv6.'); } else { ip = goog.object.clone(address); } } else { if (!goog.net.Ipv6Address.REGEX_.test(address)) { throw Error(address + ' is not a valid IPv6 address.'); } var splitColon = address.split(':'); if (splitColon[splitColon.length - 1].indexOf('.') != -1) { var newHextets = goog.net.Ipv6Address.dottedQuadtoHextets_( splitColon[splitColon.length - 1]); goog.array.removeAt(splitColon, splitColon.length - 1); goog.array.extend(splitColon, newHextets); address = splitColon.join(':'); } var splitDoubleColon = address.split('::'); if (splitDoubleColon.length > 2 || (splitDoubleColon.length == 1 && splitColon.length != 8)) { throw Error(address + ' is not a valid IPv6 address.'); } var ipArr; if (splitDoubleColon.length > 1) { ipArr = goog.net.Ipv6Address.explode_(splitDoubleColon); } else { ipArr = splitColon; } if (ipArr.length != 8) { throw Error(address + ' is not a valid IPv6 address'); } for (var i = 0; i < ipArr.length; i++) { var parsedHextet = goog.math.Integer.fromString(ipArr[i], 16); if (parsedHextet.lessThan(goog.math.Integer.ZERO) || parsedHextet.greaterThan(goog.net.Ipv6Address.MAX_HEXTET_VALUE_)) { throw Error(ipArr[i] + ' in ' + address + ' is not a valid hextet.'); } ip = ip.shiftLeft(16).or(parsedHextet); } } goog.base(this, /** @type {!goog.math.Integer} */ (ip), 6); }; goog.inherits(goog.net.Ipv6Address, goog.net.IpAddress); /** * Regular expression matching all allowed chars for an IPv6. * @type {RegExp} * @private * @const */ goog.net.Ipv6Address.REGEX_ = /^([a-fA-F0-9]*:){2}[a-fA-F0-9:.]*$/; /** * The Maximum length for a netmask (aka, the number of bits for IPv6). * @type {number} * @const */ goog.net.Ipv6Address.MAX_NETMASK_LENGTH = 128; /** * The maximum value of a hextet. * @type {goog.math.Integer} * @private * @const */ goog.net.Ipv6Address.MAX_HEXTET_VALUE_ = goog.math.Integer.fromInt(65535); /** * The Maximum address possible for IPv6. * @type {goog.math.Integer} * @private * @const */ goog.net.Ipv6Address.MAX_ADDRESS_ = goog.math.Integer.ONE.shiftLeft( goog.net.Ipv6Address.MAX_NETMASK_LENGTH).subtract(goog.math.Integer.ONE); /** * @override */ goog.net.Ipv6Address.prototype.toString = function() { if (this.ipStr_) { return this.ipStr_; } var outputArr = []; for (var i = 3; i >= 0; i--) { var bits = this.ip_.getBitsUnsigned(i); var firstHextet = bits >>> 16; var secondHextet = bits & 0xffff; outputArr.push(firstHextet.toString(16)); outputArr.push(secondHextet.toString(16)); } outputArr = goog.net.Ipv6Address.compress_(outputArr); this.ipStr_ = outputArr.join(':'); return this.ipStr_; }; /** * @override */ goog.net.Ipv6Address.prototype.toUriString = function() { return '[' + this.toString() + ']'; }; /** * This method is in charge of expanding/exploding an IPv6 string from its * compressed form. * @private * @param {!Array.<string>} address An IPv6 address split around '::'. * @return {Array.<string>} The expanded version of the IPv6. */ goog.net.Ipv6Address.explode_ = function(address) { var basePart = address[0].split(':'); var secondPart = address[1].split(':'); if (basePart.length == 1 && basePart[0] == '') { basePart = []; } if (secondPart.length == 1 && secondPart[0] == '') { secondPart = []; } // Now we fill the gap with 0. var gap = 8 - (basePart.length + secondPart.length); if (gap < 1) { return []; } goog.array.extend(basePart, goog.array.repeat('0', gap)); // Now we merge the basePart + gap + secondPart goog.array.extend(basePart, secondPart); return basePart; }; /** * This method is in charge of compressing an expanded IPv6 array of hextets. * @private * @param {!Array.<string>} hextets The array of hextet. * @return {Array.<string>} The compressed version of this array. */ goog.net.Ipv6Address.compress_ = function(hextets) { var bestStart = -1; var start = -1; var bestSize = 0; var size = 0; for (var i = 0; i < hextets.length; i++) { if (hextets[i] == '0') { size++; if (start == -1) { start = i; } if (size > bestSize) { bestSize = size; bestStart = start; } } else { start = -1; size = 0; } } if (bestSize > 0) { if ((bestStart + bestSize) == hextets.length) { hextets.push(''); } hextets.splice(bestStart, bestSize, ''); if (bestStart == 0) { hextets = [''].concat(hextets); } } return hextets; }; /** * This method will convert an IPv4 to a list of 2 hextets. * * For instance, 1.2.3.4 will be converted to ['0102', '0304']. * @private * @param {string} quads An IPv4 as a string. * @return {Array.<string>} A list of 2 hextets. */ goog.net.Ipv6Address.dottedQuadtoHextets_ = function(quads) { var ip4 = new goog.net.Ipv4Address(quads).toInteger(); var bits = ip4.getBitsUnsigned(0); var hextets = []; hextets.push(((bits >>> 16) & 0xffff).toString(16)); hextets.push((bits & 0xffff).toString(16)); return hextets; }; /** * @return {boolean} true if the IPv6 contains a mapped IPv4. */ goog.net.Ipv6Address.prototype.isMappedIpv4Address = function() { return (this.ip_.getBitsUnsigned(3) == 0 && this.ip_.getBitsUnsigned(2) == 0 && this.ip_.getBitsUnsigned(1) == 0xffff); }; /** * Will return the mapped IPv4 address in this IPv6 address. * @return {goog.net.Ipv4Address} an IPv4 or null. */ goog.net.Ipv6Address.prototype.getMappedIpv4Address = function() { if (!this.isMappedIpv4Address()) { return null; } var newIpv4 = new goog.math.Integer([this.ip_.getBitsUnsigned(0)], 0); return new goog.net.Ipv4Address(newIpv4); };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Constants for HTTP status codes. */ goog.provide('goog.net.HttpStatus'); /** * HTTP Status Codes defined in RFC 2616. * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html * @enum {number} */ goog.net.HttpStatus = { // Informational 1xx CONTINUE: 100, SWITCHING_PROTOCOLS: 101, // Successful 2xx OK: 200, CREATED: 201, ACCEPTED: 202, NON_AUTHORITATIVE_INFORMATION: 203, NO_CONTENT: 204, RESET_CONTENT: 205, PARTIAL_CONTENT: 206, // Redirection 3xx MULTIPLE_CHOICES: 300, MOVED_PERMANENTLY: 301, FOUND: 302, SEE_OTHER: 303, NOT_MODIFIED: 304, USE_PROXY: 305, TEMPORARY_REDIRECT: 307, // Client Error 4xx BAD_REQUEST: 400, UNAUTHORIZED: 401, PAYMENT_REQUIRED: 402, FORBIDDEN: 403, NOT_FOUND: 404, METHOD_NOT_ALLOWED: 405, NOT_ACCEPTABLE: 406, PROXY_AUTHENTICATION_REQUIRED: 407, REQUEST_TIMEOUT: 408, CONFLICT: 409, GONE: 410, LENGTH_REQUIRED: 411, PRECONDITION_FAILED: 412, REQUEST_ENTITY_TOO_LARGE: 413, REQUEST_URI_TOO_LONG: 414, UNSUPPORTED_MEDIA_TYPE: 415, REQUEST_RANGE_NOT_SATISFIABLE: 416, EXPECTATION_FAILED: 417, // Server Error 5xx INTERNAL_SERVER_ERROR: 500, NOT_IMPLEMENTED: 501, BAD_GATEWAY: 502, SERVICE_UNAVAILABLE: 503, GATEWAY_TIMEOUT: 504, HTTP_VERSION_NOT_SUPPORTED: 505, /* * IE returns this code for 204 due to its use of URLMon, which returns this * code for 'Operation Aborted'. The status text is 'Unknown', the response * headers are ''. Known to occur on IE 6 on XP through IE9 on Win7. */ QUIRK_IE_NO_CONTENT: 1223 }; /** * Returns whether the given status should be considered successful. * * Successful codes are OK (200), CREATED (201), ACCEPTED (202), * NO CONTENT (204), PARTIAL CONTENT (206), NOT MODIFIED (304), * and IE's no content code (1223). * * @param {number} status The status code to test. * @return {boolean} Whether the status code should be considered successful. */ goog.net.HttpStatus.isSuccess = function(status) { switch (status) { case goog.net.HttpStatus.OK: case goog.net.HttpStatus.CREATED: case goog.net.HttpStatus.ACCEPTED: case goog.net.HttpStatus.NO_CONTENT: case goog.net.HttpStatus.PARTIAL_CONTENT: case goog.net.HttpStatus.NOT_MODIFIED: case goog.net.HttpStatus.QUIRK_IE_NO_CONTENT: return true; default: return false; } };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Helper class to load a list of URIs in bulk. All URIs * must be a successfully loaded in order for the entire load to be considered * a success. * */ goog.provide('goog.net.BulkLoaderHelper'); goog.require('goog.Disposable'); goog.require('goog.debug.Logger'); /** * Helper class used to load multiple URIs. * @param {Array.<string|goog.Uri>} uris The URIs to load. * @constructor * @extends {goog.Disposable} */ goog.net.BulkLoaderHelper = function(uris) { goog.Disposable.call(this); /** * The URIs to load. * @type {Array.<string|goog.Uri>} * @private */ this.uris_ = uris; /** * The response from the XHR's. * @type {Array.<string>} * @private */ this.responseTexts_ = []; }; goog.inherits(goog.net.BulkLoaderHelper, goog.Disposable); /** * A logger. * @type {goog.debug.Logger} * @private */ goog.net.BulkLoaderHelper.prototype.logger_ = goog.debug.Logger.getLogger('goog.net.BulkLoaderHelper'); /** * Gets the URI by id. * @param {number} id The id. * @return {string|goog.Uri} The URI specified by the id. */ goog.net.BulkLoaderHelper.prototype.getUri = function(id) { return this.uris_[id]; }; /** * Gets the URIs. * @return {Array.<string|goog.Uri>} The URIs. */ goog.net.BulkLoaderHelper.prototype.getUris = function() { return this.uris_; }; /** * Gets the response texts. * @return {Array.<string>} The response texts. */ goog.net.BulkLoaderHelper.prototype.getResponseTexts = function() { return this.responseTexts_; }; /** * Sets the response text by id. * @param {number} id The id. * @param {string} responseText The response texts. */ goog.net.BulkLoaderHelper.prototype.setResponseText = function( id, responseText) { this.responseTexts_[id] = responseText; }; /** * Determines if the load of the URIs is complete. * @return {boolean} TRUE iff the load is complete. */ goog.net.BulkLoaderHelper.prototype.isLoadComplete = function() { var responseTexts = this.responseTexts_; if (responseTexts.length == this.uris_.length) { for (var i = 0; i < responseTexts.length; i++) { if (!goog.isDefAndNotNull(responseTexts[i])) { return false; } } return true; } return false; }; /** @override */ goog.net.BulkLoaderHelper.prototype.disposeInternal = function() { goog.net.BulkLoaderHelper.superClass_.disposeInternal.call(this); this.uris_ = null; this.responseTexts_ = null; };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Manages a pool of XhrIo's. This handles all the details of * dealing with the XhrPool and provides a simple interface for sending requests * and managing events. * * This class supports queueing & prioritization of requests (XhrIoPool * handles this) and retrying of requests. * * The events fired by the XhrManager are an aggregation of the events of * each of its XhrIo objects (with some filtering, i.e., ERROR only called * when there are no more retries left). For this reason, all send requests have * to have an id, so that the user of this object can know which event is for * which request. * */ goog.provide('goog.net.XhrManager'); goog.provide('goog.net.XhrManager.Event'); goog.provide('goog.net.XhrManager.Request'); goog.require('goog.Disposable'); goog.require('goog.events'); goog.require('goog.events.Event'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventTarget'); goog.require('goog.net.EventType'); goog.require('goog.net.XhrIo'); goog.require('goog.net.XhrIoPool'); goog.require('goog.structs.Map'); // TODO(user): Add some time in between retries. /** * A manager of an XhrIoPool. * @param {number=} opt_maxRetries Max. number of retries (Default: 1). * @param {goog.structs.Map=} opt_headers Map of default headers to add to every * request. * @param {number=} opt_minCount Min. number of objects (Default: 1). * @param {number=} opt_maxCount Max. number of objects (Default: 10). * @param {number=} opt_timeoutInterval Timeout (in ms) before aborting an * attempt (Default: 0ms). * @constructor * @extends {goog.events.EventTarget} */ goog.net.XhrManager = function( opt_maxRetries, opt_headers, opt_minCount, opt_maxCount, opt_timeoutInterval) { goog.base(this); /** * Maximum number of retries for a given request * @type {number} * @private */ this.maxRetries_ = goog.isDef(opt_maxRetries) ? opt_maxRetries : 1; /** * Timeout interval for an attempt of a given request. * @type {number} * @private */ this.timeoutInterval_ = goog.isDef(opt_timeoutInterval) ? Math.max(0, opt_timeoutInterval) : 0; /** * The pool of XhrIo's to use. * @type {goog.net.XhrIoPool} * @private */ this.xhrPool_ = new goog.net.XhrIoPool( opt_headers, opt_minCount, opt_maxCount); /** * Map of ID's to requests. * @type {goog.structs.Map} * @private */ this.requests_ = new goog.structs.Map(); /** * The event handler. * @type {goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); }; goog.inherits(goog.net.XhrManager, goog.events.EventTarget); /** * Error to throw when a send is attempted with an ID that the manager already * has registered for another request. * @type {string} * @private */ goog.net.XhrManager.ERROR_ID_IN_USE_ = '[goog.net.XhrManager] ID in use'; /** * The goog.net.EventType's to listen/unlisten for on the XhrIo object. * @type {Array.<goog.net.EventType>} * @private */ goog.net.XhrManager.XHR_EVENT_TYPES_ = [ goog.net.EventType.READY, goog.net.EventType.COMPLETE, goog.net.EventType.SUCCESS, goog.net.EventType.ERROR, goog.net.EventType.ABORT, goog.net.EventType.TIMEOUT]; /** * Sets the number of milliseconds after which an incomplete request will be * aborted. Zero means no timeout is set. * @param {number} ms Timeout interval in milliseconds; 0 means none. */ goog.net.XhrManager.prototype.setTimeoutInterval = function(ms) { this.timeoutInterval_ = Math.max(0, ms); }; /** * Returns the number of requests either in flight, or waiting to be sent. * The count will include the current request if used within a COMPLETE event * handler or callback. * @return {number} The number of requests in flight or pending send. */ goog.net.XhrManager.prototype.getOutstandingCount = function() { return this.requests_.getCount(); }; /** * Returns an array of request ids that are either in flight, or waiting to * be sent. The id of the current request will be included if used within a * COMPLETE event handler or callback. * @return {!Array.<string>} Request ids in flight or pending send. */ goog.net.XhrManager.prototype.getOutstandingRequestIds = function() { return this.requests_.getKeys(); }; /** * Registers the given request to be sent. Throws an error if a request * already exists with the given ID. * NOTE: It is not sent immediately. It is queued and will be sent when an * XhrIo object becomes available, taking into account the request's * priority. * @param {string} id The id of the request. * @param {string} url Uri to make the request too. * @param {string=} opt_method Send method, default: GET. * @param {ArrayBuffer|Blob|Document|FormData|string=} opt_content Post data. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the * request. * @param {*=} opt_priority The priority of the request. A smaller value means a * higher priority. * @param {Function=} opt_callback Callback function for when request is * complete. The only param is the event object from the COMPLETE event. * @param {number=} opt_maxRetries The maximum number of times the request * should be retried. * @param {goog.net.XhrIo.ResponseType=} opt_responseType The response type of * this request; defaults to goog.net.XhrIo.ResponseType.DEFAULT. * @return {goog.net.XhrManager.Request} The queued request object. */ goog.net.XhrManager.prototype.send = function( id, url, opt_method, opt_content, opt_headers, opt_priority, opt_callback, opt_maxRetries, opt_responseType) { var requests = this.requests_; // Check if there is already a request with the given id. if (requests.get(id)) { throw Error(goog.net.XhrManager.ERROR_ID_IN_USE_); } // Make the Request object. var request = new goog.net.XhrManager.Request( url, goog.bind(this.handleEvent_, this, id), opt_method, opt_content, opt_headers, opt_callback, goog.isDef(opt_maxRetries) ? opt_maxRetries : this.maxRetries_, opt_responseType); this.requests_.set(id, request); // Setup the callback for the pool. var callback = goog.bind(this.handleAvailableXhr_, this, id); this.xhrPool_.getObject(callback, opt_priority); return request; }; /** * Aborts the request associated with id. * @param {string} id The id of the request to abort. * @param {boolean=} opt_force If true, remove the id now so it can be reused. * No events are fired and the callback is not called when forced. */ goog.net.XhrManager.prototype.abort = function(id, opt_force) { var request = this.requests_.get(id); if (request) { var xhrIo = request.xhrIo; request.setAborted(true); if (opt_force) { if (xhrIo) { // We remove listeners to make sure nothing gets called if a new request // with the same id is made. this.removeXhrListener_(xhrIo, request.getXhrEventCallback()); goog.events.listenOnce( xhrIo, goog.net.EventType.READY, function() { this.xhrPool_.releaseObject(xhrIo); }, false, this); } this.requests_.remove(id); } if (xhrIo) { xhrIo.abort(); } } }; /** * Handles when an XhrIo object becomes available. Sets up the events, fires * the READY event, and starts the process to send the request. * @param {string} id The id of the request the XhrIo is for. * @param {goog.net.XhrIo} xhrIo The available XhrIo object. * @private */ goog.net.XhrManager.prototype.handleAvailableXhr_ = function(id, xhrIo) { var request = this.requests_.get(id); // Make sure the request doesn't already have an XhrIo attached. This can // happen if a forced abort occurs before an XhrIo is available, and a new // request with the same id is made. if (request && !request.xhrIo) { this.addXhrListener_(xhrIo, request.getXhrEventCallback()); // Set properties for the XhrIo. xhrIo.setTimeoutInterval(this.timeoutInterval_); xhrIo.setResponseType(request.getResponseType()); // Add a reference to the XhrIo object to the request. request.xhrIo = request.xhrLite = xhrIo; // Notify the listeners. this.dispatchEvent(new goog.net.XhrManager.Event( goog.net.EventType.READY, this, id, xhrIo)); // Send the request. this.retry_(id, xhrIo); // If the request was aborted before it got an XhrIo object, abort it now. if (request.getAborted()) { xhrIo.abort(); } } else { // If the request has an XhrIo object already, or no request exists, just // return the XhrIo back to the pool. this.xhrPool_.releaseObject(xhrIo); } }; /** * Handles all events fired by the XhrIo object for a given request. * @param {string} id The id of the request. * @param {goog.events.Event} e The event. * @return {Object} The return value from the handler, if any. * @private */ goog.net.XhrManager.prototype.handleEvent_ = function(id, e) { var xhrIo = /** @type {goog.net.XhrIo} */(e.target); switch (e.type) { case goog.net.EventType.READY: this.retry_(id, xhrIo); break; case goog.net.EventType.COMPLETE: return this.handleComplete_(id, xhrIo, e); case goog.net.EventType.SUCCESS: this.handleSuccess_(id, xhrIo); break; // A timeout is handled like an error. case goog.net.EventType.TIMEOUT: case goog.net.EventType.ERROR: this.handleError_(id, xhrIo); break; case goog.net.EventType.ABORT: this.handleAbort_(id, xhrIo); break; } return null; }; /** * Attempts to retry the given request. If the request has already attempted * the maximum number of retries, then it removes the request and releases * the XhrIo object back into the pool. * @param {string} id The id of the request. * @param {goog.net.XhrIo} xhrIo The XhrIo object. * @private */ goog.net.XhrManager.prototype.retry_ = function(id, xhrIo) { var request = this.requests_.get(id); // If the request has not completed and it is below its max. retries. if (request && !request.getCompleted() && !request.hasReachedMaxRetries()) { request.increaseAttemptCount(); xhrIo.send(request.getUrl(), request.getMethod(), request.getContent(), request.getHeaders()); } else { if (request) { // Remove the events on the XhrIo objects. this.removeXhrListener_(xhrIo, request.getXhrEventCallback()); // Remove the request. this.requests_.remove(id); } // Release the XhrIo object back into the pool. this.xhrPool_.releaseObject(xhrIo); } }; /** * Handles the complete of a request. Dispatches the COMPLETE event and sets the * the request as completed if the request has succeeded, or is done retrying. * @param {string} id The id of the request. * @param {goog.net.XhrIo} xhrIo The XhrIo object. * @param {goog.events.Event} e The original event. * @return {Object} The return value from the callback, if any. * @private */ goog.net.XhrManager.prototype.handleComplete_ = function(id, xhrIo, e) { // Only if the request is done processing should a COMPLETE event be fired. var request = this.requests_.get(id); if (xhrIo.getLastErrorCode() == goog.net.ErrorCode.ABORT || xhrIo.isSuccess() || request.hasReachedMaxRetries()) { this.dispatchEvent(new goog.net.XhrManager.Event( goog.net.EventType.COMPLETE, this, id, xhrIo)); // If the request exists, we mark it as completed and call the callback if (request) { request.setCompleted(true); // Call the complete callback as if it was set as a COMPLETE event on the // XhrIo directly. if (request.getCompleteCallback()) { return request.getCompleteCallback().call(xhrIo, e); } } } return null; }; /** * Handles the abort of an underlying XhrIo object. * @param {string} id The id of the request. * @param {goog.net.XhrIo} xhrIo The XhrIo object. * @private */ goog.net.XhrManager.prototype.handleAbort_ = function(id, xhrIo) { // Fire event. // NOTE: The complete event should always be fired before the abort event, so // the bulk of the work is done in handleComplete. this.dispatchEvent(new goog.net.XhrManager.Event( goog.net.EventType.ABORT, this, id, xhrIo)); }; /** * Handles the success of a request. Dispatches the SUCCESS event and sets the * the request as completed. * @param {string} id The id of the request. * @param {goog.net.XhrIo} xhrIo The XhrIo object. * @private */ goog.net.XhrManager.prototype.handleSuccess_ = function(id, xhrIo) { // Fire event. // NOTE: We don't release the XhrIo object from the pool here. // It is released in the retry method, when we know it is back in the // ready state. this.dispatchEvent(new goog.net.XhrManager.Event( goog.net.EventType.SUCCESS, this, id, xhrIo)); }; /** * Handles the error of a request. If the request has not reach its maximum * number of retries, then it lets the request retry naturally (will let the * request hit the READY state). Else, it dispatches the ERROR event. * @param {string} id The id of the request. * @param {goog.net.XhrIo} xhrIo The XhrIo object. * @private */ goog.net.XhrManager.prototype.handleError_ = function(id, xhrIo) { var request = this.requests_.get(id); // If the maximum number of retries has been reached. if (request.hasReachedMaxRetries()) { // Fire event. // NOTE: We don't release the XhrIo object from the pool here. // It is released in the retry method, when we know it is back in the // ready state. this.dispatchEvent(new goog.net.XhrManager.Event( goog.net.EventType.ERROR, this, id, xhrIo)); } }; /** * Remove listeners for XHR events on an XhrIo object. * @param {goog.net.XhrIo} xhrIo The object to stop listenening to events on. * @param {Function} func The callback to remove from event handling. * @param {string|Array.<string>=} opt_types Event types to remove listeners * for. Defaults to XHR_EVENT_TYPES_. * @private */ goog.net.XhrManager.prototype.removeXhrListener_ = function(xhrIo, func, opt_types) { var types = opt_types || goog.net.XhrManager.XHR_EVENT_TYPES_; this.eventHandler_.unlisten(xhrIo, types, func); }; /** * Adds a listener for XHR events on an XhrIo object. * @param {goog.net.XhrIo} xhrIo The object listen to events on. * @param {Function} func The callback when the event occurs. * @param {string|Array.<string>=} opt_types Event types to attach listeners to. * Defaults to XHR_EVENT_TYPES_. * @private */ goog.net.XhrManager.prototype.addXhrListener_ = function(xhrIo, func, opt_types) { var types = opt_types || goog.net.XhrManager.XHR_EVENT_TYPES_; this.eventHandler_.listen(xhrIo, types, func); }; /** @override */ goog.net.XhrManager.prototype.disposeInternal = function() { goog.net.XhrManager.superClass_.disposeInternal.call(this); this.xhrPool_.dispose(); this.xhrPool_ = null; this.eventHandler_.dispose(); this.eventHandler_ = null; // Call dispose on each request. var requests = this.requests_; goog.structs.forEach(requests, function(value, key) { value.dispose(); }); requests.clear(); this.requests_ = null; }; /** * An event dispatched by XhrManager. * * @param {goog.net.EventType} type Event Type. * @param {goog.net.XhrManager} target Reference to the object that is the * target of this event. * @param {string} id The id of the request this event is for. * @param {goog.net.XhrIo} xhrIo The XhrIo object of the request. * @constructor * @extends {goog.events.Event} */ goog.net.XhrManager.Event = function(type, target, id, xhrIo) { goog.events.Event.call(this, type, target); /** * The id of the request this event is for. * @type {string} */ this.id = id; /** * The XhrIo object of the request. * @type {goog.net.XhrIo} */ this.xhrIo = xhrIo; /** * The xhrLite field aliases xhrIo for backwards compatibility. * @type {goog.net.XhrLite} */ this.xhrLite = /** @type {goog.net.XhrLite} */ (xhrIo); }; goog.inherits(goog.net.XhrManager.Event, goog.events.Event); /** * An encapsulation of everything needed to make a Xhr request. * NOTE: This is used internal to the XhrManager. * * @param {string} url Uri to make the request too. * @param {Function} xhrEventCallback Callback attached to the events of the * XhrIo object of the request. * @param {string=} opt_method Send method, default: GET. * @param {ArrayBuffer|Blob|Document|FormData|string=} opt_content Post data. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the * request. * @param {Function=} opt_callback Callback function for when request is * complete. NOTE: Only 1 callback supported across all events. * @param {number=} opt_maxRetries The maximum number of times the request * should be retried (Default: 1). * @param {goog.net.XhrIo.ResponseType=} opt_responseType The response type of * this request; defaults to goog.net.XhrIo.ResponseType.DEFAULT. * * @constructor * @extends {goog.Disposable} */ goog.net.XhrManager.Request = function(url, xhrEventCallback, opt_method, opt_content, opt_headers, opt_callback, opt_maxRetries, opt_responseType) { goog.Disposable.call(this); /** * Uri to make the request too. * @type {string} * @private */ this.url_ = url; /** * Send method. * @type {string} * @private */ this.method_ = opt_method || 'GET'; /** * Post data. * @type {ArrayBuffer|Blob|Document|FormData|string|undefined} * @private */ this.content_ = opt_content; /** * Map of headers * @type {Object|goog.structs.Map|null} * @private */ this.headers_ = opt_headers || null; /** * The maximum number of times the request should be retried. * @type {number} * @private */ this.maxRetries_ = goog.isDef(opt_maxRetries) ? opt_maxRetries : 1; /** * The number of attempts so far. * @type {number} * @private */ this.attemptCount_ = 0; /** * Whether the request has been completed. * @type {boolean} * @private */ this.completed_ = false; /** * Whether the request has been aborted. * @type {boolean} * @private */ this.aborted_ = false; /** * Callback attached to the events of the XhrIo object. * @type {Function|undefined} * @private */ this.xhrEventCallback_ = xhrEventCallback; /** * Callback function called when request is complete. * @type {Function|undefined} * @private */ this.completeCallback_ = opt_callback; /** * A response type to set on this.xhrIo when it's populated. * @type {!goog.net.XhrIo.ResponseType} * @private */ this.responseType_ = opt_responseType || goog.net.XhrIo.ResponseType.DEFAULT; /** * The XhrIo instance handling this request. Set in handleAvailableXhr. * @type {goog.net.XhrIo} */ this.xhrIo = null; }; goog.inherits(goog.net.XhrManager.Request, goog.Disposable); /** * Gets the uri. * @return {string} The uri to make the request to. */ goog.net.XhrManager.Request.prototype.getUrl = function() { return this.url_; }; /** * Gets the send method. * @return {string} The send method. */ goog.net.XhrManager.Request.prototype.getMethod = function() { return this.method_; }; /** * Gets the post data. * @return {ArrayBuffer|Blob|Document|FormData|string|undefined} * The post data. */ goog.net.XhrManager.Request.prototype.getContent = function() { return this.content_; }; /** * Gets the map of headers. * @return {Object|goog.structs.Map} The map of headers. */ goog.net.XhrManager.Request.prototype.getHeaders = function() { return this.headers_; }; /** * Gets the maximum number of times the request should be retried. * @return {number} The maximum number of times the request should be retried. */ goog.net.XhrManager.Request.prototype.getMaxRetries = function() { return this.maxRetries_; }; /** * Gets the number of attempts so far. * @return {number} The number of attempts so far. */ goog.net.XhrManager.Request.prototype.getAttemptCount = function() { return this.attemptCount_; }; /** * Increases the number of attempts so far. */ goog.net.XhrManager.Request.prototype.increaseAttemptCount = function() { this.attemptCount_++; }; /** * Returns whether the request has reached the maximum number of retries. * @return {boolean} Whether the request has reached the maximum number of * retries. */ goog.net.XhrManager.Request.prototype.hasReachedMaxRetries = function() { return this.attemptCount_ > this.maxRetries_; }; /** * Sets the completed status. * @param {boolean} complete The completed status. */ goog.net.XhrManager.Request.prototype.setCompleted = function(complete) { this.completed_ = complete; }; /** * Gets the completed status. * @return {boolean} The completed status. */ goog.net.XhrManager.Request.prototype.getCompleted = function() { return this.completed_; }; /** * Sets the aborted status. * @param {boolean} aborted True if the request was aborted, otherwise False. */ goog.net.XhrManager.Request.prototype.setAborted = function(aborted) { this.aborted_ = aborted; }; /** * Gets the aborted status. * @return {boolean} True if request was aborted, otherwise False. */ goog.net.XhrManager.Request.prototype.getAborted = function() { return this.aborted_; }; /** * Gets the callback attached to the events of the XhrIo object. * @return {Function|undefined} The callback attached to the events of the * XhrIo object. */ goog.net.XhrManager.Request.prototype.getXhrEventCallback = function() { return this.xhrEventCallback_; }; /** * Gets the callback for when the request is complete. * @return {Function|undefined} The callback for when the request is complete. */ goog.net.XhrManager.Request.prototype.getCompleteCallback = function() { return this.completeCallback_; }; /** * Gets the response type that will be set on this request's XhrIo when it's * available. * @return {!goog.net.XhrIo.ResponseType} The response type to be set * when an XhrIo becomes available to this request. */ goog.net.XhrManager.Request.prototype.getResponseType = function() { return this.responseType_; }; /** @override */ goog.net.XhrManager.Request.prototype.disposeInternal = function() { goog.net.XhrManager.Request.superClass_.disposeInternal.call(this); delete this.xhrEventCallback_; delete this.completeCallback_; };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Low level handling of XMLHttpRequest. * @author arv@google.com (Erik Arvidsson) * @author dbk@google.com (David Barrett-Kahn) */ goog.provide('goog.net.DefaultXmlHttpFactory'); goog.provide('goog.net.XmlHttp'); goog.provide('goog.net.XmlHttp.OptionType'); goog.provide('goog.net.XmlHttp.ReadyState'); goog.require('goog.net.WrapperXmlHttpFactory'); goog.require('goog.net.XmlHttpFactory'); /** * Static class for creating XMLHttpRequest objects. * @return {!(XMLHttpRequest|GearsHttpRequest)} A new XMLHttpRequest object. */ goog.net.XmlHttp = function() { return goog.net.XmlHttp.factory_.createInstance(); }; /** * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to * true strips the ActiveX probing code. */ goog.net.XmlHttp.ASSUME_NATIVE_XHR = false; /** * Gets the options to use with the XMLHttpRequest objects obtained using * the static methods. * @return {Object} The options. */ goog.net.XmlHttp.getOptions = function() { return goog.net.XmlHttp.factory_.getOptions(); }; /** * Type of options that an XmlHttp object can have. * @enum {number} */ goog.net.XmlHttp.OptionType = { /** * Whether a goog.nullFunction should be used to clear the onreadystatechange * handler instead of null. */ USE_NULL_FUNCTION: 0, /** * NOTE(user): In IE if send() errors on a *local* request the readystate * is still changed to COMPLETE. We need to ignore it and allow the * try/catch around send() to pick up the error. */ LOCAL_REQUEST_ERROR: 1 }; /** * Status constants for XMLHTTP, matches: * http://msdn.microsoft.com/library/default.asp?url=/library/ * en-us/xmlsdk/html/0e6a34e4-f90c-489d-acff-cb44242fafc6.asp * @enum {number} */ goog.net.XmlHttp.ReadyState = { /** * Constant for when xmlhttprequest.readyState is uninitialized */ UNINITIALIZED: 0, /** * Constant for when xmlhttprequest.readyState is loading. */ LOADING: 1, /** * Constant for when xmlhttprequest.readyState is loaded. */ LOADED: 2, /** * Constant for when xmlhttprequest.readyState is in an interactive state. */ INTERACTIVE: 3, /** * Constant for when xmlhttprequest.readyState is completed */ COMPLETE: 4 }; /** * The global factory instance for creating XMLHttpRequest objects. * @type {goog.net.XmlHttpFactory} * @private */ goog.net.XmlHttp.factory_; /** * Sets the factories for creating XMLHttpRequest objects and their options. * @param {Function} factory The factory for XMLHttpRequest objects. * @param {Function} optionsFactory The factory for options. * @deprecated Use setGlobalFactory instead. */ goog.net.XmlHttp.setFactory = function(factory, optionsFactory) { goog.net.XmlHttp.setGlobalFactory(new goog.net.WrapperXmlHttpFactory( /** @type {function() : !(XMLHttpRequest|GearsHttpRequest)} */ (factory), /** @type {function() : !Object}*/ (optionsFactory))); }; /** * Sets the global factory object. * @param {!goog.net.XmlHttpFactory} factory New global factory object. */ goog.net.XmlHttp.setGlobalFactory = function(factory) { goog.net.XmlHttp.factory_ = factory; }; /** * Default factory to use when creating xhr objects. You probably shouldn't be * instantiating this directly, but rather using it via goog.net.XmlHttp. * @extends {goog.net.XmlHttpFactory} * @constructor */ goog.net.DefaultXmlHttpFactory = function() { goog.net.XmlHttpFactory.call(this); }; goog.inherits(goog.net.DefaultXmlHttpFactory, goog.net.XmlHttpFactory); /** @override */ goog.net.DefaultXmlHttpFactory.prototype.createInstance = function() { var progId = this.getProgId_(); if (progId) { return new ActiveXObject(progId); } else { return new XMLHttpRequest(); } }; /** @override */ goog.net.DefaultXmlHttpFactory.prototype.internalGetOptions = function() { var progId = this.getProgId_(); var options = {}; if (progId) { options[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] = true; options[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] = true; } return options; }; /** * The ActiveX PROG ID string to use to create xhr's in IE. Lazily initialized. * @type {string|undefined} * @private */ goog.net.DefaultXmlHttpFactory.prototype.ieProgId_; /** * Initialize the private state used by other functions. * @return {string} The ActiveX PROG ID string to use to create xhr's in IE. * @private */ goog.net.DefaultXmlHttpFactory.prototype.getProgId_ = function() { if (goog.net.XmlHttp.ASSUME_NATIVE_XHR) { return ''; } // The following blog post describes what PROG IDs to use to create the // XMLHTTP object in Internet Explorer: // http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx // However we do not (yet) fully trust that this will be OK for old versions // of IE on Win9x so we therefore keep the last 2. if (!this.ieProgId_ && typeof XMLHttpRequest == 'undefined' && typeof ActiveXObject != 'undefined') { // Candidate Active X types. var ACTIVE_X_IDENTS = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP']; for (var i = 0; i < ACTIVE_X_IDENTS.length; i++) { var candidate = ACTIVE_X_IDENTS[i]; /** @preserveTry */ try { new ActiveXObject(candidate); // NOTE(user): cannot assign progid and return candidate in one line // because JSCompiler complaings: BUG 658126 this.ieProgId_ = candidate; return candidate; } catch (e) { // do nothing; try next choice } } // couldn't find any matches throw Error('Could not create ActiveXObject. ActiveX might be disabled,' + ' or MSXML might not be installed'); } return /** @type {string} */ (this.ieProgId_); }; //Set the global factory to an instance of the default factory. goog.net.XmlHttp.setGlobalFactory(new goog.net.DefaultXmlHttpFactory());
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Mock of XhrLite for unit testing. * */ goog.provide('goog.net.MockXhrLite'); goog.require('goog.testing.net.XhrIo'); /** * Mock implementation of goog.net.XhrLite. This doesn't provide a mock * implementation for all cases, but it's not too hard to add them as needed. * @param {goog.testing.TestQueue=} opt_testQueue Test queue for inserting test * events. * @deprecated Use goog.testing.net.XhrIo. * @constructor */ goog.net.MockXhrLite = goog.testing.net.XhrIo;
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Creates a pool of XhrLite objects to use. This allows multiple * XhrLite objects to be grouped together and requests will use next available * XhrLite object. * */ goog.provide('goog.net.XhrLitePool'); goog.require('goog.net.XhrIoPool'); /** * A pool of XhrLite objects. * @param {goog.structs.Map=} opt_headers Map of default headers to add to every * request. * @param {number=} opt_minCount Min. number of objects (Default: 1). * @param {number=} opt_maxCount Max. number of objects (Default: 10). * @deprecated Use goog.net.XhrIoPool. * @constructor */ goog.net.XhrLitePool = goog.net.XhrIoPool;
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Functions for setting, getting and deleting cookies. * * @author arv@google.com (Erik Arvidsson) */ goog.provide('goog.net.Cookies'); goog.provide('goog.net.cookies'); /** * A class for handling browser cookies. * @param {Document} context The context document to get/set cookies on. * @constructor */ goog.net.Cookies = function(context) { /** * The context document to get/set cookies on * @type {Document} * @private */ this.document_ = context; }; /** * Static constant for the size of cookies. Per the spec, there's a 4K limit * to the size of a cookie. To make sure users can't break this limit, we * should truncate long cookies at 3950 bytes, to be extra careful with dumb * browsers/proxies that interpret 4K as 4000 rather than 4096. * @type {number} */ goog.net.Cookies.MAX_COOKIE_LENGTH = 3950; /** * RegExp used to split the cookies string. * @type {RegExp} * @private */ goog.net.Cookies.SPLIT_RE_ = /\s*;\s*/; /** * Returns true if cookies are enabled. * @return {boolean} True if cookies are enabled. */ goog.net.Cookies.prototype.isEnabled = function() { return navigator.cookieEnabled; }; /** * We do not allow '=', ';', or white space in the name. * * NOTE: The following are allowed by this method, but should be avoided for * cookies handled by the server. * - any name starting with '$' * - 'Comment' * - 'Domain' * - 'Expires' * - 'Max-Age' * - 'Path' * - 'Secure' * - 'Version' * * @param {string} name Cookie name. * @return {boolean} Whether name is valid. * * @see <a href="http://tools.ietf.org/html/rfc2109">RFC 2109</a> * @see <a href="http://tools.ietf.org/html/rfc2965">RFC 2965</a> */ goog.net.Cookies.prototype.isValidName = function(name) { return !(/[;=\s]/.test(name)); }; /** * We do not allow ';' or line break in the value. * * Spec does not mention any illegal characters, but in practice semi-colons * break parsing and line breaks truncate the name. * * @param {string} value Cookie value. * @return {boolean} Whether value is valid. * * @see <a href="http://tools.ietf.org/html/rfc2109">RFC 2109</a> * @see <a href="http://tools.ietf.org/html/rfc2965">RFC 2965</a> */ goog.net.Cookies.prototype.isValidValue = function(value) { return !(/[;\r\n]/.test(value)); }; /** * Sets a cookie. The max_age can be -1 to set a session cookie. To remove and * expire cookies, use remove() instead. * * Neither the {@code name} nor the {@code value} are encoded in any way. It is * up to the callers of {@code get} and {@code set} (as well as all the other * methods) to handle any possible encoding and decoding. * * @throws {!Error} If the {@code name} fails #goog.net.cookies.isValidName. * @throws {!Error} If the {@code value} fails #goog.net.cookies.isValidValue. * * @param {string} name The cookie name. * @param {string} value The cookie value. * @param {number=} opt_maxAge The max age in seconds (from now). Use -1 to * set a session cookie. If not provided, the default is -1 * (i.e. set a session cookie). * @param {?string=} opt_path The path of the cookie. If not present then this * uses the full request path. * @param {?string=} opt_domain The domain of the cookie, or null to not * specify a domain attribute (browser will use the full request host name). * If not provided, the default is null (i.e. let browser use full request * host name). * @param {boolean=} opt_secure Whether the cookie should only be sent over * a secure channel. */ goog.net.Cookies.prototype.set = function( name, value, opt_maxAge, opt_path, opt_domain, opt_secure) { if (!this.isValidName(name)) { throw Error('Invalid cookie name "' + name + '"'); } if (!this.isValidValue(value)) { throw Error('Invalid cookie value "' + value + '"'); } if (!goog.isDef(opt_maxAge)) { opt_maxAge = -1; } var domainStr = opt_domain ? ';domain=' + opt_domain : ''; var pathStr = opt_path ? ';path=' + opt_path : ''; var secureStr = opt_secure ? ';secure' : ''; var expiresStr; // Case 1: Set a session cookie. if (opt_maxAge < 0) { expiresStr = ''; // Case 2: Expire the cookie. // Note: We don't tell people about this option in the function doc because // we prefer people to use ExpireCookie() to expire cookies. } else if (opt_maxAge == 0) { // Note: Don't use Jan 1, 1970 for date because NS 4.76 will try to convert // it to local time, and if the local time is before Jan 1, 1970, then the // browser will ignore the Expires attribute altogether. var pastDate = new Date(1970, 1 /*Feb*/, 1); // Feb 1, 1970 expiresStr = ';expires=' + pastDate.toUTCString(); // Case 3: Set a persistent cookie. } else { var futureDate = new Date(goog.now() + opt_maxAge * 1000); expiresStr = ';expires=' + futureDate.toUTCString(); } this.setCookie_(name + '=' + value + domainStr + pathStr + expiresStr + secureStr); }; /** * Returns the value for the first cookie with the given name. * @param {string} name The name of the cookie to get. * @param {string=} opt_default If not found this is returned instead. * @return {string|undefined} The value of the cookie. If no cookie is set this * returns opt_default or undefined if opt_default is not provided. */ goog.net.Cookies.prototype.get = function(name, opt_default) { var nameEq = name + '='; var parts = this.getParts_(); for (var i = 0, part; part = parts[i]; i++) { // startsWith if (part.lastIndexOf(nameEq, 0) == 0) { return part.substr(nameEq.length); } if (part == name) { return ''; } } return opt_default; }; /** * Removes and expires a cookie. * @param {string} name The cookie name. * @param {string=} opt_path The path of the cookie, or null to expire a cookie * set at the full request path. If not provided, the default is '/' * (i.e. path=/). * @param {string=} opt_domain The domain of the cookie, or null to expire a * cookie set at the full request host name. If not provided, the default is * null (i.e. cookie at full request host name). * @return {boolean} Whether the cookie existed before it was removed. */ goog.net.Cookies.prototype.remove = function(name, opt_path, opt_domain) { var rv = this.containsKey(name); this.set(name, '', 0, opt_path, opt_domain); return rv; }; /** * Gets the names for all the cookies. * @return {Array.<string>} An array with the names of the cookies. */ goog.net.Cookies.prototype.getKeys = function() { return this.getKeyValues_().keys; }; /** * Gets the values for all the cookies. * @return {Array.<string>} An array with the values of the cookies. */ goog.net.Cookies.prototype.getValues = function() { return this.getKeyValues_().values; }; /** * @return {boolean} Whether there are any cookies for this document. */ goog.net.Cookies.prototype.isEmpty = function() { return !this.getCookie_(); }; /** * @return {number} The number of cookies for this document. */ goog.net.Cookies.prototype.getCount = function() { var cookie = this.getCookie_(); if (!cookie) { return 0; } return this.getParts_().length; }; /** * Returns whether there is a cookie with the given name. * @param {string} key The name of the cookie to test for. * @return {boolean} Whether there is a cookie by that name. */ goog.net.Cookies.prototype.containsKey = function(key) { // substring will return empty string if the key is not found, so the get // function will only return undefined return goog.isDef(this.get(key)); }; /** * Returns whether there is a cookie with the given value. (This is an O(n) * operation.) * @param {string} value The value to check for. * @return {boolean} Whether there is a cookie with that value. */ goog.net.Cookies.prototype.containsValue = function(value) { // this O(n) in any case so lets do the trivial thing. var values = this.getKeyValues_().values; for (var i = 0; i < values.length; i++) { if (values[i] == value) { return true; } } return false; }; /** * Removes all cookies for this document. Note that this will only remove * cookies from the current path and domain. If there are cookies set using a * subpath and/or another domain these will still be there. */ goog.net.Cookies.prototype.clear = function() { var keys = this.getKeyValues_().keys; for (var i = keys.length - 1; i >= 0; i--) { this.remove(keys[i]); } }; /** * Private helper function to allow testing cookies without depending on the * browser. * @param {string} s The cookie string to set. * @private */ goog.net.Cookies.prototype.setCookie_ = function(s) { this.document_.cookie = s; }; /** * Private helper function to allow testing cookies without depending on the * browser. IE6 can return null here. * @return {?string} Returns the {@code document.cookie}. * @private */ goog.net.Cookies.prototype.getCookie_ = function() { return this.document_.cookie; }; /** * @return {!Array.<string>} The cookie split on semi colons. * @private */ goog.net.Cookies.prototype.getParts_ = function() { return (this.getCookie_() || ''). split(goog.net.Cookies.SPLIT_RE_); }; /** * Gets the names and values for all the cookies. * @return {Object} An object with keys and values. * @private */ goog.net.Cookies.prototype.getKeyValues_ = function() { var parts = this.getParts_(); var keys = [], values = [], index, part; for (var i = 0; part = parts[i]; i++) { index = part.indexOf('='); if (index == -1) { // empty name keys.push(''); values.push(part); } else { keys.push(part.substring(0, index)); values.push(part.substring(index + 1)); } } return {keys: keys, values: values}; }; /** * A static default instance. * @type {goog.net.Cookies} */ goog.net.cookies = new goog.net.Cookies(document); /** * Define the constant on the instance in order not to break many references to * it. * @type {number} * @deprecated Use goog.net.Cookies.MAX_COOKIE_LENGTH instead. */ goog.net.cookies.MAX_COOKIE_LENGTH = goog.net.Cookies.MAX_COOKIE_LENGTH;
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Error codes shared between goog.net.IframeIo and * goog.net.XhrIo. */ goog.provide('goog.net.ErrorCode'); /** * Error codes * @enum {number} */ goog.net.ErrorCode = { /** * There is no error condition. */ NO_ERROR: 0, /** * The most common error from iframeio, unfortunately, is that the browser * responded with an error page that is classed as a different domain. The * situations, are when a browser error page is shown -- 404, access denied, * DNS failure, connection reset etc.) * */ ACCESS_DENIED: 1, /** * Currently the only case where file not found will be caused is when the * code is running on the local file system and a non-IE browser makes a * request to a file that doesn't exist. */ FILE_NOT_FOUND: 2, /** * If Firefox shows a browser error page, such as a connection reset by * server or access denied, then it will fail silently without the error or * load handlers firing. */ FF_SILENT_ERROR: 3, /** * Custom error provided by the client through the error check hook. */ CUSTOM_ERROR: 4, /** * Exception was thrown while processing the request. */ EXCEPTION: 5, /** * The Http response returned a non-successful http status code. */ HTTP_ERROR: 6, /** * The request was aborted. */ ABORT: 7, /** * The request timed out. */ TIMEOUT: 8, /** * The resource is not available offline. */ OFFLINE: 9 }; /** * Returns a friendly error message for an error code. These messages are for * debugging and are not localized. * @param {goog.net.ErrorCode} errorCode An error code. * @return {string} A message for debugging. */ goog.net.ErrorCode.getDebugMessage = function(errorCode) { switch (errorCode) { case goog.net.ErrorCode.NO_ERROR: return 'No Error'; case goog.net.ErrorCode.ACCESS_DENIED: return 'Access denied to content document'; case goog.net.ErrorCode.FILE_NOT_FOUND: return 'File not found'; case goog.net.ErrorCode.FF_SILENT_ERROR: return 'Firefox silently errored'; case goog.net.ErrorCode.CUSTOM_ERROR: return 'Application custom error'; case goog.net.ErrorCode.EXCEPTION: return 'An exception occurred'; case goog.net.ErrorCode.HTTP_ERROR: return 'Http response at 400 or 500 level'; case goog.net.ErrorCode.ABORT: return 'Request was aborted'; case goog.net.ErrorCode.TIMEOUT: return 'Request timed out'; case goog.net.ErrorCode.OFFLINE: return 'The resource is not available offline'; default: return 'Unrecognized error code'; } };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Class that can be used to determine when an iframe is loaded. */ goog.provide('goog.net.IframeLoadMonitor'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.events.EventTarget'); goog.require('goog.events.EventType'); goog.require('goog.userAgent'); /** * The correct way to determine whether an iframe has completed loading * is different in IE and Firefox. This class abstracts above these * differences, providing a consistent interface for: * <ol> * <li> Determing if an iframe is currently loaded * <li> Listening for an iframe that is not currently loaded, to finish loading * </ol> * * @param {HTMLIFrameElement} iframe An iframe. * @param {boolean=} opt_hasContent Does the loaded iframe have content. * @extends {goog.events.EventTarget} * @constructor */ goog.net.IframeLoadMonitor = function(iframe, opt_hasContent) { goog.base(this); /** * Iframe whose load state is monitored by this IframeLoadMonitor * @type {HTMLIFrameElement} * @private */ this.iframe_ = iframe; /** * Whether or not the loaded iframe has any content. * @type {boolean} * @private */ this.hasContent_ = !!opt_hasContent; /** * Whether or not the iframe is loaded. * @type {boolean} * @private */ this.isLoaded_ = this.isLoadedHelper_(); if (!this.isLoaded_) { // IE 6 (and lower?) does not reliably fire load events, so listen to // readystatechange. // IE 7 does not reliably fire readystatechange events but listening on load // seems to work just fine. var isIe6OrLess = goog.userAgent.IE && !goog.userAgent.isVersion('7'); var loadEvtType = isIe6OrLess ? goog.events.EventType.READYSTATECHANGE : goog.events.EventType.LOAD; this.onloadListenerKey_ = goog.events.listen( this.iframe_, loadEvtType, this.handleLoad_, false, this); // Sometimes we still don't get the event callback, so we'll poll just to // be safe. this.intervalId_ = window.setInterval( goog.bind(this.handleLoad_, this), goog.net.IframeLoadMonitor.POLL_INTERVAL_MS_); } }; goog.inherits(goog.net.IframeLoadMonitor, goog.events.EventTarget); /** * Event type dispatched by a goog.net.IframeLoadMonitor when it internal iframe * finishes loading for the first time after construction of the * goog.net.IframeLoadMonitor * @type {string} */ goog.net.IframeLoadMonitor.LOAD_EVENT = 'ifload'; /** * Poll interval for polling iframe load states in milliseconds. * @type {number} * @private */ goog.net.IframeLoadMonitor.POLL_INTERVAL_MS_ = 100; /** * Key for iframe load listener, or null if not currently listening on the * iframe for a load event. * @type {goog.events.Key} * @private */ goog.net.IframeLoadMonitor.prototype.onloadListenerKey_ = null; /** * Returns whether or not the iframe is loaded. * @return {boolean} whether or not the iframe is loaded. */ goog.net.IframeLoadMonitor.prototype.isLoaded = function() { return this.isLoaded_; }; /** * Stops the poll timer if this IframeLoadMonitor is currently polling. * @private */ goog.net.IframeLoadMonitor.prototype.maybeStopTimer_ = function() { if (this.intervalId_) { window.clearInterval(this.intervalId_); this.intervalId_ = null; } }; /** * Returns the iframe whose load state this IframeLoader monitors. * @return {HTMLIFrameElement} the iframe whose load state this IframeLoader * monitors. */ goog.net.IframeLoadMonitor.prototype.getIframe = function() { return this.iframe_; }; /** @override */ goog.net.IframeLoadMonitor.prototype.disposeInternal = function() { delete this.iframe_; this.maybeStopTimer_(); goog.events.unlistenByKey(this.onloadListenerKey_); goog.net.IframeLoadMonitor.superClass_.disposeInternal.call(this); }; /** * Returns whether or not the iframe is loaded. Determines this by inspecting * browser dependent properties of the iframe. * @return {boolean} whether or not the iframe is loaded. * @private */ goog.net.IframeLoadMonitor.prototype.isLoadedHelper_ = function() { var isLoaded = false; /** @preserveTry */ try { // IE will reliably have readyState set to complete if the iframe is loaded // For everything else, the iframe is loaded if there is a body and if the // body should have content the firstChild exists. Firefox can fire // the LOAD event and then a few hundred ms later replace the // contentDocument once the content is loaded. isLoaded = goog.userAgent.IE ? this.iframe_.readyState == 'complete' : !!goog.dom.getFrameContentDocument(this.iframe_).body && (!this.hasContent_ || !!goog.dom.getFrameContentDocument(this.iframe_).body.firstChild); } catch (e) { // Ignore these errors. This just means that the iframe is not loaded // IE will throw error reading readyState if the iframe is not appended // to the dom yet. // Firefox will throw error getting the iframe body if the iframe is not // fully loaded. } return isLoaded; }; /** * Handles an event indicating that the loading status of the iframe has * changed. In Firefox this is a goog.events.EventType.LOAD event, in IE * this is a goog.events.EventType.READYSTATECHANGED * @private */ goog.net.IframeLoadMonitor.prototype.handleLoad_ = function() { // Only do the handler if the iframe is loaded. if (this.isLoadedHelper_()) { this.maybeStopTimer_(); goog.events.unlistenByKey(this.onloadListenerKey_); this.onloadListenerKey_ = null; this.isLoaded_ = true; this.dispatchEvent(goog.net.IframeLoadMonitor.LOAD_EVENT); } };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Creates a pool of XhrIo objects to use. This allows multiple * XhrIo objects to be grouped together and requests will use next available * XhrIo object. * */ goog.provide('goog.net.XhrIoPool'); goog.require('goog.net.XhrIo'); goog.require('goog.structs'); goog.require('goog.structs.PriorityPool'); /** * A pool of XhrIo objects. * @param {goog.structs.Map=} opt_headers Map of default headers to add to every * request. * @param {number=} opt_minCount Minimum number of objects (Default: 1). * @param {number=} opt_maxCount Maximum number of objects (Default: 10). * @constructor * @extends {goog.structs.PriorityPool} */ goog.net.XhrIoPool = function(opt_headers, opt_minCount, opt_maxCount) { goog.structs.PriorityPool.call(this, opt_minCount, opt_maxCount); /** * Map of default headers to add to every request. * @type {goog.structs.Map|undefined} * @private */ this.headers_ = opt_headers; }; goog.inherits(goog.net.XhrIoPool, goog.structs.PriorityPool); /** * Creates an instance of an XhrIo object to use in the pool. * @return {goog.net.XhrIo} The created object. * @override */ goog.net.XhrIoPool.prototype.createObject = function() { var xhrIo = new goog.net.XhrIo(); var headers = this.headers_; if (headers) { goog.structs.forEach(headers, function(value, key) { xhrIo.headers.set(key, value); }); } return xhrIo; }; /** * Determine if an object has become unusable and should not be used. * @param {Object} obj The object to test. * @return {boolean} Whether the object can be reused, which is true if the * object is not disposed and not active. * @override */ goog.net.XhrIoPool.prototype.objectCanBeReused = function(obj) { // An active XhrIo object should never be used. var xhr = /** @type {goog.net.XhrIo} */ (obj); return !xhr.isDisposed() && !xhr.isActive(); };
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Implementation of XmlHttpFactory which allows construction from * simple factory methods. * @author dbk@google.com (David Barrett-Kahn) */ goog.provide('goog.net.WrapperXmlHttpFactory'); goog.require('goog.net.XmlHttpFactory'); /** * An xhr factory subclass which can be constructed using two factory methods. * This exists partly to allow the preservation of goog.net.XmlHttp.setFactory() * with an unchanged signature. * @param {function() : !(XMLHttpRequest|GearsHttpRequest)} xhrFactory A * function which returns a new XHR object. * @param {function() : !Object} optionsFactory A function which returns the * options associated with xhr objects from this factory. * @extends {goog.net.XmlHttpFactory} * @constructor */ goog.net.WrapperXmlHttpFactory = function(xhrFactory, optionsFactory) { goog.net.XmlHttpFactory.call(this); /** * XHR factory method. * @type {function() : !(XMLHttpRequest|GearsHttpRequest)} * @private */ this.xhrFactory_ = xhrFactory; /** * Options factory method. * @type {function() : !Object} * @private */ this.optionsFactory_ = optionsFactory; }; goog.inherits(goog.net.WrapperXmlHttpFactory, goog.net.XmlHttpFactory); /** @override */ goog.net.WrapperXmlHttpFactory.prototype.createInstance = function() { return this.xhrFactory_(); }; /** @override */ goog.net.WrapperXmlHttpFactory.prototype.getOptions = function() { return this.optionsFactory_(); };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Definition of the WebSocket class. A WebSocket provides a * bi-directional, full-duplex communications channel, over a single TCP socket. * * See http://dev.w3.org/html5/websockets/ * for the full HTML5 WebSocket API. * * Typical usage will look like this: * * var ws = new goog.net.WebSocket(); * * var handler = new goog.events.EventHandler(); * handler.listen(ws, goog.net.WebSocket.EventType.OPENED, onOpen); * handler.listen(ws, goog.net.WebSocket.EventType.MESSAGE, onMessage); * * try { * ws.open('ws://127.0.0.1:4200'); * } catch (e) { * ... * } * */ goog.provide('goog.net.WebSocket'); goog.provide('goog.net.WebSocket.ErrorEvent'); goog.provide('goog.net.WebSocket.EventType'); goog.provide('goog.net.WebSocket.MessageEvent'); goog.require('goog.Timer'); goog.require('goog.asserts'); goog.require('goog.debug.Logger'); goog.require('goog.debug.entryPointRegistry'); goog.require('goog.events'); goog.require('goog.events.Event'); goog.require('goog.events.EventTarget'); /** * Class encapsulating the logic for using a WebSocket. * * @param {boolean=} opt_autoReconnect True if the web socket should * automatically reconnect or not. This is true by default. * @param {function(number):number=} opt_getNextReconnect A function for * obtaining the time until the next reconnect attempt. Given the reconnect * attempt count (which is a positive integer), the function should return a * positive integer representing the milliseconds to the next reconnect * attempt. The default function used is an exponential back-off. Note that * this function is never called if auto reconnect is disabled. * @constructor * @extends {goog.events.EventTarget} */ goog.net.WebSocket = function(opt_autoReconnect, opt_getNextReconnect) { goog.base(this); /** * True if the web socket should automatically reconnect or not. * @type {boolean} * @private */ this.autoReconnect_ = goog.isDef(opt_autoReconnect) ? opt_autoReconnect : true; /** * A function for obtaining the time until the next reconnect attempt. * Given the reconnect attempt count (which is a positive integer), the * function should return a positive integer representing the milliseconds to * the next reconnect attempt. * @type {function(number):number} * @private */ this.getNextReconnect_ = opt_getNextReconnect || goog.net.WebSocket.EXPONENTIAL_BACKOFF_; /** * The time, in milliseconds, that must elapse before the next attempt to * reconnect. * @type {number} * @private */ this.nextReconnect_ = this.getNextReconnect_(this.reconnectAttempt_); }; goog.inherits(goog.net.WebSocket, goog.events.EventTarget); /** * The actual web socket that will be used to send/receive messages. * @type {WebSocket} * @private */ goog.net.WebSocket.prototype.webSocket_ = null; /** * The URL to which the web socket will connect. * @type {?string} * @private */ goog.net.WebSocket.prototype.url_ = null; /** * The subprotocol name used when establishing the web socket connection. * @type {string|undefined} * @private */ goog.net.WebSocket.prototype.protocol_ = undefined; /** * True if a call to the close callback is expected or not. * @type {boolean} * @private */ goog.net.WebSocket.prototype.closeExpected_ = false; /** * Keeps track of the number of reconnect attempts made since the last * successful connection. * @type {number} * @private */ goog.net.WebSocket.prototype.reconnectAttempt_ = 0; /** * The logger for this class. * @type {goog.debug.Logger} * @private */ goog.net.WebSocket.prototype.logger_ = goog.debug.Logger.getLogger( 'goog.net.WebSocket'); /** * The events fired by the web socket. * @enum {string} The event types for the web socket. */ goog.net.WebSocket.EventType = { /** * Fired when an attempt to open the WebSocket fails or there is a connection * failure after a successful connection has been established. */ CLOSED: goog.events.getUniqueId('closed'), /** * Fired when the WebSocket encounters an error. */ ERROR: goog.events.getUniqueId('error'), /** * Fired when a new message arrives from the WebSocket. */ MESSAGE: goog.events.getUniqueId('message'), /** * Fired when the WebSocket connection has been established. */ OPENED: goog.events.getUniqueId('opened') }; /** * The various states of the web socket. * @enum {number} The states of the web socket. * @private */ goog.net.WebSocket.ReadyState_ = { // This is the initial state during construction. CONNECTING: 0, // This is when the socket is actually open and ready for data. OPEN: 1, // This is when the socket is in the middle of a close handshake. // Note that this is a valid state even if the OPEN state was never achieved. CLOSING: 2, // This is when the socket is actually closed. CLOSED: 3 }; /** * The maximum amount of time between reconnect attempts for the exponential * back-off in milliseconds. * @type {number} * @private */ goog.net.WebSocket.EXPONENTIAL_BACKOFF_CEILING_ = 60 * 1000; /** * Computes the next reconnect time given the number of reconnect attempts since * the last successful connection. * * @param {number} attempt The number of reconnect attempts since the last * connection. * @return {number} The time, in milliseconds, until the next reconnect attempt. * @const * @private */ goog.net.WebSocket.EXPONENTIAL_BACKOFF_ = function(attempt) { var time = Math.pow(2, attempt) * 1000; return Math.min(time, goog.net.WebSocket.EXPONENTIAL_BACKOFF_CEILING_); }; /** * Installs exception protection for all entry points introduced by * goog.net.WebSocket instances which are not protected by * {@link goog.debug.ErrorHandler#protectWindowSetTimeout}, * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or * {@link goog.events.protectBrowserEventEntryPoint}. * * @param {!goog.debug.ErrorHandler} errorHandler Error handler with which to * protect the entry points. */ goog.net.WebSocket.protectEntryPoints = function(errorHandler) { goog.net.WebSocket.prototype.onOpen_ = errorHandler.protectEntryPoint( goog.net.WebSocket.prototype.onOpen_); goog.net.WebSocket.prototype.onClose_ = errorHandler.protectEntryPoint( goog.net.WebSocket.prototype.onClose_); goog.net.WebSocket.prototype.onMessage_ = errorHandler.protectEntryPoint( goog.net.WebSocket.prototype.onMessage_); goog.net.WebSocket.prototype.onError_ = errorHandler.protectEntryPoint( goog.net.WebSocket.prototype.onError_); }; /** * Creates and opens the actual WebSocket. Only call this after attaching the * appropriate listeners to this object. If listeners aren't registered, then * the {@code goog.net.WebSocket.EventType.OPENED} event might be missed. * * @param {string} url The URL to which to connect. * @param {string=} opt_protocol The subprotocol to use. The connection will * only be established if the server reports that it has selected this * subprotocol. The subprotocol name must all be a non-empty ASCII string * with no control characters and no spaces in them (i.e. only characters * in the range U+0021 to U+007E). */ goog.net.WebSocket.prototype.open = function(url, opt_protocol) { // Sanity check. This works only in modern browsers. goog.asserts.assert(goog.global['WebSocket'], 'This browser does not support WebSocket'); // Don't do anything if the web socket is already open. goog.asserts.assert(!this.isOpen(), 'The WebSocket is already open'); // Clear any pending attempts to reconnect. this.clearReconnectTimer_(); // Construct the web socket. this.url_ = url; this.protocol_ = opt_protocol; // This check has to be made otherwise you get protocol mismatch exceptions // for passing undefined, null, '', or []. if (this.protocol_) { this.logger_.info('Opening the WebSocket on ' + this.url_ + ' with protocol ' + this.protocol_); this.webSocket_ = new WebSocket(this.url_, this.protocol_); } else { this.logger_.info('Opening the WebSocket on ' + this.url_); this.webSocket_ = new WebSocket(this.url_); } // Register the event handlers. Note that it is not possible for these // callbacks to be missed because it is registered after the web socket is // instantiated. Because of the synchronous nature of JavaScript, this code // will execute before the browser creates the resource and makes any calls // to these callbacks. this.webSocket_.onopen = goog.bind(this.onOpen_, this); this.webSocket_.onclose = goog.bind(this.onClose_, this); this.webSocket_.onmessage = goog.bind(this.onMessage_, this); this.webSocket_.onerror = goog.bind(this.onError_, this); }; /** * Closes the web socket connection. */ goog.net.WebSocket.prototype.close = function() { // Clear any pending attempts to reconnect. this.clearReconnectTimer_(); // Attempt to close only if the web socket was created. if (this.webSocket_) { this.logger_.info('Closing the WebSocket.'); // Close is expected here since it was a direct call. Close is considered // unexpected when opening the connection fails or there is some other form // of connection loss after being connected. this.closeExpected_ = true; this.webSocket_.close(); this.webSocket_ = null; } }; /** * Sends the message over the web socket. * * @param {string} message The message to send. */ goog.net.WebSocket.prototype.send = function(message) { // Make sure the socket is ready to go before sending a message. goog.asserts.assert(this.isOpen(), 'Cannot send without an open socket'); // Send the message and let onError_ be called if it fails thereafter. this.webSocket_.send(message); }; /** * Checks to see if the web socket is open or not. * * @return {boolean} True if the web socket is open, false otherwise. */ goog.net.WebSocket.prototype.isOpen = function() { return !!this.webSocket_ && this.webSocket_.readyState == goog.net.WebSocket.ReadyState_.OPEN; }; /** * Called when the web socket has connected. * * @private */ goog.net.WebSocket.prototype.onOpen_ = function() { this.logger_.info('WebSocket opened on ' + this.url_); this.dispatchEvent(goog.net.WebSocket.EventType.OPENED); // Set the next reconnect interval. this.reconnectAttempt_ = 0; this.nextReconnect_ = this.getNextReconnect_(this.reconnectAttempt_); }; /** * Called when the web socket has closed. * * @param {!Event} event The close event. * @private */ goog.net.WebSocket.prototype.onClose_ = function(event) { this.logger_.info('The WebSocket on ' + this.url_ + ' closed.'); // Firing this event allows handlers to query the URL. this.dispatchEvent(goog.net.WebSocket.EventType.CLOSED); // Always clear out the web socket on a close event. this.webSocket_ = null; // See if this is an expected call to onClose_. if (this.closeExpected_) { this.logger_.info('The WebSocket closed normally.'); // Only clear out the URL if this is a normal close. this.url_ = null; this.protocol_ = undefined; } else { // Unexpected, so try to reconnect. this.logger_.severe('The WebSocket disconnected unexpectedly: ' + event.data); // Only try to reconnect if it is enabled. if (this.autoReconnect_) { // Log the reconnect attempt. var seconds = Math.floor(this.nextReconnect_ / 1000); this.logger_.info('Seconds until next reconnect attempt: ' + seconds); // Actually schedule the timer. this.reconnectTimer_ = goog.Timer.callOnce( goog.bind(this.open, this, this.url_, this.protocol_), this.nextReconnect_, this); // Set the next reconnect interval. this.reconnectAttempt_++; this.nextReconnect_ = this.getNextReconnect_(this.reconnectAttempt_); } } this.closeExpected_ = false; }; /** * Called when a new message arrives from the server. * * @param {MessageEvent} event The web socket message event. * @private */ goog.net.WebSocket.prototype.onMessage_ = function(event) { var message = /** @type {string} */ (event.data); this.dispatchEvent(new goog.net.WebSocket.MessageEvent(message)); }; /** * Called when there is any error in communication. * * @param {Event} event The error event containing the error data. * @private */ goog.net.WebSocket.prototype.onError_ = function(event) { var data = /** @type {string} */ (event.data); this.logger_.severe('An error occurred: ' + data); this.dispatchEvent(new goog.net.WebSocket.ErrorEvent(data)); }; /** * Clears the reconnect timer. * * @private */ goog.net.WebSocket.prototype.clearReconnectTimer_ = function() { if (goog.isDefAndNotNull(this.reconnectTimer_)) { goog.Timer.clear(this.reconnectTimer_); } this.reconnectTimer_ = null; }; /** @override */ goog.net.WebSocket.prototype.disposeInternal = function() { goog.base(this, 'disposeInternal'); this.close(); }; /** * Object representing a new incoming message event. * * @param {string} message The raw message coming from the web socket. * @extends {goog.events.Event} * @constructor */ goog.net.WebSocket.MessageEvent = function(message) { goog.base(this, goog.net.WebSocket.EventType.MESSAGE); /** * The new message from the web socket. * @type {string} */ this.message = message; }; goog.inherits(goog.net.WebSocket.MessageEvent, goog.events.Event); /** * Object representing an error event. This is fired whenever an error occurs * on the web socket. * * @param {string} data The error data. * @extends {goog.events.Event} * @constructor */ goog.net.WebSocket.ErrorEvent = function(data) { goog.base(this, goog.net.WebSocket.EventType.ERROR); /** * The error data coming from the web socket. * @type {string} */ this.data = data; }; goog.inherits(goog.net.WebSocket.ErrorEvent, goog.events.Event); // Register the WebSocket as an entry point, so that it can be monitored for // exception handling, etc. goog.debug.entryPointRegistry.register( /** * @param {function(!Function): !Function} transformer The transforming * function. */ function(transformer) { goog.net.WebSocket.prototype.onOpen_ = transformer(goog.net.WebSocket.prototype.onOpen_); goog.net.WebSocket.prototype.onClose_ = transformer(goog.net.WebSocket.prototype.onClose_); goog.net.WebSocket.prototype.onMessage_ = transformer(goog.net.WebSocket.prototype.onMessage_); goog.net.WebSocket.prototype.onError_ = transformer(goog.net.WebSocket.prototype.onError_); });
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Definition of goog.net.NetworkTester. */ goog.provide('goog.net.NetworkTester'); goog.require('goog.Timer'); goog.require('goog.Uri'); goog.require('goog.debug.Logger'); /** * Creates an instance of goog.net.NetworkTester which can be used to test * for internet connectivity by seeing if an image can be loaded from * google.com. It can also be tested with other URLs. * @param {Function} callback Callback that is called when the test completes. * The callback takes a single boolean parameter. True indicates the URL * was reachable, false indicates it wasn't. * @param {Object=} opt_handler Handler object for the callback. * @param {goog.Uri=} opt_uri URI to use for testing. * @constructor */ goog.net.NetworkTester = function(callback, opt_handler, opt_uri) { /** * Callback that is called when the test completes. * The callback takes a single boolean parameter. True indicates the URL was * reachable, false indicates it wasn't. * @type {Function} * @private */ this.callback_ = callback; /** * Handler object for the callback. * @type {Object|undefined} * @private */ this.handler_ = opt_handler; if (!opt_uri) { // set the default URI to be based on the cleardot image at google.com // We need to add a 'rand' to make sure the response is not fulfilled // by browser cache. Use protocol-relative URLs to avoid insecure content // warnings in IE. opt_uri = new goog.Uri('//www.google.com/images/cleardot.gif'); opt_uri.makeUnique(); } /** * Uri to use for test. Defaults to using an image off of google.com * @type {goog.Uri} * @private */ this.uri_ = opt_uri; }; /** * Default timeout * @type {number} */ goog.net.NetworkTester.DEFAULT_TIMEOUT_MS = 10000; /** * Logger object * @type {goog.debug.Logger} * @private */ goog.net.NetworkTester.prototype.logger_ = goog.debug.Logger.getLogger('goog.net.NetworkTester'); /** * Timeout for test * @type {number} * @private */ goog.net.NetworkTester.prototype.timeoutMs_ = goog.net.NetworkTester.DEFAULT_TIMEOUT_MS; /** * Whether we've already started running. * @type {boolean} * @private */ goog.net.NetworkTester.prototype.running_ = false; /** * Number of retries to attempt * @type {number} * @private */ goog.net.NetworkTester.prototype.retries_ = 0; /** * Attempt number we're on * @type {number} * @private */ goog.net.NetworkTester.prototype.attempt_ = 0; /** * Pause between retries in milliseconds. * @type {number} * @private */ goog.net.NetworkTester.prototype.pauseBetweenRetriesMs_ = 0; /** * Timer for timeouts. * @type {?number} * @private */ goog.net.NetworkTester.prototype.timeoutTimer_ = null; /** * Timer for pauses between retries. * @type {?number} * @private */ goog.net.NetworkTester.prototype.pauseTimer_ = null; /** * Returns the timeout in milliseconds. * @return {number} Timeout in milliseconds. */ goog.net.NetworkTester.prototype.getTimeout = function() { return this.timeoutMs_; }; /** * Sets the timeout in milliseconds. * @param {number} timeoutMs Timeout in milliseconds. */ goog.net.NetworkTester.prototype.setTimeout = function(timeoutMs) { this.timeoutMs_ = timeoutMs; }; /** * Returns the numer of retries to attempt. * @return {number} Number of retries to attempt. */ goog.net.NetworkTester.prototype.getNumRetries = function() { return this.retries_; }; /** * Sets the timeout in milliseconds. * @param {number} retries Number of retries to attempt. */ goog.net.NetworkTester.prototype.setNumRetries = function(retries) { this.retries_ = retries; }; /** * Returns the pause between retries in milliseconds. * @return {number} Pause between retries in milliseconds. */ goog.net.NetworkTester.prototype.getPauseBetweenRetries = function() { return this.pauseBetweenRetriesMs_; }; /** * Sets the pause between retries in milliseconds. * @param {number} pauseMs Pause between retries in milliseconds. */ goog.net.NetworkTester.prototype.setPauseBetweenRetries = function(pauseMs) { this.pauseBetweenRetriesMs_ = pauseMs; }; /** * Returns the uri to use for the test. * @return {goog.Uri} The uri for the test. */ goog.net.NetworkTester.prototype.getUri = function() { return this.uri_; }; /** * Sets the uri to use for the test. * @param {goog.Uri} uri The uri for the test. */ goog.net.NetworkTester.prototype.setUri = function(uri) { this.uri_ = uri; }; /** * Returns whether the tester is currently running. * @return {boolean} True if it's running, false if it's not running. */ goog.net.NetworkTester.prototype.isRunning = function() { return this.running_; }; /** * Starts the process of testing the network. */ goog.net.NetworkTester.prototype.start = function() { if (this.running_) { throw Error('NetworkTester.start called when already running'); } this.running_ = true; this.logger_.info('Starting'); this.attempt_ = 0; this.startNextAttempt_(); }; /** * Stops the testing of the network. This is a noop if not running. */ goog.net.NetworkTester.prototype.stop = function() { this.cleanupCallbacks_(); this.running_ = false; }; /** * Starts the next attempt to load an image. * @private */ goog.net.NetworkTester.prototype.startNextAttempt_ = function() { this.attempt_++; if (goog.net.NetworkTester.getNavigatorOffline_()) { this.logger_.info('Browser is set to work offline.'); // Call in a timeout to make async like the rest. goog.Timer.callOnce(goog.bind(this.onResult, this, false), 0); } else { this.logger_.info('Loading image (attempt ' + this.attempt_ + ') at ' + this.uri_); this.image_ = new Image(); this.image_.onload = goog.bind(this.onImageLoad_, this); this.image_.onerror = goog.bind(this.onImageError_, this); this.image_.onabort = goog.bind(this.onImageAbort_, this); this.timeoutTimer_ = goog.Timer.callOnce(this.onImageTimeout_, this.timeoutMs_, this); this.image_.src = String(this.uri_); } }; /** * @return {boolean} Whether navigator.onLine returns false. * @private */ goog.net.NetworkTester.getNavigatorOffline_ = function() { return 'onLine' in navigator && !navigator.onLine; }; /** * Callback for the image successfully loading. * @private */ goog.net.NetworkTester.prototype.onImageLoad_ = function() { this.logger_.info('Image loaded'); this.onResult(true); }; /** * Callback for the image failing to load. * @private */ goog.net.NetworkTester.prototype.onImageError_ = function() { this.logger_.info('Image load error'); this.onResult(false); }; /** * Callback for the image load being aborted. * @private */ goog.net.NetworkTester.prototype.onImageAbort_ = function() { this.logger_.info('Image load aborted'); this.onResult(false); }; /** * Callback for the image load timing out. * @private */ goog.net.NetworkTester.prototype.onImageTimeout_ = function() { this.logger_.info('Image load timed out'); this.onResult(false); }; /** * Handles a successful or failed result. * @param {boolean} succeeded Whether the image load succeeded. */ goog.net.NetworkTester.prototype.onResult = function(succeeded) { this.cleanupCallbacks_(); if (succeeded) { this.running_ = false; this.callback_.call(this.handler_, true); } else { if (this.attempt_ <= this.retries_) { if (this.pauseBetweenRetriesMs_) { this.pauseTimer_ = goog.Timer.callOnce(this.onPauseFinished_, this.pauseBetweenRetriesMs_, this); } else { this.startNextAttempt_(); } } else { this.running_ = false; this.callback_.call(this.handler_, false); } } }; /** * Callback for the pause between retry timer. * @private */ goog.net.NetworkTester.prototype.onPauseFinished_ = function() { this.pauseTimer_ = null; this.startNextAttempt_(); }; /** * Cleans up the handlers and timer associated with the image. * @private */ goog.net.NetworkTester.prototype.cleanupCallbacks_ = function() { // clear handlers to avoid memory leaks // NOTE(user): Nullified individually to avoid compiler warnings // (BUG 658126) if (this.image_) { this.image_.onload = null; this.image_.onerror = null; this.image_.onabort = null; this.image_ = null; } if (this.timeoutTimer_) { goog.Timer.clear(this.timeoutTimer_); this.timeoutTimer_ = null; } if (this.pauseTimer_) { goog.Timer.clear(this.pauseTimer_); this.pauseTimer_ = null; } };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Common events for the network classes. */ goog.provide('goog.net.EventType'); /** * Event names for network events * @enum {string} */ goog.net.EventType = { COMPLETE: 'complete', SUCCESS: 'success', ERROR: 'error', ABORT: 'abort', READY: 'ready', READY_STATE_CHANGE: 'readystatechange', TIMEOUT: 'timeout', INCREMENTAL_DATA: 'incrementaldata', PROGRESS: 'progress' };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Mock of IframeIo for unit testing. */ goog.provide('goog.net.MockIFrameIo'); goog.require('goog.events.EventTarget'); goog.require('goog.json'); goog.require('goog.net.ErrorCode'); goog.require('goog.net.EventType'); goog.require('goog.net.IframeIo'); /** * Mock implenetation of goog.net.IframeIo. This doesn't provide a mock * implementation for all cases, but it's not too hard to add them as needed. * @param {goog.testing.TestQueue} testQueue Test queue for inserting test * events. * @constructor * @extends {goog.events.EventTarget} */ goog.net.MockIFrameIo = function(testQueue) { goog.events.EventTarget.call(this); /** * Queue of events write to * @type {goog.testing.TestQueue} * @private */ this.testQueue_ = testQueue; }; goog.inherits(goog.net.MockIFrameIo, goog.events.EventTarget); /** * Whether MockIFrameIo is active. * @type {boolean} * @private */ goog.net.MockIFrameIo.prototype.active_ = false; /** * Last content. * @type {string} * @private */ goog.net.MockIFrameIo.prototype.lastContent_ = ''; /** * Last error code. * @type {goog.net.ErrorCode} * @private */ goog.net.MockIFrameIo.prototype.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; /** * Last error message. * @type {string} * @private */ goog.net.MockIFrameIo.prototype.lastError_ = ''; /** * Last custom error. * @type {Object} * @private */ goog.net.MockIFrameIo.prototype.lastCustomError_ = null; /** * Last URI. * @type {goog.Uri} * @private */ goog.net.MockIFrameIo.prototype.lastUri_ = null; /** * Simulates the iframe send. * * @param {goog.Uri|string} uri Uri of the request. * @param {string=} opt_method Default is GET, POST uses a form to submit the * request. * @param {boolean=} opt_noCache Append a timestamp to the request to avoid * caching. * @param {Object|goog.structs.Map=} opt_data Map of key-value pairs. */ goog.net.MockIFrameIo.prototype.send = function(uri, opt_method, opt_noCache, opt_data) { if (this.active_) { throw Error('[goog.net.IframeIo] Unable to send, already active.'); } this.testQueue_.enqueue(['s', uri, opt_method, opt_noCache, opt_data]); this.complete_ = false; this.active_ = true; }; /** * Simulates the iframe send from a form. * @param {Element} form Form element used to send the request to the server. * @param {string=} opt_uri Uri to set for the destination of the request, by * default the uri will come from the form. * @param {boolean=} opt_noCache Append a timestamp to the request to avoid * caching. */ goog.net.MockIFrameIo.prototype.sendFromForm = function(form, opt_uri, opt_noCache) { if (this.active_) { throw Error('[goog.net.IframeIo] Unable to send, already active.'); } this.testQueue_.enqueue(['s', form, opt_uri, opt_noCache]); this.complete_ = false; this.active_ = true; }; /** * Simulates aborting the current Iframe request. * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use - * defaults to ABORT. */ goog.net.MockIFrameIo.prototype.abort = function(opt_failureCode) { if (this.active_) { this.testQueue_.enqueue(['a', opt_failureCode]); this.complete_ = false; this.active_ = false; this.success_ = false; this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT; this.dispatchEvent(goog.net.EventType.ABORT); this.simulateReady(); } }; /** * Simulates receive of incremental data. * @param {Object} data Data. */ goog.net.MockIFrameIo.prototype.simulateIncrementalData = function(data) { this.dispatchEvent(new goog.net.IframeIo.IncrementalDataEvent(data)); }; /** * Simulates the iframe is done. * @param {goog.net.ErrorCode} errorCode The error code for any error that * should be simulated. */ goog.net.MockIFrameIo.prototype.simulateDone = function(errorCode) { if (errorCode) { this.success_ = false; this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR; this.lastError_ = this.getLastError(); this.dispatchEvent(goog.net.EventType.ERROR); } else { this.success_ = true; this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; this.dispatchEvent(goog.net.EventType.SUCCESS); } this.complete_ = true; this.dispatchEvent(goog.net.EventType.COMPLETE); }; /** * Simulates the IFrame is ready for the next request. */ goog.net.MockIFrameIo.prototype.simulateReady = function() { this.dispatchEvent(goog.net.EventType.READY); }; /** * @return {boolean} True if transfer is complete. */ goog.net.MockIFrameIo.prototype.isComplete = function() { return this.complete_; }; /** * @return {boolean} True if transfer was successful. */ goog.net.MockIFrameIo.prototype.isSuccess = function() { return this.success_; }; /** * @return {boolean} True if a transfer is in progress. */ goog.net.MockIFrameIo.prototype.isActive = function() { return this.active_; }; /** * Returns the last response text (i.e. the text content of the iframe). * Assumes plain text! * @return {string} Result from the server. */ goog.net.MockIFrameIo.prototype.getResponseText = function() { return this.lastContent_; }; /** * Parses the content as JSON. This is a safe parse and may throw an error * if the response is malformed. * @return {Object} The parsed content. */ goog.net.MockIFrameIo.prototype.getResponseJson = function() { return goog.json.parse(this.lastContent_); }; /** * Get the uri of the last request. * @return {goog.Uri} Uri of last request. */ goog.net.MockIFrameIo.prototype.getLastUri = function() { return this.lastUri_; }; /** * Gets the last error code. * @return {goog.net.ErrorCode} Last error code. */ goog.net.MockIFrameIo.prototype.getLastErrorCode = function() { return this.lastErrorCode_; }; /** * Gets the last error message. * @return {string} Last error message. */ goog.net.MockIFrameIo.prototype.getLastError = function() { return goog.net.ErrorCode.getDebugMessage(this.lastErrorCode_); }; /** * Gets the last custom error. * @return {Object} Last custom error. */ goog.net.MockIFrameIo.prototype.getLastCustomError = function() { return this.lastCustomError_; }; /** * Sets the callback function used to check if a loaded IFrame is in an error * state. * @param {Function} fn Callback that expects a document object as it's single * argument. */ goog.net.MockIFrameIo.prototype.setErrorChecker = function(fn) { this.errorChecker_ = fn; }; /** * Gets the callback function used to check if a loaded IFrame is in an error * state. * @return {Function} A callback that expects a document object as it's single * argument. */ goog.net.MockIFrameIo.prototype.getErrorChecker = function() { return this.errorChecker_; }; /** * Returns the number of milliseconds after which an incomplete request will be * aborted, or 0 if no timeout is set. * @return {number} Timeout interval in milliseconds. */ goog.net.MockIFrameIo.prototype.getTimeoutInterval = function() { return this.timeoutInterval_; }; /** * Sets the number of milliseconds after which an incomplete request will be * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no * timeout is set. * @param {number} ms Timeout interval in milliseconds; 0 means none. */ goog.net.MockIFrameIo.prototype.setTimeoutInterval = function(ms) { // TODO (pupius) - never used - doesn't look like timeouts were implemented this.timeoutInterval_ = Math.max(0, ms); };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Definition of the BrowserChannel class. A BrowserChannel * simulates a bidirectional socket over HTTP. It is the basis of the * Gmail Chat IM connections to the server. * * See http://wiki/Main/BrowserChannel * This doesn't yet completely comform to the design document as we've done * some renaming and cleanup in the design document that hasn't yet been * implemented in the protocol. * * Typical usage will look like * var handler = [handler object]; * var channel = new BrowserChannel(clientVersion); * channel.setHandler(handler); * channel.connect('channel/test', 'channel/bind'); * * See goog.net.BrowserChannel.Handler for the handler interface. * */ goog.provide('goog.net.BrowserChannel'); goog.provide('goog.net.BrowserChannel.Error'); goog.provide('goog.net.BrowserChannel.Event'); goog.provide('goog.net.BrowserChannel.Handler'); goog.provide('goog.net.BrowserChannel.LogSaver'); goog.provide('goog.net.BrowserChannel.QueuedMap'); goog.provide('goog.net.BrowserChannel.ServerReachability'); goog.provide('goog.net.BrowserChannel.ServerReachabilityEvent'); goog.provide('goog.net.BrowserChannel.Stat'); goog.provide('goog.net.BrowserChannel.StatEvent'); goog.provide('goog.net.BrowserChannel.State'); goog.provide('goog.net.BrowserChannel.TimingEvent'); goog.require('goog.Uri'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.debug.Logger'); goog.require('goog.debug.TextFormatter'); goog.require('goog.events.Event'); goog.require('goog.events.EventTarget'); goog.require('goog.json'); goog.require('goog.json.EvalJsonProcessor'); goog.require('goog.net.BrowserTestChannel'); goog.require('goog.net.ChannelDebug'); goog.require('goog.net.ChannelRequest'); goog.require('goog.net.XhrIo'); goog.require('goog.net.tmpnetwork'); goog.require('goog.string'); goog.require('goog.structs'); goog.require('goog.structs.CircularBuffer'); /** * Encapsulates the logic for a single BrowserChannel. * * @param {string=} opt_clientVersion An application-specific version number * that is sent to the server when connected. * @param {Array.<string>=} opt_firstTestResults Previously determined results * of the first browser channel test. * @param {boolean=} opt_secondTestResults Previously determined results * of the second browser channel test. * @constructor */ goog.net.BrowserChannel = function(opt_clientVersion, opt_firstTestResults, opt_secondTestResults) { /** * The application specific version that is passed to the server. * @type {?string} * @private */ this.clientVersion_ = opt_clientVersion || null; /** * The current state of the BrowserChannel. It should be one of the * goog.net.BrowserChannel.State constants. * @type {!goog.net.BrowserChannel.State} * @private */ this.state_ = goog.net.BrowserChannel.State.INIT; /** * An array of queued maps that need to be sent to the server. * @type {Array.<goog.net.BrowserChannel.QueuedMap>} * @private */ this.outgoingMaps_ = []; /** * An array of dequeued maps that we have either received a non-successful * response for, or no response at all, and which therefore may or may not * have been received by the server. * @type {Array.<goog.net.BrowserChannel.QueuedMap>} * @private */ this.pendingMaps_ = []; /** * The channel debug used for browserchannel logging * @type {!goog.net.ChannelDebug} * @private */ this.channelDebug_ = new goog.net.ChannelDebug(); /** * Parser for a response payload. Defaults to use * {@code goog.json.unsafeParse}. The parser should return an array. * @type {!goog.string.Parser} * @private */ this.parser_ = new goog.json.EvalJsonProcessor(null, true); /** * An array of results for the first browser channel test call. * @type {Array.<string>} * @private */ this.firstTestResults_ = opt_firstTestResults || null; /** * The results of the second browser channel test. True implies the * connection is buffered, False means unbuffered, null means that * the results are not available. * @private */ this.secondTestResults_ = goog.isDefAndNotNull(opt_secondTestResults) ? opt_secondTestResults : null; }; /** * Simple container class for a (mapId, map) pair. * @param {number} mapId The id for this map. * @param {Object|goog.structs.Map} map The map itself. * @param {Object=} opt_context The context associated with the map. * @constructor */ goog.net.BrowserChannel.QueuedMap = function(mapId, map, opt_context) { /** * The id for this map. * @type {number} */ this.mapId = mapId; /** * The map itself. * @type {Object|goog.structs.Map} */ this.map = map; /** * The context for the map. * @type {Object} */ this.context = opt_context || null; }; /** * Extra HTTP headers to add to all the requests sent to the server. * @type {Object} * @private */ goog.net.BrowserChannel.prototype.extraHeaders_ = null; /** * Extra parameters to add to all the requests sent to the server. * @type {Object} * @private */ goog.net.BrowserChannel.prototype.extraParams_ = null; /** * The current ChannelRequest object for the forwardchannel. * @type {goog.net.ChannelRequest?} * @private */ goog.net.BrowserChannel.prototype.forwardChannelRequest_ = null; /** * The ChannelRequest object for the backchannel. * @type {goog.net.ChannelRequest?} * @private */ goog.net.BrowserChannel.prototype.backChannelRequest_ = null; /** * The relative path (in the context of the the page hosting the browser * channel) for making requests to the server. * @type {?string} * @private */ goog.net.BrowserChannel.prototype.path_ = null; /** * The absolute URI for the forwardchannel request. * @type {goog.Uri} * @private */ goog.net.BrowserChannel.prototype.forwardChannelUri_ = null; /** * The absolute URI for the backchannel request. * @type {goog.Uri} * @private */ goog.net.BrowserChannel.prototype.backChannelUri_ = null; /** * A subdomain prefix for using a subdomain in IE for the backchannel * requests. * @type {?string} * @private */ goog.net.BrowserChannel.prototype.hostPrefix_ = null; /** * Whether we allow the use of a subdomain in IE for the backchannel requests. * @private */ goog.net.BrowserChannel.prototype.allowHostPrefix_ = true; /** * The next id to use for the RID (request identifier) parameter. This * identifier uniquely identifies the forward channel request. * @type {number} * @private */ goog.net.BrowserChannel.prototype.nextRid_ = 0; /** * The id to use for the next outgoing map. This identifier uniquely * identifies a sent map. * @type {number} * @private */ goog.net.BrowserChannel.prototype.nextMapId_ = 0; /** * Whether to fail forward-channel requests after one try, or after a few tries. * @type {boolean} * @private */ goog.net.BrowserChannel.prototype.failFast_ = false; /** * The handler that receive callbacks for state changes and data. * @type {goog.net.BrowserChannel.Handler} * @private */ goog.net.BrowserChannel.prototype.handler_ = null; /** * Timer identifier for asynchronously making a forward channel request. * @type {?number} * @private */ goog.net.BrowserChannel.prototype.forwardChannelTimerId_ = null; /** * Timer identifier for asynchronously making a back channel request. * @type {?number} * @private */ goog.net.BrowserChannel.prototype.backChannelTimerId_ = null; /** * Timer identifier for the timer that waits for us to retry the backchannel in * the case where it is dead and no longer receiving data. * @type {?number} * @private */ goog.net.BrowserChannel.prototype.deadBackChannelTimerId_ = null; /** * The BrowserTestChannel object which encapsulates the logic for determining * interesting network conditions about the client. * @type {goog.net.BrowserTestChannel?} * @private */ goog.net.BrowserChannel.prototype.connectionTest_ = null; /** * Whether the client's network conditions can support chunked responses. * @type {?boolean} * @private */ goog.net.BrowserChannel.prototype.useChunked_ = null; /** * Whether chunked mode is allowed. In certain debugging situations, it's * useful to disable this. * @private */ goog.net.BrowserChannel.prototype.allowChunkedMode_ = true; /** * The array identifier of the last array received from the server for the * backchannel request. * @type {number} * @private */ goog.net.BrowserChannel.prototype.lastArrayId_ = -1; /** * The array identifier of the last array sent by the server that we know about. * @type {number} * @private */ goog.net.BrowserChannel.prototype.lastPostResponseArrayId_ = -1; /** * The last status code received. * @type {number} * @private */ goog.net.BrowserChannel.prototype.lastStatusCode_ = -1; /** * Number of times we have retried the current forward channel request. * @type {number} * @private */ goog.net.BrowserChannel.prototype.forwardChannelRetryCount_ = 0; /** * Number of times it a row that we have retried the current back channel * request and received no data. * @type {number} * @private */ goog.net.BrowserChannel.prototype.backChannelRetryCount_ = 0; /** * The attempt id for the current back channel request. Starts at 1 and * increments for each reconnect. The server uses this to log if our connection * is flaky or not. * @type {number} * @private */ goog.net.BrowserChannel.prototype.backChannelAttemptId_; /** * The base part of the time before firing next retry request. Default is 5 * seconds. Note that a random delay is added (see {@link retryDelaySeedMs_}) * for all retries, and linear backoff is applied to the sum for subsequent * retries. * @type {number} * @private */ goog.net.BrowserChannel.prototype.baseRetryDelayMs_ = 5 * 1000; /** * A random time between 0 and this number of MS is added to the * {@link baseRetryDelayMs_}. Default is 10 seconds. * @type {number} * @private */ goog.net.BrowserChannel.prototype.retryDelaySeedMs_ = 10 * 1000; /** * Maximum number of attempts to connect to the server for forward channel * requests. Defaults to 2. * @type {number} * @private */ goog.net.BrowserChannel.prototype.forwardChannelMaxRetries_ = 2; /** * The timeout in milliseconds for a forward channel request. Defaults to 20 * seconds. Note that part of this timeout can be randomized. * @type {number} * @private */ goog.net.BrowserChannel.prototype.forwardChannelRequestTimeoutMs_ = 20 * 1000; /** * A throttle time in ms for readystatechange events for the backchannel. * Useful for throttling when ready state is INTERACTIVE (partial data). * * This throttle is useful if the server sends large data chunks down the * backchannel. It prevents examining XHR partial data on every * readystate change event. This is useful because large chunks can * trigger hundreds of readystatechange events, each of which takes ~5ms * or so to handle, in turn making the UI unresponsive for a significant period. * * If set to zero no throttle is used. * @type {number} * @private */ goog.net.BrowserChannel.prototype.readyStateChangeThrottleMs_ = 0; /** * Whether cross origin requests are supported for the browser channel. * * See {@link goog.net.XhrIo#setWithCredentials}. * @type {boolean} * @private */ goog.net.BrowserChannel.prototype.supportsCrossDomainXhrs_ = false; /** * The latest protocol version that this class supports. We request this version * from the server when opening the connection. Should match * com.google.net.browserchannel.BrowserChannel.LATEST_CHANNEL_VERSION. * @type {number} */ goog.net.BrowserChannel.LATEST_CHANNEL_VERSION = 8; /** * The channel version that we negotiated with the server for this session. * Starts out as the version we request, and then is changed to the negotiated * version after the initial open. * @type {number} * @private */ goog.net.BrowserChannel.prototype.channelVersion_ = goog.net.BrowserChannel.LATEST_CHANNEL_VERSION; /** * Enum type for the browser channel state machine. * @enum {number} */ goog.net.BrowserChannel.State = { /** The channel is closed. */ CLOSED: 0, /** The channel has been initialized but hasn't yet initiated a connection. */ INIT: 1, /** The channel is in the process of opening a connection to the server. */ OPENING: 2, /** The channel is open. */ OPENED: 3 }; /** * The timeout in milliseconds for a forward channel request. * @type {number} */ goog.net.BrowserChannel.FORWARD_CHANNEL_RETRY_TIMEOUT = 20 * 1000; /** * Maximum number of attempts to connect to the server for back channel * requests. * @type {number} */ goog.net.BrowserChannel.BACK_CHANNEL_MAX_RETRIES = 3; /** * A number in MS of how long we guess the maxmium amount of time a round trip * to the server should take. In the future this could be substituted with a * real measurement of the RTT. * @type {number} */ goog.net.BrowserChannel.RTT_ESTIMATE = 3 * 1000; /** * When retrying for an inactive channel, we will multiply the total delay by * this number. * @type {number} */ goog.net.BrowserChannel.INACTIVE_CHANNEL_RETRY_FACTOR = 2; /** * Enum type for identifying a BrowserChannel error. * @enum {number} */ goog.net.BrowserChannel.Error = { /** Value that indicates no error has occurred. */ OK: 0, /** An error due to a request failing. */ REQUEST_FAILED: 2, /** An error due to the user being logged out. */ LOGGED_OUT: 4, /** An error due to server response which contains no data. */ NO_DATA: 5, /** An error due to a server response indicating an unknown session id */ UNKNOWN_SESSION_ID: 6, /** An error due to a server response requesting to stop the channel. */ STOP: 7, /** A general network error. */ NETWORK: 8, /** An error due to the channel being blocked by a network administrator. */ BLOCKED: 9, /** An error due to bad data being returned from the server. */ BAD_DATA: 10, /** An error due to a response that doesn't start with the magic cookie. */ BAD_RESPONSE: 11, /** ActiveX is blocked by the machine's admin settings. */ ACTIVE_X_BLOCKED: 12 }; /** * Internal enum type for the two browser channel channel types. * @enum {number} * @private */ goog.net.BrowserChannel.ChannelType_ = { FORWARD_CHANNEL: 1, BACK_CHANNEL: 2 }; /** * The maximum number of maps that can be sent in one POST. Should match * com.google.net.browserchannel.BrowserChannel.MAX_MAPS_PER_REQUEST. * @type {number} * @private */ goog.net.BrowserChannel.MAX_MAPS_PER_REQUEST_ = 1000; /** * Singleton event target for firing stat events * @type {goog.events.EventTarget} * @private */ goog.net.BrowserChannel.statEventTarget_ = new goog.events.EventTarget(); /** * Events fired by BrowserChannel and associated objects * @type {Object} */ goog.net.BrowserChannel.Event = {}; /** * Stat Event that fires when things of interest happen that may be useful for * applications to know about for stats or debugging purposes. This event fires * on the EventTarget returned by getStatEventTarget. */ goog.net.BrowserChannel.Event.STAT_EVENT = 'statevent'; /** * Event class for goog.net.BrowserChannel.Event.STAT_EVENT * * @param {goog.events.EventTarget} eventTarget The stat event target for the browser channel. * @param {goog.net.BrowserChannel.Stat} stat The stat. * @constructor * @extends {goog.events.Event} */ goog.net.BrowserChannel.StatEvent = function(eventTarget, stat) { goog.events.Event.call(this, goog.net.BrowserChannel.Event.STAT_EVENT, eventTarget); /** * The stat * @type {goog.net.BrowserChannel.Stat} */ this.stat = stat; }; goog.inherits(goog.net.BrowserChannel.StatEvent, goog.events.Event); /** * An event that fires when POST requests complete successfully, indicating * the size of the POST and the round trip time. * This event fires on the EventTarget returned by getStatEventTarget. */ goog.net.BrowserChannel.Event.TIMING_EVENT = 'timingevent'; /** * Event class for goog.net.BrowserChannel.Event.TIMING_EVENT * * @param {goog.events.EventTarget} target The stat event target for the browser channel. * @param {number} size The number of characters in the POST data. * @param {number} rtt The total round trip time from POST to response in MS. * @param {number} retries The number of times the POST had to be retried. * @constructor * @extends {goog.events.Event} */ goog.net.BrowserChannel.TimingEvent = function(target, size, rtt, retries) { goog.events.Event.call(this, goog.net.BrowserChannel.Event.TIMING_EVENT, target); /** * @type {number} */ this.size = size; /** * @type {number} */ this.rtt = rtt; /** * @type {number} */ this.retries = retries; }; goog.inherits(goog.net.BrowserChannel.TimingEvent, goog.events.Event); /** * The type of event that occurs every time some information about how reachable * the server is is discovered. */ goog.net.BrowserChannel.Event.SERVER_REACHABILITY_EVENT = 'serverreachability'; /** * Types of events which reveal information about the reachability of the * server. * @enum {number} */ goog.net.BrowserChannel.ServerReachability = { REQUEST_MADE: 1, REQUEST_SUCCEEDED: 2, REQUEST_FAILED: 3, BACK_CHANNEL_ACTIVITY: 4 }; /** * Event class for goog.net.BrowserChannel.Event.SERVER_REACHABILITY_EVENT. * * @param {goog.events.EventTarget} target The stat event target for the browser channel. * @param {goog.net.BrowserChannel.ServerReachability} reachabilityType The * reachability event type. * @constructor * @extends {goog.events.Event} */ goog.net.BrowserChannel.ServerReachabilityEvent = function(target, reachabilityType) { goog.events.Event.call(this, goog.net.BrowserChannel.Event.SERVER_REACHABILITY_EVENT, target); /** * @type {goog.net.BrowserChannel.ServerReachability} */ this.reachabilityType = reachabilityType; }; goog.inherits(goog.net.BrowserChannel.ServerReachabilityEvent, goog.events.Event); /** * Enum that identifies events for statistics that are interesting to track. * TODO(user) - Change name not to use Event or use EventTarget * @enum {number} */ goog.net.BrowserChannel.Stat = { /** Event indicating a new connection attempt. */ CONNECT_ATTEMPT: 0, /** Event indicating a connection error due to a general network problem. */ ERROR_NETWORK: 1, /** * Event indicating a connection error that isn't due to a general network * problem. */ ERROR_OTHER: 2, /** Event indicating the start of test stage one. */ TEST_STAGE_ONE_START: 3, /** Event indicating the channel is blocked by a network administrator. */ CHANNEL_BLOCKED: 4, /** Event indicating the start of test stage two. */ TEST_STAGE_TWO_START: 5, /** Event indicating the first piece of test data was received. */ TEST_STAGE_TWO_DATA_ONE: 6, /** * Event indicating that the second piece of test data was received and it was * recieved separately from the first. */ TEST_STAGE_TWO_DATA_TWO: 7, /** Event indicating both pieces of test data were received simultaneously. */ TEST_STAGE_TWO_DATA_BOTH: 8, /** Event indicating stage one of the test request failed. */ TEST_STAGE_ONE_FAILED: 9, /** Event indicating stage two of the test request failed. */ TEST_STAGE_TWO_FAILED: 10, /** * Event indicating that a buffering proxy is likely between the client and * the server. */ PROXY: 11, /** * Event indicating that no buffering proxy is likely between the client and * the server. */ NOPROXY: 12, /** Event indicating an unknown SID error. */ REQUEST_UNKNOWN_SESSION_ID: 13, /** Event indicating a bad status code was received. */ REQUEST_BAD_STATUS: 14, /** Event indicating incomplete data was received */ REQUEST_INCOMPLETE_DATA: 15, /** Event indicating bad data was received */ REQUEST_BAD_DATA: 16, /** Event indicating no data was received when data was expected. */ REQUEST_NO_DATA: 17, /** Event indicating a request timeout. */ REQUEST_TIMEOUT: 18, /** * Event indicating that the server never received our hanging GET and so it * is being retried. */ BACKCHANNEL_MISSING: 19, /** * Event indicating that we have determined that our hanging GET is not * receiving data when it should be. Thus it is dead dead and will be retried. */ BACKCHANNEL_DEAD: 20, /** * The browser declared itself offline during the lifetime of a request, or * was offline when a request was initially made. */ BROWSER_OFFLINE: 21, /** ActiveX is blocked by the machine's admin settings. */ ACTIVE_X_BLOCKED: 22 }; /** * The normal response for forward channel requests. * Used only before version 8 of the protocol. * @type {string} */ goog.net.BrowserChannel.MAGIC_RESPONSE_COOKIE = 'y2f%'; /** * A guess at a cutoff at which to no longer assume the backchannel is dead * when we are slow to receive data. Number in bytes. * * Assumption: The worst bandwidth we work on is 50 kilobits/sec * 50kbits/sec * (1 byte / 8 bits) * 6 sec dead backchannel timeout * @type {number} */ goog.net.BrowserChannel.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF = 37500; /** * Returns the browserchannel logger. * * @return {goog.net.ChannelDebug} The channel debug object. */ goog.net.BrowserChannel.prototype.getChannelDebug = function() { return this.channelDebug_; }; /** * Set the browserchannel logger. * TODO(user): Add interface for channel loggers or remove this function. * * @param {goog.net.ChannelDebug} channelDebug The channel debug object. */ goog.net.BrowserChannel.prototype.setChannelDebug = function( channelDebug) { if (goog.isDefAndNotNull(channelDebug)) { this.channelDebug_ = channelDebug; } }; /** * Allows the application to set an execution hooks for when BrowserChannel * starts processing requests. This is useful to track timing or logging * special information. The function takes no parameters and return void. * @param {Function} startHook The function for the start hook. */ goog.net.BrowserChannel.setStartThreadExecutionHook = function(startHook) { goog.net.BrowserChannel.startExecutionHook_ = startHook; }; /** * Allows the application to set an execution hooks for when BrowserChannel * stops processing requests. This is useful to track timing or logging * special information. The function takes no parameters and return void. * @param {Function} endHook The function for the end hook. */ goog.net.BrowserChannel.setEndThreadExecutionHook = function(endHook) { goog.net.BrowserChannel.endExecutionHook_ = endHook; }; /** * Application provided execution hook for the start hook. * * @type {Function} * @private */ goog.net.BrowserChannel.startExecutionHook_ = function() { }; /** * Application provided execution hook for the end hook. * * @type {Function} * @private */ goog.net.BrowserChannel.endExecutionHook_ = function() { }; /** * Instantiates a ChannelRequest with the given parameters. Overidden in tests. * * @param {goog.net.BrowserChannel|goog.net.BrowserTestChannel} channel * The BrowserChannel that owns this request. * @param {goog.net.ChannelDebug} channelDebug A ChannelDebug to use for * logging. * @param {string=} opt_sessionId The session id for the channel. * @param {string|number=} opt_requestId The request id for this request. * @param {number=} opt_retryId The retry id for this request. * @return {goog.net.ChannelRequest} The created channel request. */ goog.net.BrowserChannel.createChannelRequest = function(channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) { return new goog.net.ChannelRequest( channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId); }; /** * Starts the channel. This initiates connections to the server. * * @param {string} testPath The path for the test connection. * @param {string} channelPath The path for the channel connection. * @param {Object=} opt_extraParams Extra parameter keys and values to add to * the requests. * @param {string=} opt_oldSessionId Session ID from a previous session. * @param {number=} opt_oldArrayId The last array ID from a previous session. */ goog.net.BrowserChannel.prototype.connect = function(testPath, channelPath, opt_extraParams, opt_oldSessionId, opt_oldArrayId) { this.channelDebug_.debug('connect()'); goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.CONNECT_ATTEMPT); this.path_ = channelPath; this.extraParams_ = opt_extraParams || {}; // Attach parameters about the previous session if reconnecting. if (opt_oldSessionId && goog.isDef(opt_oldArrayId)) { this.extraParams_['OSID'] = opt_oldSessionId; this.extraParams_['OAID'] = opt_oldArrayId; } this.connectTest_(testPath); }; /** * Disconnects and closes the channel. */ goog.net.BrowserChannel.prototype.disconnect = function() { this.channelDebug_.debug('disconnect()'); this.cancelRequests_(); if (this.state_ == goog.net.BrowserChannel.State.OPENED) { var rid = this.nextRid_++; var uri = this.forwardChannelUri_.clone(); uri.setParameterValue('SID', this.sid_); uri.setParameterValue('RID', rid); uri.setParameterValue('TYPE', 'terminate'); // Add the reconnect parameters. this.addAdditionalParams_(uri); var request = goog.net.BrowserChannel.createChannelRequest( this, this.channelDebug_, this.sid_, rid); request.sendUsingImgTag(uri); } this.onClose_(); }; /** * Returns the session id of the channel. Only available after the * channel has been opened. * @return {string} Session ID. */ goog.net.BrowserChannel.prototype.getSessionId = function() { return this.sid_; }; /** * Starts the test channel to determine network conditions. * * @param {string} testPath The relative PATH for the test connection. * @private */ goog.net.BrowserChannel.prototype.connectTest_ = function(testPath) { this.channelDebug_.debug('connectTest_()'); if (!this.okToMakeRequest_()) { return; // channel is cancelled } this.connectionTest_ = new goog.net.BrowserTestChannel( this, this.channelDebug_); this.connectionTest_.setExtraHeaders(this.extraHeaders_); this.connectionTest_.setParser(this.parser_); this.connectionTest_.connect(testPath); }; /** * Starts the regular channel which is run after the test channel is complete. * @private */ goog.net.BrowserChannel.prototype.connectChannel_ = function() { this.channelDebug_.debug('connectChannel_()'); this.ensureInState_(goog.net.BrowserChannel.State.INIT, goog.net.BrowserChannel.State.CLOSED); this.forwardChannelUri_ = this.getForwardChannelUri(/** @type {string} */ (this.path_)); this.ensureForwardChannel_(); }; /** * Cancels all outstanding requests. * @private */ goog.net.BrowserChannel.prototype.cancelRequests_ = function() { if (this.connectionTest_) { this.connectionTest_.abort(); this.connectionTest_ = null; } if (this.backChannelRequest_) { this.backChannelRequest_.cancel(); this.backChannelRequest_ = null; } if (this.backChannelTimerId_) { goog.global.clearTimeout(this.backChannelTimerId_); this.backChannelTimerId_ = null; } this.clearDeadBackchannelTimer_(); if (this.forwardChannelRequest_) { this.forwardChannelRequest_.cancel(); this.forwardChannelRequest_ = null; } if (this.forwardChannelTimerId_) { goog.global.clearTimeout(this.forwardChannelTimerId_); this.forwardChannelTimerId_ = null; } }; /** * Returns the extra HTTP headers to add to all the requests sent to the server. * * @return {Object} The HTTP headers, or null. */ goog.net.BrowserChannel.prototype.getExtraHeaders = function() { return this.extraHeaders_; }; /** * Sets extra HTTP headers to add to all the requests sent to the server. * * @param {Object} extraHeaders The HTTP headers, or null. */ goog.net.BrowserChannel.prototype.setExtraHeaders = function(extraHeaders) { this.extraHeaders_ = extraHeaders; }; /** * Sets the throttle for handling onreadystatechange events for the request. * * @param {number} throttle The throttle in ms. A value of zero indicates * no throttle. */ goog.net.BrowserChannel.prototype.setReadyStateChangeThrottle = function( throttle) { this.readyStateChangeThrottleMs_ = throttle; }; /** * Sets whether cross origin requests are supported for the browser channel. * * Setting this allows the creation of requests to secondary domains and * sends XHRs with the CORS withCredentials bit set to true. * * In order for cross-origin requests to work, the server will also need to set * CORS response headers as per: * https://developer.mozilla.org/en-US/docs/HTTP_access_control * * See {@link goog.net.XhrIo#setWithCredentials}. * @param {boolean} supportCrossDomain Whether cross domain XHRs are supported. */ goog.net.BrowserChannel.prototype.setSupportsCrossDomainXhrs = function( supportCrossDomain) { this.supportsCrossDomainXhrs_ = supportCrossDomain; }; /** * Returns the handler used for channel callback events. * * @return {goog.net.BrowserChannel.Handler} The handler. */ goog.net.BrowserChannel.prototype.getHandler = function() { return this.handler_; }; /** * Sets the handler used for channel callback events. * @param {goog.net.BrowserChannel.Handler} handler The handler to set. */ goog.net.BrowserChannel.prototype.setHandler = function(handler) { this.handler_ = handler; }; /** * Returns whether the channel allows the use of a subdomain. There may be * cases where this isn't allowed. * @return {boolean} Whether a host prefix is allowed. */ goog.net.BrowserChannel.prototype.getAllowHostPrefix = function() { return this.allowHostPrefix_; }; /** * Sets whether the channel allows the use of a subdomain. There may be cases * where this isn't allowed, for example, logging in with troutboard where * using a subdomain causes Apache to force the user to authenticate twice. * @param {boolean} allowHostPrefix Whether a host prefix is allowed. */ goog.net.BrowserChannel.prototype.setAllowHostPrefix = function(allowHostPrefix) { this.allowHostPrefix_ = allowHostPrefix; }; /** * Returns whether the channel is buffered or not. This state is valid for * querying only after the test connection has completed. This may be * queried in the goog.net.BrowserChannel.okToMakeRequest() callback. * A channel may be buffered if the test connection determines that * a chunked response could not be sent down within a suitable time. * @return {boolean} Whether the channel is buffered. */ goog.net.BrowserChannel.prototype.isBuffered = function() { return !this.useChunked_; }; /** * Returns whether chunked mode is allowed. In certain debugging situations, * it's useful for the application to have a way to disable chunked mode for a * user. * @return {boolean} Whether chunked mode is allowed. */ goog.net.BrowserChannel.prototype.getAllowChunkedMode = function() { return this.allowChunkedMode_; }; /** * Sets whether chunked mode is allowed. In certain debugging situations, it's * useful for the application to have a way to disable chunked mode for a user. * @param {boolean} allowChunkedMode Whether chunked mode is allowed. */ goog.net.BrowserChannel.prototype.setAllowChunkedMode = function(allowChunkedMode) { this.allowChunkedMode_ = allowChunkedMode; }; /** * Sends a request to the server. The format of the request is a Map data * structure of key/value pairs. These maps are then encoded in a format * suitable for the wire and then reconstituted as a Map data structure that * the server can process. * @param {Object|goog.structs.Map} map The map to send. * @param {?Object=} opt_context The context associated with the map. */ goog.net.BrowserChannel.prototype.sendMap = function(map, opt_context) { if (this.state_ == goog.net.BrowserChannel.State.CLOSED) { throw Error('Invalid operation: sending map when state is closed'); } // We can only send 1000 maps per POST, but typically we should never have // that much to send, so warn if we exceed that (we still send all the maps). if (this.outgoingMaps_.length == goog.net.BrowserChannel.MAX_MAPS_PER_REQUEST_) { // severe() is temporary so that we get these uploaded and can figure out // what's causing them. Afterwards can change to warning(). this.channelDebug_.severe( 'Already have ' + goog.net.BrowserChannel.MAX_MAPS_PER_REQUEST_ + ' queued maps upon queueing ' + goog.json.serialize(map)); } this.outgoingMaps_.push( new goog.net.BrowserChannel.QueuedMap(this.nextMapId_++, map, opt_context)); if (this.state_ == goog.net.BrowserChannel.State.OPENING || this.state_ == goog.net.BrowserChannel.State.OPENED) { this.ensureForwardChannel_(); } }; /** * When set to true, this changes the behavior of the forward channel so it * will not retry requests; it will fail after one network failure, and if * there was already one network failure, the request will fail immediately. * @param {boolean} failFast Whether or not to fail fast. */ goog.net.BrowserChannel.prototype.setFailFast = function(failFast) { this.failFast_ = failFast; this.channelDebug_.info('setFailFast: ' + failFast); if ((this.forwardChannelRequest_ || this.forwardChannelTimerId_) && this.forwardChannelRetryCount_ > this.getForwardChannelMaxRetries()) { this.channelDebug_.info( 'Retry count ' + this.forwardChannelRetryCount_ + ' > new maxRetries ' + this.getForwardChannelMaxRetries() + '. Fail immediately!'); if (this.forwardChannelRequest_) { this.forwardChannelRequest_.cancel(); // Go through the standard onRequestComplete logic to expose the max-retry // failure in the standard way. this.onRequestComplete(this.forwardChannelRequest_); } else { // i.e., this.forwardChannelTimerId_ goog.global.clearTimeout(this.forwardChannelTimerId_); this.forwardChannelTimerId_ = null; // The error code from the last failed request is gone, so just use a // generic one. this.signalError_(goog.net.BrowserChannel.Error.REQUEST_FAILED); } } }; /** * @return {number} The max number of forward-channel retries, which will be 0 * in fail-fast mode. */ goog.net.BrowserChannel.prototype.getForwardChannelMaxRetries = function() { return this.failFast_ ? 0 : this.forwardChannelMaxRetries_; }; /** * Sets the maximum number of attempts to connect to the server for forward * channel requests. * @param {number} retries The maximum number of attempts. */ goog.net.BrowserChannel.prototype.setForwardChannelMaxRetries = function(retries) { this.forwardChannelMaxRetries_ = retries; }; /** * Sets the timeout for a forward channel request. * @param {number} timeoutMs The timeout in milliseconds. */ goog.net.BrowserChannel.prototype.setForwardChannelRequestTimeout = function(timeoutMs) { this.forwardChannelRequestTimeoutMs_ = timeoutMs; }; /** * @return {number} The max number of back-channel retries, which is a constant. */ goog.net.BrowserChannel.prototype.getBackChannelMaxRetries = function() { // Back-channel retries is a constant. return goog.net.BrowserChannel.BACK_CHANNEL_MAX_RETRIES; }; /** * Returns whether the channel is closed * @return {boolean} true if the channel is closed. */ goog.net.BrowserChannel.prototype.isClosed = function() { return this.state_ == goog.net.BrowserChannel.State.CLOSED; }; /** * Returns the browser channel state. * @return {goog.net.BrowserChannel.State} The current state of the browser * channel. */ goog.net.BrowserChannel.prototype.getState = function() { return this.state_; }; /** * Return the last status code received for a request. * @return {number} The last status code received for a request. */ goog.net.BrowserChannel.prototype.getLastStatusCode = function() { return this.lastStatusCode_; }; /** * @return {number} The last array id received. */ goog.net.BrowserChannel.prototype.getLastArrayId = function() { return this.lastArrayId_; }; /** * Returns whether there are outstanding requests servicing the channel. * @return {boolean} true if there are outstanding requests. */ goog.net.BrowserChannel.prototype.hasOutstandingRequests = function() { return this.outstandingRequests_() != 0; }; /** * Sets a new parser for the response payload. A custom parser may be set to * avoid using eval(), for example. By default, the parser uses * {@code goog.json.unsafeParse}. * @param {!goog.string.Parser} parser Parser. */ goog.net.BrowserChannel.prototype.setParser = function(parser) { this.parser_ = parser; }; /** * Returns the number of outstanding requests. * @return {number} The number of outstanding requests to the server. * @private */ goog.net.BrowserChannel.prototype.outstandingRequests_ = function() { var count = 0; if (this.backChannelRequest_) { count++; } if (this.forwardChannelRequest_) { count++; } return count; }; /** * Ensures that a forward channel request is scheduled. * @private */ goog.net.BrowserChannel.prototype.ensureForwardChannel_ = function() { if (this.forwardChannelRequest_) { // connection in process - no need to start a new request return; } if (this.forwardChannelTimerId_) { // no need to start a new request - one is already scheduled return; } this.forwardChannelTimerId_ = goog.net.BrowserChannel.setTimeout( goog.bind(this.onStartForwardChannelTimer_, this), 0); this.forwardChannelRetryCount_ = 0; }; /** * Schedules a forward-channel retry for the specified request, unless the max * retries has been reached. * @param {goog.net.ChannelRequest} request The failed request to retry. * @return {boolean} true iff a retry was scheduled. * @private */ goog.net.BrowserChannel.prototype.maybeRetryForwardChannel_ = function(request) { if (this.forwardChannelRequest_ || this.forwardChannelTimerId_) { // Should be impossible to be called in this state. this.channelDebug_.severe('Request already in progress'); return false; } if (this.state_ == goog.net.BrowserChannel.State.INIT || // no retry open_() (this.forwardChannelRetryCount_ >= this.getForwardChannelMaxRetries())) { return false; } this.channelDebug_.debug('Going to retry POST'); this.forwardChannelTimerId_ = goog.net.BrowserChannel.setTimeout( goog.bind(this.onStartForwardChannelTimer_, this, request), this.getRetryTime_(this.forwardChannelRetryCount_)); this.forwardChannelRetryCount_++; return true; }; /** * Timer callback for ensureForwardChannel * @param {goog.net.ChannelRequest=} opt_retryRequest A failed request to retry. * @private */ goog.net.BrowserChannel.prototype.onStartForwardChannelTimer_ = function( opt_retryRequest) { this.forwardChannelTimerId_ = null; this.startForwardChannel_(opt_retryRequest); }; /** * Begins a new forward channel operation to the server. * @param {goog.net.ChannelRequest=} opt_retryRequest A failed request to retry. * @private */ goog.net.BrowserChannel.prototype.startForwardChannel_ = function( opt_retryRequest) { this.channelDebug_.debug('startForwardChannel_'); if (!this.okToMakeRequest_()) { return; // channel is cancelled } else if (this.state_ == goog.net.BrowserChannel.State.INIT) { if (opt_retryRequest) { this.channelDebug_.severe('Not supposed to retry the open'); return; } this.open_(); this.state_ = goog.net.BrowserChannel.State.OPENING; } else if (this.state_ == goog.net.BrowserChannel.State.OPENED) { if (opt_retryRequest) { this.makeForwardChannelRequest_(opt_retryRequest); return; } if (this.outgoingMaps_.length == 0) { this.channelDebug_.debug('startForwardChannel_ returned: ' + 'nothing to send'); // no need to start a new forward channel request return; } if (this.forwardChannelRequest_) { // Should be impossible to be called in this state. this.channelDebug_.severe('startForwardChannel_ returned: ' + 'connection already in progress'); return; } this.makeForwardChannelRequest_(); this.channelDebug_.debug('startForwardChannel_ finished, sent request'); } }; /** * Establishes a new channel session with the the server. * @private */ goog.net.BrowserChannel.prototype.open_ = function() { this.channelDebug_.debug('open_()'); this.nextRid_ = Math.floor(Math.random() * 100000); var rid = this.nextRid_++; var request = goog.net.BrowserChannel.createChannelRequest( this, this.channelDebug_, '', rid); request.setExtraHeaders(this.extraHeaders_); var requestText = this.dequeueOutgoingMaps_(); var uri = this.forwardChannelUri_.clone(); uri.setParameterValue('RID', rid); if (this.clientVersion_) { uri.setParameterValue('CVER', this.clientVersion_); } // Add the reconnect parameters. this.addAdditionalParams_(uri); request.xmlHttpPost(uri, requestText, true); this.forwardChannelRequest_ = request; }; /** * Makes a forward channel request using XMLHTTP. * @param {goog.net.ChannelRequest=} opt_retryRequest A failed request to retry. * @private */ goog.net.BrowserChannel.prototype.makeForwardChannelRequest_ = function(opt_retryRequest) { var rid; var requestText; if (opt_retryRequest) { if (this.channelVersion_ > 6) { // In version 7 and up we can tack on new arrays to a retry. this.requeuePendingMaps_(); rid = this.nextRid_ - 1; // Must use last RID requestText = this.dequeueOutgoingMaps_(); } else { // TODO(user): Remove this code and the opt_retryRequest passing // once server-side support for ver 7 is ubiquitous. rid = opt_retryRequest.getRequestId(); requestText = /** @type {string} */ (opt_retryRequest.getPostData()); } } else { rid = this.nextRid_++; requestText = this.dequeueOutgoingMaps_(); } var uri = this.forwardChannelUri_.clone(); uri.setParameterValue('SID', this.sid_); uri.setParameterValue('RID', rid); uri.setParameterValue('AID', this.lastArrayId_); // Add the additional reconnect parameters. this.addAdditionalParams_(uri); var request = goog.net.BrowserChannel.createChannelRequest( this, this.channelDebug_, this.sid_, rid, this.forwardChannelRetryCount_ + 1); request.setExtraHeaders(this.extraHeaders_); // randomize from 50%-100% of the forward channel timeout to avoid // a big hit if servers happen to die at once. request.setTimeout( Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50) + Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50 * Math.random())); this.forwardChannelRequest_ = request; request.xmlHttpPost(uri, requestText, true); }; /** * Adds the additional parameters from the handler to the given URI. * @param {goog.Uri} uri The URI to add the parameters to. * @private */ goog.net.BrowserChannel.prototype.addAdditionalParams_ = function(uri) { // Add the additional reconnect parameters as needed. if (this.handler_) { var params = this.handler_.getAdditionalParams(this); if (params) { goog.structs.forEach(params, function(value, key, coll) { uri.setParameterValue(key, value); }); } } }; /** * Returns the request text from the outgoing maps and resets it. * @return {string} The encoded request text created from all the currently * queued outgoing maps. * @private */ goog.net.BrowserChannel.prototype.dequeueOutgoingMaps_ = function() { var count = Math.min(this.outgoingMaps_.length, goog.net.BrowserChannel.MAX_MAPS_PER_REQUEST_); var sb = ['count=' + count]; var offset; if (this.channelVersion_ > 6 && count > 0) { // To save a bit of bandwidth, specify the base mapId and the rest as // offsets from it. offset = this.outgoingMaps_[0].mapId; sb.push('ofs=' + offset); } else { offset = 0; } for (var i = 0; i < count; i++) { var mapId = this.outgoingMaps_[i].mapId; var map = this.outgoingMaps_[i].map; if (this.channelVersion_ <= 6) { // Map IDs were not used in ver 6 and before, just indexes in the request. mapId = i; } else { mapId -= offset; } try { goog.structs.forEach(map, function(value, key, coll) { sb.push('req' + mapId + '_' + key + '=' + encodeURIComponent(value)); }); } catch (ex) { // We send a map here because lots of the retry logic relies on map IDs, // so we have to send something. sb.push('req' + mapId + '_' + 'type' + '=' + encodeURIComponent('_badmap')); if (this.handler_) { this.handler_.badMapError(this, map); } } } this.pendingMaps_ = this.pendingMaps_.concat( this.outgoingMaps_.splice(0, count)); return sb.join('&'); }; /** * Requeues unacknowledged sent arrays for retransmission in the next forward * channel request. * @private */ goog.net.BrowserChannel.prototype.requeuePendingMaps_ = function() { this.outgoingMaps_ = this.pendingMaps_.concat(this.outgoingMaps_); this.pendingMaps_.length = 0; }; /** * Ensures there is a backchannel request for receiving data from the server. * @private */ goog.net.BrowserChannel.prototype.ensureBackChannel_ = function() { if (this.backChannelRequest_) { // already have one return; } if (this.backChannelTimerId_) { // no need to start a new request - one is already scheduled return; } this.backChannelAttemptId_ = 1; this.backChannelTimerId_ = goog.net.BrowserChannel.setTimeout( goog.bind(this.onStartBackChannelTimer_, this), 0); this.backChannelRetryCount_ = 0; }; /** * Schedules a back-channel retry, unless the max retries has been reached. * @return {boolean} true iff a retry was scheduled. * @private */ goog.net.BrowserChannel.prototype.maybeRetryBackChannel_ = function() { if (this.backChannelRequest_ || this.backChannelTimerId_) { // Should be impossible to be called in this state. this.channelDebug_.severe('Request already in progress'); return false; } if (this.backChannelRetryCount_ >= this.getBackChannelMaxRetries()) { return false; } this.channelDebug_.debug('Going to retry GET'); this.backChannelAttemptId_++; this.backChannelTimerId_ = goog.net.BrowserChannel.setTimeout( goog.bind(this.onStartBackChannelTimer_, this), this.getRetryTime_(this.backChannelRetryCount_)); this.backChannelRetryCount_++; return true; }; /** * Timer callback for ensureBackChannel_. * @private */ goog.net.BrowserChannel.prototype.onStartBackChannelTimer_ = function() { this.backChannelTimerId_ = null; this.startBackChannel_(); }; /** * Begins a new back channel operation to the server. * @private */ goog.net.BrowserChannel.prototype.startBackChannel_ = function() { if (!this.okToMakeRequest_()) { // channel is cancelled return; } this.channelDebug_.debug('Creating new HttpRequest'); this.backChannelRequest_ = goog.net.BrowserChannel.createChannelRequest( this, this.channelDebug_, this.sid_, 'rpc', this.backChannelAttemptId_); this.backChannelRequest_.setExtraHeaders(this.extraHeaders_); this.backChannelRequest_.setReadyStateChangeThrottle( this.readyStateChangeThrottleMs_); var uri = this.backChannelUri_.clone(); uri.setParameterValue('RID', 'rpc'); uri.setParameterValue('SID', this.sid_); uri.setParameterValue('CI', this.useChunked_ ? '0' : '1'); uri.setParameterValue('AID', this.lastArrayId_); // Add the reconnect parameters. this.addAdditionalParams_(uri); if (!goog.net.ChannelRequest.supportsXhrStreaming()) { uri.setParameterValue('TYPE', 'html'); this.backChannelRequest_.tridentGet(uri, Boolean(this.hostPrefix_)); } else { uri.setParameterValue('TYPE', 'xmlhttp'); this.backChannelRequest_.xmlHttpGet(uri, true /* decodeChunks */, this.hostPrefix_, false /* opt_noClose */); } this.channelDebug_.debug('New Request created'); }; /** * Gives the handler a chance to return an error code and stop channel * execution. A handler might want to do this to check that the user is still * logged in, for example. * @private * @return {boolean} If it's OK to make a request. */ goog.net.BrowserChannel.prototype.okToMakeRequest_ = function() { if (this.handler_) { var result = this.handler_.okToMakeRequest(this); if (result != goog.net.BrowserChannel.Error.OK) { this.channelDebug_.debug('Handler returned error code from ' + 'okToMakeRequest'); this.signalError_(result); return false; } } return true; }; /** * Callback from BrowserTestChannel for when the channel is finished. * @param {goog.net.BrowserTestChannel} testChannel The BrowserTestChannel. * @param {boolean} useChunked Whether we can chunk responses. */ goog.net.BrowserChannel.prototype.testConnectionFinished = function(testChannel, useChunked) { this.channelDebug_.debug('Test Connection Finished'); this.useChunked_ = this.allowChunkedMode_ && useChunked; this.lastStatusCode_ = testChannel.getLastStatusCode(); this.connectChannel_(); }; /** * Callback from BrowserTestChannel for when the channel has an error. * @param {goog.net.BrowserTestChannel} testChannel The BrowserTestChannel. * @param {goog.net.ChannelRequest.Error} errorCode The error code of the failure. */ goog.net.BrowserChannel.prototype.testConnectionFailure = function(testChannel, errorCode) { this.channelDebug_.debug('Test Connection Failed'); this.lastStatusCode_ = testChannel.getLastStatusCode(); this.signalError_(goog.net.BrowserChannel.Error.REQUEST_FAILED); }; /** * Callback from BrowserTestChannel for when the channel is blocked. * @param {goog.net.BrowserTestChannel} testChannel The BrowserTestChannel. */ goog.net.BrowserChannel.prototype.testConnectionBlocked = function(testChannel) { this.channelDebug_.debug('Test Connection Blocked'); this.lastStatusCode_ = this.connectionTest_.getLastStatusCode(); this.signalError_(goog.net.BrowserChannel.Error.BLOCKED); }; /** * Callback from ChannelRequest for when new data is received * @param {goog.net.ChannelRequest} request The request object. * @param {string} responseText The text of the response. */ goog.net.BrowserChannel.prototype.onRequestData = function(request, responseText) { if (this.state_ == goog.net.BrowserChannel.State.CLOSED || (this.backChannelRequest_ != request && this.forwardChannelRequest_ != request)) { // either CLOSED or a request we don't know about (perhaps an old request) return; } this.lastStatusCode_ = request.getLastStatusCode(); if (this.forwardChannelRequest_ == request && this.state_ == goog.net.BrowserChannel.State.OPENED) { if (this.channelVersion_ > 7) { var response; try { response = this.parser_.parse(responseText); } catch (ex) { response = null; } if (goog.isArray(response) && response.length == 3) { this.handlePostResponse_(/** @type {Array} */ (response)); } else { this.channelDebug_.debug('Bad POST response data returned'); this.signalError_(goog.net.BrowserChannel.Error.BAD_RESPONSE); } } else if (responseText != goog.net.BrowserChannel.MAGIC_RESPONSE_COOKIE) { this.channelDebug_.debug('Bad data returned - missing/invald ' + 'magic cookie'); this.signalError_(goog.net.BrowserChannel.Error.BAD_RESPONSE); } } else { if (this.backChannelRequest_ == request) { this.clearDeadBackchannelTimer_(); } if (!goog.string.isEmpty(responseText)) { var response = this.parser_.parse(responseText); goog.asserts.assert(goog.isArray(response)); this.onInput_(/** @type {Array} */ (response)); } } }; /** * Handles a POST response from the server. * @param {Array} responseValues The key value pairs in the POST response. * @private */ goog.net.BrowserChannel.prototype.handlePostResponse_ = function( responseValues) { // The first response value is set to 0 if server is missing backchannel. if (responseValues[0] == 0) { this.handleBackchannelMissing_(); return; } this.lastPostResponseArrayId_ = responseValues[1]; var outstandingArrays = this.lastPostResponseArrayId_ - this.lastArrayId_; if (0 < outstandingArrays) { var numOutstandingBackchannelBytes = responseValues[2]; this.channelDebug_.debug(numOutstandingBackchannelBytes + ' bytes (in ' + outstandingArrays + ' arrays) are outstanding on the BackChannel'); if (!this.shouldRetryBackChannel_(numOutstandingBackchannelBytes)) { return; } if (!this.deadBackChannelTimerId_) { // We expect to receive data within 2 RTTs or we retry the backchannel. this.deadBackChannelTimerId_ = goog.net.BrowserChannel.setTimeout( goog.bind(this.onBackChannelDead_, this), 2 * goog.net.BrowserChannel.RTT_ESTIMATE); } } }; /** * Handles a POST response from the server telling us that it has detected that * we have no hanging GET connection. * @private */ goog.net.BrowserChannel.prototype.handleBackchannelMissing_ = function() { // As long as the back channel was started before the POST was sent, // we should retry the backchannel. We give a slight buffer of RTT_ESTIMATE // so as not to excessively retry the backchannel this.channelDebug_.debug('Server claims our backchannel is missing.'); if (this.backChannelTimerId_) { this.channelDebug_.debug('But we are currently starting the request.'); return; } else if (!this.backChannelRequest_) { this.channelDebug_.warning( 'We do not have a BackChannel established'); } else if (this.backChannelRequest_.getRequestStartTime() + goog.net.BrowserChannel.RTT_ESTIMATE < this.forwardChannelRequest_.getRequestStartTime()) { this.clearDeadBackchannelTimer_(); this.backChannelRequest_.cancel(); this.backChannelRequest_ = null; } else { return; } this.maybeRetryBackChannel_(); goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.BACKCHANNEL_MISSING); }; /** * Determines whether we should start the process of retrying a possibly * dead backchannel. * @param {number} outstandingBytes The number of bytes for which the server has * not yet received acknowledgement. * @return {boolean} Whether to start the backchannel retry timer. * @private */ goog.net.BrowserChannel.prototype.shouldRetryBackChannel_ = function( outstandingBytes) { // Not too many outstanding bytes, not buffered and not after a retry. return outstandingBytes < goog.net.BrowserChannel.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF && !this.isBuffered() && this.backChannelRetryCount_ == 0; }; /** * Decides which host prefix should be used, if any. If there is a handler, * allows the handler to validate a host prefix provided by the server, and * optionally override it. * @param {?string} serverHostPrefix The host prefix provided by the server. * @return {?string} The host prefix to actually use, if any. Will return null * if the use of host prefixes was disabled via setAllowHostPrefix(). */ goog.net.BrowserChannel.prototype.correctHostPrefix = function( serverHostPrefix) { if (this.allowHostPrefix_) { if (this.handler_) { return this.handler_.correctHostPrefix(serverHostPrefix); } return serverHostPrefix; } return null; }; /** * Handles the timer that indicates that our backchannel is no longer able to * successfully receive data from the server. * @private */ goog.net.BrowserChannel.prototype.onBackChannelDead_ = function() { if (goog.isDefAndNotNull(this.deadBackChannelTimerId_)) { this.deadBackChannelTimerId_ = null; this.backChannelRequest_.cancel(); this.backChannelRequest_ = null; this.maybeRetryBackChannel_(); goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.BACKCHANNEL_DEAD); } }; /** * Clears the timer that indicates that our backchannel is no longer able to * successfully receive data from the server. * @private */ goog.net.BrowserChannel.prototype.clearDeadBackchannelTimer_ = function() { if (goog.isDefAndNotNull(this.deadBackChannelTimerId_)) { goog.global.clearTimeout(this.deadBackChannelTimerId_); this.deadBackChannelTimerId_ = null; } }; /** * Returns whether or not the given error/status combination is fatal or not. * On fatal errors we immediately close the session rather than retrying the * failed request. * @param {goog.net.ChannelRequest.Error?} error The error code for the failed * request. * @param {number} statusCode The last HTTP status code. * @return {boolean} Whether or not the error is fatal. * @private */ goog.net.BrowserChannel.isFatalError_ = function(error, statusCode) { return error == goog.net.ChannelRequest.Error.UNKNOWN_SESSION_ID || error == goog.net.ChannelRequest.Error.ACTIVE_X_BLOCKED || (error == goog.net.ChannelRequest.Error.STATUS && statusCode > 0); }; /** * Callback from ChannelRequest that indicates a request has completed. * @param {goog.net.ChannelRequest} request The request object. */ goog.net.BrowserChannel.prototype.onRequestComplete = function(request) { this.channelDebug_.debug('Request complete'); var type; if (this.backChannelRequest_ == request) { this.clearDeadBackchannelTimer_(); this.backChannelRequest_ = null; type = goog.net.BrowserChannel.ChannelType_.BACK_CHANNEL; } else if (this.forwardChannelRequest_ == request) { this.forwardChannelRequest_ = null; type = goog.net.BrowserChannel.ChannelType_.FORWARD_CHANNEL; } else { // return if it was an old request from a previous session return; } this.lastStatusCode_ = request.getLastStatusCode(); if (this.state_ == goog.net.BrowserChannel.State.CLOSED) { return; } if (request.getSuccess()) { // Yay! if (type == goog.net.BrowserChannel.ChannelType_.FORWARD_CHANNEL) { var size = request.getPostData() ? request.getPostData().length : 0; goog.net.BrowserChannel.notifyTimingEvent(size, goog.now() - request.getRequestStartTime(), this.forwardChannelRetryCount_); this.ensureForwardChannel_(); this.onSuccess_(); this.pendingMaps_.length = 0; } else { // i.e., back-channel this.ensureBackChannel_(); } return; } // Else unsuccessful. Fall through. var lastError = request.getLastError(); if (!goog.net.BrowserChannel.isFatalError_(lastError, this.lastStatusCode_)) { // Maybe retry. this.channelDebug_.debug('Maybe retrying, last error: ' + goog.net.ChannelRequest.errorStringFromCode( /** @type {goog.net.ChannelRequest.Error} */ (lastError), this.lastStatusCode_)); if (type == goog.net.BrowserChannel.ChannelType_.FORWARD_CHANNEL) { if (this.maybeRetryForwardChannel_(request)) { return; } } if (type == goog.net.BrowserChannel.ChannelType_.BACK_CHANNEL) { if (this.maybeRetryBackChannel_()) { return; } } // Else exceeded max retries. Fall through. this.channelDebug_.debug('Exceeded max number of retries'); } else { // Else fatal error. Fall through and mark the pending maps as failed. this.channelDebug_.debug('Not retrying due to error type'); } // Can't save this session. :( this.channelDebug_.debug('Error: HTTP request failed'); switch (lastError) { case goog.net.ChannelRequest.Error.NO_DATA: this.signalError_(goog.net.BrowserChannel.Error.NO_DATA); break; case goog.net.ChannelRequest.Error.BAD_DATA: this.signalError_(goog.net.BrowserChannel.Error.BAD_DATA); break; case goog.net.ChannelRequest.Error.UNKNOWN_SESSION_ID: this.signalError_(goog.net.BrowserChannel.Error.UNKNOWN_SESSION_ID); break; case goog.net.ChannelRequest.Error.ACTIVE_X_BLOCKED: this.signalError_(goog.net.BrowserChannel.Error.ACTIVE_X_BLOCKED); break; default: this.signalError_(goog.net.BrowserChannel.Error.REQUEST_FAILED); break; } }; /** * @param {number} retryCount Number of retries so far. * @return {number} Time in ms before firing next retry request. * @private */ goog.net.BrowserChannel.prototype.getRetryTime_ = function(retryCount) { var retryTime = this.baseRetryDelayMs_ + Math.floor(Math.random() * this.retryDelaySeedMs_); if (!this.isActive()) { this.channelDebug_.debug('Inactive channel'); retryTime = retryTime * goog.net.BrowserChannel.INACTIVE_CHANNEL_RETRY_FACTOR; } // Backoff for subsequent retries retryTime = retryTime * retryCount; return retryTime; }; /** * @param {number} baseDelayMs The base part of the retry delay, in ms. * @param {number} delaySeedMs A random delay between 0 and this is added to * the base part. */ goog.net.BrowserChannel.prototype.setRetryDelay = function(baseDelayMs, delaySeedMs) { this.baseRetryDelayMs_ = baseDelayMs; this.retryDelaySeedMs_ = delaySeedMs; }; /** * Processes the data returned by the server. * @param {Array} respArray The response array returned by the server. * @private */ goog.net.BrowserChannel.prototype.onInput_ = function(respArray) { // respArray is an array of arrays var batch = this.handler_ && this.handler_.channelHandleMultipleArrays ? [] : null; for (var i = 0; i < respArray.length; i++) { var nextArray = respArray[i]; this.lastArrayId_ = nextArray[0]; nextArray = nextArray[1]; if (this.state_ == goog.net.BrowserChannel.State.OPENING) { if (nextArray[0] == 'c') { this.sid_ = nextArray[1]; this.hostPrefix_ = this.correctHostPrefix(nextArray[2]); var negotiatedVersion = nextArray[3]; if (goog.isDefAndNotNull(negotiatedVersion)) { this.channelVersion_ = negotiatedVersion; } else { // Servers prior to version 7 did not send this, so assume version 6. this.channelVersion_ = 6; } this.state_ = goog.net.BrowserChannel.State.OPENED; if (this.handler_) { this.handler_.channelOpened(this); } this.backChannelUri_ = this.getBackChannelUri( this.hostPrefix_, /** @type {string} */ (this.path_)); // Open connection to receive data this.ensureBackChannel_(); } else if (nextArray[0] == 'stop') { this.signalError_(goog.net.BrowserChannel.Error.STOP); } } else if (this.state_ == goog.net.BrowserChannel.State.OPENED) { if (nextArray[0] == 'stop') { if (batch && batch.length) { this.handler_.channelHandleMultipleArrays(this, batch); batch.length = 0; } this.signalError_(goog.net.BrowserChannel.Error.STOP); } else if (nextArray[0] == 'noop') { // ignore - noop to keep connection happy } else { if (batch) { batch.push(nextArray); } else if (this.handler_) { this.handler_.channelHandleArray(this, nextArray); } } // We have received useful data on the back-channel, so clear its retry // count. We do this because back-channels by design do not complete // quickly, so on a flaky connection we could have many fail to complete // fully but still deliver a lot of data before they fail. We don't want // to count such failures towards the retry limit, because we don't want // to give up on a session if we can still receive data. this.backChannelRetryCount_ = 0; } } if (batch && batch.length) { this.handler_.channelHandleMultipleArrays(this, batch); } }; /** * Helper to ensure the BrowserChannel is in the expected state. * @param {...number} var_args The channel must be in one of the indicated * states. * @private */ goog.net.BrowserChannel.prototype.ensureInState_ = function(var_args) { if (!goog.array.contains(arguments, this.state_)) { throw Error('Unexpected channel state: ' + this.state_); } }; /** * Signals an error has occurred. * @param {goog.net.BrowserChannel.Error} error The error code for the failure. * @private */ goog.net.BrowserChannel.prototype.signalError_ = function(error) { this.channelDebug_.info('Error code ' + error); if (error == goog.net.BrowserChannel.Error.REQUEST_FAILED || error == goog.net.BrowserChannel.Error.BLOCKED) { // Ping google to check if it's a server error or user's network error. var imageUri = null; if (this.handler_) { imageUri = this.handler_.getNetworkTestImageUri(this); } goog.net.tmpnetwork.testGoogleCom( goog.bind(this.testGoogleComCallback_, this), imageUri); } else { goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.ERROR_OTHER); } this.onError_(error); }; /** * Callback for testGoogleCom during error handling. * @param {boolean} networkUp Whether the network is up. * @private */ goog.net.BrowserChannel.prototype.testGoogleComCallback_ = function(networkUp) { if (networkUp) { this.channelDebug_.info('Successfully pinged google.com'); goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.ERROR_OTHER); } else { this.channelDebug_.info('Failed to ping google.com'); goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.ERROR_NETWORK); // We cann onError_ here instead of signalError_ because the latter just // calls notifyStatEvent, and we don't want to have another stat event. this.onError_(goog.net.BrowserChannel.Error.NETWORK); } }; /** * Called when messages have been successfully sent from the queue. * @private */ goog.net.BrowserChannel.prototype.onSuccess_ = function() { if (this.handler_) { this.handler_.channelSuccess(this, this.pendingMaps_); } }; /** * Called when we've determined the final error for a channel. It closes the * notifiers the handler of the error and closes the channel. * @param {goog.net.BrowserChannel.Error} error The error code for the failure. * @private */ goog.net.BrowserChannel.prototype.onError_ = function(error) { this.channelDebug_.debug('HttpChannel: error - ' + error); this.state_ = goog.net.BrowserChannel.State.CLOSED; if (this.handler_) { this.handler_.channelError(this, error); } this.onClose_(); this.cancelRequests_(); }; /** * Called when the channel has been closed. It notifiers the handler of the * event, and reports any pending or undelivered maps. * @private */ goog.net.BrowserChannel.prototype.onClose_ = function() { this.state_ = goog.net.BrowserChannel.State.CLOSED; this.lastStatusCode_ = -1; if (this.handler_) { if (this.pendingMaps_.length == 0 && this.outgoingMaps_.length == 0) { this.handler_.channelClosed(this); } else { this.channelDebug_.debug('Number of undelivered maps' + ', pending: ' + this.pendingMaps_.length + ', outgoing: ' + this.outgoingMaps_.length); var copyOfPendingMaps = goog.array.clone(this.pendingMaps_); var copyOfUndeliveredMaps = goog.array.clone(this.outgoingMaps_); this.pendingMaps_.length = 0; this.outgoingMaps_.length = 0; this.handler_.channelClosed(this, copyOfPendingMaps, copyOfUndeliveredMaps); } } }; /** * Gets the Uri used for the connection that sends data to the server. * @param {string} path The path on the host. * @return {goog.Uri} The forward channel URI. */ goog.net.BrowserChannel.prototype.getForwardChannelUri = function(path) { var uri = this.createDataUri(null, path); this.channelDebug_.debug('GetForwardChannelUri: ' + uri); return uri; }; /** * Gets the results for the first browser channel test * @return {Array.<string>} The results. */ goog.net.BrowserChannel.prototype.getFirstTestResults = function() { return this.firstTestResults_; }; /** * Gets the results for the second browser channel test * @return {?boolean} The results. True -> buffered connection, * False -> unbuffered, null -> unknown. */ goog.net.BrowserChannel.prototype.getSecondTestResults = function() { return this.secondTestResults_; }; /** * Gets the Uri used for the connection that receives data from the server. * @param {?string} hostPrefix The host prefix. * @param {string} path The path on the host. * @return {goog.Uri} The back channel URI. */ goog.net.BrowserChannel.prototype.getBackChannelUri = function(hostPrefix, path) { var uri = this.createDataUri(this.shouldUseSecondaryDomains() ? hostPrefix : null, path); this.channelDebug_.debug('GetBackChannelUri: ' + uri); return uri; }; /** * Creates a data Uri applying logic for secondary hostprefix, port * overrides, and versioning. * @param {?string} hostPrefix The host prefix. * @param {string} path The path on the host (may be absolute or relative). * @param {number=} opt_overridePort Optional override port. * @return {goog.Uri} The data URI. */ goog.net.BrowserChannel.prototype.createDataUri = function(hostPrefix, path, opt_overridePort) { var uri = goog.Uri.parse(path); var uriAbsolute = (uri.getDomain() != ''); if (uriAbsolute) { if (hostPrefix) { uri.setDomain(hostPrefix + '.' + uri.getDomain()); } uri.setPort(opt_overridePort || uri.getPort()); } else { var locationPage = window.location; var hostName; if (hostPrefix) { hostName = hostPrefix + '.' + locationPage.hostname; } else { hostName = locationPage.hostname; } var port = opt_overridePort || locationPage.port; uri = goog.Uri.create(locationPage.protocol, null, hostName, port, path); } if (this.extraParams_) { goog.structs.forEach(this.extraParams_, function(value, key, coll) { uri.setParameterValue(key, value); }); } // Add the protocol version to the URI. uri.setParameterValue('VER', this.channelVersion_); // Add the reconnect parameters. this.addAdditionalParams_(uri); return uri; }; /** * Called when BC needs to create an XhrIo object. Override in a subclass if * you need to customize the behavior, for example to enable the creation of * XHR's capable of calling a secondary domain. Will also allow calling * a secondary domain if withCredentials (CORS) is enabled. * @param {?string} hostPrefix The host prefix, if we need an XhrIo object * capable of calling a secondary domain. * @return {!goog.net.XhrIo} A new XhrIo object. */ goog.net.BrowserChannel.prototype.createXhrIo = function(hostPrefix) { if (hostPrefix && !this.supportsCrossDomainXhrs_) { throw Error('Can\'t create secondary domain capable XhrIo object.'); } var xhr = new goog.net.XhrIo(); xhr.setWithCredentials(this.supportsCrossDomainXhrs_); return xhr; }; /** * Gets whether this channel is currently active. This is used to determine the * length of time to wait before retrying. This call delegates to the handler. * @return {boolean} Whether the channel is currently active. */ goog.net.BrowserChannel.prototype.isActive = function() { return !!this.handler_ && this.handler_.isActive(this); }; /** * Wrapper around SafeTimeout which calls the start and end execution hooks * with a try...finally block. * @param {Function} fn The callback function. * @param {number} ms The time in MS for the timer. * @return {number} The ID of the timer. */ goog.net.BrowserChannel.setTimeout = function(fn, ms) { if (!goog.isFunction(fn)) { throw Error('Fn must not be null and must be a function'); } return goog.global.setTimeout(function() { goog.net.BrowserChannel.onStartExecution(); try { fn(); } finally { goog.net.BrowserChannel.onEndExecution(); } }, ms); }; /** * Helper function to call the start hook */ goog.net.BrowserChannel.onStartExecution = function() { goog.net.BrowserChannel.startExecutionHook_(); }; /** * Helper function to call the end hook */ goog.net.BrowserChannel.onEndExecution = function() { goog.net.BrowserChannel.endExecutionHook_(); }; /** * Returns the singleton event target for stat events. * @return {goog.events.EventTarget} The event target for stat events. */ goog.net.BrowserChannel.getStatEventTarget = function() { return goog.net.BrowserChannel.statEventTarget_; }; /** * Notify the channel that a particular fine grained network event has occurred. * Should be considered package-private. * @param {goog.net.BrowserChannel.ServerReachability} reachabilityType The * reachability event type. */ goog.net.BrowserChannel.prototype.notifyServerReachabilityEvent = function( reachabilityType) { var target = goog.net.BrowserChannel.statEventTarget_; target.dispatchEvent(new goog.net.BrowserChannel.ServerReachabilityEvent( target, reachabilityType)); }; /** * Helper function to call the stat event callback. * @param {goog.net.BrowserChannel.Stat} stat The stat. */ goog.net.BrowserChannel.notifyStatEvent = function(stat) { var target = goog.net.BrowserChannel.statEventTarget_; target.dispatchEvent( new goog.net.BrowserChannel.StatEvent(target, stat)); }; /** * Helper function to notify listeners about POST request performance. * * @param {number} size Number of characters in the POST data. * @param {number} rtt The amount of time from POST start to response. * @param {number} retries The number of times the POST had to be retried. */ goog.net.BrowserChannel.notifyTimingEvent = function(size, rtt, retries) { var target = goog.net.BrowserChannel.statEventTarget_; target.dispatchEvent( new goog.net.BrowserChannel.TimingEvent(target, size, rtt, retries)); }; /** * Determines whether to use a secondary domain when the server gives us * a host prefix. This allows us to work around browser per-domain * connection limits. * * Currently, we use secondary domains when using Trident's ActiveXObject, * because it supports cross-domain requests out of the box. Note that in IE10 * we no longer use ActiveX since it's not supported in Metro mode and IE10 * supports XHR streaming. * * If you need to use secondary domains on other browsers and IE10, * you have two choices: * 1) If you only care about browsers that support CORS * (https://developer.mozilla.org/en-US/docs/HTTP_access_control), you * can use {@link #setSupportsCrossDomainXhrs} and set the appropriate * CORS response headers on the server. * 2) Or, override this method in a subclass, and make sure that those * browsers use some messaging mechanism that works cross-domain (e.g * iframes and window.postMessage). * * @return {boolean} Whether to use secondary domains. * @see http://code.google.com/p/closure-library/issues/detail?id=339 */ goog.net.BrowserChannel.prototype.shouldUseSecondaryDomains = function() { return this.supportsCrossDomainXhrs_ || !goog.net.ChannelRequest.supportsXhrStreaming(); }; /** * A LogSaver that can be used to accumulate all the debug logs for * BrowserChannels so they can be sent to the server when a problem is * detected. */ goog.net.BrowserChannel.LogSaver = {}; /** * Buffer for accumulating the debug log * @type {goog.structs.CircularBuffer} * @private */ goog.net.BrowserChannel.LogSaver.buffer_ = new goog.structs.CircularBuffer(1000); /** * Whether we're currently accumulating the debug log. * @type {boolean} * @private */ goog.net.BrowserChannel.LogSaver.enabled_ = false; /** * Formatter for saving logs. * @type {goog.debug.Formatter} * @private */ goog.net.BrowserChannel.LogSaver.formatter_ = new goog.debug.TextFormatter(); /** * Returns whether the LogSaver is enabled. * @return {boolean} Whether saving is enabled or disabled. */ goog.net.BrowserChannel.LogSaver.isEnabled = function() { return goog.net.BrowserChannel.LogSaver.enabled_; }; /** * Enables of disables the LogSaver. * @param {boolean} enable Whether to enable or disable saving. */ goog.net.BrowserChannel.LogSaver.setEnabled = function(enable) { if (enable == goog.net.BrowserChannel.LogSaver.enabled_) { return; } var fn = goog.net.BrowserChannel.LogSaver.addLogRecord; var logger = goog.debug.Logger.getLogger('goog.net'); if (enable) { logger.addHandler(fn); } else { logger.removeHandler(fn); } }; /** * Adds a log record. * @param {goog.debug.LogRecord} logRecord the LogRecord. */ goog.net.BrowserChannel.LogSaver.addLogRecord = function(logRecord) { goog.net.BrowserChannel.LogSaver.buffer_.add( goog.net.BrowserChannel.LogSaver.formatter_.formatRecord(logRecord)); }; /** * Returns the log as a single string. * @return {string} The log as a single string. */ goog.net.BrowserChannel.LogSaver.getBuffer = function() { return goog.net.BrowserChannel.LogSaver.buffer_.getValues().join(''); }; /** * Clears the buffer */ goog.net.BrowserChannel.LogSaver.clearBuffer = function() { goog.net.BrowserChannel.LogSaver.buffer_.clear(); }; /** * Interface for the browser channel handler * @constructor */ goog.net.BrowserChannel.Handler = function() { }; /** * Callback handler for when a batch of response arrays is received from the * server. * @type {Function} */ goog.net.BrowserChannel.Handler.prototype.channelHandleMultipleArrays = null; /** * Whether it's okay to make a request to the server. A handler can return * false if the channel should fail. For example, if the user has logged out, * the handler may want all requests to fail immediately. * @param {goog.net.BrowserChannel} browserChannel The browser channel. * @return {goog.net.BrowserChannel.Error} An error code. The code should * return goog.net.BrowserChannel.Error.OK to indicate it's okay. Any other * error code will cause a failure. */ goog.net.BrowserChannel.Handler.prototype.okToMakeRequest = function(browserChannel) { return goog.net.BrowserChannel.Error.OK; }; /** * Indicates the BrowserChannel has successfully negotiated with the server * and can now send and receive data. * @param {goog.net.BrowserChannel} browserChannel The browser channel. */ goog.net.BrowserChannel.Handler.prototype.channelOpened = function(browserChannel) { }; /** * New input is available for the application to process. * * @param {goog.net.BrowserChannel} browserChannel The browser channel. * @param {Array} array The data array. */ goog.net.BrowserChannel.Handler.prototype.channelHandleArray = function(browserChannel, array) { }; /** * Indicates maps were successfully sent on the BrowserChannel. * * @param {goog.net.BrowserChannel} browserChannel The browser channel. * @param {Array.<goog.net.BrowserChannel.QueuedMap>} deliveredMaps The * array of maps that have been delivered to the server. This is a direct * reference to the internal BrowserChannel array, so a copy should be made * if the caller desires a reference to the data. */ goog.net.BrowserChannel.Handler.prototype.channelSuccess = function(browserChannel, deliveredMaps) { }; /** * Indicates an error occurred on the BrowserChannel. * * @param {goog.net.BrowserChannel} browserChannel The browser channel. * @param {goog.net.BrowserChannel.Error} error The error code. */ goog.net.BrowserChannel.Handler.prototype.channelError = function(browserChannel, error) { }; /** * Indicates the BrowserChannel is closed. Also notifies about which maps, * if any, that may not have been delivered to the server. * @param {goog.net.BrowserChannel} browserChannel The browser channel. * @param {Array.<goog.net.BrowserChannel.QueuedMap>=} opt_pendingMaps The * array of pending maps, which may or may not have been delivered to the * server. * @param {Array.<goog.net.BrowserChannel.QueuedMap>=} opt_undeliveredMaps * The array of undelivered maps, which have definitely not been delivered * to the server. */ goog.net.BrowserChannel.Handler.prototype.channelClosed = function(browserChannel, opt_pendingMaps, opt_undeliveredMaps) { }; /** * Gets any parameters that should be added at the time another connection is * made to the server. * @param {goog.net.BrowserChannel} browserChannel The browser channel. * @return {Object} Extra parameter keys and values to add to the * requests. */ goog.net.BrowserChannel.Handler.prototype.getAdditionalParams = function(browserChannel) { return {}; }; /** * Gets the URI of an image that can be used to test network connectivity. * @param {goog.net.BrowserChannel} browserChannel The browser channel. * @return {goog.Uri?} A custom URI to load for the network test. */ goog.net.BrowserChannel.Handler.prototype.getNetworkTestImageUri = function(browserChannel) { return null; }; /** * Gets whether this channel is currently active. This is used to determine the * length of time to wait before retrying. * @param {goog.net.BrowserChannel} browserChannel The browser channel. * @return {boolean} Whether the channel is currently active. */ goog.net.BrowserChannel.Handler.prototype.isActive = function(browserChannel) { return true; }; /** * Called by the channel if enumeration of the map throws an exception. * @param {goog.net.BrowserChannel} browserChannel The browser channel. * @param {Object} map The map that can't be enumerated. */ goog.net.BrowserChannel.Handler.prototype.badMapError = function(browserChannel, map) { return; }; /** * Allows the handler to override a host prefix provided by the server. Will * be called whenever the channel has received such a prefix and is considering * its use. * @param {?string} serverHostPrefix The host prefix provided by the server. * @return {?string} The host prefix the client should use. */ goog.net.BrowserChannel.Handler.prototype.correctHostPrefix = function(serverHostPrefix) { return serverHostPrefix; };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Definition of the BrowserTestChannel class. A * BrowserTestChannel is used during the first part of channel negotiation * with the server to create the channel. It helps us determine whether we're * behind a buffering proxy. It also runs the logic to see if the channel * has been blocked by a network administrator. This class is part of the * BrowserChannel implementation and is not for use by normal application code. * */ goog.provide('goog.net.BrowserTestChannel'); goog.require('goog.json.EvalJsonProcessor'); goog.require('goog.net.ChannelRequest'); goog.require('goog.net.ChannelRequest.Error'); goog.require('goog.net.tmpnetwork'); goog.require('goog.string.Parser'); goog.require('goog.userAgent'); /** * Encapsulates the logic for a single BrowserTestChannel. * * @constructor * @param {goog.net.BrowserChannel} channel The BrowserChannel that owns this * test channel. * @param {goog.net.ChannelDebug} channelDebug A ChannelDebug to use for * logging. */ goog.net.BrowserTestChannel = function(channel, channelDebug) { /** * The BrowserChannel that owns this test channel * @type {goog.net.BrowserChannel} * @private */ this.channel_ = channel; /** * The channel debug to use for logging * @type {goog.net.ChannelDebug} * @private */ this.channelDebug_ = channelDebug; /** * Parser for a response payload. Defaults to use * {@code goog.json.unsafeParse}. The parser should return an array. * @type {goog.string.Parser} * @private */ this.parser_ = new goog.json.EvalJsonProcessor(null, true); }; /** * Extra HTTP headers to add to all the requests sent to the server. * @type {Object} * @private */ goog.net.BrowserTestChannel.prototype.extraHeaders_ = null; /** * The test request. * @type {goog.net.ChannelRequest} * @private */ goog.net.BrowserTestChannel.prototype.request_ = null; /** * Whether we have received the first result as an intermediate result. This * helps us determine whether we're behind a buffering proxy. * @type {boolean} * @private */ goog.net.BrowserTestChannel.prototype.receivedIntermediateResult_ = false; /** * The time when the test request was started. We use timing in IE as * a heuristic for whether we're behind a buffering proxy. * @type {?number} * @private */ goog.net.BrowserTestChannel.prototype.startTime_ = null; /** * The time for of the first result part. We use timing in IE as a * heuristic for whether we're behind a buffering proxy. * @type {?number} * @private */ goog.net.BrowserTestChannel.prototype.firstTime_ = null; /** * The time for of the last result part. We use timing in IE as a * heuristic for whether we're behind a buffering proxy. * @type {?number} * @private */ goog.net.BrowserTestChannel.prototype.lastTime_ = null; /** * The relative path for test requests. * @type {?string} * @private */ goog.net.BrowserTestChannel.prototype.path_ = null; /** * The state of the state machine for this object. * * @type {?number} * @private */ goog.net.BrowserTestChannel.prototype.state_ = null; /** * The last status code received. * @type {number} * @private */ goog.net.BrowserTestChannel.prototype.lastStatusCode_ = -1; /** * A subdomain prefix for using a subdomain in IE for the backchannel * requests. * @type {?string} * @private */ goog.net.BrowserTestChannel.prototype.hostPrefix_ = null; /** * A subdomain prefix for testing whether the channel was disabled by * a network administrator; * @type {?string} * @private */ goog.net.BrowserTestChannel.prototype.blockedPrefix_ = null; /** * Enum type for the browser test channel state machine * @enum {number} * @private */ goog.net.BrowserTestChannel.State_ = { /** * The state for the BrowserTestChannel state machine where we making the * initial call to get the server configured parameters. */ INIT: 0, /** * The state for the BrowserTestChannel state machine where we're checking to * see if the channel has been blocked. */ CHECKING_BLOCKED: 1, /** * The state for the BrowserTestChannel state machine where we're checking to * se if we're behind a buffering proxy. */ CONNECTION_TESTING: 2 }; /** * Time in MS for waiting for the request to see if the channel is blocked. * If the response takes longer than this many ms, we assume the request has * failed. * @type {number} * @private */ goog.net.BrowserTestChannel.BLOCKED_TIMEOUT_ = 5000; /** * Number of attempts to try to see if the check to see if we're blocked * succeeds. Sometimes the request can fail because of flaky network conditions * and checking multiple times reduces false positives. * @type {number} * @private */ goog.net.BrowserTestChannel.BLOCKED_RETRIES_ = 3; /** * Time in ms between retries of the blocked request * @type {number} * @private */ goog.net.BrowserTestChannel.BLOCKED_PAUSE_BETWEEN_RETRIES_ = 2000; /** * Time between chunks in the test connection that indicates that we * are not behind a buffering proxy. This value should be less than or * equals to the time between chunks sent from the server. * @type {number} * @private */ goog.net.BrowserTestChannel.MIN_TIME_EXPECTED_BETWEEN_DATA_ = 500; /** * Sets extra HTTP headers to add to all the requests sent to the server. * * @param {Object} extraHeaders The HTTP headers. */ goog.net.BrowserTestChannel.prototype.setExtraHeaders = function(extraHeaders) { this.extraHeaders_ = extraHeaders; }; /** * Sets a new parser for the response payload. A custom parser may be set to * avoid using eval(), for example. * By default, the parser uses {@code goog.json.unsafeParse}. * @param {!goog.string.Parser} parser Parser. */ goog.net.BrowserTestChannel.prototype.setParser = function(parser) { this.parser_ = parser; }; /** * Starts the test channel. This initiates connections to the server. * * @param {string} path The relative uri for the test connection. */ goog.net.BrowserTestChannel.prototype.connect = function(path) { this.path_ = path; var sendDataUri = this.channel_.getForwardChannelUri(this.path_); goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.TEST_STAGE_ONE_START); this.startTime_ = goog.now(); // If the channel already has the result of the first test, then skip it. var firstTestResults = this.channel_.getFirstTestResults(); if (goog.isDefAndNotNull(firstTestResults)) { this.hostPrefix_ = this.channel_.correctHostPrefix(firstTestResults[0]); this.blockedPrefix_ = firstTestResults[1]; if (this.blockedPrefix_) { this.state_ = goog.net.BrowserTestChannel.State_.CHECKING_BLOCKED; this.checkBlocked_(); } else { this.state_ = goog.net.BrowserTestChannel.State_.CONNECTION_TESTING; this.connectStage2_(); } return; } // the first request returns server specific parameters sendDataUri.setParameterValues('MODE', 'init'); this.request_ = goog.net.BrowserChannel.createChannelRequest( this, this.channelDebug_); this.request_.setExtraHeaders(this.extraHeaders_); this.request_.xmlHttpGet(sendDataUri, false /* decodeChunks */, null /* hostPrefix */, true /* opt_noClose */); this.state_ = goog.net.BrowserTestChannel.State_.INIT; }; /** * Checks to see whether the channel is blocked. This is for implementing the * feature that allows network administrators to block Gmail Chat. The * strategy to determine if we're blocked is to try to load an image off a * special subdomain that network administrators will block access to if they * are trying to block chat. For Gmail Chat, the subdomain is * chatenabled.mail.google.com. * @private */ goog.net.BrowserTestChannel.prototype.checkBlocked_ = function() { var uri = this.channel_.createDataUri(this.blockedPrefix_, '/mail/images/cleardot.gif'); uri.makeUnique(); goog.net.tmpnetwork.testLoadImageWithRetries(uri.toString(), goog.net.BrowserTestChannel.BLOCKED_TIMEOUT_, goog.bind(this.checkBlockedCallback_, this), goog.net.BrowserTestChannel.BLOCKED_RETRIES_, goog.net.BrowserTestChannel.BLOCKED_PAUSE_BETWEEN_RETRIES_); this.notifyServerReachabilityEvent( goog.net.BrowserChannel.ServerReachability.REQUEST_MADE); }; /** * Callback for testLoadImageWithRetries to check if browser channel is * blocked. * @param {boolean} succeeded Whether the request succeeded. * @private */ goog.net.BrowserTestChannel.prototype.checkBlockedCallback_ = function( succeeded) { if (succeeded) { this.state_ = goog.net.BrowserTestChannel.State_.CONNECTION_TESTING; this.connectStage2_(); } else { goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.CHANNEL_BLOCKED); this.channel_.testConnectionBlocked(this); } // We don't dispatch a REQUEST_FAILED server reachability event when the // block request fails, as such a failure is not a good signal that the // server has actually become unreachable. if (succeeded) { this.notifyServerReachabilityEvent( goog.net.BrowserChannel.ServerReachability.REQUEST_SUCCEEDED); } }; /** * Begins the second stage of the test channel where we test to see if we're * behind a buffering proxy. The server sends back a multi-chunked response * with the first chunk containing the content '1' and then two seconds later * sending the second chunk containing the content '2'. Depending on how we * receive the content, we can tell if we're behind a buffering proxy. * @private */ goog.net.BrowserTestChannel.prototype.connectStage2_ = function() { this.channelDebug_.debug('TestConnection: starting stage 2'); // If the second test results are available, skip its execution. var secondTestResults = this.channel_.getSecondTestResults(); if (goog.isDefAndNotNull(secondTestResults)) { this.channelDebug_.debug( 'TestConnection: skipping stage 2, precomputed result is ' + secondTestResults ? 'Buffered' : 'Unbuffered'); goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.TEST_STAGE_TWO_START); if (secondTestResults) { // Buffered/Proxy connection goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.PROXY); this.channel_.testConnectionFinished(this, false); } else { // Unbuffered/NoProxy connection goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.NOPROXY); this.channel_.testConnectionFinished(this, true); } return; // Skip the test } this.request_ = goog.net.BrowserChannel.createChannelRequest( this, this.channelDebug_); this.request_.setExtraHeaders(this.extraHeaders_); var recvDataUri = this.channel_.getBackChannelUri(this.hostPrefix_, /** @type {string} */ (this.path_)); goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.TEST_STAGE_TWO_START); if (!goog.net.ChannelRequest.supportsXhrStreaming()) { recvDataUri.setParameterValues('TYPE', 'html'); this.request_.tridentGet(recvDataUri, Boolean(this.hostPrefix_)); } else { recvDataUri.setParameterValues('TYPE', 'xmlhttp'); this.request_.xmlHttpGet(recvDataUri, false /** decodeChunks */, this.hostPrefix_, false /** opt_noClose */); } }; /** * Factory method for XhrIo objects. * @param {?string} hostPrefix The host prefix, if we need an XhrIo object * capable of calling a secondary domain. * @return {!goog.net.XhrIo} New XhrIo object. */ goog.net.BrowserTestChannel.prototype.createXhrIo = function(hostPrefix) { return this.channel_.createXhrIo(hostPrefix); }; /** * Aborts the test channel. */ goog.net.BrowserTestChannel.prototype.abort = function() { if (this.request_) { this.request_.cancel(); this.request_ = null; } this.lastStatusCode_ = -1; }; /** * Returns whether the test channel is closed. The ChannelRequest object expects * this method to be implemented on its handler. * * @return {boolean} Whether the channel is closed. */ goog.net.BrowserTestChannel.prototype.isClosed = function() { return false; }; /** * Callback from ChannelRequest for when new data is received * * @param {goog.net.ChannelRequest} req The request object. * @param {string} responseText The text of the response. */ goog.net.BrowserTestChannel.prototype.onRequestData = function(req, responseText) { this.lastStatusCode_ = req.getLastStatusCode(); if (this.state_ == goog.net.BrowserTestChannel.State_.INIT) { this.channelDebug_.debug('TestConnection: Got data for stage 1'); if (!responseText) { this.channelDebug_.debug('TestConnection: Null responseText'); // The server should always send text; something is wrong here this.channel_.testConnectionFailure(this, goog.net.ChannelRequest.Error.BAD_DATA); return; } /** @preserveTry */ try { var respArray = this.parser_.parse(responseText); } catch (e) { this.channelDebug_.dumpException(e); this.channel_.testConnectionFailure(this, goog.net.ChannelRequest.Error.BAD_DATA); return; } this.hostPrefix_ = this.channel_.correctHostPrefix(respArray[0]); this.blockedPrefix_ = respArray[1]; } else if (this.state_ == goog.net.BrowserTestChannel.State_.CONNECTION_TESTING) { if (this.receivedIntermediateResult_) { goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.TEST_STAGE_TWO_DATA_TWO); this.lastTime_ = goog.now(); } else { // '11111' is used instead of '1' to prevent a small amount of buffering // by Safari. if (responseText == '11111') { goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.TEST_STAGE_TWO_DATA_ONE); this.receivedIntermediateResult_ = true; this.firstTime_ = goog.now(); if (this.checkForEarlyNonBuffered_()) { // If early chunk detection is on, and we passed the tests, // assume HTTP_OK, cancel the test and turn on noproxy mode. this.lastStatusCode_ = 200; this.request_.cancel(); this.channelDebug_.debug( 'Test connection succeeded; using streaming connection'); goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.NOPROXY); this.channel_.testConnectionFinished(this, true); } } else { goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.TEST_STAGE_TWO_DATA_BOTH); this.firstTime_ = this.lastTime_ = goog.now(); this.receivedIntermediateResult_ = false; } } } }; /** * Callback from ChannelRequest that indicates a request has completed. * * @param {goog.net.ChannelRequest} req The request object. */ goog.net.BrowserTestChannel.prototype.onRequestComplete = function(req) { this.lastStatusCode_ = this.request_.getLastStatusCode(); if (!this.request_.getSuccess()) { this.channelDebug_.debug( 'TestConnection: request failed, in state ' + this.state_); if (this.state_ == goog.net.BrowserTestChannel.State_.INIT) { goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.TEST_STAGE_ONE_FAILED); } else if (this.state_ == goog.net.BrowserTestChannel.State_.CONNECTION_TESTING) { goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.TEST_STAGE_TWO_FAILED); } this.channel_.testConnectionFailure(this, /** @type {goog.net.ChannelRequest.Error} */ (this.request_.getLastError())); return; } if (this.state_ == goog.net.BrowserTestChannel.State_.INIT) { this.channelDebug_.debug( 'TestConnection: request complete for initial check'); if (this.blockedPrefix_) { this.state_ = goog.net.BrowserTestChannel.State_.CHECKING_BLOCKED; this.checkBlocked_(); } else { this.state_ = goog.net.BrowserTestChannel.State_.CONNECTION_TESTING; this.connectStage2_(); } } else if (this.state_ == goog.net.BrowserTestChannel.State_.CONNECTION_TESTING) { this.channelDebug_.debug('TestConnection: request complete for stage 2'); var goodConn = false; if (!goog.net.ChannelRequest.supportsXhrStreaming()) { // we always get Trident responses in separate calls to // onRequestData, so we have to check the time they came var ms = this.lastTime_ - this.firstTime_; if (ms < 200) { // TODO: need to empirically verify that this number is OK // for slow computers goodConn = false; } else { goodConn = true; } } else { goodConn = this.receivedIntermediateResult_; } if (goodConn) { this.channelDebug_.debug( 'Test connection succeeded; using streaming connection'); goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.NOPROXY); this.channel_.testConnectionFinished(this, true); } else { this.channelDebug_.debug( 'Test connection failed; not using streaming'); goog.net.BrowserChannel.notifyStatEvent( goog.net.BrowserChannel.Stat.PROXY); this.channel_.testConnectionFinished(this, false); } } }; /** * Returns the last status code received for a request. * @return {number} The last status code received for a request. */ goog.net.BrowserTestChannel.prototype.getLastStatusCode = function() { return this.lastStatusCode_; }; /** * @return {boolean} Whether we should be using secondary domains when the * server instructs us to do so. */ goog.net.BrowserTestChannel.prototype.shouldUseSecondaryDomains = function() { return this.channel_.shouldUseSecondaryDomains(); }; /** * Gets whether this channel is currently active. This is used to determine the * length of time to wait before retrying. * * @param {goog.net.BrowserChannel} browserChannel The browser channel. * @return {boolean} Whether the channel is currently active. */ goog.net.BrowserTestChannel.prototype.isActive = function(browserChannel) { return this.channel_.isActive(); }; /** * @return {boolean} True if test stage 2 detected a non-buffered * channel early and early no buffering detection is enabled. * @private */ goog.net.BrowserTestChannel.prototype.checkForEarlyNonBuffered_ = function() { var ms = this.firstTime_ - this.startTime_; // we always get Trident responses in separate calls to // onRequestData, so we have to check the time that the first came in // and verify that the data arrived before the second portion could // have been sent. For all other browser's we skip the timing test. return goog.net.ChannelRequest.supportsXhrStreaming() || ms < goog.net.BrowserTestChannel.MIN_TIME_EXPECTED_BETWEEN_DATA_; }; /** * Notifies the channel of a fine grained network event. * @param {goog.net.BrowserChannel.ServerReachability} reachabilityType The * reachability event type. */ goog.net.BrowserTestChannel.prototype.notifyServerReachabilityEvent = function(reachabilityType) { this.channel_.notifyServerReachabilityEvent(reachabilityType); };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Wrapper class for handling XmlHttpRequests. * * One off requests can be sent through goog.net.XhrIo.send() or an * instance can be created to send multiple requests. Each request uses its * own XmlHttpRequest object and handles clearing of the event callback to * ensure no leaks. * * XhrIo is event based, it dispatches events when a request finishes, fails or * succeeds or when the ready-state changes. The ready-state or timeout event * fires first, followed by a generic completed event. Then the abort, error, * or success event is fired as appropriate. Lastly, the ready event will fire * to indicate that the object may be used to make another request. * * The error event may also be called before completed and * ready-state-change if the XmlHttpRequest.open() or .send() methods throw. * * This class does not support multiple requests, queuing, or prioritization. * * Tested = IE6, FF1.5, Safari, Opera 8.5 * * TODO(user): Error cases aren't playing nicely in Safari. * */ goog.provide('goog.net.XhrIo'); goog.provide('goog.net.XhrIo.ResponseType'); goog.require('goog.Timer'); goog.require('goog.array'); goog.require('goog.debug.Logger'); goog.require('goog.debug.entryPointRegistry'); goog.require('goog.events'); goog.require('goog.events.EventTarget'); goog.require('goog.json'); goog.require('goog.net.ErrorCode'); goog.require('goog.net.EventType'); goog.require('goog.net.HttpStatus'); goog.require('goog.net.XmlHttp'); goog.require('goog.object'); goog.require('goog.structs'); goog.require('goog.structs.Map'); goog.require('goog.uri.utils'); /** * Basic class for handling XMLHttpRequests. * @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when * creating XMLHttpRequest objects. * @constructor * @extends {goog.events.EventTarget} */ goog.net.XhrIo = function(opt_xmlHttpFactory) { goog.events.EventTarget.call(this); /** * Map of default headers to add to every request, use: * XhrIo.headers.set(name, value) * @type {goog.structs.Map} */ this.headers = new goog.structs.Map(); /** * Optional XmlHttpFactory * @type {goog.net.XmlHttpFactory} * @private */ this.xmlHttpFactory_ = opt_xmlHttpFactory || null; }; goog.inherits(goog.net.XhrIo, goog.events.EventTarget); /** * Response types that may be requested for XMLHttpRequests. * @enum {string} * @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute */ goog.net.XhrIo.ResponseType = { DEFAULT: '', TEXT: 'text', DOCUMENT: 'document', // Not supported as of Chrome 10.0.612.1 dev BLOB: 'blob', ARRAY_BUFFER: 'arraybuffer' }; /** * A reference to the XhrIo logger * @type {goog.debug.Logger} * @private */ goog.net.XhrIo.prototype.logger_ = goog.debug.Logger.getLogger('goog.net.XhrIo'); /** * The Content-Type HTTP header name * @type {string} */ goog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type'; /** * The pattern matching the 'http' and 'https' URI schemes * @type {!RegExp} */ goog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i; /** * The Content-Type HTTP header value for a url-encoded form * @type {string} */ goog.net.XhrIo.FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded;charset=utf-8'; /** * All non-disposed instances of goog.net.XhrIo created * by {@link goog.net.XhrIo.send} are in this Array. * @see goog.net.XhrIo.cleanup * @type {Array.<goog.net.XhrIo>} * @private */ goog.net.XhrIo.sendInstances_ = []; /** * Static send that creates a short lived instance of XhrIo to send the * request. * @see goog.net.XhrIo.cleanup * @param {string|goog.Uri} url Uri to make request to. * @param {Function=} opt_callback Callback function for when request is * complete. * @param {string=} opt_method Send method, default: GET. * @param {ArrayBuffer|Blob|Document|FormData|GearsBlob|string=} opt_content * Post data. This can be a Gears blob if the underlying HTTP request object * is a Gears HTTP request. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the * request. * @param {number=} opt_timeoutInterval Number of milliseconds after which an * incomplete request will be aborted; 0 means no timeout is set. * @param {boolean=} opt_withCredentials Whether to send credentials with the * request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}. */ goog.net.XhrIo.send = function(url, opt_callback, opt_method, opt_content, opt_headers, opt_timeoutInterval, opt_withCredentials) { var x = new goog.net.XhrIo(); goog.net.XhrIo.sendInstances_.push(x); if (opt_callback) { goog.events.listen(x, goog.net.EventType.COMPLETE, opt_callback); } goog.events.listen(x, goog.net.EventType.READY, goog.partial(goog.net.XhrIo.cleanupSend_, x)); if (opt_timeoutInterval) { x.setTimeoutInterval(opt_timeoutInterval); } if (opt_withCredentials) { x.setWithCredentials(opt_withCredentials); } x.send(url, opt_method, opt_content, opt_headers); }; /** * Disposes all non-disposed instances of goog.net.XhrIo created by * {@link goog.net.XhrIo.send}. * {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance * it creates when the request completes or fails. However, if * the request never completes, then the goog.net.XhrIo is not disposed. * This can occur if the window is unloaded before the request completes. * We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo * it creates and make the client of {@link goog.net.XhrIo.send} be * responsible for disposing it in this case. However, this makes things * significantly more complicated for the client, and the whole point * of {@link goog.net.XhrIo.send} is that it's simple and easy to use. * Clients of {@link goog.net.XhrIo.send} should call * {@link goog.net.XhrIo.cleanup} when doing final * cleanup on window unload. */ goog.net.XhrIo.cleanup = function() { var instances = goog.net.XhrIo.sendInstances_; while (instances.length) { instances.pop().dispose(); } }; /** * Installs exception protection for all entry point introduced by * goog.net.XhrIo instances which are not protected by * {@link goog.debug.ErrorHandler#protectWindowSetTimeout}, * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or * {@link goog.events.protectBrowserEventEntryPoint}. * * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to * protect the entry point(s). */ goog.net.XhrIo.protectEntryPoints = function(errorHandler) { goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = errorHandler.protectEntryPoint( goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_); }; /** * Disposes of the specified goog.net.XhrIo created by * {@link goog.net.XhrIo.send} and removes it from * {@link goog.net.XhrIo.pendingStaticSendInstances_}. * @param {goog.net.XhrIo} XhrIo An XhrIo created by * {@link goog.net.XhrIo.send}. * @private */ goog.net.XhrIo.cleanupSend_ = function(XhrIo) { XhrIo.dispose(); goog.array.remove(goog.net.XhrIo.sendInstances_, XhrIo); }; /** * Whether XMLHttpRequest is active. A request is active from the time send() * is called until onReadyStateChange() is complete, or error() or abort() * is called. * @type {boolean} * @private */ goog.net.XhrIo.prototype.active_ = false; /** * Reference to an XMLHttpRequest object that is being used for the transfer. * @type {XMLHttpRequest|GearsHttpRequest} * @private */ goog.net.XhrIo.prototype.xhr_ = null; /** * The options to use with the current XMLHttpRequest object. * @type {Object} * @private */ goog.net.XhrIo.prototype.xhrOptions_ = null; /** * Last URL that was requested. * @type {string|goog.Uri} * @private */ goog.net.XhrIo.prototype.lastUri_ = ''; /** * Method for the last request. * @type {string} * @private */ goog.net.XhrIo.prototype.lastMethod_ = ''; /** * Last error code. * @type {goog.net.ErrorCode} * @private */ goog.net.XhrIo.prototype.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; /** * Last error message. * @type {Error|string} * @private */ goog.net.XhrIo.prototype.lastError_ = ''; /** * This is used to ensure that we don't dispatch an multiple ERROR events. This * can happen in IE when it does a synchronous load and one error is handled in * the ready statte change and one is handled due to send() throwing an * exception. * @type {boolean} * @private */ goog.net.XhrIo.prototype.errorDispatched_ = false; /** * Used to make sure we don't fire the complete event from inside a send call. * @type {boolean} * @private */ goog.net.XhrIo.prototype.inSend_ = false; /** * Used in determining if a call to {@link #onReadyStateChange_} is from within * a call to this.xhr_.open. * @type {boolean} * @private */ goog.net.XhrIo.prototype.inOpen_ = false; /** * Used in determining if a call to {@link #onReadyStateChange_} is from within * a call to this.xhr_.abort. * @type {boolean} * @private */ goog.net.XhrIo.prototype.inAbort_ = false; /** * Number of milliseconds after which an incomplete request will be aborted and * a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout is set. * @type {number} * @private */ goog.net.XhrIo.prototype.timeoutInterval_ = 0; /** * Window timeout ID used to cancel the timeout event handler if the request * completes successfully. * @type {Object} * @private */ goog.net.XhrIo.prototype.timeoutId_ = null; /** * The requested type for the response. The empty string means use the default * XHR behavior. * @type {goog.net.XhrIo.ResponseType} * @private */ goog.net.XhrIo.prototype.responseType_ = goog.net.XhrIo.ResponseType.DEFAULT; /** * Whether a "credentialed" request is to be sent (one that is aware of cookies * and authentication) . This is applicable only for cross-domain requests and * more recent browsers that support this part of the HTTP Access Control * standard. * * @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute * * @type {boolean} * @private */ goog.net.XhrIo.prototype.withCredentials_ = false; /** * Returns the number of milliseconds after which an incomplete request will be * aborted, or 0 if no timeout is set. * @return {number} Timeout interval in milliseconds. */ goog.net.XhrIo.prototype.getTimeoutInterval = function() { return this.timeoutInterval_; }; /** * Sets the number of milliseconds after which an incomplete request will be * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no * timeout is set. * @param {number} ms Timeout interval in milliseconds; 0 means none. */ goog.net.XhrIo.prototype.setTimeoutInterval = function(ms) { this.timeoutInterval_ = Math.max(0, ms); }; /** * Sets the desired type for the response. At time of writing, this is only * supported in very recent versions of WebKit (10.0.612.1 dev and later). * * If this is used, the response may only be accessed via {@link #getResponse}. * * @param {goog.net.XhrIo.ResponseType} type The desired type for the response. */ goog.net.XhrIo.prototype.setResponseType = function(type) { this.responseType_ = type; }; /** * Gets the desired type for the response. * @return {goog.net.XhrIo.ResponseType} The desired type for the response. */ goog.net.XhrIo.prototype.getResponseType = function() { return this.responseType_; }; /** * Sets whether a "credentialed" request that is aware of cookie and * authentication information should be made. This option is only supported by * browsers that support HTTP Access Control. As of this writing, this option * is not supported in IE. * * @param {boolean} withCredentials Whether this should be a "credentialed" * request. */ goog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) { this.withCredentials_ = withCredentials; }; /** * Gets whether a "credentialed" request is to be sent. * @return {boolean} The desired type for the response. */ goog.net.XhrIo.prototype.getWithCredentials = function() { return this.withCredentials_; }; /** * Instance send that actually uses XMLHttpRequest to make a server call. * @param {string|goog.Uri} url Uri to make request to. * @param {string=} opt_method Send method, default: GET. * @param {ArrayBuffer|Blob|Document|FormData|GearsBlob|string=} opt_content * Post data. This can be a Gears blob if the underlying HTTP request object * is a Gears HTTP request. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the * request. */ goog.net.XhrIo.prototype.send = function(url, opt_method, opt_content, opt_headers) { if (this.xhr_) { throw Error('[goog.net.XhrIo] Object is active with another request=' + this.lastUri_ + '; newUri=' + url); } var method = opt_method ? opt_method.toUpperCase() : 'GET'; this.lastUri_ = url; this.lastError_ = ''; this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR; this.lastMethod_ = method; this.errorDispatched_ = false; this.active_ = true; // Use the factory to create the XHR object and options this.xhr_ = this.createXhr(); this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() : goog.net.XmlHttp.getOptions(); // Set up the onreadystatechange callback this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this); /** * Try to open the XMLHttpRequest (always async), if an error occurs here it * is generally permission denied * @preserveTry */ try { this.logger_.fine(this.formatMsg_('Opening Xhr')); this.inOpen_ = true; this.xhr_.open(method, url, true); // Always async! this.inOpen_ = false; } catch (err) { this.logger_.fine(this.formatMsg_('Error opening Xhr: ' + err.message)); this.error_(goog.net.ErrorCode.EXCEPTION, err); return; } // We can't use null since this won't allow POSTs to have a content length // specified which will cause some proxies to return a 411 error. var content = opt_content || ''; var headers = this.headers.clone(); // Add headers specific to this request if (opt_headers) { goog.structs.forEach(opt_headers, function(value, key) { headers.set(key, value); }); } // Find whether a content type header is set, ignoring case. // HTTP header names are case-insensitive. See: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 var contentTypeKey = goog.array.find(headers.getKeys(), goog.net.XhrIo.isContentTypeHeader_); var contentIsFormData = (goog.global['FormData'] && (content instanceof goog.global['FormData'])); if (method == 'POST' && !contentTypeKey && !contentIsFormData) { // For POST requests, default to the url-encoded form content type // unless this is a FormData request. For FormData, the browser will // automatically add a multipart/form-data content type with an appropriate // multipart boundary. headers.set(goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE); } // Add the headers to the Xhr object goog.structs.forEach(headers, function(value, key) { this.xhr_.setRequestHeader(key, value); }, this); if (this.responseType_) { this.xhr_.responseType = this.responseType_; } if (goog.object.containsKey(this.xhr_, 'withCredentials')) { this.xhr_.withCredentials = this.withCredentials_; } /** * Try to send the request, or other wise report an error (404 not found). * @preserveTry */ try { if (this.timeoutId_) { // This should never happen, since the if (this.active_) above shouldn't // let execution reach this point if there is a request in progress... goog.Timer.defaultTimerObject.clearTimeout(this.timeoutId_); this.timeoutId_ = null; } if (this.timeoutInterval_ > 0) { this.logger_.fine(this.formatMsg_('Will abort after ' + this.timeoutInterval_ + 'ms if incomplete')); this.timeoutId_ = goog.Timer.defaultTimerObject.setTimeout( goog.bind(this.timeout_, this), this.timeoutInterval_); } this.logger_.fine(this.formatMsg_('Sending request')); this.inSend_ = true; this.xhr_.send(content); this.inSend_ = false; } catch (err) { this.logger_.fine(this.formatMsg_('Send error: ' + err.message)); this.error_(goog.net.ErrorCode.EXCEPTION, err); } }; /** * @param {string} header An HTTP header key. * @return {boolean} Whether the key is a content type header (ignoring * case. * @private */ goog.net.XhrIo.isContentTypeHeader_ = function(header) { return goog.string.caseInsensitiveEquals( goog.net.XhrIo.CONTENT_TYPE_HEADER, header); }; /** * Creates a new XHR object. * @return {XMLHttpRequest|GearsHttpRequest} The newly created XHR object. * @protected */ goog.net.XhrIo.prototype.createXhr = function() { return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() : goog.net.XmlHttp(); }; /** * The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_} * milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts * the request. * @private */ goog.net.XhrIo.prototype.timeout_ = function() { if (typeof goog == 'undefined') { // If goog is undefined then the callback has occurred as the application // is unloading and will error. Thus we let it silently fail. } else if (this.xhr_) { this.lastError_ = 'Timed out after ' + this.timeoutInterval_ + 'ms, aborting'; this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT; this.logger_.fine(this.formatMsg_(this.lastError_)); this.dispatchEvent(goog.net.EventType.TIMEOUT); this.abort(goog.net.ErrorCode.TIMEOUT); } }; /** * Something errorred, so inactivate, fire error callback and clean up * @param {goog.net.ErrorCode} errorCode The error code. * @param {Error} err The error object. * @private */ goog.net.XhrIo.prototype.error_ = function(errorCode, err) { this.active_ = false; if (this.xhr_) { this.inAbort_ = true; this.xhr_.abort(); // Ensures XHR isn't hung (FF) this.inAbort_ = false; } this.lastError_ = err; this.lastErrorCode_ = errorCode; this.dispatchErrors_(); this.cleanUpXhr_(); }; /** * Dispatches COMPLETE and ERROR in case of an error. This ensures that we do * not dispatch multiple error events. * @private */ goog.net.XhrIo.prototype.dispatchErrors_ = function() { if (!this.errorDispatched_) { this.errorDispatched_ = true; this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.ERROR); } }; /** * Abort the current XMLHttpRequest * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use - * defaults to ABORT. */ goog.net.XhrIo.prototype.abort = function(opt_failureCode) { if (this.xhr_ && this.active_) { this.logger_.fine(this.formatMsg_('Aborting')); this.active_ = false; this.inAbort_ = true; this.xhr_.abort(); this.inAbort_ = false; this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT; this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.ABORT); this.cleanUpXhr_(); } }; /** * Nullifies all callbacks to reduce risks of leaks. * @override * @protected */ goog.net.XhrIo.prototype.disposeInternal = function() { if (this.xhr_) { // We explicitly do not call xhr_.abort() unless active_ is still true. // This is to avoid unnecessarily aborting a successful request when // dispose() is called in a callback triggered by a complete response, but // in which browser cleanup has not yet finished. // (See http://b/issue?id=1684217.) if (this.active_) { this.active_ = false; this.inAbort_ = true; this.xhr_.abort(); this.inAbort_ = false; } this.cleanUpXhr_(true); } goog.net.XhrIo.superClass_.disposeInternal.call(this); }; /** * Internal handler for the XHR object's readystatechange event. This method * checks the status and the readystate and fires the correct callbacks. * If the request has ended, the handlers are cleaned up and the XHR object is * nullified. * @private */ goog.net.XhrIo.prototype.onReadyStateChange_ = function() { if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) { // Were not being called from within a call to this.xhr_.send // this.xhr_.abort, or this.xhr_.open, so this is an entry point this.onReadyStateChangeEntryPoint_(); } else { this.onReadyStateChangeHelper_(); } }; /** * Used to protect the onreadystatechange handler entry point. Necessary * as {#onReadyStateChange_} maybe called from within send or abort, this * method is only called when {#onReadyStateChange_} is called as an * entry point. * {@see #protectEntryPoints} * @private */ goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() { this.onReadyStateChangeHelper_(); }; /** * Helper for {@link #onReadyStateChange_}. This is used so that * entry point calls to {@link #onReadyStateChange_} can be routed through * {@link #onReadyStateChangeEntryPoint_}. * @private */ goog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() { if (!this.active_) { // can get called inside abort call return; } if (typeof goog == 'undefined') { // NOTE(user): If goog is undefined then the callback has occurred as the // application is unloading and will error. Thus we let it silently fail. } else if ( this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] && this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE && this.getStatus() == 2) { // NOTE(user): In IE if send() errors on a *local* request the readystate // is still changed to COMPLETE. We need to ignore it and allow the // try/catch around send() to pick up the error. this.logger_.fine(this.formatMsg_( 'Local request error detected and ignored')); } else { // In IE when the response has been cached we sometimes get the callback // from inside the send call and this usually breaks code that assumes that // XhrIo is asynchronous. If that is the case we delay the callback // using a timer. if (this.inSend_ && this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) { goog.Timer.defaultTimerObject.setTimeout( goog.bind(this.onReadyStateChange_, this), 0); return; } this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE); // readyState indicates the transfer has finished if (this.isComplete()) { this.logger_.fine(this.formatMsg_('Request complete')); this.active_ = false; try { // Call the specific callbacks for success or failure. Only call the // success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED) if (this.isSuccess()) { this.dispatchEvent(goog.net.EventType.COMPLETE); this.dispatchEvent(goog.net.EventType.SUCCESS); } else { this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR; this.lastError_ = this.getStatusText() + ' [' + this.getStatus() + ']'; this.dispatchErrors_(); } } finally { this.cleanUpXhr_(); } } } }; /** * Remove the listener to protect against leaks, and nullify the XMLHttpRequest * object. * @param {boolean=} opt_fromDispose If this is from the dispose (don't want to * fire any events). * @private */ goog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) { if (this.xhr_) { // Save reference so we can mark it as closed after the READY event. The // READY event may trigger another request, thus we must nullify this.xhr_ var xhr = this.xhr_; var clearedOnReadyStateChange = this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ? goog.nullFunction : null; this.xhr_ = null; this.xhrOptions_ = null; if (this.timeoutId_) { // Cancel any pending timeout event handler. goog.Timer.defaultTimerObject.clearTimeout(this.timeoutId_); this.timeoutId_ = null; } if (!opt_fromDispose) { this.dispatchEvent(goog.net.EventType.READY); } try { // NOTE(user): Not nullifying in FireFox can still leak if the callbacks // are defined in the same scope as the instance of XhrIo. But, IE doesn't // allow you to set the onreadystatechange to NULL so nullFunction is // used. xhr.onreadystatechange = clearedOnReadyStateChange; } catch (e) { // This seems to occur with a Gears HTTP request. Delayed the setting of // this onreadystatechange until after READY is sent out and catching the // error to see if we can track down the problem. this.logger_.severe('Problem encountered resetting onreadystatechange: ' + e.message); } } }; /** * @return {boolean} Whether there is an active request. */ goog.net.XhrIo.prototype.isActive = function() { return !!this.xhr_; }; /** * @return {boolean} Whether the request has completed. */ goog.net.XhrIo.prototype.isComplete = function() { return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE; }; /** * @return {boolean} Whether the request completed with a success. */ goog.net.XhrIo.prototype.isSuccess = function() { var status = this.getStatus(); // A zero status code is considered successful for local files. return goog.net.HttpStatus.isSuccess(status) || status === 0 && !this.isLastUriEffectiveSchemeHttp_(); }; /** * @return {boolean} whether the effective scheme of the last URI that was * fetched was 'http' or 'https'. * @private */ goog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() { var scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_)); return goog.net.XhrIo.HTTP_SCHEME_PATTERN.test(scheme); }; /** * Get the readystate from the Xhr object * Will only return correct result when called from the context of a callback * @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*. */ goog.net.XhrIo.prototype.getReadyState = function() { return this.xhr_ ? /** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) : goog.net.XmlHttp.ReadyState.UNINITIALIZED; }; /** * Get the status from the Xhr object * Will only return correct result when called from the context of a callback * @return {number} Http status. */ goog.net.XhrIo.prototype.getStatus = function() { /** * IE doesn't like you checking status until the readystate is greater than 2 * (i.e. it is recieving or complete). The try/catch is used for when the * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_. * @preserveTry */ try { return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ? this.xhr_.status : -1; } catch (e) { this.logger_.warning('Can not get status: ' + e.message); return -1; } }; /** * Get the status text from the Xhr object * Will only return correct result when called from the context of a callback * @return {string} Status text. */ goog.net.XhrIo.prototype.getStatusText = function() { /** * IE doesn't like you checking status until the readystate is greater than 2 * (i.e. it is recieving or complete). The try/catch is used for when the * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_. * @preserveTry */ try { return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ? this.xhr_.statusText : ''; } catch (e) { this.logger_.fine('Can not get status: ' + e.message); return ''; } }; /** * Get the last Uri that was requested * @return {string} Last Uri. */ goog.net.XhrIo.prototype.getLastUri = function() { return String(this.lastUri_); }; /** * Get the response text from the Xhr object * Will only return correct result when called from the context of a callback. * @return {string} Result from the server, or '' if no result available. */ goog.net.XhrIo.prototype.getResponseText = function() { /** @preserveTry */ try { return this.xhr_ ? this.xhr_.responseText : ''; } catch (e) { // http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute // states that responseText should return '' (and responseXML null) // when the state is not LOADING or DONE. Instead, IE and Gears can // throw unexpected exceptions, for example when a request is aborted // or no data is available yet. this.logger_.fine('Can not get responseText: ' + e.message); return ''; } }; /** * Get the response body from the Xhr object. This property is only available * in IE since version 7 according to MSDN: * http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx * Will only return correct result when called from the context of a callback. * * One option is to construct a VBArray from the returned object and convert * it to a JavaScript array using the toArray method: * {@code (new window['VBArray'](xhrIo.getResponseBody())).toArray()} * This will result in an array of numbers in the range of [0..255] * * Another option is to use the VBScript CStr method to convert it into a * string as outlined in http://stackoverflow.com/questions/1919972 * * @return {Object} Binary result from the server or null if not available. */ goog.net.XhrIo.prototype.getResponseBody = function() { /** @preserveTry */ try { if (this.xhr_ && 'responseBody' in this.xhr_) { return this.xhr_['responseBody']; } } catch (e) { // IE can throw unexpected exceptions, for example when a request is aborted // or no data is yet available. this.logger_.fine('Can not get responseBody: ' + e.message); } return null; }; /** * Get the response XML from the Xhr object * Will only return correct result when called from the context of a callback. * @return {Document} The DOM Document representing the XML file, or null * if no result available. */ goog.net.XhrIo.prototype.getResponseXml = function() { /** @preserveTry */ try { return this.xhr_ ? this.xhr_.responseXML : null; } catch (e) { this.logger_.fine('Can not get responseXML: ' + e.message); return null; } }; /** * Get the response and evaluates it as JSON from the Xhr object * Will only return correct result when called from the context of a callback * @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for * stripping of the response before parsing. This needs to be set only if * your backend server prepends the same prefix string to the JSON response. * @return {Object|undefined} JavaScript object. */ goog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) { if (!this.xhr_) { return undefined; } var responseText = this.xhr_.responseText; if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) { responseText = responseText.substring(opt_xssiPrefix.length); } return goog.json.parse(responseText); }; /** * Get the response as the type specificed by {@link #setResponseType}. At time * of writing, this is only directly supported in very recent versions of WebKit * (10.0.612.1 dev and later). If the field is not supported directly, we will * try to emulate it. * * Emulating the response means following the rules laid out at * http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute * * On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only * response types of DEFAULT or TEXT may be used, and the response returned will * be the text response. * * On browsers with Mozilla's draft support for array buffers (Firefox 4, 5), * only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the * response returned will be either the text response or the Mozilla * implementation of the array buffer response. * * On browsers will full support, any valid response type supported by the * browser may be used, and the response provided by the browser will be * returned. * * @return {*} The response. */ goog.net.XhrIo.prototype.getResponse = function() { /** @preserveTry */ try { if (!this.xhr_) { return null; } if ('response' in this.xhr_) { return this.xhr_.response; } switch (this.responseType_) { case goog.net.XhrIo.ResponseType.DEFAULT: case goog.net.XhrIo.ResponseType.TEXT: return this.xhr_.responseText; // DOCUMENT and BLOB don't need to be handled here because they are // introduced in the same spec that adds the .response field, and would // have been caught above. // ARRAY_BUFFER needs an implementation for Firefox 4, where it was // implemented using a draft spec rather than the final spec. case goog.net.XhrIo.ResponseType.ARRAY_BUFFER: if ('mozResponseArrayBuffer' in this.xhr_) { return this.xhr_.mozResponseArrayBuffer; } } // Fell through to a response type that is not supported on this browser. this.logger_.severe('Response type ' + this.responseType_ + ' is not ' + 'supported on this browser'); return null; } catch (e) { this.logger_.fine('Can not get response: ' + e.message); return null; } }; /** * Get the value of the response-header with the given name from the Xhr object * Will only return correct result when called from the context of a callback * and the request has completed * @param {string} key The name of the response-header to retrieve. * @return {string|undefined} The value of the response-header named key. */ goog.net.XhrIo.prototype.getResponseHeader = function(key) { return this.xhr_ && this.isComplete() ? this.xhr_.getResponseHeader(key) : undefined; }; /** * Gets the text of all the headers in the response. * Will only return correct result when called from the context of a callback * and the request has completed. * @return {string} The value of the response headers or empty string. */ goog.net.XhrIo.prototype.getAllResponseHeaders = function() { return this.xhr_ && this.isComplete() ? this.xhr_.getAllResponseHeaders() : ''; }; /** * Get the last error message * @return {goog.net.ErrorCode} Last error code. */ goog.net.XhrIo.prototype.getLastErrorCode = function() { return this.lastErrorCode_; }; /** * Get the last error message * @return {string} Last error message. */ goog.net.XhrIo.prototype.getLastError = function() { return goog.isString(this.lastError_) ? this.lastError_ : String(this.lastError_); }; /** * Adds the last method, status and URI to the message. This is used to add * this information to the logging calls. * @param {string} msg The message text that we want to add the extra text to. * @return {string} The message with the extra text appended. * @private */ goog.net.XhrIo.prototype.formatMsg_ = function(msg) { return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' + this.getStatus() + ']'; }; // Register the xhr handler as an entry point, so that // it can be monitored for exception handling, etc. goog.debug.entryPointRegistry.register( /** * @param {function(!Function): !Function} transformer The transforming * function. */ function(transformer) { goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_); });
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A class for downloading remote files and storing them * locally using the HTML5 FileSystem API. * * The directory structure is of the form /HASH/URL/BASENAME: * * The HASH portion is a three-character slice of the hash of the URL. Since the * filesystem has a limit of about 5000 files per directory, this should divide * the downloads roughly evenly among about 5000 directories, thus allowing for * at most 5000^2 downloads. * * The URL portion is the (sanitized) full URL used for downloading the file. * This is used to ensure that each file ends up in a different location, even * if the HASH and BASENAME are the same. * * The BASENAME portion is the basename of the URL. It's used for the filename * proper so that the local filesystem: URL will be downloaded to a file with a * recognizable name. * */ goog.provide('goog.net.FileDownloader'); goog.provide('goog.net.FileDownloader.Error'); goog.require('goog.Disposable'); goog.require('goog.asserts'); goog.require('goog.async.Deferred'); goog.require('goog.crypt.hash32'); goog.require('goog.debug.Error'); goog.require('goog.events.EventHandler'); goog.require('goog.fs'); goog.require('goog.fs.DirectoryEntry.Behavior'); goog.require('goog.fs.Error.ErrorCode'); goog.require('goog.fs.FileSaver.EventType'); goog.require('goog.net.EventType'); goog.require('goog.net.XhrIo.ResponseType'); goog.require('goog.net.XhrIoPool'); /** * A class for downloading remote files and storing them locally using the * HTML5 filesystem API. * * @param {!goog.fs.DirectoryEntry} dir The directory in which the downloaded * files are stored. This directory should be solely managed by * FileDownloader. * @param {goog.net.XhrIoPool=} opt_pool The pool of XhrIo objects to use for * downloading files. * @constructor * @extends {goog.Disposable} */ goog.net.FileDownloader = function(dir, opt_pool) { goog.base(this); /** * The directory in which the downloaded files are stored. * @type {!goog.fs.DirectoryEntry} * @private */ this.dir_ = dir; /** * The pool of XHRs to use for capturing. * @type {!goog.net.XhrIoPool} * @private */ this.pool_ = opt_pool || new goog.net.XhrIoPool(); /** * A map from URLs to active downloads running for those URLs. * @type {!Object.<!goog.net.FileDownloader.Download_>} * @private */ this.downloads_ = {}; /** * The handler for URL capturing events. * @type {!goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); }; goog.inherits(goog.net.FileDownloader, goog.Disposable); /** * Download a remote file and save its contents to the filesystem. A given file * is uniquely identified by its URL string; this means that the relative and * absolute URLs for a single file are considered different for the purposes of * the FileDownloader. * * Returns a Deferred that will contain the downloaded blob. If there's an error * while downloading the URL, this Deferred will be passed the * {@link goog.net.FileDownloader.Error} object as an errback. * * If a download is already in progress for the given URL, this will return the * deferred blob for that download. If the URL has already been downloaded, this * will fail once it tries to save the downloaded blob. * * When a download is in progress, all Deferreds returned for that download will * be branches of a single parent. If all such branches are cancelled, or if one * is cancelled with opt_deepCancel set, then the download will be cancelled as * well. * * @param {string} url The URL of the file to download. * @return {!goog.async.Deferred} The deferred result blob. */ goog.net.FileDownloader.prototype.download = function(url) { if (this.isDownloading(url)) { return this.downloads_[url].deferred.branch(true /* opt_propagateCancel */); } var download = new goog.net.FileDownloader.Download_(url, this); this.downloads_[url] = download; this.pool_.getObject(goog.bind(this.gotXhr_, this, download)); return download.deferred.branch(true /* opt_propagateCancel */); }; /** * Return a Deferred that will fire once no download is active for a given URL. * If there's no download active for that URL when this is called, the deferred * will fire immediately; otherwise, it will fire once the download is complete, * whether or not it succeeds. * * @param {string} url The URL of the download to wait for. * @return {!goog.async.Deferred} The Deferred that will fire when the download * is complete. */ goog.net.FileDownloader.prototype.waitForDownload = function(url) { var deferred = new goog.async.Deferred(); if (this.isDownloading(url)) { this.downloads_[url].deferred.addBoth(function() { deferred.callback(null); }, this); } else { deferred.callback(null); } return deferred; }; /** * Returns whether or not there is an active download for a given URL. * * @param {string} url The URL of the download to check. * @return {boolean} Whether or not there is an active download for the URL. */ goog.net.FileDownloader.prototype.isDownloading = function(url) { return url in this.downloads_; }; /** * Load a downloaded blob from the filesystem. Will fire a deferred error if the * given URL has not yet been downloaded. * * @param {string} url The URL of the blob to load. * @return {!goog.async.Deferred} The deferred Blob object. The callback will be * passed the blob. If a file API error occurs while loading the blob, that * error will be passed to the errback. */ goog.net.FileDownloader.prototype.getDownloadedBlob = function(url) { return this.getFile_(url). addCallback(function(fileEntry) { return fileEntry.file(); }); }; /** * Get the local filesystem: URL for a downloaded file. This is different from * the blob: URL that's available from getDownloadedBlob(). If the end user * accesses the filesystem: URL, the resulting file's name will be determined by * the download filename as opposed to an arbitrary GUID. In addition, the * filesystem: URL is connected to a filesystem location, so if the download is * removed then that URL will become invalid. * * Warning: in Chrome 12, some filesystem: URLs are opened inline. This means * that e.g. HTML pages given to the user via filesystem: URLs will be opened * and processed by the browser. * * @param {string} url The URL of the file to get the URL of. * @return {!goog.async.Deferred} The deferred filesystem: URL. The callback * will be passed the URL. If a file API error occurs while loading the * blob, that error will be passed to the errback. */ goog.net.FileDownloader.prototype.getLocalUrl = function(url) { return this.getFile_(url). addCallback(function(fileEntry) { return fileEntry.toUrl(); }); }; /** * Return (deferred) whether or not a URL has been downloaded. Will fire a * deferred error if something goes wrong when determining this. * * @param {string} url The URL to check. * @return {!goog.async.Deferred} The deferred boolean. The callback will be * passed the boolean. If a file API error occurs while checking the * existence of the downloaded URL, that error will be passed to the * errback. */ goog.net.FileDownloader.prototype.isDownloaded = function(url) { var deferred = new goog.async.Deferred(); var blobDeferred = this.getDownloadedBlob(url); blobDeferred.addCallback(function() { deferred.callback(true); }); blobDeferred.addErrback(function(err) { if (err.code == goog.fs.Error.ErrorCode.NOT_FOUND) { deferred.callback(false); } else { deferred.errback(err); } }); return deferred; }; /** * Remove a URL from the FileDownloader. * * This returns a Deferred. If the removal is completed successfully, its * callback will be called without any value. If the removal fails, its errback * will be called with the {@link goog.fs.Error}. * * @param {string} url The URL to remove. * @return {!goog.async.Deferred} The deferred used for registering callbacks on * success or on error. */ goog.net.FileDownloader.prototype.remove = function(url) { return this.getDir_(url, goog.fs.DirectoryEntry.Behavior.DEFAULT). addCallback(function(dir) { return dir.removeRecursively(); }); }; /** * Save a blob for a given URL. This works just as through the blob were * downloaded form that URL, except you specify the blob and no HTTP request is * made. * * If the URL is currently being downloaded, it's indeterminate whether the blob * being set or the blob being downloaded will end up in the filesystem. * Whichever one doesn't get saved will have an error. To ensure that one or the * other takes precedence, use {@link #waitForDownload} to allow the download to * complete before setting the blob. * * @param {string} url The URL at which to set the blob. * @param {!Blob} blob The blob to set. * @param {string=} opt_name The name of the file. If this isn't given, it's * determined from the URL. * @return {!goog.async.Deferred} The deferred used for registering callbacks on * success or on error. This can be cancelled just like a {@link #download} * Deferred. The objects passed to the errback will be * {@link goog.net.FileDownloader.Error}s. */ goog.net.FileDownloader.prototype.setBlob = function(url, blob, opt_name) { var name = this.sanitize_(opt_name || this.urlToName_(url)); var download = new goog.net.FileDownloader.Download_(url, this); this.downloads_[url] = download; download.blob = blob; this.getDir_(download.url, goog.fs.DirectoryEntry.Behavior.CREATE_EXCLUSIVE). addCallback(function(dir) { return dir.getFile( name, goog.fs.DirectoryEntry.Behavior.CREATE_EXCLUSIVE); }). addCallback(goog.bind(this.fileSuccess_, this, download)). addErrback(goog.bind(this.error_, this, download)); return download.deferred.branch(true /* opt_propagateCancel */); }; /** * The callback called when an XHR becomes available from the XHR pool. * * @param {!goog.net.FileDownloader.Download_} download The download object for * this download. * @param {!goog.net.XhrIo} xhr The XhrIo object for downloading the page. * @private */ goog.net.FileDownloader.prototype.gotXhr_ = function(download, xhr) { if (download.cancelled) { this.freeXhr_(xhr); return; } this.eventHandler_.listen( xhr, goog.net.EventType.SUCCESS, goog.bind(this.xhrSuccess_, this, download)); this.eventHandler_.listen( xhr, [goog.net.EventType.ERROR, goog.net.EventType.ABORT], goog.bind(this.error_, this, download)); this.eventHandler_.listen( xhr, goog.net.EventType.READY, goog.bind(this.freeXhr_, this, xhr)); download.xhr = xhr; xhr.setResponseType(goog.net.XhrIo.ResponseType.ARRAY_BUFFER); xhr.send(download.url); }; /** * The callback called when an XHR succeeds in downloading a remote file. * * @param {!goog.net.FileDownloader.Download_} download The download object for * this download. * @private */ goog.net.FileDownloader.prototype.xhrSuccess_ = function(download) { if (download.cancelled) { return; } var name = this.sanitize_(this.getName_( /** @type {!goog.net.XhrIo} */ (download.xhr))); var resp = /** @type {ArrayBuffer} */ (download.xhr.getResponse()); if (!resp) { // This should never happen - it indicates the XHR hasn't completed, has // failed or has been cleaned up. If it does happen (eg. due to a bug // somewhere) we don't want to pass null to getBlob - it's not valid and // triggers a bug in some versions of WebKit causing it to crash. this.error_(download); return; } download.blob = goog.fs.getBlob(resp); delete download.xhr; this.getDir_(download.url, goog.fs.DirectoryEntry.Behavior.CREATE_EXCLUSIVE). addCallback(function(dir) { return dir.getFile( name, goog.fs.DirectoryEntry.Behavior.CREATE_EXCLUSIVE); }). addCallback(goog.bind(this.fileSuccess_, this, download)). addErrback(goog.bind(this.error_, this, download)); }; /** * The callback called when a file that will be used for saving a file is * successfully opened. * * @param {!goog.net.FileDownloader.Download_} download The download object for * this download. * @param {!goog.fs.FileEntry} file The newly-opened file object. * @private */ goog.net.FileDownloader.prototype.fileSuccess_ = function(download, file) { if (download.cancelled) { file.remove(); return; } download.file = file; file.createWriter(). addCallback(goog.bind(this.fileWriterSuccess_, this, download)). addErrback(goog.bind(this.error_, this, download)); }; /** * The callback called when a file writer is succesfully created for writing a * file to the filesystem. * * @param {!goog.net.FileDownloader.Download_} download The download object for * this download. * @param {!goog.fs.FileWriter} writer The newly-created file writer object. * @private */ goog.net.FileDownloader.prototype.fileWriterSuccess_ = function( download, writer) { if (download.cancelled) { download.file.remove(); return; } download.writer = writer; writer.write(/** @type {!Blob} */ (download.blob)); this.eventHandler_.listenOnce( writer, goog.fs.FileSaver.EventType.WRITE_END, goog.bind(this.writeEnd_, this, download)); }; /** * The callback called when file writing ends, whether or not it's successful. * * @param {!goog.net.FileDownloader.Download_} download The download object for * this download. * @private */ goog.net.FileDownloader.prototype.writeEnd_ = function(download) { if (download.cancelled || download.writer.getError()) { this.error_(download, download.writer.getError()); return; } delete this.downloads_[download.url]; download.deferred.callback(download.blob); }; /** * The error callback for all asynchronous operations. Ensures that all stages * of a given download are cleaned up, and emits the error event. * * @param {!goog.net.FileDownloader.Download_} download The download object for * this download. * @param {goog.fs.Error=} opt_err The file error object. Only defined if the * error was raised by the file API. * @private */ goog.net.FileDownloader.prototype.error_ = function(download, opt_err) { if (download.file) { download.file.remove(); } if (download.cancelled) { return; } delete this.downloads_[download.url]; download.deferred.errback( new goog.net.FileDownloader.Error(download, opt_err)); }; /** * Abort the download of the given URL. * * @param {!goog.net.FileDownloader.Download_} download The download to abort. * @private */ goog.net.FileDownloader.prototype.cancel_ = function(download) { goog.dispose(download); delete this.downloads_[download.url]; }; /** * Get the directory for a given URL. If the directory already exists when this * is called, it will contain exactly one file: the downloaded file. * * This not only calls the FileSystem API's getFile method, but attempts to * distribute the files so that they don't overload the filesystem. The spec * says directories can't contain more than 5000 files * (http://www.w3.org/TR/file-system-api/#directories), so this ensures that * each file is put into a subdirectory based on its SHA1 hash. * * All parameters are the same as in the FileSystem API's Entry#getFile method. * * @param {string} url The URL corresponding to the directory to get. * @param {goog.fs.DirectoryEntry.Behavior} behavior The behavior to pass to the * underlying method. * @return {!goog.async.Deferred} The deferred DirectoryEntry object. * @private */ goog.net.FileDownloader.prototype.getDir_ = function(url, behavior) { // 3 hex digits provide 16**3 = 4096 different possible dirnames, which is // less than the maximum of 5000 entries. Downloaded files should be // distributed roughly evenly throughout the directories due to the hash // function, allowing many more than 5000 files to be downloaded. // // The leading ` ensures that no illegal dirnames are accidentally used. % was // previously used, but Chrome has a bug (as of 12.0.725.0 dev) where // filenames are URL-decoded before checking their validity, so filenames // containing e.g. '%3f' (the URL-encoding of :, an invalid character) are // rejected. var dirname = '`' + Math.abs(goog.crypt.hash32.encodeString(url)). toString(16).substring(0, 3); return this.dir_. getDirectory(dirname, goog.fs.DirectoryEntry.Behavior.CREATE). addCallback(function(dir) { return dir.getDirectory(this.sanitize_(url), behavior); }, this); }; /** * Get the file for a given URL. This will only retrieve files that have already * been saved; it shouldn't be used for creating the file in the first place. * This is because the filename isn't necessarily determined by the URL, but by * the headers of the XHR response. * * @param {string} url The URL corresponding to the file to get. * @return {!goog.async.Deferred} The deferred FileEntry object. * @private */ goog.net.FileDownloader.prototype.getFile_ = function(url) { return this.getDir_(url, goog.fs.DirectoryEntry.Behavior.DEFAULT). addCallback(function(dir) { return dir.listDirectory().addCallback(function(files) { goog.asserts.assert(files.length == 1); // If the filesystem somehow gets corrupted and we end up with an // empty directory here, it makes sense to just return the normal // file-not-found error. return files[0] || dir.getFile('file'); }); }); }; /** * Sanitize a string so it can be safely used as a file or directory name for * the FileSystem API. * * @param {string} str The string to sanitize. * @return {string} The sanitized string. * @private */ goog.net.FileDownloader.prototype.sanitize_ = function(str) { // Add a prefix, since certain prefixes are disallowed for paths. None of the // disallowed prefixes start with '`'. We use ` rather than % for escaping the // filename due to a Chrome bug (as of 12.0.725.0 dev) where filenames are // URL-decoded before checking their validity, so filenames containing e.g. // '%3f' (the URL-encoding of :, an invalid character) are rejected. return '`' + str.replace(/[\/\\<>:?*"|%`]/g, encodeURIComponent). replace(/%/g, '`'); }; /** * Gets the filename specified by the XHR. This first attempts to parse the * Content-Disposition header for a filename and, failing that, falls back on * deriving the filename from the URL. * * @param {!goog.net.XhrIo} xhr The XHR containing the response headers. * @return {string} The filename. * @private */ goog.net.FileDownloader.prototype.getName_ = function(xhr) { var disposition = xhr.getResponseHeader('Content-Disposition'); var match = disposition && disposition.match(/^attachment *; *filename="(.*)"$/i); if (match) { // The Content-Disposition header allows for arbitrary backslash-escaped // characters (usually " and \). We want to unescape them before using them // in the filename. return match[1].replace(/\\(.)/g, '$1'); } return this.urlToName_(xhr.getLastUri()); }; /** * Extracts the basename from a URL. * * @param {string} url The URL. * @return {string} The basename. * @private */ goog.net.FileDownloader.prototype.urlToName_ = function(url) { var segments = url.split('/'); return segments[segments.length - 1]; }; /** * Remove all event listeners for an XHR and release it back into the pool. * * @param {!goog.net.XhrIo} xhr The XHR to free. * @private */ goog.net.FileDownloader.prototype.freeXhr_ = function(xhr) { goog.events.removeAll(xhr); this.pool_.addFreeObject(xhr); }; /** @override */ goog.net.FileDownloader.prototype.disposeInternal = function() { delete this.dir_; goog.dispose(this.eventHandler_); delete this.eventHandler_; goog.object.forEach(this.downloads_, function(download) { download.deferred.cancel(); }, this); delete this.downloads_; goog.dispose(this.pool_); delete this.pool_; goog.base(this, 'disposeInternal'); }; /** * The error object for FileDownloader download errors. * * @param {!goog.net.FileDownloader.Download_} download The download object for * the download in question. * @param {goog.fs.Error=} opt_fsErr The file error object, if this was a file * error. * * @constructor * @extends {goog.debug.Error} */ goog.net.FileDownloader.Error = function(download, opt_fsErr) { goog.base(this, 'Error capturing URL ' + download.url); /** * The URL the event relates to. * @type {string} */ this.url = download.url; if (download.xhr) { this.xhrStatus = download.xhr.getStatus(); this.xhrErrorCode = download.xhr.getLastErrorCode(); this.message += ': XHR failed with status ' + this.xhrStatus + ' (error code ' + this.xhrErrorCode + ')'; } else if (opt_fsErr) { this.fileError = opt_fsErr; this.message += ': file API failed (' + opt_fsErr.message + ')'; } }; goog.inherits(goog.net.FileDownloader.Error, goog.debug.Error); /** * The status of the XHR. Only set if the error was caused by an XHR failure. * @type {number|undefined} */ goog.net.FileDownloader.Error.prototype.xhrStatus; /** * The error code of the XHR. Only set if the error was caused by an XHR * failure. * @type {goog.net.ErrorCode|undefined} */ goog.net.FileDownloader.Error.prototype.xhrErrorCode; /** * The file API error. Only set if the error was caused by the file API. * @type {goog.fs.Error|undefined} */ goog.net.FileDownloader.Error.prototype.fileError; /** * A struct containing the data for a single download. * * @param {string} url The URL for the file being downloaded. * @param {!goog.net.FileDownloader} downloader The parent FileDownloader. * @extends {goog.Disposable} * @constructor * @private */ goog.net.FileDownloader.Download_ = function(url, downloader) { goog.base(this); /** * The URL for the file being downloaded. * @type {string} */ this.url = url; /** * The Deferred that will be fired when the download is complete. * @type {!goog.async.Deferred} */ this.deferred = new goog.async.Deferred( goog.bind(downloader.cancel_, downloader, this)); /** * Whether this download has been cancelled by the user. * @type {boolean} */ this.cancelled = false; /** * The XhrIo object for downloading the file. Only set once it's been * retrieved from the pool. * @type {goog.net.XhrIo} */ this.xhr = null; /** * The name of the blob being downloaded. Only sey once the XHR has completed, * if it completed successfully. * @type {?string} */ this.name = null; /** * The downloaded blob. Only set once the XHR has completed, if it completed * successfully. * @type {Blob} */ this.blob = null; /** * The file entry where the blob is to be stored. Only set once it's been * loaded from the filesystem. * @type {goog.fs.FileEntry} */ this.file = null; /** * The file writer for writing the blob to the filesystem. Only set once it's * been loaded from the filesystem. * @type {goog.fs.FileWriter} */ this.writer = null; }; goog.inherits(goog.net.FileDownloader.Download_, goog.Disposable); /** @override */ goog.net.FileDownloader.Download_.prototype.disposeInternal = function() { this.cancelled = true; if (this.xhr) { this.xhr.abort(); } else if (this.writer && this.writer.getReadyState() == goog.fs.FileSaver.ReadyState.WRITING) { this.writer.abort(); } goog.base(this, 'disposeInternal'); };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Image loader utility class. Useful when an application needs * to preload multiple images, for example so they can be sized. * * @author attila@google.com (Attila Bodis) * @author zachlloyd@google.com (Zachary Lloyd) * @author jonemerson@google.com (Jon Emerson) */ goog.provide('goog.net.ImageLoader'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventTarget'); goog.require('goog.events.EventType'); goog.require('goog.net.EventType'); goog.require('goog.object'); goog.require('goog.userAgent'); /** * Image loader utility class. Raises a {@link goog.events.EventType.LOAD} * event for each image loaded, with an {@link Image} object as the target of * the event, normalized to have {@code naturalHeight} and {@code naturalWidth} * attributes. * * To use this class, run: * * <pre> * var imageLoader = new goog.net.ImageLoader(); * goog.events.listen(imageLoader, goog.net.EventType.COMPLETE, * function(e) { ... }); * imageLoader.addImage("image_id", "http://path/to/image.gif"); * imageLoader.start(); * </pre> * * The start() method must be called to start image loading. Images can be * added and removed after loading has started, but only those images added * before start() was called will be loaded until start() is called again. * A goog.net.EventType.COMPLETE event will be dispatched only once all * outstanding images have completed uploading. * * @param {Element=} opt_parent An optional parent element whose document object * should be used to load images. * @constructor * @extends {goog.events.EventTarget} */ goog.net.ImageLoader = function(opt_parent) { goog.events.EventTarget.call(this); /** * Map of image IDs to their image src, used to keep track of the images to * load. Once images have started loading, they're removed from this map. * @type {!Object.<string, string>} * @private */ this.imageIdToUrlMap_ = {}; /** * Map of image IDs to their image element, used only for images that are in * the process of loading. Used to clean-up event listeners and to know * when we've completed loading images. * @type {!Object.<string, !Element>} * @private */ this.imageIdToImageMap_ = {}; /** * Event handler object, used to keep track of onload and onreadystatechange * listeners. * @type {!goog.events.EventHandler} * @private */ this.handler_ = new goog.events.EventHandler(this); /** * The parent element whose document object will be used to load images. * Useful if you want to load the images from a window other than the current * window in order to control the Referer header sent when the image is * loaded. * @type {Element|undefined} * @private */ this.parent_ = opt_parent; }; goog.inherits(goog.net.ImageLoader, goog.events.EventTarget); /** * An array of event types to listen to on images. This is browser dependent. * Internet Explorer doesn't reliably raise LOAD events on images, so we must * use READY_STATE_CHANGE. If the image is cached locally, IE won't fire the * LOAD event while the onreadystate event is fired always. On the other hand, * the ERROR event is always fired whenever the image is not loaded successfully * no matter whether it's cached or not. * @type {!Array.<string>} * @private */ goog.net.ImageLoader.IMAGE_LOAD_EVENTS_ = [ goog.userAgent.IE ? goog.net.EventType.READY_STATE_CHANGE : goog.events.EventType.LOAD, goog.net.EventType.ABORT, goog.net.EventType.ERROR ]; /** * Adds an image to the image loader, and associates it with the given ID * string. If an image with that ID already exists, it is silently replaced. * When the image in question is loaded, the target of the LOAD event will be * an {@code Image} object with {@code id} and {@code src} attributes based on * these arguments. * @param {string} id The ID of the image to load. * @param {string|Image} image Either the source URL of the image or the HTML * image element itself (or any object with a {@code src} property, really). */ goog.net.ImageLoader.prototype.addImage = function(id, image) { var src = goog.isString(image) ? image : image.src; if (src) { // For now, we just store the source URL for the image. this.imageIdToUrlMap_[id] = src; } }; /** * Removes the image associated with the given ID string from the image loader. * If the image was previously loading, removes any listeners for its events * and dispatches a COMPLETE event if all remaining images have now completed. * @param {string} id The ID of the image to remove. */ goog.net.ImageLoader.prototype.removeImage = function(id) { delete this.imageIdToUrlMap_[id]; var image = this.imageIdToImageMap_[id]; if (image) { delete this.imageIdToImageMap_[id]; // Stop listening for events on the image. this.handler_.unlisten(image, goog.net.ImageLoader.IMAGE_LOAD_EVENTS_, this.onNetworkEvent_); // If this was the last image, raise a COMPLETE event. if (goog.object.isEmpty(this.imageIdToImageMap_) && goog.object.isEmpty(this.imageIdToUrlMap_)) { this.dispatchEvent(goog.net.EventType.COMPLETE); } } }; /** * Starts loading all images in the image loader in parallel. Raises a LOAD * event each time an image finishes loading, and a COMPLETE event after all * images have finished loading. */ goog.net.ImageLoader.prototype.start = function() { // Iterate over the keys, rather than the full object, to essentially clone // the initial queued images in case any event handlers decide to add more // images before this loop has finished executing. var imageIdToUrlMap = this.imageIdToUrlMap_; goog.array.forEach(goog.object.getKeys(imageIdToUrlMap), function(id) { var src = imageIdToUrlMap[id]; if (src) { delete imageIdToUrlMap[id]; this.loadImage_(src, id); } }, this); }; /** * Creates an {@code Image} object with the specified ID and source URL, and * listens for network events raised as the image is loaded. * @param {string} src The image source URL. * @param {string} id The unique ID of the image to load. * @private */ goog.net.ImageLoader.prototype.loadImage_ = function(src, id) { if (this.isDisposed()) { // When loading an image in IE7 (and maybe IE8), the error handler // may fire before we yield JS control. If the error handler // dispose the ImageLoader, this method will throw exception. return; } var image; if (this.parent_) { var dom = goog.dom.getDomHelper(this.parent_); image = dom.createDom('img'); } else { image = new Image(); } this.handler_.listen(image, goog.net.ImageLoader.IMAGE_LOAD_EVENTS_, this.onNetworkEvent_); this.imageIdToImageMap_[id] = image; image.id = id; image.src = src; }; /** * Handles net events (READY_STATE_CHANGE, LOAD, ABORT, and ERROR). * @param {goog.events.Event} evt The network event to handle. * @private */ goog.net.ImageLoader.prototype.onNetworkEvent_ = function(evt) { var image = /** @type {Element} */ (evt.currentTarget); if (!image) { return; } if (evt.type == goog.net.EventType.READY_STATE_CHANGE) { // This implies that the user agent is IE; see loadImage_(). // Noe that this block is used to check whether the image is ready to // dispatch the COMPLETE event. if (image.readyState == goog.net.EventType.COMPLETE) { // This is the IE equivalent of a LOAD event. evt.type = goog.events.EventType.LOAD; } else { // This may imply that the load failed. // Note that the image has only the following states: // * uninitialized // * loading // * complete // When the ERROR or the ABORT event is fired, the readyState // will be either uninitialized or loading and we'd ignore those states // since they will be handled separately (eg: evt.type = 'ERROR'). // Notes from MSDN : The states through which an object passes are // determined by that object. An object can skip certain states // (for example, interactive) if the state does not apply to that object. // see http://msdn.microsoft.com/en-us/library/ms534359(VS.85).aspx // The image is not loaded, ignore. return; } } // Add natural width/height properties for non-Gecko browsers. if (typeof image.naturalWidth == 'undefined') { if (evt.type == goog.events.EventType.LOAD) { image.naturalWidth = image.width; image.naturalHeight = image.height; } else { // This implies that the image fails to be loaded. image.naturalWidth = 0; image.naturalHeight = 0; } } // Redispatch the event on behalf of the image. Note that the external // listener may dispose this instance. this.dispatchEvent({type: evt.type, target: image}); if (this.isDisposed()) { // If instance was disposed by listener, exit this function. return; } this.removeImage(image.id); }; /** @override */ goog.net.ImageLoader.prototype.disposeInternal = function() { delete this.imageIdToUrlMap_; delete this.imageIdToImageMap_; goog.dispose(this.handler_); goog.net.ImageLoader.superClass_.disposeInternal.call(this); };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Base class for objects monitoring and exposing runtime * network status information. */ goog.provide('goog.net.NetworkStatusMonitor'); goog.require('goog.events.EventTarget'); /** * Base class for network status information providers. * @constructor * @extends {goog.events.EventTarget} */ goog.net.NetworkStatusMonitor = function() { goog.base(this); }; goog.inherits(goog.net.NetworkStatusMonitor, goog.events.EventTarget); /** * Enum for the events dispatched by the OnlineHandler. * @enum {string} */ goog.net.NetworkStatusMonitor.EventType = { ONLINE: 'online', OFFLINE: 'offline' }; /** * @return {boolean} Whether the system is online or otherwise. */ goog.net.NetworkStatusMonitor.prototype.isOnline = goog.abstractMethod;
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Definition of the ChannelDebug class. ChannelDebug provides * a utility for tracing and debugging the BrowserChannel requests. * * TODO(user) - allow client to specify a custom redaction policy */ /** * Namespace for BrowserChannel */ goog.provide('goog.net.ChannelDebug'); goog.require('goog.debug.Logger'); goog.require('goog.json'); /** * Logs and keeps a buffer of debugging info for the Channel. * * @constructor */ goog.net.ChannelDebug = function() { /** * The logger instance. * @type {goog.debug.Logger} * @private */ this.logger_ = goog.debug.Logger.getLogger('goog.net.BrowserChannel'); }; /** * Gets the logger used by this ChannelDebug. * @return {goog.debug.Logger} The logger used by this ChannelDebug. */ goog.net.ChannelDebug.prototype.getLogger = function() { return this.logger_; }; /** * Logs that the browser went offline during the lifetime of a request. * @param {goog.Uri} url The URL being requested. */ goog.net.ChannelDebug.prototype.browserOfflineResponse = function(url) { this.info('BROWSER_OFFLINE: ' + url); }; /** * Logs an XmlHttp request.. * @param {string} verb The request type (GET/POST). * @param {goog.Uri} uri The request destination. * @param {string|number|undefined} id The request id. * @param {number} attempt Which attempt # the request was. * @param {?string} postData The data posted in the request. */ goog.net.ChannelDebug.prototype.xmlHttpChannelRequest = function(verb, uri, id, attempt, postData) { this.info( 'XMLHTTP REQ (' + id + ') [attempt ' + attempt + ']: ' + verb + '\n' + uri + '\n' + this.maybeRedactPostData_(postData)); }; /** * Logs the meta data received from an XmlHttp request. * @param {string} verb The request type (GET/POST). * @param {goog.Uri} uri The request destination. * @param {string|number|undefined} id The request id. * @param {number} attempt Which attempt # the request was. * @param {goog.net.XmlHttp.ReadyState} readyState The ready state. * @param {number} statusCode The HTTP status code. */ goog.net.ChannelDebug.prototype.xmlHttpChannelResponseMetaData = function(verb, uri, id, attempt, readyState, statusCode) { this.info( 'XMLHTTP RESP (' + id + ') [ attempt ' + attempt + ']: ' + verb + '\n' + uri + '\n' + readyState + ' ' + statusCode); }; /** * Logs the response data received from an XmlHttp request. * @param {string|number|undefined} id The request id. * @param {?string} responseText The response text. * @param {?string=} opt_desc Optional request description. */ goog.net.ChannelDebug.prototype.xmlHttpChannelResponseText = function(id, responseText, opt_desc) { this.info( 'XMLHTTP TEXT (' + id + '): ' + this.redactResponse_(responseText) + (opt_desc ? ' ' + opt_desc : '')); }; /** * Logs a Trident ActiveX request. * @param {string} verb The request type (GET/POST). * @param {goog.Uri} uri The request destination. * @param {string|number|undefined} id The request id. * @param {number} attempt Which attempt # the request was. */ goog.net.ChannelDebug.prototype.tridentChannelRequest = function(verb, uri, id, attempt) { this.info( 'TRIDENT REQ (' + id + ') [ attempt ' + attempt + ']: ' + verb + '\n' + uri); }; /** * Logs the response text received from a Trident ActiveX request. * @param {string|number|undefined} id The request id. * @param {string} responseText The response text. */ goog.net.ChannelDebug.prototype.tridentChannelResponseText = function(id, responseText) { this.info( 'TRIDENT TEXT (' + id + '): ' + this.redactResponse_(responseText)); }; /** * Logs the done response received from a Trident ActiveX request. * @param {string|number|undefined} id The request id. * @param {boolean} successful Whether the request was successful. */ goog.net.ChannelDebug.prototype.tridentChannelResponseDone = function(id, successful) { this.info( 'TRIDENT TEXT (' + id + '): ' + successful ? 'success' : 'failure'); }; /** * Logs a request timeout. * @param {goog.Uri} uri The uri that timed out. */ goog.net.ChannelDebug.prototype.timeoutResponse = function(uri) { this.info('TIMEOUT: ' + uri); }; /** * Logs a debug message. * @param {string} text The message. */ goog.net.ChannelDebug.prototype.debug = function(text) { this.info(text); }; /** * Logs an exception * @param {Error} e The error or error event. * @param {string=} opt_msg The optional message, defaults to 'Exception'. */ goog.net.ChannelDebug.prototype.dumpException = function(e, opt_msg) { this.severe((opt_msg || 'Exception') + e); }; /** * Logs an info message. * @param {string} text The message. */ goog.net.ChannelDebug.prototype.info = function(text) { this.logger_.info(text); }; /** * Logs a warning message. * @param {string} text The message. */ goog.net.ChannelDebug.prototype.warning = function(text) { this.logger_.warning(text); }; /** * Logs a severe message. * @param {string} text The message. */ goog.net.ChannelDebug.prototype.severe = function(text) { this.logger_.severe(text); }; /** * Removes potentially private data from a response so that we don't * accidentally save private and personal data to the server logs. * @param {?string} responseText A JSON response to clean. * @return {?string} The cleaned response. * @private */ goog.net.ChannelDebug.prototype.redactResponse_ = function(responseText) { // first check if it's not JS - the only non-JS should be the magic cookie if (!responseText || /** @suppress {missingRequire}. The require creates a circular * dependency. */ responseText == goog.net.BrowserChannel.MAGIC_RESPONSE_COOKIE) { return responseText; } /** @preserveTry */ try { var responseArray = goog.json.unsafeParse(responseText); if (responseArray) { for (var i = 0; i < responseArray.length; i++) { if (goog.isArray(responseArray[i])) { this.maybeRedactArray_(responseArray[i]); } } } return goog.json.serialize(responseArray); } catch (e) { this.debug('Exception parsing expected JS array - probably was not JS'); return responseText; } }; /** * Removes data from a response array that may be sensitive. * @param {Array} array The array to clean. * @private */ goog.net.ChannelDebug.prototype.maybeRedactArray_ = function(array) { if (array.length < 2) { return; } var dataPart = array[1]; if (!goog.isArray(dataPart)) { return; } if (dataPart.length < 1) { return; } var type = dataPart[0]; if (type != 'noop' && type != 'stop') { // redact all fields in the array for (var i = 1; i < dataPart.length; i++) { dataPart[i] = ''; } } }; /** * Removes potentially private data from a request POST body so that we don't * accidentally save private and personal data to the server logs. * @param {?string} data The data string to clean. * @return {?string} The data string with sensitive data replaced by 'redacted'. * @private */ goog.net.ChannelDebug.prototype.maybeRedactPostData_ = function(data) { if (!data) { return null; } var out = ''; var params = data.split('&'); for (var i = 0; i < params.length; i++) { var param = params[i]; var keyValue = param.split('='); if (keyValue.length > 1) { var key = keyValue[0]; var value = keyValue[1]; var keyParts = key.split('_'); if (keyParts.length >= 2 && keyParts[1] == 'type') { out += key + '=' + value + '&'; } else { out += key + '=' + 'redacted' + '&'; } } } return out; };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Cross domain RPC library using the <a * href="http://go/xd2_design" target="_top">XD2 approach</a>. * * <h5>Protocol</h5> * Client sends a request across domain via a form submission. Server * receives these parameters: "xdpe:request-id", "xdpe:dummy-uri" ("xdpe" for * "cross domain parameter to echo back") and other user parameters prefixed * with "xdp" (for "cross domain parameter"). Headers are passed as parameters * prefixed with "xdh" (for "cross domain header"). Only strings are supported * for parameters and headers. A GET method is mapped to a form GET. All * other methods are mapped to a POST. Server is expected to produce a * HTML response such as the following: * <pre> * &lt;body&gt; * &lt;script type="text/javascript" * src="path-to-crossdomainrpc.js"&gt;&lt;/script&gt; * var currentDirectory = location.href.substring( * 0, location.href.lastIndexOf('/') * ); * * // echo all parameters prefixed with "xdpe:" * var echo = {}; * echo[goog.net.CrossDomainRpc.PARAM_ECHO_REQUEST_ID] = * &lt;value of parameter "xdpe:request-id"&gt;; * echo[goog.net.CrossDomainRpc.PARAM_ECHO_DUMMY_URI] = * &lt;value of parameter "xdpe:dummy-uri"&gt;; * * goog.net.CrossDomainRpc.sendResponse( * '({"result":"&lt;responseInJSON"})', * true, // is JSON * echo, // parameters to echo back * status, // response status code * headers // response headers * ); * &lt;/script&gt; * &lt;/body&gt; * </pre> * * <h5>Server Side</h5> * For an example of the server side, refer to the following files: * <ul> * <li>http://go/xdservletfilter.java</li> * <li>http://go/xdservletrequest.java</li> * <li>http://go/xdservletresponse.java</li> * </ul> * * <h5>System Requirements</h5> * Tested on IE6, IE7, Firefox 2.0 and Safari nightly r23841. * */ goog.provide('goog.net.CrossDomainRpc'); goog.require('goog.Uri.QueryData'); goog.require('goog.debug.Logger'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.events.EventTarget'); goog.require('goog.events.EventType'); goog.require('goog.json'); goog.require('goog.net.EventType'); goog.require('goog.net.HttpStatus'); goog.require('goog.userAgent'); /** * Creates a new instance of cross domain RPC * @extends {goog.events.EventTarget} * @constructor */ goog.net.CrossDomainRpc = function() { goog.events.EventTarget.call(this); }; goog.inherits(goog.net.CrossDomainRpc, goog.events.EventTarget); /** * Cross-domain response iframe marker. * @type {string} * @private */ goog.net.CrossDomainRpc.RESPONSE_MARKER_ = 'xdrp'; /** * Use a fallback dummy resource if none specified or detected. * @type {boolean} * @private */ goog.net.CrossDomainRpc.useFallBackDummyResource_ = true; /** * Checks to see if we are executing inside a response iframe. This is the * case when this page is used as a dummy resource to gain caller's domain. * @return {*} True if we are executing inside a response iframe; false * otherwise. * @private */ goog.net.CrossDomainRpc.isInResponseIframe_ = function() { return window.location && (window.location.hash.indexOf( goog.net.CrossDomainRpc.RESPONSE_MARKER_) == 1 || window.location.search.indexOf( goog.net.CrossDomainRpc.RESPONSE_MARKER_) == 1); }; /** * Stops execution of the rest of the page if this page is loaded inside a * response iframe. */ if (goog.net.CrossDomainRpc.isInResponseIframe_()) { if (goog.userAgent.IE) { document.execCommand('Stop'); } else if (goog.userAgent.GECKO) { window.stop(); } else { throw Error('stopped'); } } /** * Sets the URI for a dummy resource on caller's domain. This function is * used for specifying a particular resource to use rather than relying on * auto detection. * @param {string} dummyResourceUri URI to dummy resource on the same domain * of caller's page. */ goog.net.CrossDomainRpc.setDummyResourceUri = function(dummyResourceUri) { goog.net.CrossDomainRpc.dummyResourceUri_ = dummyResourceUri; }; /** * Sets whether a fallback dummy resource ("/robots.txt" on Firefox and Safari * and current page on IE) should be used when a suitable dummy resource is * not available. * @param {boolean} useFallBack Whether to use fallback or not. */ goog.net.CrossDomainRpc.setUseFallBackDummyResource = function(useFallBack) { goog.net.CrossDomainRpc.useFallBackDummyResource_ = useFallBack; }; /** * Sends a request across domain. * @param {string} uri Uri to make request to. * @param {Function=} opt_continuation Continuation function to be called * when request is completed. Takes one argument of an event object * whose target has the following properties: "status" is the HTTP * response status code, "responseText" is the response text, * and "headers" is an object with all response headers. The event * target's getResponseJson() method returns a JavaScript object evaluated * from the JSON response or undefined if response is not JSON. * @param {string=} opt_method Method of request. Default is POST. * @param {Object=} opt_params Parameters. Each property is turned into a * request parameter. * @param {Object=} opt_headers Map of headers of the request. */ goog.net.CrossDomainRpc.send = function(uri, opt_continuation, opt_method, opt_params, opt_headers) { var xdrpc = new goog.net.CrossDomainRpc(); if (opt_continuation) { goog.events.listen(xdrpc, goog.net.EventType.COMPLETE, opt_continuation); } goog.events.listen(xdrpc, goog.net.EventType.READY, xdrpc.reset); xdrpc.sendRequest(uri, opt_method, opt_params, opt_headers); }; /** * Sets debug mode to true or false. When debug mode is on, response iframes * are visible and left behind after their use is finished. * @param {boolean} flag Flag to indicate intention to turn debug model on * (true) or off (false). */ goog.net.CrossDomainRpc.setDebugMode = function(flag) { goog.net.CrossDomainRpc.debugMode_ = flag; }; /** * Logger for goog.net.CrossDomainRpc * @type {goog.debug.Logger} * @private */ goog.net.CrossDomainRpc.logger_ = goog.debug.Logger.getLogger('goog.net.CrossDomainRpc'); /** * Creates the HTML of an input element * @param {string} name Name of input element. * @param {*} value Value of input element. * @return {string} HTML of input element with that name and value. * @private */ goog.net.CrossDomainRpc.createInputHtml_ = function(name, value) { return '<textarea name="' + name + '">' + goog.net.CrossDomainRpc.escapeAmpersand_(value) + '</textarea>'; }; /** * Escapes ampersand so that XML/HTML entities are submitted as is because * browser unescapes them when they are put into a text area. * @param {*} value Value to escape. * @return {*} Value with ampersand escaped, if value is a string; * otherwise the value itself is returned. * @private */ goog.net.CrossDomainRpc.escapeAmpersand_ = function(value) { return value && (goog.isString(value) || value.constructor == String) ? value.replace(/&/g, '&amp;') : value; }; /** * Finds a dummy resource that can be used by response to gain domain of * requester's page. * @return {string} URI of the resource to use. * @private */ goog.net.CrossDomainRpc.getDummyResourceUri_ = function() { if (goog.net.CrossDomainRpc.dummyResourceUri_) { return goog.net.CrossDomainRpc.dummyResourceUri_; } // find a style sheet if not on IE, which will attempt to save style sheet if (goog.userAgent.GECKO) { var links = document.getElementsByTagName('link'); for (var i = 0; i < links.length; i++) { var link = links[i]; // find a link which is on the same domain as this page // cannot use one with '?' or '#' in its URL as it will confuse // goog.net.CrossDomainRpc.getFramePayload_() if (link.rel == 'stylesheet' && goog.Uri.haveSameDomain(link.href, window.location.href) && link.href.indexOf('?') < 0) { return goog.net.CrossDomainRpc.removeHash_(link.href); } } } var images = document.getElementsByTagName('img'); for (var i = 0; i < images.length; i++) { var image = images[i]; // find a link which is on the same domain as this page // cannot use one with '?' or '#' in its URL as it will confuse // goog.net.CrossDomainRpc.getFramePayload_() if (goog.Uri.haveSameDomain(image.src, window.location.href) && image.src.indexOf('?') < 0) { return goog.net.CrossDomainRpc.removeHash_(image.src); } } if (!goog.net.CrossDomainRpc.useFallBackDummyResource_) { throw Error( 'No suitable dummy resource specified or detected for this page'); } if (goog.userAgent.IE) { // use this page as the dummy resource; remove hash from URL if any return goog.net.CrossDomainRpc.removeHash_(window.location.href); } else { /** * Try to use "http://<this-domain>/robots.txt" which may exist. Even if * it does not, an error page is returned and is a good dummy resource to * use on Firefox and Safari. An existing resource is faster because it * is cached. */ var locationHref = window.location.href; var rootSlash = locationHref.indexOf('/', locationHref.indexOf('//') + 2); var rootHref = locationHref.substring(0, rootSlash); return rootHref + '/robots.txt'; } }; /** * Removes everything at and after hash from URI * @param {string} uri Uri to to remove hash. * @return {string} Uri with its hash and all characters after removed. * @private */ goog.net.CrossDomainRpc.removeHash_ = function(uri) { return uri.split('#')[0]; }; // ------------ // request side /** * next request id used to support multiple XD requests at the same time * @type {number} * @private */ goog.net.CrossDomainRpc.nextRequestId_ = 0; /** * Header prefix. * @type {string} */ goog.net.CrossDomainRpc.HEADER = 'xdh:'; /** * Parameter prefix. * @type {string} */ goog.net.CrossDomainRpc.PARAM = 'xdp:'; /** * Parameter to echo prefix. * @type {string} */ goog.net.CrossDomainRpc.PARAM_ECHO = 'xdpe:'; /** * Parameter to echo: request id * @type {string} */ goog.net.CrossDomainRpc.PARAM_ECHO_REQUEST_ID = goog.net.CrossDomainRpc.PARAM_ECHO + 'request-id'; /** * Parameter to echo: dummy resource URI * @type {string} */ goog.net.CrossDomainRpc.PARAM_ECHO_DUMMY_URI = goog.net.CrossDomainRpc.PARAM_ECHO + 'dummy-uri'; /** * Cross-domain request marker. * @type {string} * @private */ goog.net.CrossDomainRpc.REQUEST_MARKER_ = 'xdrq'; /** * Sends a request across domain. * @param {string} uri Uri to make request to. * @param {string=} opt_method Method of request. Default is POST. * @param {Object=} opt_params Parameters. Each property is turned into a * request parameter. * @param {Object=} opt_headers Map of headers of the request. */ goog.net.CrossDomainRpc.prototype.sendRequest = function(uri, opt_method, opt_params, opt_headers) { // create request frame var requestFrame = this.requestFrame_ = document.createElement('iframe'); var requestId = goog.net.CrossDomainRpc.nextRequestId_++; requestFrame.id = goog.net.CrossDomainRpc.REQUEST_MARKER_ + '-' + requestId; if (!goog.net.CrossDomainRpc.debugMode_) { requestFrame.style.position = 'absolute'; requestFrame.style.top = '-5000px'; requestFrame.style.left = '-5000px'; } document.body.appendChild(requestFrame); // build inputs var inputs = []; // add request id inputs.push(goog.net.CrossDomainRpc.createInputHtml_( goog.net.CrossDomainRpc.PARAM_ECHO_REQUEST_ID, requestId)); // add dummy resource uri var dummyUri = goog.net.CrossDomainRpc.getDummyResourceUri_(); goog.net.CrossDomainRpc.logger_.log( goog.debug.Logger.Level.FINE, 'dummyUri: ' + dummyUri); inputs.push(goog.net.CrossDomainRpc.createInputHtml_( goog.net.CrossDomainRpc.PARAM_ECHO_DUMMY_URI, dummyUri)); // add parameters if (opt_params) { for (var name in opt_params) { var value = opt_params[name]; inputs.push(goog.net.CrossDomainRpc.createInputHtml_( goog.net.CrossDomainRpc.PARAM + name, value)); } } // add headers if (opt_headers) { for (var name in opt_headers) { var value = opt_headers[name]; inputs.push(goog.net.CrossDomainRpc.createInputHtml_( goog.net.CrossDomainRpc.HEADER + name, value)); } } var requestFrameContent = '<body><form method="' + (opt_method == 'GET' ? 'GET' : 'POST') + '" action="' + uri + '">' + inputs.join('') + '</form></body>'; var requestFrameDoc = goog.dom.getFrameContentDocument(requestFrame); requestFrameDoc.open(); requestFrameDoc.write(requestFrameContent); requestFrameDoc.close(); requestFrameDoc.forms[0].submit(); requestFrameDoc = null; this.loadListenerKey_ = goog.events.listen( requestFrame, goog.events.EventType.LOAD, function() { goog.net.CrossDomainRpc.logger_.log(goog.debug.Logger.Level.FINE, 'response ready'); this.responseReady_ = true; }, false, this); this.receiveResponse_(); }; /** * period of response polling (ms) * @type {number} * @private */ goog.net.CrossDomainRpc.RESPONSE_POLLING_PERIOD_ = 50; /** * timeout from response comes back to sendResponse is called (ms) * @type {number} * @private */ goog.net.CrossDomainRpc.SEND_RESPONSE_TIME_OUT_ = 500; /** * Receives response by polling to check readiness of response and then * reads response frames and assembles response data * @private */ goog.net.CrossDomainRpc.prototype.receiveResponse_ = function() { this.timeWaitedAfterResponseReady_ = 0; var responseDetectorHandle = window.setInterval(goog.bind(function() { this.detectResponse_(responseDetectorHandle); }, this), goog.net.CrossDomainRpc.RESPONSE_POLLING_PERIOD_); }; /** * Detects response inside request frame * @param {number} responseDetectorHandle Handle of detector. * @private */ goog.net.CrossDomainRpc.prototype.detectResponse_ = function(responseDetectorHandle) { var requestFrameWindow = this.requestFrame_.contentWindow; var grandChildrenLength = requestFrameWindow.frames.length; var responseInfoFrame = null; if (grandChildrenLength > 0 && goog.net.CrossDomainRpc.isResponseInfoFrame_(responseInfoFrame = requestFrameWindow.frames[grandChildrenLength - 1])) { goog.net.CrossDomainRpc.logger_.log(goog.debug.Logger.Level.FINE, 'xd response ready'); var responseInfoPayload = goog.net.CrossDomainRpc.getFramePayload_( responseInfoFrame).substring(1); var params = new goog.Uri.QueryData(responseInfoPayload); var chunks = []; var numChunks = Number(params.get('n')); goog.net.CrossDomainRpc.logger_.log(goog.debug.Logger.Level.FINE, 'xd response number of chunks: ' + numChunks); for (var i = 0; i < numChunks; i++) { var responseFrame = requestFrameWindow.frames[i]; if (!responseFrame || !responseFrame.location || !responseFrame.location.href) { // On Safari 3.0, it is sometimes the case that the // iframe exists but doesn't have a same domain href yet. goog.net.CrossDomainRpc.logger_.log(goog.debug.Logger.Level.FINE, 'xd response iframe not ready'); return; } var responseChunkPayload = goog.net.CrossDomainRpc.getFramePayload_(responseFrame); // go past "chunk=" var chunkIndex = responseChunkPayload.indexOf( goog.net.CrossDomainRpc.PARAM_CHUNK_) + goog.net.CrossDomainRpc.PARAM_CHUNK_.length + 1; var chunk = responseChunkPayload.substring(chunkIndex); chunks.push(chunk); } window.clearInterval(responseDetectorHandle); var responseData = chunks.join(''); // Payload is not encoded to begin with on IE. Decode in other cases only. if (!goog.userAgent.IE) { responseData = decodeURIComponent(responseData); } this.status = Number(params.get('status')); this.responseText = responseData; this.responseTextIsJson_ = params.get('isDataJson') == 'true'; this.responseHeaders = goog.json.unsafeParse( /** @type {string} */ (params.get('headers'))); this.dispatchEvent(goog.net.EventType.READY); this.dispatchEvent(goog.net.EventType.COMPLETE); } else { if (this.responseReady_) { /* The response has come back. But the first response iframe has not * been created yet. If this lasts long enough, it is an error. */ this.timeWaitedAfterResponseReady_ += goog.net.CrossDomainRpc.RESPONSE_POLLING_PERIOD_; if (this.timeWaitedAfterResponseReady_ > goog.net.CrossDomainRpc.SEND_RESPONSE_TIME_OUT_) { goog.net.CrossDomainRpc.logger_.log(goog.debug.Logger.Level.FINE, 'xd response timed out'); window.clearInterval(responseDetectorHandle); this.status = goog.net.HttpStatus.INTERNAL_SERVER_ERROR; this.responseText = 'response timed out'; this.dispatchEvent(goog.net.EventType.READY); this.dispatchEvent(goog.net.EventType.ERROR); this.dispatchEvent(goog.net.EventType.COMPLETE); } } } }; /** * Checks whether a frame is response info frame. * @param {Object} frame Frame to check. * @return {boolean} True if frame is a response info frame; false otherwise. * @private */ goog.net.CrossDomainRpc.isResponseInfoFrame_ = function(frame) { /** @preserveTry */ try { return goog.net.CrossDomainRpc.getFramePayload_(frame).indexOf( goog.net.CrossDomainRpc.RESPONSE_INFO_MARKER_) == 1; } catch (e) { // frame not ready for same-domain access yet return false; } }; /** * Returns the payload of a frame (value after # or ? on the URL). This value * is URL encoded except IE, where the value is not encoded to begin with. * @param {Object} frame Frame. * @return {string} Payload of that frame. * @private */ goog.net.CrossDomainRpc.getFramePayload_ = function(frame) { var href = frame.location.href; var question = href.indexOf('?'); var hash = href.indexOf('#'); // On IE, beucase the URL is not encoded, we can have a case where ? // is the delimiter before payload and # in payload or # as the delimiter // and ? in payload. So here we treat whoever is the first as the delimiter. var delimiter = question < 0 ? hash : hash < 0 ? question : Math.min(question, hash); return href.substring(delimiter); }; /** * If response is JSON, evaluates it to a JavaScript object and * returns it; otherwise returns undefined. * @return {Object|undefined} JavaScript object if response is in JSON * or undefined. */ goog.net.CrossDomainRpc.prototype.getResponseJson = function() { return this.responseTextIsJson_ ? goog.json.unsafeParse(this.responseText) : undefined; }; /** * @return {boolean} Whether the request completed with a success. */ goog.net.CrossDomainRpc.prototype.isSuccess = function() { // Definition similar to goog.net.XhrIo.prototype.isSuccess. switch (this.status) { case goog.net.HttpStatus.OK: case goog.net.HttpStatus.NOT_MODIFIED: return true; default: return false; } }; /** * Removes request iframe used. */ goog.net.CrossDomainRpc.prototype.reset = function() { if (!goog.net.CrossDomainRpc.debugMode_) { goog.net.CrossDomainRpc.logger_.log(goog.debug.Logger.Level.FINE, 'request frame removed: ' + this.requestFrame_.id); goog.events.unlistenByKey(this.loadListenerKey_); this.requestFrame_.parentNode.removeChild(this.requestFrame_); } delete this.requestFrame_; }; // ------------- // response side /** * Name of response info iframe. * @type {string} * @private */ goog.net.CrossDomainRpc.RESPONSE_INFO_MARKER_ = goog.net.CrossDomainRpc.RESPONSE_MARKER_ + '-info'; /** * Maximal chunk size. IE can only handle 4095 bytes on its URL. * 16MB has been tested on Firefox. But 1MB is a practical size. * @type {number} * @private */ goog.net.CrossDomainRpc.MAX_CHUNK_SIZE_ = goog.userAgent.IE ? 4095 : 1024 * 1024; /** * Query parameter 'chunk'. * @type {string} * @private */ goog.net.CrossDomainRpc.PARAM_CHUNK_ = 'chunk'; /** * Prefix before data chunk for passing other parameters. * type String * @private */ goog.net.CrossDomainRpc.CHUNK_PREFIX_ = goog.net.CrossDomainRpc.RESPONSE_MARKER_ + '=1&' + goog.net.CrossDomainRpc.PARAM_CHUNK_ + '='; /** * Makes response available for grandparent (requester)'s receiveResponse * call to pick up by creating a series of iframes pointed to the dummy URI * with a payload (value after either ? or #) carrying a chunk of response * data and a response info iframe that tells the grandparent (requester) the * readiness of response. * @param {string} data Response data (string or JSON string). * @param {boolean} isDataJson true if data is a JSON string; false if just a * string. * @param {Object} echo Parameters to echo back * "xdpe:request-id": Server that produces the response needs to * copy it here to support multiple current XD requests on the same page. * "xdpe:dummy-uri": URI to a dummy resource that response * iframes point to to gain the domain of the client. This can be an * image (IE) or a CSS file (FF) found on the requester's page. * Server should copy value from request parameter "xdpe:dummy-uri". * @param {number} status HTTP response status code. * @param {string} headers Response headers in JSON format. */ goog.net.CrossDomainRpc.sendResponse = function(data, isDataJson, echo, status, headers) { var dummyUri = echo[goog.net.CrossDomainRpc.PARAM_ECHO_DUMMY_URI]; // since the dummy-uri can be specified by the user, verify that it doesn't // use any other protocols. (Specifically we don't want users to use a // dummy-uri beginning with "javascript:"). if (!goog.string.caseInsensitiveStartsWith(dummyUri, 'http://') && !goog.string.caseInsensitiveStartsWith(dummyUri, 'https://')) { dummyUri = 'http://' + dummyUri; } // usable chunk size is max less dummy URI less chunk prefix length // TODO(user): Figure out why we need to do "- 1" below var chunkSize = goog.net.CrossDomainRpc.MAX_CHUNK_SIZE_ - dummyUri.length - 1 - // payload delimiter ('#' or '?') goog.net.CrossDomainRpc.CHUNK_PREFIX_.length - 1; /* * Here we used to do URI encoding of data before we divide it into chunks * and decode on the receiving end. We don't do this any more on IE for the * following reasons. * * 1) On IE, calling decodeURIComponent on a relatively large string is * extremely slow (~22s for 160KB). So even a moderate amount of data * makes this library pretty much useless. Fortunately, we can actually * put unencoded data on IE's URL and get it back reliably. So we are * completely skipping encoding and decoding on IE. When we call * getFrameHash_ to get it back, the value is still intact(*) and unencoded. * 2) On Firefox, we have to call decodeURIComponent because location.hash * does decoding by itself. Fortunately, decodeURIComponent is not slow * on Firefox. * 3) Safari automatically encodes everything you put on URL and it does not * automatically decode when you access it via location.hash or * location.href. So we encode it here and decode it in detectResponse_(). * * Note(*): IE actually does encode only space to %20 and decodes that * automatically when you do location.href or location.hash. */ if (!goog.userAgent.IE) { data = encodeURIComponent(data); } var numChunksToSend = Math.ceil(data.length / chunkSize); if (numChunksToSend == 0) { goog.net.CrossDomainRpc.createResponseInfo_( dummyUri, numChunksToSend, isDataJson, status, headers); } else { var numChunksSent = 0; var checkToCreateResponseInfo_ = function() { if (++numChunksSent == numChunksToSend) { goog.net.CrossDomainRpc.createResponseInfo_( dummyUri, numChunksToSend, isDataJson, status, headers); } }; for (var i = 0; i < numChunksToSend; i++) { var chunkStart = i * chunkSize; var chunkEnd = chunkStart + chunkSize; var chunk = chunkEnd > data.length ? data.substring(chunkStart) : data.substring(chunkStart, chunkEnd); var responseFrame = document.createElement('iframe'); responseFrame.src = dummyUri + goog.net.CrossDomainRpc.getPayloadDelimiter_(dummyUri) + goog.net.CrossDomainRpc.CHUNK_PREFIX_ + chunk; document.body.appendChild(responseFrame); // We used to call the function below when handling load event of // responseFrame. But that event does not fire on IE when current // page is used as the dummy resource (because its loading is stopped?). // It also does not fire sometimes on Firefox. So now we call it // directly. checkToCreateResponseInfo_(); } } }; /** * Creates a response info iframe to indicate completion of sendResponse * @param {string} dummyUri URI to a dummy resource. * @param {number} numChunks Total number of chunks. * @param {boolean} isDataJson Whether response is a JSON string or just string. * @param {number} status HTTP response status code. * @param {string} headers Response headers in JSON format. * @private */ goog.net.CrossDomainRpc.createResponseInfo_ = function(dummyUri, numChunks, isDataJson, status, headers) { var responseInfoFrame = document.createElement('iframe'); document.body.appendChild(responseInfoFrame); responseInfoFrame.src = dummyUri + goog.net.CrossDomainRpc.getPayloadDelimiter_(dummyUri) + goog.net.CrossDomainRpc.RESPONSE_INFO_MARKER_ + '=1&n=' + numChunks + '&isDataJson=' + isDataJson + '&status=' + status + '&headers=' + encodeURIComponent(headers); }; /** * Returns payload delimiter, either "#" when caller's page is not used as * the dummy resource or "?" when it is, in which case caching issues prevent * response frames to gain the caller's domain. * @param {string} dummyUri URI to resource being used as dummy resource. * @return {string} Either "?" when caller's page is used as dummy resource or * "#" if it is not. * @private */ goog.net.CrossDomainRpc.getPayloadDelimiter_ = function(dummyUri) { return goog.net.CrossDomainRpc.REFERRER_ == dummyUri ? '?' : '#'; }; /** * Removes all parameters (after ? or #) from URI. * @param {string} uri URI to remove parameters from. * @return {string} URI with all parameters removed. * @private */ goog.net.CrossDomainRpc.removeUriParams_ = function(uri) { // remove everything after question mark var question = uri.indexOf('?'); if (question > 0) { uri = uri.substring(0, question); } // remove everything after hash mark var hash = uri.indexOf('#'); if (hash > 0) { uri = uri.substring(0, hash); } return uri; }; /** * Gets a response header. * @param {string} name Name of response header. * @return {string|undefined} Value of response header; undefined if not found. */ goog.net.CrossDomainRpc.prototype.getResponseHeader = function(name) { return goog.isObject(this.responseHeaders) ? this.responseHeaders[name] : undefined; }; /** * Referrer of current document with all parameters after "?" and "#" stripped. * @type {string} * @private */ goog.net.CrossDomainRpc.REFERRER_ = goog.net.CrossDomainRpc.removeUriParams_(document.referrer);
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Soy data primitives. * * The goal is to encompass data types used by Soy, especially to mark content * as known to be "safe". * * @author gboyer@google.com (Garrett Boyer) */ goog.provide('goog.soy.data'); goog.provide('goog.soy.data.SanitizedContent'); goog.provide('goog.soy.data.SanitizedContentKind'); /** * A type of textual content. * * This is an enum of type Object so that these values are unforgeable. * * @enum {!Object} */ goog.soy.data.SanitizedContentKind = { /** * A snippet of HTML that does not start or end inside a tag, comment, entity, * or DOCTYPE; and that does not contain any executable code * (JS, {@code <object>}s, etc.) from a different trust domain. */ HTML: goog.DEBUG ? {sanitizedContentKindHtml: true} : {}, /** * Executable Javascript code or expression, safe for insertion in a * script-tag or event handler context, known to be free of any * attacker-controlled scripts. This can either be side-effect-free * Javascript (such as JSON) or Javascript that entirely under Google's * control. */ JS: goog.DEBUG ? {sanitizedContentJsStrChars: true} : {}, /** * A sequence of code units that can appear between quotes (either kind) in a * JS program without causing a parse error, and without causing any side * effects. * <p> * The content should not contain unescaped quotes, newlines, or anything else * that would cause parsing to fail or to cause a JS parser to finish the * string its parsing inside the content. * <p> * The content must also not end inside an escape sequence ; no partial octal * escape sequences or odd number of '{@code \}'s at the end. */ JS_STR_CHARS: goog.DEBUG ? {sanitizedContentJsStrChars: true} : {}, /** A properly encoded portion of a URI. */ URI: goog.DEBUG ? {sanitizedContentUri: true} : {}, /** * Repeated attribute names and values. For example, * {@code dir="ltr" foo="bar" onclick="trustedFunction()" checked}. */ ATTRIBUTES: goog.DEBUG ? {sanitizedContentHtmlAttribute: true} : {}, // TODO: Consider separating rules, declarations, and values into // separate types, but for simplicity, we'll treat explicitly blessed // SanitizedContent as allowed in all of these contexts. /** * A CSS3 declaration, property, value or group of semicolon separated * declarations. */ CSS: goog.DEBUG ? {sanitizedContentCss: true} : {}, /** * Unsanitized plain-text content. * * This is effectively the "null" entry of this enum, and is sometimes used * to explicitly mark content that should never be used unescaped. Since any * string is safe to use as text, being of ContentKind.TEXT makes no * guarantees about its safety in any other context such as HTML. */ TEXT: goog.DEBUG ? {sanitizedContentKindText: true} : {} }; /** * A string-like object that carries a content-type. * * IMPORTANT! Do not create these directly, nor instantiate the subclasses. * Instead, use a trusted, centrally reviewed library as endorsed by your team * to generate these objects. Otherwise, you risk accidentally creating * SanitizedContent that is attacker-controlled and gets evaluated unescaped in * templates. * * @constructor */ goog.soy.data.SanitizedContent = function() { throw Error('Do not instantiate directly'); }; /** * The context in which this content is safe from XSS attacks. * @type {goog.soy.data.SanitizedContentKind} */ goog.soy.data.SanitizedContent.prototype.contentKind; /** * The already-safe content. * @type {string} */ goog.soy.data.SanitizedContent.prototype.content; /** @override */ goog.soy.data.SanitizedContent.prototype.toString = function() { return this.content; };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides utility methods to render soy template. */ goog.provide('goog.soy'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.TagName'); goog.require('goog.soy.data'); goog.require('goog.string'); /** * @define {boolean} Whether to require all Soy templates to be "strict html". * Soy templates that use strict autoescaping forbid noAutoescape along with * many dangerous directives, and return a runtime type SanitizedContent that * marks them as safe. * * If this flag is enabled, Soy templates will fail to render if a template * returns plain text -- indicating it is a non-strict template. */ goog.soy.REQUIRE_STRICT_AUTOESCAPE = false; /** * Renders a Soy template and then set the output string as * the innerHTML of an element. It is recommended to use this helper function * instead of directly setting innerHTML in your hand-written code, so that it * will be easier to audit the code for cross-site scripting vulnerabilities. * * @param {Element} element The element whose content we are rendering into. * @param {Function} template The Soy template defining the element's content. * @param {Object=} opt_templateData The data for the template. * @param {Object=} opt_injectedData The injected data for the template. */ goog.soy.renderElement = function(element, template, opt_templateData, opt_injectedData) { element.innerHTML = goog.soy.ensureTemplateOutputHtml_(template( opt_templateData || goog.soy.defaultTemplateData_, undefined, opt_injectedData)); }; /** * Renders a Soy template into a single node or a document * fragment. If the rendered HTML string represents a single node, then that * node is returned (note that this is *not* a fragment, despite them name of * the method). Otherwise a document fragment is returned containing the * rendered nodes. * * @param {Function} template The Soy template defining the element's content. * @param {Object=} opt_templateData The data for the template. * @param {Object=} opt_injectedData The injected data for the template. * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper used to * create DOM nodes; defaults to {@code goog.dom.getDomHelper}. * @return {!Node} The resulting node or document fragment. */ goog.soy.renderAsFragment = function(template, opt_templateData, opt_injectedData, opt_domHelper) { var dom = opt_domHelper || goog.dom.getDomHelper(); return dom.htmlToDocumentFragment(goog.soy.ensureTemplateOutputHtml_( template(opt_templateData || goog.soy.defaultTemplateData_, undefined, opt_injectedData))); }; /** * Renders a Soy template into a single node. If the rendered * HTML string represents a single node, then that node is returned. Otherwise, * a DIV element is returned containing the rendered nodes. * * @param {Function} template The Soy template defining the element's content. * @param {Object=} opt_templateData The data for the template. * @param {Object=} opt_injectedData The injected data for the template. * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper used to * create DOM nodes; defaults to {@code goog.dom.getDomHelper}. * @return {!Element} Rendered template contents, wrapped in a parent DIV * element if necessary. */ goog.soy.renderAsElement = function(template, opt_templateData, opt_injectedData, opt_domHelper) { var dom = opt_domHelper || goog.dom.getDomHelper(); var wrapper = dom.createElement(goog.dom.TagName.DIV); wrapper.innerHTML = goog.soy.ensureTemplateOutputHtml_(template( opt_templateData || goog.soy.defaultTemplateData_, undefined, opt_injectedData)); // If the template renders as a single element, return it. if (wrapper.childNodes.length == 1) { var firstChild = wrapper.firstChild; if (firstChild.nodeType == goog.dom.NodeType.ELEMENT) { return /** @type {!Element} */ (firstChild); } } // Otherwise, return the wrapper DIV. return wrapper; }; /** * Ensures the result is "safe" to insert as HTML. * * Note if the template has non-strict autoescape, the guarantees here are very * weak. It is recommended applications switch to requiring strict * autoescaping over time by tweaking goog.soy.REQUIRE_STRICT_AUTOESCAPE. * * In the case the argument is a SanitizedContent object, it either must * already be of kind HTML, or if it is kind="text", the output will be HTML * escaped. * * @param {*} templateResult The template result. * @return {string} The assumed-safe HTML output string. * @private */ goog.soy.ensureTemplateOutputHtml_ = function(templateResult) { // Allow strings as long as strict autoescaping is not mandated. Note we // allow everything that isn't an object, because some non-escaping templates // end up returning non-strings if their only print statement is a // non-escaped argument, plus some unit tests spoof templates. // TODO(gboyer): Track down and fix these cases. if (!goog.soy.REQUIRE_STRICT_AUTOESCAPE && !goog.isObject(templateResult)) { return String(templateResult); } // Allow SanitizedContent of kind HTML. if (templateResult instanceof goog.soy.data.SanitizedContent) { templateResult = /** @type {!goog.soy.data.SanitizedContent} */ ( templateResult); var ContentKind = goog.soy.data.SanitizedContentKind; if (templateResult.contentKind === ContentKind.HTML) { return goog.asserts.assertString(templateResult.content); } if (templateResult.contentKind === ContentKind.TEXT) { // Allow text to be rendered, as long as we escape it. Other content // kinds will fail, since we don't know what to do with them. // TODO(gboyer): Perhaps also include URI in this case. return goog.string.htmlEscape(templateResult.content); } } goog.asserts.fail('Soy template output is unsafe for use as HTML: ' + templateResult); // In production, return a safe string, rather than failing hard. return 'zSoyz'; }; /** * Immutable object that is passed into templates that are rendered * without any data. * @type {Object} * @private */ goog.soy.defaultTemplateData_ = {};
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides a soy renderer that allows registration of * injected data ("globals") that will be passed into the rendered * templates. * * There is also an interface {@link goog.soy.InjectedDataSupplier} that * user should implement to provide the injected data for a specific * application. The injected data format is a JavaScript object: * <pre> * {'dataKey': 'value', 'otherDataKey': 'otherValue'} * </pre> * * To use injected data, you need to enable the soy-to-js compiler * option {@code --isUsingIjData}. The injected data can then be * referred to in any soy templates as part of a magic "ij" * parameter. For example, {@code $ij.dataKey} will evaluate to * 'value' with the above injected data. * * @author henrywong@google.com (Henry Wong) * @author chrishenry@google.com (Chris Henry) */ goog.provide('goog.soy.InjectedDataSupplier'); goog.provide('goog.soy.Renderer'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.soy'); goog.require('goog.soy.data.SanitizedContent'); goog.require('goog.soy.data.SanitizedContentKind'); /** * Creates a new soy renderer. Note that the renderer will only be * guaranteed to work correctly within the document scope provided in * the DOM helper. * * @param {goog.soy.InjectedDataSupplier=} opt_injectedDataSupplier A supplier * that provides an injected data. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper; * defaults to that provided by {@code goog.dom.getDomHelper()}. * @constructor */ goog.soy.Renderer = function(opt_injectedDataSupplier, opt_domHelper) { /** * @type {goog.dom.DomHelper} * @private */ this.dom_ = opt_domHelper || goog.dom.getDomHelper(); /** * @type {goog.soy.InjectedDataSupplier} * @private */ this.supplier_ = opt_injectedDataSupplier || null; /** * Map from template name to the data used to render that template. * @type {!goog.soy.Renderer.SavedTemplateRender} * @private */ this.savedTemplateRenders_ = []; }; /** * @typedef {Array.<{template: string, data: Object, ijData: Object}>} */ goog.soy.Renderer.SavedTemplateRender; /** * Renders a Soy template into a single node or a document fragment. * Delegates to {@code goog.soy.renderAsFragment}. * * @param {Function} template The Soy template defining the element's content. * @param {Object=} opt_templateData The data for the template. * @return {!Node} The resulting node or document fragment. */ goog.soy.Renderer.prototype.renderAsFragment = function(template, opt_templateData) { this.saveTemplateRender_(template, opt_templateData); return goog.soy.renderAsFragment(template, opt_templateData, this.getInjectedData_(), this.dom_); }; /** * Renders a Soy template into a single node. If the rendered HTML * string represents a single node, then that node is returned. * Otherwise, a DIV element is returned containing the rendered nodes. * Delegates to {@code goog.soy.renderAsElement}. * * @param {Function} template The Soy template defining the element's content. * @param {Object=} opt_templateData The data for the template. * @return {!Element} Rendered template contents, wrapped in a parent DIV * element if necessary. */ goog.soy.Renderer.prototype.renderAsElement = function(template, opt_templateData) { this.saveTemplateRender_(template, opt_templateData); return goog.soy.renderAsElement(template, opt_templateData, this.getInjectedData_(), this.dom_); }; /** * Renders a Soy template and then set the output string as the * innerHTML of the given element. Delegates to {@code goog.soy.renderElement}. * * @param {Element} element The element whose content we are rendering. * @param {Function} template The Soy template defining the element's content. * @param {Object=} opt_templateData The data for the template. */ goog.soy.Renderer.prototype.renderElement = function(element, template, opt_templateData) { this.saveTemplateRender_(template, opt_templateData); goog.soy.renderElement( element, template, opt_templateData, this.getInjectedData_()); }; /** * Renders a Soy template and returns the output string. * If the template is strict, it must be of kind HTML. To render strict * templates of other kinds, use {@code renderText} (for {@code kind="text"}) or * {@code renderStrict}. * * @param {Function} template The Soy template defining the element's content. * @param {Object=} opt_templateData The data for the template. * @return {string} The return value of rendering the template directly. */ goog.soy.Renderer.prototype.render = function(template, opt_templateData) { var result = template( opt_templateData || {}, undefined, this.getInjectedData_()); goog.asserts.assert(!(result instanceof goog.soy.data.SanitizedContent) || result.contentKind === goog.soy.data.SanitizedContentKind.HTML, 'render was called with a strict template of kind other than "html"' + ' (consider using renderText or renderStrict)'); this.saveTemplateRender_(template, opt_templateData); return String(result); }; /** * Renders a strict Soy template of kind="text" and returns the output string. * It is an error to use renderText on non-strict templates, or strict templates * of kinds other than "text". * * @param {Function} template The Soy template defining the element's content. * @param {Object=} opt_templateData The data for the template. * @return {string} The return value of rendering the template directly. */ goog.soy.Renderer.prototype.renderText = function(template, opt_templateData) { var result = template( opt_templateData || {}, undefined, this.getInjectedData_()); goog.asserts.assertInstanceof(result, goog.soy.data.SanitizedContent, 'renderText cannot be called on a non-strict soy template'); goog.asserts.assert( result.contentKind === goog.soy.data.SanitizedContentKind.TEXT, 'renderText was called with a template of kind other than "text"'); this.saveTemplateRender_(template, opt_templateData); return String(result); }; /** * Renders a strict Soy template and returns the output SanitizedContent object. * * @param {function(Object.<string, *>, (null|undefined), Object.<string, *>): * RETURN_TYPE} template The Soy template to render. * @param {Object=} opt_templateData The data for the template. * @param {goog.soy.data.SanitizedContentKind=} opt_kind The output kind to * assert. If null, the template must be of kind="html" (i.e., opt_kind * defaults to goog.soy.data.SanitizedContentKind.HTML). * @return {RETURN_TYPE} The SanitizedContent object. This return type is * generic based on the return type of the template, such as * soy.SanitizedHtml. * @template RETURN_TYPE */ goog.soy.Renderer.prototype.renderStrict = function( template, opt_templateData, opt_kind) { var result = template( opt_templateData || {}, undefined, this.getInjectedData_()); goog.asserts.assertInstanceof(result, goog.soy.data.SanitizedContent, 'renderStrict cannot be called on a non-strict soy template'); goog.asserts.assert( result.contentKind === (opt_kind || goog.soy.data.SanitizedContentKind.HTML), 'renderStrict was called with the wrong kind of template'); this.saveTemplateRender_(template, opt_templateData); return result; }; /** * @return {!goog.soy.Renderer.SavedTemplateRender} Saved template data for * the renders that have happened so far. */ goog.soy.Renderer.prototype.getSavedTemplateRenders = function() { return this.savedTemplateRenders_; }; /** * Saves information about the current template render for debug purposes. * @param {Function} template The Soy template defining the element's content. * @param {Object=} opt_templateData The data for the template. * @private * @suppress {missingProperties} SoyJs compiler adds soyTemplateName to the * template. */ goog.soy.Renderer.prototype.saveTemplateRender_ = function( template, opt_templateData) { if (goog.DEBUG) { this.savedTemplateRenders_.push({ template: template.soyTemplateName, data: opt_templateData, ijData: this.getInjectedData_() }); } }; /** * Creates the injectedParams map if necessary and calls the configuration * service to prepopulate it. * @return {Object} The injected params. * @private */ goog.soy.Renderer.prototype.getInjectedData_ = function() { return this.supplier_ ? this.supplier_.getData() : {}; }; /** * An interface for a supplier that provides Soy injected data. * @interface */ goog.soy.InjectedDataSupplier = function() {}; /** * Gets the injected data. Implementation may assume that v * {@code goog.soy.Renderer} will treat the returned data as * immutable. The renderer will call this every time one of its * {@code render*} methods is called. * @return {Object} A key-value pair representing the injected data. */ goog.soy.InjectedDataSupplier.prototype.getData = function() {};
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides test helpers for Soy tests. */ /** @suppress {extraProvide} */ goog.provide('goog.soy.testHelper'); goog.setTestOnly('goog.soy.testHelper'); goog.require('goog.dom'); goog.require('goog.soy.data.SanitizedContent'); goog.require('goog.soy.data.SanitizedContentKind'); goog.require('goog.string'); goog.require('goog.userAgent'); goog.require('goog.dom.TagName'); /** * Instantiable subclass of SanitizedContent. * * This is a spoof for sanitized content that isn't robust enough to get * through Soy's escaping functions but is good enough for the checks here. * * @param {string} content The text. * @param {goog.soy.data.SanitizedContentKind} kind The kind of safe content. * @extends {goog.soy.data.SanitizedContent} */ function SanitizedContentSubclass(content, kind) { // IMPORTANT! No superclass chaining to avoid exception being thrown. this.content = content; this.contentKind = kind; } goog.inherits(SanitizedContentSubclass, goog.soy.data.SanitizedContent); function makeSanitizedContent(content, kind) { return new SanitizedContentSubclass(content, kind); } // // Fake Soy-generated template functions. // var example = {}; example.textNodeTemplate = function(opt_data, opt_sb, opt_injectedData) { assertNotNull(opt_data); assertNotUndefined(opt_data); return goog.string.htmlEscape(opt_data.name); }; example.singleRootTemplate = function(opt_data, opt_sb, opt_injectedData) { assertNotNull(opt_data); assertNotUndefined(opt_data); return '<span>' + goog.string.htmlEscape(opt_data.name) + '</span>'; }; example.multiRootTemplate = function(opt_data, opt_sb, opt_injectedData) { assertNotNull(opt_data); assertNotUndefined(opt_data); return '<div>Hello</div><div>' + goog.string.htmlEscape(opt_data.name) + '</div>'; }; example.injectedDataTemplate = function(opt_data, opt_sb, opt_injectedData) { assertNotNull(opt_data); assertNotUndefined(opt_data); return goog.string.htmlEscape(opt_data.name) + goog.string.htmlEscape(opt_injectedData.name); }; example.noDataTemplate = function(opt_data, opt_sb, opt_injectedData) { assertNotNull(opt_data); assertNotUndefined(opt_data); return '<div>Hello</div>'; }; example.sanitizedHtmlTemplate = function(opt_data, opt_sb, opt_injectedData) { // Test the SanitizedContent constructor. return makeSanitizedContent('Hello World', goog.soy.data.SanitizedContentKind.HTML); }; example.sanitizedHtmlAttributesTemplate = function(opt_data, opt_sb, opt_injectedData) { return makeSanitizedContent('foo="bar"', goog.soy.data.SanitizedContentKind.ATTRIBUTES); }; example.sanitizedCssTemplate = function(opt_data, opt_sb, opt_injectedData) { return makeSanitizedContent('display:none', goog.soy.data.SanitizedContentKind.CSS); }; example.unsanitizedTextTemplate = function(opt_data, opt_sb, opt_injectedData) { return makeSanitizedContent('I <3 Puppies & Kittens', goog.soy.data.SanitizedContentKind.TEXT); }; example.templateSpoofingSanitizedContentString = function(opt_data, opt_sb, opt_injectedData) { return makeSanitizedContent('Hello World', // This is to ensure we're using triple-equals against a unique Javascript // object. For example, in Javascript, consider ({}) == '[Object object]' // is true. goog.soy.data.SanitizedContentKind.HTML.toString()); }; // // Test helper functions. // /** * Retrieves the content of document fragment as HTML. * @param {Node} fragment The document fragment. * @return {string} Content of the document fragment as HTML. */ function fragmentToHtml(fragment) { var testDiv = goog.dom.createElement(goog.dom.TagName.DIV); testDiv.appendChild(fragment); return elementToInnerHtml(testDiv); } /** * Retrieves the content of an element as HTML. * @param {Element} elem The element. * @return {string} Content of the element as HTML. */ function elementToInnerHtml(elem) { var innerHtml = elem.innerHTML; if (goog.userAgent.IE) { innerHtml = innerHtml.replace(/DIV/g, 'div').replace(/\s/g, ''); } return innerHtml; }
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Utilities for window manipulation. */ goog.provide('goog.window'); goog.require('goog.string'); goog.require('goog.userAgent'); /** * Default height for popup windows * @type {number} */ goog.window.DEFAULT_POPUP_HEIGHT = 500; /** * Default width for popup windows * @type {number} */ goog.window.DEFAULT_POPUP_WIDTH = 690; /** * Default target for popup windows * @type {string} */ goog.window.DEFAULT_POPUP_TARGET = 'google_popup'; /** * Opens a new window. * * @param {string|Object} linkRef A string or an object that supports toString, * for example goog.Uri. If this is an object with a 'href' attribute, such * as HTMLAnchorElement, it will be used instead. * * @param {Object=} opt_options supports the following options: * 'target': (string) target (window name). If null, linkRef.target will * be used. * 'width': (number) window width. * 'height': (number) window height. * 'top': (number) distance from top of screen * 'left': (number) distance from left of screen * 'toolbar': (boolean) show toolbar * 'scrollbars': (boolean) show scrollbars * 'location': (boolean) show location * 'statusbar': (boolean) show statusbar * 'menubar': (boolean) show menubar * 'resizable': (boolean) resizable * 'noreferrer': (boolean) whether to attempt to remove the referrer header * from the request headers. Does this by opening a blank window that * then redirects to the target url, so users may see some flickering. * * @param {Window=} opt_parentWin Parent window that should be used to open the * new window. * * @return {Window} Returns the window object that was opened. This returns * null if a popup blocker prevented the window from being * opened. */ goog.window.open = function(linkRef, opt_options, opt_parentWin) { if (!opt_options) { opt_options = {}; } var parentWin = opt_parentWin || window; // HTMLAnchorElement has a toString() method with the same behavior as // goog.Uri in all browsers except for Safari, which returns // '[object HTMLAnchorElement]'. We check for the href first, then // assume that it's a goog.Uri or String otherwise. var href = typeof linkRef.href != 'undefined' ? linkRef.href : String(linkRef); var target = opt_options.target || linkRef.target; var sb = []; for (var option in opt_options) { switch (option) { case 'width': case 'height': case 'top': case 'left': sb.push(option + '=' + opt_options[option]); break; case 'target': case 'noreferrer': break; default: sb.push(option + '=' + (opt_options[option] ? 1 : 0)); } } var optionString = sb.join(','); var newWin; if (opt_options['noreferrer']) { // Use a meta-refresh to stop the referrer from being included in the // request headers. newWin = parentWin.open('', target, optionString); if (newWin) { if (goog.userAgent.IE) { // IE has problems parsing the content attribute if the url contains // a semicolon. We can fix this by adding quotes around the url, but // then we can't parse quotes in the URL correctly. We take a // best-effort approach. // // If the URL has semicolons, wrap it in single quotes to protect // the semicolons. // If the URL has semicolons and single quotes, url-encode the single // quotes as well. // // This is imperfect. Notice that both ' and ; are reserved characters // in URIs, so this could do the wrong thing, but at least it will // do the wrong thing in only rare cases. // ugh. if (href.indexOf(';') != -1) { href = "'" + href.replace(/'/g, '%27') + "'"; } } newWin.opener = null; href = goog.string.htmlEscape(href); newWin.document.write('<META HTTP-EQUIV="refresh" content="0; url=' + href + '">'); newWin.document.close(); } } else { newWin = parentWin.open(href, target, optionString); } // newWin is null if a popup blocker prevented the window open. return newWin; }; /** * Opens a new window without any real content in it. * * This can be used to get around popup blockers if you need to open a window * in response to a user event, but need to do asynchronous work to determine * the URL to open, and then set the URL later. * * Example usage: * * var newWin = goog.window.openBlank('Loading...'); * setTimeout( * function() { * newWin.location.href = 'http://www.google.com'; * }, 100); * * @param {string=} opt_message String to show in the new window. This string * will be HTML-escaped to avoid XSS issues. * @param {Object=} opt_options Options to open window with. * {@see goog.window.open for exact option semantics}. * @param {Window=} opt_parentWin Parent window that should be used to open the * new window. * @return {Window} Returns the window object that was opened. This returns * null if a popup blocker prevented the window from being * opened. */ goog.window.openBlank = function(opt_message, opt_options, opt_parentWin) { // Open up a window with the loading message and nothing else. // This will be interpreted as HTML content type with a missing doctype // and html/body tags, but is otherwise acceptable. var loadingMessage = opt_message ? goog.string.htmlEscape(opt_message) : ''; return /** @type {Window} */ (goog.window.open( 'javascript:"' + encodeURI(loadingMessage) + '"', opt_options, opt_parentWin)); }; /** * Raise a help popup window, defaulting to "Google standard" size and name. * * (If your project is using GXPs, consider using {@link PopUpLink.gxp}.) * * @param {string|Object} linkRef if this is a string, it will be used as the * URL of the popped window; otherwise it's assumed to be an HTMLAnchorElement * (or some other object with "target" and "href" properties). * * @param {Object=} opt_options Options to open window with. * {@see goog.window.open for exact option semantics} * Additional wrinkles to the options: * - if 'target' field is null, linkRef.target will be used. If *that's* * null, the default is "google_popup". * - if 'width' field is not specified, the default is 690. * - if 'height' field is not specified, the default is 500. * * @return {boolean} true if the window was not popped up, false if it was. */ goog.window.popup = function(linkRef, opt_options) { if (!opt_options) { opt_options = {}; } // set default properties opt_options['target'] = opt_options['target'] || linkRef['target'] || goog.window.DEFAULT_POPUP_TARGET; opt_options['width'] = opt_options['width'] || goog.window.DEFAULT_POPUP_WIDTH; opt_options['height'] = opt_options['height'] || goog.window.DEFAULT_POPUP_HEIGHT; var newWin = goog.window.open(linkRef, opt_options); if (!newWin) { return true; } newWin.focus(); return false; };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Bootstrap for the Google JS Library (Closure). * * In uncompiled mode base.js will write out Closure's deps file, unless the * global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects to * include their own deps file(s) from different locations. * * * @provideGoog */ /** * @define {boolean} Overridden to true by the compiler when --closure_pass * or --mark_as_compiled is specified. */ var COMPILED = false; /** * Base namespace for the Closure library. Checks to see goog is * already defined in the current scope before assigning to prevent * clobbering if base.js is loaded more than once. * * @const */ var goog = goog || {}; // Identifies this file as the Closure base. /** * Reference to the global context. In most cases this will be 'window'. */ goog.global = this; /** * @define {boolean} DEBUG is provided as a convenience so that debugging code * that should not be included in a production js_binary can be easily stripped * by specifying --define goog.DEBUG=false to the JSCompiler. For example, most * toString() methods should be declared inside an "if (goog.DEBUG)" conditional * because they are generally used for debugging purposes and it is difficult * for the JSCompiler to statically determine whether they are used. */ goog.DEBUG = true; /** * @define {string} LOCALE defines the locale being used for compilation. It is * used to select locale specific data to be compiled in js binary. BUILD rule * can specify this value by "--define goog.LOCALE=<locale_name>" as JSCompiler * option. * * Take into account that the locale code format is important. You should use * the canonical Unicode format with hyphen as a delimiter. Language must be * lowercase, Language Script - Capitalized, Region - UPPERCASE. * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN. * * See more info about locale codes here: * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers * * For language codes you should use values defined by ISO 693-1. See it here * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from * this rule: the Hebrew language. For legacy reasons the old code (iw) should * be used instead of the new code (he), see http://wiki/Main/IIISynonyms. */ goog.LOCALE = 'en'; // default to en /** * @define {boolean} Whether this code is running on trusted sites. * * On untrusted sites, several native functions can be defined or overridden by * external libraries like Prototype, Datejs, and JQuery and setting this flag * to false forces closure to use its own implementations when possible. * * If your javascript can be loaded by a third party site and you are wary about * relying on non-standard implementations, specify * "--define goog.TRUSTED_SITE=false" to the JSCompiler. */ goog.TRUSTED_SITE = true; /** * Creates object stubs for a namespace. The presence of one or more * goog.provide() calls indicate that the file defines the given * objects/namespaces. Build tools also scan for provide/require statements * to discern dependencies, build dependency files (see deps.js), etc. * @see goog.require * @param {string} name Namespace provided by this file in the form * "goog.package.part". */ goog.provide = function(name) { if (!COMPILED) { // Ensure that the same namespace isn't provided twice. This is intended // to teach new developers that 'goog.provide' is effectively a variable // declaration. And when JSCompiler transforms goog.provide into a real // variable declaration, the compiled JS should work the same as the raw // JS--even when the raw JS uses goog.provide incorrectly. if (goog.isProvided_(name)) { throw Error('Namespace "' + name + '" already declared.'); } delete goog.implicitNamespaces_[name]; var namespace = name; while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) { if (goog.getObjectByName(namespace)) { break; } goog.implicitNamespaces_[namespace] = true; } } goog.exportPath_(name); }; /** * Marks that the current file should only be used for testing, and never for * live code in production. * * In the case of unit tests, the message may optionally be an exact * namespace for the test (e.g. 'goog.stringTest'). The linter will then * ignore the extra provide (if not explicitly defined in the code). * * @param {string=} opt_message Optional message to add to the error that's * raised when used in production code. */ goog.setTestOnly = function(opt_message) { if (COMPILED && !goog.DEBUG) { opt_message = opt_message || ''; throw Error('Importing test-only code into non-debug environment' + opt_message ? ': ' + opt_message : '.'); } }; if (!COMPILED) { /** * Check if the given name has been goog.provided. This will return false for * names that are available only as implicit namespaces. * @param {string} name name of the object to look for. * @return {boolean} Whether the name has been provided. * @private */ goog.isProvided_ = function(name) { return !goog.implicitNamespaces_[name] && !!goog.getObjectByName(name); }; /** * Namespaces implicitly defined by goog.provide. For example, * goog.provide('goog.events.Event') implicitly declares * that 'goog' and 'goog.events' must be namespaces. * * @type {Object} * @private */ goog.implicitNamespaces_ = {}; } /** * Builds an object structure for the provided namespace path, * ensuring that names that already exist are not overwritten. For * example: * "a.b.c" -> a = {};a.b={};a.b.c={}; * Used by goog.provide and goog.exportSymbol. * @param {string} name name of the object that this file defines. * @param {*=} opt_object the object to expose at the end of the path. * @param {Object=} opt_objectToExportTo The object to add the path to; default * is |goog.global|. * @private */ goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) { var parts = name.split('.'); var cur = opt_objectToExportTo || goog.global; // Internet Explorer exhibits strange behavior when throwing errors from // methods externed in this manner. See the testExportSymbolExceptions in // base_test.html for an example. if (!(parts[0] in cur) && cur.execScript) { cur.execScript('var ' + parts[0]); } // Certain browsers cannot parse code in the form for((a in b); c;); // This pattern is produced by the JSCompiler when it collapses the // statement above into the conditional loop below. To prevent this from // happening, use a for-loop and reserve the init logic as below. // Parentheses added to eliminate strict JS warning in Firefox. for (var part; parts.length && (part = parts.shift());) { if (!parts.length && goog.isDef(opt_object)) { // last part and we have an object; use it cur[part] = opt_object; } else if (cur[part]) { cur = cur[part]; } else { cur = cur[part] = {}; } } }; /** * Returns an object based on its fully qualified external name. If you are * using a compilation pass that renames property names beware that using this * function will not find renamed properties. * * @param {string} name The fully qualified name. * @param {Object=} opt_obj The object within which to look; default is * |goog.global|. * @return {?} The value (object or primitive) or, if not found, null. */ goog.getObjectByName = function(name, opt_obj) { var parts = name.split('.'); var cur = opt_obj || goog.global; for (var part; part = parts.shift(); ) { if (goog.isDefAndNotNull(cur[part])) { cur = cur[part]; } else { return null; } } return cur; }; /** * Globalizes a whole namespace, such as goog or goog.lang. * * @param {Object} obj The namespace to globalize. * @param {Object=} opt_global The object to add the properties to. * @deprecated Properties may be explicitly exported to the global scope, but * this should no longer be done in bulk. */ goog.globalize = function(obj, opt_global) { var global = opt_global || goog.global; for (var x in obj) { global[x] = obj[x]; } }; /** * Adds a dependency from a file to the files it requires. * @param {string} relPath The path to the js file. * @param {Array} provides An array of strings with the names of the objects * this file provides. * @param {Array} requires An array of strings with the names of the objects * this file requires. */ goog.addDependency = function(relPath, provides, requires) { if (!COMPILED) { var provide, require; var path = relPath.replace(/\\/g, '/'); var deps = goog.dependencies_; for (var i = 0; provide = provides[i]; i++) { deps.nameToPath[provide] = path; if (!(path in deps.pathToNames)) { deps.pathToNames[path] = {}; } deps.pathToNames[path][provide] = true; } for (var j = 0; require = requires[j]; j++) { if (!(path in deps.requires)) { deps.requires[path] = {}; } deps.requires[path][require] = true; } } }; // NOTE(nnaze): The debug DOM loader was included in base.js as an orignal // way to do "debug-mode" development. The dependency system can sometimes // be confusing, as can the debug DOM loader's asyncronous nature. // // With the DOM loader, a call to goog.require() is not blocking -- the // script will not load until some point after the current script. If a // namespace is needed at runtime, it needs to be defined in a previous // script, or loaded via require() with its registered dependencies. // User-defined namespaces may need their own deps file. See http://go/js_deps, // http://go/genjsdeps, or, externally, DepsWriter. // http://code.google.com/closure/library/docs/depswriter.html // // Because of legacy clients, the DOM loader can't be easily removed from // base.js. Work is being done to make it disableable or replaceable for // different environments (DOM-less JavaScript interpreters like Rhino or V8, // for example). See bootstrap/ for more information. /** * @define {boolean} Whether to enable the debug loader. * * If enabled, a call to goog.require() will attempt to load the namespace by * appending a script tag to the DOM (if the namespace has been registered). * * If disabled, goog.require() will simply assert that the namespace has been * provided (and depend on the fact that some outside tool correctly ordered * the script). */ goog.ENABLE_DEBUG_LOADER = true; /** * Implements a system for the dynamic resolution of dependencies * that works in parallel with the BUILD system. Note that all calls * to goog.require will be stripped by the JSCompiler when the * --closure_pass option is used. * @see goog.provide * @param {string} name Namespace to include (as was given in goog.provide()) * in the form "goog.package.part". */ goog.require = function(name) { // if the object already exists we do not need do do anything // TODO(arv): If we start to support require based on file name this has // to change // TODO(arv): If we allow goog.foo.* this has to change // TODO(arv): If we implement dynamic load after page load we should probably // not remove this code for the compiled output if (!COMPILED) { if (goog.isProvided_(name)) { return; } if (goog.ENABLE_DEBUG_LOADER) { var path = goog.getPathFromDeps_(name); if (path) { goog.included_[path] = true; goog.writeScripts_(); return; } } var errorMessage = 'goog.require could not find: ' + name; if (goog.global.console) { goog.global.console['error'](errorMessage); } throw Error(errorMessage); } }; /** * Path for included scripts * @type {string} */ goog.basePath = ''; /** * A hook for overriding the base path. * @type {string|undefined} */ goog.global.CLOSURE_BASE_PATH; /** * Whether to write out Closure's deps file. By default, * the deps are written. * @type {boolean|undefined} */ goog.global.CLOSURE_NO_DEPS; /** * A function to import a single script. This is meant to be overridden when * Closure is being run in non-HTML contexts, such as web workers. It's defined * in the global scope so that it can be set before base.js is loaded, which * allows deps.js to be imported properly. * * The function is passed the script source, which is a relative URI. It should * return true if the script was imported, false otherwise. */ goog.global.CLOSURE_IMPORT_SCRIPT; /** * Null function used for default values of callbacks, etc. * @return {void} Nothing. */ goog.nullFunction = function() {}; /** * The identity function. Returns its first argument. * * @param {*=} opt_returnValue The single value that will be returned. * @param {...*} var_args Optional trailing arguments. These are ignored. * @return {?} The first argument. We can't know the type -- just pass it along * without type. * @deprecated Use goog.functions.identity instead. */ goog.identityFunction = function(opt_returnValue, var_args) { return opt_returnValue; }; /** * When defining a class Foo with an abstract method bar(), you can do: * * Foo.prototype.bar = goog.abstractMethod * * Now if a subclass of Foo fails to override bar(), an error * will be thrown when bar() is invoked. * * Note: This does not take the name of the function to override as * an argument because that would make it more difficult to obfuscate * our JavaScript code. * * @type {!Function} * @throws {Error} when invoked to indicate the method should be * overridden. */ goog.abstractMethod = function() { throw Error('unimplemented abstract method'); }; /** * Adds a {@code getInstance} static method that always return the same instance * object. * @param {!Function} ctor The constructor for the class to add the static * method to. */ goog.addSingletonGetter = function(ctor) { ctor.getInstance = function() { if (ctor.instance_) { return ctor.instance_; } if (goog.DEBUG) { // NOTE: JSCompiler can't optimize away Array#push. goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor; } return ctor.instance_ = new ctor; }; }; /** * All singleton classes that have been instantiated, for testing. Don't read * it directly, use the {@code goog.testing.singleton} module. The compiler * removes this variable if unused. * @type {!Array.<!Function>} * @private */ goog.instantiatedSingletons_ = []; if (!COMPILED && goog.ENABLE_DEBUG_LOADER) { /** * Object used to keep track of urls that have already been added. This * record allows the prevention of circular dependencies. * @type {Object} * @private */ goog.included_ = {}; /** * This object is used to keep track of dependencies and other data that is * used for loading scripts * @private * @type {Object} */ goog.dependencies_ = { pathToNames: {}, // 1 to many nameToPath: {}, // 1 to 1 requires: {}, // 1 to many // used when resolving dependencies to prevent us from // visiting the file twice visited: {}, written: {} // used to keep track of script files we have written }; /** * Tries to detect whether is in the context of an HTML document. * @return {boolean} True if it looks like HTML document. * @private */ goog.inHtmlDocument_ = function() { var doc = goog.global.document; return typeof doc != 'undefined' && 'write' in doc; // XULDocument misses write. }; /** * Tries to detect the base path of the base.js script that bootstraps Closure * @private */ goog.findBasePath_ = function() { if (goog.global.CLOSURE_BASE_PATH) { goog.basePath = goog.global.CLOSURE_BASE_PATH; return; } else if (!goog.inHtmlDocument_()) { return; } var doc = goog.global.document; var scripts = doc.getElementsByTagName('script'); // Search backwards since the current script is in almost all cases the one // that has base.js. for (var i = scripts.length - 1; i >= 0; --i) { var src = scripts[i].src; var qmark = src.lastIndexOf('?'); var l = qmark == -1 ? src.length : qmark; if (src.substr(l - 7, 7) == 'base.js') { goog.basePath = src.substr(0, l - 7); return; } } }; /** * Imports a script if, and only if, that script hasn't already been imported. * (Must be called at execution time) * @param {string} src Script source. * @private */ goog.importScript_ = function(src) { var importScript = goog.global.CLOSURE_IMPORT_SCRIPT || goog.writeScriptTag_; if (!goog.dependencies_.written[src] && importScript(src)) { goog.dependencies_.written[src] = true; } }; /** * The default implementation of the import function. Writes a script tag to * import the script. * * @param {string} src The script source. * @return {boolean} True if the script was imported, false otherwise. * @private */ goog.writeScriptTag_ = function(src) { if (goog.inHtmlDocument_()) { var doc = goog.global.document; // If the user tries to require a new symbol after document load, // something has gone terribly wrong. Doing a document.write would // wipe out the page. if (doc.readyState == 'complete') { // Certain test frameworks load base.js multiple times, which tries // to write deps.js each time. If that happens, just fail silently. // These frameworks wipe the page between each load of base.js, so this // is OK. var isDeps = /\bdeps.js$/.test(src); if (isDeps) { return false; } else { throw Error('Cannot write "' + src + '" after document load'); } } doc.write( '<script type="text/javascript" src="' + src + '"></' + 'script>'); return true; } else { return false; } }; /** * Resolves dependencies based on the dependencies added using addDependency * and calls importScript_ in the correct order. * @private */ goog.writeScripts_ = function() { // the scripts we need to write this time var scripts = []; var seenScript = {}; var deps = goog.dependencies_; function visitNode(path) { if (path in deps.written) { return; } // we have already visited this one. We can get here if we have cyclic // dependencies if (path in deps.visited) { if (!(path in seenScript)) { seenScript[path] = true; scripts.push(path); } return; } deps.visited[path] = true; if (path in deps.requires) { for (var requireName in deps.requires[path]) { // If the required name is defined, we assume that it was already // bootstrapped by other means. if (!goog.isProvided_(requireName)) { if (requireName in deps.nameToPath) { visitNode(deps.nameToPath[requireName]); } else { throw Error('Undefined nameToPath for ' + requireName); } } } } if (!(path in seenScript)) { seenScript[path] = true; scripts.push(path); } } for (var path in goog.included_) { if (!deps.written[path]) { visitNode(path); } } for (var i = 0; i < scripts.length; i++) { if (scripts[i]) { goog.importScript_(goog.basePath + scripts[i]); } else { throw Error('Undefined script input'); } } }; /** * Looks at the dependency rules and tries to determine the script file that * fulfills a particular rule. * @param {string} rule In the form goog.namespace.Class or project.script. * @return {?string} Url corresponding to the rule, or null. * @private */ goog.getPathFromDeps_ = function(rule) { if (rule in goog.dependencies_.nameToPath) { return goog.dependencies_.nameToPath[rule]; } else { return null; } }; goog.findBasePath_(); // Allow projects to manage the deps files themselves. if (!goog.global.CLOSURE_NO_DEPS) { goog.importScript_(goog.basePath + 'deps.js'); } } //============================================================================== // Language Enhancements //============================================================================== /** * This is a "fixed" version of the typeof operator. It differs from the typeof * operator in such a way that null returns 'null' and arrays return 'array'. * @param {*} value The value to get the type of. * @return {string} The name of the type. */ goog.typeOf = function(value) { var s = typeof value; if (s == 'object') { if (value) { // Check these first, so we can avoid calling Object.prototype.toString if // possible. // // IE improperly marshals tyepof across execution contexts, but a // cross-context object will still return false for "instanceof Object". if (value instanceof Array) { return 'array'; } else if (value instanceof Object) { return s; } // HACK: In order to use an Object prototype method on the arbitrary // value, the compiler requires the value be cast to type Object, // even though the ECMA spec explicitly allows it. var className = Object.prototype.toString.call( /** @type {Object} */ (value)); // In Firefox 3.6, attempting to access iframe window objects' length // property throws an NS_ERROR_FAILURE, so we need to special-case it // here. if (className == '[object Window]') { return 'object'; } // We cannot always use constructor == Array or instanceof Array because // different frames have different Array objects. In IE6, if the iframe // where the array was created is destroyed, the array loses its // prototype. Then dereferencing val.splice here throws an exception, so // we can't use goog.isFunction. Calling typeof directly returns 'unknown' // so that will work. In this case, this function will return false and // most array functions will still work because the array is still // array-like (supports length and []) even though it has lost its // prototype. // Mark Miller noticed that Object.prototype.toString // allows access to the unforgeable [[Class]] property. // 15.2.4.2 Object.prototype.toString ( ) // When the toString method is called, the following steps are taken: // 1. Get the [[Class]] property of this object. // 2. Compute a string value by concatenating the three strings // "[object ", Result(1), and "]". // 3. Return Result(2). // and this behavior survives the destruction of the execution context. if ((className == '[object Array]' || // In IE all non value types are wrapped as objects across window // boundaries (not iframe though) so we have to do object detection // for this edge case typeof value.length == 'number' && typeof value.splice != 'undefined' && typeof value.propertyIsEnumerable != 'undefined' && !value.propertyIsEnumerable('splice') )) { return 'array'; } // HACK: There is still an array case that fails. // function ArrayImpostor() {} // ArrayImpostor.prototype = []; // var impostor = new ArrayImpostor; // this can be fixed by getting rid of the fast path // (value instanceof Array) and solely relying on // (value && Object.prototype.toString.vall(value) === '[object Array]') // but that would require many more function calls and is not warranted // unless closure code is receiving objects from untrusted sources. // IE in cross-window calls does not correctly marshal the function type // (it appears just as an object) so we cannot use just typeof val == // 'function'. However, if the object has a call property, it is a // function. if ((className == '[object Function]' || typeof value.call != 'undefined' && typeof value.propertyIsEnumerable != 'undefined' && !value.propertyIsEnumerable('call'))) { return 'function'; } } else { return 'null'; } } else if (s == 'function' && typeof value.call == 'undefined') { // In Safari typeof nodeList returns 'function', and on Firefox // typeof behaves similarly for HTML{Applet,Embed,Object}Elements // and RegExps. We would like to return object for those and we can // detect an invalid function by making sure that the function // object has a call method. return 'object'; } return s; }; /** * Returns true if the specified value is not |undefined|. * WARNING: Do not use this to test if an object has a property. Use the in * operator instead. Additionally, this function assumes that the global * undefined variable has not been redefined. * @param {*} val Variable to test. * @return {boolean} Whether variable is defined. */ goog.isDef = function(val) { return val !== undefined; }; /** * Returns true if the specified value is |null| * @param {*} val Variable to test. * @return {boolean} Whether variable is null. */ goog.isNull = function(val) { return val === null; }; /** * Returns true if the specified value is defined and not null * @param {*} val Variable to test. * @return {boolean} Whether variable is defined and not null. */ goog.isDefAndNotNull = function(val) { // Note that undefined == null. return val != null; }; /** * Returns true if the specified value is an array * @param {*} val Variable to test. * @return {boolean} Whether variable is an array. */ goog.isArray = function(val) { return goog.typeOf(val) == 'array'; }; /** * Returns true if the object looks like an array. To qualify as array like * the value needs to be either a NodeList or an object with a Number length * property. * @param {*} val Variable to test. * @return {boolean} Whether variable is an array. */ goog.isArrayLike = function(val) { var type = goog.typeOf(val); return type == 'array' || type == 'object' && typeof val.length == 'number'; }; /** * Returns true if the object looks like a Date. To qualify as Date-like * the value needs to be an object and have a getFullYear() function. * @param {*} val Variable to test. * @return {boolean} Whether variable is a like a Date. */ goog.isDateLike = function(val) { return goog.isObject(val) && typeof val.getFullYear == 'function'; }; /** * Returns true if the specified value is a string * @param {*} val Variable to test. * @return {boolean} Whether variable is a string. */ goog.isString = function(val) { return typeof val == 'string'; }; /** * Returns true if the specified value is a boolean * @param {*} val Variable to test. * @return {boolean} Whether variable is boolean. */ goog.isBoolean = function(val) { return typeof val == 'boolean'; }; /** * Returns true if the specified value is a number * @param {*} val Variable to test. * @return {boolean} Whether variable is a number. */ goog.isNumber = function(val) { return typeof val == 'number'; }; /** * Returns true if the specified value is a function * @param {*} val Variable to test. * @return {boolean} Whether variable is a function. */ goog.isFunction = function(val) { return goog.typeOf(val) == 'function'; }; /** * Returns true if the specified value is an object. This includes arrays * and functions. * @param {*} val Variable to test. * @return {boolean} Whether variable is an object. */ goog.isObject = function(val) { var type = typeof val; return type == 'object' && val != null || type == 'function'; // return Object(val) === val also works, but is slower, especially if val is // not an object. }; /** * Gets a unique ID for an object. This mutates the object so that further * calls with the same object as a parameter returns the same value. The unique * ID is guaranteed to be unique across the current session amongst objects that * are passed into {@code getUid}. There is no guarantee that the ID is unique * or consistent across sessions. It is unsafe to generate unique ID for * function prototypes. * * @param {Object} obj The object to get the unique ID for. * @return {number} The unique ID for the object. */ goog.getUid = function(obj) { // TODO(arv): Make the type stricter, do not accept null. // In Opera window.hasOwnProperty exists but always returns false so we avoid // using it. As a consequence the unique ID generated for BaseClass.prototype // and SubClass.prototype will be the same. return obj[goog.UID_PROPERTY_] || (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_); }; /** * Removes the unique ID from an object. This is useful if the object was * previously mutated using {@code goog.getUid} in which case the mutation is * undone. * @param {Object} obj The object to remove the unique ID field from. */ goog.removeUid = function(obj) { // TODO(arv): Make the type stricter, do not accept null. // DOM nodes in IE are not instance of Object and throws exception // for delete. Instead we try to use removeAttribute if ('removeAttribute' in obj) { obj.removeAttribute(goog.UID_PROPERTY_); } /** @preserveTry */ try { delete obj[goog.UID_PROPERTY_]; } catch (ex) { } }; /** * Name for unique ID property. Initialized in a way to help avoid collisions * with other closure javascript on the same page. * @type {string} * @private */ goog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0); /** * Counter for UID. * @type {number} * @private */ goog.uidCounter_ = 0; /** * Adds a hash code field to an object. The hash code is unique for the * given object. * @param {Object} obj The object to get the hash code for. * @return {number} The hash code for the object. * @deprecated Use goog.getUid instead. */ goog.getHashCode = goog.getUid; /** * Removes the hash code field from an object. * @param {Object} obj The object to remove the field from. * @deprecated Use goog.removeUid instead. */ goog.removeHashCode = goog.removeUid; /** * Clones a value. The input may be an Object, Array, or basic type. Objects and * arrays will be cloned recursively. * * WARNINGS: * <code>goog.cloneObject</code> does not detect reference loops. Objects that * refer to themselves will cause infinite recursion. * * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies * UIDs created by <code>getUid</code> into cloned results. * * @param {*} obj The value to clone. * @return {*} A clone of the input value. * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods. */ goog.cloneObject = function(obj) { var type = goog.typeOf(obj); if (type == 'object' || type == 'array') { if (obj.clone) { return obj.clone(); } var clone = type == 'array' ? [] : {}; for (var key in obj) { clone[key] = goog.cloneObject(obj[key]); } return clone; } return obj; }; /** * A native implementation of goog.bind. * @param {Function} fn A function to partially apply. * @param {Object|undefined} selfObj Specifies the object which |this| should * point to when the function is run. * @param {...*} var_args Additional arguments that are partially * applied to the function. * @return {!Function} A partially-applied form of the function bind() was * invoked as a method of. * @private * @suppress {deprecated} The compiler thinks that Function.prototype.bind * is deprecated because some people have declared a pure-JS version. * Only the pure-JS version is truly deprecated. */ goog.bindNative_ = function(fn, selfObj, var_args) { return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments)); }; /** * A pure-JS implementation of goog.bind. * @param {Function} fn A function to partially apply. * @param {Object|undefined} selfObj Specifies the object which |this| should * point to when the function is run. * @param {...*} var_args Additional arguments that are partially * applied to the function. * @return {!Function} A partially-applied form of the function bind() was * invoked as a method of. * @private */ goog.bindJs_ = function(fn, selfObj, var_args) { if (!fn) { throw new Error(); } if (arguments.length > 2) { var boundArgs = Array.prototype.slice.call(arguments, 2); return function() { // Prepend the bound arguments to the current arguments. var newArgs = Array.prototype.slice.call(arguments); Array.prototype.unshift.apply(newArgs, boundArgs); return fn.apply(selfObj, newArgs); }; } else { return function() { return fn.apply(selfObj, arguments); }; } }; /** * Partially applies this function to a particular 'this object' and zero or * more arguments. The result is a new function with some arguments of the first * function pre-filled and the value of |this| 'pre-specified'.<br><br> * * Remaining arguments specified at call-time are appended to the pre- * specified ones.<br><br> * * Also see: {@link #partial}.<br><br> * * Usage: * <pre>var barMethBound = bind(myFunction, myObj, 'arg1', 'arg2'); * barMethBound('arg3', 'arg4');</pre> * * @param {?function(this:T, ...)} fn A function to partially apply. * @param {T} selfObj Specifies the object which |this| should * point to when the function is run. * @param {...*} var_args Additional arguments that are partially * applied to the function. * @return {!Function} A partially-applied form of the function bind() was * invoked as a method of. * @template T * @suppress {deprecated} See above. */ goog.bind = function(fn, selfObj, var_args) { // TODO(nicksantos): narrow the type signature. if (Function.prototype.bind && // NOTE(nicksantos): Somebody pulled base.js into the default // Chrome extension environment. This means that for Chrome extensions, // they get the implementation of Function.prototype.bind that // calls goog.bind instead of the native one. Even worse, we don't want // to introduce a circular dependency between goog.bind and // Function.prototype.bind, so we have to hack this to make sure it // works correctly. Function.prototype.bind.toString().indexOf('native code') != -1) { goog.bind = goog.bindNative_; } else { goog.bind = goog.bindJs_; } return goog.bind.apply(null, arguments); }; /** * Like bind(), except that a 'this object' is not required. Useful when the * target function is already bound. * * Usage: * var g = partial(f, arg1, arg2); * g(arg3, arg4); * * @param {Function} fn A function to partially apply. * @param {...*} var_args Additional arguments that are partially * applied to fn. * @return {!Function} A partially-applied form of the function bind() was * invoked as a method of. */ goog.partial = function(fn, var_args) { var args = Array.prototype.slice.call(arguments, 1); return function() { // Prepend the bound arguments to the current arguments. var newArgs = Array.prototype.slice.call(arguments); newArgs.unshift.apply(newArgs, args); return fn.apply(this, newArgs); }; }; /** * Copies all the members of a source object to a target object. This method * does not work on all browsers for all objects that contain keys such as * toString or hasOwnProperty. Use goog.object.extend for this purpose. * @param {Object} target Target. * @param {Object} source Source. */ goog.mixin = function(target, source) { for (var x in source) { target[x] = source[x]; } // For IE7 or lower, the for-in-loop does not contain any properties that are // not enumerable on the prototype object (for example, isPrototypeOf from // Object.prototype) but also it will not include 'replace' on objects that // extend String and change 'replace' (not that it is common for anyone to // extend anything except Object). }; /** * @return {number} An integer value representing the number of milliseconds * between midnight, January 1, 1970 and the current time. */ goog.now = (goog.TRUSTED_SITE && Date.now) || (function() { // Unary plus operator converts its operand to a number which in the case of // a date is done by calling getTime(). return +new Date(); }); /** * Evals javascript in the global scope. In IE this uses execScript, other * browsers use goog.global.eval. If goog.global.eval does not evaluate in the * global scope (for example, in Safari), appends a script tag instead. * Throws an exception if neither execScript or eval is defined. * @param {string} script JavaScript string. */ goog.globalEval = function(script) { if (goog.global.execScript) { goog.global.execScript(script, 'JavaScript'); } else if (goog.global.eval) { // Test to see if eval works if (goog.evalWorksForGlobals_ == null) { goog.global.eval('var _et_ = 1;'); if (typeof goog.global['_et_'] != 'undefined') { delete goog.global['_et_']; goog.evalWorksForGlobals_ = true; } else { goog.evalWorksForGlobals_ = false; } } if (goog.evalWorksForGlobals_) { goog.global.eval(script); } else { var doc = goog.global.document; var scriptElt = doc.createElement('script'); scriptElt.type = 'text/javascript'; scriptElt.defer = false; // Note(user): can't use .innerHTML since "t('<test>')" will fail and // .text doesn't work in Safari 2. Therefore we append a text node. scriptElt.appendChild(doc.createTextNode(script)); doc.body.appendChild(scriptElt); doc.body.removeChild(scriptElt); } } else { throw Error('goog.globalEval not available'); } }; /** * Indicates whether or not we can call 'eval' directly to eval code in the * global scope. Set to a Boolean by the first call to goog.globalEval (which * empirically tests whether eval works for globals). @see goog.globalEval * @type {?boolean} * @private */ goog.evalWorksForGlobals_ = null; /** * Optional map of CSS class names to obfuscated names used with * goog.getCssName(). * @type {Object|undefined} * @private * @see goog.setCssNameMapping */ goog.cssNameMapping_; /** * Optional obfuscation style for CSS class names. Should be set to either * 'BY_WHOLE' or 'BY_PART' if defined. * @type {string|undefined} * @private * @see goog.setCssNameMapping */ goog.cssNameMappingStyle_; /** * Handles strings that are intended to be used as CSS class names. * * This function works in tandem with @see goog.setCssNameMapping. * * Without any mapping set, the arguments are simple joined with a * hyphen and passed through unaltered. * * When there is a mapping, there are two possible styles in which * these mappings are used. In the BY_PART style, each part (i.e. in * between hyphens) of the passed in css name is rewritten according * to the map. In the BY_WHOLE style, the full css name is looked up in * the map directly. If a rewrite is not specified by the map, the * compiler will output a warning. * * When the mapping is passed to the compiler, it will replace calls * to goog.getCssName with the strings from the mapping, e.g. * var x = goog.getCssName('foo'); * var y = goog.getCssName(this.baseClass, 'active'); * becomes: * var x= 'foo'; * var y = this.baseClass + '-active'; * * If one argument is passed it will be processed, if two are passed * only the modifier will be processed, as it is assumed the first * argument was generated as a result of calling goog.getCssName. * * @param {string} className The class name. * @param {string=} opt_modifier A modifier to be appended to the class name. * @return {string} The class name or the concatenation of the class name and * the modifier. */ goog.getCssName = function(className, opt_modifier) { var getMapping = function(cssName) { return goog.cssNameMapping_[cssName] || cssName; }; var renameByParts = function(cssName) { // Remap all the parts individually. var parts = cssName.split('-'); var mapped = []; for (var i = 0; i < parts.length; i++) { mapped.push(getMapping(parts[i])); } return mapped.join('-'); }; var rename; if (goog.cssNameMapping_) { rename = goog.cssNameMappingStyle_ == 'BY_WHOLE' ? getMapping : renameByParts; } else { rename = function(a) { return a; }; } if (opt_modifier) { return className + '-' + rename(opt_modifier); } else { return rename(className); } }; /** * Sets the map to check when returning a value from goog.getCssName(). Example: * <pre> * goog.setCssNameMapping({ * "goog": "a", * "disabled": "b", * }); * * var x = goog.getCssName('goog'); * // The following evaluates to: "a a-b". * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled') * </pre> * When declared as a map of string literals to string literals, the JSCompiler * will replace all calls to goog.getCssName() using the supplied map if the * --closure_pass flag is set. * * @param {!Object} mapping A map of strings to strings where keys are possible * arguments to goog.getCssName() and values are the corresponding values * that should be returned. * @param {string=} opt_style The style of css name mapping. There are two valid * options: 'BY_PART', and 'BY_WHOLE'. * @see goog.getCssName for a description. */ goog.setCssNameMapping = function(mapping, opt_style) { goog.cssNameMapping_ = mapping; goog.cssNameMappingStyle_ = opt_style; }; /** * To use CSS renaming in compiled mode, one of the input files should have a * call to goog.setCssNameMapping() with an object literal that the JSCompiler * can extract and use to replace all calls to goog.getCssName(). In uncompiled * mode, JavaScript code should be loaded before this base.js file that declares * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is * to ensure that the mapping is loaded before any calls to goog.getCssName() * are made in uncompiled mode. * * A hook for overriding the CSS name mapping. * @type {Object|undefined} */ goog.global.CLOSURE_CSS_NAME_MAPPING; if (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) { // This does not call goog.setCssNameMapping() because the JSCompiler // requires that goog.setCssNameMapping() be called with an object literal. goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING; } /** * Gets a localized message. * * This function is a compiler primitive. If you give the compiler a localized * message bundle, it will replace the string at compile-time with a localized * version, and expand goog.getMsg call to a concatenated string. * * Messages must be initialized in the form: * <code> * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'}); * </code> * * @param {string} str Translatable string, places holders in the form {$foo}. * @param {Object=} opt_values Map of place holder name to value. * @return {string} message with placeholders filled. */ goog.getMsg = function(str, opt_values) { var values = opt_values || {}; for (var key in values) { var value = ('' + values[key]).replace(/\$/g, '$$$$'); str = str.replace(new RegExp('\\{\\$' + key + '\\}', 'gi'), value); } return str; }; /** * Gets a localized message. If the message does not have a translation, gives a * fallback message. * * This is useful when introducing a new message that has not yet been * translated into all languages. * * This function is a compiler primtive. Must be used in the form: * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code> * where MSG_A and MSG_B were initialized with goog.getMsg. * * @param {string} a The preferred message. * @param {string} b The fallback message. * @return {string} The best translated message. */ goog.getMsgWithFallback = function(a, b) { return a; }; /** * Exposes an unobfuscated global namespace path for the given object. * Note that fields of the exported object *will* be obfuscated, * unless they are exported in turn via this function or * goog.exportProperty * * <p>Also handy for making public items that are defined in anonymous * closures. * * ex. goog.exportSymbol('public.path.Foo', Foo); * * ex. goog.exportSymbol('public.path.Foo.staticFunction', * Foo.staticFunction); * public.path.Foo.staticFunction(); * * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod', * Foo.prototype.myMethod); * new public.path.Foo().myMethod(); * * @param {string} publicPath Unobfuscated name to export. * @param {*} object Object the name should point to. * @param {Object=} opt_objectToExportTo The object to add the path to; default * is |goog.global|. */ goog.exportSymbol = function(publicPath, object, opt_objectToExportTo) { goog.exportPath_(publicPath, object, opt_objectToExportTo); }; /** * Exports a property unobfuscated into the object's namespace. * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction); * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod); * @param {Object} object Object whose static property is being exported. * @param {string} publicName Unobfuscated name to export. * @param {*} symbol Object the name should point to. */ goog.exportProperty = function(object, publicName, symbol) { object[publicName] = symbol; }; /** * Inherit the prototype methods from one constructor into another. * * Usage: * <pre> * function ParentClass(a, b) { } * ParentClass.prototype.foo = function(a) { } * * function ChildClass(a, b, c) { * goog.base(this, a, b); * } * goog.inherits(ChildClass, ParentClass); * * var child = new ChildClass('a', 'b', 'see'); * child.foo(); // works * </pre> * * In addition, a superclass' implementation of a method can be invoked * as follows: * * <pre> * ChildClass.prototype.foo = function(a) { * ChildClass.superClass_.foo.call(this, a); * // other code * }; * </pre> * * @param {Function} childCtor Child class. * @param {Function} parentCtor Parent class. */ goog.inherits = function(childCtor, parentCtor) { /** @constructor */ function tempCtor() {}; tempCtor.prototype = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype; childCtor.prototype = new tempCtor(); /** @override */ childCtor.prototype.constructor = childCtor; }; /** * Call up to the superclass. * * If this is called from a constructor, then this calls the superclass * contructor with arguments 1-N. * * If this is called from a prototype method, then you must pass * the name of the method as the second argument to this function. If * you do not, you will get a runtime error. This calls the superclass' * method with arguments 2-N. * * This function only works if you use goog.inherits to express * inheritance relationships between your classes. * * This function is a compiler primitive. At compile-time, the * compiler will do macro expansion to remove a lot of * the extra overhead that this function introduces. The compiler * will also enforce a lot of the assumptions that this function * makes, and treat it as a compiler error if you break them. * * @param {!Object} me Should always be "this". * @param {*=} opt_methodName The method name if calling a super method. * @param {...*} var_args The rest of the arguments. * @return {*} The return value of the superclass method. */ goog.base = function(me, opt_methodName, var_args) { var caller = arguments.callee.caller; if (caller.superClass_) { // This is a constructor. Call the superclass constructor. return caller.superClass_.constructor.apply( me, Array.prototype.slice.call(arguments, 1)); } var args = Array.prototype.slice.call(arguments, 2); var foundCaller = false; for (var ctor = me.constructor; ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) { if (ctor.prototype[opt_methodName] === caller) { foundCaller = true; } else if (foundCaller) { return ctor.prototype[opt_methodName].apply(me, args); } } // If we did not find the caller in the prototype chain, // then one of two things happened: // 1) The caller is an instance method. // 2) This method was not called by the right caller. if (me[opt_methodName] === caller) { return me.constructor.prototype[opt_methodName].apply(me, args); } else { throw Error( 'goog.base called from a method of one name ' + 'to a method of a different name'); } }; /** * Allow for aliasing within scope functions. This function exists for * uncompiled code - in compiled code the calls will be inlined and the * aliases applied. In uncompiled code the function is simply run since the * aliases as written are valid JavaScript. * @param {function()} fn Function to call. This function can contain aliases * to namespaces (e.g. "var dom = goog.dom") or classes * (e.g. "var Timer = goog.Timer"). */ goog.scope = function(fn) { fn.call(goog.global); };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Constants used by the WebGL rendering, including all of the * constants used from the WebGL context. For example, instead of using * context.ARRAY_BUFFER, your code can use * goog.webgl.ARRAY_BUFFER. The benefits for doing this include allowing * the compiler to optimize your code so that the compiled code does not have to * contain large strings to reference these properties, and reducing runtime * property access. * * Values are taken from the WebGL Spec: * https://www.khronos.org/registry/webgl/specs/1.0/#WEBGLRENDERINGCONTEXT */ goog.provide('goog.webgl'); /** * @const * @type {number} */ goog.webgl.DEPTH_BUFFER_BIT = 0x00000100; /** * @const * @type {number} */ goog.webgl.STENCIL_BUFFER_BIT = 0x00000400; /** * @const * @type {number} */ goog.webgl.COLOR_BUFFER_BIT = 0x00004000; /** * @const * @type {number} */ goog.webgl.POINTS = 0x0000; /** * @const * @type {number} */ goog.webgl.LINES = 0x0001; /** * @const * @type {number} */ goog.webgl.LINE_LOOP = 0x0002; /** * @const * @type {number} */ goog.webgl.LINE_STRIP = 0x0003; /** * @const * @type {number} */ goog.webgl.TRIANGLES = 0x0004; /** * @const * @type {number} */ goog.webgl.TRIANGLE_STRIP = 0x0005; /** * @const * @type {number} */ goog.webgl.TRIANGLE_FAN = 0x0006; /** * @const * @type {number} */ goog.webgl.ZERO = 0; /** * @const * @type {number} */ goog.webgl.ONE = 1; /** * @const * @type {number} */ goog.webgl.SRC_COLOR = 0x0300; /** * @const * @type {number} */ goog.webgl.ONE_MINUS_SRC_COLOR = 0x0301; /** * @const * @type {number} */ goog.webgl.SRC_ALPHA = 0x0302; /** * @const * @type {number} */ goog.webgl.ONE_MINUS_SRC_ALPHA = 0x0303; /** * @const * @type {number} */ goog.webgl.DST_ALPHA = 0x0304; /** * @const * @type {number} */ goog.webgl.ONE_MINUS_DST_ALPHA = 0x0305; /** * @const * @type {number} */ goog.webgl.DST_COLOR = 0x0306; /** * @const * @type {number} */ goog.webgl.ONE_MINUS_DST_COLOR = 0x0307; /** * @const * @type {number} */ goog.webgl.SRC_ALPHA_SATURATE = 0x0308; /** * @const * @type {number} */ goog.webgl.FUNC_ADD = 0x8006; /** * @const * @type {number} */ goog.webgl.BLEND_EQUATION = 0x8009; /** * Same as BLEND_EQUATION * @const * @type {number} */ goog.webgl.BLEND_EQUATION_RGB = 0x8009; /** * @const * @type {number} */ goog.webgl.BLEND_EQUATION_ALPHA = 0x883D; /** * @const * @type {number} */ goog.webgl.FUNC_SUBTRACT = 0x800A; /** * @const * @type {number} */ goog.webgl.FUNC_REVERSE_SUBTRACT = 0x800B; /** * @const * @type {number} */ goog.webgl.BLEND_DST_RGB = 0x80C8; /** * @const * @type {number} */ goog.webgl.BLEND_SRC_RGB = 0x80C9; /** * @const * @type {number} */ goog.webgl.BLEND_DST_ALPHA = 0x80CA; /** * @const * @type {number} */ goog.webgl.BLEND_SRC_ALPHA = 0x80CB; /** * @const * @type {number} */ goog.webgl.CONSTANT_COLOR = 0x8001; /** * @const * @type {number} */ goog.webgl.ONE_MINUS_CONSTANT_COLOR = 0x8002; /** * @const * @type {number} */ goog.webgl.CONSTANT_ALPHA = 0x8003; /** * @const * @type {number} */ goog.webgl.ONE_MINUS_CONSTANT_ALPHA = 0x8004; /** * @const * @type {number} */ goog.webgl.BLEND_COLOR = 0x8005; /** * @const * @type {number} */ goog.webgl.ARRAY_BUFFER = 0x8892; /** * @const * @type {number} */ goog.webgl.ELEMENT_ARRAY_BUFFER = 0x8893; /** * @const * @type {number} */ goog.webgl.ARRAY_BUFFER_BINDING = 0x8894; /** * @const * @type {number} */ goog.webgl.ELEMENT_ARRAY_BUFFER_BINDING = 0x8895; /** * @const * @type {number} */ goog.webgl.STREAM_DRAW = 0x88E0; /** * @const * @type {number} */ goog.webgl.STATIC_DRAW = 0x88E4; /** * @const * @type {number} */ goog.webgl.DYNAMIC_DRAW = 0x88E8; /** * @const * @type {number} */ goog.webgl.BUFFER_SIZE = 0x8764; /** * @const * @type {number} */ goog.webgl.BUFFER_USAGE = 0x8765; /** * @const * @type {number} */ goog.webgl.CURRENT_VERTEX_ATTRIB = 0x8626; /** * @const * @type {number} */ goog.webgl.FRONT = 0x0404; /** * @const * @type {number} */ goog.webgl.BACK = 0x0405; /** * @const * @type {number} */ goog.webgl.FRONT_AND_BACK = 0x0408; /** * @const * @type {number} */ goog.webgl.CULL_FACE = 0x0B44; /** * @const * @type {number} */ goog.webgl.BLEND = 0x0BE2; /** * @const * @type {number} */ goog.webgl.DITHER = 0x0BD0; /** * @const * @type {number} */ goog.webgl.STENCIL_TEST = 0x0B90; /** * @const * @type {number} */ goog.webgl.DEPTH_TEST = 0x0B71; /** * @const * @type {number} */ goog.webgl.SCISSOR_TEST = 0x0C11; /** * @const * @type {number} */ goog.webgl.POLYGON_OFFSET_FILL = 0x8037; /** * @const * @type {number} */ goog.webgl.SAMPLE_ALPHA_TO_COVERAGE = 0x809E; /** * @const * @type {number} */ goog.webgl.SAMPLE_COVERAGE = 0x80A0; /** * @const * @type {number} */ goog.webgl.NO_ERROR = 0; /** * @const * @type {number} */ goog.webgl.INVALID_ENUM = 0x0500; /** * @const * @type {number} */ goog.webgl.INVALID_VALUE = 0x0501; /** * @const * @type {number} */ goog.webgl.INVALID_OPERATION = 0x0502; /** * @const * @type {number} */ goog.webgl.OUT_OF_MEMORY = 0x0505; /** * @const * @type {number} */ goog.webgl.CW = 0x0900; /** * @const * @type {number} */ goog.webgl.CCW = 0x0901; /** * @const * @type {number} */ goog.webgl.LINE_WIDTH = 0x0B21; /** * @const * @type {number} */ goog.webgl.ALIASED_POINT_SIZE_RANGE = 0x846D; /** * @const * @type {number} */ goog.webgl.ALIASED_LINE_WIDTH_RANGE = 0x846E; /** * @const * @type {number} */ goog.webgl.CULL_FACE_MODE = 0x0B45; /** * @const * @type {number} */ goog.webgl.FRONT_FACE = 0x0B46; /** * @const * @type {number} */ goog.webgl.DEPTH_RANGE = 0x0B70; /** * @const * @type {number} */ goog.webgl.DEPTH_WRITEMASK = 0x0B72; /** * @const * @type {number} */ goog.webgl.DEPTH_CLEAR_VALUE = 0x0B73; /** * @const * @type {number} */ goog.webgl.DEPTH_FUNC = 0x0B74; /** * @const * @type {number} */ goog.webgl.STENCIL_CLEAR_VALUE = 0x0B91; /** * @const * @type {number} */ goog.webgl.STENCIL_FUNC = 0x0B92; /** * @const * @type {number} */ goog.webgl.STENCIL_FAIL = 0x0B94; /** * @const * @type {number} */ goog.webgl.STENCIL_PASS_DEPTH_FAIL = 0x0B95; /** * @const * @type {number} */ goog.webgl.STENCIL_PASS_DEPTH_PASS = 0x0B96; /** * @const * @type {number} */ goog.webgl.STENCIL_REF = 0x0B97; /** * @const * @type {number} */ goog.webgl.STENCIL_VALUE_MASK = 0x0B93; /** * @const * @type {number} */ goog.webgl.STENCIL_WRITEMASK = 0x0B98; /** * @const * @type {number} */ goog.webgl.STENCIL_BACK_FUNC = 0x8800; /** * @const * @type {number} */ goog.webgl.STENCIL_BACK_FAIL = 0x8801; /** * @const * @type {number} */ goog.webgl.STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802; /** * @const * @type {number} */ goog.webgl.STENCIL_BACK_PASS_DEPTH_PASS = 0x8803; /** * @const * @type {number} */ goog.webgl.STENCIL_BACK_REF = 0x8CA3; /** * @const * @type {number} */ goog.webgl.STENCIL_BACK_VALUE_MASK = 0x8CA4; /** * @const * @type {number} */ goog.webgl.STENCIL_BACK_WRITEMASK = 0x8CA5; /** * @const * @type {number} */ goog.webgl.VIEWPORT = 0x0BA2; /** * @const * @type {number} */ goog.webgl.SCISSOR_BOX = 0x0C10; /** * @const * @type {number} */ goog.webgl.COLOR_CLEAR_VALUE = 0x0C22; /** * @const * @type {number} */ goog.webgl.COLOR_WRITEMASK = 0x0C23; /** * @const * @type {number} */ goog.webgl.UNPACK_ALIGNMENT = 0x0CF5; /** * @const * @type {number} */ goog.webgl.PACK_ALIGNMENT = 0x0D05; /** * @const * @type {number} */ goog.webgl.MAX_TEXTURE_SIZE = 0x0D33; /** * @const * @type {number} */ goog.webgl.MAX_VIEWPORT_DIMS = 0x0D3A; /** * @const * @type {number} */ goog.webgl.SUBPIXEL_BITS = 0x0D50; /** * @const * @type {number} */ goog.webgl.RED_BITS = 0x0D52; /** * @const * @type {number} */ goog.webgl.GREEN_BITS = 0x0D53; /** * @const * @type {number} */ goog.webgl.BLUE_BITS = 0x0D54; /** * @const * @type {number} */ goog.webgl.ALPHA_BITS = 0x0D55; /** * @const * @type {number} */ goog.webgl.DEPTH_BITS = 0x0D56; /** * @const * @type {number} */ goog.webgl.STENCIL_BITS = 0x0D57; /** * @const * @type {number} */ goog.webgl.POLYGON_OFFSET_UNITS = 0x2A00; /** * @const * @type {number} */ goog.webgl.POLYGON_OFFSET_FACTOR = 0x8038; /** * @const * @type {number} */ goog.webgl.TEXTURE_BINDING_2D = 0x8069; /** * @const * @type {number} */ goog.webgl.SAMPLE_BUFFERS = 0x80A8; /** * @const * @type {number} */ goog.webgl.SAMPLES = 0x80A9; /** * @const * @type {number} */ goog.webgl.SAMPLE_COVERAGE_VALUE = 0x80AA; /** * @const * @type {number} */ goog.webgl.SAMPLE_COVERAGE_INVERT = 0x80AB; /** * @const * @type {number} */ goog.webgl.COMPRESSED_TEXTURE_FORMATS = 0x86A3; /** * @const * @type {number} */ goog.webgl.DONT_CARE = 0x1100; /** * @const * @type {number} */ goog.webgl.FASTEST = 0x1101; /** * @const * @type {number} */ goog.webgl.NICEST = 0x1102; /** * @const * @type {number} */ goog.webgl.GENERATE_MIPMAP_HINT = 0x8192; /** * @const * @type {number} */ goog.webgl.BYTE = 0x1400; /** * @const * @type {number} */ goog.webgl.UNSIGNED_BYTE = 0x1401; /** * @const * @type {number} */ goog.webgl.SHORT = 0x1402; /** * @const * @type {number} */ goog.webgl.UNSIGNED_SHORT = 0x1403; /** * @const * @type {number} */ goog.webgl.INT = 0x1404; /** * @const * @type {number} */ goog.webgl.UNSIGNED_INT = 0x1405; /** * @const * @type {number} */ goog.webgl.FLOAT = 0x1406; /** * @const * @type {number} */ goog.webgl.DEPTH_COMPONENT = 0x1902; /** * @const * @type {number} */ goog.webgl.ALPHA = 0x1906; /** * @const * @type {number} */ goog.webgl.RGB = 0x1907; /** * @const * @type {number} */ goog.webgl.RGBA = 0x1908; /** * @const * @type {number} */ goog.webgl.LUMINANCE = 0x1909; /** * @const * @type {number} */ goog.webgl.LUMINANCE_ALPHA = 0x190A; /** * @const * @type {number} */ goog.webgl.UNSIGNED_SHORT_4_4_4_4 = 0x8033; /** * @const * @type {number} */ goog.webgl.UNSIGNED_SHORT_5_5_5_1 = 0x8034; /** * @const * @type {number} */ goog.webgl.UNSIGNED_SHORT_5_6_5 = 0x8363; /** * @const * @type {number} */ goog.webgl.FRAGMENT_SHADER = 0x8B30; /** * @const * @type {number} */ goog.webgl.VERTEX_SHADER = 0x8B31; /** * @const * @type {number} */ goog.webgl.MAX_VERTEX_ATTRIBS = 0x8869; /** * @const * @type {number} */ goog.webgl.MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB; /** * @const * @type {number} */ goog.webgl.MAX_VARYING_VECTORS = 0x8DFC; /** * @const * @type {number} */ goog.webgl.MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D; /** * @const * @type {number} */ goog.webgl.MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C; /** * @const * @type {number} */ goog.webgl.MAX_TEXTURE_IMAGE_UNITS = 0x8872; /** * @const * @type {number} */ goog.webgl.MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD; /** * @const * @type {number} */ goog.webgl.SHADER_TYPE = 0x8B4F; /** * @const * @type {number} */ goog.webgl.DELETE_STATUS = 0x8B80; /** * @const * @type {number} */ goog.webgl.LINK_STATUS = 0x8B82; /** * @const * @type {number} */ goog.webgl.VALIDATE_STATUS = 0x8B83; /** * @const * @type {number} */ goog.webgl.ATTACHED_SHADERS = 0x8B85; /** * @const * @type {number} */ goog.webgl.ACTIVE_UNIFORMS = 0x8B86; /** * @const * @type {number} */ goog.webgl.ACTIVE_ATTRIBUTES = 0x8B89; /** * @const * @type {number} */ goog.webgl.SHADING_LANGUAGE_VERSION = 0x8B8C; /** * @const * @type {number} */ goog.webgl.CURRENT_PROGRAM = 0x8B8D; /** * @const * @type {number} */ goog.webgl.NEVER = 0x0200; /** * @const * @type {number} */ goog.webgl.LESS = 0x0201; /** * @const * @type {number} */ goog.webgl.EQUAL = 0x0202; /** * @const * @type {number} */ goog.webgl.LEQUAL = 0x0203; /** * @const * @type {number} */ goog.webgl.GREATER = 0x0204; /** * @const * @type {number} */ goog.webgl.NOTEQUAL = 0x0205; /** * @const * @type {number} */ goog.webgl.GEQUAL = 0x0206; /** * @const * @type {number} */ goog.webgl.ALWAYS = 0x0207; /** * @const * @type {number} */ goog.webgl.KEEP = 0x1E00; /** * @const * @type {number} */ goog.webgl.REPLACE = 0x1E01; /** * @const * @type {number} */ goog.webgl.INCR = 0x1E02; /** * @const * @type {number} */ goog.webgl.DECR = 0x1E03; /** * @const * @type {number} */ goog.webgl.INVERT = 0x150A; /** * @const * @type {number} */ goog.webgl.INCR_WRAP = 0x8507; /** * @const * @type {number} */ goog.webgl.DECR_WRAP = 0x8508; /** * @const * @type {number} */ goog.webgl.VENDOR = 0x1F00; /** * @const * @type {number} */ goog.webgl.RENDERER = 0x1F01; /** * @const * @type {number} */ goog.webgl.VERSION = 0x1F02; /** * @const * @type {number} */ goog.webgl.NEAREST = 0x2600; /** * @const * @type {number} */ goog.webgl.LINEAR = 0x2601; /** * @const * @type {number} */ goog.webgl.NEAREST_MIPMAP_NEAREST = 0x2700; /** * @const * @type {number} */ goog.webgl.LINEAR_MIPMAP_NEAREST = 0x2701; /** * @const * @type {number} */ goog.webgl.NEAREST_MIPMAP_LINEAR = 0x2702; /** * @const * @type {number} */ goog.webgl.LINEAR_MIPMAP_LINEAR = 0x2703; /** * @const * @type {number} */ goog.webgl.TEXTURE_MAG_FILTER = 0x2800; /** * @const * @type {number} */ goog.webgl.TEXTURE_MIN_FILTER = 0x2801; /** * @const * @type {number} */ goog.webgl.TEXTURE_WRAP_S = 0x2802; /** * @const * @type {number} */ goog.webgl.TEXTURE_WRAP_T = 0x2803; /** * @const * @type {number} */ goog.webgl.TEXTURE_2D = 0x0DE1; /** * @const * @type {number} */ goog.webgl.TEXTURE = 0x1702; /** * @const * @type {number} */ goog.webgl.TEXTURE_CUBE_MAP = 0x8513; /** * @const * @type {number} */ goog.webgl.TEXTURE_BINDING_CUBE_MAP = 0x8514; /** * @const * @type {number} */ goog.webgl.TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515; /** * @const * @type {number} */ goog.webgl.TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516; /** * @const * @type {number} */ goog.webgl.TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517; /** * @const * @type {number} */ goog.webgl.TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518; /** * @const * @type {number} */ goog.webgl.TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519; /** * @const * @type {number} */ goog.webgl.TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A; /** * @const * @type {number} */ goog.webgl.MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C; /** * @const * @type {number} */ goog.webgl.TEXTURE0 = 0x84C0; /** * @const * @type {number} */ goog.webgl.TEXTURE1 = 0x84C1; /** * @const * @type {number} */ goog.webgl.TEXTURE2 = 0x84C2; /** * @const * @type {number} */ goog.webgl.TEXTURE3 = 0x84C3; /** * @const * @type {number} */ goog.webgl.TEXTURE4 = 0x84C4; /** * @const * @type {number} */ goog.webgl.TEXTURE5 = 0x84C5; /** * @const * @type {number} */ goog.webgl.TEXTURE6 = 0x84C6; /** * @const * @type {number} */ goog.webgl.TEXTURE7 = 0x84C7; /** * @const * @type {number} */ goog.webgl.TEXTURE8 = 0x84C8; /** * @const * @type {number} */ goog.webgl.TEXTURE9 = 0x84C9; /** * @const * @type {number} */ goog.webgl.TEXTURE10 = 0x84CA; /** * @const * @type {number} */ goog.webgl.TEXTURE11 = 0x84CB; /** * @const * @type {number} */ goog.webgl.TEXTURE12 = 0x84CC; /** * @const * @type {number} */ goog.webgl.TEXTURE13 = 0x84CD; /** * @const * @type {number} */ goog.webgl.TEXTURE14 = 0x84CE; /** * @const * @type {number} */ goog.webgl.TEXTURE15 = 0x84CF; /** * @const * @type {number} */ goog.webgl.TEXTURE16 = 0x84D0; /** * @const * @type {number} */ goog.webgl.TEXTURE17 = 0x84D1; /** * @const * @type {number} */ goog.webgl.TEXTURE18 = 0x84D2; /** * @const * @type {number} */ goog.webgl.TEXTURE19 = 0x84D3; /** * @const * @type {number} */ goog.webgl.TEXTURE20 = 0x84D4; /** * @const * @type {number} */ goog.webgl.TEXTURE21 = 0x84D5; /** * @const * @type {number} */ goog.webgl.TEXTURE22 = 0x84D6; /** * @const * @type {number} */ goog.webgl.TEXTURE23 = 0x84D7; /** * @const * @type {number} */ goog.webgl.TEXTURE24 = 0x84D8; /** * @const * @type {number} */ goog.webgl.TEXTURE25 = 0x84D9; /** * @const * @type {number} */ goog.webgl.TEXTURE26 = 0x84DA; /** * @const * @type {number} */ goog.webgl.TEXTURE27 = 0x84DB; /** * @const * @type {number} */ goog.webgl.TEXTURE28 = 0x84DC; /** * @const * @type {number} */ goog.webgl.TEXTURE29 = 0x84DD; /** * @const * @type {number} */ goog.webgl.TEXTURE30 = 0x84DE; /** * @const * @type {number} */ goog.webgl.TEXTURE31 = 0x84DF; /** * @const * @type {number} */ goog.webgl.ACTIVE_TEXTURE = 0x84E0; /** * @const * @type {number} */ goog.webgl.REPEAT = 0x2901; /** * @const * @type {number} */ goog.webgl.CLAMP_TO_EDGE = 0x812F; /** * @const * @type {number} */ goog.webgl.MIRRORED_REPEAT = 0x8370; /** * @const * @type {number} */ goog.webgl.FLOAT_VEC2 = 0x8B50; /** * @const * @type {number} */ goog.webgl.FLOAT_VEC3 = 0x8B51; /** * @const * @type {number} */ goog.webgl.FLOAT_VEC4 = 0x8B52; /** * @const * @type {number} */ goog.webgl.INT_VEC2 = 0x8B53; /** * @const * @type {number} */ goog.webgl.INT_VEC3 = 0x8B54; /** * @const * @type {number} */ goog.webgl.INT_VEC4 = 0x8B55; /** * @const * @type {number} */ goog.webgl.BOOL = 0x8B56; /** * @const * @type {number} */ goog.webgl.BOOL_VEC2 = 0x8B57; /** * @const * @type {number} */ goog.webgl.BOOL_VEC3 = 0x8B58; /** * @const * @type {number} */ goog.webgl.BOOL_VEC4 = 0x8B59; /** * @const * @type {number} */ goog.webgl.FLOAT_MAT2 = 0x8B5A; /** * @const * @type {number} */ goog.webgl.FLOAT_MAT3 = 0x8B5B; /** * @const * @type {number} */ goog.webgl.FLOAT_MAT4 = 0x8B5C; /** * @const * @type {number} */ goog.webgl.SAMPLER_2D = 0x8B5E; /** * @const * @type {number} */ goog.webgl.SAMPLER_CUBE = 0x8B60; /** * @const * @type {number} */ goog.webgl.VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622; /** * @const * @type {number} */ goog.webgl.VERTEX_ATTRIB_ARRAY_SIZE = 0x8623; /** * @const * @type {number} */ goog.webgl.VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624; /** * @const * @type {number} */ goog.webgl.VERTEX_ATTRIB_ARRAY_TYPE = 0x8625; /** * @const * @type {number} */ goog.webgl.VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A; /** * @const * @type {number} */ goog.webgl.VERTEX_ATTRIB_ARRAY_POINTER = 0x8645; /** * @const * @type {number} */ goog.webgl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F; /** * @const * @type {number} */ goog.webgl.COMPILE_STATUS = 0x8B81; /** * @const * @type {number} */ goog.webgl.LOW_FLOAT = 0x8DF0; /** * @const * @type {number} */ goog.webgl.MEDIUM_FLOAT = 0x8DF1; /** * @const * @type {number} */ goog.webgl.HIGH_FLOAT = 0x8DF2; /** * @const * @type {number} */ goog.webgl.LOW_INT = 0x8DF3; /** * @const * @type {number} */ goog.webgl.MEDIUM_INT = 0x8DF4; /** * @const * @type {number} */ goog.webgl.HIGH_INT = 0x8DF5; /** * @const * @type {number} */ goog.webgl.FRAMEBUFFER = 0x8D40; /** * @const * @type {number} */ goog.webgl.RENDERBUFFER = 0x8D41; /** * @const * @type {number} */ goog.webgl.RGBA4 = 0x8056; /** * @const * @type {number} */ goog.webgl.RGB5_A1 = 0x8057; /** * @const * @type {number} */ goog.webgl.RGB565 = 0x8D62; /** * @const * @type {number} */ goog.webgl.DEPTH_COMPONENT16 = 0x81A5; /** * @const * @type {number} */ goog.webgl.STENCIL_INDEX = 0x1901; /** * @const * @type {number} */ goog.webgl.STENCIL_INDEX8 = 0x8D48; /** * @const * @type {number} */ goog.webgl.DEPTH_STENCIL = 0x84F9; /** * @const * @type {number} */ goog.webgl.RENDERBUFFER_WIDTH = 0x8D42; /** * @const * @type {number} */ goog.webgl.RENDERBUFFER_HEIGHT = 0x8D43; /** * @const * @type {number} */ goog.webgl.RENDERBUFFER_INTERNAL_FORMAT = 0x8D44; /** * @const * @type {number} */ goog.webgl.RENDERBUFFER_RED_SIZE = 0x8D50; /** * @const * @type {number} */ goog.webgl.RENDERBUFFER_GREEN_SIZE = 0x8D51; /** * @const * @type {number} */ goog.webgl.RENDERBUFFER_BLUE_SIZE = 0x8D52; /** * @const * @type {number} */ goog.webgl.RENDERBUFFER_ALPHA_SIZE = 0x8D53; /** * @const * @type {number} */ goog.webgl.RENDERBUFFER_DEPTH_SIZE = 0x8D54; /** * @const * @type {number} */ goog.webgl.RENDERBUFFER_STENCIL_SIZE = 0x8D55; /** * @const * @type {number} */ goog.webgl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0; /** * @const * @type {number} */ goog.webgl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1; /** * @const * @type {number} */ goog.webgl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2; /** * @const * @type {number} */ goog.webgl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3; /** * @const * @type {number} */ goog.webgl.COLOR_ATTACHMENT0 = 0x8CE0; /** * @const * @type {number} */ goog.webgl.DEPTH_ATTACHMENT = 0x8D00; /** * @const * @type {number} */ goog.webgl.STENCIL_ATTACHMENT = 0x8D20; /** * @const * @type {number} */ goog.webgl.DEPTH_STENCIL_ATTACHMENT = 0x821A; /** * @const * @type {number} */ goog.webgl.NONE = 0; /** * @const * @type {number} */ goog.webgl.FRAMEBUFFER_COMPLETE = 0x8CD5; /** * @const * @type {number} */ goog.webgl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6; /** * @const * @type {number} */ goog.webgl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7; /** * @const * @type {number} */ goog.webgl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9; /** * @const * @type {number} */ goog.webgl.FRAMEBUFFER_UNSUPPORTED = 0x8CDD; /** * @const * @type {number} */ goog.webgl.FRAMEBUFFER_BINDING = 0x8CA6; /** * @const * @type {number} */ goog.webgl.RENDERBUFFER_BINDING = 0x8CA7; /** * @const * @type {number} */ goog.webgl.MAX_RENDERBUFFER_SIZE = 0x84E8; /** * @const * @type {number} */ goog.webgl.INVALID_FRAMEBUFFER_OPERATION = 0x0506; /** * @const * @type {number} */ goog.webgl.UNPACK_FLIP_Y_WEBGL = 0x9240; /** * @const * @type {number} */ goog.webgl.UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241; /** * @const * @type {number} */ goog.webgl.CONTEXT_LOST_WEBGL = 0x9242; /** * @const * @type {number} */ goog.webgl.UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243; /** * @const * @type {number} */ goog.webgl.BROWSER_DEFAULT_WEBGL = 0x9244; /** * From the OES_texture_half_float extension. * http://www.khronos.org/registry/webgl/extensions/OES_texture_half_float/ * @const * @type {number} */ goog.webgl.HALF_FLOAT_OES = 0x8D61; /** * From the OES_standard_derivatives extension. * http://www.khronos.org/registry/webgl/extensions/OES_standard_derivatives/ * @const * @type {number} */ goog.webgl.FRAGMENT_SHADER_DERIVATIVE_HINT_OES = 0x8B8B; /** * From the OES_vertex_array_object extension. * http://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/ * @const * @type {number} */ goog.webgl.VERTEX_ARRAY_BINDING_OES = 0x85B5; /** * From the WEBGL_debug_renderer_info extension. * http://www.khronos.org/registry/webgl/extensions/WEBGL_debug_renderer_info/ * @const * @type {number} */ goog.webgl.UNMASKED_VENDOR_WEBGL = 0x9245; /** * From the WEBGL_debug_renderer_info extension. * http://www.khronos.org/registry/webgl/extensions/WEBGL_debug_renderer_info/ * @const * @type {number} */ goog.webgl.UNMASKED_RENDERER_WEBGL = 0x9246; /** * From the WEBGL_compressed_texture_s3tc extension. * http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/ * @const * @type {number} */ goog.webgl.COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0; /** * From the WEBGL_compressed_texture_s3tc extension. * http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/ * @const * @type {number} */ goog.webgl.COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1; /** * From the WEBGL_compressed_texture_s3tc extension. * http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/ * @const * @type {number} */ goog.webgl.COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2; /** * From the WEBGL_compressed_texture_s3tc extension. * http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/ * @const * @type {number} */ goog.webgl.COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3; /** * From the EXT_texture_filter_anisotropic extension. * http://www.khronos.org/registry/webgl/extensions/EXT_texture_filter_anisotropic/ * @const * @type {number} */ goog.webgl.TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE; /** * From the EXT_texture_filter_anisotropic extension. * http://www.khronos.org/registry/webgl/extensions/EXT_texture_filter_anisotropic/ * @const * @type {number} */ goog.webgl.MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FF;
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Announcer that allows messages to be spoken by assistive * technologies. */ goog.provide('goog.a11y.aria.Announcer'); goog.require('goog.Disposable'); goog.require('goog.a11y.aria'); goog.require('goog.a11y.aria.LivePriority'); goog.require('goog.a11y.aria.State'); goog.require('goog.dom'); goog.require('goog.object'); /** * Class that allows messages to be spoken by assistive technologies that the * user may have active. * * @param {goog.dom.DomHelper=} opt_domHelper DOM helper. * @constructor * @extends {goog.Disposable} */ goog.a11y.aria.Announcer = function(opt_domHelper) { goog.base(this); /** * @type {goog.dom.DomHelper} * @private */ this.domHelper_ = opt_domHelper || goog.dom.getDomHelper(); /** * Map of priority to live region elements to use for communicating updates. * Elements are created on demand. * @type {Object.<goog.a11y.aria.LivePriority, Element>} * @private */ this.liveRegions_ = {}; }; goog.inherits(goog.a11y.aria.Announcer, goog.Disposable); /** @override */ goog.a11y.aria.Announcer.prototype.disposeInternal = function() { goog.object.forEach( this.liveRegions_, this.domHelper_.removeNode, this.domHelper_); this.liveRegions_ = null; this.domHelper_ = null; goog.base(this, 'disposeInternal'); }; /** * Announce a message to be read by any assistive technologies the user may * have active. * @param {string} message The message to announce to screen readers. * @param {goog.a11y.aria.LivePriority=} opt_priority The priority of the * message. Defaults to POLITE. */ goog.a11y.aria.Announcer.prototype.say = function(message, opt_priority) { goog.dom.setTextContent(this.getLiveRegion_( opt_priority || goog.a11y.aria.LivePriority.POLITE), message); }; /** * Returns an aria-live region that can be used to communicate announcements. * @param {!goog.a11y.aria.LivePriority} priority The required priority. * @return {Element} A live region of the requested priority. * @private */ goog.a11y.aria.Announcer.prototype.getLiveRegion_ = function(priority) { if (this.liveRegions_[priority]) { return this.liveRegions_[priority]; } var liveRegion; liveRegion = this.domHelper_.createElement('div'); liveRegion.style.position = 'absolute'; liveRegion.style.top = '-1000px'; goog.a11y.aria.setState(liveRegion, goog.a11y.aria.State.LIVE, priority); goog.a11y.aria.setState(liveRegion, goog.a11y.aria.State.ATOMIC, 'true'); this.domHelper_.getDocument().body.appendChild(liveRegion); this.liveRegions_[priority] = liveRegion; return liveRegion; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview The file contains enumerations for ARIA states * and properties as defined by W3C ARIA standard: * http://www.w3.org/TR/wai-aria/. */ goog.provide('goog.a11y.aria.LivePriority'); goog.provide('goog.a11y.aria.State'); /** * Enumeration of ARIA states and properties. * @enum {string} */ goog.a11y.aria.State = { // ARIA property for setting the currently active descendant of an element, // for example the selected item in a list box. Value: ID of an element. ACTIVEDESCENDANT: 'activedescendant', // ARIA property that, if true, indicates that all of a changed region should // be presented, instead of only parts. Value: one of {true, false}. ATOMIC: 'atomic', // ARIA property to specify that input completion is provided. Value: // one of {'inline', 'list', 'both', 'none'}. AUTOCOMPLETE: 'autocomplete', // ARIA state to indicate that an element and its subtree are being updated. // Value: one of {true, false}. BUSY: 'busy', // ARIA state for a checked item. Value: one of {'true', 'false', 'mixed', // undefined}. CHECKED: 'checked', // ARIA property that identifies the element or elements whose contents or // presence are controlled by this element. // Value: space-separated IDs of other elements. CONTROLS: 'controls', // ARIA property that identifies the element or elements that describe // this element. Value: space-separated IDs of other elements. DESCRIBEDBY: 'describedby', // ARIA state for a disabled item. Value: one of {true, false}. DISABLED: 'disabled', // ARIA property that indicates what functions can be performed when a // dragged object is released on the drop target. Value: one of // {'copy', 'move', 'link', 'execute', 'popup', 'none'}. DROPEFFECT: 'dropeffect', // ARIA state for setting whether the element like a tree node is expanded. // Value: one of {true, false, undefined}. EXPANDED: 'expanded', // ARIA property that identifies the next element (or elements) in the // recommended reading order of content. Value: space-separated ids of // elements to flow to. FLOWTO: 'flowto', // ARIA state that indicates an element's "grabbed" state in drag-and-drop. // Value: one of {true, false, undefined}. GRABBED: 'grabbed', // ARIA property indicating whether the element has a popup. // Value: one of {true, false}. HASPOPUP: 'haspopup', // ARIA state indicating that the element is not visible or perceivable // to any user. Value: one of {true, false}. HIDDEN: 'hidden', // ARIA state indicating that the entered value does not conform. Value: // one of {false, true, 'grammar', 'spelling'} INVALID: 'invalid', // ARIA property that provides a label to override any other text, value, or // contents used to describe this element. Value: string. LABEL: 'label', // ARIA property for setting the element which labels another element. // Value: space-separated IDs of elements. LABELLEDBY: 'labelledby', // ARIA property for setting the level of an element in the hierarchy. // Value: integer. LEVEL: 'level', // ARIA property indicating that an element will be updated, and // describes the types of updates the user agents, assistive technologies, // and user can expect from the live region. Value: one of {'off', 'polite', // 'assertive'}. LIVE: 'live', // ARIA property indicating whether a text box can accept multiline input. // Value: one of {true, false}. MULTILINE: 'multiline', // ARIA property indicating if the user may select more than one item. // Value: one of {true, false}. MULTISELECTABLE: 'multiselectable', // ARIA property indicating if the element is horizontal or vertical. // Value: one of {'vertical', 'horizontal'}. ORIENTATION: 'orientation', // ARIA property creating a visual, functional, or contextual parent/child // relationship when the DOM hierarchy can't be used to represent it. // Value: Space-separated IDs of elements. OWNS: 'owns', // ARIA property that defines an element's number of position in a list. // Value: integer. POSINSET: 'posinset', // ARIA state for a pressed item. // Value: one of {true, false, undefined, 'mixed'}. PRESSED: 'pressed', // ARIA property indicating that an element is not editable. // Value: one of {true, false}. READONLY: 'readonly', // ARIA property indicating that change notifications within this subtree // of a live region should be announced. Value: one of {'additions', // 'removals', 'text', 'all', 'additions text'}. RELEVANT: 'relevant', // ARIA property indicating that user input is required on this element // before a form may be submitted. Value: one of {true, false}. REQUIRED: 'required', // ARIA state for setting the currently selected item in the list. // Value: one of {true, false, undefined}. SELECTED: 'selected', // ARIA property defining the number of items in a list. Value: integer. SETSIZE: 'setsize', // ARIA property indicating if items are sorted. Value: one of {'ascending', // 'descending', 'none', 'other'}. SORT: 'sort', // ARIA property for slider maximum value. Value: number. VALUEMAX: 'valuemax', // ARIA property for slider minimum value. Value: number. VALUEMIN: 'valuemin', // ARIA property for slider active value. Value: number. VALUENOW: 'valuenow', // ARIA property for slider active value represented as text. // Value: string. VALUETEXT: 'valuetext' }; /** * Enumeration of ARIA state values for live regions. * * See http://www.w3.org/TR/wai-aria/states_and_properties#aria-live * for more information. * @enum {string} */ goog.a11y.aria.LivePriority = { /** * Default value. Used for live regions that should never be spoken. */ OFF: 'off', /** * Spoke only when the user is idle. Best option in most cases. */ POLITE: 'polite', /** * Spoken as soon as possible, which means that the information has a * higher priority than normal, but does not necessarily interrupt * immediately. */ ASSERTIVE: 'assertive' };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview The file contains enumerations for ARIA roles * as defined by W3C ARIA standard: http://www.w3.org/TR/wai-aria/. */ goog.provide('goog.a11y.aria.Role'); /** * Enumeration of ARIA roles. * @enum {string} */ goog.a11y.aria.Role = { // ARIA role for an alert element that doesn't need to be explicitly closed. ALERT: 'alert', // ARIA role for an alert dialog element that takes focus and must be closed. ALERTDIALOG: 'alertdialog', // ARIA role for an application that implements its own keyboard navigation. APPLICATION: 'application', // ARIA role for an article. ARTICLE: 'article', // ARIA role for a banner containing mostly site content, not page content. BANNER: 'banner', // ARIA role for a button element. BUTTON: 'button', // ARIA role for a checkbox button element; use with the CHECKED state. CHECKBOX: 'checkbox', // ARIA role for a column header of a table or grid. COLUMNHEADER: 'columnheader', // ARIA role for a combo box element. COMBOBOX: 'combobox', // ARIA role for a supporting section of the document. COMPLEMENTARY: 'complementary', // ARIA role for a large perceivable region that contains information // about the parent document. CONTENTINFO: 'contentinfo', // ARIA role for a definition of a term or concept. DEFINITION: 'definition', // ARIA role for a dialog, some descendant must take initial focus. DIALOG: 'dialog', // ARIA role for a directory, like a table of contents. DIRECTORY: 'directory', // ARIA role for a part of a page that's a document, not a web application. DOCUMENT: 'document', // ARIA role for a landmark region logically considered one form. FORM: 'form', // ARIA role for an interactive control of tabular data. GRID: 'grid', // ARIA role for a cell in a grid. GRIDCELL: 'gridcell', // ARIA role for a group of related elements like tree item siblings. GROUP: 'group', // ARIA role for a heading element. HEADING: 'heading', // ARIA role for a container of elements that together comprise one image. IMG: 'img', // ARIA role for a link. LINK: 'link', // ARIA role for a list of non-interactive list items. LIST: 'list', // ARIA role for a listbox. LISTBOX: 'listbox', // ARIA role for a list item. LISTITEM: 'listitem', // ARIA role for a live region where new information is added. LOG: 'log', // ARIA landmark role for the main content in a document. Use only once. MAIN: 'main', // ARIA role for a live region of non-essential information that changes. MARQUEE: 'marquee', // ARIA role for a mathematical expression. MATH: 'math', // ARIA role for a popup menu. MENU: 'menu', // ARIA role for a menubar element containing menu elements. MENUBAR: 'menubar', // ARIA role for menu item elements. MENU_ITEM: 'menuitem', // ARIA role for a checkbox box element inside a menu. MENU_ITEM_CHECKBOX: 'menuitemcheckbox', // ARIA role for a radio button element inside a menu. MENU_ITEM_RADIO: 'menuitemradio', // ARIA landmark role for a collection of navigation links. NAVIGATION: 'navigation', // ARIA role for a section ancillary to the main content. NOTE: 'note', // ARIA role for option items that are children of combobox, listbox, menu, // radiogroup, or tree elements. OPTION: 'option', // ARIA role for ignorable cosmetic elements with no semantic significance. PRESENTATION: 'presentation', // ARIA role for a progress bar element. PROGRESSBAR: 'progressbar', // ARIA role for a radio button element. RADIO: 'radio', // ARIA role for a group of connected radio button elements. RADIOGROUP: 'radiogroup', // ARIA role for an important region of the page. REGION: 'region', // ARIA role for a row of cells in a grid. ROW: 'row', // ARIA role for a group of one or more rows in a grid. ROWGROUP: 'rowgroup', // ARIA role for a row header of a table or grid. ROWHEADER: 'rowheader', // ARIA role for a scrollbar element. SCROLLBAR: 'scrollbar', // ARIA landmark role for a part of the page providing search functionality. SEARCH: 'search', // ARIA role for a menu separator. SEPARATOR: 'separator', // ARIA role for a slider. SLIDER: 'slider', // ARIA role for a spin button. SPINBUTTON: 'spinbutton', // ARIA role for a live region with advisory info less severe than an alert. STATUS: 'status', // ARIA role for a tab button. TAB: 'tab', // ARIA role for a tab bar (i.e. a list of tab buttons). TAB_LIST: 'tablist', // ARIA role for a tab page (i.e. the element holding tab contents). TAB_PANEL: 'tabpanel', // ARIA role for a textbox element. TEXTBOX: 'textbox', // ARIA role for an element displaying elapsed time or time remaining. TIMER: 'timer', // ARIA role for a toolbar element. TOOLBAR: 'toolbar', // ARIA role for a tooltip element. TOOLTIP: 'tooltip', // ARIA role for a tree. TREE: 'tree', // ARIA role for a grid whose rows can be expanded and collapsed like a tree. TREEGRID: 'treegrid', // ARIA role for a tree item that sometimes may be expanded or collapsed. TREEITEM: 'treeitem' };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Utilities for adding, removing and setting ARIA roles * as defined by W3C ARIA Working Draft: * http://www.w3.org/TR/2010/WD-wai-aria-20100916/ * All modern browsers have some form of ARIA support, so no browser checks are * performed when adding ARIA to components. * */ goog.provide('goog.a11y.aria'); goog.require('goog.a11y.aria.Role'); goog.require('goog.a11y.aria.State'); goog.require('goog.dom'); /** * Sets the role of an element. * @param {!Element} element DOM node to set role of. * @param {!goog.a11y.aria.Role|string} roleName role name(s). */ goog.a11y.aria.setRole = function(element, roleName) { element.setAttribute('role', roleName); }; /** * Gets role of an element. * @param {!Element} element DOM node to get role of. * @return {!goog.a11y.aria.Role|string} rolename. */ goog.a11y.aria.getRole = function(element) { return /** @type {goog.a11y.aria.Role} */ ( element.getAttribute('role')) || ''; }; /** * Sets the state or property of an element. * @param {!Element} element DOM node where we set state. * @param {!goog.a11y.aria.State|string} state State attribute being set. * Automatically adds prefix 'aria-' to the state name. * @param {string|boolean|number} value Value for the state attribute. */ goog.a11y.aria.setState = function(element, state, value) { element.setAttribute('aria-' + state, value); }; /** * Gets value of specified state or property. * @param {!Element} element DOM node to get state from. * @param {!goog.a11y.aria.State|string} stateName State name. * @return {string} Value of the state attribute. */ goog.a11y.aria.getState = function(element, stateName) { var attrb = /** @type {string|number|boolean} */ ( element.getAttribute('aria-' + stateName)); // Check for multiple representations - attrb might // be a boolean or a string if ((attrb === true) || (attrb === false)) { return attrb ? 'true' : 'false'; } else if (!attrb) { return ''; } else { return String(attrb); } }; /** * Gets the activedescendant of the given element. * @param {!Element} element DOM node to get activedescendant from. * @return {Element} DOM node of the activedescendant. */ goog.a11y.aria.getActiveDescendant = function(element) { var id = goog.a11y.aria.getState( element, goog.a11y.aria.State.ACTIVEDESCENDANT); return goog.dom.getOwnerDocument(element).getElementById(id); }; /** * Sets the activedescendant value for an element. * @param {!Element} element DOM node to set activedescendant to. * @param {Element} activeElement DOM node being set as activedescendant. */ goog.a11y.aria.setActiveDescendant = function(element, activeElement) { goog.a11y.aria.setState(element, goog.a11y.aria.State.ACTIVEDESCENDANT, activeElement ? activeElement.id : ''); }; /** * Gets the label of the given element. * @param {!Element} element DOM node to get label from. * @return {string} label The label. */ goog.a11y.aria.getLabel = function(element) { return goog.a11y.aria.getState(element, goog.a11y.aria.State.LABEL); }; /** * Sets the label of the given element. * @param {!Element} element DOM node to set label to. * @param {string} label The label to set. */ goog.a11y.aria.setLabel = function(element, label) { goog.a11y.aria.setState(element, goog.a11y.aria.State.LABEL, label); };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Text editor constants for compile time feature selection. * */ goog.provide('goog.editor.defines'); /** * @define {boolean} Use contentEditable in FF. * There are a number of known bugs when the only content in your field is * inline (e.g. just text, no block elements): * -indent is a noop and then DOMSubtreeModified events stop firing until * the structure of the DOM is changed (e.g. make something bold). * -inserting lists inserts just a NBSP, no list! * Once those two are fixed, we should have one client guinea pig it and put * it through a QA run. If we can file the bugs with Mozilla, there's a chance * they'll fix them for a dot release of Firefox 3. */ goog.editor.defines.USE_CONTENTEDITABLE_IN_FIREFOX_3 = false;
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Table editing support. * This file provides the class goog.editor.Table and two * supporting classes, goog.editor.TableRow and * goog.editor.TableCell. Together these provide support for * high level table modifications: Adding and deleting rows and columns, * and merging and splitting cells. * * @supported IE6+, WebKit 525+, Firefox 2+. */ goog.provide('goog.editor.Table'); goog.provide('goog.editor.TableCell'); goog.provide('goog.editor.TableRow'); goog.require('goog.debug.Logger'); goog.require('goog.dom'); goog.require('goog.dom.DomHelper'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.TagName'); goog.require('goog.string.Unicode'); goog.require('goog.style'); /** * Class providing high level table editing functions. * @param {Element} node Element that is a table or descendant of a table. * @constructor */ goog.editor.Table = function(node) { this.element = goog.dom.getAncestorByTagNameAndClass(node, goog.dom.TagName.TABLE); if (!this.element) { this.logger_.severe( "Can't create Table based on a node " + "that isn't a table, or descended from a table."); } this.dom_ = goog.dom.getDomHelper(this.element); this.refresh(); }; /** * Logger object for debugging and error messages. * @type {goog.debug.Logger} * @private */ goog.editor.Table.prototype.logger_ = goog.debug.Logger.getLogger('goog.editor.Table'); /** * Walks the dom structure of this object's table element and populates * this.rows with goog.editor.TableRow objects. This is done initially * to populate the internal data structures, and also after each time the * DOM structure is modified. Currently this means that the all existing * information is discarded and re-read from the DOM. */ // TODO(user): support partial refresh to save cost of full update // every time there is a change to the DOM. goog.editor.Table.prototype.refresh = function() { var rows = this.rows = []; var tbody = this.element.getElementsByTagName(goog.dom.TagName.TBODY)[0]; if (!tbody) { return; } var trs = []; for (var child = tbody.firstChild; child; child = child.nextSibling) { if (child.nodeName == goog.dom.TagName.TR) { trs.push(child); } } for (var rowNum = 0, tr; tr = trs[rowNum]; rowNum++) { var existingRow = rows[rowNum]; var tds = goog.editor.Table.getChildCellElements(tr); var columnNum = 0; // A note on cellNum vs. columnNum: A cell is a td/th element. Cells may // use colspan/rowspan to extend over multiple rows/columns. cellNum // is the dom element number, columnNum is the logical column number. for (var cellNum = 0, td; td = tds[cellNum]; cellNum++) { // If there's already a cell extending into this column // (due to that cell's colspan/rowspan), increment the column counter. while (existingRow && existingRow.columns[columnNum]) { columnNum++; } var cell = new goog.editor.TableCell(td, rowNum, columnNum); // Place this cell in every row and column into which it extends. for (var i = 0; i < cell.rowSpan; i++) { var cellRowNum = rowNum + i; // Create TableRow objects in this.rows as needed. var cellRow = rows[cellRowNum]; if (!cellRow) { // TODO(user): try to avoid second trs[] lookup. rows.push( cellRow = new goog.editor.TableRow(trs[cellRowNum], cellRowNum)); } // Extend length of column array to make room for this cell. var minimumColumnLength = columnNum + cell.colSpan; if (cellRow.columns.length < minimumColumnLength) { cellRow.columns.length = minimumColumnLength; } for (var j = 0; j < cell.colSpan; j++) { var cellColumnNum = columnNum + j; cellRow.columns[cellColumnNum] = cell; } } columnNum += cell.colSpan; } } }; /** * Returns all child elements of a TR element that are of type TD or TH. * @param {Element} tr TR element in which to find children. * @return {Array.<Element>} array of child cell elements. */ goog.editor.Table.getChildCellElements = function(tr) { var cells = []; for (var i = 0, cell; cell = tr.childNodes[i]; i++) { if (cell.nodeName == goog.dom.TagName.TD || cell.nodeName == goog.dom.TagName.TH) { cells.push(cell); } } return cells; }; /** * Inserts a new row in the table. The row will be populated with new * cells, and existing rowspanned cells that overlap the new row will * be extended. * @param {number=} opt_rowIndex Index at which to insert the row. If * this is omitted the row will be appended to the end of the table. * @return {Element} The new row. */ goog.editor.Table.prototype.insertRow = function(opt_rowIndex) { var rowIndex = goog.isDefAndNotNull(opt_rowIndex) ? opt_rowIndex : this.rows.length; var refRow; var insertAfter; if (rowIndex == 0) { refRow = this.rows[0]; insertAfter = false; } else { refRow = this.rows[rowIndex - 1]; insertAfter = true; } var newTr = this.dom_.createElement('tr'); for (var i = 0, cell; cell = refRow.columns[i]; i += 1) { // Check whether the existing cell will span this new row. // If so, instead of creating a new cell, extend // the rowspan of the existing cell. if ((insertAfter && cell.endRow > rowIndex) || (!insertAfter && cell.startRow < rowIndex)) { cell.setRowSpan(cell.rowSpan + 1); if (cell.colSpan > 1) { i += cell.colSpan - 1; } } else { newTr.appendChild(this.createEmptyTd()); } if (insertAfter) { goog.dom.insertSiblingAfter(newTr, refRow.element); } else { goog.dom.insertSiblingBefore(newTr, refRow.element); } } this.refresh(); return newTr; }; /** * Inserts a new column in the table. The column will be created by * inserting new TD elements in each row, or extending the colspan * of existing TD elements. * @param {number=} opt_colIndex Index at which to insert the column. If * this is omitted the column will be appended to the right side of * the table. * @return {Array.<Element>} Array of new cell elements that were created * to populate the new column. */ goog.editor.Table.prototype.insertColumn = function(opt_colIndex) { // TODO(user): set column widths in a way that makes sense. var colIndex = goog.isDefAndNotNull(opt_colIndex) ? opt_colIndex : (this.rows[0] && this.rows[0].columns.length) || 0; var newTds = []; for (var rowNum = 0, row; row = this.rows[rowNum]; rowNum++) { var existingCell = row.columns[colIndex]; if (existingCell && existingCell.endCol >= colIndex && existingCell.startCol < colIndex) { existingCell.setColSpan(existingCell.colSpan + 1); rowNum += existingCell.rowSpan - 1; } else { var newTd = this.createEmptyTd(); // TODO(user): figure out a way to intelligently size new columns. newTd.style.width = goog.editor.Table.OPTIMUM_EMPTY_CELL_WIDTH + 'px'; this.insertCellElement(newTd, rowNum, colIndex); newTds.push(newTd); } } this.refresh(); return newTds; }; /** * Removes a row from the table, removing the TR element and * decrementing the rowspan of any cells in other rows that overlap the row. * @param {number} rowIndex Index of the row to delete. */ goog.editor.Table.prototype.removeRow = function(rowIndex) { var row = this.rows[rowIndex]; if (!row) { this.logger_.warning( "Can't remove row at position " + rowIndex + ': no such row.'); } for (var i = 0, cell; cell = row.columns[i]; i += cell.colSpan) { if (cell.rowSpan > 1) { cell.setRowSpan(cell.rowSpan - 1); if (cell.startRow == rowIndex) { // Rowspanned cell started in this row - move it down to the next row. this.insertCellElement(cell.element, rowIndex + 1, cell.startCol); } } } row.element.parentNode.removeChild(row.element); this.refresh(); }; /** * Removes a column from the table. This is done by removing cell elements, * or shrinking the colspan of elements that span multiple columns. * @param {number} colIndex Index of the column to delete. */ goog.editor.Table.prototype.removeColumn = function(colIndex) { for (var i = 0, row; row = this.rows[i]; i++) { var cell = row.columns[colIndex]; if (!cell) { this.logger_.severe( "Can't remove cell at position " + i + ', ' + colIndex + ': no such cell.'); } if (cell.colSpan > 1) { cell.setColSpan(cell.colSpan - 1); } else { cell.element.parentNode.removeChild(cell.element); } // Skip over following rows that contain this same cell. i += cell.rowSpan - 1; } this.refresh(); }; /** * Merges multiple cells into a single cell, and sets the rowSpan and colSpan * attributes of the cell to take up the same space as the original cells. * @param {number} startRowIndex Top coordinate of the cells to merge. * @param {number} startColIndex Left coordinate of the cells to merge. * @param {number} endRowIndex Bottom coordinate of the cells to merge. * @param {number} endColIndex Right coordinate of the cells to merge. * @return {boolean} Whether or not the merge was possible. If the cells * in the supplied coordinates can't be merged this will return false. */ goog.editor.Table.prototype.mergeCells = function( startRowIndex, startColIndex, endRowIndex, endColIndex) { // TODO(user): take a single goog.math.Rect parameter instead? var cells = []; var cell; if (startRowIndex == endRowIndex && startColIndex == endColIndex) { this.logger_.warning("Can't merge single cell"); return false; } // Gather cells and do sanity check. for (var i = startRowIndex; i <= endRowIndex; i++) { for (var j = startColIndex; j <= endColIndex; j++) { cell = this.rows[i].columns[j]; if (cell.startRow < startRowIndex || cell.endRow > endRowIndex || cell.startCol < startColIndex || cell.endCol > endColIndex) { this.logger_.warning( "Can't merge cells: the cell in row " + i + ', column ' + j + 'extends outside the supplied rectangle.'); return false; } // TODO(user): this is somewhat inefficient, as we will add // a reference for a cell for each position, even if it's a single // cell with row/colspan. cells.push(cell); } } var targetCell = cells[0]; var targetTd = targetCell.element; var doc = this.dom_.getDocument(); // Merge cell contents and discard other cells. for (var i = 1; cell = cells[i]; i++) { var td = cell.element; if (!td.parentNode || td == targetTd) { // We've already handled this cell at one of its previous positions. continue; } // Add a space if needed, to keep merged content from getting squished // together. if (targetTd.lastChild && targetTd.lastChild.nodeType == goog.dom.NodeType.TEXT) { targetTd.appendChild(doc.createTextNode(' ')); } var childNode; while ((childNode = td.firstChild)) { targetTd.appendChild(childNode); } td.parentNode.removeChild(td); } targetCell.setColSpan((endColIndex - startColIndex) + 1); targetCell.setRowSpan((endRowIndex - startRowIndex) + 1); if (endColIndex > startColIndex) { // Clear width on target cell. // TODO(user): instead of clearing width, calculate width // based on width of input cells targetTd.removeAttribute('width'); targetTd.style.width = null; } this.refresh(); return true; }; /** * Splits a cell with colspans or rowspans into multiple descrete cells. * @param {number} rowIndex y coordinate of the cell to split. * @param {number} colIndex x coordinate of the cell to split. * @return {Array.<Element>} Array of new cell elements created by splitting * the cell. */ // TODO(user): support splitting only horizontally or vertically, // support splitting cells that aren't already row/colspanned. goog.editor.Table.prototype.splitCell = function(rowIndex, colIndex) { var row = this.rows[rowIndex]; var cell = row.columns[colIndex]; var newTds = []; for (var i = 0; i < cell.rowSpan; i++) { for (var j = 0; j < cell.colSpan; j++) { if (i > 0 || j > 0) { var newTd = this.createEmptyTd(); this.insertCellElement(newTd, rowIndex + i, colIndex + j); newTds.push(newTd); } } } cell.setColSpan(1); cell.setRowSpan(1); this.refresh(); return newTds; }; /** * Inserts a cell element at the given position. The colIndex is the logical * column index, not the position in the dom. This takes into consideration * that cells in a given logical row may actually be children of a previous * DOM row that have used rowSpan to extend into the row. * @param {Element} td The new cell element to insert. * @param {number} rowIndex Row in which to insert the element. * @param {number} colIndex Column in which to insert the element. */ goog.editor.Table.prototype.insertCellElement = function( td, rowIndex, colIndex) { var row = this.rows[rowIndex]; var nextSiblingElement = null; for (var i = colIndex, cell; cell = row.columns[i]; i += cell.colSpan) { if (cell.startRow == rowIndex) { nextSiblingElement = cell.element; break; } } row.element.insertBefore(td, nextSiblingElement); }; /** * Creates an empty TD element and fill it with some empty content so it will * show up with borders even in IE pre-7 or if empty-cells is set to 'hide' * @return {Element} a new TD element. */ goog.editor.Table.prototype.createEmptyTd = function() { // TODO(user): more cross-browser testing to determine best // and least annoying filler content. return this.dom_.createDom(goog.dom.TagName.TD, {}, goog.string.Unicode.NBSP); }; /** * Class representing a logical table row: a tr element and any cells * that appear in that row. * @param {Element} trElement This rows's underlying TR element. * @param {number} rowIndex This row's index in its parent table. * @constructor */ goog.editor.TableRow = function(trElement, rowIndex) { this.index = rowIndex; this.element = trElement; this.columns = []; }; /** * Class representing a table cell, which may span across multiple * rows and columns * @param {Element} td This cell's underlying TD or TH element. * @param {number} startRow Index of the row where this cell begins. * @param {number} startCol Index of the column where this cell begins. * @constructor */ goog.editor.TableCell = function(td, startRow, startCol) { this.element = td; this.colSpan = parseInt(td.colSpan, 10) || 1; this.rowSpan = parseInt(td.rowSpan, 10) || 1; this.startRow = startRow; this.startCol = startCol; this.updateCoordinates_(); }; /** * Calculates this cell's endRow/endCol coordinates based on rowSpan/colSpan * @private */ goog.editor.TableCell.prototype.updateCoordinates_ = function() { this.endCol = this.startCol + this.colSpan - 1; this.endRow = this.startRow + this.rowSpan - 1; }; /** * Set this cell's colSpan, updating both its colSpan property and the * underlying element's colSpan attribute. * @param {number} colSpan The new colSpan. */ goog.editor.TableCell.prototype.setColSpan = function(colSpan) { if (colSpan != this.colSpan) { if (colSpan > 1) { this.element.colSpan = colSpan; } else { this.element.colSpan = 1, this.element.removeAttribute('colSpan'); } this.colSpan = colSpan; this.updateCoordinates_(); } }; /** * Set this cell's rowSpan, updating both its rowSpan property and the * underlying element's rowSpan attribute. * @param {number} rowSpan The new rowSpan. */ goog.editor.TableCell.prototype.setRowSpan = function(rowSpan) { if (rowSpan != this.rowSpan) { if (rowSpan > 1) { this.element.rowSpan = rowSpan.toString(); } else { this.element.rowSpan = '1'; this.element.removeAttribute('rowSpan'); } this.rowSpan = rowSpan; this.updateCoordinates_(); } }; /** * Optimum size of empty cells (in pixels), if possible. * @type {number} */ goog.editor.Table.OPTIMUM_EMPTY_CELL_WIDTH = 60; /** * Maximum width for new tables. * @type {number} */ goog.editor.Table.OPTIMUM_MAX_NEW_TABLE_WIDTH = 600; /** * Default color for table borders. * @type {string} */ goog.editor.Table.DEFAULT_BORDER_COLOR = '#888'; /** * Creates a new table element, populated with cells and formatted. * @param {Document} doc Document in which to create the table element. * @param {number} columns Number of columns in the table. * @param {number} rows Number of rows in the table. * @param {Object=} opt_tableStyle Object containing borderWidth and borderColor * properties, used to set the inital style of the table. * @return {Element} a table element. */ goog.editor.Table.createDomTable = function( doc, columns, rows, opt_tableStyle) { // TODO(user): define formatting properties as constants, // make separate formatTable() function var style = { borderWidth: '1', borderColor: goog.editor.Table.DEFAULT_BORDER_COLOR }; for (var prop in opt_tableStyle) { style[prop] = opt_tableStyle[prop]; } var dom = new goog.dom.DomHelper(doc); var tableElement = dom.createTable(rows, columns, true); var minimumCellWidth = 10; // Calculate a good cell width. var cellWidth = Math.max( minimumCellWidth, Math.min(goog.editor.Table.OPTIMUM_EMPTY_CELL_WIDTH, goog.editor.Table.OPTIMUM_MAX_NEW_TABLE_WIDTH / columns)); var tds = tableElement.getElementsByTagName(goog.dom.TagName.TD); for (var i = 0, td; td = tds[i]; i++) { td.style.width = cellWidth + 'px'; } // Set border somewhat redundantly to make sure they show // up correctly in all browsers. goog.style.setStyle( tableElement, { 'borderCollapse': 'collapse', 'borderColor': style.borderColor, 'borderWidth': style.borderWidth + 'px' }); tableElement.border = style.borderWidth; tableElement.setAttribute('bordercolor', style.borderColor); tableElement.setAttribute('cellspacing', '0'); return tableElement; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // All Rights Reserved. /** * @fileoverview Static functions for writing the contents of an iframe-based * editable field. These vary significantly from browser to browser. Uses * strings and document.write instead of DOM manipulation, because * iframe-loading is a performance bottleneck. * */ goog.provide('goog.editor.icontent'); goog.provide('goog.editor.icontent.FieldFormatInfo'); goog.provide('goog.editor.icontent.FieldStyleInfo'); goog.require('goog.editor.BrowserFeature'); goog.require('goog.style'); goog.require('goog.userAgent'); /** * A data structure for storing simple rendering info about a field. * * @param {string} fieldId The id of the field. * @param {boolean} standards Whether the field should be rendered in * standards mode. * @param {boolean} blended Whether the field is in blended mode. * @param {boolean} fixedHeight Whether the field is in fixedHeight mode. * @param {Object=} opt_extraStyles Other style attributes for the field, * represented as a map of strings. * @constructor */ goog.editor.icontent.FieldFormatInfo = function(fieldId, standards, blended, fixedHeight, opt_extraStyles) { this.fieldId_ = fieldId; this.standards_ = standards; this.blended_ = blended; this.fixedHeight_ = fixedHeight; this.extraStyles_ = opt_extraStyles || {}; }; /** * A data structure for storing simple info about the styles of a field. * Only needed in Firefox/Blended mode. * @param {Element} wrapper The wrapper div around a field. * @param {string} css The css for a field. * @constructor */ goog.editor.icontent.FieldStyleInfo = function(wrapper, css) { this.wrapper_ = wrapper; this.css_ = css; }; /** * Whether to always use standards-mode iframes. * @type {boolean} * @private */ goog.editor.icontent.useStandardsModeIframes_ = false; /** * Sets up goog.editor.icontent to always use standards-mode iframes. */ goog.editor.icontent.forceStandardsModeIframes = function() { goog.editor.icontent.useStandardsModeIframes_ = true; }; /** * Generate the initial iframe content. * @param {goog.editor.icontent.FieldFormatInfo} info Formatting info about * the field. * @param {string} bodyHtml The HTML to insert as the iframe body. * @param {goog.editor.icontent.FieldStyleInfo?} style Style info about * the field, if needed. * @return {string} The initial IFRAME content HTML. * @private */ goog.editor.icontent.getInitialIframeContent_ = function(info, bodyHtml, style) { var html = []; if (info.blended_ && info.standards_ || goog.editor.icontent.useStandardsModeIframes_) { html.push('<!DOCTYPE HTML>'); } // <HTML> // NOTE(user): Override min-widths that may be set for all // HTML/BODY nodes. A similar workaround is below for the <body> tag. This // can happen if the host page includes a rule like this in its CSS: // // html, body {min-width: 500px} // // In this case, the iframe's <html> and/or <body> may be affected. This was // part of the problem observed in http://b/5674613. (The other part of that // problem had to do with the presence of a spurious horizontal scrollbar, // which caused the editor height to be computed incorrectly.) html.push('<html style="background:none transparent;min-width:0;'); // Make sure that the HTML element's height has the // correct value as the body element's percentage height is made relative // to the HTML element's height. // For fixed-height it should be 100% since we want the body to fill the // whole height. For growing fields it should be auto since we want the // body to size to its content. if (info.blended_) { html.push('height:', info.fixedHeight_ ? '100%' : 'auto'); } html.push('">'); // <HEAD><STYLE> // IE/Safari whitebox need styles set only iff the client specifically // requested them. html.push('<head><style>'); if (style && style.css_) { html.push(style.css_); } // Firefox blended needs to inherit all the css from the original page. // Firefox standards mode needs to set extra style for images. if (goog.userAgent.GECKO && info.standards_) { // Standards mode will collapse broken images. This means that they // can never be removed from the field. This style forces the images // to render as a broken image icon, sized based on the width and height // of the image. // TODO(user): Make sure we move this into a contentEditable code // path if there ever is one for FF. html.push(' img {-moz-force-broken-image-icon: 1;}'); } html.push('</style></head>'); // <BODY> // Hidefocus is needed to ensure that IE7 doesn't show the dotted, focus // border when you tab into the field. html.push('<body g_editable="true" hidefocus="true" '); if (goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { html.push('contentEditable '); } html.push('class="editable '); // TODO: put the field's original ID on the body and stop using ID as a // way of getting the pointer to the field in the iframe now that it's // always the body. html.push('" id="', info.fieldId_, '" style="min-width:0;'); if (goog.userAgent.GECKO && info.blended_) { // IMPORTANT: Apply the css from the body then all of the clearing // CSS to make sure the clearing CSS overrides (e.g. if the body // has a 3px margin, we want to make sure to override it with 0px. html.push( // margin should not be applied to blended mode because the margin is // outside the iframe // In whitebox mode, we want to leave the margin to the default so // there is a nice margin around the text. ';width:100%;border:0;margin:0;background:none transparent;', // In standards-mode, height 100% makes the body size to its // parent html element, but in quirks mode, we want auto because // 100% makes it size to the containing window even if the html // element is smaller. // TODO: Fixed height, standards mode, CSS_WRITING, with margins on the // paragraphs has a scrollbar when it doesn't need it. Putting the // height to auto seems to fix it. Figure out if we should always // just use auto? ';height:', info.standards_ ? '100%' : 'auto'); // Only do this for mozilla. IE6 standards mode has a rendering bug when // there are scrollbars and the body's overflow property is auto if (info.fixedHeight_) { html.push(';overflow:auto'); } else { html.push(';overflow-y:hidden;overflow-x:auto'); } } // Hide the native focus rect in Opera. if (goog.userAgent.OPERA) { html.push(';outline:hidden'); } for (var key in info.extraStyles_) { html.push(';' + key + ':' + info.extraStyles_[key]); } html.push('">', bodyHtml, '</body></html>'); return html.join(''); }; /** * Write the initial iframe content in normal mode. * @param {goog.editor.icontent.FieldFormatInfo} info Formatting info about * the field. * @param {string} bodyHtml The HTML to insert as the iframe body. * @param {goog.editor.icontent.FieldStyleInfo?} style Style info about * the field, if needed. * @param {HTMLIFrameElement} iframe The iframe. */ goog.editor.icontent.writeNormalInitialBlendedIframe = function(info, bodyHtml, style, iframe) { // Firefox blended needs to inherit all the css from the original page. // Firefox standards mode needs to set extra style for images. if (info.blended_) { var field = style.wrapper_; // If there is padding on the original field, then the iFrame will be // positioned inside the padding by default. We don't want this, as it // causes the contents to appear to shift, and also causes the // scrollbars to appear inside the padding. // // To compensate, we set the iframe margins to offset the padding. var paddingBox = goog.style.getPaddingBox(field); if (paddingBox.top || paddingBox.left || paddingBox.right || paddingBox.bottom) { goog.style.setStyle(iframe, 'margin', (-paddingBox.top) + 'px ' + (-paddingBox.right) + 'px ' + (-paddingBox.bottom) + 'px ' + (-paddingBox.left) + 'px'); } } goog.editor.icontent.writeNormalInitialIframe( info, bodyHtml, style, iframe); }; /** * Write the initial iframe content in normal mode. * @param {goog.editor.icontent.FieldFormatInfo} info Formatting info about * the field. * @param {string} bodyHtml The HTML to insert as the iframe body. * @param {goog.editor.icontent.FieldStyleInfo?} style Style info about * the field, if needed. * @param {HTMLIFrameElement} iframe The iframe. */ goog.editor.icontent.writeNormalInitialIframe = function(info, bodyHtml, style, iframe) { var html = goog.editor.icontent.getInitialIframeContent_( info, bodyHtml, style); var doc = goog.dom.getFrameContentDocument(iframe); doc.open(); doc.write(html); doc.close(); }; /** * Write the initial iframe content in IE/HTTPS mode. * @param {goog.editor.icontent.FieldFormatInfo} info Formatting info about * the field. * @param {Document} doc The iframe document. * @param {string} bodyHtml The HTML to insert as the iframe body. */ goog.editor.icontent.writeHttpsInitialIframe = function(info, doc, bodyHtml) { var body = doc.body; // For HTTPS we already have a document with a doc type and a body element // and don't want to create a new history entry which can cause data loss if // the user clicks the back button. if (goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { body.contentEditable = true; } body.className = 'editable'; body.setAttribute('g_editable', true); body.hideFocus = true; body.id = info.fieldId_; goog.style.setStyle(body, info.extraStyles_); body.innerHTML = bodyHtml; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Trogedit unit tests for goog.editor.SeamlessField. * * @author nicksantos@google.com (Nick Santos) * @suppress {missingProperties} There are many mocks in this unit test, * and the mocks don't fit well in the type system. */ /** @suppress {extraProvide} */ goog.provide('goog.editor.seamlessfield_test'); goog.require('goog.dom'); goog.require('goog.dom.DomHelper'); goog.require('goog.dom.Range'); goog.require('goog.editor.BrowserFeature'); goog.require('goog.editor.Field'); goog.require('goog.editor.SeamlessField'); goog.require('goog.events'); goog.require('goog.functions'); goog.require('goog.style'); goog.require('goog.testing.MockClock'); goog.require('goog.testing.MockRange'); goog.require('goog.testing.jsunit'); goog.setTestOnly('seamlessfield_test'); var fieldElem; var fieldElemClone; function setUp() { fieldElem = goog.dom.getElement('field'); fieldElemClone = fieldElem.cloneNode(true); } function tearDown() { goog.events.removeAll(); fieldElem.parentNode.replaceChild(fieldElemClone, fieldElem); } // the following tests check for blended iframe positioning. They really // only make sense on browsers without contentEditable. function testBlankField() { if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { assertAttachSeamlessIframeSizesCorrectly( initSeamlessField('&nbsp;', {}), createSeamlessIframe()); } } function testFieldWithContent() { if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { assertAttachSeamlessIframeSizesCorrectly( initSeamlessField('Hi!', {}), createSeamlessIframe()); } } function testFieldWithPadding() { if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { assertAttachSeamlessIframeSizesCorrectly( initSeamlessField('Hi!', {'padding': '2px 5px'}), createSeamlessIframe()); } } function testFieldWithMargin() { if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { assertAttachSeamlessIframeSizesCorrectly( initSeamlessField('Hi!', {'margin': '2px 5px'}), createSeamlessIframe()); } } function testFieldWithBorder() { if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { assertAttachSeamlessIframeSizesCorrectly( initSeamlessField('Hi!', {'border': '2px 5px'}), createSeamlessIframe()); } } function testFieldWithOverflow() { if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { assertAttachSeamlessIframeSizesCorrectly( initSeamlessField(['1', '2', '3', '4', '5', '6', '7'].join('<p/>'), {'overflow': 'auto', 'position': 'relative', 'height': '20px'}), createSeamlessIframe()); assertEquals(20, fieldElem.offsetHeight); } } function testFieldWithOverflowAndPadding() { if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { var blendedField = initSeamlessField( ['1', '2', '3', '4', '5', '6', '7'].join('<p/>'), { 'overflow': 'auto', 'position': 'relative', 'height': '20px', 'padding': '2px 3px' }); var blendedIframe = createSeamlessIframe(); assertAttachSeamlessIframeSizesCorrectly(blendedField, blendedIframe); assertEquals(24, fieldElem.offsetHeight); } } function testIframeHeightGrowsOnWrap() { if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { var clock = new goog.testing.MockClock(true); var blendedField; try { blendedField = initSeamlessField('', {'border': '1px solid black', 'height': '20px'}); blendedField.makeEditable(); blendedField.setHtml(false, 'Content that should wrap after resize.'); // Ensure that the field was fully loaded and sized before measuring. clock.tick(1); // Capture starting heights. var unwrappedIframeHeight = blendedField.getEditableIframe().offsetHeight; // Resize the field such that the text should wrap. fieldElem.style.width = '200px'; blendedField.doFieldSizingGecko(); // Iframe should grow as a result. var wrappedIframeHeight = blendedField.getEditableIframe().offsetHeight; assertTrue('Wrapped text should cause iframe to grow - initial height: ' + unwrappedIframeHeight + ', wrapped height: ' + wrappedIframeHeight, wrappedIframeHeight > unwrappedIframeHeight); } finally { blendedField.dispose(); clock.dispose(); } } } function testDispatchIframeResizedForWrapperHeight() { if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { var clock = new goog.testing.MockClock(true); var blendedField = initSeamlessField('Hi!', {'border': '2px 5px'}); var iframe = createSeamlessIframe(); blendedField.attachIframe(iframe); var resizeCalled = false; goog.events.listenOnce( blendedField, goog.editor.Field.EventType.IFRAME_RESIZED, function() { resizeCalled = true; }); try { blendedField.makeEditable(); blendedField.setHtml(false, 'Content that should wrap after resize.'); // Ensure that the field was fully loaded and sized before measuring. clock.tick(1); assertFalse('Iframe resize must not be dispatched yet', resizeCalled); // Resize the field such that the text should wrap. fieldElem.style.width = '200px'; blendedField.sizeIframeToWrapperGecko_(); assertTrue('Iframe resize must be dispatched for Wrapper', resizeCalled); } finally { blendedField.dispose(); clock.dispose(); } } } function testDispatchIframeResizedForBodyHeight() { if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { var clock = new goog.testing.MockClock(true); var blendedField = initSeamlessField('Hi!', {'border': '2px 5px'}); var iframe = createSeamlessIframe(); blendedField.attachIframe(iframe); var resizeCalled = false; goog.events.listenOnce( blendedField, goog.editor.Field.EventType.IFRAME_RESIZED, function() { resizeCalled = true; }); try { blendedField.makeEditable(); blendedField.setHtml(false, 'Content that should wrap after resize.'); // Ensure that the field was fully loaded and sized before measuring. clock.tick(1); assertFalse('Iframe resize must not be dispatched yet', resizeCalled); // Resize the field to a different body height. var bodyHeight = blendedField.getIframeBodyHeightGecko_(); blendedField.getIframeBodyHeightGecko_ = function() { return bodyHeight + 1; }; blendedField.sizeIframeToBodyHeightGecko_(); assertTrue('Iframe resize must be dispatched for Body', resizeCalled); } finally { blendedField.dispose(); clock.dispose(); } } } function testDispatchBlur() { if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE && !goog.editor.BrowserFeature.CLEARS_SELECTION_WHEN_FOCUS_LEAVES) { var blendedField = initSeamlessField('Hi!', {'border': '2px 5px'}); var iframe = createSeamlessIframe(); blendedField.attachIframe(iframe); var blurCalled = false; goog.events.listenOnce(blendedField, goog.editor.Field.EventType.BLUR, function() { blurCalled = true; }); var clearSelection = goog.dom.Range.clearSelection; var cleared = false; var clearedWindow; blendedField.editableDomHelper = new goog.dom.DomHelper(); blendedField.editableDomHelper.getWindow = goog.functions.constant(iframe.contentWindow); var mockRange = new goog.testing.MockRange(); blendedField.getRange = function() { return mockRange; }; goog.dom.Range.clearSelection = function(opt_window) { clearSelection(opt_window); cleared = true; clearedWindow = opt_window; }; var clock = new goog.testing.MockClock(true); mockRange.collapse(true); mockRange.select(); mockRange.$replay(); blendedField.dispatchBlur(); clock.tick(1); assertTrue('Blur must be dispatched.', blurCalled); assertTrue('Selection must be cleared.', cleared); assertEquals('Selection must be cleared in iframe', iframe.contentWindow, clearedWindow); mockRange.$verify(); clock.dispose(); } } function testSetMinHeight() { if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { var clock = new goog.testing.MockClock(true); try { var field = initSeamlessField( ['1', '2', '3', '4', '5', '6', '7'].join('<p/>'), {'position': 'relative', 'height': '60px'}); // Initially create and size iframe. var iframe = createSeamlessIframe(); field.attachIframe(iframe); field.iframeFieldLoadHandler(iframe, '', {}); // Need to process timeouts set by load handlers. clock.tick(1000); var normalHeight = goog.style.getSize(iframe).height; var delayedChangeCalled = false; goog.events.listen(field, goog.editor.Field.EventType.DELAYEDCHANGE, function() { delayedChangeCalled = true; }); // Test that min height is obeyed. field.setMinHeight(30); clock.tick(1000); assertEquals('Iframe height must match min height.', 30, goog.style.getSize(iframe).height); assertFalse('Setting min height must not cause delayed change event.', delayedChangeCalled); // Test that min height doesn't shrink field. field.setMinHeight(0); clock.tick(1000); assertEquals(normalHeight, goog.style.getSize(iframe).height); assertFalse('Setting min height must not cause delayed change event.', delayedChangeCalled); } finally { goog.events.removeAll(); field.dispose(); clock.dispose(); } } } /** * @bug 1649967 This code used to throw a Javascript error. */ function testSetMinHeightWithNoIframe() { if (goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) { try { var field = initSeamlessField('&nbsp;', {}); field.makeEditable(); field.setMinHeight(30); } finally { field.dispose(); goog.events.removeAll(); } } } function testStartChangeEvents() { if (goog.editor.BrowserFeature.USE_MUTATION_EVENTS) { var clock = new goog.testing.MockClock(true); try { var field = initSeamlessField('&nbsp;', {}); field.makeEditable(); var changeCalled = false; goog.events.listenOnce(field, goog.editor.Field.EventType.CHANGE, function() { changeCalled = true; }); var delayedChangeCalled = false; goog.events.listenOnce(field, goog.editor.Field.EventType.CHANGE, function() { delayedChangeCalled = true; }); field.stopChangeEvents(true, true); if (field.changeTimerGecko_) { field.changeTimerGecko_.start(); } field.startChangeEvents(); clock.tick(1000); assertFalse(changeCalled); assertFalse(delayedChangeCalled); } finally { clock.dispose(); field.dispose(); } } } function testManipulateDom() { // Test in blended field since that is what fires change events. var editableField = initSeamlessField('&nbsp;', {}); var clock = new goog.testing.MockClock(true); var delayedChangeCalled = 0; goog.events.listen(editableField, goog.editor.Field.EventType.DELAYEDCHANGE, function() { delayedChangeCalled++; }); assertFalse(editableField.isLoaded()); editableField.manipulateDom(goog.nullFunction); clock.tick(1000); assertEquals('Must not fire delayed change events if field is not loaded.', 0, delayedChangeCalled); editableField.makeEditable(); var usesIframe = editableField.usesIframe(); try { editableField.manipulateDom(goog.nullFunction); clock.tick(1000); // Wait for delayed change to fire. assertEquals('By default must fire a single delayed change event.', 1, delayedChangeCalled); editableField.manipulateDom(goog.nullFunction, true); clock.tick(1000); // Wait for delayed change to fire. assertEquals('Must prevent all delayed change events.', 1, delayedChangeCalled); editableField.manipulateDom(function() { this.handleChange(); this.handleChange(); if (this.changeTimerGecko_) { this.changeTimerGecko_.fire(); } this.dispatchDelayedChange_(); this.delayedChangeTimer_.fire(); }, false, editableField); clock.tick(1000); // Wait for delayed change to fire. assertEquals('Must ignore dispatch delayed change called within func.', 2, delayedChangeCalled); } finally { // Ensure we always uninstall the mock clock and dispose of everything. editableField.dispose(); clock.dispose(); } } function testAttachIframe() { var blendedField = initSeamlessField('Hi!', {}); var iframe = createSeamlessIframe(); try { blendedField.attachIframe(iframe); } catch (err) { fail('Error occurred while attaching iframe.'); } } function createSeamlessIframe() { // NOTE(nicksantos): This is a reimplementation of // TR_EditableUtil.getIframeAttributes, but untangled for tests, and // specifically with what we need for blended mode. return goog.dom.createDom('IFRAME', { 'frameBorder': '0', 'style': 'padding:0;' }); } /** * Initialize a new editable field for the field id 'field', with the given * innerHTML and styles. * * @param {string} innerHTML html for the field contents. * @param {Object} styles Key-value pairs for styles on the field. * @return {goog.editor.SeamlessField} The field. */ function initSeamlessField(innerHTML, styles) { var field = new goog.editor.SeamlessField('field'); fieldElem.innerHTML = innerHTML; goog.style.setStyle(fieldElem, styles); return field; } /** * Make sure that the original field element for the given goog.editor.Field has * the same size before and after attaching the given iframe. If this is not * true, then the field will fidget while we're initializing the field, * and that's not what we want. * * @param {goog.editor.Field} fieldObj The field. * @param {HTMLIFrameElement} iframe The iframe. */ function assertAttachSeamlessIframeSizesCorrectly(fieldObj, iframe) { var size = goog.style.getSize(fieldObj.getOriginalElement()); fieldObj.attachIframe(iframe); var newSize = goog.style.getSize(fieldObj.getOriginalElement()); assertEquals(size.width, newSize.width); assertEquals(size.height, newSize.height); }
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Utilties for working with the styles of DOM nodes, and * related to rich text editing. * * Many of these are not general enough to go into goog.style, and use * constructs (like "isContainer") that only really make sense inside * of an HTML editor. * * The API has been optimized for iterating over large, irregular DOM * structures (with lots of text nodes), and so the API tends to be a bit * more permissive than the goog.style API should be. For example, * goog.style.getComputedStyle will throw an exception if you give it a * text node. * */ goog.provide('goog.editor.style'); goog.require('goog.dom'); goog.require('goog.dom.NodeType'); goog.require('goog.editor.BrowserFeature'); goog.require('goog.events.EventType'); goog.require('goog.object'); goog.require('goog.style'); goog.require('goog.userAgent'); /** * Gets the computed or cascaded style. * * This is different than goog.style.getStyle_ because it returns null * for text nodes (instead of throwing an exception), and never reads * inline style. These two functions may need to be reconciled. * * @param {Node} node Node to get style of. * @param {string} stylePropertyName Property to get (must be camelCase, * not css-style). * @return {?string} Style value, or null if this is not an element node. * @private */ goog.editor.style.getComputedOrCascadedStyle_ = function( node, stylePropertyName) { if (node.nodeType != goog.dom.NodeType.ELEMENT) { // Only element nodes have style. return null; } return goog.userAgent.IE ? goog.style.getCascadedStyle(/** @type {Element} */ (node), stylePropertyName) : goog.style.getComputedStyle(/** @type {Element} */ (node), stylePropertyName); }; /** * Checks whether the given element inherits display: block. * @param {Node} node The Node to check. * @return {boolean} Whether the element inherits CSS display: block. */ goog.editor.style.isDisplayBlock = function(node) { return goog.editor.style.getComputedOrCascadedStyle_( node, 'display') == 'block'; }; /** * Returns true if the element is a container of other non-inline HTML * Note that span, strong and em tags, being inline can only contain * other inline elements and are thus, not containers. Containers are elements * that should not be broken up when wrapping selections with a node of an * inline block styling. * @param {Node} element The element to check. * @return {boolean} Whether the element is a container. */ goog.editor.style.isContainer = function(element) { var nodeName = element && element.nodeName.toLowerCase(); return !!(element && (goog.editor.style.isDisplayBlock(element) || nodeName == 'td' || nodeName == 'table' || nodeName == 'li')); }; /** * Return the first ancestor of this node that is a container, inclusive. * @see isContainer * @param {Node} node Node to find the container of. * @return {Element} The element which contains node. */ goog.editor.style.getContainer = function(node) { // We assume that every node must have a container. return /** @type {Element} */ ( goog.dom.getAncestor(node, goog.editor.style.isContainer, true)); }; /** * Set of input types that should be kept selectable even when their ancestors * are made unselectable. * @type {Object} * @private */ goog.editor.style.SELECTABLE_INPUT_TYPES_ = goog.object.createSet( 'text', 'file', 'url'); /** * Prevent the default action on mousedown events. * @param {goog.events.Event} e The mouse down event. * @private */ goog.editor.style.cancelMouseDownHelper_ = function(e) { var targetTagName = e.target.tagName; if (targetTagName != goog.dom.TagName.TEXTAREA && targetTagName != goog.dom.TagName.INPUT) { e.preventDefault(); } }; /** * Makes the given element unselectable, as well as all of its children, except * for text areas, text, file and url inputs. * @param {Element} element The element to make unselectable. * @param {goog.events.EventHandler} eventHandler An EventHandler to register * the event with. Assumes when the node is destroyed, the eventHandler's * listeners are destroyed as well. */ goog.editor.style.makeUnselectable = function(element, eventHandler) { if (goog.editor.BrowserFeature.HAS_UNSELECTABLE_STYLE) { // The mousing down on a node should not blur the focused node. // This is consistent with how IE works. // TODO: Consider using just the mousedown handler and not the css property. eventHandler.listen(element, goog.events.EventType.MOUSEDOWN, goog.editor.style.cancelMouseDownHelper_, true); } goog.style.setUnselectable(element, true); // Make inputs and text areas selectable. var inputs = element.getElementsByTagName(goog.dom.TagName.INPUT); for (var i = 0, len = inputs.length; i < len; i++) { var input = inputs[i]; if (input.type in goog.editor.style.SELECTABLE_INPUT_TYPES_) { goog.editor.style.makeSelectable(input); } } goog.array.forEach(element.getElementsByTagName(goog.dom.TagName.TEXTAREA), goog.editor.style.makeSelectable); }; /** * Make the given element selectable. * * For IE this simply turns off the "unselectable" property. * * Under FF no descendent of an unselectable node can be selectable: * * https://bugzilla.mozilla.org/show_bug.cgi?id=203291 * * So we make each ancestor of node selectable, while trying to preserve the * unselectability of other nodes along that path * * This may cause certain text nodes which should be unselectable, to become * selectable. For example: * * <div id=div1 style="-moz-user-select: none"> * Text1 * <span id=span1>Text2</span> * </div> * * If we call makeSelectable on span1, then it will cause "Text1" to become * selectable, since it had to make div1 selectable in order for span1 to be * selectable. * * If "Text1" were enclosed within a <p> or <span>, then this problem would * not arise. Text nodes do not have styles, so its style can't be set to * unselectable. * * @param {Element} element The element to make selectable. */ goog.editor.style.makeSelectable = function(element) { goog.style.setUnselectable(element, false); if (goog.editor.BrowserFeature.HAS_UNSELECTABLE_STYLE) { // Go up ancestor chain, searching for nodes that are unselectable. // If such a node exists, mark it as selectable but mark its other children // as unselectable so the minimum set of nodes is changed. var child = element; var current = /** @type {Element} */ (element.parentNode); while (current && current.tagName != goog.dom.TagName.HTML) { if (goog.style.isUnselectable(current)) { goog.style.setUnselectable(current, false, true); for (var i = 0, len = current.childNodes.length; i < len; i++) { var node = current.childNodes[i]; if (node != child && node.nodeType == goog.dom.NodeType.ELEMENT) { goog.style.setUnselectable(current.childNodes[i], true); } } } child = current; current = /** @type {Element} */ (current.parentNode); } } };
JavaScript
// Copyright 2005 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Utilties for working with DOM nodes related to rich text * editing. Many of these are not general enough to go into goog.dom. * */ goog.provide('goog.editor.node'); goog.require('goog.dom'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.TagName'); goog.require('goog.dom.iter.ChildIterator'); goog.require('goog.dom.iter.SiblingIterator'); goog.require('goog.iter'); goog.require('goog.object'); goog.require('goog.string'); goog.require('goog.string.Unicode'); goog.require('goog.userAgent'); /** * Names of all block-level tags * @type {Object} * @private */ goog.editor.node.BLOCK_TAG_NAMES_ = goog.object.createSet( goog.dom.TagName.ADDRESS, goog.dom.TagName.ARTICLE, goog.dom.TagName.ASIDE, goog.dom.TagName.BLOCKQUOTE, goog.dom.TagName.BODY, goog.dom.TagName.CAPTION, goog.dom.TagName.CENTER, goog.dom.TagName.COL, goog.dom.TagName.COLGROUP, goog.dom.TagName.DETAILS, goog.dom.TagName.DIR, goog.dom.TagName.DIV, goog.dom.TagName.DL, goog.dom.TagName.DD, goog.dom.TagName.DT, goog.dom.TagName.FIELDSET, goog.dom.TagName.FIGCAPTION, goog.dom.TagName.FIGURE, goog.dom.TagName.FOOTER, goog.dom.TagName.FORM, goog.dom.TagName.H1, goog.dom.TagName.H2, goog.dom.TagName.H3, goog.dom.TagName.H4, goog.dom.TagName.H5, goog.dom.TagName.H6, goog.dom.TagName.HEADER, goog.dom.TagName.HGROUP, goog.dom.TagName.HR, goog.dom.TagName.ISINDEX, goog.dom.TagName.OL, goog.dom.TagName.LI, goog.dom.TagName.MAP, goog.dom.TagName.MENU, goog.dom.TagName.NAV, goog.dom.TagName.OPTGROUP, goog.dom.TagName.OPTION, goog.dom.TagName.P, goog.dom.TagName.PRE, goog.dom.TagName.SECTION, goog.dom.TagName.SUMMARY, goog.dom.TagName.TABLE, goog.dom.TagName.TBODY, goog.dom.TagName.TD, goog.dom.TagName.TFOOT, goog.dom.TagName.TH, goog.dom.TagName.THEAD, goog.dom.TagName.TR, goog.dom.TagName.UL); /** * Names of tags that have intrinsic content. * TODO(robbyw): What about object, br, input, textarea, button, isindex, * hr, keygen, select, table, tr, td? * @type {Object} * @private */ goog.editor.node.NON_EMPTY_TAGS_ = goog.object.createSet( goog.dom.TagName.IMG, goog.dom.TagName.IFRAME, goog.dom.TagName.EMBED); /** * Check if the node is in a standards mode document. * @param {Node} node The node to test. * @return {boolean} Whether the node is in a standards mode document. */ goog.editor.node.isStandardsMode = function(node) { return goog.dom.getDomHelper(node).isCss1CompatMode(); }; /** * Get the right-most non-ignorable leaf node of the given node. * @param {Node} parent The parent ndoe. * @return {Node} The right-most non-ignorable leaf node. */ goog.editor.node.getRightMostLeaf = function(parent) { var temp; while (temp = goog.editor.node.getLastChild(parent)) { parent = temp; } return parent; }; /** * Get the left-most non-ignorable leaf node of the given node. * @param {Node} parent The parent ndoe. * @return {Node} The left-most non-ignorable leaf node. */ goog.editor.node.getLeftMostLeaf = function(parent) { var temp; while (temp = goog.editor.node.getFirstChild(parent)) { parent = temp; } return parent; }; /** * Version of firstChild that skips nodes that are entirely * whitespace and comments. * @param {Node} parent The reference node. * @return {Node} The first child of sibling that is important according to * goog.editor.node.isImportant, or null if no such node exists. */ goog.editor.node.getFirstChild = function(parent) { return goog.editor.node.getChildHelper_(parent, false); }; /** * Version of lastChild that skips nodes that are entirely whitespace or * comments. (Normally lastChild is a property of all DOM nodes that gives the * last of the nodes contained directly in the reference node.) * @param {Node} parent The reference node. * @return {Node} The last child of sibling that is important according to * goog.editor.node.isImportant, or null if no such node exists. */ goog.editor.node.getLastChild = function(parent) { return goog.editor.node.getChildHelper_(parent, true); }; /** * Version of previoussibling that skips nodes that are entirely * whitespace or comments. (Normally previousSibling is a property * of all DOM nodes that gives the sibling node, the node that is * a child of the same parent, that occurs immediately before the * reference node.) * @param {Node} sibling The reference node. * @return {Node} The closest previous sibling to sibling that is * important according to goog.editor.node.isImportant, or null if no such * node exists. */ goog.editor.node.getPreviousSibling = function(sibling) { return /** @type {Node} */ (goog.editor.node.getFirstValue_( goog.iter.filter(new goog.dom.iter.SiblingIterator(sibling, false, true), goog.editor.node.isImportant))); }; /** * Version of nextSibling that skips nodes that are entirely whitespace or * comments. * @param {Node} sibling The reference node. * @return {Node} The closest next sibling to sibling that is important * according to goog.editor.node.isImportant, or null if no * such node exists. */ goog.editor.node.getNextSibling = function(sibling) { return /** @type {Node} */ (goog.editor.node.getFirstValue_( goog.iter.filter(new goog.dom.iter.SiblingIterator(sibling), goog.editor.node.isImportant))); }; /** * Internal helper for lastChild/firstChild that skips nodes that are entirely * whitespace or comments. * @param {Node} parent The reference node. * @param {boolean} isReversed Whether children should be traversed forward * or backward. * @return {Node} The first/last child of sibling that is important according * to goog.editor.node.isImportant, or null if no such node exists. * @private */ goog.editor.node.getChildHelper_ = function(parent, isReversed) { return (!parent || parent.nodeType != goog.dom.NodeType.ELEMENT) ? null : /** @type {Node} */ (goog.editor.node.getFirstValue_(goog.iter.filter( new goog.dom.iter.ChildIterator( /** @type {Element} */ (parent), isReversed), goog.editor.node.isImportant))); }; /** * Utility function that returns the first value from an iterator or null if * the iterator is empty. * @param {goog.iter.Iterator} iterator The iterator to get a value from. * @return {*} The first value from the iterator. * @private */ goog.editor.node.getFirstValue_ = function(iterator) { /** @preserveTry */ try { return iterator.next(); } catch (e) { return null; } }; /** * Determine if a node should be returned by the iterator functions. * @param {Node} node An object implementing the DOM1 Node interface. * @return {boolean} Whether the node is an element, or a text node that * is not all whitespace. */ goog.editor.node.isImportant = function(node) { // Return true if the node is not either a TextNode or an ElementNode. return node.nodeType == goog.dom.NodeType.ELEMENT || node.nodeType == goog.dom.NodeType.TEXT && !goog.editor.node.isAllNonNbspWhiteSpace(node); }; /** * Determine whether a node's text content is entirely whitespace. * @param {Node} textNode A node implementing the CharacterData interface (i.e., * a Text, Comment, or CDATASection node. * @return {boolean} Whether the text content of node is whitespace, * otherwise false. */ goog.editor.node.isAllNonNbspWhiteSpace = function(textNode) { return goog.string.isBreakingWhitespace(textNode.nodeValue); }; /** * Returns true if the node contains only whitespace and is not and does not * contain any images, iframes or embed tags. * @param {Node} node The node to check. * @param {boolean=} opt_prohibitSingleNbsp By default, this function treats a * single nbsp as empty. Set this to true to treat this case as non-empty. * @return {boolean} Whether the node contains only whitespace. */ goog.editor.node.isEmpty = function(node, opt_prohibitSingleNbsp) { var nodeData = goog.dom.getRawTextContent(node); if (node.getElementsByTagName) { for (var tag in goog.editor.node.NON_EMPTY_TAGS_) { if (node.tagName == tag || node.getElementsByTagName(tag).length > 0) { return false; } } } return (!opt_prohibitSingleNbsp && nodeData == goog.string.Unicode.NBSP) || goog.string.isBreakingWhitespace(nodeData); }; /** * Returns the length of the text in node if it is a text node, or the number * of children of the node, if it is an element. Useful for range-manipulation * code where you need to know the offset for the right side of the node. * @param {Node} node The node to get the length of. * @return {number} The length of the node. */ goog.editor.node.getLength = function(node) { return node.length || node.childNodes.length; }; /** * Search child nodes using a predicate function and return the first node that * satisfies the condition. * @param {Node} parent The parent node to search. * @param {function(Node):boolean} hasProperty A function that takes a child * node as a parameter and returns true if it meets the criteria. * @return {?number} The index of the node found, or null if no node is found. */ goog.editor.node.findInChildren = function(parent, hasProperty) { for (var i = 0, len = parent.childNodes.length; i < len; i++) { if (hasProperty(parent.childNodes[i])) { return i; } } return null; }; /** * Search ancestor nodes using a predicate function and returns the topmost * ancestor in the chain of consecutive ancestors that satisfies the condition. * * @param {Node} node The node whose ancestors have to be searched. * @param {function(Node): boolean} hasProperty A function that takes a parent * node as a parameter and returns true if it meets the criteria. * @return {Node} The topmost ancestor or null if no ancestor satisfies the * predicate function. */ goog.editor.node.findHighestMatchingAncestor = function(node, hasProperty) { var parent = node.parentNode; var ancestor = null; while (parent && hasProperty(parent)) { ancestor = parent; parent = parent.parentNode; } return ancestor; }; /** * Checks if node is a block-level html element. The <tt>display</tt> css * property is ignored. * @param {Node} node The node to test. * @return {boolean} Whether the node is a block-level node. */ goog.editor.node.isBlockTag = function(node) { return !!goog.editor.node.BLOCK_TAG_NAMES_[node.tagName]; }; /** * Skips siblings of a node that are empty text nodes. * @param {Node} node A node. May be null. * @return {Node} The node or the first sibling of the node that is not an * empty text node. May be null. */ goog.editor.node.skipEmptyTextNodes = function(node) { while (node && node.nodeType == goog.dom.NodeType.TEXT && !node.nodeValue) { node = node.nextSibling; } return node; }; /** * Checks if an element is a top-level editable container (meaning that * it itself is not editable, but all its child nodes are editable). * @param {Node} element The element to test. * @return {boolean} Whether the element is a top-level editable container. */ goog.editor.node.isEditableContainer = function(element) { return element.getAttribute && element.getAttribute('g_editable') == 'true'; }; /** * Checks if a node is inside an editable container. * @param {Node} node The node to test. * @return {boolean} Whether the node is in an editable container. */ goog.editor.node.isEditable = function(node) { return !!goog.dom.getAncestor(node, goog.editor.node.isEditableContainer); }; /** * Finds the top-most DOM node inside an editable field that is an ancestor * (or self) of a given DOM node and meets the specified criteria. * @param {Node} node The DOM node where the search starts. * @param {function(Node) : boolean} criteria A function that takes a DOM node * as a parameter and returns a boolean to indicate whether the node meets * the criteria or not. * @return {Node} The DOM node if found, or null. */ goog.editor.node.findTopMostEditableAncestor = function(node, criteria) { var targetNode = null; while (node && !goog.editor.node.isEditableContainer(node)) { if (criteria(node)) { targetNode = node; } node = node.parentNode; } return targetNode; }; /** * Splits off a subtree. * @param {!Node} currentNode The starting splitting point. * @param {Node=} opt_secondHalf The initial leftmost leaf the new subtree. * If null, siblings after currentNode will be placed in the subtree, but * no additional node will be. * @param {Node=} opt_root The top of the tree where splitting stops at. * @return {!Node} The new subtree. */ goog.editor.node.splitDomTreeAt = function(currentNode, opt_secondHalf, opt_root) { var parent; while (currentNode != opt_root && (parent = currentNode.parentNode)) { opt_secondHalf = goog.editor.node.getSecondHalfOfNode_(parent, currentNode, opt_secondHalf); currentNode = parent; } return /** @type {!Node} */(opt_secondHalf); }; /** * Creates a clone of node, moving all children after startNode to it. * When firstChild is not null or undefined, it is also appended to the clone * as the first child. * @param {!Node} node The node to clone. * @param {!Node} startNode All siblings after this node will be moved to the * clone. * @param {Node|undefined} firstChild The first child of the new cloned element. * @return {!Node} The cloned node that now contains the children after * startNode. * @private */ goog.editor.node.getSecondHalfOfNode_ = function(node, startNode, firstChild) { var secondHalf = /** @type {!Node} */(node.cloneNode(false)); while (startNode.nextSibling) { goog.dom.appendChild(secondHalf, startNode.nextSibling); } if (firstChild) { secondHalf.insertBefore(firstChild, secondHalf.firstChild); } return secondHalf; }; /** * Appends all of oldNode's children to newNode. This removes all children from * oldNode and appends them to newNode. oldNode is left with no children. * @param {!Node} newNode Node to transfer children to. * @param {Node} oldNode Node to transfer children from. * @deprecated Use goog.dom.append directly instead. */ goog.editor.node.transferChildren = function(newNode, oldNode) { goog.dom.append(newNode, oldNode.childNodes); }; /** * Replaces the innerHTML of a node. * * IE has serious problems if you try to set innerHTML of an editable node with * any selection. Early versions of IE tear up the old internal tree storage, to * help avoid ref-counting loops. But this sometimes leaves the selection object * in a bad state and leads to segfaults. * * Removing the nodes first prevents IE from tearing them up. This is not * strictly necessary in nodes that do not have the selection. You should always * use this function when setting innerHTML inside of a field. * * @param {Node} node A node. * @param {string} html The innerHTML to set on the node. */ goog.editor.node.replaceInnerHtml = function(node, html) { // Only do this IE. On gecko, we use element change events, and don't // want to trigger spurious events. if (goog.userAgent.IE) { goog.dom.removeChildren(node); } node.innerHTML = html; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Shared tests for goog.editor.Field and ContentEditableField. * Since ContentEditableField switches many of the internal code paths in Field * (such as via usesIframe()) it's important to re-run a lot of the same tests. * * @author nicksantos@google.com (Nick Santos) * @author jparent@google.com (Julie Parent) * @author gboyer@google.com (Garrett Boyer) */ /** @suppress {extraProvide} */ goog.provide('goog.editor.field_test'); goog.require('goog.dom'); goog.require('goog.dom.Range'); goog.require('goog.editor.BrowserFeature'); goog.require('goog.editor.Field'); goog.require('goog.editor.Plugin'); goog.require('goog.editor.range'); goog.require('goog.events'); goog.require('goog.events.BrowserEvent'); goog.require('goog.events.KeyCodes'); goog.require('goog.functions'); goog.require('goog.testing.LooseMock'); goog.require('goog.testing.MockClock'); goog.require('goog.testing.dom'); goog.require('goog.testing.events'); goog.require('goog.testing.events.Event'); goog.require('goog.testing.recordFunction'); goog.require('goog.userAgent'); goog.setTestOnly('Tests for goog.editor.*Field'); /** Constructor to use for creating the field. Set by the test HTML file. */ var FieldConstructor; /** Hard-coded HTML for the tests. */ var HTML = '<div id="testField">I am text.</div>'; function setUp() { goog.dom.getElement('parent').innerHTML = HTML; assertTrue('FieldConstructor should be set by the test HTML file', goog.isFunction(FieldConstructor)); } function tearDown() { // NOTE(nicksantos): I think IE is blowing up on this call because // it is lame. It manifests its lameness by throwing an exception. // Kudos to XT for helping me to figure this out. try { goog.events.removeAll(); } catch (e) {} } // Tests for the plugin interface. /** * Dummy plugin for test usage. * @constructor * @extends {goog.editor.Plugin} */ function TestPlugin() { this.getTrogClassId = function() { return 'TestPlugin'; }; this.handleKeyDown = goog.nullFunction; this.handleKeyPress = goog.nullFunction; this.handleKeyUp = goog.nullFunction; this.handleKeyboardShortcut = goog.nullFunction; this.isSupportedCommand = goog.nullFunction; this.execCommandInternal = goog.nullFunction; this.queryCommandValue = goog.nullFunction; this.activeOnUneditableFields = goog.nullFunction; this.handleSelectionChange = goog.nullFunction; } goog.inherits(TestPlugin, goog.editor.Plugin); /** * Tests that calling registerPlugin will add the plugin to the * plugin map. */ function testRegisterPlugin() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); editableField.registerPlugin(plugin); assertEquals('Registered plugin must be in protected plugin map.', plugin, editableField.plugins_[plugin.getTrogClassId()]); assertEquals('Plugin has a keydown handler, should be in keydown map', plugin, editableField.indexedPlugins_[goog.editor.Plugin.Op.KEYDOWN][0]); assertEquals('Plugin has a keypress handler, should be in keypress map', plugin, editableField.indexedPlugins_[goog.editor.Plugin.Op.KEYPRESS][0]); assertEquals('Plugin has a keyup handler, should be in keuup map', plugin, editableField.indexedPlugins_[goog.editor.Plugin.Op.KEYUP][0]); assertEquals( 'Plugin has a selectionchange handler, should be in selectionchange map', plugin, editableField.indexedPlugins_[goog.editor.Plugin.Op.SELECTION][0]); assertEquals('Plugin has a shortcut handler, should be in shortcut map', plugin, editableField.indexedPlugins_[goog.editor.Plugin.Op.SHORTCUT][0]); assertEquals('Plugin has a execCommand, should be in execCommand map', plugin, editableField.indexedPlugins_[goog.editor.Plugin.Op.EXEC_COMMAND][0]); assertEquals('Plugin has a queryCommand, should be in queryCommand map', plugin, editableField.indexedPlugins_[goog.editor.Plugin.Op.QUERY_COMMAND][0]); assertEquals('Plugin does not have a prepareContentsHtml,' + 'should not be in prepareContentsHtml map', undefined, editableField.indexedPlugins_[ goog.editor.Plugin.Op.PREPARE_CONTENTS_HTML][0]); assertEquals('Plugin does not have a cleanContentsDom,' + 'should not be in cleanContentsDom map', undefined, editableField.indexedPlugins_[ goog.editor.Plugin.Op.CLEAN_CONTENTS_DOM][0]); assertEquals('Plugin does not have a cleanContentsHtml,' + 'should not be in cleanContentsHtml map', undefined, editableField.indexedPlugins_[ goog.editor.Plugin.Op.CLEAN_CONTENTS_HTML][0]); editableField.dispose(); } /** * Tests that calling unregisterPlugin will remove the plugin from * the map. */ function testUnregisterPlugin() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); editableField.registerPlugin(plugin); editableField.unregisterPlugin(plugin); assertUndefined('Unregistered plugin must not be in protected plugin map.', editableField.plugins_[plugin.getTrogClassId()]); editableField.dispose(); } /** * Tests that registered plugins can be fetched by their id. */ function testGetPluginByClassId() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); assertUndefined('Must not be able to get unregistered plugins by class id.', editableField.getPluginByClassId(plugin.getTrogClassId())); editableField.registerPlugin(plugin); assertEquals('Must be able to get registered plugins by class id.', plugin, editableField.getPluginByClassId(plugin.getTrogClassId())); editableField.dispose(); } /** * Tests that plugins get auto disposed by default when the field is disposed. * Tests that plugins with setAutoDispose(false) do not get disposed when the * field is disposed. */ function testDisposed_PluginAutoDispose() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var noDisposePlugin = new goog.editor.Plugin(); noDisposePlugin.getTrogClassId = function() { return 'noDisposeId'; }; noDisposePlugin.setAutoDispose(false); editableField.registerPlugin(plugin); editableField.registerPlugin(noDisposePlugin); editableField.dispose(); assert(editableField.isDisposed()); assertTrue(plugin.isDisposed()); assertFalse(noDisposePlugin.isDisposed()); } var STRING_KEY = String.fromCharCode(goog.events.KeyCodes.A).toLowerCase(); /** * @return {goog.events.Event} Returns an event for a keyboard shortcut * for the letter 'a'. */ function getBrowserEvent() { var e = new goog.events.BrowserEvent(); e.ctrlKey = true; e.metaKey = true; e.charCode = goog.events.KeyCodes.A; return e; } /** * Tests that plugins are disabled when the field is made uneditable. */ function testMakeUneditableDisablesPlugins() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var calls = 0; plugin.disable = function(field) { assertEquals(editableField, field); assertTrue(field.isUneditable()); calls++; }; editableField.registerPlugin(plugin); editableField.makeEditable(); assertEquals(0, calls); editableField.makeUneditable(); assertEquals(1, calls); editableField.dispose(); } /** * Test that if a plugin registers keyup, it gets called. */ function testPluginKeyUp() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var e = getBrowserEvent(); var mockPlugin = new goog.testing.LooseMock(plugin); mockPlugin.getTrogClassId().$returns('mockPlugin'); mockPlugin.registerFieldObject(editableField); mockPlugin.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin.handleKeyUp(e); mockPlugin.$replay(); editableField.registerPlugin(mockPlugin); editableField.handleKeyUp_(e); mockPlugin.$verify(); } /** * Test that if a plugin registers keydown, it gets called. */ function testPluginKeyDown() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var e = getBrowserEvent(); var mockPlugin = new goog.testing.LooseMock(plugin); mockPlugin.getTrogClassId().$returns('mockPlugin'); mockPlugin.registerFieldObject(editableField); mockPlugin.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin.handleKeyDown(e).$returns(true); mockPlugin.$replay(); editableField.registerPlugin(mockPlugin); editableField.handleKeyDown_(e); mockPlugin.$verify(); } /** * Test that if a plugin registers keypress, it gets called. */ function testPluginKeyPress() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var e = getBrowserEvent(); var mockPlugin = new goog.testing.LooseMock(plugin); mockPlugin.getTrogClassId().$returns('mockPlugin'); mockPlugin.registerFieldObject(editableField); mockPlugin.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin.handleKeyPress(e).$returns(true); mockPlugin.$replay(); editableField.registerPlugin(mockPlugin); editableField.handleKeyPress_(e); mockPlugin.$verify(); } /** * If one plugin handles a key event, the rest of the plugins do not get their * key handlers invoked. */ function testHandledKeyEvent() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var e = getBrowserEvent(); var mockPlugin1 = new goog.testing.LooseMock(plugin); mockPlugin1.getTrogClassId().$returns('mockPlugin1'); mockPlugin1.registerFieldObject(editableField); mockPlugin1.isEnabled(editableField).$anyTimes().$returns(true); if (goog.editor.BrowserFeature.USES_KEYDOWN) { mockPlugin1.handleKeyDown(e).$returns(true); } else { mockPlugin1.handleKeyPress(e).$returns(true); } mockPlugin1.handleKeyUp(e).$returns(true); mockPlugin1.$replay(); var mockPlugin2 = new goog.testing.LooseMock(plugin); mockPlugin2.getTrogClassId().$returns('mockPlugin2'); mockPlugin2.registerFieldObject(editableField); mockPlugin2.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin2.$replay(); editableField.registerPlugin(mockPlugin1); editableField.registerPlugin(mockPlugin2); editableField.handleKeyUp_(e); if (goog.editor.BrowserFeature.USES_KEYDOWN) { editableField.handleKeyDown_(e); } else { editableField.handleKeyPress_(e); } mockPlugin1.$verify(); mockPlugin2.$verify(); } /** * Tests to make sure the cut and paste events are not dispatched immediately. */ function testHandleCutAndPasteEvents() { if (goog.editor.BrowserFeature.USE_MUTATION_EVENTS) { // Cut and paste events do not raise events at all in Mozilla. return; } var editableField = new FieldConstructor('testField'); var clock = new goog.testing.MockClock(true); var delayedChanges = goog.testing.recordFunction(); goog.events.listen(editableField, goog.editor.Field.EventType.DELAYEDCHANGE, delayedChanges); editableField.makeEditable(); goog.testing.events.fireBrowserEvent( new goog.testing.events.Event('cut', editableField.getElement())); assertEquals('Cut event should be on a timer', 0, delayedChanges.getCallCount()); clock.tick(1000); assertEquals('delayed change event should fire within 1s after cut', 1, delayedChanges.getCallCount()); goog.testing.events.fireBrowserEvent( new goog.testing.events.Event('paste', editableField.getElement())); assertEquals('Paste event should be on a timer', 1, delayedChanges.getCallCount()); clock.tick(1000); assertEquals('delayed change event should fire within 1s after paste', 2, delayedChanges.getCallCount()); clock.dispose(); editableField.dispose(); } /** * If the first plugin does not handle the key event, the next plugin gets * a chance to handle it. */ function testNotHandledKeyEvent() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var e = getBrowserEvent(); var mockPlugin1 = new goog.testing.LooseMock(plugin); mockPlugin1.getTrogClassId().$returns('mockPlugin1'); mockPlugin1.registerFieldObject(editableField); mockPlugin1.isEnabled(editableField).$anyTimes().$returns(true); if (goog.editor.BrowserFeature.USES_KEYDOWN) { mockPlugin1.handleKeyDown(e).$returns(false); } else { mockPlugin1.handleKeyPress(e).$returns(false); } mockPlugin1.handleKeyUp(e).$returns(false); mockPlugin1.$replay(); var mockPlugin2 = new goog.testing.LooseMock(plugin); mockPlugin2.getTrogClassId().$returns('mockPlugin2'); mockPlugin2.registerFieldObject(editableField); mockPlugin2.isEnabled(editableField).$anyTimes().$returns(true); if (goog.editor.BrowserFeature.USES_KEYDOWN) { mockPlugin2.handleKeyDown(e).$returns(true); } else { mockPlugin2.handleKeyPress(e).$returns(true); } mockPlugin2.handleKeyUp(e).$returns(true); mockPlugin2.$replay(); editableField.registerPlugin(mockPlugin1); editableField.registerPlugin(mockPlugin2); editableField.handleKeyUp_(e); if (goog.editor.BrowserFeature.USES_KEYDOWN) { editableField.handleKeyDown_(e); } else { editableField.handleKeyPress_(e); } mockPlugin1.$verify(); mockPlugin2.$verify(); } /** * Make sure that handleKeyboardShortcut is called if other key handlers * return false. */ function testKeyboardShortcutCalled() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var e = getBrowserEvent(); var mockPlugin = new goog.testing.LooseMock(plugin); mockPlugin.getTrogClassId().$returns('mockPlugin'); mockPlugin.registerFieldObject(editableField); mockPlugin.isEnabled(editableField).$anyTimes().$returns(true); if (goog.editor.BrowserFeature.USES_KEYDOWN) { mockPlugin.handleKeyDown(e).$returns(false); } else { mockPlugin.handleKeyPress(e).$returns(false); } mockPlugin.handleKeyboardShortcut(e, STRING_KEY, true).$returns(false); mockPlugin.$replay(); editableField.registerPlugin(mockPlugin); if (goog.editor.BrowserFeature.USES_KEYDOWN) { editableField.handleKeyDown_(e); } else { editableField.handleKeyPress_(e); } mockPlugin.$verify(); } /** * Make sure that handleKeyboardShortcut is not called if other key handlers * return true. */ function testKeyboardShortcutNotCalled() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var e = getBrowserEvent(); var mockPlugin = new goog.testing.LooseMock(plugin); mockPlugin.getTrogClassId().$returns('mockPlugin'); mockPlugin.registerFieldObject(editableField); mockPlugin.isEnabled(editableField).$anyTimes().$returns(true); if (goog.editor.BrowserFeature.USES_KEYDOWN) { mockPlugin.handleKeyDown(e).$returns(true); } else { mockPlugin.handleKeyPress(e).$returns(true); } mockPlugin.$replay(); editableField.registerPlugin(mockPlugin); if (goog.editor.BrowserFeature.USES_KEYDOWN) { editableField.handleKeyDown_(e); } else { editableField.handleKeyPress_(e); } mockPlugin.$verify(); } /** * Make sure that handleKeyboardShortcut is not called if alt is pressed. * @bug 1363959 */ function testKeyHandlingAlt() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var e = getBrowserEvent(); e.altKey = true; var mockPlugin = new goog.testing.LooseMock(plugin); mockPlugin.getTrogClassId().$returns('mockPlugin'); mockPlugin.registerFieldObject(editableField); mockPlugin.isEnabled(editableField).$anyTimes().$returns(true); if (goog.editor.BrowserFeature.USES_KEYDOWN) { mockPlugin.handleKeyDown(e).$returns(false); } else { mockPlugin.handleKeyPress(e).$returns(false); } mockPlugin.$replay(); editableField.registerPlugin(mockPlugin); if (goog.editor.BrowserFeature.USES_KEYDOWN) { editableField.handleKeyDown_(e); } else { editableField.handleKeyPress_(e); } mockPlugin.$verify(); } /** * Test that if a plugin has an execCommand function, it gets called * but only for supported commands. */ function testPluginExecCommand() { var plugin = new TestPlugin(); var passedCommand, passedArg; plugin.execCommand = function(command, arg) { passedCommand = command; passedArg = arg; }; var editableField = new FieldConstructor('testField'); editableField.registerPlugin(plugin); plugin.enable(editableField); plugin.isSupportedCommand = goog.functions.constant(true); editableField.execCommand('+indent', true); // Verify that the plugin's execCommand was called with the correct // args. assertEquals('+indent', passedCommand); assertTrue(passedArg); passedCommand = null; passedArg = null; plugin.isSupportedCommand = goog.functions.constant(false); editableField.execCommand('+outdent', false); // Verify that a plugin's execCommand is not called if it isn't a supported // command. assertNull(passedCommand); assertNull(passedArg); editableField.dispose(); plugin.dispose(); } /** * Test that if one plugin supports execCommand, no other plugins * get a chance to handle the execComand. */ function testSupportedExecCommand() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var mockPlugin1 = new goog.testing.LooseMock(plugin); mockPlugin1.getTrogClassId().$returns('mockPlugin1'); mockPlugin1.registerFieldObject(editableField); mockPlugin1.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin1.isSupportedCommand('+indent').$returns(true); mockPlugin1.execCommandInternal('+indent').$returns(true); mockPlugin1.execCommand('+indent').$does( function() { mockPlugin1.execCommandInternal('+indent'); }); mockPlugin1.$replay(); var mockPlugin2 = new goog.testing.LooseMock(plugin); mockPlugin2.getTrogClassId().$returns('mockPlugin2'); mockPlugin2.registerFieldObject(editableField); mockPlugin2.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin2.$replay(); editableField.registerPlugin(mockPlugin1); editableField.registerPlugin(mockPlugin2); editableField.execCommand('+indent'); mockPlugin1.$verify(); mockPlugin2.$verify(); } /** * Test that if the first plugin does not support execCommand, the other * plugins get a chance to handle the execCommand. */ function testNotSupportedExecCommand() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var mockPlugin1 = new goog.testing.LooseMock(plugin); mockPlugin1.getTrogClassId().$returns('mockPlugin1'); mockPlugin1.registerFieldObject(editableField); mockPlugin1.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin1.isSupportedCommand('+indent').$returns(false); mockPlugin1.$replay(); var mockPlugin2 = new goog.testing.LooseMock(plugin); mockPlugin2.getTrogClassId().$returns('mockPlugin2'); mockPlugin2.registerFieldObject(editableField); mockPlugin2.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin2.isSupportedCommand('+indent').$returns(true); mockPlugin2.execCommandInternal('+indent').$returns(true); mockPlugin2.execCommand('+indent').$does( function() { mockPlugin2.execCommandInternal('+indent'); }); mockPlugin2.$replay(); editableField.registerPlugin(mockPlugin1); editableField.registerPlugin(mockPlugin2); editableField.execCommand('+indent'); mockPlugin1.$verify(); mockPlugin2.$verify(); } /** * Tests that if a plugin supports a command that its queryCommandValue * gets called and no further plugins can handle the queryCommandValue. */ function testSupportedQueryCommand() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var mockPlugin1 = new goog.testing.LooseMock(plugin); mockPlugin1.getTrogClassId().$returns('mockPlugin1'); mockPlugin1.registerFieldObject(editableField); mockPlugin1.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin1.isSupportedCommand('+indent').$returns(true); mockPlugin1.queryCommandValue('+indent').$returns(true); mockPlugin1.activeOnUneditableFields().$returns(true); mockPlugin1.$replay(); var mockPlugin2 = new goog.testing.LooseMock(plugin); mockPlugin2.getTrogClassId().$returns('mockPlugin2'); mockPlugin2.registerFieldObject(editableField); mockPlugin2.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin2.$replay(); editableField.registerPlugin(mockPlugin1); editableField.registerPlugin(mockPlugin2); editableField.queryCommandValue('+indent'); mockPlugin1.$verify(); mockPlugin2.$verify(); } /** * Tests that if the first plugin does not support a command that its * queryCommandValue do not get called and the next plugin can handle the * queryCommandValue. */ function testNotSupportedQueryCommand() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var mockPlugin1 = new goog.testing.LooseMock(plugin); mockPlugin1.getTrogClassId().$returns('mockPlugin1'); mockPlugin1.registerFieldObject(editableField); mockPlugin1.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin1.isSupportedCommand('+indent').$returns(false); mockPlugin1.$replay(); var mockPlugin2 = new goog.testing.LooseMock(plugin); mockPlugin2.getTrogClassId().$returns('mockPlugin2'); mockPlugin2.registerFieldObject(editableField); mockPlugin2.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin2.isSupportedCommand('+indent').$returns(true); mockPlugin2.queryCommandValue('+indent').$returns(true); mockPlugin2.activeOnUneditableFields().$returns(true); mockPlugin2.$replay(); editableField.registerPlugin(mockPlugin1); editableField.registerPlugin(mockPlugin2); editableField.queryCommandValue('+indent'); mockPlugin1.$verify(); mockPlugin2.$verify(); } /** * Tests that if a plugin handles selectionChange that it gets called and * no further plugins can handle the selectionChange. */ function testHandledSelectionChange() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var e = getBrowserEvent(); var mockPlugin1 = new goog.testing.LooseMock(plugin); mockPlugin1.getTrogClassId().$returns('mockPlugin1'); mockPlugin1.registerFieldObject(editableField); mockPlugin1.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin1.handleSelectionChange(e, undefined).$returns(true); mockPlugin1.$replay(); var mockPlugin2 = new goog.testing.LooseMock(plugin); mockPlugin2.getTrogClassId().$returns('mockPlugin2'); mockPlugin2.registerFieldObject(editableField); mockPlugin2.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin2.$replay(); editableField.registerPlugin(mockPlugin1); editableField.registerPlugin(mockPlugin2); editableField.dispatchSelectionChangeEvent(e); mockPlugin1.$verify(); mockPlugin2.$verify(); } /** * Tests that if the first plugin does not handle selectionChange that * the next plugin gets a chance to handle it. */ function testNotHandledSelectionChange() { var editableField = new FieldConstructor('testField'); var plugin = new TestPlugin(); var e = getBrowserEvent(); var mockPlugin1 = new goog.testing.LooseMock(plugin); mockPlugin1.getTrogClassId().$returns('mockPlugin1'); mockPlugin1.registerFieldObject(editableField); mockPlugin1.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin1.handleSelectionChange(e, undefined).$returns(false); mockPlugin1.$replay(); var mockPlugin2 = new goog.testing.LooseMock(plugin); mockPlugin2.getTrogClassId().$returns('mockPlugin2'); mockPlugin2.registerFieldObject(editableField); mockPlugin2.isEnabled(editableField).$anyTimes().$returns(true); mockPlugin2.handleSelectionChange(e, undefined).$returns(true); mockPlugin2.$replay(); editableField.registerPlugin(mockPlugin1); editableField.registerPlugin(mockPlugin2); editableField.dispatchSelectionChangeEvent(e); mockPlugin1.$verify(); mockPlugin2.$verify(); } // Tests for goog.editor.Field internals. function testSelectionChange() { var editableField = new FieldConstructor('testField', document); var clock = new goog.testing.MockClock(true); var selectionChanges = goog.testing.recordFunction(); goog.events.listen(editableField, goog.editor.Field.EventType.SELECTIONCHANGE, selectionChanges); editableField.makeEditable(); // Emulate pressing left arrow key, this should result in SELECTIONCHANGE // event after a short timeout. editableField.handleKeyUp_({keyCode: goog.events.KeyCodes.LEFT}); assertEquals('Selection change should be on a timer', 0, selectionChanges.getCallCount()); clock.tick(1000); assertEquals('Selection change should fire within 1s', 1, selectionChanges.getCallCount()); // Programically place cursor at start. SELECTIONCHANGE event should be fired. editableField.placeCursorAtStart(); assertEquals('Selection change should fire', 2, selectionChanges.getCallCount()); clock.dispose(); editableField.dispose(); } function testSelectionChangeOnMouseUp() { var fakeEvent = new goog.events.BrowserEvent({type: 'mouseup', target: 'fakeTarget'}); var editableField = new FieldConstructor('testField', document); var clock = new goog.testing.MockClock(true); var selectionChanges = goog.testing.recordFunction(); goog.events.listen(editableField, goog.editor.Field.EventType.SELECTIONCHANGE, selectionChanges); var plugin = new TestPlugin(); plugin.handleSelectionChange = goog.testing.recordFunction(); editableField.registerPlugin(plugin); editableField.makeEditable(); // Emulate a mouseup event, this should result in an immediate // SELECTIONCHANGE, plus a second one in IE after a short timeout. editableField.handleMouseUp_(fakeEvent); assertEquals('Selection change should fire immediately', 1, selectionChanges.getCallCount()); assertEquals('Plugin should have handled selection change immediately', 1, plugin.handleSelectionChange.getCallCount()); assertEquals('Plugin should have received original browser event to handle', fakeEvent, plugin.handleSelectionChange.getLastCall().getArguments()[0]); // Pretend another plugin fired a SELECTIONCHANGE in the meantime. editableField.dispatchSelectionChangeEvent(); assertEquals('Second selection change should fire immediately', 2, selectionChanges.getCallCount()); assertEquals('Plugin should have handled second selection change immediately', 2, plugin.handleSelectionChange.getCallCount()); var args = plugin.handleSelectionChange.getLastCall().getArguments(); assertTrue('Plugin should not have received data from extra firing', args.length == 0 || !args[0] && (args.length == 1 || !args[1])); // Now check for the extra call in IE. clock.tick(1000); if (goog.userAgent.IE) { assertEquals('Additional selection change should fire within 1s', 3, selectionChanges.getCallCount()); assertEquals('Plugin should have handled selection change within 1s', 3, plugin.handleSelectionChange.getCallCount()); assertEquals('Plugin should have received target of original browser event', fakeEvent.target, plugin.handleSelectionChange.getLastCall().getArguments().pop()); } else { assertEquals('No additional selection change should fire', 2, selectionChanges.getCallCount()); assertEquals('Plugin should not have handled selection change again', 2, plugin.handleSelectionChange.getCallCount()); } clock.dispose(); editableField.dispose(); } function testSelectionChangeBeforeUneditable() { var editableField = new FieldConstructor('testField', document); var clock = new goog.testing.MockClock(true); var selectionChanges = goog.testing.recordFunction(); goog.events.listen(editableField, goog.editor.Field.EventType.SELECTIONCHANGE, selectionChanges); editableField.makeEditable(); editableField.handleKeyUp_({keyCode: goog.events.KeyCodes.LEFT}); assertEquals('Selection change should be on a timer', 0, selectionChanges.getCallCount()); editableField.makeUneditable(); assertEquals('Selection change should fire during make uneditable', 1, selectionChanges.getCallCount()); clock.tick(1000); assertEquals('No additional selection change should fire', 1, selectionChanges.getCallCount()); clock.dispose(); editableField.dispose(); } function testGetEditableDomHelper() { var editableField = new FieldConstructor('testField', document); assertNull('Before being made editable, we do not know the dom helper', editableField.getEditableDomHelper()); editableField.makeEditable(); assertNotNull('After being made editable, we know the dom helper', editableField.getEditableDomHelper()); assertEquals('Document from domHelper should be the editable elements doc', goog.dom.getOwnerDocument(editableField.getElement()), editableField.getEditableDomHelper().getDocument()); editableField.dispose(); } function testQueryCommandValue() { var editableField = new FieldConstructor('testField', document); assertFalse(editableField.queryCommandValue('boo')); assertObjectEquals({'boo': false, 'aieee': false}, editableField.queryCommandValue(['boo', 'aieee'])); editableField.makeEditable(); assertFalse(editableField.queryCommandValue('boo')); editableField.getElement().focus(); editableField.dispatchSelectionChangeEvent(); assertNull(editableField.queryCommandValue('boo')); assertObjectEquals({'boo': null, 'aieee': null}, editableField.queryCommandValue(['boo', 'aieee'])); editableField.dispose(); } function testSetHtml() { var editableField = new FieldConstructor('testField', document); var clock = new goog.testing.MockClock(true); try { var delayedChangeCalled = false; goog.events.listen(editableField, goog.editor.Field.EventType.DELAYEDCHANGE, function() { delayedChangeCalled = true; }); editableField.makeEditable(); clock.tick(1000); assertFalse('Make editable must not fire delayed change.', delayedChangeCalled); editableField.setHtml(false, 'bar', true /* Don't fire delayed change */); goog.testing.dom.assertHtmlContentsMatch('bar', editableField.getElement()); clock.tick(1000); assertFalse('setHtml must not fire delayed change if so configured.', delayedChangeCalled); editableField.setHtml(false, 'foo', false /* Fire delayed change */); goog.testing.dom.assertHtmlContentsMatch('foo', editableField.getElement()); clock.tick(1000); assertTrue('setHtml must fire delayed change by default', delayedChangeCalled); } finally { clock.dispose(); editableField.dispose(); } } /** * Helper to test that the cursor is placed at the beginning of the editable * field's contents. * @param {string=} opt_html Html to replace the test file default field * contents with. * @param {string=} opt_parentId Id of the parent of the node where the cursor * is expected to be placed. If omitted, will expect cursor to be placed in * the first child of the field element (or, if the field has no content, in * the field element itself). */ function doTestPlaceCursorAtStart(opt_html, opt_parentId) { var editableField = new FieldConstructor('testField', document); editableField.makeEditable(); // Initially place selection not at the start of the editable field. var textNode = editableField.getElement().firstChild; goog.dom.Range.createFromNodes(textNode, 1, textNode, 2).select(); if (opt_html != null) { editableField.getElement().innerHTML = opt_html; } editableField.placeCursorAtStart(); var range = editableField.getRange(); assertNotNull( 'Placing the cursor should result in a range object being available', range); assertTrue('The range should be collapsed', range.isCollapsed()); textNode = editableField.getElement().firstChild; // We check whether getAttribute exist because textNode may be an actual // TextNode, which does not have getAttribute. if (textNode && textNode.getAttribute && textNode.getAttribute('_moz_editor_bogus_node')) { // At least in FF >= 6, assigning '' to innerHTML of a contentEditable // element will results in textNode being modified into: // <br _moz_editor_bogus_node="TRUE" _moz_dirty=""> instead of nulling // it. So we should null it ourself. textNode = null; } var startNode = opt_parentId ? editableField.getEditableDomHelper().getElement(opt_parentId).firstChild : textNode ? textNode : editableField.getElement(); if (goog.userAgent.WEBKIT && !goog.userAgent.isVersion('528')) { // Safari 3 seems to normalize the selection to the shallowest endpoint (in // this case the editable element) in all cases tested below. This is OK // because when you start typing it magically inserts the text at the // deepest endpoint, and even behaves as desired in the case tested by // testPlaceCursorAtStartNonImportantTextNode. startNode = editableField.getElement(); } assertEquals('The range should start at the specified expected node', startNode, range.getStartNode()); assertEquals('The range should start at the beginning of the node', 0, range.getStartOffset()); } /** * Verify that restoreSavedRange() restores the range and sets the focus. */ function testRestoreSavedRange() { var editableField = new FieldConstructor('testField', document); editableField.makeEditable(); // Create another node to take the focus later. var doc = goog.dom.getOwnerDocument(editableField.getElement()); var otherElem = doc.createElement('div'); otherElem.tabIndex = '1'; // Make it focusable. editableField.getElement().parentNode.appendChild(otherElem); // Initially place selection not at the start of the editable field. var textNode = editableField.getElement().firstChild; var range = goog.dom.Range.createFromNodes(textNode, 1, textNode, 2); range.select(); var savedRange = goog.editor.range.saveUsingNormalizedCarets(range); // Change range to be a simple cursor at start, and move focus away. editableField.placeCursorAtStart(); otherElem.focus(); editableField.restoreSavedRange(savedRange); // Verify that we have focus and the range is restored. assertEquals('Field should be focused', editableField.getElement(), goog.dom.getActiveElement(doc)); var newRange = editableField.getRange(); assertEquals('Range startNode', textNode, newRange.getStartNode()); assertEquals('Range startOffset', 1, newRange.getStartOffset()); assertEquals('Range endNode', textNode, newRange.getEndNode()); assertEquals('Range endOffset', 2, newRange.getEndOffset()); } function testPlaceCursorAtStart() { doTestPlaceCursorAtStart(); } function testPlaceCursorAtStartEmptyField() { doTestPlaceCursorAtStart(''); } function testPlaceCursorAtStartNonImportantTextNode() { doTestPlaceCursorAtStart( '\n<span id="important">important text</span>', 'important'); } /** * Helper to test that the cursor is placed at the beginning of the editable * field's contents. * @param {string=} opt_html Html to replace the test file default field * contents with. * @param {string=} opt_parentId Id of the parent of the node where the cursor * is expected to be placed. If omitted, will expect cursor to be placed in * the first child of the field element (or, if the field has no content, in * the field element itself). * @param {number=} The offset to expect for the end position. */ function doTestPlaceCursorAtEnd(opt_html, opt_parentId, opt_offset) { var editableField = new FieldConstructor('testField', document); editableField.makeEditable(); // Initially place selection not at the end of the editable field. var textNode = editableField.getElement().firstChild; goog.dom.Range.createFromNodes(textNode, 0, textNode, 1).select(); if (opt_html != null) { editableField.getElement().innerHTML = opt_html; } editableField.placeCursorAtEnd(); var range = editableField.getRange(); assertNotNull( 'Placing the cursor should result in a range object being available', range); assertTrue('The range should be collapsed', range.isCollapsed()); textNode = editableField.getElement().firstChild; // We check whether getAttribute exist because textNode may be an actual // TextNode, which does not have getAttribute. var hasBogusNode = textNode && textNode.getAttribute && textNode.getAttribute('_moz_editor_bogus_node'); if (hasBogusNode) { // At least in FF >= 6, assigning '' to innerHTML of a contentEditable // element will results in textNode being modified into: // <br _moz_editor_bogus_node="TRUE" _moz_dirty=""> instead of nulling // it. So we should null it ourself. textNode = null; } var endNode = opt_parentId ? editableField.getEditableDomHelper().getElement(opt_parentId).lastChild : textNode ? textNode : editableField.getElement(); assertEquals('The range should end at the specified expected node', endNode, range.getEndNode()); var offset = goog.isDefAndNotNull(opt_offset) ? opt_offset : textNode ? endNode.nodeValue.length : endNode.childNodes.length - 1; if (hasBogusNode) { assertEquals('The range should end at the ending of the bogus node ' + 'added by FF', offset + 1, range.getEndOffset()); } else { assertEquals('The range should end at the ending of the node', offset, range.getEndOffset()); } } function testPlaceCursorAtEnd() { doTestPlaceCursorAtEnd(); } function testPlaceCursorAtEndEmptyField() { doTestPlaceCursorAtEnd('', null, 0); } function testPlaceCursorAtEndNonImportantTextNode() { doTestPlaceCursorAtStart( '\n<span id="important">important text</span>', 'important'); } // Tests related to change/delayed change events. function testClearDelayedChange() { var clock = new goog.testing.MockClock(true); var editableField = new FieldConstructor('testField', document); editableField.makeEditable(); var delayedChangeCalled = false; goog.events.listen(editableField, goog.editor.Field.EventType.DELAYEDCHANGE, function() { delayedChangeCalled = true; }); // Clears delayed change timer. editableField.delayedChangeTimer_.start(); editableField.clearDelayedChange(); assertTrue(delayedChangeCalled); if (editableField.changeTimerGecko_) { assertFalse(editableField.changeTimerGecko_.isActive()); } assertFalse(editableField.delayedChangeTimer_.isActive()); // Clears delayed changes caused by changeTimerGecko_ if (editableField.changeTimerGecko_) { delayedChangeCalled = false; editableField.changeTimerGecko_.start(); editableField.clearDelayedChange(); assertTrue(delayedChangeCalled); if (editableField.changeTimerGecko_) { assertFalse(editableField.changeTimerGecko_.isActive()); } assertFalse(editableField.delayedChangeTimer_.isActive()); } clock.dispose(); } function testHandleChange() { if (goog.editor.BrowserFeature.USE_MUTATION_EVENTS) { var editableField = new FieldConstructor('testField', document); editableField.makeEditable(); editableField.changeTimerGecko_.start(); editableField.handleChange(); assertFalse(editableField.changeTimerGecko_.isActive()); } } function testDispatchDelayedChange() { var editableField = new FieldConstructor('testField', document); editableField.makeEditable(); editableField.delayedChangeTimer_.start(); editableField.dispatchDelayedChange_(); assertFalse(editableField.delayedChangeTimer_.isActive()); } function testHandleWindowLevelMouseUp() { var editableField = new FieldConstructor('testField', document); if (editableField.usesIframe()) { // Only run this test if the editor does not use an iframe. return; } editableField.setUseWindowMouseUp(true); editableField.makeEditable(); var selectionHasFired = false; goog.events.listenOnce( editableField, goog.editor.Field.EventType.SELECTIONCHANGE, function(e) { selectionHasFired = true; }); var editableElement = editableField.getElement(); var otherElement = goog.dom.createDom('div'); goog.dom.insertSiblingAfter(otherElement, document.body.lastChild); goog.testing.events.fireMouseDownEvent(editableElement); assertFalse(selectionHasFired); goog.testing.events.fireMouseUpEvent(otherElement); assertTrue(selectionHasFired); } function testNoHandleWindowLevelMouseUp() { var editableField = new FieldConstructor('testField', document); editableField.setUseWindowMouseUp(false); editableField.makeEditable(); var selectionHasFired = false; goog.events.listenOnce( editableField, goog.editor.Field.EventType.SELECTIONCHANGE, function(e) { selectionHasFired = true; }); var editableElement = editableField.getElement(); var otherElement = goog.dom.createDom('div'); goog.dom.insertSiblingAfter(otherElement, document.body.lastChild); goog.testing.events.fireMouseDownEvent(editableElement); assertFalse(selectionHasFired); goog.testing.events.fireMouseUpEvent(otherElement); assertFalse(selectionHasFired); } function testIsGeneratingKey() { var regularKeyEvent = new goog.events.BrowserEvent(); regularKeyEvent.charCode = goog.events.KeyCodes.A; var ctrlKeyEvent = new goog.events.BrowserEvent(); ctrlKeyEvent.ctrlKey = true; ctrlKeyEvent.metaKey = true; ctrlKeyEvent.charCode = goog.events.KeyCodes.A; var imeKeyEvent = new goog.events.BrowserEvent(); imeKeyEvent.keyCode = 229; // indicates from an IME - see KEYS_CAUSING_CHANGES assertTrue(goog.editor.Field.isGeneratingKey_(regularKeyEvent, true)); assertFalse(goog.editor.Field.isGeneratingKey_(ctrlKeyEvent, true)); if (goog.userAgent.WINDOWS && !goog.userAgent.GECKO) { assertTrue(goog.editor.Field.isGeneratingKey_(imeKeyEvent, false)); } else { assertFalse(goog.editor.Field.isGeneratingKey_(imeKeyEvent, false)); } }
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // All Rights Reserved. /** * @fileoverview Abstract API for TrogEdit plugins. * * @see ../demos/editor/editor.html */ goog.provide('goog.editor.Plugin'); goog.require('goog.debug.Logger'); // TODO(user): Remove the dependency on goog.editor.Command asap. Currently only // needed for execCommand issues with links. goog.require('goog.editor.Command'); goog.require('goog.events.EventTarget'); goog.require('goog.functions'); goog.require('goog.object'); goog.require('goog.reflect'); /** * Abstract API for trogedit plugins. * @constructor * @extends {goog.events.EventTarget} */ goog.editor.Plugin = function() { goog.events.EventTarget.call(this); /** * Whether this plugin is enabled for the registered field object. * @type {boolean} * @private */ this.enabled_ = this.activeOnUneditableFields(); }; goog.inherits(goog.editor.Plugin, goog.events.EventTarget); /** * The field object this plugin is attached to. * @type {goog.editor.Field} * @protected * @deprecated Use goog.editor.Plugin.getFieldObject and * goog.editor.Plugin.setFieldObject. */ goog.editor.Plugin.prototype.fieldObject = null; /** * @return {goog.dom.DomHelper?} The dom helper object associated with the * currently active field. */ goog.editor.Plugin.prototype.getFieldDomHelper = function() { return this.getFieldObject() && this.getFieldObject().getEditableDomHelper(); }; /** * Indicates if this plugin should be automatically disposed when the * registered field is disposed. This should be changed to false for * plugins used as multi-field plugins. * @type {boolean} * @private */ goog.editor.Plugin.prototype.autoDispose_ = true; /** * The logger for this plugin. * @type {goog.debug.Logger} * @protected */ goog.editor.Plugin.prototype.logger = goog.debug.Logger.getLogger('goog.editor.Plugin'); /** * Sets the field object for use with this plugin. * @return {goog.editor.Field} The editable field object. * @protected * @suppress {deprecated} Until fieldObject can be made private. */ goog.editor.Plugin.prototype.getFieldObject = function() { return this.fieldObject; }; /** * Sets the field object for use with this plugin. * @param {goog.editor.Field} fieldObject The editable field object. * @protected * @suppress {deprecated} Until fieldObject can be made private. */ goog.editor.Plugin.prototype.setFieldObject = function(fieldObject) { this.fieldObject = fieldObject; }; /** * Registers the field object for use with this plugin. * @param {goog.editor.Field} fieldObject The editable field object. */ goog.editor.Plugin.prototype.registerFieldObject = function(fieldObject) { this.setFieldObject(fieldObject); }; /** * Unregisters and disables this plugin for the current field object. * @param {goog.editor.Field} fieldObj The field object. For single-field * plugins, this parameter is ignored. */ goog.editor.Plugin.prototype.unregisterFieldObject = function(fieldObj) { if (this.getFieldObject()) { this.disable(this.getFieldObject()); this.setFieldObject(null); } }; /** * Enables this plugin for the specified, registered field object. A field * object should only be enabled when it is loaded. * @param {goog.editor.Field} fieldObject The field object. */ goog.editor.Plugin.prototype.enable = function(fieldObject) { if (this.getFieldObject() == fieldObject) { this.enabled_ = true; } else { this.logger.severe('Trying to enable an unregistered field with ' + 'this plugin.'); } }; /** * Disables this plugin for the specified, registered field object. * @param {goog.editor.Field} fieldObject The field object. */ goog.editor.Plugin.prototype.disable = function(fieldObject) { if (this.getFieldObject() == fieldObject) { this.enabled_ = false; } else { this.logger.severe('Trying to disable an unregistered field ' + 'with this plugin.'); } }; /** * Returns whether this plugin is enabled for the field object. * * @param {goog.editor.Field} fieldObject The field object. * @return {boolean} Whether this plugin is enabled for the field object. */ goog.editor.Plugin.prototype.isEnabled = function(fieldObject) { return this.getFieldObject() == fieldObject ? this.enabled_ : false; }; /** * Set if this plugin should automatically be disposed when the registered * field is disposed. * @param {boolean} autoDispose Whether to autoDispose. */ goog.editor.Plugin.prototype.setAutoDispose = function(autoDispose) { this.autoDispose_ = autoDispose; }; /** * @return {boolean} Whether or not this plugin should automatically be disposed * when it's registered field is disposed. */ goog.editor.Plugin.prototype.isAutoDispose = function() { return this.autoDispose_; }; /** * @return {boolean} If true, field will not disable the command * when the field becomes uneditable. */ goog.editor.Plugin.prototype.activeOnUneditableFields = goog.functions.FALSE; /** * @param {string} command The command to check. * @return {boolean} If true, field will not dispatch change events * for commands of this type. This is useful for "seamless" plugins like * dialogs and lorem ipsum. */ goog.editor.Plugin.prototype.isSilentCommand = goog.functions.FALSE; /** @override */ goog.editor.Plugin.prototype.disposeInternal = function() { if (this.getFieldObject()) { this.unregisterFieldObject(this.getFieldObject()); } goog.editor.Plugin.superClass_.disposeInternal.call(this); }; /** * @return {string} The ID unique to this plugin class. Note that different * instances off the plugin share the same classId. */ goog.editor.Plugin.prototype.getTrogClassId; /** * An enum of operations that plugins may support. * @enum {number} */ goog.editor.Plugin.Op = { KEYDOWN: 1, KEYPRESS: 2, KEYUP: 3, SELECTION: 4, SHORTCUT: 5, EXEC_COMMAND: 6, QUERY_COMMAND: 7, PREPARE_CONTENTS_HTML: 8, CLEAN_CONTENTS_HTML: 10, CLEAN_CONTENTS_DOM: 11 }; /** * A map from plugin operations to the names of the methods that * invoke those operations. */ goog.editor.Plugin.OPCODE = goog.object.transpose( goog.reflect.object(goog.editor.Plugin, { handleKeyDown: goog.editor.Plugin.Op.KEYDOWN, handleKeyPress: goog.editor.Plugin.Op.KEYPRESS, handleKeyUp: goog.editor.Plugin.Op.KEYUP, handleSelectionChange: goog.editor.Plugin.Op.SELECTION, handleKeyboardShortcut: goog.editor.Plugin.Op.SHORTCUT, execCommand: goog.editor.Plugin.Op.EXEC_COMMAND, queryCommandValue: goog.editor.Plugin.Op.QUERY_COMMAND, prepareContentsHtml: goog.editor.Plugin.Op.PREPARE_CONTENTS_HTML, cleanContentsHtml: goog.editor.Plugin.Op.CLEAN_CONTENTS_HTML, cleanContentsDom: goog.editor.Plugin.Op.CLEAN_CONTENTS_DOM })); /** * A set of op codes that run even on disabled plugins. */ goog.editor.Plugin.IRREPRESSIBLE_OPS = goog.object.createSet( goog.editor.Plugin.Op.PREPARE_CONTENTS_HTML, goog.editor.Plugin.Op.CLEAN_CONTENTS_HTML, goog.editor.Plugin.Op.CLEAN_CONTENTS_DOM); /** * Handles keydown. It is run before handleKeyboardShortcut and if it returns * true handleKeyboardShortcut will not be called. * @param {!goog.events.BrowserEvent} e The browser event. * @return {boolean} Whether the event was handled and thus should *not* be * propagated to other plugins or handleKeyboardShortcut. */ goog.editor.Plugin.prototype.handleKeyDown; /** * Handles keypress. It is run before handleKeyboardShortcut and if it returns * true handleKeyboardShortcut will not be called. * @param {!goog.events.BrowserEvent} e The browser event. * @return {boolean} Whether the event was handled and thus should *not* be * propagated to other plugins or handleKeyboardShortcut. */ goog.editor.Plugin.prototype.handleKeyPress; /** * Handles keyup. * @param {!goog.events.BrowserEvent} e The browser event. * @return {boolean} Whether the event was handled and thus should *not* be * propagated to other plugins. */ goog.editor.Plugin.prototype.handleKeyUp; /** * Handles selection change. * @param {!goog.events.BrowserEvent=} opt_e The browser event. * @param {!Node=} opt_target The node the selection changed to. * @return {boolean} Whether the event was handled and thus should *not* be * propagated to other plugins. */ goog.editor.Plugin.prototype.handleSelectionChange; /** * Handles keyboard shortcuts. Preferred to using handleKey* as it will use * the proper event based on browser and will be more performant. If * handleKeyPress/handleKeyDown returns true, this will not be called. If the * plugin handles the shortcut, it is responsible for dispatching appropriate * events (change, selection change at the time of this comment). If the plugin * calls execCommand on the editable field, then execCommand already takes care * of dispatching events. * NOTE: For performance reasons this is only called when any key is pressed * in conjunction with ctrl/meta keys OR when a small subset of keys (defined * in goog.editor.Field.POTENTIAL_SHORTCUT_KEYCODES_) are pressed without * ctrl/meta keys. We specifically don't invoke it when altKey is pressed since * alt key is used in many i8n UIs to enter certain characters. * @param {!goog.events.BrowserEvent} e The browser event. * @param {string} key The key pressed. * @param {boolean} isModifierPressed Whether the ctrl/meta key was pressed or * not. * @return {boolean} Whether the event was handled and thus should *not* be * propagated to other plugins. We also call preventDefault on the event if * the return value is true. */ goog.editor.Plugin.prototype.handleKeyboardShortcut; /** * Handles execCommand. This default implementation handles dispatching * BEFORECHANGE, CHANGE, and SELECTIONCHANGE events, and calls * execCommandInternal to perform the actual command. Plugins that want to * do their own event dispatching should override execCommand, otherwise * it is preferred to only override execCommandInternal. * * This version of execCommand will only work for single field plugins. * Multi-field plugins must override execCommand. * * @param {string} command The command to execute. * @param {...*} var_args Any additional parameters needed to * execute the command. * @return {*} The result of the execCommand, if any. */ goog.editor.Plugin.prototype.execCommand = function(command, var_args) { // TODO(user): Replace all uses of isSilentCommand with plugins that just // override this base execCommand method. var silent = this.isSilentCommand(command); if (!silent) { // Stop listening to mutation events in Firefox while text formatting // is happening. This prevents us from trying to size the field in the // middle of an execCommand, catching the field in a strange intermediary // state where both replacement nodes and original nodes are appended to // the dom. Note that change events get turned back on by // fieldObj.dispatchChange. if (goog.userAgent.GECKO) { this.getFieldObject().stopChangeEvents(true, true); } this.getFieldObject().dispatchBeforeChange(); } try { var result = this.execCommandInternal.apply(this, arguments); } finally { // If the above execCommandInternal call throws an exception, we still need // to turn change events back on (see http://b/issue?id=1471355). // NOTE: If if you add to or change the methods called in this finally // block, please add them as expected calls to the unit test function // testExecCommandException(). if (!silent) { // dispatchChange includes a call to startChangeEvents, which unwinds the // call to stopChangeEvents made before the try block. this.getFieldObject().dispatchChange(); this.getFieldObject().dispatchSelectionChangeEvent(); } } return result; }; /** * Handles execCommand. This default implementation does nothing, and is * called by execCommand, which handles event dispatching. This method should * be overriden by plugins that don't need to do their own event dispatching. * If custom event dispatching is needed, execCommand shoul be overriden * instead. * * @param {string} command The command to execute. * @param {...*} var_args Any additional parameters needed to * execute the command. * @return {*} The result of the execCommand, if any. * @protected */ goog.editor.Plugin.prototype.execCommandInternal; /** * Gets the state of this command if this plugin serves that command. * @param {string} command The command to check. * @return {*} The value of the command. */ goog.editor.Plugin.prototype.queryCommandValue; /** * Prepares the given HTML for editing. Strips out content that should not * appear in an editor, and normalizes content as appropriate. The inverse * of cleanContentsHtml. * * This op is invoked even on disabled plugins. * * @param {string} originalHtml The original HTML. * @param {Object} styles A map of strings. If the plugin wants to add * any styles to the field element, it should add them as key-value * pairs to this object. * @return {string} New HTML that's ok for editing. */ goog.editor.Plugin.prototype.prepareContentsHtml; /** * Cleans the contents of the node passed to it. The node contents are modified * directly, and the modifications will subsequently be used, for operations * such as saving the innerHTML of the editor etc. Since the plugins act on * the DOM directly, this method can be very expensive. * * This op is invoked even on disabled plugins. * * @param {!Element} fieldCopy The copy of the editable field which * needs to be cleaned up. */ goog.editor.Plugin.prototype.cleanContentsDom; /** * Cleans the html contents of Trogedit. Both cleanContentsDom and * and cleanContentsHtml will be called on contents extracted from Trogedit. * The inverse of prepareContentsHtml. * * This op is invoked even on disabled plugins. * * @param {string} originalHtml The trogedit HTML. * @return {string} Cleaned-up HTML. */ goog.editor.Plugin.prototype.cleanContentsHtml; /** * Whether the string corresponds to a command this plugin handles. * @param {string} command Command string to check. * @return {boolean} Whether the plugin handles this type of command. */ goog.editor.Plugin.prototype.isSupportedCommand = function(command) { return false; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Utilties to handle focusing related to rich text editing. * */ goog.provide('goog.editor.focus'); goog.require('goog.dom.selection'); /** * Change focus to the given input field and set cursor to end of current text. * @param {Element} inputElem Input DOM element. */ goog.editor.focus.focusInputField = function(inputElem) { inputElem.focus(); goog.dom.selection.setCursorPosition(inputElem, inputElem.value.length); };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Class to encapsulate an editable field that blends in with * the style of the page. The field can be fixed height, grow with its * contents, or have a min height after which it grows to its contents. * This is a goog.editor.Field, but with blending and sizing capabilities, * and avoids using an iframe whenever possible. * * @see ../demos/editor/seamlessfield.html */ goog.provide('goog.editor.SeamlessField'); goog.require('goog.cssom.iframe.style'); goog.require('goog.debug.Logger'); goog.require('goog.dom'); goog.require('goog.dom.Range'); goog.require('goog.dom.TagName'); goog.require('goog.editor.BrowserFeature'); goog.require('goog.editor.Field'); goog.require('goog.editor.icontent'); goog.require('goog.editor.icontent.FieldFormatInfo'); goog.require('goog.editor.icontent.FieldStyleInfo'); goog.require('goog.editor.node'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.style'); /** * This class encapsulates an editable field that blends in with the * surrounding page. * To see events fired by this object, please see the base class. * * @param {string} id An identifer for the field. This is used to find the * field and the element associated with this field. * @param {Document=} opt_doc The document that the element with the given * id can be found it. * @constructor * @extends {goog.editor.Field} */ goog.editor.SeamlessField = function(id, opt_doc) { goog.editor.Field.call(this, id, opt_doc); }; goog.inherits(goog.editor.SeamlessField, goog.editor.Field); /** * @override */ goog.editor.SeamlessField.prototype.logger = goog.debug.Logger.getLogger('goog.editor.SeamlessField'); // Functions dealing with field sizing. /** * The key used for listening for the "dragover" event. * @type {goog.events.Key} * @private */ goog.editor.SeamlessField.prototype.listenForDragOverEventKey_; /** * The key used for listening for the iframe "load" event. * @type {goog.events.Key} * @private */ goog.editor.SeamlessField.prototype.listenForIframeLoadEventKey_; /** * Sets the min height of this editable field's iframe. Only used in growing * mode when an iframe is used. This will cause an immediate field sizing to * update the field if necessary based on the new min height. * @param {number} height The min height specified as a number of pixels, * e.g., 75. */ goog.editor.SeamlessField.prototype.setMinHeight = function(height) { if (height == this.minHeight_) { // Do nothing if the min height isn't changing. return; } this.minHeight_ = height; if (this.usesIframe()) { this.doFieldSizingGecko(); } }; /** * Whether the field should be rendered with a fixed height, or should expand * to fit its contents. * @type {boolean} * @private */ goog.editor.SeamlessField.prototype.isFixedHeight_ = false; /** * Whether the fixed-height handling has been overridden manually. * @type {boolean} * @private */ goog.editor.SeamlessField.prototype.isFixedHeightOverridden_ = false; /** * @return {boolean} Whether the field should be rendered with a fixed * height, or should expand to fit its contents. * @override */ goog.editor.SeamlessField.prototype.isFixedHeight = function() { return this.isFixedHeight_; }; /** * @param {boolean} newVal Explicitly set whether the field should be * of a fixed-height. This overrides auto-detection. */ goog.editor.SeamlessField.prototype.overrideFixedHeight = function(newVal) { this.isFixedHeight_ = newVal; this.isFixedHeightOverridden_ = true; }; /** * Auto-detect whether the current field should have a fixed height. * @private */ goog.editor.SeamlessField.prototype.autoDetectFixedHeight_ = function() { if (!this.isFixedHeightOverridden_) { var originalElement = this.getOriginalElement(); if (originalElement) { this.isFixedHeight_ = goog.style.getComputedOverflowY(originalElement) == 'auto'; } } }; /** * Resize the iframe in response to the wrapper div changing size. * @private */ goog.editor.SeamlessField.prototype.handleOuterDocChange_ = function() { if (this.isEventStopped(goog.editor.Field.EventType.CHANGE)) { return; } this.sizeIframeToWrapperGecko_(); }; /** * Sizes the iframe to its body's height. * @private */ goog.editor.SeamlessField.prototype.sizeIframeToBodyHeightGecko_ = function() { if (this.acquireSizeIframeLockGecko_()) { var resized = false; var ifr = this.getEditableIframe(); if (ifr) { var fieldHeight = this.getIframeBodyHeightGecko_(); if (this.minHeight_) { fieldHeight = Math.max(fieldHeight, this.minHeight_); } if (parseInt(goog.style.getStyle(ifr, 'height'), 10) != fieldHeight) { ifr.style.height = fieldHeight + 'px'; resized = true; } } this.releaseSizeIframeLockGecko_(); if (resized) { this.dispatchEvent(goog.editor.Field.EventType.IFRAME_RESIZED); } } }; /** * @return {number} The height of the editable iframe's body. * @private */ goog.editor.SeamlessField.prototype.getIframeBodyHeightGecko_ = function() { var ifr = this.getEditableIframe(); var body = ifr.contentDocument.body; var htmlElement = body.parentNode; // If the iframe's height is 0, then the offsetHeight/scrollHeight of the // HTML element in the iframe can be totally wack (i.e. too large // by 50-500px). Also, in standard's mode the clientHeight is 0. if (parseInt(goog.style.getStyle(ifr, 'height'), 10) === 0) { goog.style.setStyle(ifr, 'height', 1 + 'px'); } var fieldHeight; if (goog.editor.node.isStandardsMode(body)) { // If in standards-mode, // grab the HTML element as it will contain all the field's // contents. The body's height, for example, will not include that of // floated images at the bottom in standards mode. // Note that this value include all scrollbars *except* for scrollbars // on the HTML element itself. fieldHeight = htmlElement.offsetHeight; } else { // In quirks-mode, the body-element always seems // to size to the containing window. The html-element however, // sizes to the content, and can thus end up with a value smaller // than its child body-element if the content is shrinking. // We want to make the iframe shrink too when the content shrinks, // so rather than size the iframe to the body-element, size it to // the html-element. fieldHeight = htmlElement.scrollHeight; // If there is a horizontal scroll, add in the thickness of the // scrollbar. if (htmlElement.clientHeight != htmlElement.offsetHeight) { fieldHeight += goog.editor.SeamlessField.getScrollbarWidth_(); } } return fieldHeight; }; /** * Grabs the width of a scrollbar from the browser and caches the result. * @return {number} The scrollbar width in pixels. * @private */ goog.editor.SeamlessField.getScrollbarWidth_ = function() { return goog.editor.SeamlessField.scrollbarWidth_ || (goog.editor.SeamlessField.scrollbarWidth_ = goog.style.getScrollbarWidth()); }; /** * Sizes the iframe to its container div's width. The width of the div * is controlled by its containing context, not by its contents. * if it extends outside of it's contents, then it gets a horizontal scroll. * @private */ goog.editor.SeamlessField.prototype.sizeIframeToWrapperGecko_ = function() { if (this.acquireSizeIframeLockGecko_()) { var ifr = this.getEditableIframe(); var field = this.getElement(); var resized = false; if (ifr && field) { var fieldPaddingBox; var widthDiv = ifr.parentNode; var width = widthDiv.offsetWidth; if (parseInt(goog.style.getStyle(ifr, 'width'), 10) != width) { fieldPaddingBox = goog.style.getPaddingBox(field); ifr.style.width = width + 'px'; field.style.width = width - fieldPaddingBox.left - fieldPaddingBox.right + 'px'; resized = true; } var height = widthDiv.offsetHeight; if (this.isFixedHeight() && parseInt(goog.style.getStyle(ifr, 'height'), 10) != height) { if (!fieldPaddingBox) { fieldPaddingBox = goog.style.getPaddingBox(field); } ifr.style.height = height + 'px'; field.style.height = height - fieldPaddingBox.top - fieldPaddingBox.bottom + 'px'; resized = true; } } this.releaseSizeIframeLockGecko_(); if (resized) { this.dispatchEvent(goog.editor.Field.EventType.IFRAME_RESIZED); } } }; /** * Perform all the sizing immediately. */ goog.editor.SeamlessField.prototype.doFieldSizingGecko = function() { // Because doFieldSizingGecko can be called after a setTimeout // it is possible that the field has been destroyed before this call // to do the sizing is executed. Check for field existence and do nothing // if it has already been destroyed. if (this.getElement()) { // The order of operations is important here. Sizing the iframe to the // wrapper could cause the width to change, which could change the line // wrapping, which could change the body height. So we need to do that // first, then size the iframe to fit the body height. this.sizeIframeToWrapperGecko_(); if (!this.isFixedHeight()) { this.sizeIframeToBodyHeightGecko_(); } } }; /** * Acquires a lock on resizing the field iframe. This is used to ensure that * modifications we make while in a mutation event handler don't cause * infinite loops. * @return {boolean} False if the lock is already acquired. * @private */ goog.editor.SeamlessField.prototype.acquireSizeIframeLockGecko_ = function() { if (this.sizeIframeLock_) { return false; } return this.sizeIframeLock_ = true; }; /** * Releases a lock on resizing the field iframe. This is used to ensure that * modifications we make while in a mutation event handler don't cause * infinite loops. * @private */ goog.editor.SeamlessField.prototype.releaseSizeIframeLockGecko_ = function() { this.sizeIframeLock_ = false; }; // Functions dealing with blending in with the surrounding page. /** * String containing the css rules that, if applied to a document's body, * would style that body as if it were the original element we made editable. * See goog.cssom.iframe.style.getElementContext for more details. * @type {string} * @private */ goog.editor.SeamlessField.prototype.iframeableCss_ = ''; /** * Gets the css rules that should be used to style an iframe's body as if it * were the original element that we made editable. * @param {boolean=} opt_forceRegeneration Set to true to not read the cached * copy and instead completely regenerate the css rules. * @return {string} The string containing the css rules to use. */ goog.editor.SeamlessField.prototype.getIframeableCss = function( opt_forceRegeneration) { if (!this.iframeableCss_ || opt_forceRegeneration) { var originalElement = this.getOriginalElement(); if (originalElement) { this.iframeableCss_ = goog.cssom.iframe.style.getElementContext(originalElement, opt_forceRegeneration); } } return this.iframeableCss_; }; /** * Sets the css rules that should be used inside the editable iframe. * Note: to clear the css cache between makeNotEditable/makeEditable, * call this with "" as iframeableCss. * TODO(user): Unify all these css setting methods + Nick's open * CL. This is getting ridiculous. * @param {string} iframeableCss String containing the css rules to use. */ goog.editor.SeamlessField.prototype.setIframeableCss = function(iframeableCss) { this.iframeableCss_ = iframeableCss; }; /** * Used to ensure that CSS stylings are only installed once for none * iframe seamless mode. * TODO(user): Make it a formal part of the API that you can only * set one set of styles globally. * In seamless, non-iframe mode, all the stylings would go in the * same document and conflict. * @type {boolean} * @private */ goog.editor.SeamlessField.haveInstalledCss_ = false; /** * Applies CSS from the wrapper-div to the field iframe. */ goog.editor.SeamlessField.prototype.inheritBlendedCSS = function() { // No-op if the field isn't using an iframe. if (!this.usesIframe()) { return; } var field = this.getElement(); var head = goog.dom.getDomHelper(field).getElementsByTagNameAndClass( 'head')[0]; if (head) { // We created this <head>, and we know the only thing we put in there // is a <style> block. So it's safe to blow away all the children // as part of rewriting the styles. goog.dom.removeChildren(head); } // Force a cache-clearing in CssUtil - this function was called because // we're applying the 'blend' for the first time, or because we // *need* to recompute the blend. var newCSS = this.getIframeableCss(true); goog.style.installStyles(newCSS, field); }; // Overridden methods. /** @override */ goog.editor.SeamlessField.prototype.usesIframe = function() { // TODO(user): Switch Firefox to using contentEditable // rather than designMode iframe once contentEditable support // is less buggy. return !goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE; }; /** @override */ goog.editor.SeamlessField.prototype.setupMutationEventHandlersGecko = function() { goog.editor.SeamlessField.superClass_.setupMutationEventHandlersGecko.call( this); if (this.usesIframe()) { var iframe = this.getEditableIframe(); var outerDoc = iframe.ownerDocument; this.eventRegister.listen(outerDoc, goog.editor.Field.MUTATION_EVENTS_GECKO, this.handleOuterDocChange_, true); // If the images load after we do the initial sizing, then this will // force a field resize. this.listenForIframeLoadEventKey_ = goog.events.listenOnce( this.getEditableDomHelper().getWindow(), goog.events.EventType.LOAD, this.sizeIframeToBodyHeightGecko_, true, this); this.eventRegister.listen(outerDoc, 'DOMAttrModified', goog.bind(this.handleDomAttrChange, this, this.handleOuterDocChange_), true); } }; /** @override */ goog.editor.SeamlessField.prototype.handleChange = function() { if (this.isEventStopped(goog.editor.Field.EventType.CHANGE)) { return; } goog.editor.SeamlessField.superClass_.handleChange.call(this); if (this.usesIframe()) { this.sizeIframeToBodyHeightGecko_(); } }; /** @override */ goog.editor.SeamlessField.prototype.dispatchBlur = function() { if (this.isEventStopped(goog.editor.Field.EventType.BLUR)) { return; } goog.editor.SeamlessField.superClass_.dispatchBlur.call(this); // Clear the selection and restore the current range back after collapsing // it. The ideal solution would have been to just leave the range intact; but // when there are multiple fields present on the page, its important that // the selection isn't retained when we switch between the fields. We also // have to make sure that the cursor position is retained when we tab in and // out of a field and our approach addresses both these issues. // Another point to note is that we do it on a setTimeout to allow for // DOM modifications on blur. Otherwise, something like setLoremIpsum will // leave a blinking cursor in the field even though it's blurred. if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE && !goog.editor.BrowserFeature.CLEARS_SELECTION_WHEN_FOCUS_LEAVES) { var win = this.getEditableDomHelper().getWindow(); var dragging = false; goog.events.unlistenByKey(this.listenForDragOverEventKey_); this.listenForDragOverEventKey_ = goog.events.listenOnce( win.document.body, 'dragover', function() { dragging = true; }); goog.global.setTimeout(goog.bind(function() { // Do not clear the selection if we're only dragging text. // This addresses a bug on FF1.5/linux where dragging fires a blur, // but clearing the selection confuses Firefox's drag-and-drop // implementation. For more info, see http://b/1061064 if (!dragging) { if (this.editableDomHelper) { var rng = this.getRange(); // If there are multiple fields on a page, we need to make sure that // the selection isn't retained when we switch between fields. We // could have collapsed the range but there is a bug in GECKO where // the selection stays highlighted even though its backing range is // collapsed (http://b/1390115). To get around this, we clear the // selection and restore the collapsed range back in. Restoring the // range is important so that the cursor stays intact when we tab out // and into a field (See http://b/1790301 for additional details on // this). var iframeWindow = this.editableDomHelper.getWindow(); goog.dom.Range.clearSelection(iframeWindow); if (rng) { rng.collapse(true); rng.select(); } } } }, this), 0); } }; /** @override */ goog.editor.SeamlessField.prototype.turnOnDesignModeGecko = function() { goog.editor.SeamlessField.superClass_.turnOnDesignModeGecko.call(this); var doc = this.getEditableDomHelper().getDocument(); doc.execCommand('enableInlineTableEditing', false, 'false'); doc.execCommand('enableObjectResizing', false, 'false'); }; /** @override */ goog.editor.SeamlessField.prototype.installStyles = function() { if (!this.usesIframe()) { if (!goog.editor.SeamlessField.haveInstalledCss_) { if (this.cssStyles) { goog.style.installStyles(this.cssStyles, this.getElement()); } // TODO(user): this should be reset to false when the editor is quit. // In non-iframe mode, CSS styles should only be instaled once. goog.editor.SeamlessField.haveInstalledCss_ = true; } } }; /** @override */ goog.editor.SeamlessField.prototype.makeEditableInternal = function( opt_iframeSrc) { if (this.usesIframe()) { goog.editor.SeamlessField.superClass_.makeEditableInternal.call(this, opt_iframeSrc); } else { var field = this.getOriginalElement(); if (field) { this.setupFieldObject(field); field.contentEditable = true; this.injectContents(field.innerHTML, field); this.handleFieldLoad(); } } }; /** @override */ goog.editor.SeamlessField.prototype.handleFieldLoad = function() { if (this.usesIframe()) { // If the CSS inheriting code screws up (e.g. makes fonts too large) and // the field is sized off in goog.editor.Field.makeIframeField, then we need // to size it correctly, but it needs to be visible for the browser // to have fully rendered it. We need to put this on a timeout to give // the browser time to render. var self = this; goog.global.setTimeout(function() { self.doFieldSizingGecko(); }, 0); } goog.editor.SeamlessField.superClass_.handleFieldLoad.call(this); }; /** @override */ goog.editor.SeamlessField.prototype.getIframeAttributes = function() { return { 'frameBorder': 0, 'style': 'padding:0;' }; }; /** @override */ goog.editor.SeamlessField.prototype.attachIframe = function(iframe) { this.autoDetectFixedHeight_(); var field = this.getOriginalElement(); var dh = goog.dom.getDomHelper(field); // Grab the width/height values of the field before modifying any CSS // as some of the modifications affect its size (e.g. innerHTML='') // Here, we set the size of the field to fixed so there's not too much // jiggling when we set the innerHTML of the field. var oldWidth = field.style.width; var oldHeight = field.style.height; goog.style.setStyle(field, 'visibility', 'hidden'); // If there is a floated element at the bottom of the field, // then it needs a clearing div at the end to cause the clientHeight // to contain the entire field. // Also, with css re-writing, the margins of the first/last // paragraph don't seem to get included in the clientHeight. Specifically, // the extra divs below force the field's clientHeight to include the // margins on the first and last elements contained within it. var startDiv = dh.createDom(goog.dom.TagName.DIV, {'style': 'height:0;clear:both', 'innerHTML': '&nbsp;'}); var endDiv = startDiv.cloneNode(true); field.insertBefore(startDiv, field.firstChild); goog.dom.appendChild(field, endDiv); var contentBox = goog.style.getContentBoxSize(field); var width = contentBox.width; var height = contentBox.height; var html = ''; if (this.isFixedHeight()) { html = '&nbsp;'; goog.style.setStyle(field, 'position', 'relative'); goog.style.setStyle(field, 'overflow', 'visible'); goog.style.setStyle(iframe, 'position', 'absolute'); goog.style.setStyle(iframe, 'top', '0'); goog.style.setStyle(iframe, 'left', '0'); } goog.style.setSize(field, width, height); // In strict mode, browsers put blank space at the bottom and right // if a field when it has an iframe child, to fill up the remaining line // height. So make the line height = 0. if (goog.editor.node.isStandardsMode(field)) { this.originalFieldLineHeight_ = field.style.lineHeight; goog.style.setStyle(field, 'lineHeight', '0'); } goog.editor.node.replaceInnerHtml(field, html); // Set the initial size goog.style.setSize(iframe, width, height); goog.style.setSize(field, oldWidth, oldHeight); goog.style.setStyle(field, 'visibility', ''); goog.dom.appendChild(field, iframe); // Only write if its not IE HTTPS in which case we're waiting for load. if (!this.shouldLoadAsynchronously()) { var doc = iframe.contentWindow.document; if (goog.editor.node.isStandardsMode(iframe.ownerDocument)) { doc.open(); doc.write('<!DOCTYPE HTML><html></html>'); doc.close(); } } }; /** @override */ goog.editor.SeamlessField.prototype.getFieldFormatInfo = function( extraStyles) { var originalElement = this.getOriginalElement(); if (originalElement) { return new goog.editor.icontent.FieldFormatInfo( this.id, goog.editor.node.isStandardsMode(originalElement), true, this.isFixedHeight(), extraStyles); } throw Error('no field'); }; /** @override */ goog.editor.SeamlessField.prototype.writeIframeContent = function( iframe, innerHtml, extraStyles) { // For seamless iframes, hide the iframe while we're laying it out to // prevent the flicker. goog.style.setStyle(iframe, 'visibility', 'hidden'); var formatInfo = this.getFieldFormatInfo(extraStyles); var styleInfo = new goog.editor.icontent.FieldStyleInfo( this.getOriginalElement(), this.cssStyles + this.getIframeableCss()); goog.editor.icontent.writeNormalInitialBlendedIframe( formatInfo, innerHtml, styleInfo, iframe); this.doFieldSizingGecko(); goog.style.setStyle(iframe, 'visibility', 'visible'); }; /** @override */ goog.editor.SeamlessField.prototype.restoreDom = function() { // TODO(user): Consider only removing the iframe if we are // restoring the original node. if (this.usesIframe()) { goog.dom.removeNode(this.getEditableIframe()); } }; /** @override */ goog.editor.SeamlessField.prototype.clearListeners = function() { goog.events.unlistenByKey(this.listenForDragOverEventKey_); goog.events.unlistenByKey(this.listenForIframeLoadEventKey_); goog.base(this, 'clearListeners'); };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Commands that the editor can execute. * @see ../demos/editor/editor.html */ goog.provide('goog.editor.Command'); /** * Commands that the editor can excute via execCommand or queryCommandValue. * @enum {string} */ goog.editor.Command = { // Prepend all the strings of built in execCommands with a plus to ensure // that there's no conflict if a client wants to use the // browser's execCommand. UNDO: '+undo', REDO: '+redo', LINK: '+link', FORMAT_BLOCK: '+formatBlock', INDENT: '+indent', OUTDENT: '+outdent', REMOVE_FORMAT: '+removeFormat', STRIKE_THROUGH: '+strikeThrough', HORIZONTAL_RULE: '+insertHorizontalRule', SUBSCRIPT: '+subscript', SUPERSCRIPT: '+superscript', UNDERLINE: '+underline', BOLD: '+bold', ITALIC: '+italic', FONT_SIZE: '+fontSize', FONT_FACE: '+fontName', FONT_COLOR: '+foreColor', EMOTICON: '+emoticon', EQUATION: '+equation', BACKGROUND_COLOR: '+backColor', ORDERED_LIST: '+insertOrderedList', UNORDERED_LIST: '+insertUnorderedList', TABLE: '+table', JUSTIFY_CENTER: '+justifyCenter', JUSTIFY_FULL: '+justifyFull', JUSTIFY_RIGHT: '+justifyRight', JUSTIFY_LEFT: '+justifyLeft', BLOCKQUOTE: '+BLOCKQUOTE', // This is a nodename. Should be all caps. DIR_LTR: 'ltr', // should be exactly 'ltr' as it becomes dir attribute value DIR_RTL: 'rtl', // same here IMAGE: 'image', EDIT_HTML: 'editHtml', UPDATE_LINK_BUBBLE: 'updateLinkBubble', // queryCommandValue only: returns the default tag name used in the field. // DIV should be considered the default if no plugin responds. DEFAULT_TAG: '+defaultTag', // TODO(nicksantos): Try to give clients an API so that they don't need // these execCommands. CLEAR_LOREM: 'clearlorem', UPDATE_LOREM: 'updatelorem', USING_LOREM: 'usinglorem', // Modal editor commands (usually dialogs). MODAL_LINK_EDITOR: 'link' };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('goog.editor.plugins.equation.EquationBubble'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.editor.Command'); goog.require('goog.editor.plugins.AbstractBubblePlugin'); goog.require('goog.string.Unicode'); goog.require('goog.ui.editor.Bubble'); goog.require('goog.ui.equation.ImageRenderer'); /** * Property bubble plugin for equations. * * @constructor * @extends {goog.editor.plugins.AbstractBubblePlugin} */ goog.editor.plugins.equation.EquationBubble = function() { goog.base(this); }; goog.inherits(goog.editor.plugins.equation.EquationBubble, goog.editor.plugins.AbstractBubblePlugin); /** * Id for 'edit' link. * @type {string} * @private */ goog.editor.plugins.equation.EquationBubble.EDIT_ID_ = 'ee_bubble_edit'; /** * Id for 'remove' link. * @type {string} * @private */ goog.editor.plugins.equation.EquationBubble.REMOVE_ID_ = 'ee_remove_remove'; /** * @desc Label for the equation property bubble. */ var MSG_EE_BUBBLE_EQUATION = goog.getMsg('Equation:'); /** * @desc Link text for equation property bubble to edit the equation. */ var MSG_EE_BUBBLE_EDIT = goog.getMsg('Edit'); /** * @desc Link text for equation property bubble to remove the equation. */ var MSG_EE_BUBBLE_REMOVE = goog.getMsg('Remove'); /** @override */ goog.editor.plugins.equation.EquationBubble.prototype.getTrogClassId = function() { return 'EquationBubble'; }; /** @override */ goog.editor.plugins.equation.EquationBubble.prototype. getBubbleTargetFromSelection = function(selectedElement) { if (selectedElement && goog.ui.equation.ImageRenderer.isEquationElement(selectedElement)) { return selectedElement; } return null; }; /** @override */ goog.editor.plugins.equation.EquationBubble.prototype.createBubbleContents = function(bubbleContainer) { goog.dom.appendChild(bubbleContainer, bubbleContainer.ownerDocument.createTextNode( MSG_EE_BUBBLE_EQUATION + goog.string.Unicode.NBSP)); this.createLink(goog.editor.plugins.equation.EquationBubble.EDIT_ID_, MSG_EE_BUBBLE_EDIT, this.editEquation_, bubbleContainer); goog.dom.appendChild(bubbleContainer, bubbleContainer.ownerDocument.createTextNode( MSG_EE_BUBBLE_EQUATION + goog.editor.plugins.AbstractBubblePlugin.DASH_NBSP_STRING)); this.createLink(goog.editor.plugins.equation.EquationBubble.REMOVE_ID_, MSG_EE_BUBBLE_REMOVE, this.removeEquation_, bubbleContainer); }; /** @override */ goog.editor.plugins.equation.EquationBubble.prototype.getBubbleType = function() { return goog.dom.TagName.IMG; }; /** @override */ goog.editor.plugins.equation.EquationBubble.prototype.getBubbleTitle = function() { /** @desc Title for the equation bubble. */ var MSG_EQUATION_BUBBLE_TITLE = goog.getMsg('Equation'); return MSG_EQUATION_BUBBLE_TITLE; }; /** * Removes the equation associated with the bubble. * @private */ goog.editor.plugins.equation.EquationBubble.prototype.removeEquation_ = function() { this.getFieldObject().dispatchBeforeChange(); goog.dom.removeNode(this.getTargetElement()); this.closeBubble(); this.getFieldObject().dispatchChange(); }; /** * Opens equation editor for the equation associated with the bubble. * @private */ goog.editor.plugins.equation.EquationBubble.prototype.editEquation_ = function() { var equationNode = this.getTargetElement(); this.closeBubble(); this.getFieldObject().execCommand(goog.editor.Command.EQUATION, equationNode); };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Functions to style text. * */ goog.provide('goog.editor.plugins.BasicTextFormatter'); goog.provide('goog.editor.plugins.BasicTextFormatter.COMMAND'); goog.require('goog.array'); goog.require('goog.debug.Logger'); goog.require('goog.dom'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.Range'); goog.require('goog.dom.TagName'); goog.require('goog.editor.BrowserFeature'); goog.require('goog.editor.Command'); goog.require('goog.editor.Link'); goog.require('goog.editor.Plugin'); goog.require('goog.editor.node'); goog.require('goog.editor.range'); goog.require('goog.editor.style'); goog.require('goog.iter'); goog.require('goog.iter.StopIteration'); goog.require('goog.object'); goog.require('goog.string'); goog.require('goog.string.Unicode'); goog.require('goog.style'); goog.require('goog.ui.editor.messages'); goog.require('goog.userAgent'); /** * Functions to style text (e.g. underline, make bold, etc.) * @constructor * @extends {goog.editor.Plugin} */ goog.editor.plugins.BasicTextFormatter = function() { goog.editor.Plugin.call(this); }; goog.inherits(goog.editor.plugins.BasicTextFormatter, goog.editor.Plugin); /** @override */ goog.editor.plugins.BasicTextFormatter.prototype.getTrogClassId = function() { return 'BTF'; }; /** * Logging object. * @type {goog.debug.Logger} * @protected * @override */ goog.editor.plugins.BasicTextFormatter.prototype.logger = goog.debug.Logger.getLogger('goog.editor.plugins.BasicTextFormatter'); /** * Commands implemented by this plugin. * @enum {string} */ goog.editor.plugins.BasicTextFormatter.COMMAND = { LINK: '+link', FORMAT_BLOCK: '+formatBlock', INDENT: '+indent', OUTDENT: '+outdent', STRIKE_THROUGH: '+strikeThrough', HORIZONTAL_RULE: '+insertHorizontalRule', SUBSCRIPT: '+subscript', SUPERSCRIPT: '+superscript', UNDERLINE: '+underline', BOLD: '+bold', ITALIC: '+italic', FONT_SIZE: '+fontSize', FONT_FACE: '+fontName', FONT_COLOR: '+foreColor', BACKGROUND_COLOR: '+backColor', ORDERED_LIST: '+insertOrderedList', UNORDERED_LIST: '+insertUnorderedList', JUSTIFY_CENTER: '+justifyCenter', JUSTIFY_FULL: '+justifyFull', JUSTIFY_RIGHT: '+justifyRight', JUSTIFY_LEFT: '+justifyLeft' }; /** * Inverse map of execCommand strings to * {@link goog.editor.plugins.BasicTextFormatter.COMMAND} constants. Used to * determine whether a string corresponds to a command this plugin * handles in O(1) time. * @type {Object} * @private */ goog.editor.plugins.BasicTextFormatter.SUPPORTED_COMMANDS_ = goog.object.transpose(goog.editor.plugins.BasicTextFormatter.COMMAND); /** * Whether the string corresponds to a command this plugin handles. * @param {string} command Command string to check. * @return {boolean} Whether the string corresponds to a command * this plugin handles. * @override */ goog.editor.plugins.BasicTextFormatter.prototype.isSupportedCommand = function( command) { // TODO(user): restore this to simple check once table editing // is moved out into its own plugin return command in goog.editor.plugins.BasicTextFormatter.SUPPORTED_COMMANDS_; }; /** * @return {goog.dom.AbstractRange} The closure range object that wraps the * current user selection. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.getRange_ = function() { return this.getFieldObject().getRange(); }; /** * @return {Document} The document object associated with the currently active * field. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.getDocument_ = function() { return this.getFieldDomHelper().getDocument(); }; /** * Execute a user-initiated command. * @param {string} command Command to execute. * @param {...*} var_args For color commands, this * should be the hex color (with the #). For FORMAT_BLOCK, this should be * the goog.editor.plugins.BasicTextFormatter.BLOCK_COMMAND. * It will be unused for other commands. * @return {Object|undefined} The result of the command. * @override */ goog.editor.plugins.BasicTextFormatter.prototype.execCommandInternal = function( command, var_args) { var preserveDir, styleWithCss, needsFormatBlockDiv, hasDummySelection; var result; var opt_arg = arguments[1]; switch (command) { case goog.editor.plugins.BasicTextFormatter.COMMAND.BACKGROUND_COLOR: // Don't bother for no color selected, color picker is resetting itself. if (!goog.isNull(opt_arg)) { if (goog.editor.BrowserFeature.EATS_EMPTY_BACKGROUND_COLOR) { this.applyBgColorManually_(opt_arg); } else if (goog.userAgent.OPERA) { // backColor will color the block level element instead of // the selected span of text in Opera. this.execCommandHelper_('hiliteColor', opt_arg); } else { this.execCommandHelper_(command, opt_arg); } } break; case goog.editor.plugins.BasicTextFormatter.COMMAND.LINK: result = this.toggleLink_(opt_arg); break; case goog.editor.plugins.BasicTextFormatter.COMMAND.JUSTIFY_CENTER: case goog.editor.plugins.BasicTextFormatter.COMMAND.JUSTIFY_FULL: case goog.editor.plugins.BasicTextFormatter.COMMAND.JUSTIFY_RIGHT: case goog.editor.plugins.BasicTextFormatter.COMMAND.JUSTIFY_LEFT: this.justify_(command); break; default: if (goog.userAgent.IE && command == goog.editor.plugins.BasicTextFormatter.COMMAND.FORMAT_BLOCK && opt_arg) { // IE requires that the argument be in the form of an opening // tag, like <h1>, including angle brackets. WebKit will accept // the arguemnt with or without brackets, and Firefox pre-3 supports // only a fixed subset of tags with brackets, and prefers without. // So we only add them IE only. opt_arg = '<' + opt_arg + '>'; } if (command == goog.editor.plugins.BasicTextFormatter.COMMAND.FONT_COLOR && goog.isNull(opt_arg)) { // If we don't have a color, then FONT_COLOR is a no-op. break; } switch (command) { case goog.editor.plugins.BasicTextFormatter.COMMAND.INDENT: case goog.editor.plugins.BasicTextFormatter.COMMAND.OUTDENT: if (goog.editor.BrowserFeature.HAS_STYLE_WITH_CSS) { if (goog.userAgent.GECKO) { styleWithCss = true; } if (goog.userAgent.OPERA) { if (command == goog.editor.plugins.BasicTextFormatter.COMMAND.OUTDENT) { // styleWithCSS actually sets negative margins on <blockquote> // to outdent them. If the command is enabled without // styleWithCSS flipped on, then the caret is in a blockquote so // styleWithCSS must not be used. But if the command is not // enabled, styleWithCSS should be used so that elements such as // a <div> with a margin-left style can still be outdented. // (Opera bug: CORE-21118) styleWithCss = !this.getDocument_().queryCommandEnabled('outdent'); } else { // Always use styleWithCSS for indenting. Otherwise, Opera will // make separate <blockquote>s around *each* indented line, // which adds big default <blockquote> margins between each // indented line. styleWithCss = true; } } } // Fall through. case goog.editor.plugins.BasicTextFormatter.COMMAND.ORDERED_LIST: case goog.editor.plugins.BasicTextFormatter.COMMAND.UNORDERED_LIST: if (goog.editor.BrowserFeature.LEAVES_P_WHEN_REMOVING_LISTS && this.queryCommandStateInternal_(this.getDocument_(), command)) { // IE leaves behind P tags when unapplying lists. // If we're not in P-mode, then we want divs // So, unlistify, then convert the Ps into divs. needsFormatBlockDiv = this.getFieldObject().queryCommandValue( goog.editor.Command.DEFAULT_TAG) != goog.dom.TagName.P; } else if (!goog.editor.BrowserFeature.CAN_LISTIFY_BR) { // IE doesn't convert BRed line breaks into separate list items. // So convert the BRs to divs, then do the listify. this.convertBreaksToDivs_(); } // This fix only works in Gecko. if (goog.userAgent.GECKO && goog.editor.BrowserFeature.FORGETS_FORMATTING_WHEN_LISTIFYING && !this.queryCommandValue(command)) { hasDummySelection |= this.beforeInsertListGecko_(); } // Fall through to preserveDir block case goog.editor.plugins.BasicTextFormatter.COMMAND.FORMAT_BLOCK: // Both FF & IE may lose directionality info. Save/restore it. // TODO(user): Does Safari also need this? // TODO (gmark, jparent): This isn't ideal because it uses a string // literal, so if the plugin name changes, it would break. We need a // better solution. See also other places in code that use // this.getPluginByClassId('Bidi'). preserveDir = !!this.getFieldObject().getPluginByClassId('Bidi'); break; case goog.editor.plugins.BasicTextFormatter.COMMAND.SUBSCRIPT: case goog.editor.plugins.BasicTextFormatter.COMMAND.SUPERSCRIPT: if (goog.editor.BrowserFeature.NESTS_SUBSCRIPT_SUPERSCRIPT) { // This browser nests subscript and superscript when both are // applied, instead of canceling out the first when applying the // second. this.applySubscriptSuperscriptWorkarounds_(command); } break; case goog.editor.plugins.BasicTextFormatter.COMMAND.UNDERLINE: case goog.editor.plugins.BasicTextFormatter.COMMAND.BOLD: case goog.editor.plugins.BasicTextFormatter.COMMAND.ITALIC: // If we are applying the formatting, then we want to have // styleWithCSS false so that we generate html tags (like <b>). If we // are unformatting something, we want to have styleWithCSS true so // that we can unformat both html tags and inline styling. // TODO(user): What about WebKit and Opera? styleWithCss = goog.userAgent.GECKO && goog.editor.BrowserFeature.HAS_STYLE_WITH_CSS && this.queryCommandValue(command); break; case goog.editor.plugins.BasicTextFormatter.COMMAND.FONT_COLOR: case goog.editor.plugins.BasicTextFormatter.COMMAND.FONT_FACE: // It is very expensive in FF (order of magnitude difference) to use // font tags instead of styled spans. Whenever possible, // force FF to use spans. // Font size is very expensive too, but FF always uses font tags, // regardless of which styleWithCSS value you use. styleWithCss = goog.editor.BrowserFeature.HAS_STYLE_WITH_CSS && goog.userAgent.GECKO; } /** * Cases where we just use the default execCommand (in addition * to the above fall-throughs) * goog.editor.plugins.BasicTextFormatter.COMMAND.STRIKE_THROUGH: * goog.editor.plugins.BasicTextFormatter.COMMAND.HORIZONTAL_RULE: * goog.editor.plugins.BasicTextFormatter.COMMAND.SUBSCRIPT: * goog.editor.plugins.BasicTextFormatter.COMMAND.SUPERSCRIPT: * goog.editor.plugins.BasicTextFormatter.COMMAND.UNDERLINE: * goog.editor.plugins.BasicTextFormatter.COMMAND.BOLD: * goog.editor.plugins.BasicTextFormatter.COMMAND.ITALIC: * goog.editor.plugins.BasicTextFormatter.COMMAND.FONT_SIZE: * goog.editor.plugins.BasicTextFormatter.COMMAND.FONT_FACE: */ this.execCommandHelper_(command, opt_arg, preserveDir, !!styleWithCss); if (hasDummySelection) { this.getDocument_().execCommand('Delete', false, true); } if (needsFormatBlockDiv) { this.getDocument_().execCommand('FormatBlock', false, '<div>'); } } // FF loses focus, so we have to set the focus back to the document or the // user can't type after selecting from menu. In IE, focus is set correctly // and resetting it here messes it up. if (goog.userAgent.GECKO && !this.getFieldObject().inModalMode()) { this.focusField_(); } return result; }; /** * Focuses on the field. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.focusField_ = function() { this.getFieldDomHelper().getWindow().focus(); }; /** * Gets the command value. * @param {string} command The command value to get. * @return {string|boolean|null} The current value of the command in the given * selection. NOTE: This return type list is not documented in MSDN or MDC * and has been constructed from experience. Please update it * if necessary. * @override */ goog.editor.plugins.BasicTextFormatter.prototype.queryCommandValue = function( command) { var styleWithCss; switch (command) { case goog.editor.plugins.BasicTextFormatter.COMMAND.LINK: return this.isNodeInState_(goog.dom.TagName.A); case goog.editor.plugins.BasicTextFormatter.COMMAND.JUSTIFY_CENTER: case goog.editor.plugins.BasicTextFormatter.COMMAND.JUSTIFY_FULL: case goog.editor.plugins.BasicTextFormatter.COMMAND.JUSTIFY_RIGHT: case goog.editor.plugins.BasicTextFormatter.COMMAND.JUSTIFY_LEFT: return this.isJustification_(command); case goog.editor.plugins.BasicTextFormatter.COMMAND.FORMAT_BLOCK: // TODO(nicksantos): See if we can use queryCommandValue here. return goog.editor.plugins.BasicTextFormatter.getSelectionBlockState_( this.getFieldObject().getRange()); case goog.editor.plugins.BasicTextFormatter.COMMAND.INDENT: case goog.editor.plugins.BasicTextFormatter.COMMAND.OUTDENT: case goog.editor.plugins.BasicTextFormatter.COMMAND.HORIZONTAL_RULE: // TODO: See if there are reasonable results to return for // these commands. return false; case goog.editor.plugins.BasicTextFormatter.COMMAND.FONT_SIZE: case goog.editor.plugins.BasicTextFormatter.COMMAND.FONT_FACE: case goog.editor.plugins.BasicTextFormatter.COMMAND.FONT_COLOR: case goog.editor.plugins.BasicTextFormatter.COMMAND.BACKGROUND_COLOR: // We use queryCommandValue here since we don't just want to know if a // color/fontface/fontsize is applied, we want to know WHICH one it is. return this.queryCommandValueInternal_(this.getDocument_(), command, goog.editor.BrowserFeature.HAS_STYLE_WITH_CSS && goog.userAgent.GECKO); case goog.editor.plugins.BasicTextFormatter.COMMAND.UNDERLINE: case goog.editor.plugins.BasicTextFormatter.COMMAND.BOLD: case goog.editor.plugins.BasicTextFormatter.COMMAND.ITALIC: styleWithCss = goog.editor.BrowserFeature.HAS_STYLE_WITH_CSS && goog.userAgent.GECKO; default: /** * goog.editor.plugins.BasicTextFormatter.COMMAND.STRIKE_THROUGH * goog.editor.plugins.BasicTextFormatter.COMMAND.SUBSCRIPT * goog.editor.plugins.BasicTextFormatter.COMMAND.SUPERSCRIPT * goog.editor.plugins.BasicTextFormatter.COMMAND.UNDERLINE * goog.editor.plugins.BasicTextFormatter.COMMAND.BOLD * goog.editor.plugins.BasicTextFormatter.COMMAND.ITALIC * goog.editor.plugins.BasicTextFormatter.COMMAND.ORDERED_LIST * goog.editor.plugins.BasicTextFormatter.COMMAND.UNORDERED_LIST */ // This only works for commands that use the default execCommand return this.queryCommandStateInternal_(this.getDocument_(), command, styleWithCss); } }; /** * @override */ goog.editor.plugins.BasicTextFormatter.prototype.prepareContentsHtml = function(html) { // If the browser collapses empty nodes and the field has only a script // tag in it, then it will collapse this node. Which will mean the user // can't click into it to edit it. if (goog.editor.BrowserFeature.COLLAPSES_EMPTY_NODES && html.match(/^\s*<script/i)) { html = '&nbsp;' + html; } if (goog.editor.BrowserFeature.CONVERT_TO_B_AND_I_TAGS) { // Some browsers (FF) can't undo strong/em in some cases, but can undo b/i! html = html.replace(/<(\/?)strong([^\w])/gi, '<$1b$2'); html = html.replace(/<(\/?)em([^\w])/gi, '<$1i$2'); } return html; }; /** * @override */ goog.editor.plugins.BasicTextFormatter.prototype.cleanContentsDom = function(fieldCopy) { var images = fieldCopy.getElementsByTagName(goog.dom.TagName.IMG); for (var i = 0, image; image = images[i]; i++) { if (goog.editor.BrowserFeature.SHOWS_CUSTOM_ATTRS_IN_INNER_HTML) { // Only need to remove these attributes in IE because // Firefox and Safari don't show custom attributes in the innerHTML. image.removeAttribute('tabIndex'); image.removeAttribute('tabIndexSet'); goog.removeUid(image); // Declare oldTypeIndex for the compiler. The associated plugin may not be // included in the compiled bundle. /** @type {string} */ image.oldTabIndex; // oldTabIndex will only be set if // goog.editor.BrowserFeature.TABS_THROUGH_IMAGES is true and we're in // P-on-enter mode. if (image.oldTabIndex) { image.tabIndex = image.oldTabIndex; } } } }; /** * @override */ goog.editor.plugins.BasicTextFormatter.prototype.cleanContentsHtml = function(html) { if (goog.editor.BrowserFeature.MOVES_STYLE_TO_HEAD) { // Safari creates a new <head> element for <style> tags, so prepend their // contents to the output. var heads = this.getFieldObject().getEditableDomHelper(). getElementsByTagNameAndClass(goog.dom.TagName.HEAD); var stylesHtmlArr = []; // i starts at 1 so we don't copy in the original, legitimate <head>. var numHeads = heads.length; for (var i = 1; i < numHeads; ++i) { var styles = heads[i].getElementsByTagName(goog.dom.TagName.STYLE); var numStyles = styles.length; for (var j = 0; j < numStyles; ++j) { stylesHtmlArr.push(styles[j].outerHTML); } } return stylesHtmlArr.join('') + html; } return html; }; /** * @override */ goog.editor.plugins.BasicTextFormatter.prototype.handleKeyboardShortcut = function(e, key, isModifierPressed) { if (!isModifierPressed) { return false; } var command; switch (key) { case 'b': // Ctrl+B command = goog.editor.plugins.BasicTextFormatter.COMMAND.BOLD; break; case 'i': // Ctrl+I command = goog.editor.plugins.BasicTextFormatter.COMMAND.ITALIC; break; case 'u': // Ctrl+U command = goog.editor.plugins.BasicTextFormatter.COMMAND.UNDERLINE; break; case 's': // Ctrl+S // TODO(user): This doesn't belong in here. Clients should handle // this themselves. // Catching control + s prevents the annoying browser save dialog // from appearing. return true; } if (command) { this.getFieldObject().execCommand(command); return true; } return false; }; // Helpers for execCommand /** * Regular expression to match BRs in HTML. Saves the BRs' attributes in $1 for * use with replace(). In non-IE browsers, does not match BRs adjacent to an * opening or closing DIV or P tag, since nonrendered BR elements can occur at * the end of block level containers in those browsers' editors. * @type {RegExp} * @private */ goog.editor.plugins.BasicTextFormatter.BR_REGEXP_ = goog.userAgent.IE ? /<br([^\/>]*)\/?>/gi : /<br([^\/>]*)\/?>(?!<\/(div|p)>)/gi; /** * Convert BRs in the selection to divs. * This is only intended to be used in IE and Opera. * @return {boolean} Whether any BR's were converted. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.convertBreaksToDivs_ = function() { if (!goog.userAgent.IE && !goog.userAgent.OPERA) { // This function is only supported on IE and Opera. return false; } var range = this.getRange_(); var parent = range.getContainerElement(); var doc = this.getDocument_(); goog.editor.plugins.BasicTextFormatter.BR_REGEXP_.lastIndex = 0; // Only mess with the HTML/selection if it contains a BR. if (goog.editor.plugins.BasicTextFormatter.BR_REGEXP_.test( parent.innerHTML)) { // Insert temporary markers to remember the selection. var savedRange = range.saveUsingCarets(); if (parent.tagName == goog.dom.TagName.P) { // Can't append paragraphs to paragraph tags. Throws an exception in IE. goog.editor.plugins.BasicTextFormatter.convertParagraphToDiv_( parent, true); } else { // Used to do: // IE: <div>foo<br>bar</div> --> <div>foo<p id="temp_br">bar</div> // Opera: <div>foo<br>bar</div> --> <div>foo<p class="temp_br">bar</div> // To fix bug 1939883, now does for both: // <div>foo<br>bar</div> --> <div>foo<p trtempbr="temp_br">bar</div> // TODO(user): Confirm if there's any way to skip this // intermediate step of converting br's to p's before converting those to // div's. The reason may be hidden in CLs 5332866 and 8530601. var attribute = 'trtempbr'; var value = 'temp_br'; var newHtml = parent.innerHTML.replace( goog.editor.plugins.BasicTextFormatter.BR_REGEXP_, '<p$1 ' + attribute + '="' + value + '">'); goog.editor.node.replaceInnerHtml(parent, newHtml); var paragraphs = goog.array.toArray(parent.getElementsByTagName(goog.dom.TagName.P)); goog.iter.forEach(paragraphs, function(paragraph) { if (paragraph.getAttribute(attribute) == value) { paragraph.removeAttribute(attribute); if (goog.string.isBreakingWhitespace( goog.dom.getTextContent(paragraph))) { // Prevent the empty blocks from collapsing. // A <BR> is preferable because it doesn't result in any text being // added to the "blank" line. In IE, however, it is possible to // place the caret after the <br>, which effectively creates a // visible line break. Because of this, we have to resort to using a // &nbsp; in IE. var child = goog.userAgent.IE ? doc.createTextNode(goog.string.Unicode.NBSP) : doc.createElement(goog.dom.TagName.BR); paragraph.appendChild(child); } goog.editor.plugins.BasicTextFormatter.convertParagraphToDiv_( paragraph); } }); } // Select the previously selected text so we only listify // the selected portion and maintain the user's selection. savedRange.restore(); return true; } return false; }; /** * Convert the given paragraph to being a div. This clobbers the * passed-in node! * This is only intended to be used in IE and Opera. * @param {Node} paragraph Paragragh to convert to a div. * @param {boolean=} opt_convertBrs If true, also convert BRs to divs. * @private */ goog.editor.plugins.BasicTextFormatter.convertParagraphToDiv_ = function(paragraph, opt_convertBrs) { if (!goog.userAgent.IE && !goog.userAgent.OPERA) { // This function is only supported on IE and Opera. return; } var outerHTML = paragraph.outerHTML.replace(/<(\/?)p/gi, '<$1div'); if (opt_convertBrs) { // IE fills in the closing div tag if it's missing! outerHTML = outerHTML.replace( goog.editor.plugins.BasicTextFormatter.BR_REGEXP_, '</div><div$1>'); } if (goog.userAgent.OPERA && !/<\/div>$/i.test(outerHTML)) { // Opera doesn't automatically add the closing tag, so add it if needed. outerHTML += '</div>'; } paragraph.outerHTML = outerHTML; }; /** * If this is a goog.editor.plugins.BasicTextFormatter.COMMAND, * convert it to something that we can pass into execCommand, * queryCommandState, etc. * * TODO(user): Consider doing away with the + and converter completely. * * @param {goog.editor.plugins.BasicTextFormatter.COMMAND|string} * command A command key. * @return {string} The equivalent execCommand command. * @private */ goog.editor.plugins.BasicTextFormatter.convertToRealExecCommand_ = function( command) { return command.indexOf('+') == 0 ? command.substring(1) : command; }; /** * Justify the text in the selection. * @param {string} command The type of justification to perform. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.justify_ = function(command) { this.execCommandHelper_(command, null, false, true); // Firefox cannot justify divs. In fact, justifying divs results in removing // the divs and replacing them with brs. So "<div>foo</div><div>bar</div>" // becomes "foo<br>bar" after alignment is applied. However, if you justify // again, then you get "<div style='text-align: right'>foo<br>bar</div>", // which at least looks visually correct. Since justification is (normally) // idempotent, it isn't a problem when the selection does not contain divs to // apply justifcation again. if (goog.userAgent.GECKO) { this.execCommandHelper_(command, null, false, true); } // Convert all block elements in the selection to use CSS text-align // instead of the align property. This works better because the align // property is overridden by the CSS text-align property. // // Only for browsers that can't handle this by the styleWithCSS execCommand, // which allows us to specify if we should insert align or text-align. // TODO(user): What about WebKit or Opera? if (!(goog.editor.BrowserFeature.HAS_STYLE_WITH_CSS && goog.userAgent.GECKO)) { goog.iter.forEach(this.getFieldObject().getRange(), goog.editor.plugins.BasicTextFormatter.convertContainerToTextAlign_); } }; /** * Converts the block element containing the given node to use CSS text-align * instead of the align property. * @param {Node} node The node to convert the container of. * @private */ goog.editor.plugins.BasicTextFormatter.convertContainerToTextAlign_ = function(node) { var container = goog.editor.style.getContainer(node); // TODO(user): Fix this so that it doesn't screw up tables. if (container.align) { container.style.textAlign = container.align; container.removeAttribute('align'); } }; /** * Perform an execCommand on the active document. * @param {string} command The command to execute. * @param {string|number|boolean|null=} opt_value Optional value. * @param {boolean=} opt_preserveDir Set true to make sure that command does not * change directionality of the selected text (works only if all selected * text has the same directionality, otherwise ignored). Should not be true * if bidi plugin is not loaded. * @param {boolean=} opt_styleWithCss Set to true to ask the browser to use CSS * to perform the execCommand. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.execCommandHelper_ = function( command, opt_value, opt_preserveDir, opt_styleWithCss) { // There is a bug in FF: some commands do not preserve attributes of the // block-level elements they replace. // This (among the rest) leads to loss of directionality information. // For now we use a hack (when opt_preserveDir==true) to avoid this // directionality problem in the simplest cases. // Known affected commands: formatBlock, insertOrderedList, // insertUnorderedList, indent, outdent. // A similar problem occurs in IE when insertOrderedList or // insertUnorderedList remove existing list. var dir = null; if (opt_preserveDir) { dir = this.getFieldObject().queryCommandValue( goog.editor.Command.DIR_RTL) ? 'rtl' : this.getFieldObject().queryCommandValue( goog.editor.Command.DIR_LTR) ? 'ltr' : null; } command = goog.editor.plugins.BasicTextFormatter.convertToRealExecCommand_( command); var endDiv, nbsp; if (goog.userAgent.IE) { var ret = this.applyExecCommandIEFixes_(command); endDiv = ret[0]; nbsp = ret[1]; } if (goog.userAgent.WEBKIT) { endDiv = this.applyExecCommandSafariFixes_(command); } if (goog.userAgent.GECKO) { this.applyExecCommandGeckoFixes_(command); } if (goog.editor.BrowserFeature.DOESNT_OVERRIDE_FONT_SIZE_IN_STYLE_ATTR && command.toLowerCase() == 'fontsize') { this.removeFontSizeFromStyleAttrs_(); } var doc = this.getDocument_(); if (opt_styleWithCss && goog.editor.BrowserFeature.HAS_STYLE_WITH_CSS) { doc.execCommand('styleWithCSS', false, true); if (goog.userAgent.OPERA) { this.invalidateInlineCss_(); } } doc.execCommand(command, false, opt_value); if (opt_styleWithCss && goog.editor.BrowserFeature.HAS_STYLE_WITH_CSS) { // If we enabled styleWithCSS, turn it back off. doc.execCommand('styleWithCSS', false, false); } if (goog.userAgent.WEBKIT && !goog.userAgent.isVersion('526') && command.toLowerCase() == 'formatblock' && opt_value && /^[<]?h\d[>]?$/i.test(opt_value)) { this.cleanUpSafariHeadings_(); } if (/insert(un)?orderedlist/i.test(command)) { // NOTE(user): This doesn't check queryCommandState because it seems to // lie. Also, this runs for insertunorderedlist so that the the list // isn't made up of an <ul> for each <li> - even though it looks the same, // the markup is disgusting. if (goog.userAgent.WEBKIT) { this.fixSafariLists_(); } if (goog.userAgent.IE) { this.fixIELists_(); if (nbsp) { // Remove the text node, if applicable. Do not try to instead clobber // the contents of the text node if it was added, or the same invalid // node thing as above will happen. The error won't happen here, it // will happen after you hit enter and then do anything that loops // through the dom and tries to read that node. goog.dom.removeNode(nbsp); } } } if (endDiv) { // Remove the dummy div. goog.dom.removeNode(endDiv); } // Restore directionality if required and only when unambigous (dir!=null). if (dir) { this.getFieldObject().execCommand(dir); } }; /** * Applies a background color to a selection when the browser can't do the job. * * NOTE(nicksantos): If you think this is hacky, you should try applying * background color in Opera. It made me cry. * * @param {string} bgColor backgroundColor from .formatText to .execCommand. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.applyBgColorManually_ = function(bgColor) { var needsSpaceInTextNode = goog.userAgent.GECKO; var range = this.getFieldObject().getRange(); var textNode; var parentTag; if (range && range.isCollapsed()) { // Hack to handle Firefox bug: // https://bugzilla.mozilla.org/show_bug.cgi?id=279330 // execCommand hiliteColor in Firefox on collapsed selection creates // a font tag onkeypress textNode = this.getFieldDomHelper(). createTextNode(needsSpaceInTextNode ? ' ' : ''); var containerNode = range.getStartNode(); // Check if we're inside a tag that contains the cursor and nothing else; // if we are, don't create a dummySpan. Just use this containing tag to // hide the 1-space selection. // If the user sets a background color on a collapsed selection, then sets // another one immediately, we get a span tag with a single empty TextNode. // If the user sets a background color, types, then backspaces, we get a // span tag with nothing inside it (container is the span). parentTag = containerNode.nodeType == goog.dom.NodeType.ELEMENT ? containerNode : containerNode.parentNode; if (parentTag.innerHTML == '') { // There's an Element to work with // make the space character invisible using a CSS indent hack parentTag.style.textIndent = '-10000px'; parentTag.appendChild(textNode); } else { // No Element to work with; make one // create a span with a space character inside // make the space character invisible using a CSS indent hack parentTag = this.getFieldDomHelper().createDom('span', {'style': 'text-indent:-10000px'}, textNode); range.replaceContentsWithNode(parentTag); } goog.dom.Range.createFromNodeContents(textNode).select(); } this.execCommandHelper_('hiliteColor', bgColor, false, true); if (textNode) { // eliminate the space if necessary. if (needsSpaceInTextNode) { textNode.data = ''; } // eliminate the hack. parentTag.style.textIndent = ''; // execCommand modified our span so we leave it in place. } }; /** * Toggle link for the current selection: * If selection contains a link, unlink it, return null. * Otherwise, make selection into a link, return the link. * @param {string=} opt_target Target for the link. * @return {goog.editor.Link?} The resulting link, or null if a link was * removed. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.toggleLink_ = function( opt_target) { if (!this.getFieldObject().isSelectionEditable()) { this.focusField_(); } var range = this.getRange_(); // Since we wrap images in links, its possible that the user selected an // image and clicked link, in which case we want to actually use the // image as the selection. var parent = range && range.getContainerElement(); var link = /** @type {Element} */ ( goog.dom.getAncestorByTagNameAndClass(parent, goog.dom.TagName.A)); if (link && goog.editor.node.isEditable(link)) { goog.dom.flattenElement(link); } else { var editableLink = this.createLink_(range, '/', opt_target); if (editableLink) { if (!this.getFieldObject().execCommand( goog.editor.Command.MODAL_LINK_EDITOR, editableLink)) { var url = this.getFieldObject().getAppWindow().prompt( goog.ui.editor.messages.MSG_LINK_TO, 'http://'); if (url) { editableLink.setTextAndUrl(editableLink.getCurrentText() || url, url); editableLink.placeCursorRightOf(); } else { var savedRange = goog.editor.range.saveUsingNormalizedCarets( goog.dom.Range.createFromNodeContents(editableLink.getAnchor())); editableLink.removeLink(); savedRange.restore().select(); return null; } } return editableLink; } } return null; }; /** * Create a link out of the current selection. If nothing is selected, insert * a new link. Otherwise, enclose the selection in a link. * @param {goog.dom.AbstractRange} range The closure range object for the * current selection. * @param {string} url The url to link to. * @param {string=} opt_target Target for the link. * @return {goog.editor.Link?} The newly created link. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.createLink_ = function(range, url, opt_target) { var anchor = null; var anchors = []; var parent = range && range.getContainerElement(); // We do not yet support creating links around images. Instead of throwing // lots of js errors, just fail silently. // TODO(user): Add support for linking images. if (parent && parent.tagName == goog.dom.TagName.IMG) { return null; } if (range && range.isCollapsed()) { var textRange = range.getTextRange(0).getBrowserRangeObject(); if (goog.editor.BrowserFeature.HAS_W3C_RANGES) { anchor = this.getFieldDomHelper().createElement(goog.dom.TagName.A); textRange.insertNode(anchor); } else if (goog.editor.BrowserFeature.HAS_IE_RANGES) { // TODO: Use goog.dom.AbstractRange's surroundContents textRange.pasteHTML("<a id='newLink'></a>"); anchor = this.getFieldDomHelper().getElement('newLink'); anchor.removeAttribute('id'); } } else { // Create a unique identifier for the link so we can retrieve it later. // execCommand doesn't return the link to us, and we need a way to find // the newly created link in the dom, and the url is the only property // we have control over, so we set that to be unique and then find it. var uniqueId = goog.string.createUniqueString(); this.execCommandHelper_('CreateLink', uniqueId); var setHrefAndLink = function(element, index, arr) { // We can't do straight comparision since the href can contain the // absolute url. if (goog.string.endsWith(element.href, uniqueId)) { anchors.push(element); } }; goog.array.forEach(this.getFieldObject().getElement().getElementsByTagName( goog.dom.TagName.A), setHrefAndLink); if (anchors.length) { anchor = anchors.pop(); } } return goog.editor.Link.createNewLink( /** @type {HTMLAnchorElement} */ (anchor), url, opt_target, anchors); }; //--------------------------------------------------------------------- // browser fixes /** * The following execCommands are "broken" in some way - in IE they allow * the nodes outside the contentEditable region to get modified (see * execCommand below for more details). * @const * @private */ goog.editor.plugins.BasicTextFormatter.brokenExecCommandsIE_ = { 'indent' : 1, 'outdent' : 1, 'insertOrderedList' : 1, 'insertUnorderedList' : 1, 'justifyCenter' : 1, 'justifyFull' : 1, 'justifyRight': 1, 'justifyLeft': 1, 'ltr' : 1, 'rtl' : 1 }; /** * When the following commands are executed while the selection is * inside a blockquote, they hose the blockquote tag in weird and * unintuitive ways. * @const * @private */ goog.editor.plugins.BasicTextFormatter.blockquoteHatingCommandsIE_ = { 'insertOrderedList' : 1, 'insertUnorderedList' : 1 }; /** * Makes sure that superscript is removed before applying subscript, and vice * versa. Fixes {@link http://buganizer/issue?id=1173491} . * @param {goog.editor.plugins.BasicTextFormatter.COMMAND} command The command * being applied, either SUBSCRIPT or SUPERSCRIPT. * @private */ goog.editor.plugins.BasicTextFormatter. prototype.applySubscriptSuperscriptWorkarounds_ = function(command) { if (!this.queryCommandValue(command)) { // The current selection doesn't currently have the requested // command, so we are applying it as opposed to removing it. // (Note that queryCommandValue() will only return true if the // command is applied to the whole selection, not just part of it. // In this case it is fine because only if the whole selection has // the command applied will we be removing it and thus skipping the // removal of the opposite command.) var oppositeCommand = (command == goog.editor.plugins.BasicTextFormatter.COMMAND.SUBSCRIPT ? goog.editor.plugins.BasicTextFormatter.COMMAND.SUPERSCRIPT : goog.editor.plugins.BasicTextFormatter.COMMAND.SUBSCRIPT); var oppositeExecCommand = goog.editor.plugins.BasicTextFormatter. convertToRealExecCommand_(oppositeCommand); // Executing the opposite command on a selection that already has it // applied will cancel it out. But if the selection only has the // opposite command applied to a part of it, the browser will // normalize the selection to have the opposite command applied on // the whole of it. if (!this.queryCommandValue(oppositeCommand)) { // The selection doesn't have the opposite command applied to the // whole of it, so let's exec the opposite command to normalize // the selection. // Note: since we know both subscript and superscript commands // will boil down to a simple call to the browser's execCommand(), // for performance reasons we can do that directly instead of // calling execCommandHelper_(). However this is a potential for // bugs if the implementation of execCommandHelper_() is changed // to do something more int eh case of subscript and superscript. this.getDocument_().execCommand(oppositeExecCommand, false, null); } // Now that we know the whole selection has the opposite command // applied, we exec it a second time to properly remove it. this.getDocument_().execCommand(oppositeExecCommand, false, null); } }; /** * Removes inline font-size styles from elements fully contained in the * selection, so the font tags produced by execCommand work properly. * See {@bug 1286408}. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.removeFontSizeFromStyleAttrs_ = function() { // Expand the range so that we consider surrounding tags. E.g. if only the // text node inside a span is selected, the browser could wrap a font tag // around the span and leave the selection such that only the text node is // found when looking inside the range, not the span. var range = goog.editor.range.expand(this.getFieldObject().getRange(), this.getFieldObject().getElement()); goog.iter.forEach(goog.iter.filter(range, function(tag, dummy, iter) { return iter.isStartTag() && range.containsNode(tag); }), function(node) { goog.style.setStyle(node, 'font-size', ''); // Gecko doesn't remove empty style tags. if (goog.userAgent.GECKO && node.style.length == 0 && node.getAttribute('style') != null) { node.removeAttribute('style'); } }); }; /** * Apply pre-execCommand fixes for IE. * @param {string} command The command to execute. * @return {Array.<Node>} Array of nodes to be removed after the execCommand. * Will never be longer than 2 elements. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.applyExecCommandIEFixes_ = function(command) { // IE has a crazy bug where executing list commands // around blockquotes cause the blockquotes to get transformed // into "<OL><OL>" or "<UL><UL>" tags. var toRemove = []; var endDiv = null; var range = this.getRange_(); var dh = this.getFieldDomHelper(); if (command in goog.editor.plugins.BasicTextFormatter.blockquoteHatingCommandsIE_) { var parent = range && range.getContainerElement(); if (parent) { var blockquotes = goog.dom.getElementsByTagNameAndClass( goog.dom.TagName.BLOCKQUOTE, null, parent); // If a blockquote contains the selection, the fix is easy: // add a dummy div to the blockquote that isn't in the current selection. // // if the selection contains a blockquote, // there appears to be no easy way to protect it from getting mangled. // For now, we're just going to punt on this and try to // adjust the selection so that IE does something reasonable. // // TODO(nicksantos): Find a better fix for this. var bq; for (var i = 0; i < blockquotes.length; i++) { if (range.containsNode(blockquotes[i])) { bq = blockquotes[i]; break; } } var bqThatNeedsDummyDiv = bq || goog.dom.getAncestorByTagNameAndClass(parent, 'BLOCKQUOTE'); if (bqThatNeedsDummyDiv) { endDiv = dh.createDom('div', {style: 'height:0'}); goog.dom.appendChild(bqThatNeedsDummyDiv, endDiv); toRemove.push(endDiv); if (bq) { range = goog.dom.Range.createFromNodes(bq, 0, endDiv, 0); } else if (range.containsNode(endDiv)) { // the selection might be the entire blockquote, and // it's important that endDiv not be in the selection. range = goog.dom.Range.createFromNodes( range.getStartNode(), range.getStartOffset(), endDiv, 0); } range.select(); } } } // IE has a crazy bug where certain block execCommands cause it to mess with // the DOM nodes above the contentEditable element if the selection contains // or partially contains the last block element in the contentEditable // element. // Known commands: Indent, outdent, insertorderedlist, insertunorderedlist, // Justify (all of them) // Both of the above are "solved" by appending a dummy div to the field // before the execCommand and removing it after, but we don't need to do this // if we've alread added a dummy div somewhere else. var fieldObject = this.getFieldObject(); if (!fieldObject.usesIframe() && !endDiv) { if (command in goog.editor.plugins.BasicTextFormatter.brokenExecCommandsIE_) { var field = fieldObject.getElement(); // If the field is totally empty, or if the field contains only text nodes // and the cursor is at the end of the field, then IE stills walks outside // the contentEditable region and destroys things AND justify will not // work. This is "solved" by adding a text node into the end of the // field and moving the cursor before it. if (range && range.isCollapsed() && !goog.dom.getFirstElementChild(field)) { // The problem only occurs if the selection is at the end of the field. var selection = range.getTextRange(0).getBrowserRangeObject(); var testRange = selection.duplicate(); testRange.moveToElementText(field); testRange.collapse(false); if (testRange.isEqual(selection)) { // For reasons I really don't understand, if you use a breaking space // here, either " " or String.fromCharCode(32), this textNode becomes // corrupted, only after you hit ENTER to split it. It exists in the // dom in that its parent has it as childNode and the parent's // innerText is correct, but the node itself throws invalid argument // errors when you try to access its data, parentNode, nextSibling, // previousSibling or most other properties. WTF. var nbsp = dh.createTextNode(goog.string.Unicode.NBSP); field.appendChild(nbsp); selection.move('character', 1); selection.move('character', -1); selection.select(); toRemove.push(nbsp); } } endDiv = dh.createDom('div', {style: 'height:0'}); goog.dom.appendChild(field, endDiv); toRemove.push(endDiv); } } return toRemove; }; /** * Fix a ridiculous Safari bug: the first letters of new headings * somehow retain their original font size and weight if multiple lines are * selected during the execCommand that turns them into headings. * The solution is to strip these styles which are normally stripped when * making things headings anyway. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.cleanUpSafariHeadings_ = function() { goog.iter.forEach(this.getRange_(), function(node) { if (node.className == 'Apple-style-span') { // These shouldn't persist after creating headings via // a FormatBlock execCommand. node.style.fontSize = ''; node.style.fontWeight = ''; } }); }; /** * Prevent Safari from making each list item be "1" when converting from * unordered to ordered lists. * (see https://bugs.webkit.org/show_bug.cgi?id=19539 ) * @private */ goog.editor.plugins.BasicTextFormatter.prototype.fixSafariLists_ = function() { var previousList = false; goog.iter.forEach(this.getRange_(), function(node) { var tagName = node.tagName; if (tagName == goog.dom.TagName.UL || tagName == goog.dom.TagName.OL) { // Don't disturb lists outside of the selection. If this is the first <ul> // or <ol> in the range, we don't really want to merge the previous list // into it, since that list isn't in the range. if (!previousList) { previousList = true; return; } // The lists must be siblings to be merged; otherwise, indented sublists // could be broken. var previousElementSibling = goog.dom.getPreviousElementSibling(node); if (!previousElementSibling) { return; } // Make sure there isn't text between the two lists before they are merged var range = node.ownerDocument.createRange(); range.setStartAfter(previousElementSibling); range.setEndBefore(node); if (!goog.string.isEmpty(range.toString())) { return; } // Make sure both are lists of the same type (ordered or unordered) if (previousElementSibling.nodeName == node.nodeName) { // We must merge the previous list into this one. Moving around // the current node will break the iterator, so we can't merge // this list into the previous one. while (previousElementSibling.lastChild) { node.insertBefore(previousElementSibling.lastChild, node.firstChild); } previousElementSibling.parentNode.removeChild(previousElementSibling); } } }); }; /** * Sane "type" attribute values for OL elements * @private */ goog.editor.plugins.BasicTextFormatter.orderedListTypes_ = { '1' : 1, 'a' : 1, 'A' : 1, 'i' : 1, 'I' : 1 }; /** * Sane "type" attribute values for UL elements * @private */ goog.editor.plugins.BasicTextFormatter.unorderedListTypes_ = { 'disc' : 1, 'circle' : 1, 'square' : 1 }; /** * Changing an OL to a UL (or the other way around) will fail if the list * has a type attribute (such as "UL type=disc" becoming "OL type=disc", which * is visually identical). Most browsers will remove the type attribute * automatically, but IE doesn't. This does it manually. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.fixIELists_ = function() { // Find the lowest-level <ul> or <ol> that contains the entire range. var range = this.getRange_(); var container = range && range.getContainer(); while (container && container.tagName != goog.dom.TagName.UL && container.tagName != goog.dom.TagName.OL) { container = container.parentNode; } if (container) { // We want the parent node of the list so that we can grab it using // getElementsByTagName container = container.parentNode; } if (!container) return; var lists = goog.array.toArray( container.getElementsByTagName(goog.dom.TagName.UL)); goog.array.extend(lists, goog.array.toArray( container.getElementsByTagName(goog.dom.TagName.OL))); // Fix the lists goog.array.forEach(lists, function(node) { var type = node.type; if (type) { var saneTypes = (node.tagName == goog.dom.TagName.UL ? goog.editor.plugins.BasicTextFormatter.unorderedListTypes_ : goog.editor.plugins.BasicTextFormatter.orderedListTypes_); if (!saneTypes[type]) { node.type = ''; } } }); }; /** * In WebKit, the following commands will modify the node with * contentEditable=true if there are no block-level elements. * @private */ goog.editor.plugins.BasicTextFormatter.brokenExecCommandsSafari_ = { 'justifyCenter' : 1, 'justifyFull' : 1, 'justifyRight': 1, 'justifyLeft': 1, 'formatBlock' : 1 }; /** * In WebKit, the following commands can hang the browser if the selection * touches the beginning of the field. * https://bugs.webkit.org/show_bug.cgi?id=19735 * @private */ goog.editor.plugins.BasicTextFormatter.hangingExecCommandWebkit_ = { 'insertOrderedList': 1, 'insertUnorderedList': 1 }; /** * Apply pre-execCommand fixes for Safari. * @param {string} command The command to execute. * @return {Element|undefined} The div added to the field. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.applyExecCommandSafariFixes_ = function(command) { // See the comment on brokenExecCommandsSafari_ var div; if (goog.editor.plugins.BasicTextFormatter. brokenExecCommandsSafari_[command]) { // Add a new div at the end of the field. // Safari knows that it would be wrong to apply text-align to the // contentEditable element if there are non-empty block nodes in the field, // because then it would align them too. So in this case, it will // enclose the current selection in a block node. div = this.getFieldDomHelper().createDom( 'div', {'style': 'height: 0'}, 'x'); goog.dom.appendChild(this.getFieldObject().getElement(), div); } if (goog.editor.plugins.BasicTextFormatter. hangingExecCommandWebkit_[command]) { // Add a new div at the beginning of the field. var field = this.getFieldObject().getElement(); div = this.getFieldDomHelper().createDom( 'div', {'style': 'height: 0'}, 'x'); field.insertBefore(div, field.firstChild); } return div; }; /** * Apply pre-execCommand fixes for Gecko. * @param {string} command The command to execute. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.applyExecCommandGeckoFixes_ = function(command) { if (goog.userAgent.isVersion('1.9') && command.toLowerCase() == 'formatblock') { // Firefox 3 and above throw a JS error for formatblock if the range is // a child of the body node. Changing the selection to the BR fixes the // problem. // See https://bugzilla.mozilla.org/show_bug.cgi?id=481696 var range = this.getRange_(); var startNode = range.getStartNode(); if (range.isCollapsed() && startNode && startNode.tagName == goog.dom.TagName.BODY) { var startOffset = range.getStartOffset(); var childNode = startNode.childNodes[startOffset]; if (childNode && childNode.tagName == goog.dom.TagName.BR) { // Change the range using getBrowserRange() because goog.dom.TextRange // will avoid setting <br>s directly. // @see goog.dom.TextRange#createFromNodes var browserRange = range.getBrowserRangeObject(); browserRange.setStart(childNode, 0); browserRange.setEnd(childNode, 0); } } } }; /** * Workaround for Opera bug CORE-23903. Opera sometimes fails to invalidate * serialized CSS or innerHTML for the DOM after certain execCommands when * styleWithCSS is on. Toggling an inline style on the elements fixes it. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.invalidateInlineCss_ = function() { var ancestors = []; var ancestor = this.getFieldObject().getRange().getContainerElement(); do { ancestors.push(ancestor); } while (ancestor = ancestor.parentNode); var nodesInSelection = goog.iter.chain( goog.iter.toIterator(this.getFieldObject().getRange()), goog.iter.toIterator(ancestors)); var containersInSelection = goog.iter.filter(nodesInSelection, goog.editor.style.isContainer); goog.iter.forEach(containersInSelection, function(element) { var oldOutline = element.style.outline; element.style.outline = '0px solid red'; element.style.outline = oldOutline; }); }; /** * Work around a Gecko bug that causes inserted lists to forget the current * font. This affects WebKit in the same way and Opera in a slightly different * way, but this workaround only works in Gecko. * WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=19653 * Mozilla bug: https://bugzilla.mozilla.org/show_bug.cgi?id=439966 * Opera bug: https://bugs.opera.com/show_bug.cgi?id=340392 * TODO: work around this issue in WebKit and Opera as well. * @return {boolean} Whether the workaround was applied. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.beforeInsertListGecko_ = function() { var tag = this.getFieldObject().queryCommandValue( goog.editor.Command.DEFAULT_TAG); if (tag == goog.dom.TagName.P || tag == goog.dom.TagName.DIV) { return false; } // Prevent Firefox from forgetting current formatting // when creating a list. // The bug happens with a collapsed selection, but it won't // happen when text with the desired formatting is selected. // So, we insert some dummy text, insert the list, // then remove the dummy text (while preserving its formatting). // (This formatting bug also affects WebKit, but this fix // only seems to work in Firefox) var range = this.getRange_(); if (range.isCollapsed() && (range.getContainer().nodeType != goog.dom.NodeType.TEXT)) { var tempTextNode = this.getFieldDomHelper(). createTextNode(goog.string.Unicode.NBSP); range.insertNode(tempTextNode, false); goog.dom.Range.createFromNodeContents(tempTextNode).select(); return true; } return false; }; // Helpers for queryCommandState /** * Get the toolbar state for the block-level elements in the given range. * @param {goog.dom.AbstractRange} range The range to get toolbar state for. * @return {string?} The selection block state. * @private */ goog.editor.plugins.BasicTextFormatter.getSelectionBlockState_ = function(range) { var tagName = null; goog.iter.forEach(range, function(node, ignore, it) { if (!it.isEndTag()) { // Iterate over all containers in the range, checking if they all have the // same tagName. var container = goog.editor.style.getContainer(node); var thisTagName = container.tagName; tagName = tagName || thisTagName; if (tagName != thisTagName) { // If we find a container tag that doesn't match, exit right away. tagName = null; throw goog.iter.StopIteration; } // Skip the tag. it.skipTag(); } }); return tagName; }; /** * Hash of suppoted justifications. * @type {Object} * @private */ goog.editor.plugins.BasicTextFormatter.SUPPORTED_JUSTIFICATIONS_ = { 'center': 1, 'justify': 1, 'right': 1, 'left': 1 }; /** * Returns true if the current justification matches the justification * command for the entire selection. * @param {string} command The justification command to check for. * @return {boolean} Whether the current justification matches the justification * command for the entire selection. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.isJustification_ = function(command) { var alignment = command.replace('+justify', '').toLowerCase(); if (alignment == 'full') { alignment = 'justify'; } var bidiPlugin = this.getFieldObject().getPluginByClassId('Bidi'); if (bidiPlugin) { // BiDi aware version // TODO: Since getComputedStyle is not used here, this version may be even // faster. If profiling confirms that it would be good to use this approach // in both cases. Otherwise the bidi part should be moved into an // execCommand so this bidi plugin dependence isn't needed here. /** @type {Function} */ bidiPlugin.getSelectionAlignment; return alignment == bidiPlugin.getSelectionAlignment(); } else { // BiDi unaware version var range = this.getRange_(); if (!range) { // When nothing is in the selection then no justification // command matches. return false; } var parent = range.getContainerElement(); var nodes = goog.array.filter( parent.childNodes, function(node) { return goog.editor.node.isImportant(node) && range.containsNode(node, true); }); nodes = nodes.length ? nodes : [parent]; for (var i = 0; i < nodes.length; i++) { var current = nodes[i]; // If any node in the selection is not aligned the way we are checking, // then the justification command does not match. var container = goog.editor.style.getContainer( /** @type {Node} */ (current)); if (alignment != goog.editor.plugins.BasicTextFormatter.getNodeJustification_( container)) { return false; } } // If all nodes in the selection are aligned the way we are checking, // the justification command does match. return true; } }; /** * Determines the justification for a given block-level element. * @param {Element} element The node to get justification for. * @return {string} The justification for a given block-level node. * @private */ goog.editor.plugins.BasicTextFormatter.getNodeJustification_ = function(element) { var value = goog.style.getComputedTextAlign(element); // Strip preceding -moz- or -webkit- (@bug 2472589). value = value.replace(/^-(moz|webkit)-/, ''); // If there is no alignment, try the inline property, // otherwise assume left aligned. // TODO: for rtl languages we probably need to assume right. if (!goog.editor.plugins.BasicTextFormatter. SUPPORTED_JUSTIFICATIONS_[value]) { value = element.align || 'left'; } return /** @type {string} */ (value); }; /** * Returns true if a selection contained in the node should set the appropriate * toolbar state for the given nodeName, e.g. if the node is contained in a * strong element and nodeName is "strong", then it will return true. * @param {string} nodeName The type of node to check for. * @return {boolean} Whether the user's selection is in the given state. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.isNodeInState_ = function(nodeName) { var range = this.getRange_(); var node = range && range.getContainerElement(); var ancestor = goog.dom.getAncestorByTagNameAndClass(node, nodeName); return !!ancestor && goog.editor.node.isEditable(ancestor); }; /** * Wrapper for browser's queryCommandState. * @param {Document|TextRange|Range} queryObject The object to query. * @param {string} command The command to check. * @param {boolean=} opt_styleWithCss Set to true to enable styleWithCSS before * performing the queryCommandState. * @return {boolean} The command state. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.queryCommandStateInternal_ = function(queryObject, command, opt_styleWithCss) { return /** @type {boolean} */ (this.queryCommandHelper_(true, queryObject, command, opt_styleWithCss)); }; /** * Wrapper for browser's queryCommandValue. * @param {Document|TextRange|Range} queryObject The object to query. * @param {string} command The command to check. * @param {boolean=} opt_styleWithCss Set to true to enable styleWithCSS before * performing the queryCommandValue. * @return {string|boolean|null} The command value. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.queryCommandValueInternal_ = function(queryObject, command, opt_styleWithCss) { return this.queryCommandHelper_(false, queryObject, command, opt_styleWithCss); }; /** * Helper function to perform queryCommand(Value|State). * @param {boolean} isGetQueryCommandState True to use queryCommandState, false * to use queryCommandValue. * @param {Document|TextRange|Range} queryObject The object to query. * @param {string} command The command to check. * @param {boolean=} opt_styleWithCss Set to true to enable styleWithCSS before * performing the queryCommand(Value|State). * @return {string|boolean|null} The command value. * @private */ goog.editor.plugins.BasicTextFormatter.prototype.queryCommandHelper_ = function( isGetQueryCommandState, queryObject, command, opt_styleWithCss) { command = goog.editor.plugins.BasicTextFormatter.convertToRealExecCommand_( command); if (opt_styleWithCss) { var doc = this.getDocument_(); // Don't use this.execCommandHelper_ here, as it is more heavyweight // and inserts a dummy div to protect against comamnds that could step // outside the editable region, which would cause change event on // every toolbar update. doc.execCommand('styleWithCSS', false, true); } var ret = isGetQueryCommandState ? queryObject.queryCommandState(command) : queryObject.queryCommandValue(command); if (opt_styleWithCss) { doc.execCommand('styleWithCSS', false, false); } return ret; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Plugin that enables table editing. * * @see ../../demos/editor/tableeditor.html */ goog.provide('goog.editor.plugins.TableEditor'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.editor.Plugin'); goog.require('goog.editor.Table'); goog.require('goog.editor.node'); goog.require('goog.editor.range'); goog.require('goog.object'); /** * Plugin that adds support for table creation and editing commands. * @constructor * @extends {goog.editor.Plugin} */ goog.editor.plugins.TableEditor = function() { goog.base(this); /** * The array of functions that decide whether a table element could be * editable by the user or not. * @type {Array.<function(Element):boolean>} * @private */ this.isTableEditableFunctions_ = []; /** * The pre-bound function that decides whether a table element could be * editable by the user or not overall. * @type {function(Node):boolean} * @private */ this.isUserEditableTableBound_ = goog.bind(this.isUserEditableTable_, this); }; goog.inherits(goog.editor.plugins.TableEditor, goog.editor.Plugin); /** @override */ // TODO(user): remove this once there's a sensible default // implementation in the base Plugin. goog.editor.plugins.TableEditor.prototype.getTrogClassId = function() { return String(goog.getUid(this.constructor)); }; /** * Commands supported by goog.editor.plugins.TableEditor. * @enum {string} */ goog.editor.plugins.TableEditor.COMMAND = { TABLE: '+table', INSERT_ROW_AFTER: '+insertRowAfter', INSERT_ROW_BEFORE: '+insertRowBefore', INSERT_COLUMN_AFTER: '+insertColumnAfter', INSERT_COLUMN_BEFORE: '+insertColumnBefore', REMOVE_ROWS: '+removeRows', REMOVE_COLUMNS: '+removeColumns', SPLIT_CELL: '+splitCell', MERGE_CELLS: '+mergeCells', REMOVE_TABLE: '+removeTable' }; /** * Inverse map of execCommand strings to * {@link goog.editor.plugins.TableEditor.COMMAND} constants. Used to * determine whether a string corresponds to a command this plugin handles * in O(1) time. * @type {Object} * @private */ goog.editor.plugins.TableEditor.SUPPORTED_COMMANDS_ = goog.object.transpose(goog.editor.plugins.TableEditor.COMMAND); /** * Whether the string corresponds to a command this plugin handles. * @param {string} command Command string to check. * @return {boolean} Whether the string corresponds to a command * this plugin handles. * @override */ goog.editor.plugins.TableEditor.prototype.isSupportedCommand = function(command) { return command in goog.editor.plugins.TableEditor.SUPPORTED_COMMANDS_; }; /** @override */ goog.editor.plugins.TableEditor.prototype.enable = function(fieldObject) { goog.base(this, 'enable', fieldObject); // enableObjectResizing is supported only for Gecko. // You can refer to http://qooxdoo.org/contrib/project/htmlarea/html_editing // for a compatibility chart. if (goog.userAgent.GECKO) { var doc = this.getFieldDomHelper().getDocument(); doc.execCommand('enableObjectResizing', false, 'true'); } }; /** * Returns the currently selected table. * @return {Element?} The table in which the current selection is * contained, or null if there isn't such a table. * @private */ goog.editor.plugins.TableEditor.prototype.getCurrentTable_ = function() { var selectedElement = this.getFieldObject().getRange().getContainer(); return this.getAncestorTable_(selectedElement); }; /** * Finds the first user-editable table element in the input node's ancestors. * @param {Node?} node The node to start with. * @return {Element?} The table element that is closest ancestor of the node. * @private */ goog.editor.plugins.TableEditor.prototype.getAncestorTable_ = function(node) { var ancestor = goog.dom.getAncestor(node, this.isUserEditableTableBound_, true); if (goog.editor.node.isEditable(ancestor)) { return /** @type {Element?} */(ancestor); } else { return null; } }; /** * Returns the current value of a given command. Currently this plugin * only returns a value for goog.editor.plugins.TableEditor.COMMAND.TABLE. * @override */ goog.editor.plugins.TableEditor.prototype.queryCommandValue = function(command) { if (command == goog.editor.plugins.TableEditor.COMMAND.TABLE) { return !!this.getCurrentTable_(); } }; /** @override */ goog.editor.plugins.TableEditor.prototype.execCommandInternal = function( command, opt_arg) { var result = null; // TD/TH in which to place the cursor, if the command destroys the current // cursor position. var cursorCell = null; var range = this.getFieldObject().getRange(); if (command == goog.editor.plugins.TableEditor.COMMAND.TABLE) { // Don't create a table if the cursor isn't in an editable region. if (!goog.editor.range.isEditable(range)) { return null; } // Create the table. var tableProps = opt_arg || {width: 4, height: 2}; var doc = this.getFieldDomHelper().getDocument(); var table = goog.editor.Table.createDomTable( doc, tableProps.width, tableProps.height); range.replaceContentsWithNode(table); // In IE, replaceContentsWithNode uses pasteHTML, so we lose our reference // to the inserted table. // TODO(user): use the reference to the table element returned from // replaceContentsWithNode. if (!goog.userAgent.IE) { cursorCell = table.getElementsByTagName('td')[0]; } } else { var cellSelection = new goog.editor.plugins.TableEditor.CellSelection_( range, goog.bind(this.getAncestorTable_, this)); var table = cellSelection.getTable(); if (!table) { return null; } switch (command) { case goog.editor.plugins.TableEditor.COMMAND.INSERT_ROW_BEFORE: table.insertRow(cellSelection.getFirstRowIndex()); break; case goog.editor.plugins.TableEditor.COMMAND.INSERT_ROW_AFTER: table.insertRow(cellSelection.getLastRowIndex() + 1); break; case goog.editor.plugins.TableEditor.COMMAND.INSERT_COLUMN_BEFORE: table.insertColumn(cellSelection.getFirstColumnIndex()); break; case goog.editor.plugins.TableEditor.COMMAND.INSERT_COLUMN_AFTER: table.insertColumn(cellSelection.getLastColumnIndex() + 1); break; case goog.editor.plugins.TableEditor.COMMAND.REMOVE_ROWS: var startRow = cellSelection.getFirstRowIndex(); var endRow = cellSelection.getLastRowIndex(); if (startRow == 0 && endRow == (table.rows.length - 1)) { // Instead of deleting all rows, delete the entire table. return this.execCommandInternal( goog.editor.plugins.TableEditor.COMMAND.REMOVE_TABLE); } var startColumn = cellSelection.getFirstColumnIndex(); var rowCount = (endRow - startRow) + 1; for (var i = 0; i < rowCount; i++) { table.removeRow(startRow); } if (table.rows.length > 0) { // Place cursor in the previous/first row. var closestRow = Math.min(startRow, table.rows.length - 1); cursorCell = table.rows[closestRow].columns[startColumn].element; } break; case goog.editor.plugins.TableEditor.COMMAND.REMOVE_COLUMNS: var startCol = cellSelection.getFirstColumnIndex(); var endCol = cellSelection.getLastColumnIndex(); if (startCol == 0 && endCol == (table.rows[0].columns.length - 1)) { // Instead of deleting all columns, delete the entire table. return this.execCommandInternal( goog.editor.plugins.TableEditor.COMMAND.REMOVE_TABLE); } var startRow = cellSelection.getFirstRowIndex(); var removeCount = (endCol - startCol) + 1; for (var i = 0; i < removeCount; i++) { table.removeColumn(startCol); } var currentRow = table.rows[startRow]; if (currentRow) { // Place cursor in the previous/first column. var closestCol = Math.min(startCol, currentRow.columns.length - 1); cursorCell = currentRow.columns[closestCol].element; } break; case goog.editor.plugins.TableEditor.COMMAND.MERGE_CELLS: if (cellSelection.isRectangle()) { table.mergeCells(cellSelection.getFirstRowIndex(), cellSelection.getFirstColumnIndex(), cellSelection.getLastRowIndex(), cellSelection.getLastColumnIndex()); } break; case goog.editor.plugins.TableEditor.COMMAND.SPLIT_CELL: if (cellSelection.containsSingleCell()) { table.splitCell(cellSelection.getFirstRowIndex(), cellSelection.getFirstColumnIndex()); } break; case goog.editor.plugins.TableEditor.COMMAND.REMOVE_TABLE: table.element.parentNode.removeChild(table.element); break; default: } } if (cursorCell) { range = goog.dom.Range.createFromNodeContents(cursorCell); range.collapse(false); range.select(); } return result; }; /** * Checks whether the element is a table editable by the user. * @param {Node} element The element in question. * @return {boolean} Whether the element is a table editable by the user. * @private */ goog.editor.plugins.TableEditor.prototype.isUserEditableTable_ = function(element) { // Default implementation. if (element.tagName != goog.dom.TagName.TABLE) { return false; } // Check for extra user-editable filters. return goog.array.every(this.isTableEditableFunctions_, function(func) { return func(/** @type {Element} */ (element)); }); }; /** * Adds a function to filter out non-user-editable tables. * @param {function(Element):boolean} func A function to decide whether the * table element could be editable by the user or not. */ goog.editor.plugins.TableEditor.prototype.addIsTableEditableFunction = function(func) { goog.array.insert(this.isTableEditableFunctions_, func); }; /** * Class representing the selected cell objects within a single table. * @param {goog.dom.AbstractRange} range Selected range from which to calculate * selected cells. * @param {function(Element):Element?} getParentTableFunction A function that * finds the user-editable table from a given element. * @constructor * @private */ goog.editor.plugins.TableEditor.CellSelection_ = function(range, getParentTableFunction) { this.cells_ = []; // Mozilla lets users select groups of cells, with each cell showing // up as a separate range in the selection. goog.dom.Range doesn't // currently support this. // TODO(user): support this case in range.js var selectionContainer = range.getContainerElement(); var elementInSelection = function(node) { // TODO(user): revert to the more liberal containsNode(node, true), // which will match partially-selected cells. We're using // containsNode(node, false) at the moment because otherwise it's // broken in WebKit due to a closure range bug. return selectionContainer == node || selectionContainer.parentNode == node || range.containsNode(node, false); }; var parentTableElement = selectionContainer && getParentTableFunction(selectionContainer); if (!parentTableElement) { return; } var parentTable = new goog.editor.Table(parentTableElement); // It's probably not possible to select a table with no cells, but // do a sanity check anyway. if (!parentTable.rows.length || !parentTable.rows[0].columns.length) { return; } // Loop through cells to calculate dimensions for this CellSelection. for (var i = 0, row; row = parentTable.rows[i]; i++) { for (var j = 0, cell; cell = row.columns[j]; j++) { if (elementInSelection(cell.element)) { // Update dimensions based on cell. if (!this.cells_.length) { this.firstRowIndex_ = cell.startRow; this.lastRowIndex_ = cell.endRow; this.firstColIndex_ = cell.startCol; this.lastColIndex_ = cell.endCol; } else { this.firstRowIndex_ = Math.min(this.firstRowIndex_, cell.startRow); this.lastRowIndex_ = Math.max(this.lastRowIndex_, cell.endRow); this.firstColIndex_ = Math.min(this.firstColIndex_, cell.startCol); this.lastColIndex_ = Math.max(this.lastColIndex_, cell.endCol); } this.cells_.push(cell); } } } this.parentTable_ = parentTable; }; /** * Returns the EditableTable object of which this selection's cells are a * subset. * @return {goog.editor.Table?} the table. */ goog.editor.plugins.TableEditor.CellSelection_.prototype.getTable = function() { return this.parentTable_; }; /** * Returns the row index of the uppermost cell in this selection. * @return {number} The row index. */ goog.editor.plugins.TableEditor.CellSelection_.prototype.getFirstRowIndex = function() { return this.firstRowIndex_; }; /** * Returns the row index of the lowermost cell in this selection. * @return {number} The row index. */ goog.editor.plugins.TableEditor.CellSelection_.prototype.getLastRowIndex = function() { return this.lastRowIndex_; }; /** * Returns the column index of the farthest left cell in this selection. * @return {number} The column index. */ goog.editor.plugins.TableEditor.CellSelection_.prototype.getFirstColumnIndex = function() { return this.firstColIndex_; }; /** * Returns the column index of the farthest right cell in this selection. * @return {number} The column index. */ goog.editor.plugins.TableEditor.CellSelection_.prototype.getLastColumnIndex = function() { return this.lastColIndex_; }; /** * Returns the cells in this selection. * @return {Array.<Element>} Cells in this selection. */ goog.editor.plugins.TableEditor.CellSelection_.prototype.getCells = function() { return this.cells_; }; /** * Returns a boolean value indicating whether or not the cells in this * selection form a rectangle. * @return {boolean} Whether the selection forms a rectangle. */ goog.editor.plugins.TableEditor.CellSelection_.prototype.isRectangle = function() { // TODO(user): check for missing cells. Right now this returns // whether all cells in the selection are in the rectangle, but doesn't // verify that every expected cell is present. if (!this.cells_.length) { return false; } var firstCell = this.cells_[0]; var lastCell = this.cells_[this.cells_.length - 1]; return !(this.firstRowIndex_ < firstCell.startRow || this.lastRowIndex_ > lastCell.endRow || this.firstColIndex_ < firstCell.startCol || this.lastColIndex_ > lastCell.endCol); }; /** * Returns a boolean value indicating whether or not there is exactly * one cell in this selection. Note that this may not be the same as checking * whether getCells().length == 1; if there is a single cell with * rowSpan/colSpan set it will appear multiple times. * @return {boolean} Whether there is exatly one cell in this selection. */ goog.editor.plugins.TableEditor.CellSelection_.prototype.containsSingleCell = function() { var cellCount = this.cells_.length; return cellCount > 0 && (this.cells_[0] == this.cells_[cellCount - 1]); };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A plugin to enable the First Strong Bidi algorithm. The First * Strong algorithm as a heuristic used to automatically set paragraph direction * depending on its content. * * In the documentation below, a 'paragraph' is the local element which we * evaluate as a whole for purposes of determining directionality. It may be a * block-level element (e.g. &lt;div&gt;) or a whole list (e.g. &lt;ul&gt;). * * This implementation is based on, but is not identical to, the original * First Strong algorithm defined in Unicode * @see http://www.unicode.org/reports/tr9/ * The central difference from the original First Strong algorithm is that this * implementation decides the paragraph direction based on the first strong * character that is <em>typed</em> into the paragraph, regardless of its * location in the paragraph, as opposed to the original algorithm where it is * the first character in the paragraph <em>by location</em>, regardless of * whether other strong characters already appear in the paragraph, further its * start. * * <em>Please note</em> that this plugin does not perform the direction change * itself. Rather, it fires editor commands upon the key up event when a * direction change needs to be performed; {@code goog.editor.Command.DIR_RTL} * or {@code goog.editor.Command.DIR_RTL}. * */ goog.provide('goog.editor.plugins.FirstStrong'); goog.require('goog.dom'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.TagIterator'); goog.require('goog.dom.TagName'); goog.require('goog.editor.Command'); goog.require('goog.editor.Plugin'); goog.require('goog.editor.node'); goog.require('goog.editor.range'); goog.require('goog.i18n.bidi'); goog.require('goog.i18n.uChar'); goog.require('goog.iter'); goog.require('goog.userAgent'); /** * First Strong plugin. * @constructor * @extends {goog.editor.Plugin} */ goog.editor.plugins.FirstStrong = function() { goog.base(this); /** * Indicates whether or not the cursor is in a paragraph we have not yet * finished evaluating for directionality. This is set to true whenever the * cursor is moved, and set to false after seeing a strong character in the * paragraph the cursor is currently in. * * @type {boolean} * @private */ this.isNewBlock_ = true; /** * Indicates whether or not the current paragraph the cursor is in should be * set to Right-To-Left directionality. * * @type {boolean} * @private */ this.switchToRtl_ = false; /** * Indicates whether or not the current paragraph the cursor is in should be * set to Left-To-Right directionality. * * @type {boolean} * @private */ this.switchToLtr_ = false; }; goog.inherits(goog.editor.plugins.FirstStrong, goog.editor.Plugin); /** @override */ goog.editor.plugins.FirstStrong.prototype.getTrogClassId = function() { return 'FirstStrong'; }; /** @override */ goog.editor.plugins.FirstStrong.prototype.queryCommandValue = function(command) { return false; }; /** @override */ goog.editor.plugins.FirstStrong.prototype.handleSelectionChange = function(e, node) { this.isNewBlock_ = true; return false; }; /** * The name of the attribute which records the input text. * * @type {string} * @const */ goog.editor.plugins.FirstStrong.INPUT_ATTRIBUTE = 'fs-input'; /** @override */ goog.editor.plugins.FirstStrong.prototype.handleKeyPress = function(e) { if (!this.isNewBlock_) { return false; // We've already determined this paragraph's direction. } // Ignore non-character key press events. if (e.ctrlKey || e.metaKey) { return false; } var newInput = goog.i18n.uChar.fromCharCode(e.charCode); if (!newInput) { var browserEvent = e.getBrowserEvent(); if (browserEvent) { if (goog.userAgent.IE && browserEvent['getAttribute']) { newInput = browserEvent['getAttribute']( goog.editor.plugins.FirstStrong.INPUT_ATTRIBUTE); } else { newInput = browserEvent[ goog.editor.plugins.FirstStrong.INPUT_ATTRIBUTE]; } } } if (!newInput) { return false; // Unrecognized key. } var isLtr = goog.i18n.bidi.isLtrChar(newInput); var isRtl = !isLtr && goog.i18n.bidi.isRtlChar(newInput); if (!isLtr && !isRtl) { return false; // This character cannot change anything (it is not Strong). } // This character is Strongly LTR or Strongly RTL. We might switch direction // on it now, but in any case we do not need to check any more characters in // this paragraph after it. this.isNewBlock_ = false; // Are there no Strong characters already in the paragraph? if (this.isNeutralBlock_()) { this.switchToRtl_ = isRtl; this.switchToLtr_ = isLtr; } return false; }; /** * Calls the flip directionality commands. This is done here so things go into * the redo-undo stack at the expected order; fist enter the input, then flip * directionality. * @override */ goog.editor.plugins.FirstStrong.prototype.handleKeyUp = function(e) { if (this.switchToRtl_) { var field = this.getFieldObject(); field.dispatchChange(true); field.execCommand(goog.editor.Command.DIR_RTL); this.switchToRtl_ = false; } else if (this.switchToLtr_) { var field = this.getFieldObject(); field.dispatchChange(true); field.execCommand(goog.editor.Command.DIR_LTR); this.switchToLtr_ = false; } return false; }; /** * @return {Element} The lowest Block element ancestor of the node where the * next character will be placed. * @private */ goog.editor.plugins.FirstStrong.prototype.getBlockAncestor_ = function() { var start = this.getFieldObject().getRange().getStartNode(); // Go up in the DOM until we reach a Block element. while (!goog.editor.plugins.FirstStrong.isBlock_(start)) { start = start.parentNode; } return /** @type {Element} */ (start); }; /** * @return {boolean} Whether the paragraph where the next character will be * entered contains only non-Strong characters. * @private */ goog.editor.plugins.FirstStrong.prototype.isNeutralBlock_ = function() { var root = this.getBlockAncestor_(); // The exact node with the cursor location. Simply calling getStartNode() on // the range only returns the containing block node. var cursor = goog.editor.range.getDeepEndPoint( this.getFieldObject().getRange(), false).node; // In FireFox the BR tag also represents a change in paragraph if not inside a // list. So we need special handling to only look at the sub-block between // BR elements. var blockFunction = (goog.userAgent.GECKO && !this.isList_(root)) ? goog.editor.plugins.FirstStrong.isGeckoBlock_ : goog.editor.plugins.FirstStrong.isBlock_; var paragraph = this.getTextAround_(root, cursor, blockFunction); // Not using {@code goog.i18n.bidi.isNeutralText} as it contains additional, // unwanted checks to the content. return !goog.i18n.bidi.hasAnyLtr(paragraph) && !goog.i18n.bidi.hasAnyRtl(paragraph); }; /** * Checks if an element is a list element ('UL' or 'OL'). * * @param {Element} element The element to test. * @return {boolean} Whether the element is a list element ('UL' or 'OL'). * @private */ goog.editor.plugins.FirstStrong.prototype.isList_ = function(element) { if (!element) { return false; } var tagName = element.tagName; return tagName == goog.dom.TagName.UL || tagName == goog.dom.TagName.OL; }; /** * Returns the text within the local paragraph around the cursor. * Notice that for GECKO a BR represents a pargraph change despite not being a * block element. * * @param {Element} root The first block element ancestor of the node the cursor * is in. * @param {Node} cursorLocation Node where the cursor currently is, marking the * paragraph whose text we will return. * @param {function(Node): boolean} isParagraphBoundary The function to * determine if a node represents the start or end of the paragraph. * @return {string} the text in the paragraph around the cursor location. * @private */ goog.editor.plugins.FirstStrong.prototype.getTextAround_ = function(root, cursorLocation, isParagraphBoundary) { // The buffer where we're collecting the text. var buffer = []; // Have we reached the cursor yet, or are we still before it? var pastCursorLocation = false; if (root && cursorLocation) { goog.iter.some(new goog.dom.TagIterator(root), function(node) { if (node == cursorLocation) { pastCursorLocation = true; } else if (isParagraphBoundary(node)) { if (pastCursorLocation) { // This is the end of the paragraph containing the cursor. We're done. return true; } else { // All we collected so far does not count; it was in a previous // paragraph that did not contain the cursor. buffer = []; } } if (node.nodeType == goog.dom.NodeType.TEXT) { buffer.push(node.nodeValue); } return false; // Keep going. }); } return buffer.join(''); }; /** * @param {Node} node Node to check. * @return {boolean} Does the given node represent a Block element? Notice we do * not consider list items as Block elements in the algorithm. * @private */ goog.editor.plugins.FirstStrong.isBlock_ = function(node) { return !!node && goog.editor.node.isBlockTag(node) && node.tagName != goog.dom.TagName.LI; }; /** * @param {Node} node Node to check. * @return {boolean} Does the given node represent a Block element from the * point of view of FireFox? Notice we do not consider list items as Block * elements in the algorithm. * @private */ goog.editor.plugins.FirstStrong.isGeckoBlock_ = function(node) { return !!node && (node.tagName == goog.dom.TagName.BR || goog.editor.plugins.FirstStrong.isBlock_(node)); };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A plugin for the LinkDialog. * * @author nicksantos@google.com (Nick Santos) * @author marcosalmeida@google.com (Marcos Almeida) * @author robbyw@google.com (Robby Walker) */ goog.provide('goog.editor.plugins.LinkDialogPlugin'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.editor.Command'); goog.require('goog.editor.plugins.AbstractDialogPlugin'); goog.require('goog.events.EventHandler'); goog.require('goog.functions'); goog.require('goog.ui.editor.AbstractDialog.EventType'); goog.require('goog.ui.editor.LinkDialog'); goog.require('goog.ui.editor.LinkDialog.EventType'); goog.require('goog.ui.editor.LinkDialog.OkEvent'); goog.require('goog.uri.utils'); /** * A plugin that opens the link dialog. * @constructor * @extends {goog.editor.plugins.AbstractDialogPlugin} */ goog.editor.plugins.LinkDialogPlugin = function() { goog.base(this, goog.editor.Command.MODAL_LINK_EDITOR); /** * Event handler for this object. * @type {goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); /** * A list of whitelisted URL schemes which are safe to open. * @type {Array.<string>} * @private */ this.safeToOpenSchemes_ = ['http', 'https', 'ftp']; }; goog.inherits(goog.editor.plugins.LinkDialogPlugin, goog.editor.plugins.AbstractDialogPlugin); /** * Link object that the dialog is editing. * @type {goog.editor.Link} * @protected */ goog.editor.plugins.LinkDialogPlugin.prototype.currentLink_; /** * Optional warning to show about email addresses. * @type {string|undefined} * @private */ goog.editor.plugins.LinkDialogPlugin.prototype.emailWarning_; /** * Whether to show a checkbox where the user can choose to have the link open in * a new window. * @type {boolean} * @private */ goog.editor.plugins.LinkDialogPlugin.prototype.showOpenLinkInNewWindow_ = false; /** * Whether the "open link in new window" checkbox should be checked when the * dialog is shown, and also whether it was checked last time the dialog was * closed. * @type {boolean} * @private */ goog.editor.plugins.LinkDialogPlugin.prototype.isOpenLinkInNewWindowChecked_ = false; /** * Weather to show a checkbox where the user can choose to add 'rel=nofollow' * attribute added to the link. * @type {boolean} * @private */ goog.editor.plugins.LinkDialogPlugin.prototype.showRelNoFollow_ = false; /** * Whether to stop referrer leaks. Defaults to false. * @type {boolean} * @private */ goog.editor.plugins.LinkDialogPlugin.prototype.stopReferrerLeaks_ = false; /** * Whether to block opening links with a non-whitelisted URL scheme. * @type {boolean} * @private */ goog.editor.plugins.LinkDialogPlugin.prototype.blockOpeningUnsafeSchemes_ = true; /** @override */ goog.editor.plugins.LinkDialogPlugin.prototype.getTrogClassId = goog.functions.constant('LinkDialogPlugin'); /** * Tells the plugin whether to block URLs with schemes not in the whitelist. * If blocking is enabled, this plugin will stop the 'Test Link' popup * window from being created. Blocking doesn't affect link creation--if the * user clicks the 'OK' button with an unsafe URL, the link will still be * created as normal. * @param {boolean} blockOpeningUnsafeSchemes Whether to block non-whitelisted * schemes. */ goog.editor.plugins.LinkDialogPlugin.prototype.setBlockOpeningUnsafeSchemes = function(blockOpeningUnsafeSchemes) { this.blockOpeningUnsafeSchemes_ = blockOpeningUnsafeSchemes; }; /** * Sets a whitelist of allowed URL schemes that are safe to open. * Schemes should all be in lowercase. If the plugin is set to block opening * unsafe schemes, user-entered URLs will be converted to lowercase and checked * against this list. The whitelist has no effect if blocking is not enabled. * @param {Array.<string>} schemes String array of URL schemes to allow (http, * https, etc.). */ goog.editor.plugins.LinkDialogPlugin.prototype.setSafeToOpenSchemes = function(schemes) { this.safeToOpenSchemes_ = schemes; }; /** * Tells the dialog to show a checkbox where the user can choose to have the * link open in a new window. * @param {boolean} startChecked Whether to check the checkbox the first * time the dialog is shown. Subesquent times the checkbox will remember its * previous state. */ goog.editor.plugins.LinkDialogPlugin.prototype.showOpenLinkInNewWindow = function(startChecked) { this.showOpenLinkInNewWindow_ = true; this.isOpenLinkInNewWindowChecked_ = startChecked; }; /** * Tells the dialog to show a checkbox where the user can choose to have * 'rel=nofollow' attribute added to the link. */ goog.editor.plugins.LinkDialogPlugin.prototype.showRelNoFollow = function() { this.showRelNoFollow_ = true; }; /** * Returns whether the"open link in new window" checkbox was checked last time * the dialog was closed. * @return {boolean} Whether the"open link in new window" checkbox was checked * last time the dialog was closed. */ goog.editor.plugins.LinkDialogPlugin.prototype. getOpenLinkInNewWindowCheckedState = function() { return this.isOpenLinkInNewWindowChecked_; }; /** * Tells the plugin to stop leaking the page's url via the referrer header when * the "test this link" link is clicked. When the user clicks on a link, the * browser makes a request for the link url, passing the url of the current page * in the request headers. If the user wants the current url to be kept secret * (e.g. an unpublished document), the owner of the url that was clicked will * see the secret url in the request headers, and it will no longer be a secret. * Calling this method will not send a referrer header in the request, just as * if the user had opened a blank window and typed the url in themselves. */ goog.editor.plugins.LinkDialogPlugin.prototype.stopReferrerLeaks = function() { this.stopReferrerLeaks_ = true; }; /** * Sets the warning message to show to users about including email addresses on * public web pages. * @param {string} emailWarning Warning message to show users about including * email addresses on the web. */ goog.editor.plugins.LinkDialogPlugin.prototype.setEmailWarning = function( emailWarning) { this.emailWarning_ = emailWarning; }; /** * Handles execCommand by opening the dialog. * @param {string} command The command to execute. * @param {*=} opt_arg {@link A goog.editor.Link} object representing the link * being edited. * @return {*} Always returns true, indicating the dialog was shown. * @protected * @override */ goog.editor.plugins.LinkDialogPlugin.prototype.execCommandInternal = function( command, opt_arg) { this.currentLink_ = /** @type {goog.editor.Link} */(opt_arg); return goog.base(this, 'execCommandInternal', command, opt_arg); }; /** * Handles when the dialog closes. * @param {goog.events.Event} e The AFTER_HIDE event object. * @override * @protected */ goog.editor.plugins.LinkDialogPlugin.prototype.handleAfterHide = function(e) { goog.base(this, 'handleAfterHide', e); this.currentLink_ = null; }; /** * @return {goog.events.EventHandler} The event handler. * @protected */ goog.editor.plugins.LinkDialogPlugin.prototype.getEventHandler = function() { return this.eventHandler_; }; /** * @return {goog.editor.Link} The link being edited. * @protected */ goog.editor.plugins.LinkDialogPlugin.prototype.getCurrentLink = function() { return this.currentLink_; }; /** * Creates a new instance of the dialog and registers for the relevant events. * @param {goog.dom.DomHelper} dialogDomHelper The dom helper to be used to * create the dialog. * @param {*=} opt_link The target link (should be a goog.editor.Link). * @return {goog.ui.editor.LinkDialog} The dialog. * @override * @protected */ goog.editor.plugins.LinkDialogPlugin.prototype.createDialog = function( dialogDomHelper, opt_link) { var dialog = new goog.ui.editor.LinkDialog(dialogDomHelper, /** @type {goog.editor.Link} */ (opt_link)); if (this.emailWarning_) { dialog.setEmailWarning(this.emailWarning_); } if (this.showOpenLinkInNewWindow_) { dialog.showOpenLinkInNewWindow(this.isOpenLinkInNewWindowChecked_); } if (this.showRelNoFollow_) { dialog.showRelNoFollow(); } dialog.setStopReferrerLeaks(this.stopReferrerLeaks_); this.eventHandler_. listen(dialog, goog.ui.editor.AbstractDialog.EventType.OK, this.handleOk). listen(dialog, goog.ui.editor.AbstractDialog.EventType.CANCEL, this.handleCancel_). listen(dialog, goog.ui.editor.LinkDialog.EventType.BEFORE_TEST_LINK, this.handleBeforeTestLink); return dialog; }; /** @override */ goog.editor.plugins.LinkDialogPlugin.prototype.disposeInternal = function() { goog.base(this, 'disposeInternal'); this.eventHandler_.dispose(); }; /** * Handles the OK event from the dialog by updating the link in the field. * @param {goog.ui.editor.LinkDialog.OkEvent} e OK event object. * @protected */ goog.editor.plugins.LinkDialogPlugin.prototype.handleOk = function(e) { // We're not restoring the original selection, so clear it out. this.disposeOriginalSelection(); this.currentLink_.setTextAndUrl(e.linkText, e.linkUrl); if (this.showOpenLinkInNewWindow_) { // Save checkbox state for next time. this.isOpenLinkInNewWindowChecked_ = e.openInNewWindow; } var anchor = this.currentLink_.getAnchor(); this.touchUpAnchorOnOk_(anchor, e); var extraAnchors = this.currentLink_.getExtraAnchors(); for (var i = 0; i < extraAnchors.length; ++i) { extraAnchors[i].href = anchor.href; this.touchUpAnchorOnOk_(extraAnchors[i], e); } // Place cursor to the right of the modified link. this.currentLink_.placeCursorRightOf(); this.getFieldObject().focus(); this.getFieldObject().dispatchSelectionChangeEvent(); this.getFieldObject().dispatchChange(); this.eventHandler_.removeAll(); }; /** * Apply the necessary properties to a link upon Ok being clicked in the dialog. * @param {HTMLAnchorElement} anchor The anchor to set properties on. * @param {goog.events.Event} e Event object. * @private */ goog.editor.plugins.LinkDialogPlugin.prototype.touchUpAnchorOnOk_ = function(anchor, e) { if (this.showOpenLinkInNewWindow_) { if (e.openInNewWindow) { anchor.target = '_blank'; } else { if (anchor.target == '_blank') { anchor.target = ''; } // If user didn't indicate to open in a new window but the link already // had a target other than '_blank', let's leave what they had before. } } if (this.showRelNoFollow_) { var alreadyPresent = goog.ui.editor.LinkDialog.hasNoFollow(anchor.rel); if (alreadyPresent && !e.noFollow) { anchor.rel = goog.ui.editor.LinkDialog.removeNoFollow(anchor.rel); } else if (!alreadyPresent && e.noFollow) { anchor.rel = anchor.rel ? anchor.rel + ' nofollow' : 'nofollow'; } } }; /** * Handles the CANCEL event from the dialog by clearing the anchor if needed. * @param {goog.events.Event} e Event object. * @private */ goog.editor.plugins.LinkDialogPlugin.prototype.handleCancel_ = function(e) { if (this.currentLink_.isNew()) { goog.dom.flattenElement(this.currentLink_.getAnchor()); var extraAnchors = this.currentLink_.getExtraAnchors(); for (var i = 0; i < extraAnchors.length; ++i) { goog.dom.flattenElement(extraAnchors[i]); } // Make sure listeners know the anchor was flattened out. this.getFieldObject().dispatchChange(); } this.eventHandler_.removeAll(); }; /** * Handles the BeforeTestLink event fired when the 'test' link is clicked. * @param {goog.ui.editor.LinkDialog.BeforeTestLinkEvent} e BeforeTestLink event * object. * @protected */ goog.editor.plugins.LinkDialogPlugin.prototype.handleBeforeTestLink = function(e) { if (!this.shouldOpenUrl(e.url)) { /** @desc Message when the user tries to test (preview) a link, but the * link cannot be tested. */ var MSG_UNSAFE_LINK = goog.getMsg('This link cannot be tested.'); alert(MSG_UNSAFE_LINK); e.preventDefault(); } }; /** * Checks whether the plugin should open the given url in a new window. * @param {string} url The url to check. * @return {boolean} If the plugin should open the given url in a new window. * @protected */ goog.editor.plugins.LinkDialogPlugin.prototype.shouldOpenUrl = function(url) { return !this.blockOpeningUnsafeSchemes_ || this.isSafeSchemeToOpen_(url); }; /** * Determines whether or not a url has a scheme which is safe to open. * Schemes like javascript are unsafe due to the possibility of XSS. * @param {string} url A url. * @return {boolean} Whether the url has a safe scheme. * @private */ goog.editor.plugins.LinkDialogPlugin.prototype.isSafeSchemeToOpen_ = function(url) { var scheme = goog.uri.utils.getScheme(url) || 'http'; return goog.array.contains(this.safeToOpenSchemes_, scheme.toLowerCase()); };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Base class for bubble plugins. * */ goog.provide('goog.editor.plugins.LinkBubble'); goog.provide('goog.editor.plugins.LinkBubble.Action'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.editor.BrowserFeature'); goog.require('goog.editor.Command'); goog.require('goog.editor.Link'); goog.require('goog.editor.plugins.AbstractBubblePlugin'); goog.require('goog.editor.range'); goog.require('goog.string'); goog.require('goog.style'); goog.require('goog.ui.editor.messages'); goog.require('goog.uri.utils'); goog.require('goog.window'); /** * Property bubble plugin for links. * @param {...!goog.editor.plugins.LinkBubble.Action} var_args List of * extra actions supported by the bubble. * @constructor * @extends {goog.editor.plugins.AbstractBubblePlugin} */ goog.editor.plugins.LinkBubble = function(var_args) { goog.base(this); /** * List of extra actions supported by the bubble. * @type {Array.<!goog.editor.plugins.LinkBubble.Action>} * @private */ this.extraActions_ = goog.array.toArray(arguments); /** * List of spans corresponding to the extra actions. * @type {Array.<!Element>} * @private */ this.actionSpans_ = []; /** * A list of whitelisted URL schemes which are safe to open. * @type {Array.<string>} * @private */ this.safeToOpenSchemes_ = ['http', 'https', 'ftp']; }; goog.inherits(goog.editor.plugins.LinkBubble, goog.editor.plugins.AbstractBubblePlugin); /** * Element id for the link text. * type {string} * @private */ goog.editor.plugins.LinkBubble.LINK_TEXT_ID_ = 'tr_link-text'; /** * Element id for the test link span. * type {string} * @private */ goog.editor.plugins.LinkBubble.TEST_LINK_SPAN_ID_ = 'tr_test-link-span'; /** * Element id for the test link. * type {string} * @private */ goog.editor.plugins.LinkBubble.TEST_LINK_ID_ = 'tr_test-link'; /** * Element id for the change link span. * type {string} * @private */ goog.editor.plugins.LinkBubble.CHANGE_LINK_SPAN_ID_ = 'tr_change-link-span'; /** * Element id for the link. * type {string} * @private */ goog.editor.plugins.LinkBubble.CHANGE_LINK_ID_ = 'tr_change-link'; /** * Element id for the delete link span. * type {string} * @private */ goog.editor.plugins.LinkBubble.DELETE_LINK_SPAN_ID_ = 'tr_delete-link-span'; /** * Element id for the delete link. * type {string} * @private */ goog.editor.plugins.LinkBubble.DELETE_LINK_ID_ = 'tr_delete-link'; /** * Element id for the link bubble wrapper div. * type {string} * @private */ goog.editor.plugins.LinkBubble.LINK_DIV_ID_ = 'tr_link-div'; /** * @desc Text label for link that lets the user click it to see where the link * this bubble is for point to. */ var MSG_LINK_BUBBLE_TEST_LINK = goog.getMsg('Go to link: '); /** * @desc Label that pops up a dialog to change the link. */ var MSG_LINK_BUBBLE_CHANGE = goog.getMsg('Change'); /** * @desc Label that allow the user to remove this link. */ var MSG_LINK_BUBBLE_REMOVE = goog.getMsg('Remove'); /** * Whether to stop leaking the page's url via the referrer header when the * link text link is clicked. * @type {boolean} * @private */ goog.editor.plugins.LinkBubble.prototype.stopReferrerLeaks_ = false; /** * Whether to block opening links with a non-whitelisted URL scheme. * @type {boolean} * @private */ goog.editor.plugins.LinkBubble.prototype.blockOpeningUnsafeSchemes_ = true; /** * Tells the plugin to stop leaking the page's url via the referrer header when * the link text link is clicked. When the user clicks on a link, the * browser makes a request for the link url, passing the url of the current page * in the request headers. If the user wants the current url to be kept secret * (e.g. an unpublished document), the owner of the url that was clicked will * see the secret url in the request headers, and it will no longer be a secret. * Calling this method will not send a referrer header in the request, just as * if the user had opened a blank window and typed the url in themselves. */ goog.editor.plugins.LinkBubble.prototype.stopReferrerLeaks = function() { // TODO(user): Right now only 2 plugins have this API to stop // referrer leaks. If more plugins need to do this, come up with a way to // enable the functionality in all plugins at once. Same thing for // setBlockOpeningUnsafeSchemes and associated functionality. this.stopReferrerLeaks_ = true; }; /** * Tells the plugin whether to block URLs with schemes not in the whitelist. * If blocking is enabled, this plugin will not linkify the link in the bubble * popup. * @param {boolean} blockOpeningUnsafeSchemes Whether to block non-whitelisted * schemes. */ goog.editor.plugins.LinkBubble.prototype.setBlockOpeningUnsafeSchemes = function(blockOpeningUnsafeSchemes) { this.blockOpeningUnsafeSchemes_ = blockOpeningUnsafeSchemes; }; /** * Sets a whitelist of allowed URL schemes that are safe to open. * Schemes should all be in lowercase. If the plugin is set to block opening * unsafe schemes, user-entered URLs will be converted to lowercase and checked * against this list. The whitelist has no effect if blocking is not enabled. * @param {Array.<string>} schemes String array of URL schemes to allow (http, * https, etc.). */ goog.editor.plugins.LinkBubble.prototype.setSafeToOpenSchemes = function(schemes) { this.safeToOpenSchemes_ = schemes; }; /** @override */ goog.editor.plugins.LinkBubble.prototype.getTrogClassId = function() { return 'LinkBubble'; }; /** @override */ goog.editor.plugins.LinkBubble.prototype.isSupportedCommand = function(command) { return command == goog.editor.Command.UPDATE_LINK_BUBBLE; }; /** @override */ goog.editor.plugins.LinkBubble.prototype.execCommandInternal = function(command, var_args) { if (command == goog.editor.Command.UPDATE_LINK_BUBBLE) { this.updateLink_(); } }; /** * Updates the href in the link bubble with a new link. * @private */ goog.editor.plugins.LinkBubble.prototype.updateLink_ = function() { var targetEl = this.getTargetElement(); this.closeBubble(); this.createBubble(targetEl); }; /** @override */ goog.editor.plugins.LinkBubble.prototype.getBubbleTargetFromSelection = function(selectedElement) { var bubbleTarget = goog.dom.getAncestorByTagNameAndClass(selectedElement, goog.dom.TagName.A); if (!bubbleTarget) { // See if the selection is touching the right side of a link, and if so, // show a bubble for that link. The check for "touching" is very brittle, // and currently only guarantees that it will pop up a bubble at the // position the cursor is placed at after the link dialog is closed. // NOTE(robbyw): This assumes this method is always called with // selected element = range.getContainerElement(). Right now this is true, // but attempts to re-use this method for other purposes could cause issues. // TODO(robbyw): Refactor this method to also take a range, and use that. var range = this.getFieldObject().getRange(); if (range && range.isCollapsed() && range.getStartOffset() == 0) { var startNode = range.getStartNode(); var previous = startNode.previousSibling; if (previous && previous.tagName == goog.dom.TagName.A) { bubbleTarget = previous; } } } return /** @type {Element} */ (bubbleTarget); }; /** * Set the optional function for getting the "test" link of a url. * @param {function(string) : string} func The function to use. */ goog.editor.plugins.LinkBubble.prototype.setTestLinkUrlFn = function(func) { this.testLinkUrlFn_ = func; }; /** * Returns the target element url for the bubble. * @return {string} The url href. * @protected */ goog.editor.plugins.LinkBubble.prototype.getTargetUrl = function() { // Get the href-attribute through getAttribute() rather than the href property // because Google-Toolbar on Firefox with "Send with Gmail" turned on // modifies the href-property of 'mailto:' links but leaves the attribute // untouched. return this.getTargetElement().getAttribute('href') || ''; }; /** @override */ goog.editor.plugins.LinkBubble.prototype.getBubbleType = function() { return goog.dom.TagName.A; }; /** @override */ goog.editor.plugins.LinkBubble.prototype.getBubbleTitle = function() { return goog.ui.editor.messages.MSG_LINK_CAPTION; }; /** @override */ goog.editor.plugins.LinkBubble.prototype.createBubbleContents = function( bubbleContainer) { var linkObj = this.getLinkToTextObj_(); // Create linkTextSpan, show plain text for e-mail address or truncate the // text to <= 48 characters so that property bubbles don't grow too wide and // create a link if URL. Only linkify valid links. // TODO(robbyw): Repalce this color with a CSS class. var color = linkObj.valid ? 'black' : 'red'; var shouldOpenUrl = this.shouldOpenUrl(linkObj.linkText); var linkTextSpan; if (goog.editor.Link.isLikelyEmailAddress(linkObj.linkText) || !linkObj.valid || !shouldOpenUrl) { linkTextSpan = this.dom_.createDom(goog.dom.TagName.SPAN, { id: goog.editor.plugins.LinkBubble.LINK_TEXT_ID_, style: 'color:' + color }, this.dom_.createTextNode(linkObj.linkText)); } else { var testMsgSpan = this.dom_.createDom(goog.dom.TagName.SPAN, {id: goog.editor.plugins.LinkBubble.TEST_LINK_SPAN_ID_}, MSG_LINK_BUBBLE_TEST_LINK); linkTextSpan = this.dom_.createDom(goog.dom.TagName.SPAN, { id: goog.editor.plugins.LinkBubble.LINK_TEXT_ID_, style: 'color:' + color }, ''); var linkText = goog.string.truncateMiddle(linkObj.linkText, 48); // Actually creates a pseudo-link that can't be right-clicked to open in a // new tab, because that would avoid the logic to stop referrer leaks. this.createLink(goog.editor.plugins.LinkBubble.TEST_LINK_ID_, this.dom_.createTextNode(linkText).data, this.testLink, linkTextSpan); } var changeLinkSpan = this.createLinkOption( goog.editor.plugins.LinkBubble.CHANGE_LINK_SPAN_ID_); this.createLink(goog.editor.plugins.LinkBubble.CHANGE_LINK_ID_, MSG_LINK_BUBBLE_CHANGE, this.showLinkDialog_, changeLinkSpan); // This function is called multiple times - we have to reset the array. this.actionSpans_ = []; for (var i = 0; i < this.extraActions_.length; i++) { var action = this.extraActions_[i]; var actionSpan = this.createLinkOption(action.spanId_); this.actionSpans_.push(actionSpan); this.createLink(action.linkId_, action.message_, function() { action.actionFn_(this.getTargetUrl()); }, actionSpan); } var removeLinkSpan = this.createLinkOption( goog.editor.plugins.LinkBubble.DELETE_LINK_SPAN_ID_); this.createLink(goog.editor.plugins.LinkBubble.DELETE_LINK_ID_, MSG_LINK_BUBBLE_REMOVE, this.deleteLink_, removeLinkSpan); this.onShow(); var bubbleContents = this.dom_.createDom(goog.dom.TagName.DIV, {id: goog.editor.plugins.LinkBubble.LINK_DIV_ID_}, testMsgSpan || '', linkTextSpan, changeLinkSpan); for (i = 0; i < this.actionSpans_.length; i++) { bubbleContents.appendChild(this.actionSpans_[i]); } bubbleContents.appendChild(removeLinkSpan); goog.dom.appendChild(bubbleContainer, bubbleContents); }; /** * Tests the link by opening it in a new tab/window. Should be used as the * click event handler for the test pseudo-link. * @protected */ goog.editor.plugins.LinkBubble.prototype.testLink = function() { goog.window.open(this.getTestLinkAction_(), { 'target': '_blank', 'noreferrer': this.stopReferrerLeaks_ }, this.getFieldObject().getAppWindow()); }; /** * Returns whether the URL should be considered invalid. This always returns * false in the base class, and should be overridden by subclasses that wish * to impose validity rules on URLs. * @param {string} url The url to check. * @return {boolean} Whether the URL should be considered invalid. */ goog.editor.plugins.LinkBubble.prototype.isInvalidUrl = goog.functions.FALSE; /** * Gets the text to display for a link, based on the type of link * @return {Object} Returns an object of the form: * {linkText: displayTextForLinkTarget, valid: ifTheLinkIsValid}. * @private */ goog.editor.plugins.LinkBubble.prototype.getLinkToTextObj_ = function() { var isError; var targetUrl = this.getTargetUrl(); if (this.isInvalidUrl(targetUrl)) { /** * @desc Message shown in a link bubble when the link is not a valid url. */ var MSG_INVALID_URL_LINK_BUBBLE = goog.getMsg('invalid url'); targetUrl = MSG_INVALID_URL_LINK_BUBBLE; isError = true; } else if (goog.editor.Link.isMailto(targetUrl)) { targetUrl = targetUrl.substring(7); // 7 == "mailto:".length } return {linkText: targetUrl, valid: !isError}; }; /** * Shows the link dialog. * @param {goog.events.BrowserEvent} e The event. * @private */ goog.editor.plugins.LinkBubble.prototype.showLinkDialog_ = function(e) { // Needed when this occurs due to an ENTER key event, else the newly created // dialog manages to have its OK button pressed, causing it to disappear. e.preventDefault(); this.getFieldObject().execCommand(goog.editor.Command.MODAL_LINK_EDITOR, new goog.editor.Link( /** @type {HTMLAnchorElement} */ (this.getTargetElement()), false)); this.closeBubble(); }; /** * Deletes the link associated with the bubble * @private */ goog.editor.plugins.LinkBubble.prototype.deleteLink_ = function() { this.getFieldObject().dispatchBeforeChange(); var link = this.getTargetElement(); var child = link.lastChild; goog.dom.flattenElement(link); goog.editor.range.placeCursorNextTo(child, false); this.closeBubble(); this.getFieldObject().dispatchChange(); this.getFieldObject().focus(); }; /** * Sets the proper state for the action links. * @protected * @override */ goog.editor.plugins.LinkBubble.prototype.onShow = function() { var linkDiv = this.dom_.getElement( goog.editor.plugins.LinkBubble.LINK_DIV_ID_); if (linkDiv) { var testLinkSpan = this.dom_.getElement( goog.editor.plugins.LinkBubble.TEST_LINK_SPAN_ID_); if (testLinkSpan) { var url = this.getTargetUrl(); goog.style.setElementShown(testLinkSpan, !goog.editor.Link.isMailto(url)); } for (var i = 0; i < this.extraActions_.length; i++) { var action = this.extraActions_[i]; var actionSpan = this.dom_.getElement(action.spanId_); if (actionSpan) { goog.style.setElementShown(actionSpan, action.toShowFn_( this.getTargetUrl())); } } } }; /** * Gets the url for the bubble test link. The test link is the link in the * bubble the user can click on to make sure the link they entered is correct. * @return {string} The url for the bubble link href. * @private */ goog.editor.plugins.LinkBubble.prototype.getTestLinkAction_ = function() { var targetUrl = this.getTargetUrl(); return this.testLinkUrlFn_ ? this.testLinkUrlFn_(targetUrl) : targetUrl; }; /** * Checks whether the plugin should open the given url in a new window. * @param {string} url The url to check. * @return {boolean} If the plugin should open the given url in a new window. * @protected */ goog.editor.plugins.LinkBubble.prototype.shouldOpenUrl = function(url) { return !this.blockOpeningUnsafeSchemes_ || this.isSafeSchemeToOpen_(url); }; /** * Determines whether or not a url has a scheme which is safe to open. * Schemes like javascript are unsafe due to the possibility of XSS. * @param {string} url A url. * @return {boolean} Whether the url has a safe scheme. * @private */ goog.editor.plugins.LinkBubble.prototype.isSafeSchemeToOpen_ = function(url) { var scheme = goog.uri.utils.getScheme(url) || 'http'; return goog.array.contains(this.safeToOpenSchemes_, scheme.toLowerCase()); }; /** * Constructor for extra actions that can be added to the link bubble. * @param {string} spanId The ID for the span showing the action. * @param {string} linkId The ID for the link showing the action. * @param {string} message The text for the link showing the action. * @param {function(string):boolean} toShowFn Test function to determine whether * to show the action for the given URL. * @param {function(string):void} actionFn Action function to run when the * action is clicked. Takes the current target URL as a parameter. * @constructor */ goog.editor.plugins.LinkBubble.Action = function(spanId, linkId, message, toShowFn, actionFn) { this.spanId_ = spanId; this.linkId_ = linkId; this.message_ = message; this.toShowFn_ = toShowFn; this.actionFn_ = actionFn; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // All Rights Reserved /** * @fileoverview Plugin for generating emoticons. * * @author nicksantos@google.com (Nick Santos) */ goog.provide('goog.editor.plugins.Emoticons'); goog.require('goog.dom.TagName'); goog.require('goog.editor.Plugin'); goog.require('goog.functions'); goog.require('goog.ui.emoji.Emoji'); /** * Plugin for generating emoticons. * * @constructor * @extends {goog.editor.Plugin} */ goog.editor.plugins.Emoticons = function() { goog.base(this); }; goog.inherits(goog.editor.plugins.Emoticons, goog.editor.Plugin); /** The emoticon command. */ goog.editor.plugins.Emoticons.COMMAND = '+emoticon'; /** @override */ goog.editor.plugins.Emoticons.prototype.getTrogClassId = goog.functions.constant(goog.editor.plugins.Emoticons.COMMAND); /** @override */ goog.editor.plugins.Emoticons.prototype.isSupportedCommand = function( command) { return command == goog.editor.plugins.Emoticons.COMMAND; }; /** * Inserts an emoticon into the editor at the cursor location. Places the * cursor to the right of the inserted emoticon. * @param {string} command Command to execute. * @param {*=} opt_arg Emoji to insert. * @return {Object|undefined} The result of the command. * @override */ goog.editor.plugins.Emoticons.prototype.execCommandInternal = function( command, opt_arg) { var emoji = /** @type {goog.ui.emoji.Emoji} */ (opt_arg); var dom = this.getFieldDomHelper(); var img = dom.createDom(goog.dom.TagName.IMG, { 'src': emoji.getUrl(), 'style': 'margin:0 0.2ex;vertical-align:middle' }); img.setAttribute(goog.ui.emoji.Emoji.ATTRIBUTE, emoji.getId()); this.getFieldObject().getRange().replaceContentsWithNode(img); // IE8 does the right thing with the cursor, and has a js error when we try // to place the cursor manually. // IE9 loses the cursor when the window is focused, so focus first. if (!goog.userAgent.IE || goog.userAgent.isDocumentMode(9)) { this.getFieldObject().focus(); goog.editor.range.placeCursorNextTo(img, false); } };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Editor plugin to handle tab keys not in lists to add 4 spaces. * * @author robbyw@google.com (Robby Walker) * @author ajp@google.com (Andy Perelson) */ goog.provide('goog.editor.plugins.SpacesTabHandler'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.editor.plugins.AbstractTabHandler'); goog.require('goog.editor.range'); /** * Plugin to handle tab keys when not in lists to add 4 spaces. * @constructor * @extends {goog.editor.plugins.AbstractTabHandler} */ goog.editor.plugins.SpacesTabHandler = function() { goog.editor.plugins.AbstractTabHandler.call(this); }; goog.inherits(goog.editor.plugins.SpacesTabHandler, goog.editor.plugins.AbstractTabHandler); /** @override */ goog.editor.plugins.SpacesTabHandler.prototype.getTrogClassId = function() { return 'SpacesTabHandler'; }; /** @override */ goog.editor.plugins.SpacesTabHandler.prototype.handleTabKey = function(e) { var dh = this.getFieldDomHelper(); var range = this.getFieldObject().getRange(); if (!goog.editor.range.intersectsTag(range, goog.dom.TagName.LI)) { // In the shift + tab case we don't want to insert spaces, but we don't // want focus to move either so skip the spacing logic and just prevent // default. if (!e.shiftKey) { // Not in a list but we want to insert 4 spaces. // Stop change events while we make multiple field changes. this.getFieldObject().stopChangeEvents(true, true); // Inserting nodes below completely messes up the selection, doing the // deletion here before it's messed up. Only delete if text is selected, // otherwise we would remove the character to the right of the cursor. if (!range.isCollapsed()) { dh.getDocument().execCommand('delete', false, null); // Safari 3 has some DOM exceptions if we don't reget the range here, // doing it all the time just to be safe. range = this.getFieldObject().getRange(); } // Emulate tab by removing selection and inserting 4 spaces // Two breaking spaces in a row can be collapsed by the browser into one // space. Inserting the string below because it is guaranteed to never // collapse to less than four spaces, regardless of what is adjacent to // the inserted spaces. This might make line wrapping slightly // sub-optimal around a grouping of non-breaking spaces. var elem = dh.createDom('span', null, '\u00a0\u00a0 \u00a0'); elem = range.insertNode(elem, false); this.getFieldObject().dispatchChange(); goog.editor.range.placeCursorNextTo(elem, false); this.getFieldObject().dispatchSelectionChangeEvent(); } e.preventDefault(); return true; } return false; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview goog.editor plugin to handle splitting block quotes. * */ goog.provide('goog.editor.plugins.Blockquote'); goog.require('goog.debug.Logger'); goog.require('goog.dom'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.TagName'); goog.require('goog.dom.classes'); goog.require('goog.editor.BrowserFeature'); goog.require('goog.editor.Command'); goog.require('goog.editor.Plugin'); goog.require('goog.editor.node'); goog.require('goog.functions'); /** * Plugin to handle splitting block quotes. This plugin does nothing on its * own and should be used in conjunction with EnterHandler or one of its * subclasses. * @param {boolean} requiresClassNameToSplit Whether to split only blockquotes * that have the given classname. * @param {string=} opt_className The classname to apply to generated * blockquotes. Defaults to 'tr_bq'. * @constructor * @extends {goog.editor.Plugin} */ goog.editor.plugins.Blockquote = function(requiresClassNameToSplit, opt_className) { goog.editor.Plugin.call(this); /** * Whether we only split blockquotes that have {@link classname}, or whether * all blockquote tags should be split on enter. * @type {boolean} * @private */ this.requiresClassNameToSplit_ = requiresClassNameToSplit; /** * Classname to put on blockquotes that are generated via the toolbar for * blockquote, so that we can internally distinguish these from blockquotes * that are used for indentation. This classname can be over-ridden by * clients for styling or other purposes. * @type {string} * @private */ this.className_ = opt_className || goog.getCssName('tr_bq'); }; goog.inherits(goog.editor.plugins.Blockquote, goog.editor.Plugin); /** * Command implemented by this plugin. * @type {string} */ goog.editor.plugins.Blockquote.SPLIT_COMMAND = '+splitBlockquote'; /** * Class ID used to identify this plugin. * @type {string} */ goog.editor.plugins.Blockquote.CLASS_ID = 'Blockquote'; /** * Logging object. * @type {goog.debug.Logger} * @protected * @override */ goog.editor.plugins.Blockquote.prototype.logger = goog.debug.Logger.getLogger('goog.editor.plugins.Blockquote'); /** @override */ goog.editor.plugins.Blockquote.prototype.getTrogClassId = function() { return goog.editor.plugins.Blockquote.CLASS_ID; }; /** * Since our exec command is always called from elsewhere, we make it silent. * @override */ goog.editor.plugins.Blockquote.prototype.isSilentCommand = goog.functions.TRUE; /** * Checks if a node is a blockquote node. If isAlreadySetup is set, it also * makes sure the node has the blockquote classname applied. Otherwise, it * ensures that the blockquote does not already have the classname applied. * @param {Node} node DOM node to check. * @param {boolean} isAlreadySetup True to enforce that the classname must be * set in order for it to count as a blockquote, false to * enforce that the classname must not be set in order for * it to count as a blockquote. * @param {boolean} requiresClassNameToSplit Whether only blockquotes with the * class name should be split. * @param {string} className The official blockquote class name. * @return {boolean} Whether node is a blockquote and if isAlreadySetup is * true, then whether this is a setup blockquote. * @deprecated Use {@link #isSplittableBlockquote}, * {@link #isSetupBlockquote}, or {@link #isUnsetupBlockquote} instead * since this has confusing behavior. */ goog.editor.plugins.Blockquote.isBlockquote = function(node, isAlreadySetup, requiresClassNameToSplit, className) { if (node.tagName != goog.dom.TagName.BLOCKQUOTE) { return false; } if (!requiresClassNameToSplit) { return isAlreadySetup; } var hasClassName = goog.dom.classes.has(/** @type {Element} */ (node), className); return isAlreadySetup ? hasClassName : !hasClassName; }; /** * Checks if a node is a blockquote which can be split. A splittable blockquote * meets the following criteria: * <ol> * <li>Node is a blockquote element</li> * <li>Node has the blockquote classname if the classname is required to * split</li> * </ol> * * @param {Node} node DOM node in question. * @return {boolean} Whether the node is a splittable blockquote. */ goog.editor.plugins.Blockquote.prototype.isSplittableBlockquote = function(node) { if (node.tagName != goog.dom.TagName.BLOCKQUOTE) { return false; } if (!this.requiresClassNameToSplit_) { return true; } return goog.dom.classes.has(node, this.className_); }; /** * Checks if a node is a blockquote element which has been setup. * @param {Node} node DOM node to check. * @return {boolean} Whether the node is a blockquote with the required class * name applied. */ goog.editor.plugins.Blockquote.prototype.isSetupBlockquote = function(node) { return node.tagName == goog.dom.TagName.BLOCKQUOTE && goog.dom.classes.has(node, this.className_); }; /** * Checks if a node is a blockquote element which has not been setup yet. * @param {Node} node DOM node to check. * @return {boolean} Whether the node is a blockquote without the required * class name applied. */ goog.editor.plugins.Blockquote.prototype.isUnsetupBlockquote = function(node) { return node.tagName == goog.dom.TagName.BLOCKQUOTE && !this.isSetupBlockquote(node); }; /** * Gets the class name required for setup blockquotes. * @return {string} The blockquote class name. */ goog.editor.plugins.Blockquote.prototype.getBlockquoteClassName = function() { return this.className_; }; /** * Helper routine which walks up the tree to find the topmost * ancestor with only a single child. The ancestor node or the original * node (if no ancestor was found) is then removed from the DOM. * * @param {Node} node The node whose ancestors have to be searched. * @param {Node} root The root node to stop the search at. * @private */ goog.editor.plugins.Blockquote.findAndRemoveSingleChildAncestor_ = function( node, root) { var predicateFunc = function(parentNode) { return parentNode != root && parentNode.childNodes.length == 1; }; var ancestor = goog.editor.node.findHighestMatchingAncestor(node, predicateFunc); if (!ancestor) { ancestor = node; } goog.dom.removeNode(ancestor); }; /** * Remove every nodes from the DOM tree that are all white space nodes. * @param {Array.<Node>} nodes Nodes to be checked. * @private */ goog.editor.plugins.Blockquote.removeAllWhiteSpaceNodes_ = function(nodes) { for (var i = 0; i < nodes.length; ++i) { if (goog.editor.node.isEmpty(nodes[i], true)) { goog.dom.removeNode(nodes[i]); } } }; /** @override */ goog.editor.plugins.Blockquote.prototype.isSupportedCommand = function( command) { return command == goog.editor.plugins.Blockquote.SPLIT_COMMAND; }; /** * Splits a quoted region if any. To be called on a key press event. When this * function returns true, the event that caused it to be called should be * canceled. * @param {string} command The command to execute. * @param {...*} var_args Single additional argument representing the * current cursor position. In IE, it is a single node. In any other * browser, it is an object with a {@code node} key and an {@code offset} * key. * @return {boolean|undefined} Boolean true when the quoted region has been * split, false or undefined otherwise. * @override */ goog.editor.plugins.Blockquote.prototype.execCommandInternal = function( command, var_args) { var pos = arguments[1]; if (command == goog.editor.plugins.Blockquote.SPLIT_COMMAND && pos && (this.className_ || !this.requiresClassNameToSplit_)) { return goog.editor.BrowserFeature.HAS_W3C_RANGES ? this.splitQuotedBlockW3C_(pos) : this.splitQuotedBlockIE_(/** @type {Node} */ (pos)); } }; /** * Version of splitQuotedBlock_ that uses W3C ranges. * @param {Object} anchorPos The current cursor position. * @return {boolean} Whether the blockquote was split. * @private */ goog.editor.plugins.Blockquote.prototype.splitQuotedBlockW3C_ = function(anchorPos) { var cursorNode = anchorPos.node; var quoteNode = goog.editor.node.findTopMostEditableAncestor( cursorNode.parentNode, goog.bind(this.isSplittableBlockquote, this)); var secondHalf, textNodeToRemove; var insertTextNode = false; // There are two special conditions that we account for here. // // 1. Whenever the cursor is after (one<BR>|) or just before a BR element // (one|<BR>) and the user presses enter, the second quoted block starts // with a BR which appears to the user as an extra newline. This stems // from the fact that we create two text nodes as our split boundaries // and the BR becomes a part of the second half because of this. // // 2. When the cursor is at the end of a text node with no siblings and // the user presses enter, the second blockquote might contain a // empty subtree that ends in a 0 length text node. We account for that // as a post-splitting operation. if (quoteNode) { // selection is in a line that has text in it if (cursorNode.nodeType == goog.dom.NodeType.TEXT) { if (anchorPos.offset == cursorNode.length) { var siblingNode = cursorNode.nextSibling; // This accounts for the condition where the cursor appears at the // end of a text node and right before the BR eg: one|<BR>. We ensure // that we split on the BR in that case. if (siblingNode && siblingNode.tagName == goog.dom.TagName.BR) { cursorNode = siblingNode; // This might be null but splitDomTreeAt accounts for the null case. secondHalf = siblingNode.nextSibling; } else { textNodeToRemove = cursorNode.splitText(anchorPos.offset); secondHalf = textNodeToRemove; } } else { secondHalf = cursorNode.splitText(anchorPos.offset); } } else if (cursorNode.tagName == goog.dom.TagName.BR) { // This might be null but splitDomTreeAt accounts for the null case. secondHalf = cursorNode.nextSibling; } else { // The selection is in a line that is empty, with more than 1 level // of quote. insertTextNode = true; } } else { // Check if current node is a quote node. // This will happen if user clicks in an empty line in the quote, // when there is 1 level of quote. if (this.isSetupBlockquote(cursorNode)) { quoteNode = cursorNode; insertTextNode = true; } } if (insertTextNode) { // Create two empty text nodes to split between. cursorNode = this.insertEmptyTextNodeBeforeRange_(); secondHalf = this.insertEmptyTextNodeBeforeRange_(); } if (!quoteNode) { return false; } secondHalf = goog.editor.node.splitDomTreeAt(cursorNode, secondHalf, quoteNode); goog.dom.insertSiblingAfter(secondHalf, quoteNode); // Set the insertion point. var dh = this.getFieldDomHelper(); var tagToInsert = this.getFieldObject().queryCommandValue( goog.editor.Command.DEFAULT_TAG) || goog.dom.TagName.DIV; var container = dh.createElement(/** @type {string} */ (tagToInsert)); container.innerHTML = '&nbsp;'; // Prevent the div from collapsing. quoteNode.parentNode.insertBefore(container, secondHalf); dh.getWindow().getSelection().collapse(container, 0); // We need to account for the condition where the second blockquote // might contain an empty DOM tree. This arises from trying to split // at the end of an empty text node. We resolve this by walking up the tree // till we either reach the blockquote or till we hit a node with more // than one child. The resulting node is then removed from the DOM. if (textNodeToRemove) { goog.editor.plugins.Blockquote.findAndRemoveSingleChildAncestor_( textNodeToRemove, secondHalf); } goog.editor.plugins.Blockquote.removeAllWhiteSpaceNodes_( [quoteNode, secondHalf]); return true; }; /** * Inserts an empty text node before the field's range. * @return {!Node} The empty text node. * @private */ goog.editor.plugins.Blockquote.prototype.insertEmptyTextNodeBeforeRange_ = function() { var range = this.getFieldObject().getRange(); var node = this.getFieldDomHelper().createTextNode(''); range.insertNode(node, true); return node; }; /** * IE version of splitQuotedBlock_. * @param {Node} splitNode The current cursor position. * @return {boolean} Whether the blockquote was split. * @private */ goog.editor.plugins.Blockquote.prototype.splitQuotedBlockIE_ = function(splitNode) { var dh = this.getFieldDomHelper(); var quoteNode = goog.editor.node.findTopMostEditableAncestor( splitNode.parentNode, goog.bind(this.isSplittableBlockquote, this)); if (!quoteNode) { return false; } var clone = splitNode.cloneNode(false); // Whenever the cursor is just before a BR element (one|<BR>) and the user // presses enter, the second quoted block starts with a BR which appears // to the user as an extra newline. This stems from the fact that the // dummy span that we create (splitNode) occurs before the BR and we split // on that. if (splitNode.nextSibling && splitNode.nextSibling.tagName == goog.dom.TagName.BR) { splitNode = splitNode.nextSibling; } var secondHalf = goog.editor.node.splitDomTreeAt(splitNode, clone, quoteNode); goog.dom.insertSiblingAfter(secondHalf, quoteNode); // Set insertion point. var tagToInsert = this.getFieldObject().queryCommandValue( goog.editor.Command.DEFAULT_TAG) || goog.dom.TagName.DIV; var div = dh.createElement(/** @type {string} */ (tagToInsert)); quoteNode.parentNode.insertBefore(div, secondHalf); // The div needs non-whitespace contents in order for the insertion point // to get correctly inserted. div.innerHTML = '&nbsp;'; // Moving the range 1 char isn't enough when you have markup. // This moves the range to the end of the nbsp. var range = dh.getDocument().selection.createRange(); range.moveToElementText(splitNode); range.move('character', 2); range.select(); // Remove the no-longer-necessary nbsp. div.innerHTML = ''; // Clear the original selection. range.pasteHTML(''); // We need to remove clone from the DOM but just removing clone alone will // not suffice. Let's assume we have the following DOM structure and the // cursor is placed after the first numbered list item "one". // // <blockquote class="gmail-quote"> // <div><div>a</div><ol><li>one|</li></ol></div> // <div>b</div> // </blockquote> // // After pressing enter, we have the following structure. // // <blockquote class="gmail-quote"> // <div><div>a</div><ol><li>one|</li></ol></div> // </blockquote> // <div>&nbsp;</div> // <blockquote class="gmail-quote"> // <div><ol><li><span id=""></span></li></ol></div> // <div>b</div> // </blockquote> // // The clone is contained in a subtree which should be removed. This stems // from the fact that we invoke splitDomTreeAt with the dummy span // as the starting splitting point and this results in the empty subtree // <div><ol><li><span id=""></span></li></ol></div>. // // We resolve this by walking up the tree till we either reach the // blockquote or till we hit a node with more than one child. The resulting // node is then removed from the DOM. goog.editor.plugins.Blockquote.findAndRemoveSingleChildAncestor_( clone, secondHalf); goog.editor.plugins.Blockquote.removeAllWhiteSpaceNodes_( [quoteNode, secondHalf]); return true; };
JavaScript
// Copyright 2005 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Base class for bubble plugins. */ goog.provide('goog.editor.plugins.AbstractBubblePlugin'); goog.require('goog.dom'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.Range'); goog.require('goog.dom.TagName'); goog.require('goog.editor.Plugin'); goog.require('goog.editor.style'); goog.require('goog.events'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventType'); goog.require('goog.events.KeyCodes'); goog.require('goog.events.actionEventWrapper'); goog.require('goog.functions'); goog.require('goog.string.Unicode'); goog.require('goog.ui.Component.EventType'); goog.require('goog.ui.editor.Bubble'); goog.require('goog.userAgent'); /** * Base class for bubble plugins. This is used for to connect user behavior * in the editor to a goog.ui.editor.Bubble UI element that allows * the user to modify the properties of an element on their page (e.g. the alt * text of an image tag). * * Subclasses should override the abstract method getBubbleTargetFromSelection() * with code to determine if the current selection should activate the bubble * type. The other abstract method createBubbleContents() should be overriden * with code to create the inside markup of the bubble. The base class creates * the rest of the bubble. * * @constructor * @extends {goog.editor.Plugin} */ goog.editor.plugins.AbstractBubblePlugin = function() { goog.base(this); /** * Place to register events the plugin listens to. * @type {goog.events.EventHandler} * @protected */ this.eventRegister = new goog.events.EventHandler(this); }; goog.inherits(goog.editor.plugins.AbstractBubblePlugin, goog.editor.Plugin); /** * The css class name of option link elements. * @type {string} * @private */ goog.editor.plugins.AbstractBubblePlugin.OPTION_LINK_CLASSNAME_ = goog.getCssName('tr_option-link'); /** * The css class name of link elements. * @type {string} * @private */ goog.editor.plugins.AbstractBubblePlugin.LINK_CLASSNAME_ = goog.getCssName('tr_bubble_link'); /** * The constant string used to separate option links. * @type {string} * @protected */ goog.editor.plugins.AbstractBubblePlugin.DASH_NBSP_STRING = goog.string.Unicode.NBSP + '-' + goog.string.Unicode.NBSP; /** * Default factory function for creating a bubble UI component. * @param {!Element} parent The parent element for the bubble. * @param {number} zIndex The z index to draw the bubble at. * @return {!goog.ui.editor.Bubble} The new bubble component. * @private */ goog.editor.plugins.AbstractBubblePlugin.defaultBubbleFactory_ = function( parent, zIndex) { return new goog.ui.editor.Bubble(parent, zIndex); }; /** * Factory function that creates a bubble UI component. It takes as parameters * the bubble parent element and the z index to draw the bubble at. * @type {function(!Element, number): !goog.ui.editor.Bubble} * @private */ goog.editor.plugins.AbstractBubblePlugin.bubbleFactory_ = goog.editor.plugins.AbstractBubblePlugin.defaultBubbleFactory_; /** * Sets the bubble factory function. * @param {function(!Element, number): !goog.ui.editor.Bubble} * bubbleFactory Function that creates a bubble for the given bubble parent * element and z index. */ goog.editor.plugins.AbstractBubblePlugin.setBubbleFactory = function( bubbleFactory) { goog.editor.plugins.AbstractBubblePlugin.bubbleFactory_ = bubbleFactory; }; /** * Map from field id to shared bubble object. * @type {Object.<goog.ui.editor.Bubble>} * @private */ goog.editor.plugins.AbstractBubblePlugin.bubbleMap_ = {}; /** * The optional parent of the bubble. If null or not set, we will use the * application document. This is useful when you have an editor embedded in * a scrolling DIV. * @type {Element|undefined} * @private */ goog.editor.plugins.AbstractBubblePlugin.prototype.bubbleParent_; /** * The id of the panel this plugin added to the shared bubble. Null when * this plugin doesn't currently have a panel in a bubble. * @type {string?} * @private */ goog.editor.plugins.AbstractBubblePlugin.prototype.panelId_ = null; /** * Whether this bubble should support tabbing through the link elements. False * by default. * @type {boolean} * @private */ goog.editor.plugins.AbstractBubblePlugin.prototype.keyboardNavigationEnabled_ = false; /** * Sets whether the bubble should support tabbing through the link elements. * @param {boolean} keyboardNavigationEnabled Whether the bubble should support * tabbing through the link elements. */ goog.editor.plugins.AbstractBubblePlugin.prototype.enableKeyboardNavigation = function(keyboardNavigationEnabled) { this.keyboardNavigationEnabled_ = keyboardNavigationEnabled; }; /** * Sets the bubble parent. * @param {Element} bubbleParent An element where the bubble will be * anchored. If null, we will use the application document. This * is useful when you have an editor embedded in a scrolling div. */ goog.editor.plugins.AbstractBubblePlugin.prototype.setBubbleParent = function( bubbleParent) { this.bubbleParent_ = bubbleParent; }; /** * @return {goog.dom.DomHelper} The dom helper for the bubble window. */ goog.editor.plugins.AbstractBubblePlugin.prototype.getBubbleDom = function() { return this.dom_; }; /** @override */ goog.editor.plugins.AbstractBubblePlugin.prototype.getTrogClassId = goog.functions.constant('AbstractBubblePlugin'); /** * Returns the element whose properties the bubble manipulates. * @return {Element} The target element. */ goog.editor.plugins.AbstractBubblePlugin.prototype.getTargetElement = function() { return this.targetElement_; }; /** @override */ goog.editor.plugins.AbstractBubblePlugin.prototype.handleKeyUp = function(e) { // For example, when an image is selected, pressing any key overwrites // the image and the panel should be hidden. // Therefore we need to track key presses when the bubble is showing. if (this.isVisible()) { this.handleSelectionChange(); } return false; }; /** * Pops up a property bubble for the given selection if appropriate and closes * open property bubbles if no longer needed. This should not be overridden. * @override */ goog.editor.plugins.AbstractBubblePlugin.prototype.handleSelectionChange = function(opt_e, opt_target) { var selectedElement; if (opt_e) { selectedElement = /** @type {Element} */ (opt_e.target); } else if (opt_target) { selectedElement = /** @type {Element} */ (opt_target); } else { var range = this.getFieldObject().getRange(); if (range) { var startNode = range.getStartNode(); var endNode = range.getEndNode(); var startOffset = range.getStartOffset(); var endOffset = range.getEndOffset(); // Sometimes in IE, the range will be collapsed, but think the end node // and start node are different (although in the same visible position). // In this case, favor the position IE thinks is the start node. if (goog.userAgent.IE && range.isCollapsed() && startNode != endNode) { range = goog.dom.Range.createCaret(startNode, startOffset); } if (startNode.nodeType == goog.dom.NodeType.ELEMENT && startNode == endNode && startOffset == endOffset - 1) { var element = startNode.childNodes[startOffset]; if (element.nodeType == goog.dom.NodeType.ELEMENT) { selectedElement = element; } } } selectedElement = selectedElement || range && range.getContainerElement(); } return this.handleSelectionChangeInternal(selectedElement); }; /** * Pops up a property bubble for the given selection if appropriate and closes * open property bubbles if no longer needed. * @param {Element?} selectedElement The selected element. * @return {boolean} Always false, allowing every bubble plugin to handle the * event. * @protected */ goog.editor.plugins.AbstractBubblePlugin.prototype. handleSelectionChangeInternal = function(selectedElement) { if (selectedElement) { var bubbleTarget = this.getBubbleTargetFromSelection(selectedElement); if (bubbleTarget) { if (bubbleTarget != this.targetElement_ || !this.panelId_) { // Make sure any existing panel of the same type is closed before // creating a new one. if (this.panelId_) { this.closeBubble(); } this.createBubble(bubbleTarget); } return false; } } if (this.panelId_) { this.closeBubble(); } return false; }; /** * Should be overriden by subclasses to return the bubble target element or * null if an element of their required type isn't found. * @param {Element} selectedElement The target of the selection change event or * the parent container of the current entire selection. * @return {Element?} The HTML bubble target element or null if no element of * the required type is not found. */ goog.editor.plugins.AbstractBubblePlugin.prototype. getBubbleTargetFromSelection = goog.abstractMethod; /** @override */ goog.editor.plugins.AbstractBubblePlugin.prototype.disable = function(field) { // When the field is made uneditable, dispose of the bubble. We do this // because the next time the field is made editable again it may be in // a different document / iframe. if (field.isUneditable()) { var bubble = goog.editor.plugins.AbstractBubblePlugin.bubbleMap_[field.id]; if (bubble) { bubble.dispose(); delete goog.editor.plugins.AbstractBubblePlugin.bubbleMap_[field.id]; } } }; /** * @return {goog.ui.editor.Bubble} The shared bubble object for the field this * plugin is registered on. Creates it if necessary. * @private */ goog.editor.plugins.AbstractBubblePlugin.prototype.getSharedBubble_ = function() { var bubbleParent = /** @type {!Element} */ (this.bubbleParent_ || this.getFieldObject().getAppWindow().document.body); this.dom_ = goog.dom.getDomHelper(bubbleParent); var bubble = goog.editor.plugins.AbstractBubblePlugin.bubbleMap_[ this.getFieldObject().id]; if (!bubble) { bubble = goog.editor.plugins.AbstractBubblePlugin.bubbleFactory_.call(null, bubbleParent, this.getFieldObject().getBaseZindex()); goog.editor.plugins.AbstractBubblePlugin.bubbleMap_[ this.getFieldObject().id] = bubble; } return bubble; }; /** * Creates and shows the property bubble. * @param {Element} targetElement The target element of the bubble. */ goog.editor.plugins.AbstractBubblePlugin.prototype.createBubble = function( targetElement) { var bubble = this.getSharedBubble_(); if (!bubble.hasPanelOfType(this.getBubbleType())) { this.targetElement_ = targetElement; this.panelId_ = bubble.addPanel(this.getBubbleType(), this.getBubbleTitle(), targetElement, goog.bind(this.createBubbleContents, this), this.shouldPreferBubbleAboveElement()); this.eventRegister.listen(bubble, goog.ui.Component.EventType.HIDE, this.handlePanelClosed_); this.onShow(); if (this.keyboardNavigationEnabled_) { this.eventRegister.listen(bubble.getContentElement(), goog.events.EventType.KEYDOWN, this.onBubbleKey_); } } }; /** * @return {string} The type of bubble shown by this plugin. Usually the tag * name of the element this bubble targets. * @protected */ goog.editor.plugins.AbstractBubblePlugin.prototype.getBubbleType = function() { return ''; }; /** * @return {string} The title for bubble shown by this plugin. Defaults to no * title. Should be overridden by subclasses. * @protected */ goog.editor.plugins.AbstractBubblePlugin.prototype.getBubbleTitle = function() { return ''; }; /** * @return {boolean} Whether the bubble should prefer placement above the * target element. * @protected */ goog.editor.plugins.AbstractBubblePlugin.prototype. shouldPreferBubbleAboveElement = goog.functions.FALSE; /** * Should be overriden by subclasses to add the type specific contents to the * bubble. * @param {Element} bubbleContainer The container element of the bubble to * which the contents should be added. * @protected */ goog.editor.plugins.AbstractBubblePlugin.prototype.createBubbleContents = goog.abstractMethod; /** * Register the handler for the target's CLICK event. * @param {Element} target The event source element. * @param {Function} handler The event handler. * @protected * @deprecated Use goog.editor.plugins.AbstractBubblePlugin. * registerActionHandler to register click and enter events. */ goog.editor.plugins.AbstractBubblePlugin.prototype.registerClickHandler = function(target, handler) { this.registerActionHandler(target, handler); }; /** * Register the handler for the target's CLICK and ENTER key events. * @param {Element} target The event source element. * @param {Function} handler The event handler. * @protected */ goog.editor.plugins.AbstractBubblePlugin.prototype.registerActionHandler = function(target, handler) { this.eventRegister.listenWithWrapper(target, goog.events.actionEventWrapper, handler); }; /** * Closes the bubble. */ goog.editor.plugins.AbstractBubblePlugin.prototype.closeBubble = function() { if (this.panelId_) { this.getSharedBubble_().removePanel(this.panelId_); this.handlePanelClosed_(); } }; /** * Called after the bubble is shown. The default implementation does nothing. * Override it to provide your own one. * @protected */ goog.editor.plugins.AbstractBubblePlugin.prototype.onShow = goog.nullFunction; /** * Handles when the bubble panel is closed. Invoked when the entire bubble is * hidden and also directly when the panel is closed manually. * @private */ goog.editor.plugins.AbstractBubblePlugin.prototype.handlePanelClosed_ = function() { this.targetElement_ = null; this.panelId_ = null; this.eventRegister.removeAll(); }; /** * In case the keyboard navigation is enabled, this will focus to the first link * element in the bubble when TAB is clicked. The user could still go through * the rest of tabbable UI elements using shift + TAB. * @override */ goog.editor.plugins.AbstractBubblePlugin.prototype.handleKeyDown = function(e) { if (this.keyboardNavigationEnabled_ && this.isVisible() && e.keyCode == goog.events.KeyCodes.TAB && !e.shiftKey) { var bubbleEl = this.getSharedBubble_().getContentElement(); var linkEl = goog.dom.getElementByClass( goog.editor.plugins.AbstractBubblePlugin.LINK_CLASSNAME_, bubbleEl); if (linkEl) { linkEl.focus(); e.preventDefault(); return true; } } return false; }; /** * Handles a key event on the bubble. This ensures that the focus loops through * the link elements found in the bubble and then the focus is got by the field * element. * @param {goog.events.BrowserEvent} e The event. * @private */ goog.editor.plugins.AbstractBubblePlugin.prototype.onBubbleKey_ = function(e) { if (this.isVisible() && e.keyCode == goog.events.KeyCodes.TAB) { var bubbleEl = this.getSharedBubble_().getContentElement(); var links = goog.dom.getElementsByClass( goog.editor.plugins.AbstractBubblePlugin.LINK_CLASSNAME_, bubbleEl); var tabbingOutOfBubble = e.shiftKey ? links[0] == e.target : links.length && links[links.length - 1] == e.target; if (tabbingOutOfBubble) { this.getFieldObject().focus(); e.preventDefault(); } } }; /** * @return {boolean} Whether the bubble is visible. */ goog.editor.plugins.AbstractBubblePlugin.prototype.isVisible = function() { return !!this.panelId_; }; /** * Reposition the property bubble. */ goog.editor.plugins.AbstractBubblePlugin.prototype.reposition = function() { var bubble = this.getSharedBubble_(); if (bubble) { bubble.reposition(); } }; /** * Helper method that creates option links (such as edit, test, remove) * @param {string} id String id for the span id. * @return {Element} The option link element. * @protected */ goog.editor.plugins.AbstractBubblePlugin.prototype.createLinkOption = function( id) { // Dash plus link are together in a span so we can hide/show them easily return this.dom_.createDom(goog.dom.TagName.SPAN, { id: id, className: goog.editor.plugins.AbstractBubblePlugin.OPTION_LINK_CLASSNAME_ }, this.dom_.createTextNode( goog.editor.plugins.AbstractBubblePlugin.DASH_NBSP_STRING)); }; /** * Helper method that creates a link with text set to linkText and optionaly * wires up a listener for the CLICK event or the link. * @param {string} linkId The id of the link. * @param {string} linkText Text of the link. * @param {Function=} opt_onClick Optional function to call when the link is * clicked. * @param {Element=} opt_container If specified, location to insert link. If no * container is specified, the old link is removed and replaced. * @return {Element} The link element. * @protected */ goog.editor.plugins.AbstractBubblePlugin.prototype.createLink = function( linkId, linkText, opt_onClick, opt_container) { var link = this.createLinkHelper(linkId, linkText, false, opt_container); if (opt_onClick) { this.registerActionHandler(link, opt_onClick); } return link; }; /** * Helper method to create a link to insert into the bubble. * @param {string} linkId The id of the link. * @param {string} linkText Text of the link. * @param {boolean} isAnchor Set to true to create an actual anchor tag * instead of a span. Actual links are right clickable (e.g. to open in * a new window) and also update window status on hover. * @param {Element=} opt_container If specified, location to insert link. If no * container is specified, the old link is removed and replaced. * @return {Element} The link element. * @protected */ goog.editor.plugins.AbstractBubblePlugin.prototype.createLinkHelper = function( linkId, linkText, isAnchor, opt_container) { var link = this.dom_.createDom( isAnchor ? goog.dom.TagName.A : goog.dom.TagName.SPAN, {className: goog.editor.plugins.AbstractBubblePlugin.LINK_CLASSNAME_}, linkText); if (this.keyboardNavigationEnabled_) { link.setAttribute('tabindex', 0); } link.setAttribute('role', 'link'); this.setupLink(link, linkId, opt_container); goog.editor.style.makeUnselectable(link, this.eventRegister); return link; }; /** * Inserts a link in the given container if it is specified or removes * the old link with this id and replaces it with the new link * @param {Element} link Html element to insert. * @param {string} linkId Id of the link. * @param {Element=} opt_container If specified, location to insert link. * @protected */ goog.editor.plugins.AbstractBubblePlugin.prototype.setupLink = function( link, linkId, opt_container) { if (opt_container) { opt_container.appendChild(link); } else { var oldLink = this.dom_.getElement(linkId); if (oldLink) { goog.dom.replaceNode(link, oldLink); } } link.id = linkId; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('goog.editor.plugins.EquationEditorPlugin'); goog.require('goog.editor.Command'); goog.require('goog.editor.plugins.AbstractDialogPlugin'); goog.require('goog.editor.range'); goog.require('goog.functions'); goog.require('goog.ui.editor.AbstractDialog.Builder'); goog.require('goog.ui.editor.EquationEditorDialog'); goog.require('goog.ui.editor.EquationEditorOkEvent'); goog.require('goog.ui.equation.EquationEditor'); goog.require('goog.ui.equation.ImageRenderer'); goog.require('goog.ui.equation.PaletteManager'); goog.require('goog.ui.equation.TexEditor'); /** * A plugin that opens the equation editor in a dialog window. * @param {string=} opt_helpUrl A URL pointing to help documentation. * @constructor * @extends {goog.editor.plugins.AbstractDialogPlugin} */ goog.editor.plugins.EquationEditorPlugin = function(opt_helpUrl) { /** * The IMG element for the equation being edited, null if creating a new * equation. * @type {Element} * @private */ this.originalElement_; /** * A URL pointing to help documentation. * @type {string} * @private */ this.helpUrl_ = opt_helpUrl || ''; /** * The listener key for double click events. * @type {goog.events.Key} * @private */ this.dblClickKey_; goog.editor.plugins.AbstractDialogPlugin.call(this, goog.editor.Command.EQUATION); }; goog.inherits(goog.editor.plugins.EquationEditorPlugin, goog.editor.plugins.AbstractDialogPlugin); /** * The logger for the EquationEditorPlugin. * @type {goog.debug.Logger} * @private */ goog.editor.plugins.EquationEditorPlugin.prototype.logger_ = goog.debug.Logger.getLogger('goog.editor.plugins.EquationEditorPlugin'); /** @override */ goog.editor.plugins.EquationEditorPlugin.prototype.getTrogClassId = goog.functions.constant('EquationEditorPlugin'); /** * @override */ goog.editor.plugins.EquationEditorPlugin.prototype.createDialog = function(dom, opt_arg) { var equationImgEl = /** @type {Element} */ (opt_arg || null); var equationStr = equationImgEl ? goog.ui.equation.ImageRenderer.getEquationFromImage(equationImgEl) : ''; this.originalElement_ = equationImgEl; var dialog = new goog.ui.editor.EquationEditorDialog( this.populateContext_(), dom, equationStr, this.helpUrl_); dialog.addEventListener(goog.ui.editor.AbstractDialog.EventType.OK, this.handleOk_, false, this); return dialog; }; /** * Populates the context that this plugin runs in. * @return {Object} The context that this plugin runs in. * @private */ goog.editor.plugins.EquationEditorPlugin.prototype.populateContext_ = function() { var context = {}; context.paletteManager = new goog.ui.equation.PaletteManager(); return context; }; /** * Returns the selected text in the editable field for using as initial * equation string for the equation editor. * * TODO(user): Sanity check the selected text and return it only if it * reassembles a TeX equation and is not too long. * * @return {string} Selected text in the editable field for using it as * initial equation string for the equation editor. * @private */ goog.editor.plugins.EquationEditorPlugin.prototype.getEquationFromSelection_ = function() { var range = this.getFieldObject().getRange(); if (range) { return range.getText(); } return ''; }; /** @override */ goog.editor.plugins.EquationEditorPlugin.prototype.enable = function(fieldObject) { goog.base(this, 'enable', fieldObject); if (this.isEnabled(fieldObject)) { this.dblClickKey_ = goog.events.listen(fieldObject.getElement(), goog.events.EventType.DBLCLICK, goog.bind(this.handleDoubleClick_, this), false, this); } }; /** @override */ goog.editor.plugins.EquationEditorPlugin.prototype.disable = function(fieldObject) { goog.base(this, 'disable', fieldObject); if (!this.isEnabled(fieldObject)) { goog.events.unlistenByKey(this.dblClickKey_); } }; /** * Handles double clicks in the field area. * @param {goog.events.Event} e The event. * @private */ goog.editor.plugins.EquationEditorPlugin.prototype.handleDoubleClick_ = function(e) { var node = /** @type {Node} */ (e.target); this.execCommand(goog.editor.Command.EQUATION, node); }; /** * Called when user clicks OK. Inserts the equation at cursor position in the * active editable field. * @param {goog.ui.editor.EquationEditorOkEvent} e The OK event. * @private */ goog.editor.plugins.EquationEditorPlugin.prototype.handleOk_ = function(e) { // First restore the selection so we can manipulate the editable field's // content according to what was selected. this.restoreOriginalSelection(); // Notify listeners that the editable field's contents are about to change. this.getFieldObject().dispatchBeforeChange(); var dh = this.getFieldDomHelper(); var node = dh.htmlToDocumentFragment(e.equationHtml); if (this.originalElement_) { // Editing existing equation: replace the old equation node with the new // one. goog.dom.replaceNode(node, this.originalElement_); } else { // Clear out what was previously selected, unless selection is already // empty (aka collapsed), and replace it with the new equation node. // TODO(user): there is a bug in FF where removeContents() may remove a // <br> right before and/or after the selection. Currently this is fixed // only for case of collapsed selection where we simply avoid calling // removeContants(). var range = this.getFieldObject().getRange(); if (!range.isCollapsed()) { range.removeContents(); } node = range.insertNode(node, false); } // Place the cursor to the right of the // equation image. goog.editor.range.placeCursorNextTo(node, false); this.getFieldObject().dispatchChange(); };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // All Rights Reserved. /** * @fileoverview Plugin to handle Remove Formatting. * */ goog.provide('goog.editor.plugins.RemoveFormatting'); goog.require('goog.dom'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.Range'); goog.require('goog.dom.TagName'); goog.require('goog.editor.BrowserFeature'); goog.require('goog.editor.Plugin'); goog.require('goog.editor.node'); goog.require('goog.editor.range'); goog.require('goog.string'); /** * A plugin to handle removing formatting from selected text. * @constructor * @extends {goog.editor.Plugin} */ goog.editor.plugins.RemoveFormatting = function() { goog.editor.Plugin.call(this); /** * Optional function to perform remove formatting in place of the * provided removeFormattingWorker_. * @type {?function(string): string} * @private */ this.optRemoveFormattingFunc_ = null; }; goog.inherits(goog.editor.plugins.RemoveFormatting, goog.editor.Plugin); /** * The editor command this plugin in handling. * @type {string} */ goog.editor.plugins.RemoveFormatting.REMOVE_FORMATTING_COMMAND = '+removeFormat'; /** * Regular expression that matches a block tag name. * @type {RegExp} * @private */ goog.editor.plugins.RemoveFormatting.BLOCK_RE_ = /^(DIV|TR|LI|BLOCKQUOTE|H\d|PRE|XMP)/; /** * Appends a new line to a string buffer. * @param {Array.<string>} sb The string buffer to add to. * @private */ goog.editor.plugins.RemoveFormatting.appendNewline_ = function(sb) { sb.push('<br>'); }; /** * Create a new range delimited by the start point of the first range and * the end point of the second range. * @param {goog.dom.AbstractRange} startRange Use the start point of this * range as the beginning of the new range. * @param {goog.dom.AbstractRange} endRange Use the end point of this * range as the end of the new range. * @return {goog.dom.AbstractRange} The new range. * @private */ goog.editor.plugins.RemoveFormatting.createRangeDelimitedByRanges_ = function( startRange, endRange) { return goog.dom.Range.createFromNodes( startRange.getStartNode(), startRange.getStartOffset(), endRange.getEndNode(), endRange.getEndOffset()); }; /** @override */ goog.editor.plugins.RemoveFormatting.prototype.getTrogClassId = function() { return 'RemoveFormatting'; }; /** @override */ goog.editor.plugins.RemoveFormatting.prototype.isSupportedCommand = function( command) { return command == goog.editor.plugins.RemoveFormatting.REMOVE_FORMATTING_COMMAND; }; /** @override */ goog.editor.plugins.RemoveFormatting.prototype.execCommandInternal = function(command, var_args) { if (command == goog.editor.plugins.RemoveFormatting.REMOVE_FORMATTING_COMMAND) { this.removeFormatting_(); } }; /** @override */ goog.editor.plugins.RemoveFormatting.prototype.handleKeyboardShortcut = function(e, key, isModifierPressed) { if (!isModifierPressed) { return false; } if (key == ' ') { this.getFieldObject().execCommand( goog.editor.plugins.RemoveFormatting.REMOVE_FORMATTING_COMMAND); return true; } return false; }; /** * Removes formatting from the current selection. Removes basic formatting * (B/I/U) using the browser's execCommand. Then extracts the html from the * selection to convert, calls either a client's specified removeFormattingFunc * callback or trogedit's general built-in removeFormattingWorker_, * and then replaces the current selection with the converted text. * @private */ goog.editor.plugins.RemoveFormatting.prototype.removeFormatting_ = function() { var range = this.getFieldObject().getRange(); if (range.isCollapsed()) { return; } // Get the html to format and send it off for formatting. Built in // removeFormat only strips some inline elements and some inline CSS styles var convFunc = this.optRemoveFormattingFunc_ || goog.bind(this.removeFormattingWorker_, this); this.convertSelectedHtmlText_(convFunc); // Do the execCommand last as it needs block elements removed to work // properly on background/fontColor in FF. There are, unfortunately, still // cases where background/fontColor are not removed here. var doc = this.getFieldDomHelper().getDocument(); doc.execCommand('RemoveFormat', false, undefined); if (goog.editor.BrowserFeature.ADDS_NBSPS_IN_REMOVE_FORMAT) { // WebKit converts spaces to non-breaking spaces when doing a RemoveFormat. // See: https://bugs.webkit.org/show_bug.cgi?id=14062 this.convertSelectedHtmlText_(function(text) { // This loses anything that might have legitimately been a non-breaking // space, but that's better than the alternative of only having non- // breaking spaces. // Old versions of WebKit (Safari 3, Chrome 1) incorrectly match /u00A0 // and newer versions properly match &nbsp;. var nbspRegExp = goog.userAgent.isVersion('528') ? /&nbsp;/g : /\u00A0/g; return text.replace(nbspRegExp, ' '); }); } }; /** * Finds the nearest ancestor of the node that is a table. * @param {Node} nodeToCheck Node to search from. * @return {Node} The table, or null if one was not found. * @private */ goog.editor.plugins.RemoveFormatting.prototype.getTableAncestor_ = function( nodeToCheck) { var fieldElement = this.getFieldObject().getElement(); while (nodeToCheck && nodeToCheck != fieldElement) { if (nodeToCheck.tagName == goog.dom.TagName.TABLE) { return nodeToCheck; } nodeToCheck = nodeToCheck.parentNode; } return null; }; /** * Replaces the contents of the selection with html. Does its best to maintain * the original selection. Also does its best to result in a valid DOM. * * TODO(user): See if there's any way to make this work on Ranges, and then * move it into goog.editor.range. The Firefox implementation uses execCommand * on the document, so must work on the actual selection. * * @param {string} html The html string to insert into the range. * @private */ goog.editor.plugins.RemoveFormatting.prototype.pasteHtml_ = function(html) { var range = this.getFieldObject().getRange(); var dh = this.getFieldDomHelper(); // Use markers to set the extent of the selection so that we can reselect it // afterwards. This works better than builtin range manipulation in FF and IE // because their implementations are so self-inconsistent and buggy. var startSpanId = goog.string.createUniqueString(); var endSpanId = goog.string.createUniqueString(); html = '<span id="' + startSpanId + '"></span>' + html + '<span id="' + endSpanId + '"></span>'; var dummyNodeId = goog.string.createUniqueString(); var dummySpanText = '<span id="' + dummyNodeId + '"></span>'; if (goog.editor.BrowserFeature.HAS_IE_RANGES) { // IE's selection often doesn't include the outermost tags. // We want to use pasteHTML to replace the range contents with the newly // unformatted text, so we have to check to make sure we aren't just // pasting into some stray tags. To do this, we first clear out the // contents of the range and then delete all empty nodes parenting the now // empty range. This way, the pasted contents are never re-embedded into // formated nodes. Pasting purely empty html does not work, since IE moves // the selection inside the next node, so we insert a dummy span. var textRange = range.getTextRange(0).getBrowserRangeObject(); textRange.pasteHTML(dummySpanText); var parent; while ((parent = textRange.parentElement()) && goog.editor.node.isEmpty(parent) && !goog.editor.node.isEditableContainer(parent)) { var tag = parent.nodeName; // We can't remove these table tags as it will invalidate the table dom. if (tag == goog.dom.TagName.TD || tag == goog.dom.TagName.TR || tag == goog.dom.TagName.TH) { break; } goog.dom.removeNode(parent); } textRange.pasteHTML(html); var dummySpan = dh.getElement(dummyNodeId); // If we entered the while loop above, the node has already been removed // since it was a child of parent and parent was removed. if (dummySpan) { goog.dom.removeNode(dummySpan); } } else if (goog.editor.BrowserFeature.HAS_W3C_RANGES) { // insertHtml and range.insertNode don't merge blocks correctly. // (e.g. if your selection spans two paragraphs) dh.getDocument().execCommand('insertImage', false, dummyNodeId); var dummyImageNodePattern = new RegExp('<[^<]*' + dummyNodeId + '[^>]*>'); var parent = this.getFieldObject().getRange().getContainerElement(); if (parent.nodeType == goog.dom.NodeType.TEXT) { // Opera sometimes returns a text node here. // TODO(user): perhaps we should modify getParentContainer? parent = parent.parentNode; } // We have to search up the DOM because in some cases, notably when // selecting li's within a list, execCommand('insertImage') actually splits // tags in such a way that parent that used to contain the selection does // not contain inserted image. while (!dummyImageNodePattern.test(parent.innerHTML)) { parent = parent.parentNode; } // Like the IE case above, sometimes the selection does not include the // outermost tags. For Gecko, we have already expanded the range so that // it does, so we can just replace the dummy image with the final html. // For WebKit, we use the same approach as we do with IE - we // inject a dummy span where we will eventually place the contents, and // remove parentNodes of the span while they are empty. if (goog.userAgent.GECKO) { goog.editor.node.replaceInnerHtml(parent, parent.innerHTML.replace(dummyImageNodePattern, html)); } else { goog.editor.node.replaceInnerHtml(parent, parent.innerHTML.replace(dummyImageNodePattern, dummySpanText)); var dummySpan = dh.getElement(dummyNodeId); parent = dummySpan; while ((parent = dummySpan.parentNode) && goog.editor.node.isEmpty(parent) && !goog.editor.node.isEditableContainer(parent)) { var tag = parent.nodeName; // We can't remove these table tags as it will invalidate the table dom. if (tag == goog.dom.TagName.TD || tag == goog.dom.TagName.TR || tag == goog.dom.TagName.TH) { break; } // We can't just remove parent since dummySpan is inside it, and we need // to keep dummy span around for the replacement. So we move the // dummySpan up as we go. goog.dom.insertSiblingAfter(dummySpan, parent); goog.dom.removeNode(parent); } goog.editor.node.replaceInnerHtml(parent, parent.innerHTML.replace(new RegExp(dummySpanText, 'i'), html)); } } var startSpan = dh.getElement(startSpanId); var endSpan = dh.getElement(endSpanId); goog.dom.Range.createFromNodes(startSpan, 0, endSpan, endSpan.childNodes.length).select(); goog.dom.removeNode(startSpan); goog.dom.removeNode(endSpan); }; /** * Gets the html inside the selection to send off for further processing. * * TODO(user): Make this general so that it can be moved into * goog.editor.range. The main reason it can't be moved is becuase we need to * get the range before we do the execCommand and continue to operate on that * same range (reasons are documented above). * * @param {goog.dom.AbstractRange} range The selection. * @return {string} The html string to format. * @private */ goog.editor.plugins.RemoveFormatting.prototype.getHtmlText_ = function(range) { var div = this.getFieldDomHelper().createDom('div'); var textRange = range.getBrowserRangeObject(); if (goog.editor.BrowserFeature.HAS_W3C_RANGES) { // Get the text to convert. div.appendChild(textRange.cloneContents()); } else if (goog.editor.BrowserFeature.HAS_IE_RANGES) { // Trim the whitespace on the ends of the range, so that it the container // will be the container of only the text content that we are changing. // This gets around issues in IE where the spaces are included in the // selection, but ignored sometimes by execCommand, and left orphaned. var rngText = range.getText(); // BRs get reported as \r\n, but only count as one character for moves. // Adjust the string so our move counter is correct. rngText = rngText.replace(/\r\n/g, '\r'); var rngTextLength = rngText.length; var left = rngTextLength - goog.string.trimLeft(rngText).length; var right = rngTextLength - goog.string.trimRight(rngText).length; textRange.moveStart('character', left); textRange.moveEnd('character', -right); var htmlText = textRange.htmlText; // Check if in pretag and fix up formatting so that new lines are preserved. if (textRange.queryCommandValue('formatBlock') == 'Formatted') { htmlText = goog.string.newLineToBr(textRange.htmlText); } div.innerHTML = htmlText; } // Get the innerHTML of the node instead of just returning the text above // so that its properly html escaped. return div.innerHTML; }; /** * Move the range so that it doesn't include any partially selected tables. * @param {goog.dom.AbstractRange} range The range to adjust. * @param {Node} startInTable Table node that the range starts in. * @param {Node} endInTable Table node that the range ends in. * @return {goog.dom.SavedCaretRange} Range to use to restore the * selection after we run our custom remove formatting. * @private */ goog.editor.plugins.RemoveFormatting.prototype.adjustRangeForTables_ = function(range, startInTable, endInTable) { // Create placeholders for the current selection so we can restore it // later. var savedCaretRange = goog.editor.range.saveUsingNormalizedCarets(range); var startNode = range.getStartNode(); var startOffset = range.getStartOffset(); var endNode = range.getEndNode(); var endOffset = range.getEndOffset(); var dh = this.getFieldDomHelper(); // Move start after the table. if (startInTable) { var textNode = dh.createTextNode(''); goog.dom.insertSiblingAfter(textNode, startInTable); startNode = textNode; startOffset = 0; } // Move end before the table. if (endInTable) { var textNode = dh.createTextNode(''); goog.dom.insertSiblingBefore(textNode, endInTable); endNode = textNode; endOffset = 0; } goog.dom.Range.createFromNodes(startNode, startOffset, endNode, endOffset).select(); return savedCaretRange; }; /** * Remove a caret from the dom and hide it in a safe place, so it can * be restored later via restoreCaretsFromCave. * @param {goog.dom.SavedCaretRange} caretRange The caret range to * get the carets from. * @param {boolean} isStart Whether this is the start or end caret. * @private */ goog.editor.plugins.RemoveFormatting.prototype.putCaretInCave_ = function( caretRange, isStart) { var cavedCaret = goog.dom.removeNode(caretRange.getCaret(isStart)); if (isStart) { this.startCaretInCave_ = cavedCaret; } else { this.endCaretInCave_ = cavedCaret; } }; /** * Restore carets that were hidden away by adding them back into the dom. * Note: this does not restore to the original dom location, as that * will likely have been modified with remove formatting. The only * guarentees here are that start will still be before end, and that * they will be in the editable region. This should only be used when * you don't actually intend to USE the caret again. * @private */ goog.editor.plugins.RemoveFormatting.prototype.restoreCaretsFromCave_ = function() { // To keep start before end, we put the end caret at the bottom of the field // and the start caret at the start of the field. var field = this.getFieldObject().getElement(); if (this.startCaretInCave_) { field.insertBefore(this.startCaretInCave_, field.firstChild); this.startCaretInCave_ = null; } if (this.endCaretInCave_) { field.appendChild(this.endCaretInCave_); this.endCaretInCave_ = null; } }; /** * Gets the html inside the current selection, passes it through the given * conversion function, and puts it back into the selection. * * @param {function(string): string} convertFunc A conversion function that * transforms an html string to new html string. * @private */ goog.editor.plugins.RemoveFormatting.prototype.convertSelectedHtmlText_ = function(convertFunc) { var range = this.getFieldObject().getRange(); // For multiple ranges, it is really hard to do our custom remove formatting // without invalidating other ranges. So instead of always losing the // content, this solution at least lets the browser do its own remove // formatting which works correctly most of the time. if (range.getTextRangeCount() > 1) { return; } if (goog.userAgent.GECKO) { // Determine if we need to handle tables, since they are special cases. // If the selection is entirely within a table, there is no extra // formatting removal we can do. If a table is fully selected, we will // just blow it away. If a table is only partially selected, we can // perform custom remove formatting only on the non table parts, since we // we can't just remove the parts and paste back into it (eg. we can't // inject html where a TR used to be). // If the selection contains the table and more, this is automatically // handled, but if just the table is selected, it can be tricky to figure // this case out, because of the numerous ways selections can be formed - // ex. if a table has a single tr with a single td with a single text node // in it, and the selection is (textNode: 0), (textNode: nextNode.length) // then the entire table is selected, even though the start and end aren't // the table itself. We are truly inside a table if the expanded endpoints // are still inside the table. // Expand the selection to include any outermost tags that weren't included // in the selection, but have the same visible selection. Stop expanding // if we reach the top level field. var expandedRange = goog.editor.range.expand(range, this.getFieldObject().getElement()); var startInTable = this.getTableAncestor_(expandedRange.getStartNode()); var endInTable = this.getTableAncestor_(expandedRange.getEndNode()); if (startInTable || endInTable) { if (startInTable == endInTable) { // We are fully contained in the same table, there is no extra // remove formatting that we can do, just return and run browser // formatting only. return; } // Adjust the range to not contain any partially selected tables, since // we don't want to run our custom remove formatting on them. var savedCaretRange = this.adjustRangeForTables_(range, startInTable, endInTable); // Hack alert!! // If start is not in a table, then the saved caret will get sent out // for uber remove formatting, and it will get blown away. This is // fine, except that we need to be able to re-create a range from the // savedCaretRange later on. So, we just remove it from the dom, and // put it back later so we can create a range later (not exactly in the // same spot, but don't worry we don't actually try to use it later) // and then it will be removed when we dispose the range. if (!startInTable) { this.putCaretInCave_(savedCaretRange, true); } if (!endInTable) { this.putCaretInCave_(savedCaretRange, false); } // Re-fetch the range, and re-expand it, since we just modified it. range = this.getFieldObject().getRange(); expandedRange = goog.editor.range.expand(range, this.getFieldObject().getElement()); } expandedRange.select(); range = expandedRange; } // Convert the selected text to the format-less version, paste back into // the selection. var text = this.getHtmlText_(range); this.pasteHtml_(convertFunc(text)); if (goog.userAgent.GECKO && savedCaretRange) { // If we moved the selection, move it back so the user can't tell we did // anything crazy and so the browser removeFormat that we call next // will operate on the entire originally selected range. range = this.getFieldObject().getRange(); this.restoreCaretsFromCave_(); var realSavedCaretRange = savedCaretRange.toAbstractRange(); var startRange = startInTable ? realSavedCaretRange : range; var endRange = endInTable ? realSavedCaretRange : range; var restoredRange = goog.editor.plugins.RemoveFormatting.createRangeDelimitedByRanges_( startRange, endRange); restoredRange.select(); savedCaretRange.dispose(); } }; /** * Does a best-effort attempt at clobbering all formatting that the * browser's execCommand couldn't clobber without being totally inefficient. * Attempts to convert visual line breaks to BRs. Leaves anchors that contain an * href and images. * Adapted from Gmail's MessageUtil's htmlToPlainText. http://go/messageutil.js * @param {string} html The original html of the message. * @return {string} The unformatted html, which is just text, br's, anchors and * images. * @private */ goog.editor.plugins.RemoveFormatting.prototype.removeFormattingWorker_ = function(html) { var el = goog.dom.createElement('div'); el.innerHTML = html; // Put everything into a string buffer to avoid lots of expensive string // concatenation along the way. var sb = []; var stack = [el.childNodes, 0]; // Keep separate stacks for places where we need to keep track of // how deeply embedded we are. These are analogous to the general stack. var preTagStack = []; var preTagLevel = 0; // Length of the prestack. var tableStack = []; var tableLevel = 0; // sp = stack pointer, pointing to the stack array. // decrement by 2 since the stack alternates node lists and // processed node counts for (var sp = 0; sp >= 0; sp -= 2) { // Check if we should pop the table level. var changedLevel = false; while (tableLevel > 0 && sp <= tableStack[tableLevel - 1]) { tableLevel--; changedLevel = true; } if (changedLevel) { goog.editor.plugins.RemoveFormatting.appendNewline_(sb); } // Check if we should pop the <pre>/<xmp> level. changedLevel = false; while (preTagLevel > 0 && sp <= preTagStack[preTagLevel - 1]) { preTagLevel--; changedLevel = true; } if (changedLevel) { goog.editor.plugins.RemoveFormatting.appendNewline_(sb); } // The list of of nodes to process at the current stack level. var nodeList = stack[sp]; // The number of nodes processed so far, stored in the stack immediately // following the node list for that stack level. var numNodesProcessed = stack[sp + 1]; while (numNodesProcessed < nodeList.length) { var node = nodeList[numNodesProcessed++]; var nodeName = node.nodeName; var formatted = this.getValueForNode(node); if (goog.isDefAndNotNull(formatted)) { sb.push(formatted); continue; } // TODO(user): Handle case 'EMBED' and case 'OBJECT'. switch (nodeName) { case '#text': // Note that IE does not preserve whitespace in the dom // values, even in a pre tag, so this is useless for IE. var nodeValue = preTagLevel > 0 ? node.nodeValue : goog.string.stripNewlines(node.nodeValue); nodeValue = goog.string.htmlEscape(nodeValue); sb.push(nodeValue); continue; case goog.dom.TagName.P: goog.editor.plugins.RemoveFormatting.appendNewline_(sb); goog.editor.plugins.RemoveFormatting.appendNewline_(sb); break; // break (not continue) so that child nodes are processed. case goog.dom.TagName.BR: goog.editor.plugins.RemoveFormatting.appendNewline_(sb); continue; case goog.dom.TagName.TABLE: goog.editor.plugins.RemoveFormatting.appendNewline_(sb); tableStack[tableLevel++] = sp; break; case goog.dom.TagName.PRE: case 'XMP': // This doesn't fully handle xmp, since // it doesn't actually ignore tags within the xmp tag. preTagStack[preTagLevel++] = sp; break; case goog.dom.TagName.STYLE: case goog.dom.TagName.SCRIPT: case goog.dom.TagName.SELECT: continue; case goog.dom.TagName.A: if (node.href && node.href != '') { sb.push("<a href='"); sb.push(node.href); sb.push("'>"); sb.push(this.removeFormattingWorker_(node.innerHTML)); sb.push('</a>'); continue; // Children taken care of. } else { break; // Take care of the children. } case goog.dom.TagName.IMG: sb.push("<img src='"); sb.push(node.src); sb.push("'"); // border=0 is a common way to not show a blue border around an image // that is wrapped by a link. If we remove that, the blue border will // show up, which to the user looks like adding format, not removing. if (node.border == '0') { sb.push(" border='0'"); } sb.push('>'); continue; case goog.dom.TagName.TD: // Don't add a space for the first TD, we only want spaces to // separate td's. if (node.previousSibling) { sb.push(' '); } break; case goog.dom.TagName.TR: // Don't add a newline for the first TR. if (node.previousSibling) { goog.editor.plugins.RemoveFormatting.appendNewline_(sb); } break; case goog.dom.TagName.DIV: var parent = node.parentNode; if (parent.firstChild == node && goog.editor.plugins.RemoveFormatting.BLOCK_RE_.test( parent.tagName)) { // If a DIV is the first child of another element that itself is a // block element, the DIV does not add a new line. break; } // Otherwise, the DIV does add a new line. Fall through. default: if (goog.editor.plugins.RemoveFormatting.BLOCK_RE_.test(nodeName)) { goog.editor.plugins.RemoveFormatting.appendNewline_(sb); } } // Recurse down the node. var children = node.childNodes; if (children.length > 0) { // Push the current state on the stack. stack[sp++] = nodeList; stack[sp++] = numNodesProcessed; // Iterate through the children nodes. nodeList = children; numNodesProcessed = 0; } } } // Replace &nbsp; with white space. return goog.string.normalizeSpaces(sb.join('')); }; /** * Handle per node special processing if neccessary. If this function returns * null then standard cleanup is applied. Otherwise this node and all children * are assumed to be cleaned. * NOTE(user): If an alternate RemoveFormatting processor is provided * (setRemoveFormattingFunc()), this will no longer work. * @param {Element} node The node to clean. * @return {?string} The HTML strig representation of the cleaned data. */ goog.editor.plugins.RemoveFormatting.prototype.getValueForNode = function( node) { return null; }; /** * Sets a function to be used for remove formatting. * @param {function(string): string} removeFormattingFunc - A function that * takes a string of html and returns a string of html that does any other * formatting changes desired. Use this only if trogedit's behavior doesn't * meet your needs. */ goog.editor.plugins.RemoveFormatting.prototype.setRemoveFormattingFunc = function(removeFormattingFunc) { this.optRemoveFormattingFunc_ = removeFormattingFunc; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview An abstract superclass for TrogEdit dialog plugins. Each * Trogedit dialog has its own plugin. * * @author nicksantos@google.com (Nick Santos) * @author marcosalmeida@google.com (Marcos Almeida) */ goog.provide('goog.editor.plugins.AbstractDialogPlugin'); goog.provide('goog.editor.plugins.AbstractDialogPlugin.EventType'); goog.require('goog.dom'); goog.require('goog.dom.Range'); goog.require('goog.editor.Field.EventType'); goog.require('goog.editor.Plugin'); goog.require('goog.editor.range'); goog.require('goog.events'); goog.require('goog.ui.editor.AbstractDialog.EventType'); // *** Public interface ***************************************************** // /** * An abstract superclass for a Trogedit plugin that creates exactly one * dialog. By default dialogs are not reused -- each time execCommand is called, * a new instance of the dialog object is created (and the old one disposed of). * To enable reusing of the dialog object, subclasses should call * setReuseDialog() after calling the superclass constructor. * @param {string} command The command that this plugin handles. * @constructor * @extends {goog.editor.Plugin} */ goog.editor.plugins.AbstractDialogPlugin = function(command) { goog.editor.Plugin.call(this); this.command_ = command; }; goog.inherits(goog.editor.plugins.AbstractDialogPlugin, goog.editor.Plugin); /** @override */ goog.editor.plugins.AbstractDialogPlugin.prototype.isSupportedCommand = function(command) { return command == this.command_; }; /** * Handles execCommand. Dialog plugins don't make any changes when they open a * dialog, just when the dialog closes (because only modal dialogs are * supported). Hence this method does not dispatch the change events that the * superclass method does. * @param {string} command The command to execute. * @param {...*} var_args Any additional parameters needed to * execute the command. * @return {*} The result of the execCommand, if any. * @override */ goog.editor.plugins.AbstractDialogPlugin.prototype.execCommand = function( command, var_args) { return this.execCommandInternal.apply(this, arguments); }; // *** Events *************************************************************** // /** * Event type constants for events the dialog plugins fire. * @enum {string} */ goog.editor.plugins.AbstractDialogPlugin.EventType = { // This event is fired when a dialog has been opened. OPENED: 'dialogOpened', // This event is fired when a dialog has been closed. CLOSED: 'dialogClosed' }; // *** Protected interface ************************************************** // /** * Creates a new instance of this plugin's dialog. Must be overridden by * subclasses. * @param {!goog.dom.DomHelper} dialogDomHelper The dom helper to be used to * create the dialog. * @param {*=} opt_arg The dialog specific argument. Concrete subclasses should * declare a specific type. * @return {goog.ui.editor.AbstractDialog} The newly created dialog. * @protected */ goog.editor.plugins.AbstractDialogPlugin.prototype.createDialog = goog.abstractMethod; /** * Returns the current dialog that was created and opened by this plugin. * @return {goog.ui.editor.AbstractDialog} The current dialog that was created * and opened by this plugin. * @protected */ goog.editor.plugins.AbstractDialogPlugin.prototype.getDialog = function() { return this.dialog_; }; /** * Sets whether this plugin should reuse the same instance of the dialog each * time execCommand is called or create a new one. This is intended for use by * subclasses only, hence protected. * @param {boolean} reuse Whether to reuse the dialog. * @protected */ goog.editor.plugins.AbstractDialogPlugin.prototype.setReuseDialog = function(reuse) { this.reuseDialog_ = reuse; }; /** * Handles execCommand by opening the dialog. Dispatches * {@link goog.editor.plugins.AbstractDialogPlugin.EventType.OPENED} after the * dialog is shown. * @param {string} command The command to execute. * @param {*=} opt_arg The dialog specific argument. Should be the same as * {@link createDialog}. * @return {*} Always returns true, indicating the dialog was shown. * @protected * @override */ goog.editor.plugins.AbstractDialogPlugin.prototype.execCommandInternal = function(command, opt_arg) { // If this plugin should not reuse dialog instances, first dispose of the // previous dialog. if (!this.reuseDialog_) { this.disposeDialog_(); } // If there is no dialog yet (or we aren't reusing the previous one), create // one. if (!this.dialog_) { this.dialog_ = this.createDialog( // TODO(user): Add Field.getAppDomHelper. (Note dom helper will // need to be updated if setAppWindow is called by clients.) goog.dom.getDomHelper(this.getFieldObject().getAppWindow()), opt_arg); } // Since we're opening a dialog, we need to clear the selection because the // focus will be going to the dialog, and if we leave an selection in the // editor while another selection is active in the dialog as the user is // typing, some browsers will screw up the original selection. But first we // save it so we can restore it when the dialog closes. // getRange may return null if there is no selection in the field. var tempRange = this.getFieldObject().getRange(); // saveUsingDom() did not work as well as saveUsingNormalizedCarets(), // not sure why. this.savedRange_ = tempRange && goog.editor.range.saveUsingNormalizedCarets( tempRange); goog.dom.Range.clearSelection( this.getFieldObject().getEditableDomHelper().getWindow()); // Listen for the dialog closing so we can clean up. goog.events.listenOnce(this.dialog_, goog.ui.editor.AbstractDialog.EventType.AFTER_HIDE, this.handleAfterHide, false, this); this.getFieldObject().setModalMode(true); this.dialog_.show(); this.dispatchEvent(goog.editor.plugins.AbstractDialogPlugin.EventType.OPENED); // Since the selection has left the document, dispatch a selection // change event. this.getFieldObject().dispatchSelectionChangeEvent(); return true; }; /** * Cleans up after the dialog has closed, including restoring the selection to * what it was before the dialog was opened. If a subclass modifies the editable * field's content such that the original selection is no longer valid (usually * the case when the user clicks OK, and sometimes also on Cancel), it is that * subclass' responsibility to place the selection in the desired place during * the OK or Cancel (or other) handler. In that case, this method will leave the * selection in place. * @param {goog.events.Event} e The AFTER_HIDE event object. * @protected */ goog.editor.plugins.AbstractDialogPlugin.prototype.handleAfterHide = function( e) { this.getFieldObject().setModalMode(false); this.restoreOriginalSelection(); if (!this.reuseDialog_) { this.disposeDialog_(); } this.dispatchEvent(goog.editor.plugins.AbstractDialogPlugin.EventType.CLOSED); // Since the selection has returned to the document, dispatch a selection // change event. this.getFieldObject().dispatchSelectionChangeEvent(); // When the dialog closes due to pressing enter or escape, that happens on the // keydown event. But the browser will still fire a keyup event after that, // which is caught by the editable field and causes it to try to fire a // selection change event. To avoid that, we "debounce" the selection change // event, meaning the editable field will not fire that event if the keyup // that caused it immediately after this dialog was hidden ("immediately" // means a small number of milliseconds defined by the editable field). this.getFieldObject().debounceEvent( goog.editor.Field.EventType.SELECTIONCHANGE); }; /** * Restores the selection in the editable field to what it was before the dialog * was opened. This is not guaranteed to work if the contents of the field * have changed. * @protected */ goog.editor.plugins.AbstractDialogPlugin.prototype.restoreOriginalSelection = function() { this.getFieldObject().restoreSavedRange(this.savedRange_); this.savedRange_ = null; }; /** * Cleans up the structure used to save the original selection before the dialog * was opened. Should be used by subclasses that don't restore the original * selection via restoreOriginalSelection. * @protected */ goog.editor.plugins.AbstractDialogPlugin.prototype.disposeOriginalSelection = function() { if (this.savedRange_) { this.savedRange_.dispose(); this.savedRange_ = null; } }; /** @override */ goog.editor.plugins.AbstractDialogPlugin.prototype.disposeInternal = function() { this.disposeDialog_(); goog.base(this, 'disposeInternal'); }; // *** Private implementation *********************************************** // /** * The command that this plugin handles. * @type {string} * @private */ goog.editor.plugins.AbstractDialogPlugin.prototype.command_; /** * The current dialog that was created and opened by this plugin. * @type {goog.ui.editor.AbstractDialog} * @private */ goog.editor.plugins.AbstractDialogPlugin.prototype.dialog_; /** * Whether this plugin should reuse the same instance of the dialog each time * execCommand is called or create a new one. * @type {boolean} * @private */ goog.editor.plugins.AbstractDialogPlugin.prototype.reuseDialog_ = false; /** * Mutex to prevent recursive calls to disposeDialog_. * @type {boolean} * @private */ goog.editor.plugins.AbstractDialogPlugin.prototype.isDisposingDialog_ = false; /** * SavedRange representing the selection before the dialog was opened. * @type {goog.dom.SavedRange} * @private */ goog.editor.plugins.AbstractDialogPlugin.prototype.savedRange_; /** * Disposes of the dialog if needed. It is this abstract class' responsibility * to dispose of the dialog. The "if needed" refers to the fact this method * might be called twice (nested calls, not sequential) in the dispose flow, so * if the dialog was already disposed once it should not be disposed again. * @private */ goog.editor.plugins.AbstractDialogPlugin.prototype.disposeDialog_ = function() { // Wrap disposing the dialog in a mutex. Otherwise disposing it would cause it // to get hidden (if it is still open) and fire AFTER_HIDE, which in // turn would cause the dialog to be disposed again (closure only flags an // object as disposed after the dispose call chain completes, so it doesn't // prevent recursive dispose calls). if (this.dialog_ && !this.isDisposingDialog_) { this.isDisposingDialog_ = true; this.dialog_.dispose(); this.dialog_ = null; this.isDisposingDialog_ = false; } };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Code for an UndoRedoState interface representing an undo and * redo action for a particular state change. To be used by * {@link goog.editor.plugins.UndoRedoManager}. * */ goog.provide('goog.editor.plugins.UndoRedoState'); goog.require('goog.events.EventTarget'); /** * Represents an undo and redo action for a particular state transition. * * @param {boolean} asynchronous Whether the undo or redo actions for this * state complete asynchronously. If true, then this state must fire * an ACTION_COMPLETED event when undo or redo is complete. * @constructor * @extends {goog.events.EventTarget} */ goog.editor.plugins.UndoRedoState = function(asynchronous) { goog.base(this); /** * Indicates if the undo or redo actions for this state complete * asynchronously. * @type {boolean} * @private */ this.asynchronous_ = asynchronous; }; goog.inherits(goog.editor.plugins.UndoRedoState, goog.events.EventTarget); /** * Event type for events indicating that this state has completed an undo or * redo operation. */ goog.editor.plugins.UndoRedoState.ACTION_COMPLETED = 'action_completed'; /** * @return {boolean} Whether or not the undo and redo actions of this state * complete asynchronously. If true, the state will fire an ACTION_COMPLETED * event when an undo or redo action is complete. */ goog.editor.plugins.UndoRedoState.prototype.isAsynchronous = function() { return this.asynchronous_; }; /** * Undoes the action represented by this state. */ goog.editor.plugins.UndoRedoState.prototype.undo = goog.abstractMethod; /** * Redoes the action represented by this state. */ goog.editor.plugins.UndoRedoState.prototype.redo = goog.abstractMethod; /** * Checks if two undo-redo states are the same. * @param {goog.editor.plugins.UndoRedoState} state The state to compare. * @return {boolean} Wether the two states are equal. */ goog.editor.plugins.UndoRedoState.prototype.equals = goog.abstractMethod;
JavaScript
// Copyright 2005 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Code for handling edit history (undo/redo). * */ goog.provide('goog.editor.plugins.UndoRedo'); goog.require('goog.debug.Logger'); goog.require('goog.dom'); goog.require('goog.dom.NodeOffset'); goog.require('goog.dom.Range'); goog.require('goog.editor.BrowserFeature'); goog.require('goog.editor.Command'); goog.require('goog.editor.Field.EventType'); goog.require('goog.editor.Plugin'); goog.require('goog.editor.node'); goog.require('goog.editor.plugins.UndoRedoManager'); goog.require('goog.editor.plugins.UndoRedoState'); goog.require('goog.events'); goog.require('goog.events.EventHandler'); /** * Encapsulates undo/redo logic using a custom undo stack (i.e. not browser * built-in). Browser built-in undo stacks are too flaky (e.g. IE's gets * clobbered on DOM modifications). Also, this allows interleaving non-editing * commands into the undo stack via the UndoRedoManager. * * @param {goog.editor.plugins.UndoRedoManager=} opt_manager An undo redo * manager to be used by this plugin. If none is provided one is created. * @constructor * @extends {goog.editor.Plugin} */ goog.editor.plugins.UndoRedo = function(opt_manager) { goog.editor.Plugin.call(this); this.setUndoRedoManager(opt_manager || new goog.editor.plugins.UndoRedoManager()); // Map of goog.editor.Field hashcode to goog.events.EventHandler this.eventHandlers_ = {}; this.currentStates_ = {}; /** * @type {?string} * @private */ this.initialFieldChange_ = null; /** * A copy of {@code goog.editor.plugins.UndoRedo.restoreState} bound to this, * used by undo-redo state objects to restore the state of an editable field. * @type {Function} * @see goog.editor.plugins.UndoRedo#restoreState * @private */ this.boundRestoreState_ = goog.bind(this.restoreState, this); }; goog.inherits(goog.editor.plugins.UndoRedo, goog.editor.Plugin); /** * The logger for this class. * @type {goog.debug.Logger} * @protected * @override */ goog.editor.plugins.UndoRedo.prototype.logger = goog.debug.Logger.getLogger('goog.editor.plugins.UndoRedo'); /** * The {@code UndoState_} whose change is in progress, null if an undo or redo * is not in progress. * * @type {goog.editor.plugins.UndoRedo.UndoState_?} * @private */ goog.editor.plugins.UndoRedo.prototype.inProgressUndo_ = null; /** * The undo-redo stack manager used by this plugin. * @type {goog.editor.plugins.UndoRedoManager} * @private */ goog.editor.plugins.UndoRedo.prototype.undoManager_; /** * The key for the event listener handling state change events from the * undo-redo manager. * @type {goog.events.Key} * @private */ goog.editor.plugins.UndoRedo.prototype.managerStateChangeKey_; /** * Commands implemented by this plugin. * @enum {string} */ goog.editor.plugins.UndoRedo.COMMAND = { UNDO: '+undo', REDO: '+redo' }; /** * Inverse map of execCommand strings to * {@link goog.editor.plugins.UndoRedo.COMMAND} constants. Used to determine * whether a string corresponds to a command this plugin handles in O(1) time. * @type {Object} * @private */ goog.editor.plugins.UndoRedo.SUPPORTED_COMMANDS_ = goog.object.transpose(goog.editor.plugins.UndoRedo.COMMAND); /** * Set the max undo stack depth (not the real memory usage). * @param {number} depth Depth of the stack. */ goog.editor.plugins.UndoRedo.prototype.setMaxUndoDepth = function(depth) { this.undoManager_.setMaxUndoDepth(depth); }; /** * Set the undo-redo manager used by this plugin. Any state on a previous * undo-redo manager is lost. * @param {goog.editor.plugins.UndoRedoManager} manager The undo-redo manager. */ goog.editor.plugins.UndoRedo.prototype.setUndoRedoManager = function(manager) { if (this.managerStateChangeKey_) { goog.events.unlistenByKey(this.managerStateChangeKey_); } this.undoManager_ = manager; this.managerStateChangeKey_ = goog.events.listen(this.undoManager_, goog.editor.plugins.UndoRedoManager.EventType.STATE_CHANGE, this.dispatchCommandValueChange_, false, this); }; /** * Whether the string corresponds to a command this plugin handles. * @param {string} command Command string to check. * @return {boolean} Whether the string corresponds to a command * this plugin handles. * @override */ goog.editor.plugins.UndoRedo.prototype.isSupportedCommand = function(command) { return command in goog.editor.plugins.UndoRedo.SUPPORTED_COMMANDS_; }; /** * Unregisters and disables the fieldObject with this plugin. Thie does *not* * clobber the undo stack for the fieldObject though. * TODO(user): For the multifield version, we really should add a way to * ignore undo actions on field's that have been made uneditable. * This is probably as simple as skipping over entries in the undo stack * that have a hashcode of an uneditable field. * @param {goog.editor.Field} fieldObject The field to register with the plugin. * @override */ goog.editor.plugins.UndoRedo.prototype.unregisterFieldObject = function( fieldObject) { this.disable(fieldObject); this.setFieldObject(null); }; /** * This is so subclasses can deal with multifield undo-redo. * @return {goog.editor.Field} The active field object for this field. This is * the one registered field object for the single-plugin case and the * focused field for the multi-field plugin case. */ goog.editor.plugins.UndoRedo.prototype.getCurrentFieldObject = function() { return this.getFieldObject(); }; /** * This is so subclasses can deal with multifield undo-redo. * @param {string} fieldHashCode The Field's hashcode. * @return {goog.editor.Field} The field object with the hashcode. */ goog.editor.plugins.UndoRedo.prototype.getFieldObjectForHash = function( fieldHashCode) { // With single field undoredo, there's only one Field involved. return this.getFieldObject(); }; /** * This is so subclasses can deal with multifield undo-redo. * @return {goog.editor.Field} Target for COMMAND_VALUE_CHANGE events. */ goog.editor.plugins.UndoRedo.prototype.getCurrentEventTarget = function() { return this.getFieldObject(); }; /** @override */ goog.editor.plugins.UndoRedo.prototype.enable = function(fieldObject) { if (this.isEnabled(fieldObject)) { return; } // Don't want pending delayed changes from when undo-redo was disabled // firing after undo-redo is enabled since they might cause undo-redo stack // updates. fieldObject.clearDelayedChange(); var eventHandler = new goog.events.EventHandler(this); // TODO(user): From ojan during a code review: // The beforechange handler is meant to be there so you can grab the cursor // position *before* the change is made as that's where you want the cursor to // be after an undo. // // It kinda looks like updateCurrentState_ doesn't do that correctly right // now, but it really should be fixed to do so. The cursor position stored in // the state should be the cursor position before any changes are made, not // the cursor position when the change finishes. // // It also seems like the if check below is just a bad one. We should do this // for browsers that use mutation events as well even though the beforechange // happens too late...maybe not. I don't know about this. if (!goog.editor.BrowserFeature.USE_MUTATION_EVENTS) { // We don't listen to beforechange in mutation-event browsers because // there we fire beforechange, then syncronously file change. The point // of before change is to capture before the user has changed anything. eventHandler.listen(fieldObject, goog.editor.Field.EventType.BEFORECHANGE, this.handleBeforeChange_); } eventHandler.listen(fieldObject, goog.editor.Field.EventType.DELAYEDCHANGE, this.handleDelayedChange_); eventHandler.listen(fieldObject, goog.editor.Field.EventType.BLUR, this.handleBlur_); this.eventHandlers_[fieldObject.getHashCode()] = eventHandler; // We want to capture the initial state of a Trogedit field before any // editing has happened. This is necessary so that we can undo the first // change to a field, even if we don't handle beforeChange. this.updateCurrentState_(fieldObject); }; /** @override */ goog.editor.plugins.UndoRedo.prototype.disable = function(fieldObject) { // Process any pending changes so we don't lose any undo-redo states that we // want prior to disabling undo-redo. fieldObject.clearDelayedChange(); var eventHandler = this.eventHandlers_[fieldObject.getHashCode()]; if (eventHandler) { eventHandler.dispose(); delete this.eventHandlers_[fieldObject.getHashCode()]; } // We delete the current state of the field on disable. When we re-enable // the state will be re-fetched. In most cases the content will be the same, // but this allows us to pick up changes while not editable. That way, when // undoing after starting an editable session, you can always undo to the // state you started in. Given this sequence of events: // Make editable // Type 'anakin' // Make not editable // Set HTML to be 'padme' // Make editable // Type 'dark side' // Undo // Without re-snapshoting current state on enable, the undo would go from // 'dark-side' -> 'anakin', rather than 'dark-side' -> 'padme'. You couldn't // undo the field to the state that existed immediately after it was made // editable for the second time. if (this.currentStates_[fieldObject.getHashCode()]) { delete this.currentStates_[fieldObject.getHashCode()]; } }; /** @override */ goog.editor.plugins.UndoRedo.prototype.isEnabled = function(fieldObject) { // All enabled plugins have a eventHandler so reuse that map rather than // storing additional enabled state. return !!this.eventHandlers_[fieldObject.getHashCode()]; }; /** @override */ goog.editor.plugins.UndoRedo.prototype.disposeInternal = function() { goog.editor.plugins.UndoRedo.superClass_.disposeInternal.call(this); for (var hashcode in this.eventHandlers_) { this.eventHandlers_[hashcode].dispose(); delete this.eventHandlers_[hashcode]; } this.setFieldObject(null); if (this.undoManager_) { this.undoManager_.dispose(); delete this.undoManager_; } }; /** @override */ goog.editor.plugins.UndoRedo.prototype.getTrogClassId = function() { return 'UndoRedo'; }; /** @override */ goog.editor.plugins.UndoRedo.prototype.execCommand = function(command, var_args) { if (command == goog.editor.plugins.UndoRedo.COMMAND.UNDO) { this.undoManager_.undo(); } else if (command == goog.editor.plugins.UndoRedo.COMMAND.REDO) { this.undoManager_.redo(); } }; /** @override */ goog.editor.plugins.UndoRedo.prototype.queryCommandValue = function(command) { var state = null; if (command == goog.editor.plugins.UndoRedo.COMMAND.UNDO) { state = this.undoManager_.hasUndoState(); } else if (command == goog.editor.plugins.UndoRedo.COMMAND.REDO) { state = this.undoManager_.hasRedoState(); } return state; }; /** * Dispatches the COMMAND_VALUE_CHANGE event on the editable field or the field * manager, as appropriate. * Note: Really, people using multi field mode should be listening directly * to the undo-redo manager for events. * @private */ goog.editor.plugins.UndoRedo.prototype.dispatchCommandValueChange_ = function() { var eventTarget = this.getCurrentEventTarget(); eventTarget.dispatchEvent({ type: goog.editor.Field.EventType.COMMAND_VALUE_CHANGE, commands: [goog.editor.plugins.UndoRedo.COMMAND.REDO, goog.editor.plugins.UndoRedo.COMMAND.UNDO]}); }; /** * Restores the state of the editable field. * @param {goog.editor.plugins.UndoRedo.UndoState_} state The state initiating * the restore. * @param {string} content The content to restore. * @param {goog.editor.plugins.UndoRedo.CursorPosition_?} cursorPosition * The cursor position within the content. */ goog.editor.plugins.UndoRedo.prototype.restoreState = function( state, content, cursorPosition) { // Fire any pending changes to get the current field state up to date and // then stop listening to changes while doing the undo/redo. var fieldObj = this.getFieldObjectForHash(state.fieldHashCode); if (!fieldObj) { return; } // Fires any pending changes, and stops the change events. Still want to // dispatch before change, as a change is being made and the change event // will be manually dispatched below after the new content has been restored // (also restarting change events). fieldObj.stopChangeEvents(true, true); // To prevent the situation where we stop change events and then an exception // happens before we can restart change events, the following code must be in // a try-finally block. try { fieldObj.dispatchBeforeChange(); // Restore the state fieldObj.execCommand(goog.editor.Command.CLEAR_LOREM, true); // We specifically set the raw innerHTML of the field here as that's what // we get from the field when we save an undo/redo state. There's // no need to clean/unclean the contents in either direction. goog.editor.node.replaceInnerHtml(fieldObj.getElement(), content); if (cursorPosition) { cursorPosition.select(); } var previousFieldObject = this.getCurrentFieldObject(); fieldObj.focus(); // Apps that integrate their undo-redo with Trogedit may be // in a state where there is no previous field object (no field focused at // the time of undo), so check for existence first. if (previousFieldObject && previousFieldObject.getHashCode() != state.fieldHashCode) { previousFieldObject.execCommand(goog.editor.Command.UPDATE_LOREM); } // We need to update currentState_ to reflect the change. this.currentStates_[state.fieldHashCode].setUndoState( content, cursorPosition); } catch (e) { this.logger.severe('Error while restoring undo state', e); } finally { // Clear the delayed change event, set flag so we know not to act on it. this.inProgressUndo_ = state; // Notify the editor that we've changed (fire autosave). // Note that this starts up change events again, so we don't have to // manually do so even though we stopped change events above. fieldObj.dispatchChange(); fieldObj.dispatchSelectionChangeEvent(); } }; /** * @override */ goog.editor.plugins.UndoRedo.prototype.handleKeyboardShortcut = function(e, key, isModifierPressed) { if (isModifierPressed) { var command; if (key == 'z') { command = e.shiftKey ? goog.editor.plugins.UndoRedo.COMMAND.REDO : goog.editor.plugins.UndoRedo.COMMAND.UNDO; } else if (key == 'y') { command = goog.editor.plugins.UndoRedo.COMMAND.REDO; } if (command) { // In the case where Trogedit shares its undo redo stack with another // application it's possible that an undo or redo will not be for an // goog.editor.Field. In this case we don't want to go through the // goog.editor.Field execCommand flow which stops and restarts events on // the current field. Only Trogedit UndoState's have a fieldHashCode so // use that to distinguish between Trogedit and other states. var state = command == goog.editor.plugins.UndoRedo.COMMAND.UNDO ? this.undoManager_.undoPeek() : this.undoManager_.redoPeek(); if (state && state.fieldHashCode) { this.getCurrentFieldObject().execCommand(command); } else { this.execCommand(command); } return true; } } return false; }; /** * Clear the undo/redo stack. */ goog.editor.plugins.UndoRedo.prototype.clearHistory = function() { // Fire all pending change events, so that they don't come back // asynchronously to fill the queue. this.getFieldObject().stopChangeEvents(true, true); this.undoManager_.clearHistory(); this.getFieldObject().startChangeEvents(); }; /** * Refreshes the current state of the editable field as maintained by undo-redo, * without adding any undo-redo states to the stack. * @param {goog.editor.Field} fieldObject The editable field. */ goog.editor.plugins.UndoRedo.prototype.refreshCurrentState = function( fieldObject) { if (this.isEnabled(fieldObject)) { if (this.currentStates_[fieldObject.getHashCode()]) { delete this.currentStates_[fieldObject.getHashCode()]; } this.updateCurrentState_(fieldObject); } }; /** * Before the field changes, we want to save the state. * @param {goog.events.Event} e The event. * @private */ goog.editor.plugins.UndoRedo.prototype.handleBeforeChange_ = function(e) { if (this.inProgressUndo_) { // We are in between a previous undo and its delayed change event. // Continuing here clobbers the redo stack. // This does mean that if you are trying to undo/redo really quickly, it // will be gated by the speed of delayed change events. return; } var fieldObj = /** @type {goog.editor.Field} */ (e.target); var fieldHashCode = fieldObj.getHashCode(); if (this.initialFieldChange_ != fieldHashCode) { this.initialFieldChange_ = fieldHashCode; this.updateCurrentState_(fieldObj); } }; /** * After some idle time, we want to save the state. * @param {goog.events.Event} e The event. * @private */ goog.editor.plugins.UndoRedo.prototype.handleDelayedChange_ = function(e) { // This was undo making a change, don't add it BACK into the history if (this.inProgressUndo_) { // Must clear this.inProgressUndo_ before dispatching event because the // dispatch can cause another, queued undo that should be allowed to go // through. var state = this.inProgressUndo_; this.inProgressUndo_ = null; state.dispatchEvent(goog.editor.plugins.UndoRedoState.ACTION_COMPLETED); return; } this.updateCurrentState_(/** @type {goog.editor.Field} */ (e.target)); }; /** * When the user blurs away, we need to save the state on that field. * @param {goog.events.Event} e The event. * @private */ goog.editor.plugins.UndoRedo.prototype.handleBlur_ = function(e) { var fieldObj = /** @type {goog.editor.Field} */ (e.target); if (fieldObj) { fieldObj.clearDelayedChange(); } }; /** * Returns the goog.editor.plugins.UndoRedo.CursorPosition_ for the current * selection in the given Field. * @param {goog.editor.Field} fieldObj The field object. * @return {goog.editor.plugins.UndoRedo.CursorPosition_} The CursorPosition_ or * null if there is no valid selection. * @private */ goog.editor.plugins.UndoRedo.prototype.getCursorPosition_ = function(fieldObj) { var cursorPos = new goog.editor.plugins.UndoRedo.CursorPosition_(fieldObj); if (!cursorPos.isValid()) { return null; } return cursorPos; }; /** * Helper method for saving state. * @param {goog.editor.Field} fieldObj The field object. * @private */ goog.editor.plugins.UndoRedo.prototype.updateCurrentState_ = function( fieldObj) { var fieldHashCode = fieldObj.getHashCode(); // We specifically grab the raw innerHTML of the field here as that's what // we would set on the field in the case of an undo/redo operation. There's // no need to clean/unclean the contents in either direction. In the case of // lorem ipsum being used, we want to capture the effective state (empty, no // cursor position) rather than capturing the lorem html. var content, cursorPos; if (fieldObj.queryCommandValue(goog.editor.Command.USING_LOREM)) { content = ''; cursorPos = null; } else { content = fieldObj.getElement().innerHTML; cursorPos = this.getCursorPosition_(fieldObj); } var currentState = this.currentStates_[fieldHashCode]; if (currentState) { // Don't create states if the content hasn't changed (spurious // delayed change). This can happen when lorem is cleared, for example. if (currentState.undoContent_ == content) { return; } else if (content == '' || currentState.undoContent_ == '') { // If lorem ipsum is on we say the contents are the empty string. However, // for an empty text shape with focus, the empty contents might not be // the same, depending on plugins. We want these two empty states to be // considered identical because to the user they are indistinguishable, // so we use fieldObj.getInjectableContents to map between them. // We cannot use getInjectableContents when first creating the undo // content for a field with lorem, because on enable when this is first // called we can't guarantee plugin registration order, so the // injectableContents at that time might not match the final // injectableContents. var emptyContents = fieldObj.getInjectableContents('', {}); if (content == emptyContents && currentState.undoContent_ == '' || currentState.undoContent_ == emptyContents && content == '') { return; } } currentState.setRedoState(content, cursorPos); this.undoManager_.addState(currentState); } this.currentStates_[fieldHashCode] = new goog.editor.plugins.UndoRedo.UndoState_(fieldHashCode, content, cursorPos, this.boundRestoreState_); }; /** * This object encapsulates the state of an editable field. * * @param {string} fieldHashCode String the id of the field we're saving the * content of. * @param {string} content String the actual text we're saving. * @param {goog.editor.plugins.UndoRedo.CursorPosition_?} cursorPosition * CursorPosLite object for the cursor position in the field. * @param {Function} restore The function used to restore editable field state. * @private * @constructor * @extends {goog.editor.plugins.UndoRedoState} */ goog.editor.plugins.UndoRedo.UndoState_ = function(fieldHashCode, content, cursorPosition, restore) { goog.editor.plugins.UndoRedoState.call(this, true); /** * The hash code for the field whose content is being saved. * @type {string} */ this.fieldHashCode = fieldHashCode; /** * The bound copy of {@code goog.editor.plugins.UndoRedo.restoreState} used by * this state. * @type {Function} * @private */ this.restore_ = restore; this.setUndoState(content, cursorPosition); }; goog.inherits(goog.editor.plugins.UndoRedo.UndoState_, goog.editor.plugins.UndoRedoState); /** * The content to restore on undo. * @type {string} * @private */ goog.editor.plugins.UndoRedo.UndoState_.prototype.undoContent_; /** * The cursor position to restore on undo. * @type {goog.editor.plugins.UndoRedo.CursorPosition_?} * @private */ goog.editor.plugins.UndoRedo.UndoState_.prototype.undoCursorPosition_; /** * The content to restore on redo, undefined until the state is pushed onto the * undo stack. * @type {string|undefined} * @private */ goog.editor.plugins.UndoRedo.UndoState_.prototype.redoContent_; /** * The cursor position to restore on redo, undefined until the state is pushed * onto the undo stack. * @type {goog.editor.plugins.UndoRedo.CursorPosition_|null|undefined} * @private */ goog.editor.plugins.UndoRedo.UndoState_.prototype.redoCursorPosition_; /** * Performs the undo operation represented by this state. * @override */ goog.editor.plugins.UndoRedo.UndoState_.prototype.undo = function() { this.restore_(this, this.undoContent_, this.undoCursorPosition_); }; /** * Performs the redo operation represented by this state. * @override */ goog.editor.plugins.UndoRedo.UndoState_.prototype.redo = function() { this.restore_(this, this.redoContent_, this.redoCursorPosition_); }; /** * Updates the undo portion of this state. Should only be used to update the * current state of an editable field, which is not yet on the undo stack after * an undo or redo operation. You should never be modifying states on the stack! * @param {string} content The current content. * @param {goog.editor.plugins.UndoRedo.CursorPosition_?} cursorPosition * The current cursor position. */ goog.editor.plugins.UndoRedo.UndoState_.prototype.setUndoState = function( content, cursorPosition) { this.undoContent_ = content; this.undoCursorPosition_ = cursorPosition; }; /** * Adds redo information to this state. This method should be called before the * state is added onto the undo stack. * * @param {string} content The content to restore on a redo. * @param {goog.editor.plugins.UndoRedo.CursorPosition_?} cursorPosition * The cursor position to restore on a redo. */ goog.editor.plugins.UndoRedo.UndoState_.prototype.setRedoState = function( content, cursorPosition) { this.redoContent_ = content; this.redoCursorPosition_ = cursorPosition; }; /** * Checks if the *contents* of two * {@code goog.editor.plugins.UndoRedo.UndoState_}s are the same. We don't * bother checking the cursor position (that's not something we'd want to save * anyway). * @param {goog.editor.plugins.UndoRedoState} rhs The state to compare. * @return {boolean} Whether the contents are the same. * @override */ goog.editor.plugins.UndoRedo.UndoState_.prototype.equals = function(rhs) { return this.fieldHashCode == rhs.fieldHashCode && this.undoContent_ == rhs.undoContent_ && this.redoContent_ == rhs.redoContent_; }; /** * Stores the state of the selection in a way the survives DOM modifications * that don't modify the user-interactable content (e.g. making something bold * vs. typing a character). * * TODO(user): Completely get rid of this and use goog.dom.SavedCaretRange. * * @param {goog.editor.Field} field The field the selection is in. * @private * @constructor */ goog.editor.plugins.UndoRedo.CursorPosition_ = function(field) { this.field_ = field; var win = field.getEditableDomHelper().getWindow(); var range = field.getRange(); var isValidRange = !!range && range.isRangeInDocument() && range.getWindow() == win; range = isValidRange ? range : null; if (goog.editor.BrowserFeature.HAS_W3C_RANGES) { this.initW3C_(range); } else if (goog.editor.BrowserFeature.HAS_IE_RANGES) { this.initIE_(range); } }; /** * The standards compliant version keeps a list of childNode offsets. * @param {goog.dom.AbstractRange?} range The range to save. * @private */ goog.editor.plugins.UndoRedo.CursorPosition_.prototype.initW3C_ = function( range) { this.isValid_ = false; // TODO: Check if the range is in the field before trying to save it // for FF 3 contentEditable. if (!range) { return; } var anchorNode = range.getAnchorNode(); var focusNode = range.getFocusNode(); if (!anchorNode || !focusNode) { return; } var anchorOffset = range.getAnchorOffset(); var anchor = new goog.dom.NodeOffset(anchorNode, this.field_.getElement()); var focusOffset = range.getFocusOffset(); var focus = new goog.dom.NodeOffset(focusNode, this.field_.getElement()); // Test range direction. if (range.isReversed()) { this.startOffset_ = focus; this.startChildOffset_ = focusOffset; this.endOffset_ = anchor; this.endChildOffset_ = anchorOffset; } else { this.startOffset_ = anchor; this.startChildOffset_ = anchorOffset; this.endOffset_ = focus; this.endChildOffset_ = focusOffset; } this.isValid_ = true; }; /** * In IE, we just keep track of the text offset (number of characters). * @param {goog.dom.AbstractRange?} range The range to save. * @private */ goog.editor.plugins.UndoRedo.CursorPosition_.prototype.initIE_ = function( range) { this.isValid_ = false; if (!range) { return; } var ieRange = range.getTextRange(0).getBrowserRangeObject(); if (!goog.dom.contains(this.field_.getElement(), ieRange.parentElement())) { return; } // Create a range that encompasses the contentEditable region to serve // as a reference to form ranges below. var contentEditableRange = this.field_.getEditableDomHelper().getDocument().body.createTextRange(); contentEditableRange.moveToElementText(this.field_.getElement()); // startMarker is a range from the start of the contentEditable node to the // start of the current selection. var startMarker = ieRange.duplicate(); startMarker.collapse(true); startMarker.setEndPoint('StartToStart', contentEditableRange); this.startOffset_ = goog.editor.plugins.UndoRedo.CursorPosition_.computeEndOffsetIE_( startMarker); // endMarker is a range from the start of teh contentEditable node to the // end of the current selection. var endMarker = ieRange.duplicate(); endMarker.setEndPoint('StartToStart', contentEditableRange); this.endOffset_ = goog.editor.plugins.UndoRedo.CursorPosition_.computeEndOffsetIE_( endMarker); this.isValid_ = true; }; /** * @return {boolean} Whether this object is valid. */ goog.editor.plugins.UndoRedo.CursorPosition_.prototype.isValid = function() { return this.isValid_; }; /** * @return {string} A string representation of this object. * @override */ goog.editor.plugins.UndoRedo.CursorPosition_.prototype.toString = function() { if (goog.editor.BrowserFeature.HAS_W3C_RANGES) { return 'W3C:' + this.startOffset_.toString() + '\n' + this.startChildOffset_ + ':' + this.endOffset_.toString() + '\n' + this.endChildOffset_; } return 'IE:' + this.startOffset_ + ',' + this.endOffset_; }; /** * Makes the browser's selection match the cursor position. */ goog.editor.plugins.UndoRedo.CursorPosition_.prototype.select = function() { var range = this.getRange_(this.field_.getElement()); if (range) { if (goog.editor.BrowserFeature.HAS_IE_RANGES) { this.field_.getElement().focus(); } goog.dom.Range.createFromBrowserRange(range).select(); } }; /** * Get the range that encompases the the cursor position relative to a given * base node. * @param {Element} baseNode The node to get the cursor position relative to. * @return {Range|TextRange|null} The browser range for this position. * @private */ goog.editor.plugins.UndoRedo.CursorPosition_.prototype.getRange_ = function(baseNode) { if (goog.editor.BrowserFeature.HAS_W3C_RANGES) { var startNode = this.startOffset_.findTargetNode(baseNode); var endNode = this.endOffset_.findTargetNode(baseNode); if (!startNode || !endNode) { return null; } // Create range. return /** @type {Range} */ ( goog.dom.Range.createFromNodes(startNode, this.startChildOffset_, endNode, this.endChildOffset_).getBrowserRangeObject()); } // Create a collapsed selection at the start of the contentEditable region, // which the offsets were calculated relative to before. Note that we force // a text range here so we can use moveToElementText. var sel = baseNode.ownerDocument.body.createTextRange(); sel.moveToElementText(baseNode); sel.collapse(true); sel.moveEnd('character', this.endOffset_); sel.moveStart('character', this.startOffset_); return sel; }; /** * Compute the number of characters to the end of the range in IE. * @param {TextRange} range The range to compute an offset for. * @return {number} The number of characters to the end of the range. * @private */ goog.editor.plugins.UndoRedo.CursorPosition_.computeEndOffsetIE_ = function(range) { var testRange = range.duplicate(); // The number of offset characters is a little off depending on // what type of block elements happen to be between the start of the // textedit and the cursor position. We fudge the offset until the // two ranges match. var text = range.text; var guess = text.length; testRange.collapse(true); testRange.moveEnd('character', guess); // Adjust the range until the end points match. This doesn't quite // work if we're at the end of the field so we give up after a few // iterations. var diff; var numTries = 10; while (diff = testRange.compareEndPoints('EndToEnd', range)) { guess -= diff; testRange.moveEnd('character', -diff); --numTries; if (0 == numTries) { break; } } // When we set innerHTML, blank lines become a single space, causing // the cursor position to be off by one. So we accommodate for blank // lines. var offset = 0; var pos = text.indexOf('\n\r'); while (pos != -1) { ++offset; pos = text.indexOf('\n\r', pos + 1); } return guess + offset; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Handles applying header styles to text. * */ goog.provide('goog.editor.plugins.HeaderFormatter'); goog.require('goog.editor.Command'); goog.require('goog.editor.Plugin'); goog.require('goog.userAgent'); /** * Applies header styles to text. * @constructor * @extends {goog.editor.Plugin} */ goog.editor.plugins.HeaderFormatter = function() { goog.editor.Plugin.call(this); }; goog.inherits(goog.editor.plugins.HeaderFormatter, goog.editor.Plugin); /** @override */ goog.editor.plugins.HeaderFormatter.prototype.getTrogClassId = function() { return 'HeaderFormatter'; }; // TODO(user): Move execCommand functionality from basictextformatter into // here for headers. I'm not doing this now because it depends on the // switch statements in basictextformatter and we'll need to abstract that out // in order to seperate out any of the functions from basictextformatter. /** * Commands that can be passed as the optional argument to execCommand. * @enum {string} */ goog.editor.plugins.HeaderFormatter.HEADER_COMMAND = { H1: 'H1', H2: 'H2', H3: 'H3', H4: 'H4' }; /** * @override */ goog.editor.plugins.HeaderFormatter.prototype.handleKeyboardShortcut = function( e, key, isModifierPressed) { if (!isModifierPressed) { return false; } var command = null; switch (key) { case '1': command = goog.editor.plugins.HeaderFormatter.HEADER_COMMAND.H1; break; case '2': command = goog.editor.plugins.HeaderFormatter.HEADER_COMMAND.H2; break; case '3': command = goog.editor.plugins.HeaderFormatter.HEADER_COMMAND.H3; break; case '4': command = goog.editor.plugins.HeaderFormatter.HEADER_COMMAND.H4; break; } if (command) { this.getFieldObject().execCommand( goog.editor.Command.FORMAT_BLOCK, command); // Prevent default isn't enough to cancel tab navigation in FF. if (goog.userAgent.GECKO) { e.stopPropagation(); } return true; } return false; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Editor plugin to handle tab keys in lists to indent and * outdent. * * @author robbyw@google.com (Robby Walker) * @author ajp@google.com (Andy Perelson) */ goog.provide('goog.editor.plugins.ListTabHandler'); goog.require('goog.dom.TagName'); goog.require('goog.editor.Command'); goog.require('goog.editor.plugins.AbstractTabHandler'); /** * Plugin to handle tab keys in lists to indent and outdent. * @constructor * @extends {goog.editor.plugins.AbstractTabHandler} */ goog.editor.plugins.ListTabHandler = function() { goog.editor.plugins.AbstractTabHandler.call(this); }; goog.inherits(goog.editor.plugins.ListTabHandler, goog.editor.plugins.AbstractTabHandler); /** @override */ goog.editor.plugins.ListTabHandler.prototype.getTrogClassId = function() { return 'ListTabHandler'; }; /** @override */ goog.editor.plugins.ListTabHandler.prototype.handleTabKey = function(e) { var range = this.getFieldObject().getRange(); if (goog.dom.getAncestorByTagNameAndClass(range.getContainerElement(), goog.dom.TagName.LI) || goog.iter.some(range, function(node) { return node.tagName == goog.dom.TagName.LI; })) { this.getFieldObject().execCommand(e.shiftKey ? goog.editor.Command.OUTDENT : goog.editor.Command.INDENT); e.preventDefault(); return true; } return false; };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Adds a keyboard shortcut for the link command. * */ goog.provide('goog.editor.plugins.LinkShortcutPlugin'); goog.require('goog.editor.Command'); goog.require('goog.editor.Link'); goog.require('goog.editor.Plugin'); goog.require('goog.string'); /** * Plugin to add a keyboard shortcut for the link command * @constructor * @extends {goog.editor.Plugin} */ goog.editor.plugins.LinkShortcutPlugin = function() { goog.base(this); }; goog.inherits(goog.editor.plugins.LinkShortcutPlugin, goog.editor.Plugin); /** @override */ goog.editor.plugins.LinkShortcutPlugin.prototype.getTrogClassId = function() { return 'LinkShortcutPlugin'; }; /** * @inheritDoc */ goog.editor.plugins.LinkShortcutPlugin.prototype.handleKeyboardShortcut = function(e, key, isModifierPressed) { var command; if (isModifierPressed && key == 'k' && !e.shiftKey) { var link = /** @type {goog.editor.Link?} */ ( this.getFieldObject().execCommand(goog.editor.Command.LINK)); if (link) { link.finishLinkCreation(this.getFieldObject()); } return true; } return false; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Abstract Editor plugin class to handle tab keys. Has one * abstract method which should be overriden to handle a tab key press. * * @author robbyw@google.com (Robby Walker) * @author ajp@google.com (Andy Perelson) */ goog.provide('goog.editor.plugins.AbstractTabHandler'); goog.require('goog.editor.Plugin'); goog.require('goog.events.KeyCodes'); /** * Plugin to handle tab keys. Specific tab behavior defined by subclasses. * * @constructor * @extends {goog.editor.Plugin} */ goog.editor.plugins.AbstractTabHandler = function() { goog.editor.Plugin.call(this); }; goog.inherits(goog.editor.plugins.AbstractTabHandler, goog.editor.Plugin); /** @override */ goog.editor.plugins.AbstractTabHandler.prototype.getTrogClassId = goog.abstractMethod; /** @override */ goog.editor.plugins.AbstractTabHandler.prototype.handleKeyboardShortcut = function(e, key, isModifierPressed) { // If a dialog doesn't have selectable field, Moz grabs the event and // performs actions in editor window. This solves that problem and allows // the event to be passed on to proper handlers. if (goog.userAgent.GECKO && this.getFieldObject().inModalMode()) { return false; } // Don't handle Ctrl+Tab since the user is most likely trying to switch // browser tabs. See bug 1305086. // FF3 on Mac sends Ctrl-Tab to trogedit and we end up inserting a tab, but // then it also switches the tabs. See bug 1511681. Note that we don't use // isModifierPressed here since isModifierPressed is true only if metaKey // is true on Mac. if (e.keyCode == goog.events.KeyCodes.TAB && !e.metaKey && !e.ctrlKey) { return this.handleTabKey(e); } return false; }; /** * Handle a tab key press. * @param {goog.events.Event} e The key event. * @return {boolean} Whether this event was handled by this plugin. * @protected */ goog.editor.plugins.AbstractTabHandler.prototype.handleTabKey = goog.abstractMethod;
JavaScript