code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
// 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 Enum for button side constants. In its own file so as to not
* cause a circular dependency with {@link goog.ui.ButtonRenderer}.
*
* @author doughtie@google.com (Gavin Doughtie)
*/
goog.provide('goog.ui.ButtonSide');
/**
* Constants for button sides, see {@link goog.ui.Button.prototype.setCollapsed}
* for details.
* @enum {number}
*/
goog.ui.ButtonSide = {
/** Neither side. */
NONE: 0,
/** Left for LTR, right for RTL. */
START: 1,
/** Right for LTR, left for RTL. */
END: 2,
/** Both sides. */
BOTH: 3
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Definition of the Bubble class.
*
*
* @see ../demos/bubble.html
*
* TODO: support decoration and addChild
*/
goog.provide('goog.ui.Bubble');
goog.require('goog.Timer');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.math.Box');
goog.require('goog.positioning');
goog.require('goog.positioning.AbsolutePosition');
goog.require('goog.positioning.AnchoredPosition');
goog.require('goog.positioning.Corner');
goog.require('goog.positioning.CornerBit');
goog.require('goog.style');
goog.require('goog.ui.Component');
goog.require('goog.ui.Popup');
/**
* The Bubble provides a general purpose bubble implementation that can be
* anchored to a particular element and displayed for a period of time.
*
* @param {string|Element} message HTML string or an element to display inside
* the bubble.
* @param {Object=} opt_config The configuration
* for the bubble. If not specified, the default configuration will be
* used. {@see goog.ui.Bubble.defaultConfig}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @constructor
* @extends {goog.ui.Component}
*/
goog.ui.Bubble = function(message, opt_config, opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
/**
* The HTML string or element to display inside the bubble.
*
* @type {string|Element}
* @private
*/
this.message_ = message;
/**
* The Popup element used to position and display the bubble.
*
* @type {goog.ui.Popup}
* @private
*/
this.popup_ = new goog.ui.Popup();
/**
* Configuration map that contains bubble's UI elements.
*
* @type {Object}
* @private
*/
this.config_ = opt_config || goog.ui.Bubble.defaultConfig;
/**
* Id of the close button for this bubble.
*
* @type {string}
* @private
*/
this.closeButtonId_ = this.makeId('cb');
/**
* Id of the div for the embedded element.
*
* @type {string}
* @private
*/
this.messageId_ = this.makeId('mi');
};
goog.inherits(goog.ui.Bubble, goog.ui.Component);
/**
* In milliseconds, timeout after which the button auto-hides. Null means
* infinite.
* @type {?number}
* @private
*/
goog.ui.Bubble.prototype.timeout_ = null;
/**
* Key returned by the bubble timer.
* @type {number}
* @private
*/
goog.ui.Bubble.prototype.timerId_ = 0;
/**
* Key returned by the listen function for the close button.
* @type {goog.events.Key}
* @private
*/
goog.ui.Bubble.prototype.listener_ = null;
/**
* Key returned by the listen function for the close button.
* @type {Element}
* @private
*/
goog.ui.Bubble.prototype.anchor_ = null;
/** @override */
goog.ui.Bubble.prototype.createDom = function() {
goog.ui.Bubble.superClass_.createDom.call(this);
var element = this.getElement();
element.style.position = 'absolute';
element.style.visibility = 'hidden';
this.popup_.setElement(element);
};
/**
* Attaches the bubble to an anchor element. Computes the positioning and
* orientation of the bubble.
*
* @param {Element} anchorElement The element to which we are attaching.
*/
goog.ui.Bubble.prototype.attach = function(anchorElement) {
this.setAnchoredPosition_(
anchorElement, this.computePinnedCorner_(anchorElement));
};
/**
* Sets the corner of the bubble to used in the positioning algorithm.
*
* @param {goog.positioning.Corner} corner The bubble corner used for
* positioning constants.
*/
goog.ui.Bubble.prototype.setPinnedCorner = function(corner) {
this.popup_.setPinnedCorner(corner);
};
/**
* Sets the position of the bubble. Pass null for corner in AnchoredPosition
* for corner to be computed automatically.
*
* @param {goog.positioning.AbstractPosition} position The position of the
* bubble.
*/
goog.ui.Bubble.prototype.setPosition = function(position) {
if (position instanceof goog.positioning.AbsolutePosition) {
this.popup_.setPosition(position);
} else if (position instanceof goog.positioning.AnchoredPosition) {
this.setAnchoredPosition_(position.element, position.corner);
} else {
throw Error('Bubble only supports absolute and anchored positions!');
}
};
/**
* Sets the timeout after which bubble hides itself.
*
* @param {number} timeout Timeout of the bubble.
*/
goog.ui.Bubble.prototype.setTimeout = function(timeout) {
this.timeout_ = timeout;
};
/**
* Sets whether the bubble should be automatically hidden whenever user clicks
* outside the bubble element.
*
* @param {boolean} autoHide Whether to hide if user clicks outside the bubble.
*/
goog.ui.Bubble.prototype.setAutoHide = function(autoHide) {
this.popup_.setAutoHide(autoHide);
};
/**
* Sets whether the bubble should be visible.
*
* @param {boolean} visible Desired visibility state.
*/
goog.ui.Bubble.prototype.setVisible = function(visible) {
if (visible && !this.popup_.isVisible()) {
this.configureElement_();
}
this.popup_.setVisible(visible);
if (!this.popup_.isVisible()) {
this.unconfigureElement_();
}
};
/**
* @return {boolean} Whether the bubble is visible.
*/
goog.ui.Bubble.prototype.isVisible = function() {
return this.popup_.isVisible();
};
/** @override */
goog.ui.Bubble.prototype.disposeInternal = function() {
this.unconfigureElement_();
this.popup_.dispose();
this.popup_ = null;
goog.ui.Bubble.superClass_.disposeInternal.call(this);
};
/**
* Creates element's contents and configures all timers. This is called on
* setVisible(true).
* @private
*/
goog.ui.Bubble.prototype.configureElement_ = function() {
if (!this.isInDocument()) {
throw Error('You must render the bubble before showing it!');
}
var element = this.getElement();
var corner = this.popup_.getPinnedCorner();
element.innerHTML = this.computeHtmlForCorner_(corner);
if (typeof this.message_ == 'object') {
var messageDiv = this.getDomHelper().getElement(this.messageId_);
this.getDomHelper().appendChild(messageDiv, this.message_);
}
var closeButton = this.getDomHelper().getElement(this.closeButtonId_);
this.listener_ = goog.events.listen(closeButton,
goog.events.EventType.CLICK, this.hideBubble_, false, this);
if (this.timeout_) {
this.timerId_ = goog.Timer.callOnce(this.hideBubble_, this.timeout_, this);
}
};
/**
* Gets rid of the element's contents and all assoicated timers and listeners.
* This is called on dispose as well as on setVisible(false).
* @private
*/
goog.ui.Bubble.prototype.unconfigureElement_ = function() {
if (this.listener_) {
goog.events.unlistenByKey(this.listener_);
this.listener_ = null;
}
if (this.timerId_) {
goog.Timer.clear(this.timerId_);
this.timerId = null;
}
var element = this.getElement();
if (element) {
this.getDomHelper().removeChildren(element);
element.innerHTML = '';
}
};
/**
* Computes bubble position based on anchored element.
*
* @param {Element} anchorElement The element to which we are attaching.
* @param {goog.positioning.Corner} corner The bubble corner used for
* positioning.
* @private
*/
goog.ui.Bubble.prototype.setAnchoredPosition_ = function(anchorElement,
corner) {
this.popup_.setPinnedCorner(corner);
var margin = this.createMarginForCorner_(corner);
this.popup_.setMargin(margin);
var anchorCorner = goog.positioning.flipCorner(corner);
this.popup_.setPosition(new goog.positioning.AnchoredPosition(
anchorElement, anchorCorner));
};
/**
* Hides the bubble. This is called asynchronously by timer of event processor
* for the mouse click on the close button.
* @private
*/
goog.ui.Bubble.prototype.hideBubble_ = function() {
this.setVisible(false);
};
/**
* Returns an AnchoredPosition that will position the bubble optimally
* given the position of the anchor element and the size of the viewport.
*
* @param {Element} anchorElement The element to which the bubble is attached.
* @return {goog.ui.Popup.AnchoredPosition} The AnchoredPosition to give to
* {@link #setPosition}.
*/
goog.ui.Bubble.prototype.getComputedAnchoredPosition = function(anchorElement) {
return new goog.ui.Popup.AnchoredPosition(
anchorElement, this.computePinnedCorner_(anchorElement));
};
/**
* Computes the pinned corner for the bubble.
*
* @param {Element} anchorElement The element to which the button is attached.
* @return {goog.positioning.Corner} The pinned corner.
* @private
*/
goog.ui.Bubble.prototype.computePinnedCorner_ = function(anchorElement) {
var doc = this.getDomHelper().getOwnerDocument(anchorElement);
var viewportElement = goog.style.getClientViewportElement(doc);
var viewportWidth = viewportElement.offsetWidth;
var viewportHeight = viewportElement.offsetHeight;
var anchorElementOffset = goog.style.getPageOffset(anchorElement);
var anchorElementSize = goog.style.getSize(anchorElement);
var anchorType = 0;
// right margin or left?
if (viewportWidth - anchorElementOffset.x - anchorElementSize.width >
anchorElementOffset.x) {
anchorType += 1;
}
// attaches to the top or to the bottom?
if (viewportHeight - anchorElementOffset.y - anchorElementSize.height >
anchorElementOffset.y) {
anchorType += 2;
}
return goog.ui.Bubble.corners_[anchorType];
};
/**
* Computes the right offset for a given bubble corner
* and creates a margin element for it. This is done to have the
* button anchor element on its frame rather than on the corner.
*
* @param {goog.positioning.Corner} corner The corner.
* @return {goog.math.Box} the computed margin. Only left or right fields are
* non-zero, but they may be negative.
* @private
*/
goog.ui.Bubble.prototype.createMarginForCorner_ = function(corner) {
var margin = new goog.math.Box(0, 0, 0, 0);
if (corner & goog.positioning.CornerBit.RIGHT) {
margin.right -= this.config_.marginShift;
} else {
margin.left -= this.config_.marginShift;
}
return margin;
};
/**
* Computes the HTML string for a given bubble orientation.
*
* @param {goog.positioning.Corner} corner The corner.
* @return {string} The HTML string to place inside the bubble's popup.
* @private
*/
goog.ui.Bubble.prototype.computeHtmlForCorner_ = function(corner) {
var bubbleTopClass;
var bubbleBottomClass;
switch (corner) {
case goog.positioning.Corner.TOP_LEFT:
bubbleTopClass = this.config_.cssBubbleTopLeftAnchor;
bubbleBottomClass = this.config_.cssBubbleBottomNoAnchor;
break;
case goog.positioning.Corner.TOP_RIGHT:
bubbleTopClass = this.config_.cssBubbleTopRightAnchor;
bubbleBottomClass = this.config_.cssBubbleBottomNoAnchor;
break;
case goog.positioning.Corner.BOTTOM_LEFT:
bubbleTopClass = this.config_.cssBubbleTopNoAnchor;
bubbleBottomClass = this.config_.cssBubbleBottomLeftAnchor;
break;
case goog.positioning.Corner.BOTTOM_RIGHT:
bubbleTopClass = this.config_.cssBubbleTopNoAnchor;
bubbleBottomClass = this.config_.cssBubbleBottomRightAnchor;
break;
default:
throw Error('This corner type is not supported by bubble!');
}
var message = null;
if (typeof this.message_ == 'object') {
message = '<div id="' + this.messageId_ + '">';
} else {
message = this.message_;
}
var html =
'<table border=0 cellspacing=0 cellpadding=0 style="z-index:1"' +
' width=' + this.config_.bubbleWidth + '>' +
'<tr><td colspan=4 class="' + bubbleTopClass + '">' +
'<tr>' +
'<td class="' + this.config_.cssBubbleLeft + '">' +
'<td class="' + this.config_.cssBubbleFont + '"' +
' style="padding:0 4px;background:white">' + message +
'<td id="' + this.closeButtonId_ + '"' +
' class="' + this.config_.cssCloseButton + '"/>' +
'<td class="' + this.config_.cssBubbleRight + '">' +
'<tr>' +
'<td colspan=4 class="' + bubbleBottomClass + '">' +
'</table>';
return html;
};
/**
* A default configuration for the bubble.
*
* @type {Object}
*/
goog.ui.Bubble.defaultConfig = {
bubbleWidth: 147,
marginShift: 60,
cssBubbleFont: goog.getCssName('goog-bubble-font'),
cssCloseButton: goog.getCssName('goog-bubble-close-button'),
cssBubbleTopRightAnchor: goog.getCssName('goog-bubble-top-right-anchor'),
cssBubbleTopLeftAnchor: goog.getCssName('goog-bubble-top-left-anchor'),
cssBubbleTopNoAnchor: goog.getCssName('goog-bubble-top-no-anchor'),
cssBubbleBottomRightAnchor:
goog.getCssName('goog-bubble-bottom-right-anchor'),
cssBubbleBottomLeftAnchor: goog.getCssName('goog-bubble-bottom-left-anchor'),
cssBubbleBottomNoAnchor: goog.getCssName('goog-bubble-bottom-no-anchor'),
cssBubbleLeft: goog.getCssName('goog-bubble-left'),
cssBubbleRight: goog.getCssName('goog-bubble-right')
};
/**
* An auxiliary array optimizing the corner computation.
*
* @type {Array.<goog.positioning.Corner>}
* @private
*/
goog.ui.Bubble.corners_ = [
goog.positioning.Corner.BOTTOM_RIGHT,
goog.positioning.Corner.BOTTOM_LEFT,
goog.positioning.Corner.TOP_RIGHT,
goog.positioning.Corner.TOP_LEFT
];
| 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 Activity Monitor.
*
* Fires throttled events when a user interacts with the specified document.
* This class also exposes the amount of time since the last user event.
*
* If you would prefer to get BECOME_ACTIVE and BECOME_IDLE events when the
* user changes states, then you should use the IdleTimer class instead.
*
*/
goog.provide('goog.ui.ActivityMonitor');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
/**
* Once initialized with a document, the activity monitor can be queried for
* the current idle time.
*
* @param {goog.dom.DomHelper|Array.<goog.dom.DomHelper>=} opt_domHelper
* DomHelper which contains the document(s) to listen to. If null, the
* default document is usedinstead.
* @param {boolean=} opt_useBubble Whether to use the bubble phase to listen for
* events. By default listens on the capture phase so that it won't miss
* events that get stopPropagation/cancelBubble'd. However, this can cause
* problems in IE8 if the page loads multiple scripts that include the
* closure event handling code.
*
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.ui.ActivityMonitor = function(opt_domHelper, opt_useBubble) {
goog.events.EventTarget.call(this);
/**
* Array of documents that are being listened to.
* @type {Array.<Document>}
* @private
*/
this.documents_ = [];
/**
* Whether to use the bubble phase to listen for events.
* @type {boolean}
* @private
*/
this.useBubble_ = !!opt_useBubble;
/**
* The event handler.
* @type {goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler(this);
if (!opt_domHelper) {
this.addDocument(goog.dom.getDomHelper().getDocument());
} else if (goog.isArray(opt_domHelper)) {
for (var i = 0; i < opt_domHelper.length; i++) {
this.addDocument(opt_domHelper[i].getDocument());
}
} else {
this.addDocument(opt_domHelper.getDocument());
}
/**
* The time (in milliseconds) of the last user event.
* @type {number}
* @private
*/
this.lastEventTime_ = goog.now();
};
goog.inherits(goog.ui.ActivityMonitor, goog.events.EventTarget);
/**
* The last event type that was detected.
* @type {string}
* @private
*/
goog.ui.ActivityMonitor.prototype.lastEventType_ = '';
/**
* The mouse x-position after the last user event.
* @type {number}
* @private
*/
goog.ui.ActivityMonitor.prototype.lastMouseX_;
/**
* The mouse y-position after the last user event.
* @type {number}
* @private
*/
goog.ui.ActivityMonitor.prototype.lastMouseY_;
/**
* The earliest time that another throttled ACTIVITY event will be dispatched
* @type {number}
* @private
*/
goog.ui.ActivityMonitor.prototype.minEventTime_ = 0;
/**
* Minimum amount of time in ms between throttled ACTIVITY events
* @type {number}
*/
goog.ui.ActivityMonitor.MIN_EVENT_SPACING = 3 * 1000;
/**
* If a user executes one of these events, s/he is considered not idle.
* @type {Array.<goog.events.EventType>}
* @private
*/
goog.ui.ActivityMonitor.userEventTypesBody_ = [
goog.events.EventType.CLICK,
goog.events.EventType.DBLCLICK,
goog.events.EventType.MOUSEDOWN,
goog.events.EventType.MOUSEMOVE,
goog.events.EventType.MOUSEUP,
goog.events.EventType.TOUCHEND,
goog.events.EventType.TOUCHMOVE,
goog.events.EventType.TOUCHSTART
];
/**
* If a user executes one of these events, s/he is considered not idle.
* @type {Array.<goog.events.EventType>}
* @private
*/
goog.ui.ActivityMonitor.userEventTypesDocuments_ =
[goog.events.EventType.KEYDOWN, goog.events.EventType.KEYUP];
/**
* Event constants for the activity monitor.
* @enum {string}
*/
goog.ui.ActivityMonitor.Event = {
/** Event fired when the user does something interactive */
ACTIVITY: 'activity'
};
/** @override */
goog.ui.ActivityMonitor.prototype.disposeInternal = function() {
goog.ui.ActivityMonitor.superClass_.disposeInternal.call(this);
this.eventHandler_.dispose();
this.eventHandler_ = null;
delete this.documents_;
};
/**
* Adds a document to those being monitored by this class.
*
* @param {Document} doc Document to monitor.
*/
goog.ui.ActivityMonitor.prototype.addDocument = function(doc) {
this.documents_.push(doc);
var useCapture = !this.useBubble_;
this.eventHandler_.listen(
doc, goog.ui.ActivityMonitor.userEventTypesDocuments_,
this.handleEvent_, useCapture);
this.eventHandler_.listen(
doc, goog.ui.ActivityMonitor.userEventTypesBody_,
this.handleEvent_, useCapture);
};
/**
* Removes a document from those being monitored by this class.
*
* @param {Document} doc Document to monitor.
*/
goog.ui.ActivityMonitor.prototype.removeDocument = function(doc) {
if (this.isDisposed()) {
return;
}
goog.array.remove(this.documents_, doc);
var useCapture = !this.useBubble_;
this.eventHandler_.unlisten(
doc, goog.ui.ActivityMonitor.userEventTypesDocuments_,
this.handleEvent_, useCapture);
this.eventHandler_.unlisten(
doc, goog.ui.ActivityMonitor.userEventTypesBody_,
this.handleEvent_, useCapture);
};
/**
* Updates the last event time when a user action occurs.
* @param {goog.events.BrowserEvent} e Event object.
* @private
*/
goog.ui.ActivityMonitor.prototype.handleEvent_ = function(e) {
var update = false;
switch (e.type) {
case goog.events.EventType.MOUSEMOVE:
// In FF 1.5, we get spurious mouseover and mouseout events when the UI
// redraws. We only want to update the idle time if the mouse has moved.
if (typeof this.lastMouseX_ == 'number' &&
this.lastMouseX_ != e.clientX ||
typeof this.lastMouseY_ == 'number' &&
this.lastMouseY_ != e.clientY) {
update = true;
}
this.lastMouseX_ = e.clientX;
this.lastMouseY_ = e.clientY;
break;
default:
update = true;
}
if (update) {
var type = goog.asserts.assertString(e.type);
this.updateIdleTime(goog.now(), type);
}
};
/**
* Updates the last event time to be the present time, useful for non-DOM
* events that should update idle time.
*/
goog.ui.ActivityMonitor.prototype.resetTimer = function() {
this.updateIdleTime(goog.now(), 'manual');
};
/**
* Updates the idle time and fires an event if time has elapsed since
* the last update.
* @param {number} eventTime Time (in MS) of the event that cleared the idle
* timer.
* @param {string} eventType Type of the event, used only for debugging.
* @protected
*/
goog.ui.ActivityMonitor.prototype.updateIdleTime = function(
eventTime, eventType) {
// update internal state noting whether the user was idle
this.lastEventTime_ = eventTime;
this.lastEventType_ = eventType;
// dispatch event
if (eventTime > this.minEventTime_) {
this.dispatchEvent(goog.ui.ActivityMonitor.Event.ACTIVITY);
this.minEventTime_ = eventTime + goog.ui.ActivityMonitor.MIN_EVENT_SPACING;
}
};
/**
* Returns the amount of time the user has been idle.
* @param {number=} opt_now The current time can optionally be passed in for the
* computation to avoid an extra Date allocation.
* @return {number} The amount of time in ms that the user has been idle.
*/
goog.ui.ActivityMonitor.prototype.getIdleTime = function(opt_now) {
var now = opt_now || goog.now();
return now - this.lastEventTime_;
};
/**
* Returns the type of the last user event.
* @return {string} event type.
*/
goog.ui.ActivityMonitor.prototype.getLastEventType = function() {
return this.lastEventType_;
};
/**
* Returns the time of the last event
* @return {number} last event time.
*/
goog.ui.ActivityMonitor.prototype.getLastEventTime = function() {
return this.lastEventTime_;
};
| 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 Abstract class for all UI components. This defines the standard
* design pattern that all UI components should follow.
*
* @see ../demos/samplecomponent.html
* @see http://code.google.com/p/closure-library/wiki/IntroToComponents
*/
goog.provide('goog.ui.Component');
goog.provide('goog.ui.Component.Error');
goog.provide('goog.ui.Component.EventType');
goog.provide('goog.ui.Component.State');
goog.require('goog.array');
goog.require('goog.array.ArrayLike');
goog.require('goog.dom');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.object');
goog.require('goog.style');
goog.require('goog.ui.IdGenerator');
/**
* Default implementation of UI component.
*
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.ui.Component = function(opt_domHelper) {
goog.events.EventTarget.call(this);
this.dom_ = opt_domHelper || goog.dom.getDomHelper();
// Set the defalt right to left value.
this.rightToLeft_ = goog.ui.Component.defaultRightToLeft_;
};
goog.inherits(goog.ui.Component, goog.events.EventTarget);
/**
* Generator for unique IDs.
* @type {goog.ui.IdGenerator}
* @private
*/
goog.ui.Component.prototype.idGenerator_ = goog.ui.IdGenerator.getInstance();
/**
* The default right to left value.
* @type {?boolean}
* @private
*/
goog.ui.Component.defaultRightToLeft_ = null;
/**
* Common events fired by components so that event propagation is useful. Not
* all components are expected to dispatch or listen for all event types.
* Events dispatched before a state transition should be cancelable to prevent
* the corresponding state change.
* @enum {string}
*/
goog.ui.Component.EventType = {
/** Dispatched before the component becomes visible. */
BEFORE_SHOW: 'beforeshow',
/**
* Dispatched after the component becomes visible.
* NOTE(user): For goog.ui.Container, this actually fires before containers
* are shown. Use goog.ui.Container.EventType.AFTER_SHOW if you want an event
* that fires after a goog.ui.Container is shown.
*/
SHOW: 'show',
/** Dispatched before the component becomes hidden. */
HIDE: 'hide',
/** Dispatched before the component becomes disabled. */
DISABLE: 'disable',
/** Dispatched before the component becomes enabled. */
ENABLE: 'enable',
/** Dispatched before the component becomes highlighted. */
HIGHLIGHT: 'highlight',
/** Dispatched before the component becomes un-highlighted. */
UNHIGHLIGHT: 'unhighlight',
/** Dispatched before the component becomes activated. */
ACTIVATE: 'activate',
/** Dispatched before the component becomes deactivated. */
DEACTIVATE: 'deactivate',
/** Dispatched before the component becomes selected. */
SELECT: 'select',
/** Dispatched before the component becomes un-selected. */
UNSELECT: 'unselect',
/** Dispatched before a component becomes checked. */
CHECK: 'check',
/** Dispatched before a component becomes un-checked. */
UNCHECK: 'uncheck',
/** Dispatched before a component becomes focused. */
FOCUS: 'focus',
/** Dispatched before a component becomes blurred. */
BLUR: 'blur',
/** Dispatched before a component is opened (expanded). */
OPEN: 'open',
/** Dispatched before a component is closed (collapsed). */
CLOSE: 'close',
/** Dispatched after a component is moused over. */
ENTER: 'enter',
/** Dispatched after a component is moused out of. */
LEAVE: 'leave',
/** Dispatched after the user activates the component. */
ACTION: 'action',
/** Dispatched after the external-facing state of a component is changed. */
CHANGE: 'change'
};
/**
* Errors thrown by the component.
* @enum {string}
*/
goog.ui.Component.Error = {
/**
* Error when a method is not supported.
*/
NOT_SUPPORTED: 'Method not supported',
/**
* Error when the given element can not be decorated.
*/
DECORATE_INVALID: 'Invalid element to decorate',
/**
* Error when the component is already rendered and another render attempt is
* made.
*/
ALREADY_RENDERED: 'Component already rendered',
/**
* Error when an attempt is made to set the parent of a component in a way
* that would result in an inconsistent object graph.
*/
PARENT_UNABLE_TO_BE_SET: 'Unable to set parent component',
/**
* Error when an attempt is made to add a child component at an out-of-bounds
* index. We don't support sparse child arrays.
*/
CHILD_INDEX_OUT_OF_BOUNDS: 'Child component index out of bounds',
/**
* Error when an attempt is made to remove a child component from a component
* other than its parent.
*/
NOT_OUR_CHILD: 'Child is not in parent component',
/**
* Error when an operation requiring DOM interaction is made when the
* component is not in the document
*/
NOT_IN_DOCUMENT: 'Operation not supported while component is not in document',
/**
* Error when an invalid component state is encountered.
*/
STATE_INVALID: 'Invalid component state'
};
/**
* Common component states. Components may have distinct appearance depending
* on what state(s) apply to them. Not all components are expected to support
* all states.
* @enum {number}
*/
goog.ui.Component.State = {
/**
* Union of all supported component states.
*/
ALL: 0xFF,
/**
* Component is disabled.
* @see goog.ui.Component.EventType.DISABLE
* @see goog.ui.Component.EventType.ENABLE
*/
DISABLED: 0x01,
/**
* Component is highlighted.
* @see goog.ui.Component.EventType.HIGHLIGHT
* @see goog.ui.Component.EventType.UNHIGHLIGHT
*/
HOVER: 0x02,
/**
* Component is active (or "pressed").
* @see goog.ui.Component.EventType.ACTIVATE
* @see goog.ui.Component.EventType.DEACTIVATE
*/
ACTIVE: 0x04,
/**
* Component is selected.
* @see goog.ui.Component.EventType.SELECT
* @see goog.ui.Component.EventType.UNSELECT
*/
SELECTED: 0x08,
/**
* Component is checked.
* @see goog.ui.Component.EventType.CHECK
* @see goog.ui.Component.EventType.UNCHECK
*/
CHECKED: 0x10,
/**
* Component has focus.
* @see goog.ui.Component.EventType.FOCUS
* @see goog.ui.Component.EventType.BLUR
*/
FOCUSED: 0x20,
/**
* Component is opened (expanded). Applies to tree nodes, menu buttons,
* submenus, zippys (zippies?), etc.
* @see goog.ui.Component.EventType.OPEN
* @see goog.ui.Component.EventType.CLOSE
*/
OPENED: 0x40
};
/**
* Static helper method; returns the type of event components are expected to
* dispatch when transitioning to or from the given state.
* @param {goog.ui.Component.State} state State to/from which the component
* is transitioning.
* @param {boolean} isEntering Whether the component is entering or leaving the
* state.
* @return {goog.ui.Component.EventType} Event type to dispatch.
*/
goog.ui.Component.getStateTransitionEvent = function(state, isEntering) {
switch (state) {
case goog.ui.Component.State.DISABLED:
return isEntering ? goog.ui.Component.EventType.DISABLE :
goog.ui.Component.EventType.ENABLE;
case goog.ui.Component.State.HOVER:
return isEntering ? goog.ui.Component.EventType.HIGHLIGHT :
goog.ui.Component.EventType.UNHIGHLIGHT;
case goog.ui.Component.State.ACTIVE:
return isEntering ? goog.ui.Component.EventType.ACTIVATE :
goog.ui.Component.EventType.DEACTIVATE;
case goog.ui.Component.State.SELECTED:
return isEntering ? goog.ui.Component.EventType.SELECT :
goog.ui.Component.EventType.UNSELECT;
case goog.ui.Component.State.CHECKED:
return isEntering ? goog.ui.Component.EventType.CHECK :
goog.ui.Component.EventType.UNCHECK;
case goog.ui.Component.State.FOCUSED:
return isEntering ? goog.ui.Component.EventType.FOCUS :
goog.ui.Component.EventType.BLUR;
case goog.ui.Component.State.OPENED:
return isEntering ? goog.ui.Component.EventType.OPEN :
goog.ui.Component.EventType.CLOSE;
default:
// Fall through.
}
// Invalid state.
throw Error(goog.ui.Component.Error.STATE_INVALID);
};
/**
* Set the default right-to-left value. This causes all component's created from
* this point foward to have the given value. This is useful for cases where
* a given page is always in one directionality, avoiding unnecessary
* right to left determinations.
* @param {?boolean} rightToLeft Whether the components should be rendered
* right-to-left. Null iff components should determine their directionality.
*/
goog.ui.Component.setDefaultRightToLeft = function(rightToLeft) {
goog.ui.Component.defaultRightToLeft_ = rightToLeft;
};
/**
* Unique ID of the component, lazily initialized in {@link
* goog.ui.Component#getId} if needed. This property is strictly private and
* must not be accessed directly outside of this class!
* @type {?string}
* @private
*/
goog.ui.Component.prototype.id_ = null;
/**
* DomHelper used to interact with the document, allowing components to be
* created in a different window.
* @type {!goog.dom.DomHelper}
* @protected
* @suppress {underscore}
*/
goog.ui.Component.prototype.dom_;
/**
* Whether the component is in the document.
* @type {boolean}
* @private
*/
goog.ui.Component.prototype.inDocument_ = false;
// TODO(attila): Stop referring to this private field in subclasses.
/**
* The DOM element for the component.
* @type {Element}
* @private
*/
goog.ui.Component.prototype.element_ = null;
/**
* Event handler.
* TODO(user): rename it to handler_ after all component subclasses in
* inside Google have been cleaned up.
* Code search: http://go/component_code_search
* @type {goog.events.EventHandler}
* @private
*/
goog.ui.Component.prototype.googUiComponentHandler_;
/**
* Whether the component is rendered right-to-left. Right-to-left is set
* lazily when {@link #isRightToLeft} is called the first time, unless it has
* been set by calling {@link #setRightToLeft} explicitly.
* @type {?boolean}
* @private
*/
goog.ui.Component.prototype.rightToLeft_ = null;
/**
* Arbitrary data object associated with the component. Such as meta-data.
* @type {*}
* @private
*/
goog.ui.Component.prototype.model_ = null;
/**
* Parent component to which events will be propagated. This property is
* strictly private and must not be accessed directly outside of this class!
* @type {goog.ui.Component?}
* @private
*/
goog.ui.Component.prototype.parent_ = null;
/**
* Array of child components. Lazily initialized on first use. Must be kept in
* sync with {@code childIndex_}. This property is strictly private and must
* not be accessed directly outside of this class!
* @type {Array.<goog.ui.Component>?}
* @private
*/
goog.ui.Component.prototype.children_ = null;
/**
* Map of child component IDs to child components. Used for constant-time
* random access to child components by ID. Lazily initialized on first use.
* Must be kept in sync with {@code children_}. This property is strictly
* private and must not be accessed directly outside of this class!
*
* We use a plain Object, not a {@link goog.structs.Map}, for simplicity.
* This means components can't have children with IDs such as 'constructor' or
* 'valueOf', but this shouldn't really be an issue in practice, and if it is,
* we can always fix it later without changing the API.
*
* @type {Object}
* @private
*/
goog.ui.Component.prototype.childIndex_ = null;
/**
* Flag used to keep track of whether a component decorated an already existing
* element or whether it created the DOM itself.
*
* If an element is decorated, dispose will leave the node in the document.
* It is up to the app to remove the node.
*
* If an element was rendered, dispose will remove the node automatically.
*
* @type {boolean}
* @private
*/
goog.ui.Component.prototype.wasDecorated_ = false;
/**
* Gets the unique ID for the instance of this component. If the instance
* doesn't already have an ID, generates one on the fly.
* @return {string} Unique component ID.
*/
goog.ui.Component.prototype.getId = function() {
return this.id_ || (this.id_ = this.idGenerator_.getNextUniqueId());
};
/**
* Assigns an ID to this component instance. It is the caller's responsibility
* to guarantee that the ID is unique. If the component is a child of a parent
* component, then the parent component's child index is updated to reflect the
* new ID; this may throw an error if the parent already has a child with an ID
* that conflicts with the new ID.
* @param {string} id Unique component ID.
*/
goog.ui.Component.prototype.setId = function(id) {
if (this.parent_ && this.parent_.childIndex_) {
// Update the parent's child index.
goog.object.remove(this.parent_.childIndex_, this.id_);
goog.object.add(this.parent_.childIndex_, id, this);
}
// Update the component ID.
this.id_ = id;
};
/**
* Gets the component's element.
* @return {Element} The element for the component.
*/
goog.ui.Component.prototype.getElement = function() {
return this.element_;
};
/**
* Gets the component's element. This differs from getElement in that
* it assumes that the element exists (i.e. the component has been
* rendered/decorated) and will cause an assertion error otherwise (if
* assertion is enabled).
* @return {!Element} The element for the component.
*/
goog.ui.Component.prototype.getElementStrict = function() {
var el = this.element_;
goog.asserts.assert(
el, 'Can not call getElementStrict before rendering/decorating.');
return el;
};
/**
* Sets the component's root element to the given element. Considered
* protected and final.
*
* This should generally only be called during createDom. Setting the element
* does not actually change which element is rendered, only the element that is
* associated with this UI component.
*
* @param {Element} element Root element for the component.
* @protected
*/
goog.ui.Component.prototype.setElementInternal = function(element) {
this.element_ = element;
};
/**
* Returns an array of all the elements in this component's DOM with the
* provided className.
* @param {string} className The name of the class to look for.
* @return {!goog.array.ArrayLike} The items found with the class name provided.
*/
goog.ui.Component.prototype.getElementsByClass = function(className) {
return this.element_ ?
this.dom_.getElementsByClass(className, this.element_) : [];
};
/**
* Returns the first element in this component's DOM with the provided
* className.
* @param {string} className The name of the class to look for.
* @return {Element} The first item with the class name provided.
*/
goog.ui.Component.prototype.getElementByClass = function(className) {
return this.element_ ?
this.dom_.getElementByClass(className, this.element_) : null;
};
/**
* Returns the event handler for this component, lazily created the first time
* this method is called.
* @return {!goog.events.EventHandler} Event handler for this component.
* @protected
*/
goog.ui.Component.prototype.getHandler = function() {
return this.googUiComponentHandler_ ||
(this.googUiComponentHandler_ = new goog.events.EventHandler(this));
};
/**
* Sets the parent of this component to use for event bubbling. Throws an error
* if the component already has a parent or if an attempt is made to add a
* component to itself as a child. Callers must use {@code removeChild}
* or {@code removeChildAt} to remove components from their containers before
* calling this method.
* @see goog.ui.Component#removeChild
* @see goog.ui.Component#removeChildAt
* @param {goog.ui.Component} parent The parent component.
*/
goog.ui.Component.prototype.setParent = function(parent) {
if (this == parent) {
// Attempting to add a child to itself is an error.
throw Error(goog.ui.Component.Error.PARENT_UNABLE_TO_BE_SET);
}
if (parent && this.parent_ && this.id_ && this.parent_.getChild(this.id_) &&
this.parent_ != parent) {
// This component is already the child of some parent, so it should be
// removed using removeChild/removeChildAt first.
throw Error(goog.ui.Component.Error.PARENT_UNABLE_TO_BE_SET);
}
this.parent_ = parent;
goog.ui.Component.superClass_.setParentEventTarget.call(this, parent);
};
/**
* Returns the component's parent, if any.
* @return {goog.ui.Component?} The parent component.
*/
goog.ui.Component.prototype.getParent = function() {
return this.parent_;
};
/**
* Overrides {@link goog.events.EventTarget#setParentEventTarget} to throw an
* error if the parent component is set, and the argument is not the parent.
* @override
*/
goog.ui.Component.prototype.setParentEventTarget = function(parent) {
if (this.parent_ && this.parent_ != parent) {
throw Error(goog.ui.Component.Error.NOT_SUPPORTED);
}
goog.ui.Component.superClass_.setParentEventTarget.call(this, parent);
};
/**
* Returns the dom helper that is being used on this component.
* @return {!goog.dom.DomHelper} The dom helper used on this component.
*/
goog.ui.Component.prototype.getDomHelper = function() {
return this.dom_;
};
/**
* Determines whether the component has been added to the document.
* @return {boolean} TRUE if rendered. Otherwise, FALSE.
*/
goog.ui.Component.prototype.isInDocument = function() {
return this.inDocument_;
};
/**
* Creates the initial DOM representation for the component. The default
* implementation is to set this.element_ = div.
*/
goog.ui.Component.prototype.createDom = function() {
this.element_ = this.dom_.createElement('div');
};
/**
* Renders the component. If a parent element is supplied, the component's
* element will be appended to it. If there is no optional parent element and
* the element doesn't have a parentNode then it will be appended to the
* document body.
*
* If this component has a parent component, and the parent component is
* not in the document already, then this will not call {@code enterDocument}
* on this component.
*
* Throws an Error if the component is already rendered.
*
* @param {Element=} opt_parentElement Optional parent element to render the
* component into.
*/
goog.ui.Component.prototype.render = function(opt_parentElement) {
this.render_(opt_parentElement);
};
/**
* Renders the component before another element. The other element should be in
* the document already.
*
* Throws an Error if the component is already rendered.
*
* @param {Node} sibling Node to render the component before.
*/
goog.ui.Component.prototype.renderBefore = function(sibling) {
this.render_(/** @type {Element} */ (sibling.parentNode),
sibling);
};
/**
* Renders the component. If a parent element is supplied, the component's
* element will be appended to it. If there is no optional parent element and
* the element doesn't have a parentNode then it will be appended to the
* document body.
*
* If this component has a parent component, and the parent component is
* not in the document already, then this will not call {@code enterDocument}
* on this component.
*
* Throws an Error if the component is already rendered.
*
* @param {Element=} opt_parentElement Optional parent element to render the
* component into.
* @param {Node=} opt_beforeNode Node before which the component is to
* be rendered. If left out the node is appended to the parent element.
* @private
*/
goog.ui.Component.prototype.render_ = function(opt_parentElement,
opt_beforeNode) {
if (this.inDocument_) {
throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
}
if (!this.element_) {
this.createDom();
}
if (opt_parentElement) {
opt_parentElement.insertBefore(this.element_, opt_beforeNode || null);
} else {
this.dom_.getDocument().body.appendChild(this.element_);
}
// If this component has a parent component that isn't in the document yet,
// we don't call enterDocument() here. Instead, when the parent component
// enters the document, the enterDocument() call will propagate to its
// children, including this one. If the component doesn't have a parent
// or if the parent is already in the document, we call enterDocument().
if (!this.parent_ || this.parent_.isInDocument()) {
this.enterDocument();
}
};
/**
* Decorates the element for the UI component.
* @param {Element} element Element to decorate.
*/
goog.ui.Component.prototype.decorate = function(element) {
if (this.inDocument_) {
throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
} else if (element && this.canDecorate(element)) {
this.wasDecorated_ = true;
// Set the DOM helper of the component to match the decorated element.
if (!this.dom_ ||
this.dom_.getDocument() != goog.dom.getOwnerDocument(element)) {
this.dom_ = goog.dom.getDomHelper(element);
}
// Call specific component decorate logic.
this.decorateInternal(element);
this.enterDocument();
} else {
throw Error(goog.ui.Component.Error.DECORATE_INVALID);
}
};
/**
* Determines if a given element can be decorated by this type of component.
* This method should be overridden by inheriting objects.
* @param {Element} element Element to decorate.
* @return {boolean} True if the element can be decorated, false otherwise.
*/
goog.ui.Component.prototype.canDecorate = function(element) {
return true;
};
/**
* @return {boolean} Whether the component was decorated.
*/
goog.ui.Component.prototype.wasDecorated = function() {
return this.wasDecorated_;
};
/**
* Actually decorates the element. Should be overridden by inheriting objects.
* This method can assume there are checks to ensure the component has not
* already been rendered have occurred and that enter document will be called
* afterwards. This method is considered protected.
* @param {Element} element Element to decorate.
* @protected
*/
goog.ui.Component.prototype.decorateInternal = function(element) {
this.element_ = element;
};
/**
* Called when the component's element is known to be in the document. Anything
* using document.getElementById etc. should be done at this stage.
*
* If the component contains child components, this call is propagated to its
* children.
*/
goog.ui.Component.prototype.enterDocument = function() {
this.inDocument_ = true;
// Propagate enterDocument to child components that have a DOM, if any.
this.forEachChild(function(child) {
if (!child.isInDocument() && child.getElement()) {
child.enterDocument();
}
});
};
/**
* Called by dispose to clean up the elements and listeners created by a
* component, or by a parent component/application who has removed the
* component from the document but wants to reuse it later.
*
* If the component contains child components, this call is propagated to its
* children.
*
* It should be possible for the component to be rendered again once this method
* has been called.
*/
goog.ui.Component.prototype.exitDocument = function() {
// Propagate exitDocument to child components that have been rendered, if any.
this.forEachChild(function(child) {
if (child.isInDocument()) {
child.exitDocument();
}
});
if (this.googUiComponentHandler_) {
this.googUiComponentHandler_.removeAll();
}
this.inDocument_ = false;
};
/**
* Disposes of the component. Calls {@code exitDocument}, which is expected to
* remove event handlers and clean up the component. Propagates the call to
* the component's children, if any. Removes the component's DOM from the
* document unless it was decorated.
* @override
* @protected
*/
goog.ui.Component.prototype.disposeInternal = function() {
if (this.inDocument_) {
this.exitDocument();
}
if (this.googUiComponentHandler_) {
this.googUiComponentHandler_.dispose();
delete this.googUiComponentHandler_;
}
// Disposes of the component's children, if any.
this.forEachChild(function(child) {
child.dispose();
});
// Detach the component's element from the DOM, unless it was decorated.
if (!this.wasDecorated_ && this.element_) {
goog.dom.removeNode(this.element_);
}
this.children_ = null;
this.childIndex_ = null;
this.element_ = null;
this.model_ = null;
this.parent_ = null;
goog.ui.Component.superClass_.disposeInternal.call(this);
};
/**
* Helper function for subclasses that gets a unique id for a given fragment,
* this can be used by components to generate unique string ids for DOM
* elements.
* @param {string} idFragment A partial id.
* @return {string} Unique element id.
*/
goog.ui.Component.prototype.makeId = function(idFragment) {
return this.getId() + '.' + idFragment;
};
/**
* Makes a collection of ids. This is a convenience method for makeId. The
* object's values are the id fragments and the new values are the generated
* ids. The key will remain the same.
* @param {Object} object The object that will be used to create the ids.
* @return {Object} An object of id keys to generated ids.
*/
goog.ui.Component.prototype.makeIds = function(object) {
var ids = {};
for (var key in object) {
ids[key] = this.makeId(object[key]);
}
return ids;
};
/**
* Returns the model associated with the UI component.
* @return {*} The model.
*/
goog.ui.Component.prototype.getModel = function() {
return this.model_;
};
/**
* Sets the model associated with the UI component.
* @param {*} obj The model.
*/
goog.ui.Component.prototype.setModel = function(obj) {
this.model_ = obj;
};
/**
* Helper function for returning the fragment portion of an id generated using
* makeId().
* @param {string} id Id generated with makeId().
* @return {string} Fragment.
*/
goog.ui.Component.prototype.getFragmentFromId = function(id) {
return id.substring(this.getId().length + 1);
};
/**
* Helper function for returning an element in the document with a unique id
* generated using makeId().
* @param {string} idFragment The partial id.
* @return {Element} The element with the unique id, or null if it cannot be
* found.
*/
goog.ui.Component.prototype.getElementByFragment = function(idFragment) {
if (!this.inDocument_) {
throw Error(goog.ui.Component.Error.NOT_IN_DOCUMENT);
}
return this.dom_.getElement(this.makeId(idFragment));
};
/**
* Adds the specified component as the last child of this component. See
* {@link goog.ui.Component#addChildAt} for detailed semantics.
*
* @see goog.ui.Component#addChildAt
* @param {goog.ui.Component} child The new child component.
* @param {boolean=} opt_render If true, the child component will be rendered
* into the parent.
*/
goog.ui.Component.prototype.addChild = function(child, opt_render) {
// TODO(gboyer): addChildAt(child, this.getChildCount(), false) will
// reposition any already-rendered child to the end. Instead, perhaps
// addChild(child, false) should never reposition the child; instead, clients
// that need the repositioning will use addChildAt explicitly. Right now,
// clients can get around this by calling addChild first.
this.addChildAt(child, this.getChildCount(), opt_render);
};
/**
* Adds the specified component as a child of this component at the given
* 0-based index.
*
* Both {@code addChild} and {@code addChildAt} assume the following contract
* between parent and child components:
* <ul>
* <li>the child component's element must be a descendant of the parent
* component's element, and
* <li>the DOM state of the child component must be consistent with the DOM
* state of the parent component (see {@code isInDocument}) in the
* steady state -- the exception is to addChildAt(child, i, false) and
* then immediately decorate/render the child.
* </ul>
*
* In particular, {@code parent.addChild(child)} will throw an error if the
* child component is already in the document, but the parent isn't.
*
* Clients of this API may call {@code addChild} and {@code addChildAt} with
* {@code opt_render} set to true. If {@code opt_render} is true, calling these
* methods will automatically render the child component's element into the
* parent component's element. However, {@code parent.addChild(child, true)}
* will throw an error if:
* <ul>
* <li>the parent component has no DOM (i.e. {@code parent.getElement()} is
* null), or
* <li>the child component is already in the document, regardless of the
* parent's DOM state.
* </ul>
*
* If {@code opt_render} is true and the parent component is not already
* in the document, {@code enterDocument} will not be called on this component
* at this point.
*
* Finally, this method also throws an error if the new child already has a
* different parent, or the given index is out of bounds.
*
* @see goog.ui.Component#addChild
* @param {goog.ui.Component} child The new child component.
* @param {number} index 0-based index at which the new child component is to be
* added; must be between 0 and the current child count (inclusive).
* @param {boolean=} opt_render If true, the child component will be rendered
* into the parent.
* @return {void} Nada.
*/
goog.ui.Component.prototype.addChildAt = function(child, index, opt_render) {
if (child.inDocument_ && (opt_render || !this.inDocument_)) {
// Adding a child that's already in the document is an error, except if the
// parent is also in the document and opt_render is false (e.g. decorate()).
throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
}
if (index < 0 || index > this.getChildCount()) {
// Allowing sparse child arrays would lead to strange behavior, so we don't.
throw Error(goog.ui.Component.Error.CHILD_INDEX_OUT_OF_BOUNDS);
}
// Create the index and the child array on first use.
if (!this.childIndex_ || !this.children_) {
this.childIndex_ = {};
this.children_ = [];
}
// Moving child within component, remove old reference.
if (child.getParent() == this) {
goog.object.set(this.childIndex_, child.getId(), child);
goog.array.remove(this.children_, child);
// Add the child to this component. goog.object.add() throws an error if
// a child with the same ID already exists.
} else {
goog.object.add(this.childIndex_, child.getId(), child);
}
// Set the parent of the child to this component. This throws an error if
// the child is already contained by another component.
child.setParent(this);
goog.array.insertAt(this.children_, child, index);
if (child.inDocument_ && this.inDocument_ && child.getParent() == this) {
// Changing the position of an existing child, move the DOM node.
var contentElement = this.getContentElement();
contentElement.insertBefore(child.getElement(),
(contentElement.childNodes[index] || null));
} else if (opt_render) {
// If this (parent) component doesn't have a DOM yet, call createDom now
// to make sure we render the child component's element into the correct
// parent element (otherwise render_ with a null first argument would
// render the child into the document body, which is almost certainly not
// what we want).
if (!this.element_) {
this.createDom();
}
// Render the child into the parent at the appropriate location. Note that
// getChildAt(index + 1) returns undefined if inserting at the end.
// TODO(attila): We should have a renderer with a renderChildAt API.
var sibling = this.getChildAt(index + 1);
// render_() calls enterDocument() if the parent is already in the document.
child.render_(this.getContentElement(), sibling ? sibling.element_ : null);
} else if (this.inDocument_ && !child.inDocument_ && child.element_ &&
child.element_.parentNode &&
// Under some circumstances, IE8 implicitly creates a Document Fragment
// for detached nodes, so ensure the parent is an Element as it should be.
child.element_.parentNode.nodeType == goog.dom.NodeType.ELEMENT) {
// We don't touch the DOM, but if the parent is in the document, and the
// child element is in the document but not marked as such, then we call
// enterDocument on the child.
// TODO(gboyer): It would be nice to move this condition entirely, but
// there's a large risk of breaking existing applications that manually
// append the child to the DOM and then call addChild.
child.enterDocument();
}
};
/**
* Returns the DOM element into which child components are to be rendered,
* or null if the component itself hasn't been rendered yet. This default
* implementation returns the component's root element. Subclasses with
* complex DOM structures must override this method.
* @return {Element} Element to contain child elements (null if none).
*/
goog.ui.Component.prototype.getContentElement = function() {
return this.element_;
};
/**
* Returns true if the component is rendered right-to-left, false otherwise.
* The first time this function is invoked, the right-to-left rendering property
* is set if it has not been already.
* @return {boolean} Whether the control is rendered right-to-left.
*/
goog.ui.Component.prototype.isRightToLeft = function() {
if (this.rightToLeft_ == null) {
this.rightToLeft_ = goog.style.isRightToLeft(this.inDocument_ ?
this.element_ : this.dom_.getDocument().body);
}
return /** @type {boolean} */(this.rightToLeft_);
};
/**
* Set is right-to-left. This function should be used if the component needs
* to know the rendering direction during dom creation (i.e. before
* {@link #enterDocument} is called and is right-to-left is set).
* @param {boolean} rightToLeft Whether the component is rendered
* right-to-left.
*/
goog.ui.Component.prototype.setRightToLeft = function(rightToLeft) {
if (this.inDocument_) {
throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
}
this.rightToLeft_ = rightToLeft;
};
/**
* Returns true if the component has children.
* @return {boolean} True if the component has children.
*/
goog.ui.Component.prototype.hasChildren = function() {
return !!this.children_ && this.children_.length != 0;
};
/**
* Returns the number of children of this component.
* @return {number} The number of children.
*/
goog.ui.Component.prototype.getChildCount = function() {
return this.children_ ? this.children_.length : 0;
};
/**
* Returns an array containing the IDs of the children of this component, or an
* empty array if the component has no children.
* @return {Array.<string>} Child component IDs.
*/
goog.ui.Component.prototype.getChildIds = function() {
var ids = [];
// We don't use goog.object.getKeys(this.childIndex_) because we want to
// return the IDs in the correct order as determined by this.children_.
this.forEachChild(function(child) {
// addChild()/addChildAt() guarantee that the child array isn't sparse.
ids.push(child.getId());
});
return ids;
};
/**
* Returns the child with the given ID, or null if no such child exists.
* @param {string} id Child component ID.
* @return {goog.ui.Component?} The child with the given ID; null if none.
*/
goog.ui.Component.prototype.getChild = function(id) {
// Use childIndex_ for O(1) access by ID.
return (this.childIndex_ && id) ? /** @type {goog.ui.Component} */ (
goog.object.get(this.childIndex_, id)) || null : null;
};
/**
* Returns the child at the given index, or null if the index is out of bounds.
* @param {number} index 0-based index.
* @return {goog.ui.Component?} The child at the given index; null if none.
*/
goog.ui.Component.prototype.getChildAt = function(index) {
// Use children_ for access by index.
return this.children_ ? this.children_[index] || null : null;
};
/**
* Calls the given function on each of this component's children in order. If
* {@code opt_obj} is provided, it will be used as the 'this' object in the
* function when called. The function should take two arguments: the child
* component and its 0-based index. The return value is ignored.
* @param {function(this:T,?,number):?} f The function to call for every
* child component; should take 2 arguments (the child and its index).
* @param {T=} opt_obj Used as the 'this' object in f when called.
* @template T
*/
goog.ui.Component.prototype.forEachChild = function(f, opt_obj) {
if (this.children_) {
goog.array.forEach(this.children_, f, opt_obj);
}
};
/**
* Returns the 0-based index of the given child component, or -1 if no such
* child is found.
* @param {goog.ui.Component?} child The child component.
* @return {number} 0-based index of the child component; -1 if not found.
*/
goog.ui.Component.prototype.indexOfChild = function(child) {
return (this.children_ && child) ? goog.array.indexOf(this.children_, child) :
-1;
};
/**
* Removes the given child from this component, and returns it. Throws an error
* if the argument is invalid or if the specified child isn't found in the
* parent component. The argument can either be a string (interpreted as the
* ID of the child component to remove) or the child component itself.
*
* If {@code opt_unrender} is true, calls {@link goog.ui.component#exitDocument}
* on the removed child, and subsequently detaches the child's DOM from the
* document. Otherwise it is the caller's responsibility to clean up the child
* component's DOM.
*
* @see goog.ui.Component#removeChildAt
* @param {string|goog.ui.Component|null} child The ID of the child to remove,
* or the child component itself.
* @param {boolean=} opt_unrender If true, calls {@code exitDocument} on the
* removed child component, and detaches its DOM from the document.
* @return {goog.ui.Component} The removed component, if any.
*/
goog.ui.Component.prototype.removeChild = function(child, opt_unrender) {
if (child) {
// Normalize child to be the object and id to be the ID string. This also
// ensures that the child is really ours.
var id = goog.isString(child) ? child : child.getId();
child = this.getChild(id);
if (id && child) {
goog.object.remove(this.childIndex_, id);
goog.array.remove(this.children_, child);
if (opt_unrender) {
// Remove the child component's DOM from the document. We have to call
// exitDocument first (see documentation).
child.exitDocument();
if (child.element_) {
goog.dom.removeNode(child.element_);
}
}
// Child's parent must be set to null after exitDocument is called
// so that the child can unlisten to its parent if required.
child.setParent(null);
}
}
if (!child) {
throw Error(goog.ui.Component.Error.NOT_OUR_CHILD);
}
return /** @type {goog.ui.Component} */(child);
};
/**
* Removes the child at the given index from this component, and returns it.
* Throws an error if the argument is out of bounds, or if the specified child
* isn't found in the parent. See {@link goog.ui.Component#removeChild} for
* detailed semantics.
*
* @see goog.ui.Component#removeChild
* @param {number} index 0-based index of the child to remove.
* @param {boolean=} opt_unrender If true, calls {@code exitDocument} on the
* removed child component, and detaches its DOM from the document.
* @return {goog.ui.Component} The removed component, if any.
*/
goog.ui.Component.prototype.removeChildAt = function(index, opt_unrender) {
// removeChild(null) will throw error.
return this.removeChild(this.getChildAt(index), opt_unrender);
};
/**
* Removes every child component attached to this one and returns them.
*
* @see goog.ui.Component#removeChild
* @param {boolean=} opt_unrender If true, calls {@link #exitDocument} on the
* removed child components, and detaches their DOM from the document.
* @return {!Array.<goog.ui.Component>} The removed components if any.
*/
goog.ui.Component.prototype.removeChildren = function(opt_unrender) {
var removedChildren = [];
while (this.hasChildren()) {
removedChildren.push(this.removeChildAt(0, opt_unrender));
}
return removedChildren;
};
| 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 Twothumbslider is a slider that allows to select a subrange
* within a range by dragging two thumbs. The selected sub-range is exposed
* through getValue() and getExtent().
*
* To decorate, the twothumbslider should be bound to an element with the class
* name 'goog-twothumbslider-[vertical / horizontal]' containing children with
* the classname 'goog-twothumbslider-value-thumb' and
* 'goog-twothumbslider-extent-thumb', respectively.
*
* Decorate Example:
* <div id="twothumbslider" class="goog-twothumbslider-horizontal">
* <div class="goog-twothumbslider-value-thumb">
* <div class="goog-twothumbslider-extent-thumb">
* </div>
* <script>
*
* var slider = new goog.ui.TwoThumbSlider;
* slider.decorate(document.getElementById('twothumbslider'));
*
* TODO(user): add a11y once we know what this element is
*
* @see ../demos/twothumbslider.html
*/
goog.provide('goog.ui.TwoThumbSlider');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.Role');
goog.require('goog.dom');
goog.require('goog.ui.SliderBase');
/**
* This creates a TwoThumbSlider object.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @constructor
* @extends {goog.ui.SliderBase}
*/
goog.ui.TwoThumbSlider = function(opt_domHelper) {
goog.ui.SliderBase.call(this, opt_domHelper);
this.rangeModel.setValue(this.getMinimum());
this.rangeModel.setExtent(this.getMaximum() - this.getMinimum());
};
goog.inherits(goog.ui.TwoThumbSlider, goog.ui.SliderBase);
/**
* The prefix we use for the CSS class names for the slider and its elements.
* @type {string}
*/
goog.ui.TwoThumbSlider.CSS_CLASS_PREFIX =
goog.getCssName('goog-twothumbslider');
/**
* CSS class name for the value thumb element.
* @type {string}
*/
goog.ui.TwoThumbSlider.VALUE_THUMB_CSS_CLASS =
goog.getCssName(goog.ui.TwoThumbSlider.CSS_CLASS_PREFIX, 'value-thumb');
/**
* CSS class name for the extent thumb element.
* @type {string}
*/
goog.ui.TwoThumbSlider.EXTENT_THUMB_CSS_CLASS =
goog.getCssName(goog.ui.TwoThumbSlider.CSS_CLASS_PREFIX, 'extent-thumb');
/**
* CSS class name for the range highlight element.
* @type {string}
*/
goog.ui.TwoThumbSlider.RANGE_HIGHLIGHT_CSS_CLASS =
goog.getCssName(goog.ui.TwoThumbSlider.CSS_CLASS_PREFIX, 'rangehighlight');
/**
* @param {goog.ui.SliderBase.Orientation} orient orientation of the slider.
* @return {string} The CSS class applied to the twothumbslider element.
* @protected
* @override
*/
goog.ui.TwoThumbSlider.prototype.getCssClass = function(orient) {
return orient == goog.ui.SliderBase.Orientation.VERTICAL ?
goog.getCssName(goog.ui.TwoThumbSlider.CSS_CLASS_PREFIX, 'vertical') :
goog.getCssName(goog.ui.TwoThumbSlider.CSS_CLASS_PREFIX, 'horizontal');
};
/**
* This creates a thumb element with the specified CSS class name.
* @param {string} cs CSS class name of the thumb to be created.
* @return {HTMLDivElement} The created thumb element.
* @private
*/
goog.ui.TwoThumbSlider.prototype.createThumb_ = function(cs) {
var thumb = this.getDomHelper().createDom('div', cs);
goog.a11y.aria.setRole(thumb, goog.a11y.aria.Role.BUTTON);
return /** @type {HTMLDivElement} */ (thumb);
};
/**
* Creates the thumb members for a twothumbslider. If the
* element contains a child with a class name 'goog-twothumbslider-value-thumb'
* (or 'goog-twothumbslider-extent-thumb', respectively), then that will be used
* as the valueThumb (or as the extentThumb, respectively). If the element
* contains a child with a class name 'goog-twothumbslider-rangehighlight',
* then that will be used as the range highlight.
* @override
*/
goog.ui.TwoThumbSlider.prototype.createThumbs = function() {
// find range highlight and thumbs
var valueThumb = goog.dom.getElementsByTagNameAndClass(
null, goog.ui.TwoThumbSlider.VALUE_THUMB_CSS_CLASS, this.getElement())[0];
var extentThumb = goog.dom.getElementsByTagNameAndClass(null,
goog.ui.TwoThumbSlider.EXTENT_THUMB_CSS_CLASS, this.getElement())[0];
var rangeHighlight = goog.dom.getElementsByTagNameAndClass(null,
goog.ui.TwoThumbSlider.RANGE_HIGHLIGHT_CSS_CLASS, this.getElement())[0];
if (!valueThumb) {
valueThumb =
this.createThumb_(goog.ui.TwoThumbSlider.VALUE_THUMB_CSS_CLASS);
this.getElement().appendChild(valueThumb);
}
if (!extentThumb) {
extentThumb =
this.createThumb_(goog.ui.TwoThumbSlider.EXTENT_THUMB_CSS_CLASS);
this.getElement().appendChild(extentThumb);
}
if (!rangeHighlight) {
rangeHighlight = this.getDomHelper().createDom('div',
goog.ui.TwoThumbSlider.RANGE_HIGHLIGHT_CSS_CLASS);
// Insert highlight before value thumb so that it renders under the thumbs.
this.getDomHelper().insertSiblingBefore(rangeHighlight, valueThumb);
}
this.valueThumb = valueThumb;
this.extentThumb = extentThumb;
this.rangeHighlight = rangeHighlight;
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A customized MenuButton for selection of items among lists.
* Menu contains 'select all' and 'select none' MenuItems for selecting all and
* no items by default. Other MenuItems can be added by user.
*
* The checkbox content fires the action events associated with the 'select all'
* and 'select none' menu items.
*
* @see ../demos/selectionmenubutton.html
*/
goog.provide('goog.ui.SelectionMenuButton');
goog.provide('goog.ui.SelectionMenuButton.SelectionState');
goog.require('goog.events.EventType');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.Menu');
goog.require('goog.ui.MenuButton');
goog.require('goog.ui.MenuItem');
/**
* A selection menu button control. Extends {@link goog.ui.MenuButton}.
* Menu contains 'select all' and 'select none' MenuItems for selecting all and
* no items by default. Other MenuItems can be added by user.
*
* The checkbox content fires the action events associated with the 'select all'
* and 'select none' menu items.
*
* @param {goog.ui.ButtonRenderer=} opt_renderer Renderer used to render or
* decorate the menu button; defaults to {@link goog.ui.MenuButtonRenderer}.
* @param {goog.ui.MenuItemRenderer=} opt_itemRenderer Optional menu item
* renderer.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
* document interaction.
* @constructor
* @extends {goog.ui.MenuButton}
*/
goog.ui.SelectionMenuButton = function(opt_renderer,
opt_itemRenderer,
opt_domHelper) {
goog.ui.MenuButton.call(this,
null,
null,
opt_renderer,
opt_domHelper);
this.initialItemRenderer_ = opt_itemRenderer || null;
};
goog.inherits(goog.ui.SelectionMenuButton, goog.ui.MenuButton);
/**
* Constants for menu action types.
* @enum {number}
*/
goog.ui.SelectionMenuButton.SelectionState = {
ALL: 0,
SOME: 1,
NONE: 2
};
/**
* Select button state
* @type {goog.ui.SelectionMenuButton.SelectionState}
* @protected
*/
goog.ui.SelectionMenuButton.prototype.selectionState =
goog.ui.SelectionMenuButton.SelectionState.NONE;
/**
* Item renderer used for the first 2 items, 'select all' and 'select none'.
* @type {goog.ui.MenuItemRenderer}
* @private
*/
goog.ui.SelectionMenuButton.prototype.initialItemRenderer_;
/**
* Enables button and embedded checkbox.
* @param {boolean} enable Whether to enable or disable the button.
* @override
*/
goog.ui.SelectionMenuButton.prototype.setEnabled = function(enable) {
goog.base(this, 'setEnabled', enable);
this.setCheckboxEnabled(enable);
};
/**
* Enables the embedded checkbox.
* @param {boolean} enable Whether to enable or disable the checkbox.
* @protected
*/
goog.ui.SelectionMenuButton.prototype.setCheckboxEnabled = function(enable) {
this.getCheckboxElement().disabled = !enable;
};
/** @override */
goog.ui.SelectionMenuButton.prototype.handleMouseDown = function(e) {
if (!this.getDomHelper().contains(this.getCheckboxElement(),
/** @type {Element} */ (e.target))) {
goog.ui.SelectionMenuButton.superClass_.handleMouseDown.call(this, e);
}
};
/**
* Gets the checkbox element. Needed because if decorating html, getContent()
* may include and comment/text elements in addition to the input element.
* @return {Element} Checkbox.
* @protected
*/
goog.ui.SelectionMenuButton.prototype.getCheckboxElement = function() {
var elements = this.getDomHelper().getElementsByTagNameAndClass(
'input',
goog.getCssName('goog-selectionmenubutton-checkbox'),
this.getContentElement());
return elements[0];
};
/**
* Checkbox click handler.
* @param {goog.events.BrowserEvent} e Checkbox click event.
* @protected
*/
goog.ui.SelectionMenuButton.prototype.handleCheckboxClick = function(e) {
if (this.selectionState == goog.ui.SelectionMenuButton.SelectionState.NONE) {
this.setSelectionState(goog.ui.SelectionMenuButton.SelectionState.ALL);
if (this.getItemAt(0)) {
this.getItemAt(0).dispatchEvent( // 'All' item
goog.ui.Component.EventType.ACTION);
}
} else {
this.setSelectionState(goog.ui.SelectionMenuButton.SelectionState.NONE);
if (this.getItemAt(1)) {
this.getItemAt(1).dispatchEvent( // 'None' item
goog.ui.Component.EventType.ACTION);
}
}
};
/**
* Menu action handler to update checkbox checked state.
* @param {goog.events.Event} e Menu action event.
* @private
*/
goog.ui.SelectionMenuButton.prototype.handleMenuAction_ = function(e) {
if (e.target.getModel() == goog.ui.SelectionMenuButton.SelectionState.ALL) {
this.setSelectionState(goog.ui.SelectionMenuButton.SelectionState.ALL);
} else {
this.setSelectionState(goog.ui.SelectionMenuButton.SelectionState.NONE);
}
};
/**
* Set up events related to the menu items.
* @private
*/
goog.ui.SelectionMenuButton.prototype.addMenuEvent_ = function() {
if (this.getItemAt(0) && this.getItemAt(1)) {
this.getHandler().listen(this.getMenu(),
goog.ui.Component.EventType.ACTION,
this.handleMenuAction_);
this.getItemAt(0).setModel(goog.ui.SelectionMenuButton.SelectionState.ALL);
this.getItemAt(1).setModel(goog.ui.SelectionMenuButton.SelectionState.NONE);
}
};
/**
* Set up events related to the checkbox.
* @protected
*/
goog.ui.SelectionMenuButton.prototype.addCheckboxEvent = function() {
this.getHandler().listen(this.getCheckboxElement(),
goog.events.EventType.CLICK,
this.handleCheckboxClick);
};
/**
* Adds the checkbox to the button, and adds 2 items to the menu corresponding
* to 'select all' and 'select none'.
* @override
* @protected
*/
goog.ui.SelectionMenuButton.prototype.createDom = function() {
goog.ui.SelectionMenuButton.superClass_.createDom.call(this);
this.createCheckbox();
/** @desc Text for 'All' button, used to select all items in a list. */
var MSG_SELECTIONMENUITEM_ALL = goog.getMsg('All');
/** @desc Text for 'None' button, used to unselect all items in a list. */
var MSG_SELECTIONMENUITEM_NONE = goog.getMsg('None');
var itemAll = new goog.ui.MenuItem(MSG_SELECTIONMENUITEM_ALL,
null,
this.getDomHelper(),
this.initialItemRenderer_);
var itemNone = new goog.ui.MenuItem(MSG_SELECTIONMENUITEM_NONE,
null,
this.getDomHelper(),
this.initialItemRenderer_);
this.addItem(itemAll);
this.addItem(itemNone);
this.addCheckboxEvent();
this.addMenuEvent_();
};
/**
* Creates and adds the checkbox to the button.
* @protected
*/
goog.ui.SelectionMenuButton.prototype.createCheckbox = function() {
var checkbox = this.getDomHelper().createElement('input');
checkbox.type = 'checkbox';
checkbox.className = goog.getCssName('goog-selectionmenubutton-checkbox');
this.setContent(checkbox);
};
/** @override */
goog.ui.SelectionMenuButton.prototype.decorateInternal = function(element) {
goog.ui.SelectionMenuButton.superClass_.decorateInternal.call(this, element);
this.addCheckboxEvent();
this.addMenuEvent_();
};
/** @override */
goog.ui.SelectionMenuButton.prototype.setMenu = function(menu) {
goog.ui.SelectionMenuButton.superClass_.setMenu.call(this, menu);
this.addMenuEvent_();
};
/**
* Set selection state and update checkbox.
* @param {goog.ui.SelectionMenuButton.SelectionState} state Selection state.
*/
goog.ui.SelectionMenuButton.prototype.setSelectionState = function(state) {
if (this.selectionState != state) {
var checkbox = this.getCheckboxElement();
if (state == goog.ui.SelectionMenuButton.SelectionState.ALL) {
checkbox.checked = true;
goog.style.setOpacity(checkbox, 1);
} else if (state == goog.ui.SelectionMenuButton.SelectionState.SOME) {
checkbox.checked = true;
// TODO(user): Get UX help to style this
goog.style.setOpacity(checkbox, 0.5);
} else { // NONE
checkbox.checked = false;
goog.style.setOpacity(checkbox, 1);
}
this.selectionState = state;
}
};
/**
* Get selection state.
* @return {goog.ui.SelectionMenuButton.SelectionState} Selection state.
*/
goog.ui.SelectionMenuButton.prototype.getSelectionState = function() {
return this.selectionState;
};
// Register a decorator factory function for goog.ui.SelectionMenuButton.
goog.ui.registry.setDecoratorByClassName(
goog.getCssName('goog-selectionmenubutton-button'),
function() {
return new goog.ui.SelectionMenuButton();
});
| 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 toolbar separator control.
*
* @author attila@google.com (Attila Bodis)
* @author ssaviano@google.com (Steven Saviano)
*/
goog.provide('goog.ui.ToolbarSeparator');
goog.require('goog.ui.Separator');
goog.require('goog.ui.ToolbarSeparatorRenderer');
goog.require('goog.ui.registry');
/**
* A separator control for a toolbar.
*
* @param {goog.ui.ToolbarSeparatorRenderer=} opt_renderer Renderer to render or
* decorate the separator; defaults to
* {@link goog.ui.ToolbarSeparatorRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
* document interaction.
* @constructor
* @extends {goog.ui.Separator}
*/
goog.ui.ToolbarSeparator = function(opt_renderer, opt_domHelper) {
goog.ui.Separator.call(this, opt_renderer ||
goog.ui.ToolbarSeparatorRenderer.getInstance(), opt_domHelper);
};
goog.inherits(goog.ui.ToolbarSeparator, goog.ui.Separator);
// Registers a decorator factory function for toolbar separators.
goog.ui.registry.setDecoratorByClassName(
goog.ui.ToolbarSeparatorRenderer.CSS_CLASS,
function() {
return new goog.ui.ToolbarSeparator();
});
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A class for representing menu headers.
* @see goog.ui.Menu
*
*/
goog.provide('goog.ui.MenuHeader');
goog.require('goog.ui.Component.State');
goog.require('goog.ui.Control');
goog.require('goog.ui.MenuHeaderRenderer');
goog.require('goog.ui.registry');
/**
* Class representing a menu header.
* @param {goog.ui.ControlContent} content Text caption or DOM structure to
* display as the content of the item (use to add icons or styling to
* menus).
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper used for
* document interactions.
* @param {goog.ui.MenuHeaderRenderer=} opt_renderer Optional renderer.
* @constructor
* @extends {goog.ui.Control}
*/
goog.ui.MenuHeader = function(content, opt_domHelper, opt_renderer) {
goog.ui.Control.call(this, content, opt_renderer ||
goog.ui.MenuHeaderRenderer.getInstance(), opt_domHelper);
this.setSupportedState(goog.ui.Component.State.DISABLED, false);
this.setSupportedState(goog.ui.Component.State.HOVER, false);
this.setSupportedState(goog.ui.Component.State.ACTIVE, false);
this.setSupportedState(goog.ui.Component.State.FOCUSED, false);
// Headers are always considered disabled.
this.setStateInternal(goog.ui.Component.State.DISABLED);
};
goog.inherits(goog.ui.MenuHeader, goog.ui.Control);
// Register a decorator factory function for goog.ui.MenuHeaders.
goog.ui.registry.setDecoratorByClassName(
goog.ui.MenuHeaderRenderer.CSS_CLASS,
function() {
// MenuHeader defaults to using MenuHeaderRenderer.
return new goog.ui.MenuHeader(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 Component for an input field with bidi direction automatic
* detection. The input element directionality is automatically set according
* to the contents (value) of the element.
*
* @see ../demos/bidiinput.html
*/
goog.provide('goog.ui.BidiInput');
goog.require('goog.events');
goog.require('goog.events.InputHandler');
goog.require('goog.i18n.bidi');
goog.require('goog.ui.Component');
/**
* Default implementation of BidiInput.
*
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @constructor
* @extends {goog.ui.Component}
*/
goog.ui.BidiInput = function(opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
};
goog.inherits(goog.ui.BidiInput, goog.ui.Component);
/**
* The input handler that provides the input event.
* @type {goog.events.InputHandler?}
* @private
*/
goog.ui.BidiInput.prototype.inputHandler_ = null;
/**
* Decorates the given HTML element as a BidiInput. The HTML element
* must be an input element with type='text' or a textarea element.
* Overrides {@link goog.ui.Component#decorateInternal}. Considered protected.
* @param {Element} element Element (HTML Input element) to decorate.
* @protected
* @override
*/
goog.ui.BidiInput.prototype.decorateInternal = function(element) {
goog.ui.BidiInput.superClass_.decorateInternal.call(this, element);
this.init_();
};
/**
* Creates the element for the text input.
* @protected
* @override
*/
goog.ui.BidiInput.prototype.createDom = function() {
this.setElementInternal(
this.getDomHelper().createDom('input', {'type': 'text'}));
this.init_();
};
/**
* Initializes the events and initial text direction.
* Called from either decorate or createDom, after the input field has
* been created.
* @private
*/
goog.ui.BidiInput.prototype.init_ = function() {
// Set initial direction by current text
this.setDirection_();
// Listen to value change events
this.inputHandler_ = new goog.events.InputHandler(this.getElement());
goog.events.listen(this.inputHandler_,
goog.events.InputHandler.EventType.INPUT,
this.setDirection_, false, this);
};
/**
* Set the direction of the input element based on the current value. If the
* value does not have any strongly directional characters, remove the dir
* attribute so that the direction is inherited instead.
* This method is called when the user changes the input element value, or
* when a program changes the value using
* {@link goog.ui.BidiInput#setValue}
* @private
*/
goog.ui.BidiInput.prototype.setDirection_ = function() {
var element = this.getElement();
var text = element.value;
switch (goog.i18n.bidi.estimateDirection(text)) {
case (goog.i18n.bidi.Dir.LTR):
element.dir = 'ltr';
break;
case (goog.i18n.bidi.Dir.RTL):
element.dir = 'rtl';
break;
default:
// Default for no direction, inherit from document.
element.removeAttribute('dir');
}
};
/**
* Returns the direction of the input element.
* @return {?string} Return 'rtl' for right-to-left text,
* 'ltr' for left-to-right text, or null if the value itself is not
* enough to determine directionality (e.g. an empty value), and the
* direction is inherited from a parent element (typically the body
* element).
*/
goog.ui.BidiInput.prototype.getDirection = function() {
var dir = this.getElement().dir;
if (dir == '') {
dir = null;
}
return dir;
};
/**
* Sets the value of the underlying input field, and sets the direction
* according to the given value.
* @param {string} value The Value to set in the underlying input field.
*/
goog.ui.BidiInput.prototype.setValue = function(value) {
this.getElement().value = value;
this.setDirection_();
};
/**
* Returns the value of the underlying input field.
* @return {string} Value of the underlying input field.
*/
goog.ui.BidiInput.prototype.getValue = function() {
return this.getElement().value;
};
/** @override */
goog.ui.BidiInput.prototype.disposeInternal = function() {
if (this.inputHandler_) {
goog.events.removeAll(this.inputHandler_);
this.inputHandler_.dispose();
this.inputHandler_ = null;
goog.ui.BidiInput.superClass_.disposeInternal.call(this);
}
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Renderer for {@link goog.ui.MenuButton}s and subclasses.
*
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.ui.MenuButtonRenderer');
goog.require('goog.dom');
goog.require('goog.style');
goog.require('goog.ui.CustomButtonRenderer');
goog.require('goog.ui.INLINE_BLOCK_CLASSNAME');
goog.require('goog.ui.Menu');
goog.require('goog.ui.MenuRenderer');
goog.require('goog.userAgent');
/**
* Renderer for {@link goog.ui.MenuButton}s. This implementation overrides
* {@link goog.ui.CustomButtonRenderer#createButton} to create a separate
* caption and dropdown element.
* @constructor
* @extends {goog.ui.CustomButtonRenderer}
*/
goog.ui.MenuButtonRenderer = function() {
goog.ui.CustomButtonRenderer.call(this);
};
goog.inherits(goog.ui.MenuButtonRenderer, goog.ui.CustomButtonRenderer);
goog.addSingletonGetter(goog.ui.MenuButtonRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.MenuButtonRenderer.CSS_CLASS = goog.getCssName('goog-menu-button');
/**
* A property to denote content elements that have been wrapped in an extra
* div to work around FF2/RTL bugs.
* @type {string}
* @private
*/
goog.ui.MenuButtonRenderer.WRAPPER_PROP_ = '__goog_wrapper_div';
if (goog.userAgent.GECKO) {
/**
* Takes the menubutton's root element, and sets its content to the given
* text caption or DOM structure. Because the DOM structure of this button is
* conditional based on whether we need to work around FF2/RTL bugs, we
* override the default implementation to take this into account.
* @param {Element} element The control's root element.
* @param {goog.ui.ControlContent} content Text caption or DOM
* structure to be set as the control's content.
* @override
*/
goog.ui.MenuButtonRenderer.prototype.setContent = function(element,
content) {
var caption =
goog.ui.MenuButtonRenderer.superClass_.getContentElement.call(this,
/** @type {Element} */ (element && element.firstChild));
if (caption) {
goog.dom.replaceNode(
this.createCaption(content, goog.dom.getDomHelper(element)),
caption);
}
};
} // end goog.userAgent.GECKO
/**
* Takes the button's root element and returns the parent element of the
* button's contents. Overrides the superclass implementation by taking
* the nested DIV structure of menu buttons into account.
* @param {Element} element Root element of the button whose content element
* is to be returned.
* @return {Element} The button's content element.
* @override
*/
goog.ui.MenuButtonRenderer.prototype.getContentElement = function(element) {
var content =
goog.ui.MenuButtonRenderer.superClass_.getContentElement.call(this,
/** @type {Element} */ (element && element.firstChild));
if (goog.userAgent.GECKO && content &&
content[goog.ui.MenuButtonRenderer.WRAPPER_PROP_]) {
content = /** @type {Element} */ (content.firstChild);
}
return content;
};
/**
* Takes an element, decorates it with the menu button control, and returns
* the element. Overrides {@link goog.ui.CustomButtonRenderer#decorate} by
* looking for a child element that can be decorated by a menu, and if it
* finds one, decorates it and attaches it to the menu button.
* @param {goog.ui.Control} control goog.ui.MenuButton to decorate the element.
* @param {Element} element Element to decorate.
* @return {Element} Decorated element.
* @override
*/
goog.ui.MenuButtonRenderer.prototype.decorate = function(control, element) {
var button = /** @type {goog.ui.MenuButton} */ (control);
// TODO(attila): Add more robust support for subclasses of goog.ui.Menu.
var menuElem = goog.dom.getElementsByTagNameAndClass(
'*', goog.ui.MenuRenderer.CSS_CLASS, element)[0];
if (menuElem) {
// Move the menu element directly under the body (but hide it first to
// prevent flicker; see bug 1089244).
goog.style.setElementShown(menuElem, false);
goog.dom.appendChild(goog.dom.getOwnerDocument(menuElem).body, menuElem);
// Decorate the menu and attach it to the button.
var menu = new goog.ui.Menu();
menu.decorate(menuElem);
button.setMenu(menu);
}
// Let the superclass do the rest.
return goog.ui.MenuButtonRenderer.superClass_.decorate.call(this, button,
element);
};
/**
* Takes a text caption or existing DOM structure, and returns the content and
* a dropdown arrow element wrapped in a pseudo-rounded-corner box. Creates
* the following DOM structure:
* <div class="goog-inline-block goog-menu-button-outer-box">
* <div class="goog-inline-block goog-menu-button-inner-box">
* <div class="goog-inline-block goog-menu-button-caption">
* Contents...
* </div>
* <div class="goog-inline-block goog-menu-button-dropdown">
*
* </div>
* </div>
* </div>
* @param {goog.ui.ControlContent} content Text caption or DOM structure
* to wrap in a box.
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Pseudo-rounded-corner box containing the content.
* @override
*/
goog.ui.MenuButtonRenderer.prototype.createButton = function(content, dom) {
return goog.ui.MenuButtonRenderer.superClass_.createButton.call(this,
[this.createCaption(content, dom), this.createDropdown(dom)], dom);
};
/**
* Takes a text caption or existing DOM structure, and returns it wrapped in
* an appropriately-styled DIV. Creates the following DOM structure:
* <div class="goog-inline-block goog-menu-button-caption">
* Contents...
* </div>
* @param {goog.ui.ControlContent} content Text caption or DOM structure
* to wrap in a box.
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Caption element.
*/
goog.ui.MenuButtonRenderer.prototype.createCaption = function(content, dom) {
return goog.ui.MenuButtonRenderer.wrapCaption(
content, this.getCssClass(), dom);
};
/**
* Takes a text caption or existing DOM structure, and returns it wrapped in
* an appropriately-styled DIV. Creates the following DOM structure:
* <div class="goog-inline-block goog-menu-button-caption">
* Contents...
* </div>
* @param {goog.ui.ControlContent} content Text caption or DOM structure
* to wrap in a box.
* @param {string} cssClass The CSS class for the renderer.
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Caption element.
*/
goog.ui.MenuButtonRenderer.wrapCaption = function(content, cssClass, dom) {
return dom.createDom(
'div',
goog.ui.INLINE_BLOCK_CLASSNAME + ' ' +
goog.getCssName(cssClass, 'caption'),
content);
};
/**
* Returns an appropriately-styled DIV containing a dropdown arrow element.
* Creates the following DOM structure:
* <div class="goog-inline-block goog-menu-button-dropdown">
*
* </div>
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Dropdown element.
*/
goog.ui.MenuButtonRenderer.prototype.createDropdown = function(dom) {
// 00A0 is
return dom.createDom('div',
goog.ui.INLINE_BLOCK_CLASSNAME + ' ' +
goog.getCssName(this.getCssClass(), 'dropdown'), '\u00A0');
};
/**
* Returns the CSS class to be applied to the root element of components
* rendered using this renderer.
* @return {string} Renderer-specific CSS class.
* @override
*/
goog.ui.MenuButtonRenderer.prototype.getCssClass = function() {
return goog.ui.MenuButtonRenderer.CSS_CLASS;
};
| 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 Renderer for {@link goog.ui.ColorMenuButton}s.
*
* @author robbyw@google.com (Robby Walker)
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.ui.ColorMenuButtonRenderer');
goog.require('goog.color');
goog.require('goog.dom.classes');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.MenuButtonRenderer');
goog.require('goog.userAgent');
/**
* Renderer for {@link goog.ui.ColorMenuButton}s.
* @constructor
* @extends {goog.ui.MenuButtonRenderer}
*/
goog.ui.ColorMenuButtonRenderer = function() {
goog.ui.MenuButtonRenderer.call(this);
};
goog.inherits(goog.ui.ColorMenuButtonRenderer, goog.ui.MenuButtonRenderer);
goog.addSingletonGetter(goog.ui.ColorMenuButtonRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.ColorMenuButtonRenderer.CSS_CLASS =
goog.getCssName('goog-color-menu-button');
/**
* Overrides the superclass implementation by wrapping the caption text or DOM
* structure in a color indicator element. Creates the following DOM structure:
* <div class="goog-inline-block goog-menu-button-caption">
* <div class="goog-color-menu-button-indicator">
* Contents...
* </div>
* </div>
* The 'goog-color-menu-button-indicator' style should be defined to have a
* bottom border of nonzero width and a default color that blends into its
* background.
* @param {goog.ui.ControlContent} content Text caption or DOM structure.
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Caption element.
* @override
*/
goog.ui.ColorMenuButtonRenderer.prototype.createCaption = function(content,
dom) {
return goog.ui.ColorMenuButtonRenderer.superClass_.createCaption.call(this,
goog.ui.ColorMenuButtonRenderer.wrapCaption(content, dom), dom);
};
/**
* Wrap a caption in a div with the color-menu-button-indicator CSS class.
* @param {goog.ui.ControlContent} content Text caption or DOM structure.
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Caption element.
*/
goog.ui.ColorMenuButtonRenderer.wrapCaption = function(content, dom) {
return dom.createDom('div',
goog.getCssName(goog.ui.ColorMenuButtonRenderer.CSS_CLASS, 'indicator'),
content);
};
/**
* Takes a color menu button control's root element and a value object
* (which is assumed to be a color), and updates the button's DOM to reflect
* the new color. Overrides {@link goog.ui.ButtonRenderer#setValue}.
* @param {Element} element The button control's root element (if rendered).
* @param {*} value New value; assumed to be a color spec string.
* @override
*/
goog.ui.ColorMenuButtonRenderer.prototype.setValue = function(element, value) {
if (element) {
goog.ui.ColorMenuButtonRenderer.setCaptionValue(
this.getContentElement(element), value);
}
};
/**
* Takes a control's content element and a value object (which is assumed
* to be a color), and updates its DOM to reflect the new color.
* @param {Element} caption A content element of a control.
* @param {*} value New value; assumed to be a color spec string.
*/
goog.ui.ColorMenuButtonRenderer.setCaptionValue = function(caption, value) {
// Assume that the caption's first child is the indicator.
if (caption && caption.firstChild) {
// Normalize the value to a hex color spec or null (otherwise setting
// borderBottomColor will cause a JS error on IE).
var hexColor;
var strValue = /** @type {string} */ (value);
hexColor = strValue && goog.color.isValidColor(strValue) ?
goog.color.parse(strValue).hex :
null;
// Stupid IE6/7 doesn't do transparent borders.
// TODO(attila): Add user-agent version check when IE8 comes out...
caption.firstChild.style.borderBottomColor = hexColor ||
(goog.userAgent.IE ? '' : 'transparent');
}
};
/**
* Initializes the button's DOM when it enters the document. Overrides the
* superclass implementation by making sure the button's color indicator is
* initialized.
* @param {goog.ui.Control} button goog.ui.ColorMenuButton whose DOM is to be
* initialized as it enters the document.
* @override
*/
goog.ui.ColorMenuButtonRenderer.prototype.initializeDom = function(button) {
this.setValue(button.getElement(), button.getValue());
goog.dom.classes.add(button.getElement(),
goog.ui.ColorMenuButtonRenderer.CSS_CLASS);
goog.ui.ColorMenuButtonRenderer.superClass_.initializeDom.call(this,
button);
};
| 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.
goog.provide('goog.ui.equation.ChangeEvent');
goog.require('goog.events.Event');
goog.require('goog.events.EventType');
/**
* Event fired when equation changes.
* @constructor
* @param {boolean} isValid Whether the equation is valid.
* @extends {goog.events.Event}
*/
goog.ui.equation.ChangeEvent = function(isValid) {
goog.events.Event.call(this, 'change');
/**
* Whether equation is valid.
* @type {boolean}
*/
this.isValid = isValid;
};
goog.inherits(goog.ui.equation.ChangeEvent, 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.
goog.provide('goog.ui.equation.EquationEditorDialog');
goog.require('goog.dom');
goog.require('goog.ui.Dialog');
goog.require('goog.ui.Dialog.ButtonSet');
goog.require('goog.ui.equation.EquationEditor');
goog.require('goog.ui.equation.ImageRenderer');
goog.require('goog.ui.equation.PaletteManager');
goog.require('goog.ui.equation.TexEditor');
/**
* User interface for equation editor plugin standalone tests.
* @constructor
* @param {string=} opt_equation Encoded equation. If not specified, starts with
* an empty equation.
* @extends {goog.ui.Dialog}
*/
goog.ui.equation.EquationEditorDialog = function(opt_equation) {
goog.ui.Dialog.call(this);
this.setTitle('Equation Editor');
var buttonSet = new goog.ui.Dialog.ButtonSet();
buttonSet.set(goog.ui.Dialog.DefaultButtonKeys.OK,
opt_equation ? 'Save changes' : 'Insert equation',
true);
buttonSet.set(goog.ui.Dialog.DefaultButtonKeys.CANCEL,
'Cancel', false, true);
this.setButtonSet(buttonSet);
// Create the main editor contents.
var contentElement = this.getContentElement();
var domHelper = goog.dom.getDomHelper(contentElement);
var context = this.populateContext_();
/**
* The equation editor main API.
* @type {goog.ui.equation.TexEditor}
* @private
*/
this.equationEditor_ =
new goog.ui.equation.TexEditor(context, '', domHelper);
this.equationEditor_.addEventListener(
goog.ui.equation.EquationEditor.EventType.CHANGE,
this.onChange_, false, this);
this.equationEditor_.render(this.getContentElement());
this.setEquation(opt_equation || '');
goog.dom.classes.add(this.getDialogElement(), 'ee-modal-dialog');
};
goog.inherits(goog.ui.equation.EquationEditorDialog, goog.ui.Dialog);
/**
* The dialog's OK button element.
* @type {Element?}
* @private
*/
goog.ui.equation.EquationEditorDialog.prototype.okButton_;
/** @override */
goog.ui.equation.EquationEditorDialog.prototype.setVisible = function(visible) {
goog.base(this, 'setVisible', visible);
this.equationEditor_.setVisible(visible);
};
/**
* Populates the context of this dialog.
* @return {Object} The context that this dialog runs in.
* @private
*/
goog.ui.equation.EquationEditorDialog.prototype.populateContext_ = function() {
var context = {};
context.paletteManager = new goog.ui.equation.PaletteManager();
return context;
};
/**
* Handles CHANGE event fired when user changes equation.
* @param {goog.ui.equation.ChangeEvent} e The event object.
* @private
*/
goog.ui.equation.EquationEditorDialog.prototype.onChange_ = function(e) {
if (!this.okButton_) {
this.okButton_ = this.getButtonSet().getButton(
goog.ui.Dialog.DefaultButtonKeys.OK);
}
this.okButton_.disabled = !e.isValid;
};
/**
* Returns the encoded equation.
* @return {string} The encoded equation.
*/
goog.ui.equation.EquationEditorDialog.prototype.getEquation = function() {
return this.equationEditor_.getEquation();
};
/**
* Sets the encoded equation.
* @param {string} equation The encoded equation.
*/
goog.ui.equation.EquationEditorDialog.prototype.setEquation =
function(equation) {
this.equationEditor_.setEquation(equation);
};
/**
* @return {string} The html code to embed in the document.
*/
goog.ui.equation.EquationEditorDialog.prototype.getHtml = function() {
return this.equationEditor_.getHtml();
};
| 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.ui.equation.MenuPalette');
goog.provide('goog.ui.equation.MenuPaletteRenderer');
goog.require('goog.math.Size');
goog.require('goog.style');
goog.require('goog.ui.equation.Palette');
goog.require('goog.ui.equation.PaletteRenderer');
/**
* Constructs a new menu palette.
* @param {goog.ui.equation.PaletteManager} paletteManager The
* manager of the palette.
* @extends {goog.ui.equation.Palette}
* @constructor
*/
goog.ui.equation.MenuPalette = function(paletteManager) {
goog.ui.equation.Palette.call(this, paletteManager,
goog.ui.equation.Palette.Type.MENU,
0, 0, 46, 18,
[goog.ui.equation.Palette.Type.GREEK,
goog.ui.equation.Palette.Type.SYMBOL,
goog.ui.equation.Palette.Type.COMPARISON,
goog.ui.equation.Palette.Type.MATH,
goog.ui.equation.Palette.Type.ARROW],
goog.ui.equation.MenuPaletteRenderer.getInstance());
this.setSize(new goog.math.Size(5, 1));
};
goog.inherits(goog.ui.equation.MenuPalette, goog.ui.equation.Palette);
/**
* The CSS class name for the palette.
* @type {string}
*/
goog.ui.equation.MenuPalette.CSS_CLASS = 'ee-menu-palette';
/**
* Overrides the setVisible method to make menu palette always visible.
* @param {boolean} visible Whether to show or hide the component.
* @param {boolean=} opt_force If true, doesn't check whether the component
* already has the requested visibility, and doesn't dispatch any events.
* @return {boolean} Whether the visibility was changed.
* @override
*/
goog.ui.equation.MenuPalette.prototype.setVisible = function(
visible, opt_force) {
return goog.base(this, 'setVisible', true, opt_force);
};
/**
* The renderer for menu palette.
* @extends {goog.ui.equation.PaletteRenderer}
* @constructor
*/
goog.ui.equation.MenuPaletteRenderer = function() {
goog.ui.PaletteRenderer.call(this);
};
goog.inherits(goog.ui.equation.MenuPaletteRenderer,
goog.ui.equation.PaletteRenderer);
goog.addSingletonGetter(goog.ui.equation.MenuPaletteRenderer);
/** @override */
goog.ui.equation.MenuPaletteRenderer.prototype.getCssClass =
function() {
return goog.ui.equation.MenuPalette.CSS_CLASS;
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A palette of symbols.
*
*/
goog.provide('goog.ui.equation.SymbolPalette');
goog.require('goog.math.Size');
goog.require('goog.ui.equation.Palette');
/**
* Constructs a new symbols palette.
* @param {goog.ui.equation.PaletteManager} paletteManager The
* manager of the palette.
* @extends {goog.ui.equation.Palette}
* @constructor
*/
goog.ui.equation.SymbolPalette = function(paletteManager) {
goog.ui.equation.Palette.call(this, paletteManager,
goog.ui.equation.Palette.Type.SYMBOL,
0, 50, 18, 18,
['\\times',
'\\div',
'\\cdot',
'\\pm',
'\\mp',
'\\ast',
'\\star',
'\\circ',
'\\bullet',
'\\oplus',
'\\ominus',
'\\oslash',
'\\otimes',
'\\odot',
'\\dagger',
'\\ddagger',
'\\vee',
'\\wedge',
'\\cap',
'\\cup',
'\\aleph',
'\\Re',
'\\Im',
'\\top',
'\\bot',
'\\infty',
'\\partial',
'\\forall',
'\\exists',
'\\neg',
'\\angle',
'\\triangle',
'\\diamond']);
this.setSize(new goog.math.Size(7, 5));
};
goog.inherits(goog.ui.equation.SymbolPalette, goog.ui.equation.Palette);
| 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.ui.equation.TexPane');
goog.require('goog.Timer');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.selection');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.events.InputHandler');
goog.require('goog.string');
goog.require('goog.style');
goog.require('goog.ui.Component');
goog.require('goog.ui.equation.ChangeEvent');
goog.require('goog.ui.equation.EditorPane');
goog.require('goog.ui.equation.ImageRenderer');
goog.require('goog.ui.equation.PaletteManager');
/**
* User interface for TeX equation editor tab pane.
* @param {Object} context The context this Tex editor pane runs in.
* @param {string} helpUrl The help link URL.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @constructor
* @extends {goog.ui.equation.EditorPane}
*/
goog.ui.equation.TexPane = function(
context, helpUrl, opt_domHelper) {
goog.ui.equation.EditorPane.call(this, opt_domHelper);
this.setHelpUrl(helpUrl);
/**
* The palette manager instance.
* @type {goog.ui.equation.PaletteManager}
* @private
*/
this.paletteManager_ =
/** @type {goog.ui.equation.PaletteManager} */(
context.paletteManager);
};
goog.inherits(goog.ui.equation.TexPane,
goog.ui.equation.EditorPane);
/**
* The CSS class name for the preview container.
* @type {string}
*/
goog.ui.equation.TexPane.PREVIEW_CONTAINER_CSS_CLASS =
'ee-preview-container';
/**
* The CSS class name for section titles.
* @type {string}
*/
goog.ui.equation.TexPane.SECTION_TITLE_CSS_CLASS =
'ee-section-title';
/**
* The CSS class name for section titles that float left.
* @type {string}
*/
goog.ui.equation.TexPane.SECTION_TITLE_FLOAT_CSS_CLASS =
'ee-section-title-floating';
/**
* The CSS id name for the link to "Learn more".
* @type {string}
*/
goog.ui.equation.TexPane.SECTION_LEARN_MORE_CSS_ID =
'ee-section-learn-more';
/**
* The CSS class name for the Tex editor.
* @type {string}
*/
goog.ui.equation.TexPane.TEX_EDIT_CSS_CLASS = 'ee-tex';
/**
* The CSS class name for the preview container.
* @type {string}
*/
goog.ui.equation.TexPane.WARNING_CLASS =
'ee-warning';
/**
* The content div of the TeX editor.
* @type {Element}
* @private
*/
goog.ui.equation.TexPane.prototype.texEditorElement_ = null;
/**
* The container div for the server-generated image of the equation.
* @type {Element}
* @private
*/
goog.ui.equation.TexPane.prototype.previewContainer_;
/**
* An inner container used to layout all the elements in Tex Editor.
* @type {Element}
* @private
*/
goog.ui.equation.TexPane.prototype.innerContainer_;
/**
* The textarea for free form TeX.
* @type {Element}
* @private
*/
goog.ui.equation.TexPane.prototype.texEdit_;
/**
* The input handler for Tex editor.
* @type {goog.events.InputHandler}
* @private
*/
goog.ui.equation.TexPane.prototype.texInputHandler_;
/**
* The last text that was renderred as an image.
* @type {string}
* @private
*/
goog.ui.equation.TexPane.prototype.lastRenderredText_ = '';
/**
* A sequence number for text change events. Used to delay drawing
* until the user paused typing.
* @type {number}
* @private
*/
goog.ui.equation.TexPane.prototype.changeSequence_ = 0;
/** @override */
goog.ui.equation.TexPane.prototype.createDom = function() {
/** @desc Title for TeX editor tab in the equation editor dialog. */
var MSG_EE_TEX_EQUATION = goog.getMsg('TeX Equation');
/** @desc Title for equation preview image in the equation editor dialog. */
var MSG_EE_TEX_PREVIEW = goog.getMsg('Preview');
/** @desc Link text that leads to an info page about the equation dialog. */
var MSG_EE_LEARN_MORE = goog.getMsg('Learn more');
var domHelper = this.dom_;
var innerContainer;
var texEditorEl = domHelper.createDom(goog.dom.TagName.DIV,
{'style': 'display: none;'},
domHelper.createDom(goog.dom.TagName.SPAN,
{'class':
goog.ui.equation.TexPane.SECTION_TITLE_CSS_CLASS +
' ' +
goog.ui.equation.TexPane.SECTION_TITLE_FLOAT_CSS_CLASS},
MSG_EE_TEX_EQUATION),
this.getHelpUrl() ?
domHelper.createDom(goog.dom.TagName.A,
{'id':
goog.ui.equation.TexPane.SECTION_LEARN_MORE_CSS_ID,
'target': '_blank', 'href': this.getHelpUrl()},
MSG_EE_LEARN_MORE) : null,
domHelper.createDom(goog.dom.TagName.DIV,
{'style': 'clear: both;'}),
innerContainer = this.innerContainer_ =
domHelper.createDom(goog.dom.TagName.DIV,
{'style': 'position: relative'}));
// Create menu palette.
var menuPalette =
this.paletteManager_.setActive(
goog.ui.equation.Palette.Type.MENU);
// Render the menu palette.
menuPalette.render(innerContainer);
innerContainer.appendChild(domHelper.createDom(goog.dom.TagName.DIV,
{'style': 'clear:both'}));
var texEdit = this.texEdit_ = domHelper.createDom('textarea',
{'class': goog.ui.equation.TexPane.TEX_EDIT_CSS_CLASS,
'dir': 'ltr'});
innerContainer.appendChild(texEdit);
innerContainer.appendChild(
domHelper.createDom(goog.dom.TagName.DIV,
{'class':
goog.ui.equation.TexPane.SECTION_TITLE_CSS_CLASS},
MSG_EE_TEX_PREVIEW));
var previewContainer = this.previewContainer_ = domHelper.createDom(
goog.dom.TagName.DIV,
{'class':
goog.ui.equation.TexPane.PREVIEW_CONTAINER_CSS_CLASS});
innerContainer.appendChild(previewContainer);
this.setElementInternal(texEditorEl);
};
/** @override */
goog.ui.equation.TexPane.prototype.enterDocument = function() {
this.texInputHandler_ = new goog.events.InputHandler(this.texEdit_);
// Listen to changes in the edit box to redraw equation.
goog.events.listen(this.texInputHandler_,
goog.events.InputHandler.EventType.INPUT,
this.handleTexChange_, false, this);
// Add a keyup listener for Safari that does not support the INPUT event,
// and for users pasting with ctrl+v, which does not generate an INPUT event
// in some browsers.
this.getHandler().listen(
this.texEdit_, goog.events.EventType.KEYDOWN, this.handleTexChange_);
// Listen to the action event on the active palette.
this.getHandler().listen(this.paletteManager_,
goog.ui.equation.PaletteEvent.Type.ACTION,
this.handlePaletteAction_, false, this);
};
/** @override */
goog.ui.equation.TexPane.prototype.setVisible = function(visible) {
goog.base(this, 'setVisible', visible);
if (visible) {
goog.Timer.callOnce(this.focusTexEdit_, 0, this);
}
};
/**
* Sets the focus to the TeX edit box.
* @private
*/
goog.ui.equation.TexPane.prototype.focusTexEdit_ = function() {
this.texEdit_.focus();
goog.dom.selection.setCursorPosition(this.texEdit_,
this.texEdit_.value.length);
};
/**
* Handles input change within the TeX textarea.
* @private
*/
goog.ui.equation.TexPane.prototype.handleEquationChange_ = function() {
var text = this.getEquation();
if (text == this.lastRenderredText_) {
return; // No change, no need to re-draw
}
this.lastRenderredText_ = text;
var isEquationValid =
!goog.ui.equation.ImageRenderer.isEquationTooLong(text);
// Dispatch change so that dialog might update the state of its buttons.
this.dispatchEvent(
new goog.ui.equation.ChangeEvent(
isEquationValid));
var container = this.previewContainer_;
var dom = goog.dom.getDomHelper(container);
dom.removeChildren(container);
if (text) {
var childNode;
if (isEquationValid) {
// Show equation image.
var imgSrc = goog.ui.equation.ImageRenderer.getImageUrl(text);
childNode = dom.createDom(goog.dom.TagName.IMG, {'src': imgSrc});
} else {
// Show a warning message.
/**
* @desc A warning message shown when equation the user entered is too
* long to display.
*/
var MSG_EE_TEX_EQUATION_TOO_LONG =
goog.getMsg('Equation is too long');
childNode = dom.createDom(goog.dom.TagName.DIV,
{'class': goog.ui.equation.TexPane.WARNING_CLASS},
MSG_EE_TEX_EQUATION_TOO_LONG);
}
dom.appendChild(container, childNode);
}
};
/**
* Handles a change to the equation text.
* Queues a request to handle input change within the TeX textarea.
* Refreshing the image is done only after a short timeout, to combine
* fast typing events into one draw.
* @param {goog.events.Event} e The keyboard event.
* @private
*/
goog.ui.equation.TexPane.prototype.handleTexChange_ = function(e) {
this.changeSequence_++;
goog.Timer.callOnce(
goog.bind(this.handleTexChangeTimer_, this, this.changeSequence_),
500);
};
/**
* Handles a timer timeout on delayed text change redraw.
* @param {number} seq The change sequence number when the timer started.
* @private
*/
goog.ui.equation.TexPane.prototype.handleTexChangeTimer_ =
function(seq) {
// Draw only if this was the last change. If not, just wait for the last.
if (seq == this.changeSequence_) {
this.handleEquationChange_();
}
};
/**
* Handles an action generated by a palette click.
* @param {goog.ui.equation.PaletteEvent} e The event object.
* @private
*/
goog.ui.equation.TexPane.prototype.handlePaletteAction_ = function(e) {
var palette = e.getPalette();
var paletteManager = this.paletteManager_;
var activePalette = paletteManager.getActive();
var texEdit = this.texEdit_;
// This is a click on the menu palette.
if (palette.getType() == goog.ui.equation.Palette.Type.MENU) {
var idx = palette.getHighlightedIndex();
var action = (idx != -1) ? palette.getAction(idx) : null;
// Current palette is not menu. This means there's a palette popping up.
if (activePalette != palette && activePalette.getType() == action) {
// Deactivate the palette.
paletteManager.deactivateNow();
return;
}
// We are clicking on the menu palette and there's no sub palette opening.
// Then we just open the one corresponding to the item under the mouse.
if (action) {
var subPalette = this.paletteManager_.setActive(
/** @type {goog.ui.equation.Palette.Type} */ (action));
if (!subPalette.getElement()) {
subPalette.render(this.innerContainer_);
}
var el = subPalette.getElement();
goog.style.setPosition(el, 0, - el.clientHeight);
}
} else {
activePalette = this.paletteManager_.getActive();
var action = activePalette.getAction(activePalette.getHighlightedIndex());
// If the click is on white space in the palette, do nothing.
if (!action) {
return;
}
// Do actual insert async because IE8 does not move the selection
// position and inserts in the wrong place if called in flow.
// See bug 2066876
goog.Timer.callOnce(goog.bind(this.insert_, this, action + ' '), 0);
}
// Let the tex editor always catch the focus.
texEdit.focus();
};
/**
* Inserts text into the equation at the current cursor position.
* Moves the cursor to after the inserted text.
* @param {string} text Text to insert.
* @private
*/
goog.ui.equation.TexPane.prototype.insert_ = function(text) {
var texEdit = this.texEdit_;
var pos = goog.dom.selection.getStart(texEdit);
var equation = texEdit['value'];
equation = equation.substring(0, pos) + text + equation.substring(pos);
texEdit['value'] = equation;
goog.dom.selection.setCursorPosition(texEdit, pos + text.length);
this.handleEquationChange_();
};
/** @override */
goog.ui.equation.TexPane.prototype.getEquation = function() {
return this.texEdit_['value'];
};
/** @override */
goog.ui.equation.TexPane.prototype.setEquation =
function(equation) {
this.texEdit_['value'] = equation;
this.handleEquationChange_();
};
/** @override */
goog.ui.equation.TexPane.prototype.disposeInternal = function() {
this.texInputHandler_.dispose();
this.paletteManager_ = null;
goog.base(this, 'disposeInternal');
};
| 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.ui.equation.TexEditor');
goog.require('goog.dom');
goog.require('goog.ui.Component');
goog.require('goog.ui.equation.ImageRenderer');
goog.require('goog.ui.equation.TexPane');
/**
* User interface for equation editor plugin.
* @constructor
* @param {Object} context The context that this Tex editor runs in.
* @param {string} helpUrl URL pointing to help documentation.
* @param {goog.dom.DomHelper=} opt_domHelper DomHelper to use.
* @extends {goog.ui.Component}
*/
goog.ui.equation.TexEditor = function(context, helpUrl, opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
/**
* The context that this Tex editor runs in.
* @type {Object}
* @private
*/
this.context_ = context;
/**
* A URL pointing to help documentation.
* @type {string}
* @private
*/
this.helpUrl_ = helpUrl;
};
goog.inherits(goog.ui.equation.TexEditor, goog.ui.Component);
/**
* The TeX editor pane.
* @type {goog.ui.equation.TexPane}
* @private
*/
goog.ui.equation.TexEditor.prototype.texPane_ = null;
/** @override */
goog.ui.equation.TexEditor.prototype.createDom = function() {
goog.base(this, 'createDom');
this.createDom_();
};
/**
* Creates main editor contents.
* @private
*/
goog.ui.equation.TexEditor.prototype.createDom_ = function() {
var contentElement = this.getElement();
this.texPane_ = new goog.ui.equation.TexPane(this.context_,
this.helpUrl_, this.dom_);
this.addChild(this.texPane_);
this.texPane_.render(contentElement);
this.texPane_.setVisible(true);
};
/** @override */
goog.ui.equation.TexEditor.prototype.decorateInternal = function(element) {
this.setElementInternal(element);
this.createDom_();
};
/**
* Returns the encoded equation.
* @return {string} The encoded equation.
*/
goog.ui.equation.TexEditor.prototype.getEquation = function() {
return this.texPane_.getEquation();
};
/**
* Parse an equation and draw it.
* Clears any previous displayed equation.
* @param {string} equation The equation text to parse.
*/
goog.ui.equation.TexEditor.prototype.setEquation = function(equation) {
this.texPane_.setEquation(equation);
};
/**
* @return {string} The html code to embed in the document.
*/
goog.ui.equation.TexEditor.prototype.getHtml = function() {
return goog.ui.equation.ImageRenderer.getHtml(this.getEquation());
};
/**
* Checks whether the current equation is valid and can be used in a document.
* @return {boolean} Whether the equation valid.
*/
goog.ui.equation.TexEditor.prototype.isValid = function() {
return goog.ui.equation.ImageRenderer.isEquationTooLong(
this.getEquation());
};
/**
* Sets the visibility of the editor.
* @param {boolean} visible Whether the editor should be visible.
*/
goog.ui.equation.TexEditor.prototype.setVisible = function(visible) {
this.texPane_.setVisible(visible);
};
/** @override */
goog.ui.equation.TexEditor.prototype.disposeInternal = function() {
if (this.texPane_) {
this.texPane_.dispose();
}
this.context_ = null;
goog.base(this, 'disposeInternal');
};
| 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.ui.equation.GreekPalette');
goog.require('goog.math.Size');
goog.require('goog.ui.equation.Palette');
/**
* Constructs a new Greek symbols palette.
* @param {goog.ui.equation.PaletteManager} paletteManager The
* manager of the palette.
* @extends {goog.ui.equation.Palette}
* @constructor
*/
goog.ui.equation.GreekPalette = function(paletteManager) {
goog.ui.equation.Palette.call(this, paletteManager,
goog.ui.equation.Palette.Type.GREEK,
0, 30, 18, 18,
['\\alpha',
'\\beta',
'\\gamma',
'\\delta',
'\\epsilon',
'\\varepsilon',
'\\zeta',
'\\eta',
'\\theta',
'\\vartheta',
'\\iota',
'\\kappa',
'\\lambda',
'\\mu',
'\\nu',
'\\xi',
'\\pi',
'\\varpi',
'\\rho',
'\\varrho',
'\\sigma',
'\\varsigma',
'\\tau',
'\\upsilon',
'\\phi',
'\\varphi',
'\\chi',
'\\psi',
'\\omega',
'\\Gamma',
'\\Delta',
'\\Theta',
'\\Lambda',
'\\Xi',
'\\Pi',
'\\Sigma',
'\\Upsilon',
'\\Phi',
'\\Psi',
'\\Omega']);
this.setSize(new goog.math.Size(7, 6));
};
goog.inherits(goog.ui.equation.GreekPalette, goog.ui.equation.Palette);
| 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 Functions for rendering the equation images.
*
*/
goog.provide('goog.ui.equation.ImageRenderer');
goog.require('goog.dom.TagName');
goog.require('goog.dom.classes');
goog.require('goog.string');
goog.require('goog.uri.utils');
/**
* The server name which renders the equations.
* We use https as equations may be embedded in https pages
* and using https prevents mixed content warnings. Note that
* https equations work only on google.com domains.
* @type {string}
* @private
*/
goog.ui.equation.ImageRenderer.SERVER_NAME_ =
'https://www.google.com';
/**
* The longest equation which may be displayed, in characters.
* @type {number}
*/
goog.ui.equation.ImageRenderer.MAX_EQUATION_LENGTH = 200;
/**
* Class to put on our equations IMG elements.
* @type {string}
*/
goog.ui.equation.ImageRenderer.EE_IMG_CLASS = 'ee_img';
/**
* Non-standard to put on our equations IMG elements. Useful when classes need
* to be scrubbed from the user-generated HTML, but non-standard attributes
* can be white-listed.
*
* @type {string}
*/
goog.ui.equation.ImageRenderer.EE_IMG_ATTR = 'eeimg';
/**
* Vertical alignment for the equations IMG elements.
* @type {string}
*/
goog.ui.equation.ImageRenderer.EE_IMG_VERTICAL_ALIGN = 'middle';
/**
* The default background color as used in the img url, which is fully
* transparent white.
* @type {string}
*/
goog.ui.equation.ImageRenderer.BACKGROUND_COLOR = 'FFFFFF00';
/**
* The default foreground color as used in the img url, which is black.
* @type {string}
*/
goog.ui.equation.ImageRenderer.FOREGROUND_COLOR = '000000';
/**
* Class to put on IMG elements to keep the resize property bubble from
* appearing. This is different from PLACEHOLDER_IMG_CLASS because it's
* reasonable in some cases to be able to resize a placeholder (which should
* be reflected when the placeholder is replaced with the other content).
* @type {string}
*/
goog.ui.equation.ImageRenderer.NO_RESIZE_IMG_CLASS =
goog.getCssName('tr_noresize');
/**
* Returns the equation image src url given the equation.
* @param {string} equation The equation.
* @return {string} The equation image src url (empty string in case the
* equation was empty).
*/
goog.ui.equation.ImageRenderer.getImageUrl = function(equation) {
if (!equation) {
return '';
}
var url = goog.ui.equation.ImageRenderer.SERVER_NAME_ +
'/chart?cht=tx' +
'&chf=bg,s,' +
goog.ui.equation.ImageRenderer.BACKGROUND_COLOR +
'&chco=' +
goog.ui.equation.ImageRenderer.FOREGROUND_COLOR +
'&chl=' +
encodeURIComponent(equation);
return url;
};
/**
* Returns the equation string src for given image url.
* @param {string} imageUrl The image url.
* @return {string?} The equation string, null if imageUrl cannot be parsed.
*/
goog.ui.equation.ImageRenderer.getEquationFromImageUrl = function(imageUrl) {
return goog.uri.utils.getParamValue(imageUrl, 'chl');
};
/**
* Gets the equation string from the given equation IMG node. Returns empty
* string if the src attribute of the is not a valid equation url.
* @param {Element} equationNode The equation IMG element.
* @return {string} The equation string.
*/
goog.ui.equation.ImageRenderer.getEquationFromImage = function(equationNode) {
var url = equationNode.getAttribute('src');
if (!url) {
// Should never happen.
return '';
}
return goog.ui.equation.ImageRenderer.getEquationFromImageUrl(
url) || '';
};
/**
* Checks whether given node is an equation element.
* @param {Node} node The node to check.
* @return {boolean} Whether given node is an equation element.
*/
goog.ui.equation.ImageRenderer.isEquationElement = function(node) {
return node.nodeName == goog.dom.TagName.IMG &&
(node.getAttribute(
goog.ui.equation.ImageRenderer.EE_IMG_ATTR) ||
goog.dom.classes.has(node,
goog.ui.equation.ImageRenderer.EE_IMG_CLASS));
};
/**
* Returns the html for the html image tag for the given equation.
* @param {string} equation The equation.
* @return {string} The html code to embed in the document.
*/
goog.ui.equation.ImageRenderer.getHtml = function(equation) {
var imageSrc =
goog.ui.equation.ImageRenderer.getImageUrl(equation);
if (!imageSrc) {
return '';
}
return '<img src="' + imageSrc + '" ' +
'alt="' + goog.string.htmlEscape(equation) + '" ' +
'class="' + goog.ui.equation.ImageRenderer.EE_IMG_CLASS +
' ' + goog.ui.equation.ImageRenderer.NO_RESIZE_IMG_CLASS +
'" ' + goog.ui.equation.ImageRenderer.EE_IMG_ATTR + '="1" ' +
'style="vertical-align: ' +
goog.ui.equation.ImageRenderer.EE_IMG_VERTICAL_ALIGN + '">';
};
/**
* Checks whether equation is too long to be displayed.
* @param {string} equation The equation to test.
* @return {boolean} Whether the equation is too long.
*/
goog.ui.equation.ImageRenderer.isEquationTooLong = function(equation) {
return equation.length >
goog.ui.equation.ImageRenderer.MAX_EQUATION_LENGTH;
};
| 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.ui.equation.PaletteManager');
goog.require('goog.Timer');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.ui.equation.ArrowPalette');
goog.require('goog.ui.equation.ComparisonPalette');
goog.require('goog.ui.equation.GreekPalette');
goog.require('goog.ui.equation.MathPalette');
goog.require('goog.ui.equation.MenuPalette');
goog.require('goog.ui.equation.Palette');
goog.require('goog.ui.equation.SymbolPalette');
/**
* Constructs the palette manager that manages all the palettes in Equation
* Editor.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.ui.equation.PaletteManager = function() {
goog.events.EventTarget.call(this);
/**
* The map of palette type and instance pair.
* @type {Object.<string, goog.ui.equation.Palette>}
* @private
*/
this.paletteMap_ = {};
/**
* The current active palette.
* @type {goog.ui.equation.Palette}
* @private
*/
this.activePalette_ = null;
/**
* The event handler for managing events.
* @type {goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler(this);
/**
* The timer used to add grace period when deactivate palettes.
* @type {goog.Timer}
* @private
*/
this.deactivationTimer_ = new goog.Timer(300);
this.eventHandler_.listen(this.deactivationTimer_, goog.Timer.TICK,
this.handleDeactivation_);
};
goog.inherits(goog.ui.equation.PaletteManager,
goog.events.EventTarget);
/**
* Clears the deactivation timer. This is used to prevent palette manager
* deactivation when mouse pointer is moved outside palettes and moved back
* quickly inside a grace period.
*/
goog.ui.equation.PaletteManager.prototype.stopDeactivation = function() {
this.deactivationTimer_.stop();
};
/**
* Returns the palette instance of given type.
* @param {goog.ui.equation.Palette.Type} type The type of palette
* to get.
* @return {goog.ui.equation.Palette} The palette instance of given
* type. A new instance will be created. If the instance doesn't exist.
*/
goog.ui.equation.PaletteManager.prototype.getPalette =
function(type) {
var paletteMap = this.paletteMap_;
var palette = paletteMap[type];
if (!palette) {
switch (type) {
case goog.ui.equation.Palette.Type.MENU:
palette = new goog.ui.equation.MenuPalette(this);
break;
case goog.ui.equation.Palette.Type.GREEK:
palette = new goog.ui.equation.GreekPalette(this);
break;
case goog.ui.equation.Palette.Type.SYMBOL:
palette = new goog.ui.equation.SymbolPalette(this);
break;
case goog.ui.equation.Palette.Type.COMPARISON:
palette = new goog.ui.equation.ComparisonPalette(this);
break;
case goog.ui.equation.Palette.Type.MATH:
palette = new goog.ui.equation.MathPalette(this);
break;
case goog.ui.equation.Palette.Type.ARROW:
palette = new goog.ui.equation.ArrowPalette(this);
break;
default:
throw new Error('Invalid palette type!');
}
paletteMap[type] = palette;
}
return palette;
};
/**
* Sets the palette instance of given type to be the active one.
* @param {goog.ui.equation.Palette.Type} type The type of the
* palette to set active.
* @return {goog.ui.equation.Palette} The palette instance of given
* type. A new instance will be created, if the instance doesn't exist.
*/
goog.ui.equation.PaletteManager.prototype.setActive =
function(type) {
var palette = this.activePalette_;
if (palette) {
palette.setVisible(false);
}
palette = this.getPalette(type);
this.activePalette_ = palette;
palette.setVisible(true);
return palette;
};
/**
* Returns the active palette.
* @return {goog.ui.equation.Palette} The active palette.
*/
goog.ui.equation.PaletteManager.prototype.getActive = function() {
return this.activePalette_;
};
/**
* Starts the deactivation of open palette.
* This method has a slight delay before doing the real deactivation. This
* helps prevent sudden disappearing of palettes when user moves mouse outside
* them just briefly (and maybe accidentally). If you really want to deactivate
* the active palette, use {@link #deactivateNow()} instead.
*/
goog.ui.equation.PaletteManager.prototype.deactivate = function() {
this.deactivationTimer_.start();
};
/**
* Deactivate the open palette immediately.
*/
goog.ui.equation.PaletteManager.prototype.deactivateNow = function() {
this.handleDeactivation_();
};
/**
* Internal process of deactivation of the manager.
* @private
*/
goog.ui.equation.PaletteManager.prototype.handleDeactivation_ = function() {
this.setActive(goog.ui.equation.Palette.Type.MENU);
};
/** @override */
goog.ui.equation.PaletteManager.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
this.activePalette_ = null;
this.paletteMap_ = null;
};
| 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.ui.equation.EditorPane');
goog.require('goog.dom');
goog.require('goog.style');
goog.require('goog.ui.Component');
/**
* An abstract equation editor tab pane.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @constructor
* @extends {goog.ui.Component}
*/
goog.ui.equation.EditorPane = function(opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
};
goog.inherits(goog.ui.equation.EditorPane, goog.ui.Component);
/**
* A link to any available help documentation to be displayed in a "Learn more"
* link. If not set through the equationeditor plugin constructor, the link
* will be omitted.
* @type {string}
* @private
*/
goog.ui.equation.EditorPane.prototype.helpUrl_ = '';
/**
* Sets the visibility of this tab pane.
* @param {boolean} visible Whether this tab should become visible.
*/
goog.ui.equation.EditorPane.prototype.setVisible =
function(visible) {
goog.style.setElementShown(this.getElement(), visible);
};
/**
* Sets the equation to show in this tab pane.
* @param {string} equation The equation.
* @protected
*/
goog.ui.equation.EditorPane.prototype.setEquation = goog.abstractMethod;
/**
* @return {string} The equation shown in this tab pane.
* @protected
*/
goog.ui.equation.EditorPane.prototype.getEquation = goog.abstractMethod;
/**
* Sets the help link URL to show in this tab pane.
* @param {string} url The help link URL.
* @protected
*/
goog.ui.equation.EditorPane.prototype.setHelpUrl = function(url) {
this.helpUrl_ = url;
};
/**
* @return {string} The help link URL.
* @protected
*/
goog.ui.equation.EditorPane.prototype.getHelpUrl = function() {
return this.helpUrl_;
};
/**
* @return {boolean} Whether the equation was modified.
* @protected
*/
goog.ui.equation.EditorPane.prototype.isModified = goog.abstractMethod;
| 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.ui.equation.EquationEditor');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.ui.Component');
goog.require('goog.ui.Tab');
goog.require('goog.ui.TabBar');
goog.require('goog.ui.equation.EditorPane');
goog.require('goog.ui.equation.ImageRenderer');
goog.require('goog.ui.equation.TexPane');
/**
* User interface for equation editor plugin.
* @constructor
* @param {Object} context The context that this equation editor runs in.
* @param {goog.dom.DomHelper=} opt_domHelper DomHelper to use.
* @param {string=} opt_helpUrl Help document URL to use in the "Learn more"
* link.
* @extends {goog.ui.Component}
*/
goog.ui.equation.EquationEditor = function(context, opt_domHelper,
opt_helpUrl) {
goog.base(this, opt_domHelper);
/**
* The context this editor runs in.
* @type {Object}
* @private
*/
this.context_ = context;
/**
* Help document URL to use in the "Learn more" link.
* @type {string}
* @private
*/
this.helpUrl_ = opt_helpUrl || '';
};
goog.inherits(goog.ui.equation.EquationEditor, goog.ui.Component);
/**
* Constants for event names.
* @enum {string}
*/
goog.ui.equation.EquationEditor.EventType = {
/**
* Dispatched when equation changes.
*/
CHANGE: 'change'
};
/**
* The index of the last active tab. Zero means first tab.
* @type {number}
* @private
*/
goog.ui.equation.EquationEditor.prototype.activeTabIndex_ = 0;
/** @override */
goog.ui.equation.EquationEditor.prototype.createDom = function() {
goog.base(this, 'createDom');
this.createDom_();
};
/**
* Creates main editor contents.
* @private
*/
goog.ui.equation.EquationEditor.prototype.createDom_ = function() {
var contentElement = this.getElement();
/** @desc Title of the visual equation editor tab. */
var MSG_VISUAL_EDITOR = goog.getMsg('Editor');
/** @desc Title of the TeX equation editor tab. */
var MSG_TEX_EDITOR = goog.getMsg('TeX');
// Create the main tabs
var dom = this.dom_;
var tabTop = dom.createDom('div',
{'class': 'goog-tab-bar goog-tab-bar-top'},
dom.createDom('div',
{'class': 'goog-tab goog-tab-selected'}, MSG_VISUAL_EDITOR),
dom.createDom('div', {'class': 'goog-tab'}, MSG_TEX_EDITOR));
var tabClear = dom.createDom('div', {'class': 'goog-tab-bar-clear'});
var tabContent = dom.createDom('div', {'class': 'ee-content'});
dom.appendChild(contentElement, tabTop);
dom.appendChild(contentElement, tabClear);
dom.appendChild(contentElement, tabContent);
var tabBar = new goog.ui.TabBar();
tabBar.decorate(tabTop);
/**
* The tab bar.
* @type {!goog.ui.TabBar}
* @private
*/
this.tabBar_ = tabBar;
goog.events.listen(tabBar, goog.ui.Component.EventType.SELECT,
goog.bind(this.handleTabSelect_, this));
var texEditor = new goog.ui.equation.TexPane(this.context_,
this.helpUrl_, this.dom_);
this.addChild(texEditor);
texEditor.render(tabContent);
this.setVisibleTab_(0); // Make first tab visible
};
/**
* Sets the visibility of the editor.
* @param {boolean} visible Whether the editor should be visible.
*/
goog.ui.equation.EquationEditor.prototype.setVisible = function(visible) {
// Show active tab if visible, or none if not
this.setVisibleTab_(visible ? this.activeTabIndex_ : -1);
};
/**
* Sets the tab at the selected index as visible and all the rest as not
* visible.
* @param {number} tabIndex The tab index that is visible. -1 means no
* tab is visible.
* @private
*/
goog.ui.equation.EquationEditor.prototype.setVisibleTab_ = function(tabIndex) {
for (var i = 0; i < this.getChildCount(); i++) {
this.getChildAt(i).setVisible(i == tabIndex);
}
};
/** @override */
goog.ui.equation.EquationEditor.prototype.decorateInternal = function(element) {
this.setElementInternal(element);
this.createDom_();
};
/**
* Returns the encoded equation.
* @return {string} The encoded equation.
*/
goog.ui.equation.EquationEditor.prototype.getEquation = function() {
var sel = this.tabBar_.getSelectedTabIndex();
return this.getChildAt(sel).getEquation();
};
/**
* @return {string} The html code to embed in the document.
*/
goog.ui.equation.EquationEditor.prototype.getHtml = function() {
return goog.ui.equation.ImageRenderer.getHtml(this.getEquation());
};
/**
* Checks whether the current equation is valid and can be used in a document.
* @return {boolean} Whether the equation is valid.
*/
goog.ui.equation.EquationEditor.prototype.isValid = function() {
return goog.ui.equation.ImageRenderer.isEquationTooLong(
this.getEquation());
};
/**
* Handles a tab selection by the user.
* @param {goog.events.Event} e The event.
* @private
*/
goog.ui.equation.EquationEditor.prototype.handleTabSelect_ = function(e) {
var sel = this.tabBar_.getSelectedTabIndex();
if (sel != this.activeTabIndex_) {
this.activeTabIndex_ = sel;
this.setVisibleTab_(sel);
}
// TODO(user) Pass equation from the tab to the other is modified
};
/**
* Parse an equation and draw it.
* Clears any previous displayed equation.
* @param {string} equation The equation text to parse.
*/
goog.ui.equation.EquationEditor.prototype.setEquation = function(equation) {
var sel = this.tabBar_.getSelectedTabIndex();
this.getChildAt(sel).setEquation(equation);
};
/** @override */
goog.ui.equation.EquationEditor.prototype.disposeInternal = function() {
this.context_ = null;
goog.base(this, 'disposeInternal');
};
| 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.ui.equation.ComparisonPalette');
goog.require('goog.math.Size');
goog.require('goog.ui.equation.Palette');
/**
* Constructs a new comparison palette.
* @param {goog.ui.equation.PaletteManager} paletteManager The
* manager of the palette.
* @extends {goog.ui.equation.Palette}
* @constructor
*/
goog.ui.equation.ComparisonPalette = function(paletteManager) {
goog.ui.equation.Palette.call(this, paletteManager,
goog.ui.equation.Palette.Type.COMPARISON,
0, 70, 18, 18,
['\\leq',
'\\geq',
'\\prec',
'\\succ',
'\\preceq',
'\\succeq',
'\\ll',
'\\gg',
'\\equiv',
'\\sim',
'\\\simeq',
'\\\asymp',
'\\approx',
'\\ne',
'\\\subset',
'\\supset',
'\\subseteq',
'\\supseteq',
'\\in',
'\\ni',
'\\notin']);
this.setSize(new goog.math.Size(7, 3));
};
goog.inherits(goog.ui.equation.ComparisonPalette, goog.ui.equation.Palette);
| 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.ui.equation.MathPalette');
goog.require('goog.math.Size');
goog.require('goog.ui.equation.Palette');
/**
* Constructs a new math palette.
* @param {goog.ui.equation.PaletteManager} paletteManager The
* manager of the palette.
* @extends {goog.ui.equation.Palette}
* @constructor
*/
goog.ui.equation.MathPalette = function(paletteManager) {
goog.ui.equation.Palette.call(this, paletteManager,
goog.ui.equation.Palette.Type.MATH,
0, 90, 30, 56,
['x_{a}',
'x^{b}',
'x_{a}^{b}',
'\\bar{x}',
'\\tilde{x}',
'\\frac{a}{b}',
'\\sqrt{x}',
'\\sqrt[n]{x}',
'\\bigcap_{a}^{b}',
'\\bigcup_{a}^{b}',
'\\prod_{a}^{b}',
'\\coprod_{a}^{b}',
'\\left( x \\right)',
'\\left[ x \\right]',
'\\left\\{ x \\right\\}',
'\\left| x \\right|',
'\\int_{a}^{b}',
'\\oint_{a}^{b}',
'\\sum_{a}^{b}{x}',
'\\lim_{a \\rightarrow b}{x}']);
this.setSize(new goog.math.Size(10, 2));
};
goog.inherits(goog.ui.equation.MathPalette, goog.ui.equation.Palette);
| 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.ui.equation.ArrowPalette');
goog.require('goog.math.Size');
goog.require('goog.ui.equation.Palette');
/**
* Constructs a new arrows palette.
* @param {goog.ui.equation.PaletteManager} paletteManager The
* manager of the palette.
* @extends {goog.ui.equation.Palette}
* @constructor
*/
goog.ui.equation.ArrowPalette = function(paletteManager) {
goog.ui.equation.Palette.call(this, paletteManager,
goog.ui.equation.Palette.Type.ARROW,
0, 150, 18, 18,
['\\leftarrow',
'\\rightarrow',
'\\leftrightarrow',
'\\Leftarrow',
'\\Rightarrow',
'\\Leftrightarrow',
'\\uparrow',
'\\downarrow',
'\\updownarrow',
'\\Uparrow',
'\\Downarrow',
'\\Updownarrow']);
this.setSize(new goog.math.Size(12, 1));
};
goog.inherits(goog.ui.equation.ArrowPalette, goog.ui.equation.Palette);
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A palette of icons.
* The icons are generated from a single sprite image that
* is used for multiple palettes.
* All icons of a single palette must be on the same sprite row
* (same y coordinate) and all have the same width.
* Each item has an associated action command that should be taken
* when certain event is dispatched.
*
*/
goog.provide('goog.ui.equation.Palette');
goog.provide('goog.ui.equation.PaletteEvent');
goog.provide('goog.ui.equation.PaletteRenderer');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.ui.Palette');
goog.require('goog.ui.equation.ImageRenderer');
/**
* Constructs a new palette.
* @param {goog.ui.equation.PaletteManager} paletteManager The
* manager of the palette.
* @param {goog.ui.equation.Palette.Type} type The type of the
* palette.
* @param {number} spriteX Coordinate of first icon in sprite.
* @param {number} spriteY Coordinate of top of all icons in sprite.
* @param {number} itemWidth Pixel width of each palette icon.
* @param {number} itemHeight Pixel height of each palette icon.
* @param {Array.<string>=} opt_actions An optional action list for palette
* elements. The number of actions determine the number of palette
* elements.
* @param {goog.ui.PaletteRenderer=} opt_renderer Optional customized renderer,
* defaults to {@link goog.ui.PaletteRenderer}.
* @extends {goog.ui.Palette}
* @constructor
*/
goog.ui.equation.Palette = function(paletteManager, type, spriteX,
spriteY, itemWidth, itemHeight, opt_actions, opt_renderer) {
/**
* The type of the palette.
* @type {goog.ui.equation.Palette.Type}
* @private
*/
this.type_ = type;
/**
* The palette actions.
* @type {Array.<string>}
* @private
*/
this.actions_ = opt_actions || [];
var renderer =
opt_renderer ||
goog.ui.equation.PaletteRenderer.getInstance();
// Create a div element for each icon.
var elements = [];
var x = - spriteX;
var y = - spriteY;
for (var i = 0; i < opt_actions.length; i++) {
elements.push(goog.dom.createDom(goog.dom.TagName.DIV,
{'class': renderer.getItemCssClass(),
'style': 'width:' + itemWidth +
'px;height:' + itemHeight +
'px;' +
'background-position:' +
x + 'px ' + y + 'px;'}));
x -= itemWidth;
}
/**
* The palette manager that manages all the palettes.
* @type {goog.ui.equation.PaletteManager}
* @private
*/
this.paletteManager_ = paletteManager;
goog.ui.Palette.call(this, elements, renderer);
};
goog.inherits(goog.ui.equation.Palette, goog.ui.Palette);
/**
* The type of possible palettes. They are made short to minimize JS size.
* @enum {string}
*/
goog.ui.equation.Palette.Type = {
MENU: 'mn',
GREEK: 'g',
SYMBOL: 's',
COMPARISON: 'c',
MATH: 'm',
ARROW: 'a'
};
/**
* The CSS class name for the palette.
* @type {string}
*/
goog.ui.equation.Palette.CSS_CLASS = 'ee-palette';
/**
* Returns the type of the palette.
* @return {goog.ui.equation.Palette.Type} The type of the palette.
*/
goog.ui.equation.Palette.prototype.getType = function() {
return this.type_;
};
/**
* Returns the palette manager.
* @return {goog.ui.equation.PaletteManager} The palette manager
* that manages all the palette.
*/
goog.ui.equation.Palette.prototype.getPaletteManager = function() {
return this.paletteManager_;
};
/**
* Returns actions for this palette.
* @return {Array.<string>} The palette actions.
*/
goog.ui.equation.Palette.prototype.getActions = function() {
return this.actions_;
};
/**
* Returns the action for a given index.
* @param {number} index The index of the action to be retrieved.
* @return {string?} The action for given index, or {@code null} if action is
* not found.
*/
goog.ui.equation.Palette.prototype.getAction = function(index) {
return (index >= 0 && index < this.actions_.length) ?
this.actions_[index] : null;
};
/**
* Handles mouseup events. Overrides {@link goog.ui.Palette#handleMouseUp}
* by dispatching a {@link goog.ui.equation.PaletteEvent}.
* @param {goog.events.Event} e Mouse event to handle.
* @override
*/
goog.ui.equation.Palette.prototype.handleMouseUp = function(e) {
goog.base(this, 'handleMouseUp', e);
this.paletteManager_.dispatchEvent(
new goog.ui.equation.PaletteEvent(
goog.ui.equation.PaletteEvent.Type.ACTION, this));
};
/**
* Handles mouse out events. Overrides {@link goog.ui.Palette#handleMouseOut}
* by deactivate the palette.
* @param {goog.events.BrowserEvent} e Mouse event to handle.
* @override
*/
goog.ui.equation.Palette.prototype.handleMouseOut = function(e) {
goog.base(this, 'handleMouseOut', e);
// Ignore mouse moves between descendants.
if (e.relatedTarget &&
!goog.dom.contains(this.getElement(), e.relatedTarget)) {
this.paletteManager_.deactivate();
}
};
/**
* Handles mouse over events. Overrides {@link goog.ui.Palette#handleMouseOver}
* by stop deactivating the palette. When mouse leaves the palettes, the
* palettes will be deactivated after a centain period of time. Reentering the
* palettes inside this time will stop the timer and cancel the deactivation.
* @param {goog.events.BrowserEvent} e Mouse event to handle.
* @override
*/
goog.ui.equation.Palette.prototype.handleMouseOver = function(e) {
goog.base(this, 'handleMouseOver', e);
// Ignore mouse moves between descendants.
if (e.relatedTarget &&
!goog.dom.contains(this.getElement(), e.relatedTarget)) {
// Stop the timer to deactivate the palettes.
this.paletteManager_.stopDeactivation();
}
};
/**
* The event that palettes dispatches.
* @param {string} type Type of the event.
* @param {goog.ui.equation.Palette} palette The palette that the
* event is fired on.
* @param {Element=} opt_target The optional target of the event.
* @constructor
* @extends {goog.events.Event}
*/
goog.ui.equation.PaletteEvent = function(type, palette, opt_target) {
goog.events.Event.call(this, type, opt_target);
/**
* The palette the event is fired from.
* @type {goog.ui.equation.Palette}
* @private
*/
this.palette_ = palette;
};
/**
* The type of events that can be fired on palettes.
* @enum {string}
*/
goog.ui.equation.PaletteEvent.Type = {
// Take the action that is associated with the palette item.
ACTION: 'a'
};
/**
* Returns the palette that this event is fired from.
* @return {goog.ui.equation.Palette} The palette this event is
* fired from.
*/
goog.ui.equation.PaletteEvent.prototype.getPalette = function() {
return this.palette_;
};
/**
* The renderer for palette.
* @extends {goog.ui.PaletteRenderer}
* @constructor
*/
goog.ui.equation.PaletteRenderer = function() {
goog.ui.PaletteRenderer.call(this);
};
goog.inherits(goog.ui.equation.PaletteRenderer, goog.ui.PaletteRenderer);
goog.addSingletonGetter(goog.ui.equation.PaletteRenderer);
/** @override */
goog.ui.equation.PaletteRenderer.prototype.getCssClass =
function() {
return goog.ui.equation.Palette.CSS_CLASS;
};
/**
* Returns the CSS class name for the palette item.
* @return {string} The CSS class name of the palette item.
*/
goog.ui.equation.PaletteRenderer.prototype.getItemCssClass = function() {
return this.getCssClass() + '-item';
};
| 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 TabPane widget implementation.
*
* @author eae@google.com (Emil A Eklund)
*/
goog.provide('goog.ui.TabPane');
goog.provide('goog.ui.TabPane.Events');
goog.provide('goog.ui.TabPane.TabLocation');
goog.provide('goog.ui.TabPane.TabPage');
goog.provide('goog.ui.TabPaneEvent');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.events');
goog.require('goog.events.Event');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.style');
/**
* TabPane widget. All children already inside the tab pane container element
* will be be converted to tabs. Each tab is represented by a goog.ui.TabPane.
* TabPage object. Further pages can be constructed either from an existing
* container or created from scratch.
*
* @param {Element} el Container element to create the tab pane out of.
* @param {goog.ui.TabPane.TabLocation=} opt_tabLocation Location of the tabs
* in relation to the content container. Default is top.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @param {boolean=} opt_useMouseDown Whether to use MOUSEDOWN instead of CLICK
* for tab changes.
* @extends {goog.events.EventTarget}
* @constructor
* @see ../demos/tabpane.html
* @deprecated Use goog.ui.TabBar instead.
*/
goog.ui.TabPane = function(el, opt_tabLocation, opt_domHelper,
opt_useMouseDown) {
goog.events.EventTarget.call(this);
/**
* DomHelper used to interact with the document, allowing components to be
* created in a different window. This property is considered protected;
* subclasses of Component may refer to it directly.
* @type {goog.dom.DomHelper}
* @protected
* @suppress {underscore}
*/
this.dom_ = opt_domHelper || goog.dom.getDomHelper();
/**
* Tab pane element.
* @type {Element}
* @private
*/
this.el_ = el;
/**
* Collection of tab panes.
* @type {Array.<goog.ui.TabPane.TabPage>}
* @private
*/
this.pages_ = [];
/**
* Location of the tabs with respect to the content box.
* @type {goog.ui.TabPane.TabLocation}
* @private
*/
this.tabLocation_ =
opt_tabLocation ? opt_tabLocation : goog.ui.TabPane.TabLocation.TOP;
/**
* Whether to use MOUSEDOWN instead of CLICK for tab change events. This
* fixes some focus problems on Safari/Chrome.
* @type {boolean}
* @private
*/
this.useMouseDown_ = !!opt_useMouseDown;
this.create_();
};
goog.inherits(goog.ui.TabPane, goog.events.EventTarget);
/**
* Element containing the tab buttons.
* @type {Element}
* @private
*/
goog.ui.TabPane.prototype.elButtonBar_;
/**
* Element containing the tab pages.
* @type {Element}
* @private
*/
goog.ui.TabPane.prototype.elContent_;
/**
* Selected page.
* @type {goog.ui.TabPane.TabPage?}
* @private
*/
goog.ui.TabPane.prototype.selected_;
/**
* Constants for event names
*
* @type {Object}
*/
goog.ui.TabPane.Events = {
CHANGE: 'change'
};
/**
* Enum for representing the location of the tabs in relation to the content.
*
* @enum {number}
*/
goog.ui.TabPane.TabLocation = {
TOP: 0,
BOTTOM: 1,
LEFT: 2,
RIGHT: 3
};
/**
* Creates HTML nodes for tab pane.
*
* @private
*/
goog.ui.TabPane.prototype.create_ = function() {
this.el_.className = goog.getCssName('goog-tabpane');
var nodes = this.getChildNodes_();
// Create tab strip
this.elButtonBar_ = this.dom_.createDom('ul',
{'className': goog.getCssName('goog-tabpane-tabs'), 'tabIndex': '0'});
// Create content area
this.elContent_ =
this.dom_.createDom('div', goog.getCssName('goog-tabpane-cont'));
this.el_.appendChild(this.elContent_);
switch (this.tabLocation_) {
case goog.ui.TabPane.TabLocation.TOP:
this.el_.insertBefore(this.elButtonBar_, this.elContent_);
this.el_.insertBefore(this.createClear_(), this.elContent_);
goog.dom.classes.add(this.el_, goog.getCssName('goog-tabpane-top'));
break;
case goog.ui.TabPane.TabLocation.BOTTOM:
this.el_.appendChild(this.elButtonBar_);
this.el_.appendChild(this.createClear_());
goog.dom.classes.add(this.el_, goog.getCssName('goog-tabpane-bottom'));
break;
case goog.ui.TabPane.TabLocation.LEFT:
this.el_.insertBefore(this.elButtonBar_, this.elContent_);
goog.dom.classes.add(this.el_, goog.getCssName('goog-tabpane-left'));
break;
case goog.ui.TabPane.TabLocation.RIGHT:
this.el_.insertBefore(this.elButtonBar_, this.elContent_);
goog.dom.classes.add(this.el_, goog.getCssName('goog-tabpane-right'));
break;
default:
throw Error('Invalid tab location');
}
// Listen for click and keydown events on header
this.elButtonBar_.tabIndex = 0;
goog.events.listen(this.elButtonBar_,
this.useMouseDown_ ?
goog.events.EventType.MOUSEDOWN :
goog.events.EventType.CLICK,
this.onHeaderClick_, false, this);
goog.events.listen(this.elButtonBar_, goog.events.EventType.KEYDOWN,
this.onHeaderKeyDown_, false, this);
this.createPages_(nodes);
};
/**
* Creates the HTML node for the clearing div, and associated style in
* the <HEAD>.
*
* @return {Element} Reference to a DOM div node.
* @private
*/
goog.ui.TabPane.prototype.createClear_ = function() {
var clearFloatStyle = '.' + goog.getCssName('goog-tabpane-clear') +
' { clear: both; height: 0px; overflow: hidden }';
goog.style.installStyles(clearFloatStyle);
return this.dom_.createDom('div', goog.getCssName('goog-tabpane-clear'));
};
/** @override */
goog.ui.TabPane.prototype.disposeInternal = function() {
goog.ui.TabPane.superClass_.disposeInternal.call(this);
goog.events.unlisten(this.elButtonBar_,
this.useMouseDown_ ?
goog.events.EventType.MOUSEDOWN :
goog.events.EventType.CLICK,
this.onHeaderClick_, false, this);
goog.events.unlisten(this.elButtonBar_, goog.events.EventType.KEYDOWN,
this.onHeaderKeyDown_, false, this);
delete this.el_;
this.elButtonBar_ = null;
this.elContent_ = null;
};
/**
* @return {Array.<Element>} The element child nodes of tab pane container.
* @private
*/
goog.ui.TabPane.prototype.getChildNodes_ = function() {
var nodes = [];
var child = goog.dom.getFirstElementChild(this.el_);
while (child) {
nodes.push(child);
child = goog.dom.getNextElementSibling(child);
}
return nodes;
};
/**
* Creates pages out of a collection of elements.
*
* @param {Array.<Element>} nodes Array of elements to create pages out of.
* @private
*/
goog.ui.TabPane.prototype.createPages_ = function(nodes) {
for (var node, i = 0; node = nodes[i]; i++) {
this.addPage(new goog.ui.TabPane.TabPage(node));
}
};
/**
* Adds a page to the tab pane.
*
* @param {goog.ui.TabPane.TabPage} page Tab page to add.
* @param {number=} opt_index Zero based index to insert tab at. Inserted at the
* end if not specified.
*/
goog.ui.TabPane.prototype.addPage = function(page, opt_index) {
// If page is already in another tab pane it's removed from that one before it
// can be added to this one.
if (page.parent_ && page.parent_ != this &&
page.parent_ instanceof goog.ui.TabPane) {
page.parent_.removePage(page);
}
// Insert page at specified position
var index = this.pages_.length;
if (goog.isDef(opt_index) && opt_index != index) {
index = opt_index;
this.pages_.splice(index, 0, page);
this.elButtonBar_.insertBefore(page.elTitle_,
this.elButtonBar_.childNodes[index]);
}
// Append page to end
else {
this.pages_.push(page);
this.elButtonBar_.appendChild(page.elTitle_);
}
page.setParent_(this, index);
// Select first page and fire change event
if (!this.selected_) {
this.selected_ = page;
this.dispatchEvent(new goog.ui.TabPaneEvent(goog.ui.TabPane.Events.CHANGE,
this, this.selected_));
}
// Move page content to the tab pane and update visibility.
this.elContent_.appendChild(page.elContent_);
page.setVisible_(page == this.selected_);
// Update index for following pages
for (var pg, i = index + 1; pg = this.pages_[i]; i++) {
pg.index_ = i;
}
};
/**
* Removes the specified page from the tab pane.
*
* @param {goog.ui.TabPane.TabPage|number} page Reference to tab page or zero
* based index.
*/
goog.ui.TabPane.prototype.removePage = function(page) {
if (goog.isNumber(page)) {
page = this.pages_[page];
}
this.pages_.splice(page.index_, 1);
page.setParent_(null);
goog.dom.removeNode(page.elTitle_);
goog.dom.removeNode(page.elContent_);
for (var pg, i = 0; pg = this.pages_[i]; i++) {
pg.setParent_(this, i);
}
};
/**
* Gets the tab page by zero based index.
*
* @param {number} index Index of page to return.
* @return {goog.ui.TabPane.TabPage?} page The tab page.
*/
goog.ui.TabPane.prototype.getPage = function(index) {
return this.pages_[index];
};
/**
* Sets the selected tab page by object reference.
*
* @param {goog.ui.TabPane.TabPage} page Tab page to select.
*/
goog.ui.TabPane.prototype.setSelectedPage = function(page) {
if (page.isEnabled() &&
(!this.selected_ || page != this.selected_)) {
this.selected_.setVisible_(false);
page.setVisible_(true);
this.selected_ = page;
// Fire changed event
this.dispatchEvent(new goog.ui.TabPaneEvent(goog.ui.TabPane.Events.CHANGE,
this, this.selected_));
}
};
/**
* Sets the selected tab page by zero based index.
*
* @param {number} index Index of page to select.
*/
goog.ui.TabPane.prototype.setSelectedIndex = function(index) {
if (index >= 0 && index < this.pages_.length) {
this.setSelectedPage(this.pages_[index]);
}
};
/**
* @return {number} The index for the selected tab page or -1 if no page is
* selected.
*/
goog.ui.TabPane.prototype.getSelectedIndex = function() {
return this.selected_ ? /** @type {number} */ (this.selected_.index_) : -1;
};
/**
* @return {goog.ui.TabPane.TabPage?} The selected tab page.
*/
goog.ui.TabPane.prototype.getSelectedPage = function() {
return this.selected_ || null;
};
/**
* @return {Element} The element that contains the tab pages.
*/
goog.ui.TabPane.prototype.getContentElement = function() {
return this.elContent_ || null;
};
/**
* @return {Element} The main element for the tabpane.
*/
goog.ui.TabPane.prototype.getElement = function() {
return this.el_ || null;
};
/**
* Click event handler for header element, handles clicks on tabs.
*
* @param {goog.events.BrowserEvent} event Click event.
* @private
*/
goog.ui.TabPane.prototype.onHeaderClick_ = function(event) {
var el = event.target;
// Determine index if a tab (li element) was clicked.
while (el != this.elButtonBar_) {
if (el.tagName == 'LI') {
var i;
// {} prevents compiler warning
for (i = 0; el = el.previousSibling; i++) {}
this.setSelectedIndex(i);
break;
}
el = el.parentNode;
}
event.preventDefault();
};
/**
* KeyDown event handler for header element. Arrow keys moves between pages.
* Home and end selects the first/last page.
*
* @param {goog.events.BrowserEvent} event KeyDown event.
* @private
*/
goog.ui.TabPane.prototype.onHeaderKeyDown_ = function(event) {
if (event.altKey || event.metaKey || event.ctrlKey) {
return;
}
switch (event.keyCode) {
case goog.events.KeyCodes.LEFT:
var index = this.selected_.getIndex() - 1;
this.setSelectedIndex(index < 0 ? this.pages_.length - 1 : index);
break;
case goog.events.KeyCodes.RIGHT:
var index = this.selected_.getIndex() + 1;
this.setSelectedIndex(index >= this.pages_.length ? 0 : index);
break;
case goog.events.KeyCodes.HOME:
this.setSelectedIndex(0);
break;
case goog.events.KeyCodes.END:
this.setSelectedIndex(this.pages_.length - 1);
break;
}
};
/**
* Object representing an individual tab pane.
*
* @param {Element=} opt_el Container element to create the pane out of.
* @param {(Element|string)=} opt_title Pane title or element to use as the
* title. If not specified the first element in the container is used as
* the title.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper
* The first parameter can be omitted.
* @constructor
*/
goog.ui.TabPane.TabPage = function(opt_el, opt_title, opt_domHelper) {
var title, el;
if (goog.isString(opt_el) && !goog.isDef(opt_title)) {
title = opt_el;
} else if (opt_title) {
title = opt_title;
el = opt_el;
} else if (opt_el) {
var child = goog.dom.getFirstElementChild(opt_el);
if (child) {
title = goog.dom.getTextContent(child);
child.parentNode.removeChild(child);
}
el = opt_el;
}
/**
* DomHelper used to interact with the document, allowing components to be
* created in a different window. This property is considered protected;
* subclasses of Component may refer to it directly.
* @type {goog.dom.DomHelper}
* @protected
* @suppress {underscore}
*/
this.dom_ = opt_domHelper || goog.dom.getDomHelper();
/**
* Content element
* @type {Element}
* @private
*/
this.elContent_ = el || this.dom_.createDom('div');
/**
* Title element
* @type {Element}
* @private
*/
this.elTitle_ = this.dom_.createDom('li', null, title);
/**
* Parent TabPane reference.
* @type {goog.ui.TabPane?}
* @private
*/
this.parent_ = null;
/**
* Index for page in tab pane.
* @type {?number}
* @private
*/
this.index_ = null;
/**
* Flags if this page is enabled and can be selected.
* @type {boolean}
* @private
*/
this.enabled_ = true;
};
/**
* @return {string} The title for tab page.
*/
goog.ui.TabPane.TabPage.prototype.getTitle = function() {
return goog.dom.getTextContent(this.elTitle_);
};
/**
* Sets title for tab page.
*
* @param {string} title Title for tab page.
*/
goog.ui.TabPane.TabPage.prototype.setTitle = function(title) {
goog.dom.setTextContent(this.elTitle_, title);
};
/**
* @return {Element} The title element.
*/
goog.ui.TabPane.TabPage.prototype.getTitleElement = function() {
return this.elTitle_;
};
/**
* @return {Element} The content element.
*/
goog.ui.TabPane.TabPage.prototype.getContentElement = function() {
return this.elContent_;
};
/**
* @return {?number} The index of page in tab pane.
*/
goog.ui.TabPane.TabPage.prototype.getIndex = function() {
return this.index_;
};
/**
* @return {goog.ui.TabPane?} The parent tab pane for page.
*/
goog.ui.TabPane.TabPage.prototype.getParent = function() {
return this.parent_;
};
/**
* Selects page in the associated tab pane.
*/
goog.ui.TabPane.TabPage.prototype.select = function() {
if (this.parent_) {
this.parent_.setSelectedPage(this);
}
};
/**
* Sets the enabled state.
*
* @param {boolean} enabled Enabled state.
*/
goog.ui.TabPane.TabPage.prototype.setEnabled = function(enabled) {
this.enabled_ = enabled;
this.elTitle_.className = enabled ?
goog.getCssName('goog-tabpane-tab') :
goog.getCssName('goog-tabpane-tab-disabled');
};
/**
* Returns if the page is enabled.
* @return {boolean} Whether the page is enabled or not.
*/
goog.ui.TabPane.TabPage.prototype.isEnabled = function() {
return this.enabled_;
};
/**
* Sets visible state for page content and updates style of tab.
*
* @param {boolean} visible Visible state.
* @private
*/
goog.ui.TabPane.TabPage.prototype.setVisible_ = function(visible) {
if (this.isEnabled()) {
this.elContent_.style.display = visible ? '' : 'none';
this.elTitle_.className = visible ?
goog.getCssName('goog-tabpane-tab-selected') :
goog.getCssName('goog-tabpane-tab');
}
};
/**
* Sets parent tab pane for tab page.
*
* @param {goog.ui.TabPane?} tabPane Tab strip object.
* @param {number=} opt_index Index of page in pane.
* @private
*/
goog.ui.TabPane.TabPage.prototype.setParent_ = function(tabPane, opt_index) {
this.parent_ = tabPane;
this.index_ = goog.isDef(opt_index) ? opt_index : null;
};
/**
* Object representing a tab pane page changed event.
*
* @param {string} type Event type.
* @param {goog.ui.TabPane} target Tab widget initiating event.
* @param {goog.ui.TabPane.TabPage} page Selected page in tab pane.
* @extends {goog.events.Event}
* @constructor
*/
goog.ui.TabPaneEvent = function(type, target, page) {
goog.events.Event.call(this, type, target);
/**
* The selected page.
* @type {goog.ui.TabPane.TabPage}
*/
this.page = page;
};
goog.inherits(goog.ui.TabPaneEvent, 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 Generator for unique element IDs.
*
*/
goog.provide('goog.ui.IdGenerator');
/**
* Creates a new id generator.
* @constructor
*/
goog.ui.IdGenerator = function() {
};
goog.addSingletonGetter(goog.ui.IdGenerator);
/**
* Next unique ID to use
* @type {number}
* @private
*/
goog.ui.IdGenerator.prototype.nextId_ = 0;
/**
* Gets the next unique ID.
* @return {string} The next unique identifier.
*/
goog.ui.IdGenerator.prototype.getNextUniqueId = function() {
return ':' + (this.nextId_++).toString(36);
};
/**
* Default instance for id generation. Done as an instance instead of statics
* so it's possible to inject a mock for unit testing purposes.
* @type {goog.ui.IdGenerator}
* @deprecated Use goog.ui.IdGenerator.getInstance() instead and do not refer
* to goog.ui.IdGenerator.instance anymore.
*/
goog.ui.IdGenerator.instance = goog.ui.IdGenerator.getInstance();
| 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 Abstract base class for spell checker implementations.
*
* The spell checker supports two modes - synchronous and asynchronous.
*
* In synchronous mode subclass calls processText_ which processes all the text
* given to it before it returns. If the text string is very long, it could
* cause warnings from the browser that considers the script to be
* busy-looping.
*
* Asynchronous mode allows breaking processing large text segments without
* encountering stop script warnings by rescheduling remaining parts of the
* text processing to another stack.
*
* In asynchronous mode abstract spell checker keeps track of a number of text
* chunks that have been processed after the very beginning, and returns every
* so often so that the calling function could reschedule its execution on a
* different stack (for example by calling setInterval(0)).
*
* @author eae@google.com (Emil A Eklund)
* @author sergeys@google.com (Sergey Solyanik)
*/
goog.provide('goog.ui.AbstractSpellChecker');
goog.provide('goog.ui.AbstractSpellChecker.AsyncResult');
goog.require('goog.a11y.aria');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.dom.selection');
goog.require('goog.events.EventType');
goog.require('goog.math.Coordinate');
goog.require('goog.spell.SpellCheck');
goog.require('goog.structs.Set');
goog.require('goog.style');
goog.require('goog.ui.MenuItem');
goog.require('goog.ui.MenuSeparator');
goog.require('goog.ui.PopupMenu');
/**
* Abstract base class for spell checker editor implementations. Provides basic
* functionality such as word lookup and caching.
*
* @param {goog.spell.SpellCheck} handler Instance of the SpellCheckHandler
* support object to use. A single instance can be shared by multiple editor
* components.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @constructor
* @extends {goog.ui.Component}
*/
goog.ui.AbstractSpellChecker = function(handler, opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
/**
* Handler to use for caching and lookups.
* @type {goog.spell.SpellCheck}
* @protected
* @suppress {underscore}
*/
this.handler_ = handler;
/**
* Word to element references. Used by replace/ignore.
* @type {Object}
* @private
*/
this.wordElements_ = {};
/**
* List of all 'edit word' input elements.
* @type {Array.<Element>}
* @private
*/
this.inputElements_ = [];
/**
* Global regular expression for splitting a string into individual words and
* blocks of separators. Matches zero or one word followed by zero or more
* separators.
* @type {RegExp}
* @private
*/
this.splitRegex_ = new RegExp(
'([^' + goog.spell.SpellCheck.WORD_BOUNDARY_CHARS + ']*)' +
'([' + goog.spell.SpellCheck.WORD_BOUNDARY_CHARS + ']*)', 'g');
goog.events.listen(this.handler_,
goog.spell.SpellCheck.EventType.WORD_CHANGED, this.onWordChanged_,
false, this);
};
goog.inherits(goog.ui.AbstractSpellChecker, goog.ui.Component);
/**
* The prefix to mark keys with.
* @type {string}
* @private
*/
goog.ui.AbstractSpellChecker.KEY_PREFIX_ = ':';
/**
* The prefix for ids on the spans.
* @type {string}
* @private
*/
goog.ui.AbstractSpellChecker.ID_SUFFIX_ = 'sc';
/**
* The attribute name for original element contents (to offer subsequent
* correction menu).
* @type {string}
* @private
*/
goog.ui.AbstractSpellChecker.ORIGINAL_ = 'g-spell-original';
/**
* Suggestions menu.
*
* @type {goog.ui.PopupMenu|undefined}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.menu_;
/**
* Separator between suggestions and ignore in suggestions menu.
*
* @type {goog.ui.MenuSeparator|undefined}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.menuSeparator_;
/**
* Menu item for ignore option.
*
* @type {goog.ui.MenuItem|undefined}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.menuIgnore_;
/**
* Menu item for edit word option.
*
* @type {goog.ui.MenuItem|undefined}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.menuEdit_;
/**
* Whether the correction UI is visible.
*
* @type {boolean}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.isVisible_ = false;
/**
* Cache for corrected words. All corrected words are reverted to their original
* status on resume. Therefore that status is never written to the cache and is
* instead indicated by this set.
*
* @type {goog.structs.Set|undefined}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.correctedWords_;
/**
* Class name for suggestions menu.
*
* @type {string}
*/
goog.ui.AbstractSpellChecker.prototype.suggestionsMenuClassName =
goog.getCssName('goog-menu');
/**
* Whether corrected words should be highlighted.
*
* @type {boolean}
*/
goog.ui.AbstractSpellChecker.prototype.markCorrected = false;
/**
* Word the correction menu is displayed for.
*
* @type {string|undefined}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.activeWord_;
/**
* Element the correction menu is displayed for.
*
* @type {Element|undefined}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.activeElement_;
/**
* Indicator that the spell checker is running in the asynchronous mode.
*
* @type {boolean}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.asyncMode_ = false;
/**
* Maximum number of words to process on a single stack in asynchronous mode.
*
* @type {number}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.asyncWordsPerBatch_ = 1000;
/**
* Current text to process when running in the asynchronous mode.
*
* @type {string|undefined}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.asyncText_;
/**
* Current start index of the range that spell-checked correctly.
*
* @type {number|undefined}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.asyncRangeStart_;
/**
* Current node with which the asynchronous text is associated.
*
* @type {Node|undefined}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.asyncNode_;
/**
* Number of elements processed in the asyncronous mode since last yield.
*
* @type {number}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.processedElementsCount_ = 0;
/**
* Markers for the text that does not need to be included in the processing.
*
* For rich text editor this is a list of strings formatted as
* tagName.className or className. If both are specified, the element will be
* excluded if BOTH are matched. If only a className is specified, then we will
* exclude regions with the className. If only one marker is needed, it may be
* passed as a string.
* For plain text editor this is a RegExp that matches the excluded text.
*
* Used exclusively by the derived classes
*
* @type {Array.<string>|string|RegExp|undefined}
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.excludeMarker;
/**
* Next unique instance ID for a misspelled word.
* @type {number}
* @private
*/
goog.ui.AbstractSpellChecker.nextId_ = 1;
/**
* @return {goog.spell.SpellCheck} The handler used for caching and lookups.
* @override
* @suppress {checkTypes} This method makes no sense. It overrides
* Component's getHandler with something different.
*/
goog.ui.AbstractSpellChecker.prototype.getHandler = function() {
return this.handler_;
};
/**
* Sets the handler used for caching and lookups.
*
* @param {goog.spell.SpellCheck} handler The handler used for caching and
* lookups.
*/
goog.ui.AbstractSpellChecker.prototype.setHandler = function(handler) {
this.handler_ = handler;
};
/**
* @return {goog.ui.PopupMenu|undefined} The suggestions menu.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.getMenu = function() {
return this.menu_;
};
/**
* @return {goog.ui.MenuItem|undefined} The menu item for edit word option.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.getMenuEdit = function() {
return this.menuEdit_;
};
/**
* @return {number} The next unique instance ID for a misspelled word.
* @protected
*/
goog.ui.AbstractSpellChecker.getNextId = function() {
return goog.ui.AbstractSpellChecker.nextId_;
};
/**
* Sets the marker for the excluded text.
*
* {@see goog.ui.AbstractSpellChecker.prototype.excludeMarker}
*
* @param {Array.<string>|string|RegExp|null} marker A RegExp for plain text
* or class names for the rich text spell checker for the elements to
* exclude from checking.
*/
goog.ui.AbstractSpellChecker.prototype.setExcludeMarker = function(marker) {
this.excludeMarker = marker || undefined;
};
/**
* Checks spelling for all text.
* Should be overridden by implementation.
*/
goog.ui.AbstractSpellChecker.prototype.check = function() {
this.isVisible_ = true;
if (this.markCorrected) {
this.correctedWords_ = new goog.structs.Set();
}
};
/**
* Hides correction UI.
* Should be overridden by implementation.
*/
goog.ui.AbstractSpellChecker.prototype.resume = function() {
this.isVisible_ = false;
this.clearWordElements();
var input;
while (input = this.inputElements_.pop()) {
input.parentNode.replaceChild(
this.getDomHelper().createTextNode(input.value), input);
}
if (this.correctedWords_) {
this.correctedWords_.clear();
}
};
/**
* @return {boolean} Whether the correction ui is visible.
*/
goog.ui.AbstractSpellChecker.prototype.isVisible = function() {
return this.isVisible_;
};
/**
* Clears the word to element references map used by replace/ignore.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.clearWordElements = function() {
this.wordElements_ = {};
};
/**
* Ignores spelling of word.
*
* @param {string} word Word to add.
*/
goog.ui.AbstractSpellChecker.prototype.ignoreWord = function(word) {
this.handler_.setWordStatus(word,
goog.spell.SpellCheck.WordStatus.IGNORED);
};
/**
* Edits a word.
*
* @param {Element} el An element wrapping the word that should be edited.
* @param {string} old Word to edit.
* @private
*/
goog.ui.AbstractSpellChecker.prototype.editWord_ = function(el, old) {
var input = this.getDomHelper().createDom(
'input', {'type': 'text', 'value': old});
var w = goog.style.getSize(el).width;
// Minimum width to ensure there's always enough room to type.
if (w < 50) {
w = 50;
}
input.style.width = w + 'px';
el.parentNode.replaceChild(input, el);
try {
input.focus();
goog.dom.selection.setCursorPosition(input, old.length);
} catch (o) { }
this.inputElements_.push(input);
};
/**
* Replaces word.
*
* @param {Element} el An element wrapping the word that should be replaced.
* @param {string} old Word that was replaced.
* @param {string} word Word to replace with.
*/
goog.ui.AbstractSpellChecker.prototype.replaceWord = function(el, old, word) {
if (old != word) {
if (!el.getAttribute(goog.ui.AbstractSpellChecker.ORIGINAL_)) {
el.setAttribute(goog.ui.AbstractSpellChecker.ORIGINAL_, old);
}
goog.dom.setTextContent(el, word);
var status = this.handler_.checkWord(word);
// Indicate that the word is corrected unless the status is 'INVALID'.
// (if markCorrected is enabled).
if (this.markCorrected && this.correctedWords_ &&
status != goog.spell.SpellCheck.WordStatus.INVALID) {
this.correctedWords_.add(word);
status = goog.spell.SpellCheck.WordStatus.CORRECTED;
}
// Avoid potential collision with the built-in object namespace. For
// example, 'watch' is a reserved name in FireFox.
var oldIndex = goog.ui.AbstractSpellChecker.toInternalKey_(old);
var newIndex = goog.ui.AbstractSpellChecker.toInternalKey_(word);
// Remove reference between old word and element
var elements = this.wordElements_[oldIndex];
goog.array.remove(elements, el);
if (status != goog.spell.SpellCheck.WordStatus.VALID) {
// Create reference between new word and element
if (this.wordElements_[newIndex]) {
this.wordElements_[newIndex].push(el);
} else {
this.wordElements_[newIndex] = [el];
}
}
// Update element based on status.
this.updateElement(el, word, status);
this.dispatchEvent(goog.events.EventType.CHANGE);
}
};
/**
* Retrieves the array of suggested spelling choices.
*
* @return {Array.<string>} Suggested spelling choices.
* @private
*/
goog.ui.AbstractSpellChecker.prototype.getSuggestions_ = function() {
// Add new suggestion entries.
var suggestions = this.handler_.getSuggestions(
/** @type {string} */ (this.activeWord_));
if (!suggestions[0]) {
var originalWord = this.activeElement_.getAttribute(
goog.ui.AbstractSpellChecker.ORIGINAL_);
if (originalWord && originalWord != this.activeWord_) {
suggestions = this.handler_.getSuggestions(originalWord);
}
}
return suggestions;
};
/**
* Displays suggestions menu.
*
* @param {Element} el Element to display menu for.
* @param {goog.events.BrowserEvent|goog.math.Coordinate=} opt_pos Position to
* display menu at relative to the viewport (in client coordinates), or a
* mouse event.
*/
goog.ui.AbstractSpellChecker.prototype.showSuggestionsMenu = function(el,
opt_pos) {
this.activeWord_ = goog.dom.getTextContent(el);
this.activeElement_ = el;
// Remove suggestion entries from menu, if any.
while (this.menu_.getChildAt(0) != this.menuSeparator_) {
this.menu_.removeChildAt(0, true).dispose();
}
// Add new suggestion entries.
var suggestions = this.getSuggestions_();
for (var suggestion, i = 0; suggestion = suggestions[i]; i++) {
this.menu_.addChildAt(new goog.ui.MenuItem(
suggestion, suggestion, this.getDomHelper()), i, true);
}
if (!suggestions[0]) {
/** @desc Item shown in menu when no suggestions are available. */
var MSG_SPELL_NO_SUGGESTIONS = goog.getMsg('No Suggestions');
var item = new goog.ui.MenuItem(
MSG_SPELL_NO_SUGGESTIONS, '', this.getDomHelper());
item.setEnabled(false);
this.menu_.addChildAt(item, 0, true);
}
// Show 'Edit word' option if {@link markCorrected} is enabled and don't show
// 'Ignore' option for corrected words.
if (this.markCorrected) {
var corrected = this.correctedWords_ &&
this.correctedWords_.contains(this.activeWord_);
this.menuIgnore_.setVisible(!corrected);
this.menuEdit_.setVisible(true);
} else {
this.menuIgnore_.setVisible(true);
this.menuEdit_.setVisible(false);
}
if (opt_pos) {
if (!(opt_pos instanceof goog.math.Coordinate)) { // it's an event
var posX = opt_pos.clientX;
var posY = opt_pos.clientY;
// Certain implementations which derive from AbstractSpellChecker
// use an iframe in which case the coordinates are relative to
// that iframe's view port.
if (this.getElement().contentDocument ||
this.getElement().contentWindow) {
var offset = goog.style.getClientPosition(this.getElement());
posX += offset.x;
posY += offset.y;
}
opt_pos = new goog.math.Coordinate(posX, posY);
}
this.menu_.showAt(opt_pos.x, opt_pos.y);
} else {
this.menu_.setVisible(true);
}
};
/**
* Initializes suggestions menu. Populates menu with separator and ignore option
* that are always valid. Suggestions are later added above the separator.
*
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.initSuggestionsMenu = function() {
this.menu_ = new goog.ui.PopupMenu(this.getDomHelper());
this.menuSeparator_ = new goog.ui.MenuSeparator(this.getDomHelper());
// Leave alone setAllowAutoFocus at default (true). This allows menu to get
// keyboard focus and thus allowing non-mouse users to get to the menu.
/** @desc Ignore entry in suggestions menu. */
var MSG_SPELL_IGNORE = goog.getMsg('Ignore');
/** @desc Edit word entry in suggestions menu. */
var MSG_SPELL_EDIT_WORD = goog.getMsg('Edit Word');
this.menu_.addChild(this.menuSeparator_, true);
this.menuIgnore_ =
new goog.ui.MenuItem(MSG_SPELL_IGNORE, '', this.getDomHelper());
this.menu_.addChild(this.menuIgnore_, true);
this.menuEdit_ =
new goog.ui.MenuItem(MSG_SPELL_EDIT_WORD, '', this.getDomHelper());
this.menuEdit_.setVisible(false);
this.menu_.addChild(this.menuEdit_, true);
this.menu_.render();
goog.dom.classes.add(this.menu_.getElement(), this.suggestionsMenuClassName);
goog.events.listen(this.menu_, goog.ui.Component.EventType.ACTION,
this.onCorrectionAction, false, this);
};
/**
* Handles correction menu actions.
*
* @param {goog.events.Event} event Action event.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.onCorrectionAction = function(event) {
var word = /** @type {string} */ (this.activeWord_);
var el = /** @type {Element} */ (this.activeElement_);
if (event.target == this.menuIgnore_) {
this.ignoreWord(word);
} else if (event.target == this.menuEdit_) {
this.editWord_(el, word);
} else {
this.replaceWord(el, word, event.target.getModel());
this.dispatchEvent(goog.ui.Component.EventType.CHANGE);
}
delete this.activeWord_;
delete this.activeElement_;
};
/**
* Removes spell-checker markup and restore the node to text.
*
* @param {Element} el Word element. MUST have a text node child.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.removeMarkup = function(el) {
var firstChild = el.firstChild;
var text = firstChild.nodeValue;
if (el.nextSibling &&
el.nextSibling.nodeType == goog.dom.NodeType.TEXT) {
if (el.previousSibling &&
el.previousSibling.nodeType == goog.dom.NodeType.TEXT) {
el.previousSibling.nodeValue = el.previousSibling.nodeValue + text +
el.nextSibling.nodeValue;
this.getDomHelper().removeNode(el.nextSibling);
} else {
el.nextSibling.nodeValue = text + el.nextSibling.nodeValue;
}
} else if (el.previousSibling &&
el.previousSibling.nodeType == goog.dom.NodeType.TEXT) {
el.previousSibling.nodeValue += text;
} else {
el.parentNode.insertBefore(firstChild, el);
}
this.getDomHelper().removeNode(el);
};
/**
* Updates element based on word status. Either converts it to a text node, or
* merges it with the previous or next text node if the status of the world is
* VALID, in which case the element itself is eliminated.
*
* @param {Element} el Word element.
* @param {string} word Word to update status for.
* @param {goog.spell.SpellCheck.WordStatus} status Status of word.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.updateElement =
function(el, word, status) {
if (this.markCorrected && this.correctedWords_ &&
this.correctedWords_.contains(word)) {
status = goog.spell.SpellCheck.WordStatus.CORRECTED;
}
if (status == goog.spell.SpellCheck.WordStatus.VALID) {
this.removeMarkup(el);
} else {
goog.dom.setProperties(el, this.getElementProperties(status));
}
};
/**
* Generates unique Ids for spell checker elements.
* @param {number=} opt_id Id to suffix with.
* @return {string} Unique element id.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.makeElementId = function(opt_id) {
return (opt_id ? opt_id : goog.ui.AbstractSpellChecker.nextId_++) +
'.' + goog.ui.AbstractSpellChecker.ID_SUFFIX_;
};
/**
* Returns the span element that matches the given number id.
* @param {number} id Number id to make the element id.
* @return {Element} The matching span element or null if no span matches.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.getElementById = function(id) {
return this.getDomHelper().getElement(this.makeElementId(id));
};
/**
* Creates an element for a specified word and stores a reference to it.
*
* @param {string} word Word to create element for.
* @param {goog.spell.SpellCheck.WordStatus} status Status of word.
* @return {HTMLSpanElement} The created element.
* @protected
* @suppress {underscore}
*/
goog.ui.AbstractSpellChecker.prototype.createWordElement_ = function(word,
status) {
var parameters = this.getElementProperties(status);
// Add id & tabindex as necessary.
if (!parameters['id']) {
parameters['id'] = this.makeElementId();
}
if (!parameters['tabIndex']) {
parameters['tabIndex'] = -1;
}
var el = /** @type {!HTMLSpanElement} */
(this.getDomHelper().createDom('span', parameters, word));
goog.a11y.aria.setRole(el, 'menuitem');
goog.a11y.aria.setState(el, 'haspopup', true);
this.registerWordElement_(word, el);
return el;
};
/**
* Stores a reference to word element.
*
* @param {string} word The word to store.
* @param {HTMLSpanElement} el The element associated with it.
* @protected
* @suppress {underscore}
*/
goog.ui.AbstractSpellChecker.prototype.registerWordElement_ = function(word,
el) {
// Avoid potential collision with the built-in object namespace. For
// example, 'watch' is a reserved name in FireFox.
var index = goog.ui.AbstractSpellChecker.toInternalKey_(word);
if (this.wordElements_[index]) {
this.wordElements_[index].push(el);
} else {
this.wordElements_[index] = [el];
}
};
/**
* Returns desired element properties for the specified status.
* Should be overridden by implementation.
*
* @param {goog.spell.SpellCheck.WordStatus} status Status of word.
* @return {Object} Properties to apply to the element.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.getElementProperties =
goog.abstractMethod;
/**
* Handles word change events and updates the word elements accordingly.
*
* @param {goog.spell.SpellCheck.WordChangedEvent} event The event object.
* @private
*/
goog.ui.AbstractSpellChecker.prototype.onWordChanged_ = function(event) {
// Avoid potential collision with the built-in object namespace. For
// example, 'watch' is a reserved name in FireFox.
var index = goog.ui.AbstractSpellChecker.toInternalKey_(event.word);
var elements = this.wordElements_[index];
if (elements) {
for (var el, i = 0; el = elements[i]; i++) {
this.updateElement(el, event.word, event.status);
}
}
};
/** @override */
goog.ui.AbstractSpellChecker.prototype.disposeInternal = function() {
if (this.isVisible_) {
// Clears wordElements_
this.resume();
}
goog.events.unlisten(this.handler_,
goog.spell.SpellCheck.EventType.WORD_CHANGED, this.onWordChanged_,
false, this);
if (this.menu_) {
this.menu_.dispose();
delete this.menu_;
delete this.menuIgnore_;
delete this.menuSeparator_;
}
delete this.handler_;
delete this.wordElements_;
goog.ui.AbstractSpellChecker.superClass_.disposeInternal.call(this);
};
/**
* Precharges local dictionary cache. This is optional, but greatly reduces
* amount of subsequent churn in the DOM tree because most of the words become
* known from the very beginning.
*
* @param {string} text Text to process.
* @param {number} words Max number of words to scan.
* @return {number} number of words actually scanned.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.populateDictionary = function(text,
words) {
this.splitRegex_.lastIndex = 0;
var result;
var numScanned = 0;
while (result = this.splitRegex_.exec(text)) {
if (result[0].length == 0) {
break;
}
var word = result[1];
if (word) {
this.handler_.checkWord(word);
++numScanned;
if (numScanned >= words) {
break;
}
}
}
this.handler_.processPending();
return numScanned;
};
/**
* Processes word.
* Should be overridden by implementation.
*
* @param {Node} node Node containing word.
* @param {string} text Word to process.
* @param {goog.spell.SpellCheck.WordStatus} status Status of the word.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.processWord = function(
node, text, status) {
throw Error('Need to override processWord_ in derivative class');
};
/**
* Processes range of text that checks out (contains no unrecognized words).
* Should be overridden by implementation. May contain words and separators.
*
* @param {Node} node Node containing text range.
* @param {string} text text to process.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.processRange = function(node, text) {
throw Error('Need to override processRange_ in derivative class');
};
/**
* Starts asynchronous processing mode.
*
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.initializeAsyncMode = function() {
if (this.asyncMode_ || this.processedElementsCount_ ||
this.asyncText_ != null || this.asyncNode_) {
throw Error('Async mode already in progress.');
}
this.asyncMode_ = true;
this.processedElementsCount_ = 0;
delete this.asyncText_;
this.asyncRangeStart_ = 0;
delete this.asyncNode_;
this.blockReadyEvents();
};
/**
* Finalizes asynchronous processing mode. Should be called after there is no
* more text to process and processTextAsync and/or continueAsyncProcessing
* returned FINISHED.
*
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.finishAsyncProcessing = function() {
if (!this.asyncMode_ || this.asyncText_ != null || this.asyncNode_) {
throw Error('Async mode not started or there is still text to process.');
}
this.asyncMode_ = false;
this.processedElementsCount_ = 0;
this.unblockReadyEvents();
this.handler_.processPending();
};
/**
* Blocks processing of spell checker READY events. This is used in dictionary
* recharge and async mode so that completion is not signaled prematurely.
*
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.blockReadyEvents = function() {
goog.events.listen(this.handler_, goog.spell.SpellCheck.EventType.READY,
goog.events.Event.stopPropagation, true);
};
/**
* Unblocks processing of spell checker READY events. This is used in
* dictionary recharge and async mode so that completion is not signaled
* prematurely.
*
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.unblockReadyEvents = function() {
goog.events.unlisten(this.handler_, goog.spell.SpellCheck.EventType.READY,
goog.events.Event.stopPropagation, true);
};
/**
* Splits text into individual words and blocks of separators. Calls virtual
* processWord_ and processRange_ methods.
*
* @param {Node} node Node containing text.
* @param {string} text Text to process.
* @return {goog.ui.AbstractSpellChecker.AsyncResult} operation result.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.processTextAsync = function(
node, text) {
if (!this.asyncMode_ || this.asyncText_ != null || this.asyncNode_) {
throw Error('Not in async mode or previous text has not been processed.');
}
this.splitRegex_.lastIndex = 0;
var stringSegmentStart = 0;
var result;
while (result = this.splitRegex_.exec(text)) {
if (result[0].length == 0) {
break;
}
var word = result[1];
if (word) {
var status = this.handler_.checkWord(word);
if (status != goog.spell.SpellCheck.WordStatus.VALID) {
var preceedingText = text.substr(stringSegmentStart, result.index -
stringSegmentStart);
if (preceedingText) {
this.processRange(node, preceedingText);
}
stringSegmentStart = result.index + word.length;
this.processWord(node, word, status);
}
}
this.processedElementsCount_++;
if (this.processedElementsCount_ > this.asyncWordsPerBatch_) {
this.asyncText_ = text;
this.asyncRangeStart_ = stringSegmentStart;
this.asyncNode_ = node;
this.processedElementsCount_ = 0;
return goog.ui.AbstractSpellChecker.AsyncResult.PENDING;
}
}
var leftoverText = text.substr(stringSegmentStart);
if (leftoverText) {
this.processRange(node, leftoverText);
}
return goog.ui.AbstractSpellChecker.AsyncResult.DONE;
};
/**
* Continues processing started by processTextAsync. Calls virtual
* processWord_ and processRange_ methods.
*
* @return {goog.ui.AbstractSpellChecker.AsyncResult} operation result.
* @protected
*/
goog.ui.AbstractSpellChecker.prototype.continueAsyncProcessing = function() {
if (!this.asyncMode_ || this.asyncText_ == null || !this.asyncNode_) {
throw Error('Not in async mode or processing not started.');
}
var node = /** @type {Node} */ (this.asyncNode_);
var stringSegmentStart = this.asyncRangeStart_;
goog.asserts.assertNumber(stringSegmentStart);
var text = this.asyncText_;
var result;
while (result = this.splitRegex_.exec(text)) {
if (result[0].length == 0) {
break;
}
var word = result[1];
if (word) {
var status = this.handler_.checkWord(word);
if (status != goog.spell.SpellCheck.WordStatus.VALID) {
var preceedingText = text.substr(stringSegmentStart, result.index -
stringSegmentStart);
if (preceedingText) {
this.processRange(node, preceedingText);
}
stringSegmentStart = result.index + word.length;
this.processWord(node, word, status);
}
}
this.processedElementsCount_++;
if (this.processedElementsCount_ > this.asyncWordsPerBatch_) {
this.processedElementsCount_ = 0;
this.asyncRangeStart_ = stringSegmentStart;
return goog.ui.AbstractSpellChecker.AsyncResult.PENDING;
}
}
delete this.asyncText_;
this.asyncRangeStart_ = 0;
delete this.asyncNode_;
var leftoverText = text.substr(stringSegmentStart);
if (leftoverText) {
this.processRange(node, leftoverText);
}
return goog.ui.AbstractSpellChecker.AsyncResult.DONE;
};
/**
* Converts a word to an internal key representation. This is necessary to
* avoid collisions with object's internal namespace. Only words that are
* reserved need to be escaped.
*
* @param {string} word The word to map.
* @return {string} The index.
* @private
*/
goog.ui.AbstractSpellChecker.toInternalKey_ = function(word) {
if (word in Object.prototype) {
return goog.ui.AbstractSpellChecker.KEY_PREFIX_ + word;
}
return word;
};
/**
* Constants for representing the direction while navigating.
*
* @enum {number}
*/
goog.ui.AbstractSpellChecker.Direction = {
PREVIOUS: 0,
NEXT: 1
};
/**
* Constants for the result of asynchronous processing.
* @enum {number}
*/
goog.ui.AbstractSpellChecker.AsyncResult = {
/**
* Caller must reschedule operation and call continueAsyncProcessing on the
* new stack frame.
*/
PENDING: 1,
/**
* Current element has been fully processed. Caller can call
* processTextAsync or finishAsyncProcessing.
*/
DONE: 2
};
| 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 control renderers.
* TODO(attila): If the renderer framework works well, pull it into Component.
*
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.ui.ControlRenderer');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.State');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.object');
goog.require('goog.style');
goog.require('goog.ui.Component');
goog.require('goog.userAgent');
/**
* Default renderer for {@link goog.ui.Control}s. Can be used as-is, but
* subclasses of Control will probably want to use renderers specifically
* tailored for them by extending this class. Controls that use renderers
* delegate one or more of the following API methods to the renderer:
* <ul>
* <li>{@code createDom} - renders the DOM for the component
* <li>{@code canDecorate} - determines whether an element can be decorated
* by the component
* <li>{@code decorate} - decorates an existing element with the component
* <li>{@code setState} - updates the appearance of the component based on
* its state
* <li>{@code getContent} - returns the component's content
* <li>{@code setContent} - sets the component's content
* </ul>
* Controls are stateful; renderers, on the other hand, should be stateless and
* reusable.
* @constructor
*/
goog.ui.ControlRenderer = function() {
};
goog.addSingletonGetter(goog.ui.ControlRenderer);
/**
* Constructs a new renderer and sets the CSS class that the renderer will use
* as the base CSS class to apply to all elements rendered by that renderer.
* An example to use this function using a color palette:
*
* <pre>
* var myCustomRenderer = goog.ui.ControlRenderer.getCustomRenderer(
* goog.ui.PaletteRenderer, 'my-special-palette');
* var newColorPalette = new goog.ui.ColorPalette(
* colors, myCustomRenderer, opt_domHelper);
* </pre>
*
* Your CSS can look like this now:
* <pre>
* .my-special-palette { }
* .my-special-palette-table { }
* .my-special-palette-cell { }
* etc.
* </pre>
*
* <em>instead</em> of
* <pre>
* .CSS_MY_SPECIAL_PALETTE .goog-palette { }
* .CSS_MY_SPECIAL_PALETTE .goog-palette-table { }
* .CSS_MY_SPECIAL_PALETTE .goog-palette-cell { }
* etc.
* </pre>
*
* You would want to use this functionality when you want an instance of a
* component to have specific styles different than the other components of the
* same type in your application. This avoids using descendant selectors to
* apply the specific styles to this component.
*
* @param {Function} ctor The constructor of the renderer you are trying to
* create.
* @param {string} cssClassName The name of the CSS class for this renderer.
* @return {goog.ui.ControlRenderer} An instance of the desired renderer with
* its getCssClass() method overridden to return the supplied custom CSS
* class name.
*/
goog.ui.ControlRenderer.getCustomRenderer = function(ctor, cssClassName) {
var renderer = new ctor();
/**
* Returns the CSS class to be applied to the root element of components
* rendered using this renderer.
* @return {string} Renderer-specific CSS class.
*/
renderer.getCssClass = function() {
return cssClassName;
};
return renderer;
};
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.ControlRenderer.CSS_CLASS = goog.getCssName('goog-control');
/**
* Array of arrays of CSS classes that we want composite classes added and
* removed for in IE6 and lower as a workaround for lack of multi-class CSS
* selector support.
*
* Subclasses that have accompanying CSS requiring this workaround should define
* their own static IE6_CLASS_COMBINATIONS constant and override
* getIe6ClassCombinations to return it.
*
* For example, if your stylesheet uses the selector .button.collapse-left
* (and is compiled to .button_collapse-left for the IE6 version of the
* stylesheet,) you should include ['button', 'collapse-left'] in this array
* and the class button_collapse-left will be applied to the root element
* whenever both button and collapse-left are applied individually.
*
* Members of each class name combination will be joined with underscores in the
* order that they're defined in the array. You should alphabetize them (for
* compatibility with the CSS compiler) unless you are doing something special.
* @type {Array.<Array.<string>>}
*/
goog.ui.ControlRenderer.IE6_CLASS_COMBINATIONS = [];
/**
* Map of component states to corresponding ARIA states. Since the mapping of
* component states to ARIA states is neither component- nor renderer-specific,
* this is a static property of the renderer class, and is initialized on first
* use.
* @type {Object}
* @private
*/
goog.ui.ControlRenderer.ARIA_STATE_MAP_;
/**
* Returns the ARIA role to be applied to the control.
* See http://wiki/Main/ARIA for more info.
* @return {goog.a11y.aria.Role|undefined} ARIA role.
*/
goog.ui.ControlRenderer.prototype.getAriaRole = function() {
// By default, the ARIA role is unspecified.
return undefined;
};
/**
* Returns the control's contents wrapped in a DIV, with the renderer's own
* CSS class and additional state-specific classes applied to it.
* @param {goog.ui.Control} control Control to render.
* @return {Element} Root element for the control.
*/
goog.ui.ControlRenderer.prototype.createDom = function(control) {
// Create and return DIV wrapping contents.
var element = control.getDomHelper().createDom(
'div', this.getClassNames(control).join(' '), control.getContent());
this.setAriaStates(control, element);
return element;
};
/**
* Takes the control's root element and returns the parent element of the
* control's contents. Since by default controls are rendered as a single
* DIV, the default implementation returns the element itself. Subclasses
* with more complex DOM structures must override this method as needed.
* @param {Element} element Root element of the control whose content element
* is to be returned.
* @return {Element} The control's content element.
*/
goog.ui.ControlRenderer.prototype.getContentElement = function(element) {
return element;
};
/**
* Updates the control's DOM by adding or removing the specified class name
* to/from its root element. May add additional combined classes as needed in
* IE6 and lower. Because of this, subclasses should use this method when
* modifying class names on the control's root element.
* @param {goog.ui.Control|Element} control Control instance (or root element)
* to be updated.
* @param {string} className CSS class name to add or remove.
* @param {boolean} enable Whether to add or remove the class name.
*/
goog.ui.ControlRenderer.prototype.enableClassName = function(control,
className, enable) {
var element = /** @type {Element} */ (
control.getElement ? control.getElement() : control);
if (element) {
// For IE6, we need to enable any combined classes involving this class
// as well.
if (goog.userAgent.IE && !goog.userAgent.isVersion('7')) {
var combinedClasses = this.getAppliedCombinedClassNames_(
goog.dom.classes.get(element), className);
combinedClasses.push(className);
var f = enable ? goog.dom.classes.add : goog.dom.classes.remove;
goog.partial(f, element).apply(null, combinedClasses);
} else {
goog.dom.classes.enable(element, className, enable);
}
}
};
/**
* Updates the control's DOM by adding or removing the specified extra class
* name to/from its element.
* @param {goog.ui.Control} control Control to be updated.
* @param {string} className CSS class name to add or remove.
* @param {boolean} enable Whether to add or remove the class name.
*/
goog.ui.ControlRenderer.prototype.enableExtraClassName = function(control,
className, enable) {
// The base class implementation is trivial; subclasses should override as
// needed.
this.enableClassName(control, className, enable);
};
/**
* Returns true if this renderer can decorate the element, false otherwise.
* The default implementation always returns true.
* @param {Element} element Element to decorate.
* @return {boolean} Whether the renderer can decorate the element.
*/
goog.ui.ControlRenderer.prototype.canDecorate = function(element) {
return true;
};
/**
* Default implementation of {@code decorate} for {@link goog.ui.Control}s.
* Initializes the control's ID, content, and state based on the ID of the
* element, its child nodes, and its CSS classes, respectively. Returns the
* element.
* @param {goog.ui.Control} control Control instance to decorate the element.
* @param {Element} element Element to decorate.
* @return {Element} Decorated element.
* @suppress {visibility} setContentInternal and setStateInternal
*/
goog.ui.ControlRenderer.prototype.decorate = function(control, element) {
// Set the control's ID to the decorated element's DOM ID, if any.
if (element.id) {
control.setId(element.id);
}
// Set the control's content to the decorated element's content.
var contentElem = this.getContentElement(element);
if (contentElem && contentElem.firstChild) {
control.setContentInternal(contentElem.firstChild.nextSibling ?
goog.array.clone(contentElem.childNodes) : contentElem.firstChild);
} else {
control.setContentInternal(null);
}
// Initialize the control's state based on the decorated element's CSS class.
// This implementation is optimized to minimize object allocations, string
// comparisons, and DOM access.
var state = 0x00;
var rendererClassName = this.getCssClass();
var structuralClassName = this.getStructuralCssClass();
var hasRendererClassName = false;
var hasStructuralClassName = false;
var hasCombinedClassName = false;
var classNames = goog.dom.classes.get(element);
goog.array.forEach(classNames, function(className) {
if (!hasRendererClassName && className == rendererClassName) {
hasRendererClassName = true;
if (structuralClassName == rendererClassName) {
hasStructuralClassName = true;
}
} else if (!hasStructuralClassName && className == structuralClassName) {
hasStructuralClassName = true;
} else {
state |= this.getStateFromClass(className);
}
}, this);
control.setStateInternal(state);
// Make sure the element has the renderer's CSS classes applied, as well as
// any extra class names set on the control.
if (!hasRendererClassName) {
classNames.push(rendererClassName);
if (structuralClassName == rendererClassName) {
hasStructuralClassName = true;
}
}
if (!hasStructuralClassName) {
classNames.push(structuralClassName);
}
var extraClassNames = control.getExtraClassNames();
if (extraClassNames) {
classNames.push.apply(classNames, extraClassNames);
}
// For IE6, rewrite all classes on the decorated element if any combined
// classes apply.
if (goog.userAgent.IE && !goog.userAgent.isVersion('7')) {
var combinedClasses = this.getAppliedCombinedClassNames_(
classNames);
if (combinedClasses.length > 0) {
classNames.push.apply(classNames, combinedClasses);
hasCombinedClassName = true;
}
}
// Only write to the DOM if new class names had to be added to the element.
if (!hasRendererClassName || !hasStructuralClassName ||
extraClassNames || hasCombinedClassName) {
goog.dom.classes.set(element, classNames.join(' '));
}
this.setAriaStates(control, element);
return element;
};
/**
* Initializes the control's DOM by configuring properties that can only be set
* after the DOM has entered the document. This implementation sets up BiDi
* and keyboard focus. Called from {@link goog.ui.Control#enterDocument}.
* @param {goog.ui.Control} control Control whose DOM is to be initialized
* as it enters the document.
*/
goog.ui.ControlRenderer.prototype.initializeDom = function(control) {
// Initialize render direction (BiDi). We optimize the left-to-right render
// direction by assuming that elements are left-to-right by default, and only
// updating their styling if they are explicitly set to right-to-left.
if (control.isRightToLeft()) {
this.setRightToLeft(control.getElement(), true);
}
// Initialize keyboard focusability (tab index). We assume that components
// aren't focusable by default (i.e have no tab index), and only touch the
// DOM if the component is focusable, enabled, and visible, and therefore
// needs a tab index.
if (control.isEnabled()) {
this.setFocusable(control, control.isVisible());
}
};
/**
* Sets the element's ARIA role.
* @param {Element} element Element to update.
* @param {?goog.a11y.aria.Role=} opt_preferredRole The preferred ARIA role.
*/
goog.ui.ControlRenderer.prototype.setAriaRole = function(element,
opt_preferredRole) {
var ariaRole = opt_preferredRole || this.getAriaRole();
if (ariaRole) {
goog.asserts.assert(element,
'The element passed as a first parameter cannot be null.');
goog.a11y.aria.setRole(element, ariaRole);
}
};
/**
* Sets the element's ARIA states. An element does not need an ARIA role in
* order to have an ARIA state. Only states which are initialized to be true
* will be set.
* @param {!goog.ui.Control} control Control whose ARIA state will be updated.
* @param {!Element} element Element whose ARIA state is to be updated.
*/
goog.ui.ControlRenderer.prototype.setAriaStates = function(control, element) {
goog.asserts.assert(control);
goog.asserts.assert(element);
if (!control.isVisible()) {
goog.a11y.aria.setState(
element, goog.a11y.aria.State.HIDDEN, !control.isVisible());
}
if (!control.isEnabled()) {
this.updateAriaState(
element, goog.ui.Component.State.DISABLED, !control.isEnabled());
}
if (control.isSupportedState(goog.ui.Component.State.SELECTED)) {
this.updateAriaState(
element, goog.ui.Component.State.SELECTED, control.isSelected());
}
if (control.isSupportedState(goog.ui.Component.State.CHECKED)) {
this.updateAriaState(
element, goog.ui.Component.State.CHECKED, control.isChecked());
}
if (control.isSupportedState(goog.ui.Component.State.OPENED)) {
this.updateAriaState(
element, goog.ui.Component.State.OPENED, control.isOpen());
}
};
/**
* Allows or disallows text selection within the control's DOM.
* @param {Element} element The control's root element.
* @param {boolean} allow Whether the element should allow text selection.
*/
goog.ui.ControlRenderer.prototype.setAllowTextSelection = function(element,
allow) {
// On all browsers other than IE and Opera, it isn't necessary to recursively
// apply unselectable styling to the element's children.
goog.style.setUnselectable(element, !allow,
!goog.userAgent.IE && !goog.userAgent.OPERA);
};
/**
* Applies special styling to/from the control's element if it is rendered
* right-to-left, and removes it if it is rendered left-to-right.
* @param {Element} element The control's root element.
* @param {boolean} rightToLeft Whether the component is rendered
* right-to-left.
*/
goog.ui.ControlRenderer.prototype.setRightToLeft = function(element,
rightToLeft) {
this.enableClassName(element,
goog.getCssName(this.getStructuralCssClass(), 'rtl'), rightToLeft);
};
/**
* Returns true if the control's key event target supports keyboard focus
* (based on its {@code tabIndex} attribute), false otherwise.
* @param {goog.ui.Control} control Control whose key event target is to be
* checked.
* @return {boolean} Whether the control's key event target is focusable.
*/
goog.ui.ControlRenderer.prototype.isFocusable = function(control) {
var keyTarget;
if (control.isSupportedState(goog.ui.Component.State.FOCUSED) &&
(keyTarget = control.getKeyEventTarget())) {
return goog.dom.isFocusableTabIndex(keyTarget);
}
return false;
};
/**
* Updates the control's key event target to make it focusable or non-focusable
* via its {@code tabIndex} attribute. Does nothing if the control doesn't
* support the {@code FOCUSED} state, or if it has no key event target.
* @param {goog.ui.Control} control Control whose key event target is to be
* updated.
* @param {boolean} focusable Whether to enable keyboard focus support on the
* control's key event target.
*/
goog.ui.ControlRenderer.prototype.setFocusable = function(control, focusable) {
var keyTarget;
if (control.isSupportedState(goog.ui.Component.State.FOCUSED) &&
(keyTarget = control.getKeyEventTarget())) {
if (!focusable && control.isFocused()) {
// Blur before hiding. Note that IE calls onblur handlers asynchronously.
try {
keyTarget.blur();
} catch (e) {
// TODO(user|user): Find out why this fails on IE.
}
// The blur event dispatched by the key event target element when blur()
// was called on it should have been handled by the control's handleBlur()
// method, so at this point the control should no longer be focused.
// However, blur events are unreliable on IE and FF3, so if at this point
// the control is still focused, we trigger its handleBlur() method
// programmatically.
if (control.isFocused()) {
control.handleBlur(null);
}
}
// Don't overwrite existing tab index values unless needed.
if (goog.dom.isFocusableTabIndex(keyTarget) != focusable) {
goog.dom.setFocusableTabIndex(keyTarget, focusable);
}
}
};
/**
* Shows or hides the element.
* @param {Element} element Element to update.
* @param {boolean} visible Whether to show the element.
*/
goog.ui.ControlRenderer.prototype.setVisible = function(element, visible) {
// The base class implementation is trivial; subclasses should override as
// needed. It should be possible to do animated reveals, for example.
goog.style.setElementShown(element, visible);
if (element) {
goog.a11y.aria.setState(element, goog.a11y.aria.State.HIDDEN, !visible);
}
};
/**
* Updates the appearance of the control in response to a state change.
* @param {goog.ui.Control} control Control instance to update.
* @param {goog.ui.Component.State} state State to enable or disable.
* @param {boolean} enable Whether the control is entering or exiting the state.
*/
goog.ui.ControlRenderer.prototype.setState = function(control, state, enable) {
var element = control.getElement();
if (element) {
var className = this.getClassForState(state);
if (className) {
this.enableClassName(control, className, enable);
}
this.updateAriaState(element, state, enable);
}
};
/**
* Updates the element's ARIA (accessibility) state.
* @param {Element} element Element whose ARIA state is to be updated.
* @param {goog.ui.Component.State} state Component state being enabled or
* disabled.
* @param {boolean} enable Whether the state is being enabled or disabled.
* @protected
*/
goog.ui.ControlRenderer.prototype.updateAriaState = function(element, state,
enable) {
// Ensure the ARIA state map exists.
if (!goog.ui.ControlRenderer.ARIA_STATE_MAP_) {
goog.ui.ControlRenderer.ARIA_STATE_MAP_ = goog.object.create(
goog.ui.Component.State.DISABLED, goog.a11y.aria.State.DISABLED,
goog.ui.Component.State.SELECTED, goog.a11y.aria.State.SELECTED,
goog.ui.Component.State.CHECKED, goog.a11y.aria.State.CHECKED,
goog.ui.Component.State.OPENED, goog.a11y.aria.State.EXPANDED);
}
var ariaState = goog.ui.ControlRenderer.ARIA_STATE_MAP_[state];
if (ariaState) {
goog.asserts.assert(element,
'The element passed as a first parameter cannot be null.');
goog.a11y.aria.setState(element, ariaState, enable);
}
};
/**
* Takes a control's root element, and sets its content to the given text
* caption or DOM structure. The default implementation replaces the children
* of the given element. Renderers that create more complex DOM structures
* must override this method accordingly.
* @param {Element} element The control's root element.
* @param {goog.ui.ControlContent} content Text caption or DOM structure to be
* set as the control's content. The DOM nodes will not be cloned, they
* will only moved under the content element of the control.
*/
goog.ui.ControlRenderer.prototype.setContent = function(element, content) {
var contentElem = this.getContentElement(element);
if (contentElem) {
goog.dom.removeChildren(contentElem);
if (content) {
if (goog.isString(content)) {
goog.dom.setTextContent(contentElem, content);
} else {
var childHandler = function(child) {
if (child) {
var doc = goog.dom.getOwnerDocument(contentElem);
contentElem.appendChild(goog.isString(child) ?
doc.createTextNode(child) : child);
}
};
if (goog.isArray(content)) {
// Array of nodes.
goog.array.forEach(content, childHandler);
} else if (goog.isArrayLike(content) && !('nodeType' in content)) {
// NodeList. The second condition filters out TextNode which also has
// length attribute but is not array like. The nodes have to be cloned
// because childHandler removes them from the list during iteration.
goog.array.forEach(goog.array.clone(/** @type {NodeList} */(content)),
childHandler);
} else {
// Node or string.
childHandler(content);
}
}
}
}
};
/**
* Returns the element within the component's DOM that should receive keyboard
* focus (null if none). The default implementation returns the control's root
* element.
* @param {goog.ui.Control} control Control whose key event target is to be
* returned.
* @return {Element} The key event target.
*/
goog.ui.ControlRenderer.prototype.getKeyEventTarget = function(control) {
return control.getElement();
};
// CSS class name management.
/**
* Returns the CSS class name to be applied to the root element of all
* components rendered or decorated using this renderer. The class name
* is expected to uniquely identify the renderer class, i.e. no two
* renderer classes are expected to share the same CSS class name.
* @return {string} Renderer-specific CSS class name.
*/
goog.ui.ControlRenderer.prototype.getCssClass = function() {
return goog.ui.ControlRenderer.CSS_CLASS;
};
/**
* Returns an array of combinations of classes to apply combined class names for
* in IE6 and below. See {@link IE6_CLASS_COMBINATIONS} for more detail. This
* method doesn't reference {@link IE6_CLASS_COMBINATIONS} so that it can be
* compiled out, but subclasses should return their IE6_CLASS_COMBINATIONS
* static constant instead.
* @return {Array.<Array.<string>>} Array of class name combinations.
*/
goog.ui.ControlRenderer.prototype.getIe6ClassCombinations = function() {
return [];
};
/**
* Returns the name of a DOM structure-specific CSS class to be applied to the
* root element of all components rendered or decorated using this renderer.
* Unlike the class name returned by {@link #getCssClass}, the structural class
* name may be shared among different renderers that generate similar DOM
* structures. The structural class name also serves as the basis of derived
* class names used to identify and style structural elements of the control's
* DOM, as well as the basis for state-specific class names. The default
* implementation returns the same class name as {@link #getCssClass}, but
* subclasses are expected to override this method as needed.
* @return {string} DOM structure-specific CSS class name (same as the renderer-
* specific CSS class name by default).
*/
goog.ui.ControlRenderer.prototype.getStructuralCssClass = function() {
return this.getCssClass();
};
/**
* Returns all CSS class names applicable to the given control, based on its
* state. The return value is an array of strings containing
* <ol>
* <li>the renderer-specific CSS class returned by {@link #getCssClass},
* followed by
* <li>the structural CSS class returned by {@link getStructuralCssClass} (if
* different from the renderer-specific CSS class), followed by
* <li>any state-specific classes returned by {@link #getClassNamesForState},
* followed by
* <li>any extra classes returned by the control's {@code getExtraClassNames}
* method and
* <li>for IE6 and lower, additional combined classes from
* {@link getAppliedCombinedClassNames_}.
* </ol>
* Since all controls have at least one renderer-specific CSS class name, this
* method is guaranteed to return an array of at least one element.
* @param {goog.ui.Control} control Control whose CSS classes are to be
* returned.
* @return {Array.<string>} Array of CSS class names applicable to the control.
* @protected
*/
goog.ui.ControlRenderer.prototype.getClassNames = function(control) {
var cssClass = this.getCssClass();
// Start with the renderer-specific class name.
var classNames = [cssClass];
// Add structural class name, if different.
var structuralCssClass = this.getStructuralCssClass();
if (structuralCssClass != cssClass) {
classNames.push(structuralCssClass);
}
// Add state-specific class names, if any.
var classNamesForState = this.getClassNamesForState(control.getState());
classNames.push.apply(classNames, classNamesForState);
// Add extra class names, if any.
var extraClassNames = control.getExtraClassNames();
if (extraClassNames) {
classNames.push.apply(classNames, extraClassNames);
}
// Add composite classes for IE6 support
if (goog.userAgent.IE && !goog.userAgent.isVersion('7')) {
classNames.push.apply(classNames,
this.getAppliedCombinedClassNames_(classNames));
}
return classNames;
};
/**
* Returns an array of all the combined class names that should be applied based
* on the given list of classes. Checks the result of
* {@link getIe6ClassCombinations} for any combinations that have all
* members contained in classes. If a combination matches, the members are
* joined with an underscore (in order), and added to the return array.
*
* If opt_includedClass is provided, return only the combined classes that have
* all members contained in classes AND include opt_includedClass as well.
* opt_includedClass is added to classes as well.
* @param {Array.<string>} classes Array of classes to return matching combined
* classes for.
* @param {?string=} opt_includedClass If provided, get only the combined
* classes that include this one.
* @return {Array.<string>} Array of combined class names that should be
* applied.
* @private
*/
goog.ui.ControlRenderer.prototype.getAppliedCombinedClassNames_ = function(
classes, opt_includedClass) {
var toAdd = [];
if (opt_includedClass) {
classes = classes.concat([opt_includedClass]);
}
goog.array.forEach(this.getIe6ClassCombinations(), function(combo) {
if (goog.array.every(combo, goog.partial(goog.array.contains, classes)) &&
(!opt_includedClass || goog.array.contains(combo, opt_includedClass))) {
toAdd.push(combo.join('_'));
}
});
return toAdd;
};
/**
* Takes a bit mask of {@link goog.ui.Component.State}s, and returns an array
* of the appropriate class names representing the given state, suitable to be
* applied to the root element of a component rendered using this renderer, or
* null if no state-specific classes need to be applied. This default
* implementation uses the renderer's {@link getClassForState} method to
* generate each state-specific class.
* @param {number} state Bit mask of component states.
* @return {!Array.<string>} Array of CSS class names representing the given
* state.
* @protected
*/
goog.ui.ControlRenderer.prototype.getClassNamesForState = function(state) {
var classNames = [];
while (state) {
// For each enabled state, push the corresponding CSS class name onto
// the classNames array.
var mask = state & -state; // Least significant bit
classNames.push(this.getClassForState(
/** @type {goog.ui.Component.State} */ (mask)));
state &= ~mask;
}
return classNames;
};
/**
* Takes a single {@link goog.ui.Component.State}, and returns the
* corresponding CSS class name (null if none).
* @param {goog.ui.Component.State} state Component state.
* @return {string|undefined} CSS class representing the given state (undefined
* if none).
* @protected
*/
goog.ui.ControlRenderer.prototype.getClassForState = function(state) {
if (!this.classByState_) {
this.createClassByStateMap_();
}
return this.classByState_[state];
};
/**
* Takes a single CSS class name which may represent a component state, and
* returns the corresponding component state (0x00 if none).
* @param {string} className CSS class name, possibly representing a component
* state.
* @return {goog.ui.Component.State} state Component state corresponding
* to the given CSS class (0x00 if none).
* @protected
*/
goog.ui.ControlRenderer.prototype.getStateFromClass = function(className) {
if (!this.stateByClass_) {
this.createStateByClassMap_();
}
var state = parseInt(this.stateByClass_[className], 10);
return /** @type {goog.ui.Component.State} */ (isNaN(state) ? 0x00 : state);
};
/**
* Creates the lookup table of states to classes, used during state changes.
* @private
*/
goog.ui.ControlRenderer.prototype.createClassByStateMap_ = function() {
var baseClass = this.getStructuralCssClass();
/**
* Map of component states to state-specific structural class names,
* used when changing the DOM in response to a state change. Precomputed
* and cached on first use to minimize object allocations and string
* concatenation.
* @type {Object}
* @private
*/
this.classByState_ = goog.object.create(
goog.ui.Component.State.DISABLED, goog.getCssName(baseClass, 'disabled'),
goog.ui.Component.State.HOVER, goog.getCssName(baseClass, 'hover'),
goog.ui.Component.State.ACTIVE, goog.getCssName(baseClass, 'active'),
goog.ui.Component.State.SELECTED, goog.getCssName(baseClass, 'selected'),
goog.ui.Component.State.CHECKED, goog.getCssName(baseClass, 'checked'),
goog.ui.Component.State.FOCUSED, goog.getCssName(baseClass, 'focused'),
goog.ui.Component.State.OPENED, goog.getCssName(baseClass, 'open'));
};
/**
* Creates the lookup table of classes to states, used during decoration.
* @private
*/
goog.ui.ControlRenderer.prototype.createStateByClassMap_ = function() {
// We need the classByState_ map so we can transpose it.
if (!this.classByState_) {
this.createClassByStateMap_();
}
/**
* Map of state-specific structural class names to component states,
* used during element decoration. Precomputed and cached on first use
* to minimize object allocations and string concatenation.
* @type {Object}
* @private
*/
this.stateByClass_ = goog.object.transpose(this.classByState_);
};
| 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 alternative custom button renderer that uses even more CSS
* voodoo than the default implementation to render custom buttons with fake
* rounded corners and dimensionality (via a subtle flat shadow on the bottom
* half of the button) without the use of images.
*
* Based on the Custom Buttons 3.1 visual specification, see
* http://go/custombuttons
*
* @author eae@google.com (Emil A Eklund)
* @author dalewis@google.com (Darren Lewis)
* @see ../demos/imagelessmenubutton.html
*/
goog.provide('goog.ui.ImagelessMenuButtonRenderer');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.classes');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.INLINE_BLOCK_CLASSNAME');
goog.require('goog.ui.MenuButton');
goog.require('goog.ui.MenuButtonRenderer');
goog.require('goog.ui.registry');
/**
* Custom renderer for {@link goog.ui.MenuButton}s. Imageless buttons can
* contain almost arbitrary HTML content, will flow like inline elements, but
* can be styled like block-level elements.
*
* @constructor
* @extends {goog.ui.MenuButtonRenderer}
*/
goog.ui.ImagelessMenuButtonRenderer = function() {
goog.ui.MenuButtonRenderer.call(this);
};
goog.inherits(goog.ui.ImagelessMenuButtonRenderer, goog.ui.MenuButtonRenderer);
/**
* The singleton instance of this renderer class.
* @type {goog.ui.ImagelessMenuButtonRenderer?}
* @private
*/
goog.ui.ImagelessMenuButtonRenderer.instance_ = null;
goog.addSingletonGetter(goog.ui.ImagelessMenuButtonRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.ImagelessMenuButtonRenderer.CSS_CLASS =
goog.getCssName('goog-imageless-button');
/** @override */
goog.ui.ImagelessMenuButtonRenderer.prototype.getContentElement = function(
element) {
if (element) {
var captionElem = goog.dom.getElementsByTagNameAndClass(
'*', goog.getCssName(this.getCssClass(), 'caption'), element)[0];
return captionElem;
}
return null;
};
/**
* Returns true if this renderer can decorate the element. Overrides
* {@link goog.ui.MenuButtonRenderer#canDecorate} by returning true if the
* element is a DIV, false otherwise.
* @param {Element} element Element to decorate.
* @return {boolean} Whether the renderer can decorate the element.
* @override
*/
goog.ui.ImagelessMenuButtonRenderer.prototype.canDecorate = function(element) {
return element.tagName == goog.dom.TagName.DIV;
};
/**
* Takes a text caption or existing DOM structure, and returns the content
* wrapped in a pseudo-rounded-corner box. Creates the following DOM structure:
* <div class="goog-inline-block goog-imageless-button">
* <div class="goog-inline-block goog-imageless-button-outer-box">
* <div class="goog-imageless-button-inner-box">
* <div class="goog-imageless-button-pos-box">
* <div class="goog-imageless-button-top-shadow"> </div>
* <div class="goog-imageless-button-content
* goog-imageless-menubutton-caption">Contents...
* </div>
* <div class="goog-imageless-menubutton-dropdown"></div>
* </div>
* </div>
* </div>
* </div>
* Used by both {@link #createDom} and {@link #decorate}. To be overridden
* by subclasses.
* @param {goog.ui.ControlContent} content Text caption or DOM structure to wrap
* in a box.
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Pseudo-rounded-corner box containing the content.
* @override
*/
goog.ui.ImagelessMenuButtonRenderer.prototype.createButton = function(content,
dom) {
var baseClass = this.getCssClass();
var inlineBlock = goog.ui.INLINE_BLOCK_CLASSNAME + ' ';
return dom.createDom('div',
inlineBlock + goog.getCssName(baseClass, 'outer-box'),
dom.createDom('div',
inlineBlock + goog.getCssName(baseClass, 'inner-box'),
dom.createDom('div', goog.getCssName(baseClass, 'pos'),
dom.createDom('div', goog.getCssName(baseClass, 'top-shadow'),
'\u00A0'),
dom.createDom('div', [goog.getCssName(baseClass, 'content'),
goog.getCssName(baseClass, 'caption'),
goog.getCssName('goog-inline-block')],
content),
dom.createDom('div', [goog.getCssName(baseClass, 'dropdown'),
goog.getCssName('goog-inline-block')]))));
};
/**
* Check if the button's element has a box structure.
* @param {goog.ui.Button} button Button instance whose structure is being
* checked.
* @param {Element} element Element of the button.
* @return {boolean} Whether the element has a box structure.
* @protected
* @override
*/
goog.ui.ImagelessMenuButtonRenderer.prototype.hasBoxStructure = function(
button, element) {
var outer = button.getDomHelper().getFirstElementChild(element);
var outerClassName = goog.getCssName(this.getCssClass(), 'outer-box');
if (outer && goog.dom.classes.has(outer, outerClassName)) {
var inner = button.getDomHelper().getFirstElementChild(outer);
var innerClassName = goog.getCssName(this.getCssClass(), 'inner-box');
if (inner && goog.dom.classes.has(inner, innerClassName)) {
var pos = button.getDomHelper().getFirstElementChild(inner);
var posClassName = goog.getCssName(this.getCssClass(), 'pos');
if (pos && goog.dom.classes.has(pos, posClassName)) {
var shadow = button.getDomHelper().getFirstElementChild(pos);
var shadowClassName = goog.getCssName(
this.getCssClass(), 'top-shadow');
if (shadow && goog.dom.classes.has(shadow, shadowClassName)) {
var content = button.getDomHelper().getNextElementSibling(shadow);
var contentClassName = goog.getCssName(
this.getCssClass(), 'content');
if (content && goog.dom.classes.has(content, contentClassName)) {
// We have a proper box structure.
return true;
}
}
}
}
}
return false;
};
/**
* Returns the CSS class to be applied to the root element of components
* rendered using this renderer.
* @return {string} Renderer-specific CSS class.
* @override
*/
goog.ui.ImagelessMenuButtonRenderer.prototype.getCssClass = function() {
return goog.ui.ImagelessMenuButtonRenderer.CSS_CLASS;
};
// Register a decorator factory function for
// goog.ui.ImagelessMenuButtonRenderer. Since we're using goog-imageless-button
// as the base class in order to get the same styling as
// goog.ui.ImagelessButtonRenderer, we need to be explicit about giving
// goog-imageless-menu-button here.
goog.ui.registry.setDecoratorByClassName(
goog.getCssName('goog-imageless-menu-button'),
function() {
return new goog.ui.MenuButton(null, null,
goog.ui.ImagelessMenuButtonRenderer.getInstance());
});
| 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 Detects images dragged and dropped on to the window.
*
* @author robbyw@google.com (Robby Walker)
* @author wcrosby@google.com (Wayne Crosby)
*/
goog.provide('goog.ui.DragDropDetector');
goog.provide('goog.ui.DragDropDetector.EventType');
goog.provide('goog.ui.DragDropDetector.ImageDropEvent');
goog.provide('goog.ui.DragDropDetector.LinkDropEvent');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.events.Event');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.math.Coordinate');
goog.require('goog.string');
goog.require('goog.style');
goog.require('goog.userAgent');
/**
* Creates a new drag and drop detector.
* @param {string=} opt_filePath The URL of the page to use for the detector.
* It should contain the same contents as dragdropdetector_target.html in
* the demos directory.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.ui.DragDropDetector = function(opt_filePath) {
goog.base(this);
var iframe = goog.dom.createDom(goog.dom.TagName.IFRAME, {
'frameborder': 0
});
// In Firefox, we do all drop detection with an IFRAME. In IE, we only use
// the IFRAME to capture copied, non-linked images. (When we don't need it,
// we put a text INPUT before it and push it off screen.)
iframe.className = goog.userAgent.IE ?
goog.getCssName(
goog.ui.DragDropDetector.BASE_CSS_NAME_, 'ie-editable-iframe') :
goog.getCssName(
goog.ui.DragDropDetector.BASE_CSS_NAME_, 'w3c-editable-iframe');
iframe.src = opt_filePath || goog.ui.DragDropDetector.DEFAULT_FILE_PATH_;
this.element_ = /** @type {HTMLIFrameElement} */ (iframe);
this.handler_ = new goog.events.EventHandler(this);
this.handler_.listen(iframe, goog.events.EventType.LOAD, this.initIframe_);
if (goog.userAgent.IE) {
// In IE, we have to bounce between an INPUT for catching links and an
// IFRAME for catching images.
this.textInput_ = goog.dom.createDom(goog.dom.TagName.INPUT, {
'type': 'text',
'className': goog.getCssName(
goog.ui.DragDropDetector.BASE_CSS_NAME_, 'ie-input')
});
this.root_ = goog.dom.createDom(goog.dom.TagName.DIV,
goog.getCssName(goog.ui.DragDropDetector.BASE_CSS_NAME_, 'ie-div'),
this.textInput_, iframe);
} else {
this.root_ = iframe;
}
document.body.appendChild(this.root_);
};
goog.inherits(goog.ui.DragDropDetector, goog.events.EventTarget);
/**
* Drag and drop event types.
* @enum {string}
*/
goog.ui.DragDropDetector.EventType = {
IMAGE_DROPPED: 'onimagedrop',
LINK_DROPPED: 'onlinkdrop'
};
/**
* Browser specific drop event type.
* @type {string}
* @private
*/
goog.ui.DragDropDetector.DROP_EVENT_TYPE_ = goog.userAgent.IE ?
goog.events.EventType.DROP : 'dragdrop';
/**
* Initial value for clientX and clientY indicating that the location has
* never been updated.
*/
goog.ui.DragDropDetector.INIT_POSITION = -10000;
/**
* Prefix for all CSS names.
* @type {string}
* @private
*/
goog.ui.DragDropDetector.BASE_CSS_NAME_ = goog.getCssName('goog-dragdrop');
/**
* @desc Message shown to users to inform them that they can't drag and drop
* local files.
*/
var MSG_DRAG_DROP_LOCAL_FILE_ERROR = goog.getMsg('It is not possible to drag ' +
'and drop image files at this time.\nPlease drag an image from your web ' +
'browser.');
/**
* @desc Message shown to users trying to drag and drop protected images from
* Flickr, etc.
*/
var MSG_DRAG_DROP_PROTECTED_FILE_ERROR = goog.getMsg('The image you are ' +
'trying to drag has been blocked by the hosting site.');
/**
* A map of special case information for URLs that cannot be dropped. Each
* entry is of the form:
* regex: url regex
* message: user visible message about this special case
* @type {Array.<{regex: RegExp, message: string}>}
* @private
*/
goog.ui.DragDropDetector.SPECIAL_CASE_URLS_ = [
{
regex: /^file:\/\/\//,
message: MSG_DRAG_DROP_LOCAL_FILE_ERROR
},
{
regex: /flickr(.*)spaceball.gif$/,
message: MSG_DRAG_DROP_PROTECTED_FILE_ERROR
}
];
/**
* Regex that matches anything that looks kind of like a URL. It matches
* nonspacechars://nonspacechars
* @type {RegExp}
* @private
*/
goog.ui.DragDropDetector.URL_LIKE_REGEX_ = /^\S+:\/\/\S*$/;
/**
* Path to the dragdrop.html file.
* @type {string}
* @private
*/
goog.ui.DragDropDetector.DEFAULT_FILE_PATH_ = 'dragdropdetector_target.html';
/**
* Our event handler object.
* @type {goog.events.EventHandler}
* @private
*/
goog.ui.DragDropDetector.prototype.handler_;
/**
* The root element (the IFRAME on most browsers, the DIV on IE).
* @type {Element}
* @private
*/
goog.ui.DragDropDetector.prototype.root_;
/**
* The text INPUT element used to detect link drops on IE. null on Firefox.
* @type {Element}
* @private
*/
goog.ui.DragDropDetector.prototype.textInput_;
/**
* The iframe element.
* @type {HTMLIFrameElement}
* @private
*/
goog.ui.DragDropDetector.prototype.element_;
/**
* The iframe's window, null if the iframe hasn't loaded yet.
* @type {Window}
* @private
*/
goog.ui.DragDropDetector.prototype.window_ = null;
/**
* The iframe's document, null if the iframe hasn't loaded yet.
* @type {HTMLDocument}
* @private
*/
goog.ui.DragDropDetector.prototype.document_ = null;
/**
* The iframe's body, null if the iframe hasn't loaded yet.
* @type {HTMLBodyElement}
* @private
*/
goog.ui.DragDropDetector.prototype.body_ = null;
/**
* Whether we are in "screen cover" mode in which the iframe or div is
* covering the entire screen.
* @type {boolean}
* @private
*/
goog.ui.DragDropDetector.prototype.isCoveringScreen_ = false;
/**
* The last position of the mouse while dragging.
* @type {goog.math.Coordinate}
* @private
*/
goog.ui.DragDropDetector.prototype.mousePosition_ = null;
/**
* Initialize the iframe after it has loaded.
* @private
*/
goog.ui.DragDropDetector.prototype.initIframe_ = function() {
// Set up a holder for position data.
this.mousePosition_ = new goog.math.Coordinate(
goog.ui.DragDropDetector.INIT_POSITION,
goog.ui.DragDropDetector.INIT_POSITION);
// Set up pointers to the important parts of the IFrame.
this.window_ = this.element_.contentWindow;
this.document_ = this.window_.document;
this.body_ = this.document_.body;
if (goog.userAgent.GECKO) {
this.document_.designMode = 'on';
} else if (!goog.userAgent.IE) {
// Bug 1667110
// In IE, we only set the IFrame body as content-editable when we bring it
// into view at the top of the page. Otherwise it may take focus when the
// page is loaded, scrolling the user far offscreen.
// Note that this isn't easily unit-testable, since it depends on a
// browser-specific behavior with content-editable areas.
this.body_.contentEditable = true;
}
this.handler_.listen(document.body, goog.events.EventType.DRAGENTER,
this.coverScreen_);
if (goog.userAgent.IE) {
// IE only events.
// Set up events on the IFrame.
this.handler_.
listen(this.body_,
[goog.events.EventType.DRAGENTER, goog.events.EventType.DRAGOVER],
goog.ui.DragDropDetector.enforceCopyEffect_).
listen(this.body_, goog.events.EventType.MOUSEOUT,
this.switchToInput_).
listen(this.body_, goog.events.EventType.DRAGLEAVE,
this.uncoverScreen_).
listen(this.body_, goog.ui.DragDropDetector.DROP_EVENT_TYPE_,
function(e) {
this.trackMouse_(e);
// The drop event occurs before the content is added to the
// iframe. We setTimeout so that handleNodeInserted_ is called
// after the content is in the document.
goog.global.setTimeout(
goog.bind(this.handleNodeInserted_, this, e), 0);
return true;
}).
// Set up events on the DIV.
listen(this.root_,
[goog.events.EventType.DRAGENTER, goog.events.EventType.DRAGOVER],
this.handleNewDrag_).
listen(this.root_,
[
goog.events.EventType.MOUSEMOVE,
goog.events.EventType.KEYPRESS
], this.uncoverScreen_).
// Set up events on the text INPUT.
listen(this.textInput_, goog.events.EventType.DRAGOVER,
goog.events.Event.preventDefault).
listen(this.textInput_, goog.ui.DragDropDetector.DROP_EVENT_TYPE_,
this.handleInputDrop_);
} else {
// W3C events.
this.handler_.
listen(this.body_, goog.ui.DragDropDetector.DROP_EVENT_TYPE_,
function(e) {
this.trackMouse_(e);
this.uncoverScreen_();
}).
listen(this.body_,
[goog.events.EventType.MOUSEMOVE, goog.events.EventType.KEYPRESS],
this.uncoverScreen_).
// Detect content insertion.
listen(this.document_, 'DOMNodeInserted',
this.handleNodeInserted_);
}
};
/**
* Enforce that anything dragged over the IFRAME is copied in to it, rather
* than making it navigate to a different URL.
* @param {goog.events.BrowserEvent} e The event to enforce copying on.
* @private
*/
goog.ui.DragDropDetector.enforceCopyEffect_ = function(e) {
var event = e.getBrowserEvent();
// This function is only called on IE.
if (event.dataTransfer.dropEffect.toLowerCase() != 'copy') {
event.dataTransfer.dropEffect = 'copy';
}
};
/**
* Cover the screen with the iframe.
* @param {goog.events.BrowserEvent} e The event that caused this function call.
* @private
*/
goog.ui.DragDropDetector.prototype.coverScreen_ = function(e) {
// Don't do anything if the drop effect is 'none' and we are in IE.
// It is set to 'none' in cases like dragging text inside a text area.
if (goog.userAgent.IE &&
e.getBrowserEvent().dataTransfer.dropEffect == 'none') {
return;
}
if (!this.isCoveringScreen_) {
this.isCoveringScreen_ = true;
if (goog.userAgent.IE) {
goog.style.setStyle(this.root_, 'top', '0');
this.body_.contentEditable = true;
this.switchToInput_(e);
} else {
goog.style.setStyle(this.root_, 'height', '5000px');
}
}
};
/**
* Uncover the screen.
* @private
*/
goog.ui.DragDropDetector.prototype.uncoverScreen_ = function() {
if (this.isCoveringScreen_) {
this.isCoveringScreen_ = false;
if (goog.userAgent.IE) {
this.body_.contentEditable = false;
goog.style.setStyle(this.root_, 'top', '-5000px');
} else {
goog.style.setStyle(this.root_, 'height', '10px');
}
}
};
/**
* Re-insert the INPUT into the DIV. Does nothing when the DIV is off screen.
* @param {goog.events.BrowserEvent} e The event that caused this function call.
* @private
*/
goog.ui.DragDropDetector.prototype.switchToInput_ = function(e) {
// This is only called on IE.
if (this.isCoveringScreen_) {
goog.style.setElementShown(this.textInput_, true);
}
};
/**
* Remove the text INPUT so the IFRAME is showing. Does nothing when the DIV is
* off screen.
* @param {goog.events.BrowserEvent} e The event that caused this function call.
* @private
*/
goog.ui.DragDropDetector.prototype.switchToIframe_ = function(e) {
// This is only called on IE.
if (this.isCoveringScreen_) {
goog.style.setElementShown(this.textInput_, false);
this.isShowingInput_ = false;
}
};
/**
* Handle a new drag event.
* @param {goog.events.BrowserEvent} e The event object.
* @return {boolean|undefined} Returns false in IE to cancel the event.
* @private
*/
goog.ui.DragDropDetector.prototype.handleNewDrag_ = function(e) {
var event = e.getBrowserEvent();
// This is only called on IE.
if (event.dataTransfer.dropEffect == 'link') {
this.switchToInput_(e);
e.preventDefault();
return false;
}
// Things that aren't links can be placed in the contentEditable iframe.
this.switchToIframe_(e);
// No need to return true since for events return true is the same as no
// return.
};
/**
* Handle mouse tracking.
* @param {goog.events.BrowserEvent} e The event object.
* @private
*/
goog.ui.DragDropDetector.prototype.trackMouse_ = function(e) {
this.mousePosition_.x = e.clientX;
this.mousePosition_.y = e.clientY;
// Check if the event is coming from within the iframe.
if (goog.dom.getOwnerDocument(/** @type {Node} */ (e.target)) != document) {
var iframePosition = goog.style.getClientPosition(this.element_);
this.mousePosition_.x += iframePosition.x;
this.mousePosition_.y += iframePosition.y;
}
};
/**
* Handle a drop on the IE text INPUT.
* @param {goog.events.BrowserEvent} e The event object.
* @private
*/
goog.ui.DragDropDetector.prototype.handleInputDrop_ = function(e) {
this.dispatchEvent(
new goog.ui.DragDropDetector.LinkDropEvent(
e.getBrowserEvent().dataTransfer.getData('Text')));
this.uncoverScreen_();
e.preventDefault();
};
/**
* Clear the contents of the iframe.
* @private
*/
goog.ui.DragDropDetector.prototype.clearContents_ = function() {
if (goog.userAgent.WEBKIT) {
// Since this is called on a mutation event for the nodes we are going to
// clear, calling this right away crashes some versions of WebKit. Wait
// until the events are finished.
goog.global.setTimeout(goog.bind(function() {
this.innerHTML = '';
}, this.body_), 0);
} else {
this.document_.execCommand('selectAll', false, null);
this.document_.execCommand('delete', false, null);
this.document_.execCommand('selectAll', false, null);
}
};
/**
* Event handler called when the content of the iframe changes.
* @param {goog.events.BrowserEvent} e The event that caused this function call.
* @private
*/
goog.ui.DragDropDetector.prototype.handleNodeInserted_ = function(e) {
var uri;
if (this.body_.innerHTML.indexOf('<') == -1) {
// If the document contains no tags (i.e. is just text), try it out.
uri = goog.string.trim(goog.dom.getTextContent(this.body_));
// See if it looks kind of like a url.
if (!uri.match(goog.ui.DragDropDetector.URL_LIKE_REGEX_)) {
uri = null;
}
}
if (!uri) {
var imgs = this.body_.getElementsByTagName(goog.dom.TagName.IMG);
if (imgs && imgs.length) {
// TODO(robbyw): Grab all the images, instead of just the first.
var img = imgs[0];
uri = img.src;
}
}
if (uri) {
var specialCases = goog.ui.DragDropDetector.SPECIAL_CASE_URLS_;
var len = specialCases.length;
for (var i = 0; i < len; i++) {
var specialCase = specialCases[i];
if (uri.match(specialCase.regex)) {
alert(specialCase.message);
break;
}
}
// If no special cases matched, add the image.
if (i == len) {
this.dispatchEvent(
new goog.ui.DragDropDetector.ImageDropEvent(
uri, this.mousePosition_));
return;
}
}
var links = this.body_.getElementsByTagName(goog.dom.TagName.A);
if (links) {
for (i = 0, len = links.length; i < len; i++) {
this.dispatchEvent(
new goog.ui.DragDropDetector.LinkDropEvent(links[i].href));
}
}
this.clearContents_();
this.uncoverScreen_();
};
/** @override */
goog.ui.DragDropDetector.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
this.handler_.dispose();
this.handler_ = null;
};
/**
* Creates a new image drop event object.
* @param {string} url The url of the dropped image.
* @param {goog.math.Coordinate} position The screen position where the drop
* occurred.
* @constructor
* @extends {goog.events.Event}
*/
goog.ui.DragDropDetector.ImageDropEvent = function(url, position) {
goog.base(this, goog.ui.DragDropDetector.EventType.IMAGE_DROPPED);
/**
* The url of the image that was dropped.
* @type {string}
* @private
*/
this.url_ = url;
/**
* The screen position where the drop occurred.
* @type {goog.math.Coordinate}
* @private
*/
this.position_ = position;
};
goog.inherits(goog.ui.DragDropDetector.ImageDropEvent,
goog.events.Event);
/**
* @return {string} The url of the image that was dropped.
*/
goog.ui.DragDropDetector.ImageDropEvent.prototype.getUrl = function() {
return this.url_;
};
/**
* @return {goog.math.Coordinate} The screen position where the drop occurred.
* This may be have x and y of goog.ui.DragDropDetector.INIT_POSITION,
* indicating the drop position is unknown.
*/
goog.ui.DragDropDetector.ImageDropEvent.prototype.getPosition = function() {
return this.position_;
};
/**
* Creates a new link drop event object.
* @param {string} url The url of the dropped link.
* @constructor
* @extends {goog.events.Event}
*/
goog.ui.DragDropDetector.LinkDropEvent = function(url) {
goog.base(this, goog.ui.DragDropDetector.EventType.LINK_DROPPED);
/**
* The url of the link that was dropped.
* @type {string}
* @private
*/
this.url_ = url;
};
goog.inherits(goog.ui.DragDropDetector.LinkDropEvent,
goog.events.Event);
/**
* @return {string} The url of the link that was dropped.
*/
goog.ui.DragDropDetector.LinkDropEvent.prototype.getUrl = function() {
return this.url_;
};
| 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 Renderer for {@link goog.ui.style.app.MenuButton}s and
* subclasses.
*
* @author attila@google.com (Attila Bodis)
* @author gveen@google.com (Greg Veen)
*/
goog.provide('goog.ui.style.app.MenuButtonRenderer');
goog.require('goog.a11y.aria.Role');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.style');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.Menu');
goog.require('goog.ui.MenuRenderer');
goog.require('goog.ui.style.app.ButtonRenderer');
/**
* Renderer for {@link goog.ui.style.app.MenuButton}s. This implementation
* overrides {@link goog.ui.style.app.ButtonRenderer#createButton} to insert a
* dropdown element into the content element after the specified content.
* @constructor
* @extends {goog.ui.style.app.ButtonRenderer}
*/
goog.ui.style.app.MenuButtonRenderer = function() {
goog.ui.style.app.ButtonRenderer.call(this);
};
goog.inherits(goog.ui.style.app.MenuButtonRenderer,
goog.ui.style.app.ButtonRenderer);
goog.addSingletonGetter(goog.ui.style.app.MenuButtonRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.style.app.MenuButtonRenderer.CSS_CLASS =
goog.getCssName('goog-menu-button');
/**
* Array of arrays of CSS classes that we want composite classes added and
* removed for in IE6 and lower as a workaround for lack of multi-class CSS
* selector support.
* @type {Array.<Array.<string>>}
*/
goog.ui.style.app.MenuButtonRenderer.IE6_CLASS_COMBINATIONS = [
[goog.getCssName('goog-button-base-rtl'),
goog.getCssName('goog-menu-button')],
[goog.getCssName('goog-button-base-hover'),
goog.getCssName('goog-menu-button')],
[goog.getCssName('goog-button-base-focused'),
goog.getCssName('goog-menu-button')],
[goog.getCssName('goog-button-base-disabled'),
goog.getCssName('goog-menu-button')],
[goog.getCssName('goog-button-base-active'),
goog.getCssName('goog-menu-button')],
[goog.getCssName('goog-button-base-open'),
goog.getCssName('goog-menu-button')],
[goog.getCssName('goog-button-base-active'),
goog.getCssName('goog-button-base-open'),
goog.getCssName('goog-menu-button')]
];
/**
* Returns the ARIA role to be applied to menu buttons, which
* have a menu attached to them.
* @return {goog.a11y.aria.Role} ARIA role.
* @override
*/
goog.ui.style.app.MenuButtonRenderer.prototype.getAriaRole = function() {
// If we apply the 'button' ARIA role to the menu button, the
// screen reader keeps referring to menus as buttons, which
// might be misleading for the users. Hence the ARIA role
// 'menu' is assigned.
return goog.a11y.aria.Role.MENU;
};
/**
* Takes the button's root element and returns the parent element of the
* button's contents. Overrides the superclass implementation by taking
* the nested DIV structure of menu buttons into account.
* @param {Element} element Root element of the button whose content element
* is to be returned.
* @return {Element} The button's content element.
* @override
*/
goog.ui.style.app.MenuButtonRenderer.prototype.getContentElement =
function(element) {
return goog.ui.style.app.MenuButtonRenderer.superClass_.getContentElement
.call(this, element);
};
/**
* Takes an element, decorates it with the menu button control, and returns
* the element. Overrides {@link goog.ui.style.app.ButtonRenderer#decorate} by
* looking for a child element that can be decorated by a menu, and if it
* finds one, decorates it and attaches it to the menu button.
* @param {goog.ui.Control} control goog.ui.MenuButton to decorate the element.
* @param {Element} element Element to decorate.
* @return {Element} Decorated element.
* @override
*/
goog.ui.style.app.MenuButtonRenderer.prototype.decorate =
function(control, element) {
var button = /** @type {goog.ui.MenuButton} */ (control);
// TODO(attila): Add more robust support for subclasses of goog.ui.Menu.
var menuElem = goog.dom.getElementsByTagNameAndClass(
'*', goog.ui.MenuRenderer.CSS_CLASS, element)[0];
if (menuElem) {
// Move the menu element directly under the body (but hide it first to
// prevent flicker; see bug 1089244).
goog.style.setElementShown(menuElem, false);
goog.dom.appendChild(goog.dom.getOwnerDocument(menuElem).body, menuElem);
// Decorate the menu and attach it to the button.
var menu = new goog.ui.Menu();
menu.decorate(menuElem);
button.setMenu(menu);
}
// Let the superclass do the rest.
return goog.ui.style.app.MenuButtonRenderer.superClass_.decorate.call(this,
button, element);
};
/**
* Takes a text caption or existing DOM structure, and returns the content and
* a dropdown arrow element wrapped in a pseudo-rounded-corner box. Creates
* the following DOM structure:
* <div class="goog-inline-block goog-button-outer-box">
* <div class="goog-inline-block goog-button-inner-box">
* <div class="goog-button-pos">
* <div class="goog-button-top-shadow"> </div>
* <div class="goog-button-content">
* Contents...
* <div class="goog-menu-button-dropdown"> </div>
* </div>
* </div>
* </div>
* </div>
* @param {goog.ui.ControlContent} content Text caption or DOM structure to wrap
* in a box.
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Pseudo-rounded-corner box containing the content.
* @override
*/
goog.ui.style.app.MenuButtonRenderer.prototype.createButton = function(content,
dom) {
var contentWithDropdown = this.createContentWithDropdown(content, dom);
return goog.ui.style.app.MenuButtonRenderer.superClass_.createButton.call(
this, contentWithDropdown, dom);
};
/** @override */
goog.ui.style.app.MenuButtonRenderer.prototype.setContent = function(element,
content) {
var dom = goog.dom.getDomHelper(this.getContentElement(element));
goog.ui.style.app.MenuButtonRenderer.superClass_.setContent.call(
this, element, this.createContentWithDropdown(content, dom));
};
/**
* Inserts dropdown element as last child of existing content.
* @param {goog.ui.ControlContent} content Text caption or DOM structure.
* @param {goog.dom.DomHelper} dom DOM helper, used for document ineraction.
* @return {Array.<Node>} DOM structure to be set as the button's content.
*/
goog.ui.style.app.MenuButtonRenderer.prototype.createContentWithDropdown =
function(content, dom) {
var caption = dom.createDom('div', null, content, this.createDropdown(dom));
return goog.array.toArray(caption.childNodes);
};
/**
* Returns an appropriately-styled DIV containing a dropdown arrow.
* Creates the following DOM structure:
* <div class="goog-menu-button-dropdown"> </div>
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Dropdown element.
*/
goog.ui.style.app.MenuButtonRenderer.prototype.createDropdown = function(dom) {
return dom.createDom('div', goog.getCssName(this.getCssClass(), 'dropdown'));
};
/**
* Returns the CSS class to be applied to the root element of components
* rendered using this renderer.
* @return {string} Renderer-specific CSS class.
* @override
*/
goog.ui.style.app.MenuButtonRenderer.prototype.getCssClass = function() {
return goog.ui.style.app.MenuButtonRenderer.CSS_CLASS;
};
/** @override */
goog.ui.style.app.MenuButtonRenderer.prototype.getIe6ClassCombinations =
function() {
return goog.ui.style.app.MenuButtonRenderer.IE6_CLASS_COMBINATIONS;
};
| 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 Renderer for {@link goog.ui.Button}s in App style. This
* type of button is typically used for an application's "primary action," eg
* in Gmail, it's "Compose," in Calendar, it's "Create Event".
*
*/
goog.provide('goog.ui.style.app.PrimaryActionButtonRenderer');
goog.require('goog.ui.Button');
goog.require('goog.ui.registry');
goog.require('goog.ui.style.app.ButtonRenderer');
/**
* Custom renderer for {@link goog.ui.Button}s. This renderer supports the
* "primary action" style for buttons.
*
* @constructor
* @extends {goog.ui.style.app.ButtonRenderer}
*/
goog.ui.style.app.PrimaryActionButtonRenderer = function() {
goog.ui.style.app.ButtonRenderer.call(this);
};
goog.inherits(goog.ui.style.app.PrimaryActionButtonRenderer,
goog.ui.style.app.ButtonRenderer);
goog.addSingletonGetter(goog.ui.style.app.PrimaryActionButtonRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.style.app.PrimaryActionButtonRenderer.CSS_CLASS =
'goog-primaryactionbutton';
/**
* Array of arrays of CSS classes that we want composite classes added and
* removed for in IE6 and lower as a workaround for lack of multi-class CSS
* selector support.
* @type {Array.<Array.<string>>}
*/
goog.ui.style.app.PrimaryActionButtonRenderer.IE6_CLASS_COMBINATIONS = [
['goog-button-base-disabled', 'goog-primaryactionbutton'],
['goog-button-base-focused', 'goog-primaryactionbutton'],
['goog-button-base-hover', 'goog-primaryactionbutton']
];
/** @override */
goog.ui.style.app.PrimaryActionButtonRenderer.prototype.getCssClass =
function() {
return goog.ui.style.app.PrimaryActionButtonRenderer.CSS_CLASS;
};
/** @override */
goog.ui.style.app.PrimaryActionButtonRenderer.prototype.
getIe6ClassCombinations = function() {
return goog.ui.style.app.PrimaryActionButtonRenderer.IE6_CLASS_COMBINATIONS;
};
// Register a decorator factory function for
// goog.ui.style.app.PrimaryActionButtonRenderer.
goog.ui.registry.setDecoratorByClassName(
goog.ui.style.app.PrimaryActionButtonRenderer.CSS_CLASS,
function() {
return new goog.ui.Button(null,
goog.ui.style.app.PrimaryActionButtonRenderer.getInstance());
});
| 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 Renderer for {@link goog.ui.Button}s in App style.
*
* Based on ImagelessButtonRender. Uses even more CSS voodoo than the default
* implementation to render custom buttons with fake rounded corners and
* dimensionality (via a subtle flat shadow on the bottom half of the button)
* without the use of images.
*
* Based on the Custom Buttons 3.1 visual specification, see
* http://go/custombuttons
*
* @author eae@google.com (Emil A Eklund)
*/
goog.provide('goog.ui.style.app.ButtonRenderer');
goog.require('goog.dom.classes');
goog.require('goog.ui.Button');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.CustomButtonRenderer');
goog.require('goog.ui.INLINE_BLOCK_CLASSNAME');
goog.require('goog.ui.registry');
/**
* Custom renderer for {@link goog.ui.Button}s. Imageless buttons can contain
* almost arbitrary HTML content, will flow like inline elements, but can be
* styled like block-level elements.
*
* @constructor
* @extends {goog.ui.CustomButtonRenderer}
*/
goog.ui.style.app.ButtonRenderer = function() {
goog.ui.CustomButtonRenderer.call(this);
};
goog.inherits(goog.ui.style.app.ButtonRenderer, goog.ui.CustomButtonRenderer);
goog.addSingletonGetter(goog.ui.style.app.ButtonRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.style.app.ButtonRenderer.CSS_CLASS = goog.getCssName('goog-button');
/**
* Array of arrays of CSS classes that we want composite classes added and
* removed for in IE6 and lower as a workaround for lack of multi-class CSS
* selector support.
* @type {Array.<Array.<string>>}
*/
goog.ui.style.app.ButtonRenderer.IE6_CLASS_COMBINATIONS = [];
/**
* Returns the button's contents wrapped in the following DOM structure:
* <div class="goog-inline-block goog-button-base goog-button">
* <div class="goog-inline-block goog-button-base-outer-box">
* <div class="goog-button-base-inner-box">
* <div class="goog-button-base-pos">
* <div class="goog-button-base-top-shadow"> </div>
* <div class="goog-button-base-content">Contents...</div>
* </div>
* </div>
* </div>
* </div>
* @override
*/
goog.ui.style.app.ButtonRenderer.prototype.createDom;
/** @override */
goog.ui.style.app.ButtonRenderer.prototype.getContentElement = function(
element) {
return element && /** @type {Element} */(
element.firstChild.firstChild.firstChild.lastChild);
};
/**
* Takes a text caption or existing DOM structure, and returns the content
* wrapped in a pseudo-rounded-corner box. Creates the following DOM structure:
* <div class="goog-inline-block goog-button-base-outer-box">
* <div class="goog-inline-block goog-button-base-inner-box">
* <div class="goog-button-base-pos">
* <div class="goog-button-base-top-shadow"> </div>
* <div class="goog-button-base-content">Contents...</div>
* </div>
* </div>
* </div>
* Used by both {@link #createDom} and {@link #decorate}. To be overridden
* by subclasses.
* @param {goog.ui.ControlContent} content Text caption or DOM structure to wrap
* in a box.
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Pseudo-rounded-corner box containing the content.
* @override
*/
goog.ui.style.app.ButtonRenderer.prototype.createButton = function(content,
dom) {
var baseClass = this.getStructuralCssClass();
var inlineBlock = goog.ui.INLINE_BLOCK_CLASSNAME + ' ';
return dom.createDom(
'div', inlineBlock + goog.getCssName(baseClass, 'outer-box'),
dom.createDom(
'div', inlineBlock + goog.getCssName(baseClass, 'inner-box'),
dom.createDom('div', goog.getCssName(baseClass, 'pos'),
dom.createDom(
'div', goog.getCssName(baseClass, 'top-shadow'), '\u00A0'),
dom.createDom(
'div', goog.getCssName(baseClass, 'content'), content))));
};
/**
* Check if the button's element has a box structure.
* @param {goog.ui.Button} button Button instance whose structure is being
* checked.
* @param {Element} element Element of the button.
* @return {boolean} Whether the element has a box structure.
* @protected
* @override
*/
goog.ui.style.app.ButtonRenderer.prototype.hasBoxStructure = function(
button, element) {
var baseClass = this.getStructuralCssClass();
var outer = button.getDomHelper().getFirstElementChild(element);
var outerClassName = goog.getCssName(baseClass, 'outer-box');
if (outer && goog.dom.classes.has(outer, outerClassName)) {
var inner = button.getDomHelper().getFirstElementChild(outer);
var innerClassName = goog.getCssName(baseClass, 'inner-box');
if (inner && goog.dom.classes.has(inner, innerClassName)) {
var pos = button.getDomHelper().getFirstElementChild(inner);
var posClassName = goog.getCssName(baseClass, 'pos');
if (pos && goog.dom.classes.has(pos, posClassName)) {
var shadow = button.getDomHelper().getFirstElementChild(pos);
var shadowClassName = goog.getCssName(baseClass, 'top-shadow');
if (shadow && goog.dom.classes.has(shadow, shadowClassName)) {
var content = button.getDomHelper().getNextElementSibling(shadow);
var contentClassName = goog.getCssName(baseClass, 'content');
if (content && goog.dom.classes.has(content, contentClassName)) {
// We have a proper box structure.
return true;
}
}
}
}
}
return false;
};
/** @override */
goog.ui.style.app.ButtonRenderer.prototype.getCssClass = function() {
return goog.ui.style.app.ButtonRenderer.CSS_CLASS;
};
/** @override */
goog.ui.style.app.ButtonRenderer.prototype.getStructuralCssClass = function() {
// TODO(user): extract to a constant.
return goog.getCssName('goog-button-base');
};
/** @override */
goog.ui.style.app.ButtonRenderer.prototype.getIe6ClassCombinations =
function() {
return goog.ui.style.app.ButtonRenderer.IE6_CLASS_COMBINATIONS;
};
// Register a decorator factory function for goog.ui.style.app.ButtonRenderer.
goog.ui.registry.setDecoratorByClassName(
goog.ui.style.app.ButtonRenderer.CSS_CLASS,
function() {
return new goog.ui.Button(null,
goog.ui.style.app.ButtonRenderer.getInstance());
});
| 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 Native browser button renderer for {@link goog.ui.Button}s.
*
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.ui.NativeButtonRenderer');
goog.require('goog.dom.classes');
goog.require('goog.events.EventType');
goog.require('goog.ui.ButtonRenderer');
goog.require('goog.ui.Component.State');
/**
* Renderer for {@link goog.ui.Button}s. Renders and decorates native HTML
* button elements. Since native HTML buttons have built-in support for many
* features, overrides many expensive (and redundant) superclass methods to
* be no-ops.
* @constructor
* @extends {goog.ui.ButtonRenderer}
*/
goog.ui.NativeButtonRenderer = function() {
goog.ui.ButtonRenderer.call(this);
};
goog.inherits(goog.ui.NativeButtonRenderer, goog.ui.ButtonRenderer);
goog.addSingletonGetter(goog.ui.NativeButtonRenderer);
/** @override */
goog.ui.NativeButtonRenderer.prototype.getAriaRole = function() {
// Native buttons don't need ARIA roles to be recognized by screen readers.
return undefined;
};
/**
* Returns the button's contents wrapped in a native HTML button element. Sets
* the button's disabled attribute as needed.
* @param {goog.ui.Control} button Button to render.
* @return {Element} Root element for the button (a native HTML button element).
* @override
*/
goog.ui.NativeButtonRenderer.prototype.createDom = function(button) {
this.setUpNativeButton_(button);
return button.getDomHelper().createDom('button', {
'class': this.getClassNames(button).join(' '),
'disabled': !button.isEnabled(),
'title': button.getTooltip() || '',
'value': button.getValue() || ''
}, button.getCaption() || '');
};
/**
* Overrides {@link goog.ui.ButtonRenderer#canDecorate} by returning true only
* if the element is an HTML button.
* @param {Element} element Element to decorate.
* @return {boolean} Whether the renderer can decorate the element.
* @override
*/
goog.ui.NativeButtonRenderer.prototype.canDecorate = function(element) {
return element.tagName == 'BUTTON' ||
(element.tagName == 'INPUT' && (element.type == 'button' ||
element.type == 'submit' || element.type == 'reset'));
};
/** @override */
goog.ui.NativeButtonRenderer.prototype.decorate = function(button, element) {
this.setUpNativeButton_(button);
if (element.disabled) {
// Add the marker class for the DISABLED state before letting the superclass
// implementation decorate the element, so its state will be correct.
goog.dom.classes.add(element,
this.getClassForState(goog.ui.Component.State.DISABLED));
}
return goog.ui.NativeButtonRenderer.superClass_.decorate.call(this, button,
element);
};
/**
* Native buttons natively support BiDi and keyboard focus.
* @suppress {visibility} getHandler and performActionInternal
* @override
*/
goog.ui.NativeButtonRenderer.prototype.initializeDom = function(button) {
// WARNING: This is a hack, and it is only applicable to native buttons,
// which are special because they do natively what most goog.ui.Controls
// do programmatically. Do not use your renderer's initializeDom method
// to hook up event handlers!
button.getHandler().listen(button.getElement(), goog.events.EventType.CLICK,
button.performActionInternal);
};
/**
* @override
* Native buttons don't support text selection.
*/
goog.ui.NativeButtonRenderer.prototype.setAllowTextSelection =
goog.nullFunction;
/**
* @override
* Native buttons natively support right-to-left rendering.
*/
goog.ui.NativeButtonRenderer.prototype.setRightToLeft = goog.nullFunction;
/**
* @override
* Native buttons are always focusable as long as they are enabled.
*/
goog.ui.NativeButtonRenderer.prototype.isFocusable = function(button) {
return button.isEnabled();
};
/**
* @override
* Native buttons natively support keyboard focus.
*/
goog.ui.NativeButtonRenderer.prototype.setFocusable = goog.nullFunction;
/**
* @override
* Native buttons also expose the DISABLED state in the HTML button's
* {@code disabled} attribute.
*/
goog.ui.NativeButtonRenderer.prototype.setState = function(button, state,
enable) {
goog.ui.NativeButtonRenderer.superClass_.setState.call(this, button, state,
enable);
var element = button.getElement();
if (element && state == goog.ui.Component.State.DISABLED) {
element.disabled = enable;
}
};
/**
* @override
* Native buttons store their value in the HTML button's {@code value}
* attribute.
*/
goog.ui.NativeButtonRenderer.prototype.getValue = function(element) {
// TODO(attila): Make this work on IE! This never worked...
// See http://www.fourmilab.ch/fourmilog/archives/2007-03/000824.html
// for a description of the problem.
return element.value;
};
/**
* @override
* Native buttons also expose their value in the HTML button's {@code value}
* attribute.
*/
goog.ui.NativeButtonRenderer.prototype.setValue = function(element, value) {
if (element) {
// TODO(attila): Make this work on IE! This never worked...
// See http://www.fourmilab.ch/fourmilog/archives/2007-03/000824.html
// for a description of the problem.
element.value = value;
}
};
/**
* @override
* Native buttons don't need ARIA states to support accessibility, so this is
* a no-op.
*/
goog.ui.NativeButtonRenderer.prototype.updateAriaState = goog.nullFunction;
/**
* Sets up the button control such that it doesn't waste time adding
* functionality that is already natively supported by native browser
* buttons.
* @param {goog.ui.Control} button Button control to configure.
* @private
*/
goog.ui.NativeButtonRenderer.prototype.setUpNativeButton_ = function(button) {
button.setHandleMouseEvents(false);
button.setAutoStates(goog.ui.Component.State.ALL, false);
button.setSupportedState(goog.ui.Component.State.FOCUSED, 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 A table sorting decorator.
*
* @author robbyw@google.com (Robby Walker)
* @see ../demos/tablesorter.html
*/
goog.provide('goog.ui.TableSorter');
goog.provide('goog.ui.TableSorter.EventType');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.classes');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.functions');
goog.require('goog.ui.Component');
/**
* A table sorter allows for sorting of a table by column. This component can
* be used to decorate an already existing TABLE element with sorting
* features.
*
* The TABLE should use a THEAD containing TH elements for the table column
* headers.
*
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
* document interaction.
* @constructor
* @extends {goog.ui.Component}
*/
goog.ui.TableSorter = function(opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
/**
* The current sort column of the table, or -1 if none.
* @type {number}
* @private
*/
this.column_ = -1;
/**
* Whether the last sort was in reverse.
* @type {boolean}
* @private
*/
this.reversed_ = false;
/**
* The default sorting function.
* @type {function(*, *) : number}
* @private
*/
this.defaultSortFunction_ = goog.ui.TableSorter.numericSort;
/**
* Array of custom sorting functions per colun.
* @type {Array.<function(*, *) : number>}
* @private
*/
this.sortFunctions_ = [];
};
goog.inherits(goog.ui.TableSorter, goog.ui.Component);
/**
* Row number (in <thead>) to use for sorting.
* @type {number}
* @private
*/
goog.ui.TableSorter.prototype.sortableHeaderRowIndex_ = 0;
/**
* Sets the row index (in <thead>) to be used for sorting.
* By default, the first row (index 0) is used.
* Must be called before decorate() is called.
* @param {number} index The row index.
*/
goog.ui.TableSorter.prototype.setSortableHeaderRowIndex = function(index) {
if (this.isInDocument()) {
throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
}
this.sortableHeaderRowIndex_ = index;
};
/**
* Table sorter events.
* @enum {string}
*/
goog.ui.TableSorter.EventType = {
BEFORESORT: 'beforesort',
SORT: 'sort'
};
/** @override */
goog.ui.TableSorter.prototype.canDecorate = function(element) {
return element.tagName == goog.dom.TagName.TABLE;
};
/** @override */
goog.ui.TableSorter.prototype.enterDocument = function() {
goog.ui.TableSorter.superClass_.enterDocument.call(this);
var table = this.getElement();
var headerRow = table.tHead.rows[this.sortableHeaderRowIndex_];
this.getHandler().listen(headerRow, goog.events.EventType.CLICK, this.sort_);
};
/**
* @return {number} The current sort column of the table, or -1 if none.
*/
goog.ui.TableSorter.prototype.getSortColumn = function() {
return this.column_;
};
/**
* @return {boolean} Whether the last sort was in reverse.
*/
goog.ui.TableSorter.prototype.isSortReversed = function() {
return this.reversed_;
};
/**
* @return {function(*, *) : number} The default sort function to be used by
* all columns.
*/
goog.ui.TableSorter.prototype.getDefaultSortFunction = function() {
return this.defaultSortFunction_;
};
/**
* Sets the default sort function to be used by all columns. If not set
* explicitly, this defaults to numeric sorting.
* @param {function(*, *) : number} sortFunction The new default sort function.
*/
goog.ui.TableSorter.prototype.setDefaultSortFunction = function(sortFunction) {
this.defaultSortFunction_ = sortFunction;
};
/**
* Gets the sort function to be used by the given column. Returns the default
* sort function if no sort function is explicitly set for this column.
* @param {number} column The column index.
* @return {function(*, *) : number} The sort function used by the column.
*/
goog.ui.TableSorter.prototype.getSortFunction = function(column) {
return this.sortFunctions_[column] || this.defaultSortFunction_;
};
/**
* Set the sort function for the given column, overriding the default sort
* function.
* @param {number} column The column index.
* @param {function(*, *) : number} sortFunction The new sort function.
*/
goog.ui.TableSorter.prototype.setSortFunction = function(column, sortFunction) {
this.sortFunctions_[column] = sortFunction;
};
/**
* Sort the table contents by the values in the given column.
* @param {goog.events.BrowserEvent} e The click event.
* @private
*/
goog.ui.TableSorter.prototype.sort_ = function(e) {
// Determine what column was clicked.
// TODO(robbyw): If this table cell contains another table, this could break.
var target = /** @type {Node} */ (e.target);
var th = goog.dom.getAncestorByTagNameAndClass(target,
goog.dom.TagName.TH);
var col = th.cellIndex;
// If the user clicks on the same column, sort it in reverse of what it is
// now. Otherwise, sort forward.
var reverse = col == this.column_ ? !this.reversed_ : false;
// Perform the sort.
if (this.dispatchEvent(goog.ui.TableSorter.EventType.BEFORESORT)) {
if (this.sort(col, reverse)) {
this.dispatchEvent(goog.ui.TableSorter.EventType.SORT);
}
}
};
/**
* Sort the table contents by the values in the given column.
* @param {number} column The column to sort by.
* @param {boolean=} opt_reverse Whether to sort in reverse.
* @return {boolean} Whether the sort was executed.
*/
goog.ui.TableSorter.prototype.sort = function(column, opt_reverse) {
var sortFunction = this.getSortFunction(column);
if (sortFunction === goog.ui.TableSorter.noSort) {
return false;
}
// Get some useful DOM nodes.
var table = this.getElement();
var tBody = table.tBodies[0];
var rows = tBody.rows;
var headers = table.tHead.rows[this.sortableHeaderRowIndex_].cells;
// Remove old header classes.
if (this.column_ >= 0) {
var oldHeader = headers[this.column_];
goog.dom.classes.remove(oldHeader, this.reversed_ ?
goog.getCssName('goog-tablesorter-sorted-reverse') :
goog.getCssName('goog-tablesorter-sorted'));
}
// If the user clicks on the same column, sort it in reverse of what it is
// now. Otherwise, sort forward.
this.reversed_ = !!opt_reverse;
// Get some useful DOM nodes.
var header = headers[column];
// Collect all the rows in to an array.
var values = [];
for (var i = 0, len = rows.length; i < len; i++) {
var row = rows[i];
var value = goog.dom.getTextContent(row.cells[column]);
values.push([value, row]);
}
// Sort the array.
var multiplier = this.reversed_ ? -1 : 1;
goog.array.stableSort(values,
function(a, b) {
return sortFunction(a[0], b[0]) * multiplier;
});
// Remove the tbody temporarily since this speeds up the sort on some
// browsers.
table.removeChild(tBody);
// Sort the rows, using the resulting array.
for (i = 0; i < len; i++) {
tBody.appendChild(values[i][1]);
}
// Reinstate the tbody.
table.insertBefore(tBody, table.tBodies[0] || null);
// Mark this as the last sorted column.
this.column_ = column;
// Update the header class.
goog.dom.classes.add(header, this.reversed_ ?
goog.getCssName('goog-tablesorter-sorted-reverse') :
goog.getCssName('goog-tablesorter-sorted'));
return true;
};
/**
* Disables sorting on the specified column
* @param {*} a First sort value.
* @param {*} b Second sort value.
* @return {number} Negative if a < b, 0 if a = b, and positive if a > b.
*/
goog.ui.TableSorter.noSort = goog.functions.error('no sort');
/**
* A numeric sort function.
* @param {*} a First sort value.
* @param {*} b Second sort value.
* @return {number} Negative if a < b, 0 if a = b, and positive if a > b.
*/
goog.ui.TableSorter.numericSort = function(a, b) {
return parseFloat(a) - parseFloat(b);
};
/**
* Alphabetic sort function.
* @param {*} a First sort value.
* @param {*} b Second sort value.
* @return {number} Negative if a < b, 0 if a = b, and positive if a > b.
*/
goog.ui.TableSorter.alphaSort = goog.array.defaultCompare;
/**
* Returns a function that is the given sort function in reverse.
* @param {function(*, *) : number} sortFunction The original sort function.
* @return {function(*, *) : number} A new sort function that reverses the
* given sort function.
*/
goog.ui.TableSorter.createReverseSort = function(sortFunction) {
return function(a, b) {
return -1 * sortFunction(a, b);
};
};
| 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 Tristate checkbox widget.
*
* @see ../demos/checkbox.html
*/
goog.provide('goog.ui.Checkbox');
goog.provide('goog.ui.Checkbox.State');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.State');
goog.require('goog.asserts');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.ui.CheckboxRenderer');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.Component.State');
goog.require('goog.ui.Control');
goog.require('goog.ui.registry');
/**
* 3-state checkbox widget. Fires CHECK or UNCHECK events before toggled and
* CHANGE event after toggled by user.
* The checkbox can also be enabled/disabled and get focused and highlighted.
*
* @param {goog.ui.Checkbox.State=} opt_checked Checked state to set.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
* document interaction.
* @param {goog.ui.CheckboxRenderer=} opt_renderer Renderer used to render or
* decorate the checkbox; defaults to {@link goog.ui.CheckboxRenderer}.
* @constructor
* @extends {goog.ui.Control}
*/
goog.ui.Checkbox = function(opt_checked, opt_domHelper, opt_renderer) {
var renderer = opt_renderer || goog.ui.CheckboxRenderer.getInstance();
goog.ui.Control.call(this, null, renderer, opt_domHelper);
// The checkbox maintains its own tri-state CHECKED state.
// The control class maintains DISABLED, ACTIVE, and FOCUSED (which enable tab
// navigation, and keyHandling with SPACE).
/**
* Checked state of the checkbox.
* @type {goog.ui.Checkbox.State}
* @private
*/
this.checked_ = goog.isDef(opt_checked) ?
opt_checked : goog.ui.Checkbox.State.UNCHECKED;
};
goog.inherits(goog.ui.Checkbox, goog.ui.Control);
/**
* Possible checkbox states.
* @enum {?boolean}
*/
goog.ui.Checkbox.State = {
CHECKED: true,
UNCHECKED: false,
UNDETERMINED: null
};
/**
* Label element bound to the checkbox.
* @type {Element}
* @private
*/
goog.ui.Checkbox.prototype.label_ = null;
/**
* @return {goog.ui.Checkbox.State} Checked state of the checkbox.
*/
goog.ui.Checkbox.prototype.getChecked = function() {
return this.checked_;
};
/**
* @return {boolean} Whether the checkbox is checked.
* @override
*/
goog.ui.Checkbox.prototype.isChecked = function() {
return this.checked_ == goog.ui.Checkbox.State.CHECKED;
};
/**
* @return {boolean} Whether the checkbox is not checked.
*/
goog.ui.Checkbox.prototype.isUnchecked = function() {
return this.checked_ == goog.ui.Checkbox.State.UNCHECKED;
};
/**
* @return {boolean} Whether the checkbox is in partially checked state.
*/
goog.ui.Checkbox.prototype.isUndetermined = function() {
return this.checked_ == goog.ui.Checkbox.State.UNDETERMINED;
};
/**
* Sets the checked state of the checkbox.
* @param {?boolean} checked The checked state to set.
* @override
*/
goog.ui.Checkbox.prototype.setChecked = function(checked) {
if (checked != this.checked_) {
this.checked_ = /** @type {goog.ui.Checkbox.State} */ (checked);
this.getRenderer().setCheckboxState(this.getElement(), this.checked_);
}
};
/**
* Sets the checked state for the checkbox. Unlike {@link #setChecked},
* doesn't update the checkbox's DOM. Considered protected; to be called
* only by renderer code during element decoration.
* @param {goog.ui.Checkbox.State} checked New checkbox state.
*/
goog.ui.Checkbox.prototype.setCheckedInternal = function(checked) {
this.checked_ = checked;
};
/**
* Binds an HTML element to the checkbox which if clicked toggles the checkbox.
* Behaves the same way as the 'label' HTML tag. The label element has to be the
* direct or non-direct ancestor of the checkbox element because it will get the
* focus when keyboard support is implemented.
*
* @param {Element} label The label control to set. If null, only the checkbox
* reacts to clicks.
*/
goog.ui.Checkbox.prototype.setLabel = function(label) {
if (this.isInDocument()) {
this.exitDocument();
this.label_ = label;
this.enterDocument();
} else {
this.label_ = label;
}
};
/**
* Toggles the checkbox. State transitions:
* <ul>
* <li>unchecked -> checked
* <li>undetermined -> checked
* <li>checked -> unchecked
* </ul>
*/
goog.ui.Checkbox.prototype.toggle = function() {
this.setChecked(this.checked_ ? goog.ui.Checkbox.State.UNCHECKED :
goog.ui.Checkbox.State.CHECKED);
};
/** @override */
goog.ui.Checkbox.prototype.enterDocument = function() {
goog.base(this, 'enterDocument');
if (this.isHandleMouseEvents()) {
var handler = this.getHandler();
// Listen to the label, if it was set.
if (this.label_) {
// Any mouse events that happen to the associated label should have the
// same effect on the checkbox as if they were happening to the checkbox
// itself.
handler.
listen(this.label_, goog.events.EventType.CLICK,
this.handleClickOrSpace_).
listen(this.label_, goog.events.EventType.MOUSEOVER,
this.handleMouseOver).
listen(this.label_, goog.events.EventType.MOUSEOUT,
this.handleMouseOut).
listen(this.label_, goog.events.EventType.MOUSEDOWN,
this.handleMouseDown).
listen(this.label_, goog.events.EventType.MOUSEUP,
this.handleMouseUp);
}
// Checkbox needs to explicitly listen for click event.
handler.listen(this.getElement(),
goog.events.EventType.CLICK, this.handleClickOrSpace_);
}
// Set aria label.
if (this.label_) {
if (!this.label_.id) {
this.label_.id = this.makeId('lbl');
}
var checkboxElement = this.getElement();
goog.asserts.assert(checkboxElement,
'The checkbox DOM element cannot be null.');
goog.a11y.aria.setState(checkboxElement,
goog.a11y.aria.State.LABELLEDBY,
this.label_.id);
}
};
/**
* Fix for tabindex not being updated so that disabled checkbox is not
* focusable. In particular this fails in Chrome.
* Note: in general tabIndex=-1 will prevent from keyboard focus but enables
* mouse focus, however in this case the control class prevents mouse focus.
* @override
*/
goog.ui.Checkbox.prototype.setEnabled = function(enabled) {
goog.base(this, 'setEnabled', enabled);
var el = this.getElement();
if (el) {
el.tabIndex = this.isEnabled() ? 0 : -1;
}
};
/**
* Handles the click event.
* @param {!goog.events.BrowserEvent} e The event.
* @private
*/
goog.ui.Checkbox.prototype.handleClickOrSpace_ = function(e) {
e.stopPropagation();
var eventType = this.checked_ ? goog.ui.Component.EventType.UNCHECK :
goog.ui.Component.EventType.CHECK;
if (this.isEnabled() && this.dispatchEvent(eventType)) {
e.preventDefault(); // Prevent scrolling in Chrome if SPACE is pressed.
this.toggle();
this.dispatchEvent(goog.ui.Component.EventType.CHANGE);
}
};
/** @override */
goog.ui.Checkbox.prototype.handleKeyEventInternal = function(e) {
if (e.keyCode == goog.events.KeyCodes.SPACE) {
this.handleClickOrSpace_(e);
}
return false;
};
/**
* Register this control so it can be created from markup.
*/
goog.ui.registry.setDecoratorByClassName(
goog.ui.CheckboxRenderer.CSS_CLASS,
function() {
return new goog.ui.Checkbox();
});
| 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 Similiar to {@link goog.ui.FlatButtonRenderer},
* but underlines text instead of adds borders.
*
* For accessibility reasons, it is best to use this with a goog.ui.Button
* instead of an A element for links that perform actions in the page. Links
* that have an href and open a new page can and should remain as A elements.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.ui.LinkButtonRenderer');
goog.require('goog.ui.Button');
goog.require('goog.ui.FlatButtonRenderer');
goog.require('goog.ui.registry');
/**
* Link renderer for {@link goog.ui.Button}s. Link buttons can contain
* almost arbitrary HTML content, will flow like inline elements, but can be
* styled like block-level elements.
* @constructor
* @extends {goog.ui.FlatButtonRenderer}
*/
goog.ui.LinkButtonRenderer = function() {
goog.ui.FlatButtonRenderer.call(this);
};
goog.inherits(goog.ui.LinkButtonRenderer, goog.ui.FlatButtonRenderer);
goog.addSingletonGetter(goog.ui.LinkButtonRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.LinkButtonRenderer.CSS_CLASS = goog.getCssName('goog-link-button');
/** @override */
goog.ui.LinkButtonRenderer.prototype.getCssClass = function() {
return goog.ui.LinkButtonRenderer.CSS_CLASS;
};
// Register a decorator factory function for Link Buttons.
goog.ui.registry.setDecoratorByClassName(goog.ui.LinkButtonRenderer.CSS_CLASS,
function() {
// Uses goog.ui.Button, but with LinkButtonRenderer.
return new goog.ui.Button(null, goog.ui.LinkButtonRenderer.getInstance());
});
| 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 toolbar toggle button control.
*
* @author attila@google.com (Attila Bodis)
* @author ssaviano@google.com (Steven Saviano)
*/
goog.provide('goog.ui.ToolbarToggleButton');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.ToggleButton');
goog.require('goog.ui.ToolbarButtonRenderer');
goog.require('goog.ui.registry');
/**
* A toggle button control for a toolbar.
*
* @param {goog.ui.ControlContent} content Text caption or existing DOM
* structure to display as the button's caption.
* @param {goog.ui.ToolbarButtonRenderer=} opt_renderer Optional renderer used
* to render or decorate the button; defaults to
* {@link goog.ui.ToolbarButtonRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
* document interaction.
* @constructor
* @extends {goog.ui.ToggleButton}
*/
goog.ui.ToolbarToggleButton = function(content, opt_renderer, opt_domHelper) {
goog.ui.ToggleButton.call(this, content, opt_renderer ||
goog.ui.ToolbarButtonRenderer.getInstance(), opt_domHelper);
};
goog.inherits(goog.ui.ToolbarToggleButton, goog.ui.ToggleButton);
// Registers a decorator factory function for toggle buttons in toolbars.
goog.ui.registry.setDecoratorByClassName(
goog.getCssName('goog-toolbar-toggle-button'), function() {
return new goog.ui.ToolbarToggleButton(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 Factory class to create a simple autocomplete that will match
* from an array of data provided via ajax.
*
* @see ../../demos/autocompleteremote.html
*/
goog.provide('goog.ui.ac.Remote');
goog.require('goog.ui.ac.AutoComplete');
goog.require('goog.ui.ac.InputHandler');
goog.require('goog.ui.ac.RemoteArrayMatcher');
goog.require('goog.ui.ac.Renderer');
/**
* Factory class for building a remote autocomplete widget that autocompletes
* an inputbox or text area from a data array provided via ajax.
* @param {string} url The Uri which generates the auto complete matches.
* @param {Element} input Input element or text area.
* @param {boolean=} opt_multi Whether to allow multiple entries; defaults
* to false.
* @param {boolean=} opt_useSimilar Whether to use similar matches; e.g.
* "gost" => "ghost".
* @constructor
* @extends {goog.ui.ac.AutoComplete}
*/
goog.ui.ac.Remote = function(url, input, opt_multi, opt_useSimilar) {
var matcher = new goog.ui.ac.RemoteArrayMatcher(url, !opt_useSimilar);
this.matcher_ = matcher;
var renderer = new goog.ui.ac.Renderer();
var inputhandler = new goog.ui.ac.InputHandler(null, null, !!opt_multi, 300);
goog.ui.ac.AutoComplete.call(this, matcher, renderer, inputhandler);
inputhandler.attachAutoComplete(this);
inputhandler.attachInputs(input);
};
goog.inherits(goog.ui.ac.Remote, goog.ui.ac.AutoComplete);
/**
* Set whether or not standard highlighting should be used when rendering rows.
* @param {boolean} useStandardHighlighting true if standard highlighting used.
*/
goog.ui.ac.Remote.prototype.setUseStandardHighlighting =
function(useStandardHighlighting) {
this.renderer_.setUseStandardHighlighting(useStandardHighlighting);
};
/**
* Gets the attached InputHandler object.
* @return {goog.ui.ac.InputHandler} The input handler.
*/
goog.ui.ac.Remote.prototype.getInputHandler = function() {
return /** @type {goog.ui.ac.InputHandler} */ (
this.selectionHandler_);
};
/**
* Set the send method ("GET", "POST") for the matcher.
* @param {string} method The send method; default: GET.
*/
goog.ui.ac.Remote.prototype.setMethod = function(method) {
this.matcher_.setMethod(method);
};
/**
* Set the post data for the matcher.
* @param {string} content Post data.
*/
goog.ui.ac.Remote.prototype.setContent = function(content) {
this.matcher_.setContent(content);
};
/**
* Set the HTTP headers for the matcher.
* @param {Object|goog.structs.Map} headers Map of headers to add to the
* request.
*/
goog.ui.ac.Remote.prototype.setHeaders = function(headers) {
this.matcher_.setHeaders(headers);
};
/**
* Set the timeout interval for the matcher.
* @param {number} interval Number of milliseconds after which an
* incomplete request will be aborted; 0 means no timeout is set.
*/
goog.ui.ac.Remote.prototype.setTimeoutInterval = function(interval) {
this.matcher_.setTimeoutInterval(interval);
};
| 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 Basic class for matching words in an array.
*
*/
goog.provide('goog.ui.ac.ArrayMatcher');
goog.require('goog.string');
/**
* Basic class for matching words in an array
* @constructor
* @param {Array} rows Dictionary of items to match. Can be objects if they
* have a toString method that returns the value to match against.
* @param {boolean=} opt_noSimilar if true, do not do similarity matches for the
* input token against the dictionary.
*/
goog.ui.ac.ArrayMatcher = function(rows, opt_noSimilar) {
this.rows_ = rows;
this.useSimilar_ = !opt_noSimilar;
};
/**
* Replaces the rows that this object searches over.
* @param {Array} rows Dictionary of items to match.
*/
goog.ui.ac.ArrayMatcher.prototype.setRows = function(rows) {
this.rows_ = rows;
};
/**
* Function used to pass matches to the autocomplete
* @param {string} token Token to match.
* @param {number} maxMatches Max number of matches to return.
* @param {Function} matchHandler callback to execute after matching.
* @param {string=} opt_fullString The full string from the input box.
*/
goog.ui.ac.ArrayMatcher.prototype.requestMatchingRows =
function(token, maxMatches, matchHandler, opt_fullString) {
var matches = this.getPrefixMatches(token, maxMatches);
if (matches.length == 0 && this.useSimilar_) {
matches = this.getSimilarRows(token, maxMatches);
}
matchHandler(token, matches);
};
/**
* Matches the token against the start of words in the row.
* @param {string} token Token to match.
* @param {number} maxMatches Max number of matches to return.
* @return {Array} Rows that match.
*/
goog.ui.ac.ArrayMatcher.prototype.getPrefixMatches =
function(token, maxMatches) {
var matches = [];
if (token != '') {
var escapedToken = goog.string.regExpEscape(token);
var matcher = new RegExp('(^|\\W+)' + escapedToken, 'i');
for (var i = 0; i < this.rows_.length && matches.length < maxMatches; i++) {
var row = this.rows_[i];
if (String(row).match(matcher)) {
matches.push(row);
}
}
}
return matches;
};
/**
* Matches the token against similar rows, by calculating "distance" between the
* terms.
* @param {string} token Token to match.
* @param {number} maxMatches Max number of matches to return.
* @return {Array} The best maxMatches rows.
*/
goog.ui.ac.ArrayMatcher.prototype.getSimilarRows = function(token, maxMatches) {
var results = [];
for (var index = 0; index < this.rows_.length; index++) {
var row = this.rows_[index];
var str = token.toLowerCase();
var txt = String(row).toLowerCase();
var score = 0;
if (txt.indexOf(str) != -1) {
score = parseInt((txt.indexOf(str) / 4).toString(), 10);
} else {
var arr = str.split('');
var lastPos = -1;
var penalty = 10;
for (var i = 0, c; c = arr[i]; i++) {
var pos = txt.indexOf(c);
if (pos > lastPos) {
var diff = pos - lastPos - 1;
if (diff > penalty - 5) {
diff = penalty - 5;
}
score += diff;
lastPos = pos;
} else {
score += penalty;
penalty += 5;
}
}
}
if (score < str.length * 6) {
results.push({
str: row,
score: score,
index: index
});
}
}
results.sort(function(a, b) {
var diff = a.score - b.score;
if (diff != 0) {
return diff;
}
return a.index - b.index;
});
var matches = [];
for (var i = 0; i < maxMatches && i < results.length; i++) {
matches.push(results[i].str);
}
return matches;
};
| 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 Options for rendering matches.
*
*/
goog.provide('goog.ui.ac.RenderOptions');
/**
* A simple class that contains options for rendering a set of autocomplete
* matches. Used as an optional argument in the callback from the matcher.
* @constructor
*/
goog.ui.ac.RenderOptions = function() {
};
/**
* Whether the current highlighting is to be preserved when displaying the new
* set of matches.
* @type {boolean}
* @private
*/
goog.ui.ac.RenderOptions.prototype.preserveHilited_ = false;
/**
* Whether the first match is to be highlighted. When undefined the autoHilite
* flag of the autocomplete is used.
* @type {boolean|undefined}
* @private
*/
goog.ui.ac.RenderOptions.prototype.autoHilite_;
/**
* @param {boolean} flag The new value for the preserveHilited_ flag.
*/
goog.ui.ac.RenderOptions.prototype.setPreserveHilited = function(flag) {
this.preserveHilited_ = flag;
};
/**
* @return {boolean} The value of the preserveHilited_ flag.
*/
goog.ui.ac.RenderOptions.prototype.getPreserveHilited = function() {
return this.preserveHilited_;
};
/**
* @param {boolean} flag The new value for the autoHilite_ flag.
*/
goog.ui.ac.RenderOptions.prototype.setAutoHilite = function(flag) {
this.autoHilite_ = flag;
};
/**
* @return {boolean|undefined} The value of the autoHilite_ flag.
*/
goog.ui.ac.RenderOptions.prototype.getAutoHilite = function() {
return this.autoHilite_;
};
| 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 Class for managing the interactions between a rich autocomplete
* object and a text-input or textarea.
*
*/
goog.provide('goog.ui.ac.RichInputHandler');
goog.require('goog.ui.ac.InputHandler');
/**
* Class for managing the interaction between an autocomplete object and a
* text-input or textarea.
* @param {?string=} opt_separators Seperators to split multiple entries.
* @param {?string=} opt_literals Characters used to delimit text literals.
* @param {?boolean=} opt_multi Whether to allow multiple entries
* (Default: true).
* @param {?number=} opt_throttleTime Number of milliseconds to throttle
* keyevents with (Default: 150).
* @constructor
* @extends {goog.ui.ac.InputHandler}
*/
goog.ui.ac.RichInputHandler = function(opt_separators, opt_literals,
opt_multi, opt_throttleTime) {
goog.ui.ac.InputHandler.call(this, opt_separators, opt_literals,
opt_multi, opt_throttleTime);
};
goog.inherits(goog.ui.ac.RichInputHandler, goog.ui.ac.InputHandler);
/**
* Selects the given rich row. The row's select(target) method is called.
* @param {Object} row The row to select.
* @return {boolean} Whether to suppress the update event.
* @override
*/
goog.ui.ac.RichInputHandler.prototype.selectRow = function(row) {
var suppressUpdate = goog.ui.ac.RichInputHandler.superClass_
.selectRow.call(this, row);
row.select(this.ac_.getTarget());
return suppressUpdate;
};
| 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 Factory class to create a rich autocomplete that will match
* from an array of data provided via ajax. The server returns a complex data
* structure that is used with client-side javascript functions to render the
* results.
*
* The server sends a list of the form:
* [["type1", {...}, {...}, ...], ["type2", {...}, {...}, ...], ...]
* The first element of each sublist is a string designating the type of the
* hashes in the sublist, each of which represents one match. The type string
* must be the name of a function(item) which converts the hash into a rich
* row that contains both a render(node, token) and a select(target) method.
* The render method is called by the renderer when rendering the rich row,
* and the select method is called by the RichInputHandler when the rich row is
* selected.
*
* @see ../../demos/autocompleterichremote.html
*/
goog.provide('goog.ui.ac.RichRemote');
goog.require('goog.ui.ac.AutoComplete');
goog.require('goog.ui.ac.Remote');
goog.require('goog.ui.ac.Renderer');
goog.require('goog.ui.ac.RichInputHandler');
goog.require('goog.ui.ac.RichRemoteArrayMatcher');
/**
* Factory class to create a rich autocomplete widget that autocompletes an
* inputbox or textarea from data provided via ajax. The server returns a
* complex data structure that is used with client-side javascript functions to
* render the results.
* @param {string} url The Uri which generates the auto complete matches.
* @param {Element} input Input element or text area.
* @param {boolean=} opt_multi Whether to allow multiple entries; defaults
* to false.
* @param {boolean=} opt_useSimilar Whether to use similar matches; e.g.
* "gost" => "ghost".
* @constructor
* @extends {goog.ui.ac.Remote}
*/
goog.ui.ac.RichRemote = function(url, input, opt_multi, opt_useSimilar) {
// Create a custom renderer that renders rich rows. The renderer calls
// row.render(node, token) for each row.
var customRenderer = {};
customRenderer.renderRow = function(row, token, node) {
return row.data.render(node, token);
};
/**
* A standard renderer that uses a custom row renderer to display the
* rich rows generated by this autocomplete widget.
* @type {goog.ui.ac.Renderer}
* @private
*/
var renderer = new goog.ui.ac.Renderer(null, customRenderer);
this.renderer_ = renderer;
/**
* A remote matcher that parses rich results returned by the server.
* @type {goog.ui.ac.RichRemoteArrayMatcher}
* @private
*/
var matcher = new goog.ui.ac.RichRemoteArrayMatcher(url,
!opt_useSimilar);
this.matcher_ = matcher;
/**
* An input handler that calls select on a row when it is selected.
* @type {goog.ui.ac.RichInputHandler}
* @private
*/
var inputhandler = new goog.ui.ac.RichInputHandler(null, null,
!!opt_multi, 300);
// Create the widget and connect it to the input handler.
goog.ui.ac.AutoComplete.call(this, matcher, renderer, inputhandler);
inputhandler.attachAutoComplete(this);
inputhandler.attachInputs(input);
};
goog.inherits(goog.ui.ac.RichRemote, goog.ui.ac.Remote);
/**
* Set the filter that is called before the array matches are returned.
* @param {Function} rowFilter A function(rows) that returns an array of rows as
* a subset of the rows input array.
*/
goog.ui.ac.RichRemote.prototype.setRowFilter = function(rowFilter) {
this.matcher_.setRowFilter(rowFilter);
};
| 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 Class that retrieves rich autocomplete matches, represented as
* a structured list of lists, via an ajax call. The first element of each
* sublist is the name of a client-side javascript function that converts the
* remaining sublist elements into rich rows.
*
*/
goog.provide('goog.ui.ac.RichRemoteArrayMatcher');
goog.require('goog.ui.ac.RemoteArrayMatcher');
/**
* An array matcher that requests rich matches via ajax and converts them into
* rich rows.
* @param {string} url The Uri which generates the auto complete matches. The
* search term is passed to the server as the 'token' query param.
* @param {boolean=} opt_noSimilar If true, request that the server does not do
* similarity matches for the input token against the dictionary.
* The value is sent to the server as the 'use_similar' query param which is
* either "1" (opt_noSimilar==false) or "0" (opt_noSimilar==true).
* @constructor
* @extends {goog.ui.ac.RemoteArrayMatcher}
*/
goog.ui.ac.RichRemoteArrayMatcher = function(url, opt_noSimilar) {
goog.ui.ac.RemoteArrayMatcher.call(this, url, opt_noSimilar);
/**
* A function(rows) that is called before the array matches are returned.
* It runs client-side and filters the results given by the server before
* being rendered by the client.
* @type {Function}
* @private
*/
this.rowFilter_ = null;
};
goog.inherits(goog.ui.ac.RichRemoteArrayMatcher, goog.ui.ac.RemoteArrayMatcher);
/**
* Set the filter that is called before the array matches are returned.
* @param {Function} rowFilter A function(rows) that returns an array of rows as
* a subset of the rows input array.
*/
goog.ui.ac.RichRemoteArrayMatcher.prototype.setRowFilter = function(rowFilter) {
this.rowFilter_ = rowFilter;
};
/**
* Retrieve a set of matching rows from the server via ajax and convert them
* into rich rows.
* @param {string} token The text that should be matched; passed to the server
* as the 'token' query param.
* @param {number} maxMatches The maximum number of matches requested from the
* server; passed as the 'max_matches' query param. The server is
* responsible for limiting the number of matches that are returned.
* @param {Function} matchHandler Callback to execute on the result after
* matching.
* @override
*/
goog.ui.ac.RichRemoteArrayMatcher.prototype.requestMatchingRows =
function(token, maxMatches, matchHandler) {
// The RichRemoteArrayMatcher must map over the results and filter them
// before calling the request matchHandler. This is done by passing
// myMatchHandler to RemoteArrayMatcher.requestMatchingRows which maps,
// filters, and then calls matchHandler.
var myMatchHandler = goog.bind(function(token, matches) {
/** @preserveTry */
try {
var rows = [];
for (var i = 0; i < matches.length; i++) {
var func = /** @type {!Function} */
(goog.json.unsafeParse(matches[i][0]));
for (var j = 1; j < matches[i].length; j++) {
var richRow = func(matches[i][j]);
rows.push(richRow);
// If no render function was provided, set the node's innerHTML.
if (typeof richRow.render == 'undefined') {
richRow.render = function(node, token) {
node.innerHTML = richRow.toString();
};
}
// If no select function was provided, set the text of the input.
if (typeof richRow.select == 'undefined') {
richRow.select = function(target) {
target.value = richRow.toString();
};
}
}
}
if (this.rowFilter_) {
rows = this.rowFilter_(rows);
}
matchHandler(token, rows);
} catch (exception) {
// TODO(user): Is this what we want?
matchHandler(token, []);
}
}, this);
// Call the super's requestMatchingRows with myMatchHandler
goog.ui.ac.RichRemoteArrayMatcher.superClass_
.requestMatchingRows.call(this, token, maxMatches, myMatchHandler);
};
| 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 Gmail-like AutoComplete logic.
*
* @see ../../demos/autocomplete-basic.html
*/
goog.provide('goog.ui.ac.AutoComplete');
goog.provide('goog.ui.ac.AutoComplete.EventType');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
/**
* This is the central manager class for an AutoComplete instance. The matcher
* can specify disabled rows that should not be hilited or selected by
* implementing <code>isRowDisabled(row):boolean</code> for each autocomplete
* row. No row will not be considered disabled if this method is not
* implemented.
*
* @param {Object} matcher A data source and row matcher, implements
* <code>requestMatchingRows(token, maxMatches, matchCallback)</code>.
* @param {goog.events.EventTarget} renderer An object that implements
* <code>
* isVisible():boolean<br>
* renderRows(rows:Array, token:string, target:Element);<br>
* hiliteId(row-id:number);<br>
* dismiss();<br>
* dispose():
* </code>.
* @param {Object} selectionHandler An object that implements
* <code>
* selectRow(row);<br>
* update(opt_force);
* </code>.
*
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.ui.ac.AutoComplete = function(matcher, renderer, selectionHandler) {
goog.events.EventTarget.call(this);
/**
* A data-source which provides autocomplete suggestions.
* @type {Object}
* @protected
* @suppress {underscore}
*/
this.matcher_ = matcher;
/**
* A handler which interacts with the input DOM element (textfield, textarea,
* or richedit).
* @type {Object}
* @protected
* @suppress {underscore}
*/
this.selectionHandler_ = selectionHandler;
/**
* A renderer to render/show/highlight/hide the autocomplete menu.
* @type {goog.events.EventTarget}
* @protected
* @suppress {underscore}
*/
this.renderer_ = renderer;
goog.events.listen(renderer, [
goog.ui.ac.AutoComplete.EventType.HILITE,
goog.ui.ac.AutoComplete.EventType.SELECT,
goog.ui.ac.AutoComplete.EventType.CANCEL_DISMISS,
goog.ui.ac.AutoComplete.EventType.DISMISS], this);
/**
* Currently typed token which will be used for completion.
* @type {?string}
* @protected
* @suppress {underscore}
*/
this.token_ = null;
/**
* Autcomplete suggestion items.
* @type {Array}
* @protected
* @suppress {underscore}
*/
this.rows_ = [];
/**
* Id of the currently highlighted row.
* @type {number}
* @protected
* @suppress {underscore}
*/
this.hiliteId_ = -1;
/**
* Id of the first row in autocomplete menu. Note that new ids are assigned
* everytime new suggestions are fetched.
* @type {number}
* @protected
* @suppress {underscore}
*/
this.firstRowId_ = 0;
/**
* The target HTML node for displaying.
* @type {Element}
* @protected
* @suppress {underscore}
*/
this.target_ = null;
/**
* The timer id for dismissing autocomplete menu with a delay.
* @type {?number}
* @private
*/
this.dismissTimer_ = null;
/**
* Mapping from text input element to the anchor element. If the
* mapping does not exist, the input element will act as the anchor
* element.
* @type {Object.<Element>}
* @private
*/
this.inputToAnchorMap_ = {};
};
goog.inherits(goog.ui.ac.AutoComplete, goog.events.EventTarget);
/**
* The maximum number of matches that should be returned
* @type {number}
* @private
*/
goog.ui.ac.AutoComplete.prototype.maxMatches_ = 10;
/**
* True iff the first row should automatically be highlighted
* @type {boolean}
* @private
*/
goog.ui.ac.AutoComplete.prototype.autoHilite_ = true;
/**
* True iff the user can unhilight all rows by pressing the up arrow.
* @type {boolean}
* @private
*/
goog.ui.ac.AutoComplete.prototype.allowFreeSelect_ = false;
/**
* True iff item selection should wrap around from last to first. If
* allowFreeSelect_ is on in conjunction, there is a step of free selection
* before wrapping.
* @type {boolean}
* @private
*/
goog.ui.ac.AutoComplete.prototype.wrap_ = false;
/**
* Whether completion from suggestion triggers fetching new suggestion.
* @type {boolean}
* @private
*/
goog.ui.ac.AutoComplete.prototype.triggerSuggestionsOnUpdate_ = false;
/**
* Events associated with the autocomplete
* @enum {string}
*/
goog.ui.ac.AutoComplete.EventType = {
/** A row has been highlighted by the renderer */
ROW_HILITE: 'rowhilite',
// Note: The events below are used for internal autocomplete events only and
// should not be used in non-autocomplete code.
/** A row has been mouseovered and should be highlighted by the renderer. */
HILITE: 'hilite',
/** A row has been selected by the renderer */
SELECT: 'select',
/** A dismiss event has occurred */
DISMISS: 'dismiss',
/** Event that cancels a dismiss event */
CANCEL_DISMISS: 'canceldismiss',
/**
* Field value was updated. A row field is included and is non-null when a
* row has been selected. The value of the row typically includes fields:
* contactData and formattedValue as well as a toString function (though none
* of these fields are guaranteed to exist). The row field may be used to
* return custom-type row data.
*/
UPDATE: 'update',
/**
* The list of suggestions has been updated, usually because either the list
* has opened, or because the user has typed another character and the
* suggestions have been updated, or the user has dismissed the autocomplete.
*/
SUGGESTIONS_UPDATE: 'suggestionsupdate'
};
/**
* Returns the renderer that renders/shows/highlights/hides the autocomplete
* menu.
* @return {goog.events.EventTarget} Renderer used by the this widget.
*/
goog.ui.ac.AutoComplete.prototype.getRenderer = function() {
return this.renderer_;
};
/**
* Generic event handler that handles any events this object is listening to.
* @param {goog.events.Event} e Event Object.
*/
goog.ui.ac.AutoComplete.prototype.handleEvent = function(e) {
if (e.target == this.renderer_) {
switch (e.type) {
case goog.ui.ac.AutoComplete.EventType.HILITE:
this.hiliteId(/** @type {number} */ (e.row));
break;
case goog.ui.ac.AutoComplete.EventType.SELECT:
// Make sure the row selected is not a disabled row.
var index = this.getIndexOfId(/** @type {number} */ (e.row));
var row = this.rows_[index];
var rowDisabled = !!row && this.matcher_.isRowDisabled &&
this.matcher_.isRowDisabled(row);
if (!rowDisabled) {
this.selectHilited();
}
break;
case goog.ui.ac.AutoComplete.EventType.CANCEL_DISMISS:
this.cancelDelayedDismiss();
break;
case goog.ui.ac.AutoComplete.EventType.DISMISS:
this.dismissOnDelay();
break;
}
}
};
/**
* Sets the max number of matches to fetch from the Matcher.
*
* @param {number} max Max number of matches.
*/
goog.ui.ac.AutoComplete.prototype.setMaxMatches = function(max) {
this.maxMatches_ = max;
};
/**
* Sets whether or not the first row should be highlighted by default.
*
* @param {boolean} autoHilite true iff the first row should be
* highlighted by default.
*/
goog.ui.ac.AutoComplete.prototype.setAutoHilite = function(autoHilite) {
this.autoHilite_ = autoHilite;
};
/**
* Sets whether or not the up/down arrow can unhilite all rows.
*
* @param {boolean} allowFreeSelect true iff the up arrow can unhilite all rows.
*/
goog.ui.ac.AutoComplete.prototype.setAllowFreeSelect =
function(allowFreeSelect) {
this.allowFreeSelect_ = allowFreeSelect;
};
/**
* Sets whether or not selections can wrap around the edges.
*
* @param {boolean} wrap true iff sections should wrap around the edges.
*/
goog.ui.ac.AutoComplete.prototype.setWrap = function(wrap) {
this.wrap_ = wrap;
};
/**
* Sets whether or not to request new suggestions immediately after completion
* of a suggestion.
*
* @param {boolean} triggerSuggestionsOnUpdate true iff completion should fetch
* new suggestions.
*/
goog.ui.ac.AutoComplete.prototype.setTriggerSuggestionsOnUpdate = function(
triggerSuggestionsOnUpdate) {
this.triggerSuggestionsOnUpdate_ = triggerSuggestionsOnUpdate;
};
/**
* Sets the token to match against. This triggers calls to the Matcher to
* fetch the matches (up to maxMatches), and then it triggers a call to
* <code>renderer.renderRows()</code>.
*
* @param {string} token The string for which to search in the Matcher.
* @param {string=} opt_fullString Optionally, the full string in the input
* field.
*/
goog.ui.ac.AutoComplete.prototype.setToken = function(token, opt_fullString) {
if (this.token_ == token) {
return;
}
this.token_ = token;
this.matcher_.requestMatchingRows(this.token_,
this.maxMatches_, goog.bind(this.matchListener_, this), opt_fullString);
this.cancelDelayedDismiss();
};
/**
* Gets the current target HTML node for displaying autocomplete UI.
* @return {Element} The current target HTML node for displaying autocomplete
* UI.
*/
goog.ui.ac.AutoComplete.prototype.getTarget = function() {
return this.target_;
};
/**
* Sets the current target HTML node for displaying autocomplete UI.
* Can be an implementation specific definition of how to display UI in relation
* to the target node.
* This target will be passed into <code>renderer.renderRows()</code>
*
* @param {Element} target The current target HTML node for displaying
* autocomplete UI.
*/
goog.ui.ac.AutoComplete.prototype.setTarget = function(target) {
this.target_ = target;
};
/**
* @return {boolean} Whether the autocomplete's renderer is open.
*/
goog.ui.ac.AutoComplete.prototype.isOpen = function() {
return this.renderer_.isVisible();
};
/**
* @return {number} Number of rows in the autocomplete.
*/
goog.ui.ac.AutoComplete.prototype.getRowCount = function() {
return this.rows_.length;
};
/**
* Moves the hilite to the next non-disabled row.
* Calls renderer.hiliteId() when there's something to do.
* @return {boolean} Returns true on a successful hilite.
*/
goog.ui.ac.AutoComplete.prototype.hiliteNext = function() {
var lastId = this.firstRowId_ + this.rows_.length - 1;
var toHilite = this.hiliteId_;
// Hilite the next row, skipping any disabled rows.
for (var i = 0; i < this.rows_.length; i++) {
// Increment to the next row.
if (toHilite >= this.firstRowId_ && toHilite < lastId) {
toHilite++;
} else if (toHilite == -1) {
toHilite = this.firstRowId_;
} else if (this.allowFreeSelect_ && toHilite == lastId) {
this.hiliteId(-1);
return false;
} else if (this.wrap_ && toHilite == lastId) {
toHilite = this.firstRowId_;
} else {
return false;
}
if (this.hiliteId(toHilite)) {
return true;
}
}
return false;
};
/**
* Moves the hilite to the previous non-disabled row. Calls
* renderer.hiliteId() when there's something to do.
* @return {boolean} Returns true on a successful hilite.
*/
goog.ui.ac.AutoComplete.prototype.hilitePrev = function() {
var lastId = this.firstRowId_ + this.rows_.length - 1;
var toHilite = this.hiliteId_;
// Hilite the previous row, skipping any disabled rows.
for (var i = 0; i < this.rows_.length; i++) {
// Decrement to the previous row.
if (toHilite > this.firstRowId_) {
toHilite--;
} else if (this.allowFreeSelect_ && toHilite == this.firstRowId_) {
this.hiliteId(-1);
return false;
} else if (this.wrap_ && (toHilite == -1 || toHilite == this.firstRowId_)) {
toHilite = lastId;
} else {
return false;
}
if (this.hiliteId(toHilite)) {
return true;
}
}
return false;
};
/**
* Hilites the id if it's valid and the row is not disabled, otherwise does
* nothing.
* @param {number} id A row id (not index).
* @return {boolean} Whether the id was hilited. Returns false if the row is
* disabled.
*/
goog.ui.ac.AutoComplete.prototype.hiliteId = function(id) {
var index = this.getIndexOfId(id);
var row = this.rows_[index];
var rowDisabled = !!row && this.matcher_.isRowDisabled &&
this.matcher_.isRowDisabled(row);
if (!rowDisabled) {
this.hiliteId_ = id;
this.renderer_.hiliteId(id);
return index != -1;
}
return false;
};
/**
* Hilites the index, if it's valid and the row is not disabled, otherwise does
* nothing.
* @param {number} index The row's index.
* @return {boolean} Whether the index was hilited.
*/
goog.ui.ac.AutoComplete.prototype.hiliteIndex = function(index) {
return this.hiliteId(this.getIdOfIndex_(index));
};
/**
* If there are any current matches, this passes the hilited row data to
* <code>selectionHandler.selectRow()</code>
* @return {boolean} Whether there are any current matches.
*/
goog.ui.ac.AutoComplete.prototype.selectHilited = function() {
var index = this.getIndexOfId(this.hiliteId_);
if (index != -1) {
var selectedRow = this.rows_[index];
var suppressUpdate = this.selectionHandler_.selectRow(selectedRow);
if (this.triggerSuggestionsOnUpdate_) {
this.token_ = null;
this.dismissOnDelay();
} else {
this.dismiss();
}
if (!suppressUpdate) {
this.dispatchEvent({
type: goog.ui.ac.AutoComplete.EventType.UPDATE,
row: selectedRow
});
if (this.triggerSuggestionsOnUpdate_) {
this.selectionHandler_.update(true);
}
}
return true;
} else {
this.dismiss();
this.dispatchEvent(
{
type: goog.ui.ac.AutoComplete.EventType.UPDATE,
row: null
});
return false;
}
};
/**
* Returns whether or not the autocomplete is open and has a highlighted row.
* @return {boolean} Whether an autocomplete row is highlighted.
*/
goog.ui.ac.AutoComplete.prototype.hasHighlight = function() {
return this.isOpen() && this.getIndexOfId(this.hiliteId_) != -1;
};
/**
* Clears out the token, rows, and hilite, and calls
* <code>renderer.dismiss()</code>
*/
goog.ui.ac.AutoComplete.prototype.dismiss = function() {
this.hiliteId_ = -1;
this.token_ = null;
this.firstRowId_ += this.rows_.length;
this.rows_ = [];
window.clearTimeout(this.dismissTimer_);
this.dismissTimer_ = null;
this.renderer_.dismiss();
this.dispatchEvent(goog.ui.ac.AutoComplete.EventType.SUGGESTIONS_UPDATE);
this.dispatchEvent(goog.ui.ac.AutoComplete.EventType.DISMISS);
};
/**
* Call a dismiss after a delay, if there's already a dismiss active, ignore.
*/
goog.ui.ac.AutoComplete.prototype.dismissOnDelay = function() {
if (!this.dismissTimer_) {
this.dismissTimer_ = window.setTimeout(goog.bind(this.dismiss, this), 100);
}
};
/**
* Cancels any delayed dismiss events immediately.
* @return {boolean} Whether a delayed dismiss was cancelled.
* @private
*/
goog.ui.ac.AutoComplete.prototype.immediatelyCancelDelayedDismiss_ =
function() {
if (this.dismissTimer_) {
window.clearTimeout(this.dismissTimer_);
this.dismissTimer_ = null;
return true;
}
return false;
};
/**
* Cancel the active delayed dismiss if there is one.
*/
goog.ui.ac.AutoComplete.prototype.cancelDelayedDismiss = function() {
// Under certain circumstances a cancel event occurs immediately prior to a
// delayedDismiss event that it should be cancelling. To handle this situation
// properly, a timer is used to stop that event.
// Using only the timer creates undesirable behavior when the cancel occurs
// less than 10ms before the delayed dismiss timout ends. If that happens the
// clearTimeout() will occur too late and have no effect.
if (!this.immediatelyCancelDelayedDismiss_()) {
window.setTimeout(goog.bind(this.immediatelyCancelDelayedDismiss_, this),
10);
}
};
/** @override */
goog.ui.ac.AutoComplete.prototype.disposeInternal = function() {
goog.ui.ac.AutoComplete.superClass_.disposeInternal.call(this);
delete this.inputToAnchorMap_;
this.renderer_.dispose();
this.selectionHandler_.dispose();
this.matcher_ = null;
};
/**
* Callback passed to Matcher when requesting matches for a token.
* This might be called synchronously, or asynchronously, or both, for
* any implementation of a Matcher.
* If the Matcher calls this back, with the same token this AutoComplete
* has set currently, then this will package the matching rows in object
* of the form
* <pre>
* {
* id: an integer ID unique to this result set and AutoComplete instance,
* data: the raw row data from Matcher
* }
* </pre>
*
* @param {string} matchedToken Token that corresponds with the rows.
* @param {!Array} rows Set of data that match the given token.
* @param {(boolean|goog.ui.ac.RenderOptions)=} opt_options If true,
* keeps the currently hilited (by index) element hilited. If false not.
* Otherwise a RenderOptions object.
* @private
*/
goog.ui.ac.AutoComplete.prototype.matchListener_ =
function(matchedToken, rows, opt_options) {
if (this.token_ != matchedToken) {
// Matcher's response token doesn't match current token.
// This is probably an async response that came in after
// the token was changed, so don't do anything.
return;
}
this.renderRows(rows, opt_options);
};
/**
* Renders the rows and adds highlighting.
* @param {!Array} rows Set of data that match the given token.
* @param {(boolean|goog.ui.ac.RenderOptions)=} opt_options If true,
* keeps the currently hilited (by index) element hilited. If false not.
* Otherwise a RenderOptions object.
*/
goog.ui.ac.AutoComplete.prototype.renderRows = function(rows, opt_options) {
// The optional argument should be a RenderOptions object. It can be a
// boolean for backwards compatibility, defaulting to false.
var optionsObj = goog.typeOf(opt_options) == 'object' && opt_options;
var preserveHilited =
optionsObj ? optionsObj.getPreserveHilited() : opt_options;
var indexToHilite = preserveHilited ? this.getIndexOfId(this.hiliteId_) : -1;
// Current token matches the matcher's response token.
this.firstRowId_ += this.rows_.length;
this.rows_ = rows;
var rendRows = [];
for (var i = 0; i < rows.length; ++i) {
rendRows.push({
id: this.getIdOfIndex_(i),
data: rows[i]
});
}
var anchor = null;
if (this.target_) {
anchor = this.inputToAnchorMap_[goog.getUid(this.target_)] || this.target_;
}
this.renderer_.setAnchorElement(anchor);
this.renderer_.renderRows(rendRows, this.token_, this.target_);
var autoHilite = this.autoHilite_;
if (optionsObj && optionsObj.getAutoHilite() !== undefined) {
autoHilite = optionsObj.getAutoHilite();
}
this.hiliteId_ = -1;
if ((autoHilite || indexToHilite >= 0) &&
rendRows.length != 0 &&
this.token_) {
if (indexToHilite >= 0) {
this.hiliteId(this.getIdOfIndex_(indexToHilite));
} else {
// Hilite the first non-disabled row.
this.hiliteNext();
}
}
this.dispatchEvent(goog.ui.ac.AutoComplete.EventType.SUGGESTIONS_UPDATE);
};
/**
* Gets the index corresponding to a particular id.
* @param {number} id A unique id for the row.
* @return {number} A valid index into rows_, or -1 if the id is invalid.
* @protected
*/
goog.ui.ac.AutoComplete.prototype.getIndexOfId = function(id) {
var index = id - this.firstRowId_;
if (index < 0 || index >= this.rows_.length) {
return -1;
}
return index;
};
/**
* Gets the id corresponding to a particular index. (Does no checking.)
* @param {number} index The index of a row in the result set.
* @return {number} The id that currently corresponds to that index.
* @private
*/
goog.ui.ac.AutoComplete.prototype.getIdOfIndex_ = function(index) {
return this.firstRowId_ + index;
};
/**
* Attach text areas or input boxes to the autocomplete by DOM reference. After
* elements are attached to the autocomplete, when a user types they will see
* the autocomplete drop down.
* @param {...Element} var_args Variable args: Input or text area elements to
* attach the autocomplete too.
*/
goog.ui.ac.AutoComplete.prototype.attachInputs = function(var_args) {
// Delegate to the input handler
var inputHandler = /** @type {goog.ui.ac.InputHandler} */
(this.selectionHandler_);
inputHandler.attachInputs.apply(inputHandler, arguments);
};
/**
* Detach text areas or input boxes to the autocomplete by DOM reference.
* @param {...Element} var_args Variable args: Input or text area elements to
* detach from the autocomplete.
*/
goog.ui.ac.AutoComplete.prototype.detachInputs = function(var_args) {
// Delegate to the input handler
var inputHandler = /** @type {goog.ui.ac.InputHandler} */
(this.selectionHandler_);
inputHandler.detachInputs.apply(inputHandler, arguments);
// Remove mapping from input to anchor if one exists.
goog.array.forEach(arguments, function(input) {
goog.object.remove(this.inputToAnchorMap_, goog.getUid(input));
}, this);
};
/**
* Attaches the autocompleter to a text area or text input element
* with an anchor element. The anchor element is the element the
* autocomplete box will be positioned against.
* @param {Element} inputElement The input element. May be 'textarea',
* text 'input' element, or any other element that exposes similar
* interface.
* @param {Element} anchorElement The anchor element.
*/
goog.ui.ac.AutoComplete.prototype.attachInputWithAnchor = function(
inputElement, anchorElement) {
this.inputToAnchorMap_[goog.getUid(inputElement)] = anchorElement;
this.attachInputs(inputElement);
};
/**
* Forces an update of the display.
* @param {boolean=} opt_force Whether to force an update.
*/
goog.ui.ac.AutoComplete.prototype.update = function(opt_force) {
var inputHandler = /** @type {goog.ui.ac.InputHandler} */
(this.selectionHandler_);
inputHandler.update(opt_force);
};
| 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 Utility methods supporting the autocomplete package.
*
* @see ../../demos/autocomplete-basic.html
*/
goog.provide('goog.ui.ac');
goog.require('goog.ui.ac.ArrayMatcher');
goog.require('goog.ui.ac.AutoComplete');
goog.require('goog.ui.ac.InputHandler');
goog.require('goog.ui.ac.Renderer');
/**
* Factory function for building a basic autocomplete widget that autocompletes
* an inputbox or text area from a data array.
* @param {Array} data Data array.
* @param {Element} input Input element or text area.
* @param {boolean=} opt_multi Whether to allow multiple entries separated with
* semi-colons or commas.
* @param {boolean=} opt_useSimilar use similar matches. e.g. "gost" => "ghost".
* @return {!goog.ui.ac.AutoComplete} A new autocomplete object.
*/
goog.ui.ac.createSimpleAutoComplete =
function(data, input, opt_multi, opt_useSimilar) {
var matcher = new goog.ui.ac.ArrayMatcher(data, !opt_useSimilar);
var renderer = new goog.ui.ac.Renderer();
var inputHandler = new goog.ui.ac.InputHandler(null, null, !!opt_multi);
var autoComplete = new goog.ui.ac.AutoComplete(
matcher, renderer, inputHandler);
inputHandler.attachAutoComplete(autoComplete);
inputHandler.attachInputs(input);
return autoComplete;
};
| 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 Class that retrieves autocomplete matches via an ajax call.
*
*/
goog.provide('goog.ui.ac.RemoteArrayMatcher');
goog.require('goog.Disposable');
goog.require('goog.Uri');
goog.require('goog.events');
goog.require('goog.json');
goog.require('goog.net.XhrIo');
/**
* An array matcher that requests matches via ajax.
* @param {string} url The Uri which generates the auto complete matches. The
* search term is passed to the server as the 'token' query param.
* @param {boolean=} opt_noSimilar If true, request that the server does not do
* similarity matches for the input token against the dictionary.
* The value is sent to the server as the 'use_similar' query param which is
* either "1" (opt_noSimilar==false) or "0" (opt_noSimilar==true).
* @constructor
* @extends {goog.Disposable}
*/
goog.ui.ac.RemoteArrayMatcher = function(url, opt_noSimilar) {
goog.Disposable.call(this);
/**
* The base URL for the ajax call. The token and max_matches are added as
* query params.
* @type {string}
* @private
*/
this.url_ = url;
/**
* Whether similar matches should be found as well. This is sent as a hint
* to the server only.
* @type {boolean}
* @private
*/
this.useSimilar_ = !opt_noSimilar;
/**
* The XhrIo object used for making remote requests. When a new request
* is made, the current one is aborted and the new one sent.
* @type {goog.net.XhrIo}
* @private
*/
this.xhr_ = new goog.net.XhrIo();
};
goog.inherits(goog.ui.ac.RemoteArrayMatcher, goog.Disposable);
/**
* The HTTP send method (GET, POST) to use when making the ajax call.
* @type {string}
* @private
*/
goog.ui.ac.RemoteArrayMatcher.prototype.method_ = 'GET';
/**
* Data to submit during a POST.
* @type {string|undefined}
* @private
*/
goog.ui.ac.RemoteArrayMatcher.prototype.content_ = undefined;
/**
* Headers to send with every HTTP request.
* @type {Object|goog.structs.Map}
* @private
*/
goog.ui.ac.RemoteArrayMatcher.prototype.headers_ = null;
/**
* Key to the listener on XHR. Used to clear previous listeners.
* @type {goog.events.Key}
* @private
*/
goog.ui.ac.RemoteArrayMatcher.prototype.lastListenerKey_ = null;
/**
* Set the send method ("GET", "POST").
* @param {string} method The send method; default: GET.
*/
goog.ui.ac.RemoteArrayMatcher.prototype.setMethod = function(method) {
this.method_ = method;
};
/**
* Set the post data.
* @param {string} content Post data.
*/
goog.ui.ac.RemoteArrayMatcher.prototype.setContent = function(content) {
this.content_ = content;
};
/**
* Set the HTTP headers.
* @param {Object|goog.structs.Map} headers Map of headers to add to the
* request.
*/
goog.ui.ac.RemoteArrayMatcher.prototype.setHeaders = function(headers) {
this.headers_ = headers;
};
/**
* Set the timeout interval.
* @param {number} interval Number of milliseconds after which an
* incomplete request will be aborted; 0 means no timeout is set.
*/
goog.ui.ac.RemoteArrayMatcher.prototype.setTimeoutInterval =
function(interval) {
this.xhr_.setTimeoutInterval(interval);
};
/**
* Builds a complete GET-style URL, given the base URI and autocomplete related
* parameter values.
* <b>Override this to build any customized lookup URLs.</b>
* <b>Can be used to change request method and any post content as well.</b>
* @param {string} uri The base URI of the request target.
* @param {string} token Current token in autocomplete.
* @param {number} maxMatches Maximum number of matches required.
* @param {boolean} useSimilar A hint to the server.
* @param {string=} opt_fullString Complete text in the input element.
* @return {?string} The complete url. Return null if no request should be sent.
* @protected
*/
goog.ui.ac.RemoteArrayMatcher.prototype.buildUrl = function(uri,
token, maxMatches, useSimilar, opt_fullString) {
var url = new goog.Uri(uri);
url.setParameterValue('token', token);
url.setParameterValue('max_matches', String(maxMatches));
url.setParameterValue('use_similar', String(Number(useSimilar)));
return url.toString();
};
/**
* Returns whether the suggestions should be updated?
* <b>Override this to prevent updates eg - when token is empty.</b>
* @param {string} uri The base URI of the request target.
* @param {string} token Current token in autocomplete.
* @param {number} maxMatches Maximum number of matches required.
* @param {boolean} useSimilar A hint to the server.
* @param {string=} opt_fullString Complete text in the input element.
* @return {boolean} Whether new matches be requested.
* @protected
*/
goog.ui.ac.RemoteArrayMatcher.prototype.shouldRequestMatches =
function(uri, token, maxMatches, useSimilar, opt_fullString) {
return true;
};
/**
* Parses and retrieves the array of suggestions from XHR response.
* <b>Override this if the response is not a simple JSON array.</b>
* @param {string} responseText The XHR response text.
* @return {Array.<string>} The array of suggestions.
* @protected
*/
goog.ui.ac.RemoteArrayMatcher.prototype.parseResponseText = function(
responseText) {
var matches = [];
// If there is no response text, unsafeParse will throw a syntax error.
if (responseText) {
/** @preserveTry */
try {
matches = goog.json.unsafeParse(responseText);
} catch (exception) {
}
}
return /** @type {Array.<string>} */ (matches);
};
/**
* Handles the XHR response.
* @param {string} token The XHR autocomplete token.
* @param {Function} matchHandler The AutoComplete match handler.
* @param {goog.events.Event} event The XHR success event.
*/
goog.ui.ac.RemoteArrayMatcher.prototype.xhrCallback = function(token,
matchHandler, event) {
var text = event.target.getResponseText();
matchHandler(token, this.parseResponseText(text));
};
/**
* Retrieve a set of matching rows from the server via ajax.
* @param {string} token The text that should be matched; passed to the server
* as the 'token' query param.
* @param {number} maxMatches The maximum number of matches requested from the
* server; passed as the 'max_matches' query param. The server is
* responsible for limiting the number of matches that are returned.
* @param {Function} matchHandler Callback to execute on the result after
* matching.
* @param {string=} opt_fullString The full string from the input box.
*/
goog.ui.ac.RemoteArrayMatcher.prototype.requestMatchingRows =
function(token, maxMatches, matchHandler, opt_fullString) {
if (!this.shouldRequestMatches(this.url_, token, maxMatches, this.useSimilar_,
opt_fullString)) {
return;
}
// Set the query params on the URL.
var url = this.buildUrl(this.url_, token, maxMatches, this.useSimilar_,
opt_fullString);
if (!url) {
// Do nothing if there is no URL.
return;
}
// The callback evals the server response and calls the match handler on
// the array of matches.
var callback = goog.bind(this.xhrCallback, this, token, matchHandler);
// Abort the current request and issue the new one; prevent requests from
// being queued up by the browser with a slow server
if (this.xhr_.isActive()) {
this.xhr_.abort();
}
// This ensures if previous XHR is aborted or ends with error, the
// corresponding success-callbacks are cleared.
if (this.lastListenerKey_) {
goog.events.unlistenByKey(this.lastListenerKey_);
}
// Listen once ensures successful callback gets cleared by itself.
this.lastListenerKey_ = goog.events.listenOnce(this.xhr_,
goog.net.EventType.SUCCESS, callback);
this.xhr_.send(url, this.method_, this.content_, this.headers_);
};
/** @override */
goog.ui.ac.RemoteArrayMatcher.prototype.disposeInternal = function() {
this.xhr_.dispose();
goog.ui.ac.RemoteArrayMatcher.superClass_.disposeInternal.call(
this);
};
| 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 rendering the results of an auto complete and
* allow the user to select an row.
*
*/
goog.provide('goog.ui.ac.Renderer');
goog.provide('goog.ui.ac.Renderer.CustomRenderer');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.Role');
goog.require('goog.a11y.aria.State');
goog.require('goog.array');
goog.require('goog.dispose');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.events.Event');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.fx.dom.FadeInAndShow');
goog.require('goog.fx.dom.FadeOutAndHide');
goog.require('goog.positioning');
goog.require('goog.positioning.Corner');
goog.require('goog.positioning.Overflow');
goog.require('goog.string');
goog.require('goog.style');
goog.require('goog.ui.IdGenerator');
goog.require('goog.ui.ac.AutoComplete.EventType');
goog.require('goog.userAgent');
/**
* Class for rendering the results of an auto-complete in a drop down list.
*
* @constructor
* @param {Element=} opt_parentNode optional reference to the parent element
* that will hold the autocomplete elements. goog.dom.getDocument().body
* will be used if this is null.
* @param {?({renderRow}|{render})=} opt_customRenderer Custom full renderer to
* render each row. Should be something with a renderRow or render method.
* @param {boolean=} opt_rightAlign Determines if the autocomplete will always
* be right aligned. False by default.
* @param {boolean=} opt_useStandardHighlighting Determines if standard
* highlighting should be applied to each row of data. Standard highlighting
* bolds every matching substring for a given token in each row. True by
* default.
* @extends {goog.events.EventTarget}
*/
goog.ui.ac.Renderer = function(opt_parentNode, opt_customRenderer,
opt_rightAlign, opt_useStandardHighlighting) {
goog.base(this);
/**
* Reference to the parent element that will hold the autocomplete elements
* @type {Element}
* @private
*/
this.parent_ = opt_parentNode || goog.dom.getDocument().body;
/**
* Dom helper for the parent element's document.
* @type {goog.dom.DomHelper}
* @private
*/
this.dom_ = goog.dom.getDomHelper(this.parent_);
/**
* Whether to reposition the autocomplete UI below the target node
* @type {boolean}
* @private
*/
this.reposition_ = !opt_parentNode;
/**
* Reference to the main element that controls the rendered autocomplete
* @type {Element}
* @private
*/
this.element_ = null;
/**
* The current token that has been entered
* @type {string}
* @private
*/
this.token_ = '';
/**
* Array used to store the current set of rows being displayed
* @type {Array}
* @private
*/
this.rows_ = [];
/**
* Array of the node divs that hold each result that is being displayed.
* @type {Array.<Element>}
* @protected
* @suppress {underscore}
*/
this.rowDivs_ = [];
/**
* The index of the currently highlighted row
* @type {number}
* @protected
* @suppress {underscore}
*/
this.hilitedRow_ = -1;
/**
* The time that the rendering of the menu rows started
* @type {number}
* @protected
* @suppress {underscore}
*/
this.startRenderingRows_ = -1;
/**
* Store the current state for the renderer
* @type {boolean}
* @private
*/
this.visible_ = false;
/**
* Classname for the main element
* @type {string}
*/
this.className = goog.getCssName('ac-renderer');
/**
* Classname for row divs
* @type {string}
*/
this.rowClassName = goog.getCssName('ac-row');
// TODO(gboyer): Remove this as soon as we remove references and ensure that
// no groups are pushing javascript using this.
/**
* The old class name for active row. This name is deprecated because its
* name is generic enough that a typical implementation would require a
* descendant selector.
* Active row will have rowClassName & activeClassName &
* legacyActiveClassName.
* @type {string}
* @private
*/
this.legacyActiveClassName_ = goog.getCssName('active');
/**
* Class name for active row div.
* Active row will have rowClassName & activeClassName &
* legacyActiveClassName.
* @type {string}
*/
this.activeClassName = goog.getCssName('ac-active');
/**
* Class name for the bold tag highlighting the matched part of the text.
* @type {string}
*/
this.highlightedClassName = goog.getCssName('ac-highlighted');
/**
* Custom full renderer
* @type {?({renderRow}|{render})}
* @private
*/
this.customRenderer_ = opt_customRenderer || null;
/**
* Flag to indicate whether standard highlighting should be applied.
* this is set to true if left unspecified to retain existing
* behaviour for autocomplete clients
* @type {boolean}
* @private
*/
this.useStandardHighlighting_ = opt_useStandardHighlighting != null ?
opt_useStandardHighlighting : true;
/**
* Flag to indicate whether matches should be done on whole words instead
* of any string.
* @type {boolean}
* @private
*/
this.matchWordBoundary_ = true;
/**
* Flag to set all tokens as highlighted in the autocomplete row.
* @type {boolean}
* @private
*/
this.highlightAllTokens_ = false;
/**
* Determines if the autocomplete will always be right aligned
* @type {boolean}
* @private
*/
this.rightAlign_ = !!opt_rightAlign;
/**
* Whether to align with top of target field
* @type {boolean}
* @private
*/
this.topAlign_ = false;
/**
* Duration (in msec) of fade animation when menu is shown/hidden.
* Setting to 0 (default) disables animation entirely.
* @type {number}
* @private
*/
this.menuFadeDuration_ = 0;
/**
* Animation in progress, if any.
* @type {goog.fx.Animation|undefined}
*/
this.animation_;
};
goog.inherits(goog.ui.ac.Renderer, goog.events.EventTarget);
/**
* The anchor element to position the rendered autocompleter against.
* @type {Element}
* @private
*/
goog.ui.ac.Renderer.prototype.anchorElement_;
/**
* The element on which to base the width of the autocomplete.
* @type {Node}
* @private
*/
goog.ui.ac.Renderer.prototype.widthProvider_;
/**
* The delay before mouseover events are registered, in milliseconds
* @type {number}
* @const
*/
goog.ui.ac.Renderer.DELAY_BEFORE_MOUSEOVER = 300;
/**
* Gets the renderer's element.
* @return {Element} The main element that controls the rendered autocomplete.
*/
goog.ui.ac.Renderer.prototype.getElement = function() {
return this.element_;
};
/**
* Sets the width provider element. The provider is only used on redraw and as
* such will not automatically update on resize.
* @param {Node} widthProvider The element whose width should be mirrored.
*/
goog.ui.ac.Renderer.prototype.setWidthProvider = function(widthProvider) {
this.widthProvider_ = widthProvider;
};
/**
* Set whether to align autocomplete to top of target element
* @param {boolean} align If true, align to top.
*/
goog.ui.ac.Renderer.prototype.setTopAlign = function(align) {
this.topAlign_ = align;
};
/**
* @return {boolean} Whether we should be aligning to the top of
* the target element.
*/
goog.ui.ac.Renderer.prototype.getTopAlign = function() {
return this.topAlign_;
};
/**
* Set whether to align autocomplete to the right of the target element.
* @param {boolean} align If true, align to right.
*/
goog.ui.ac.Renderer.prototype.setRightAlign = function(align) {
this.rightAlign_ = align;
};
/**
* @return {boolean} Whether the autocomplete menu should be right aligned.
*/
goog.ui.ac.Renderer.prototype.getRightAlign = function() {
return this.rightAlign_;
};
/**
* Set whether or not standard highlighting should be used when rendering rows.
* @param {boolean} useStandardHighlighting true if standard highlighting used.
*/
goog.ui.ac.Renderer.prototype.setUseStandardHighlighting =
function(useStandardHighlighting) {
this.useStandardHighlighting_ = useStandardHighlighting;
};
/**
* @param {boolean} matchWordBoundary Determines whether matches should be
* higlighted only when the token matches text at a whole-word boundary.
* True by default.
*/
goog.ui.ac.Renderer.prototype.setMatchWordBoundary =
function(matchWordBoundary) {
this.matchWordBoundary_ = matchWordBoundary;
};
/**
* Set whether or not to highlight all matching tokens rather than just the
* first.
* @param {boolean} highlightAllTokens Whether to highlight all matching tokens
* rather than just the first.
*/
goog.ui.ac.Renderer.prototype.setHighlightAllTokens =
function(highlightAllTokens) {
this.highlightAllTokens_ = highlightAllTokens;
};
/**
* Sets the duration (in msec) of the fade animation when menu is shown/hidden.
* Setting to 0 (default) disables animation entirely.
* @param {number} duration Duration (in msec) of the fade animation (or 0 for
* no animation).
*/
goog.ui.ac.Renderer.prototype.setMenuFadeDuration = function(duration) {
this.menuFadeDuration_ = duration;
};
/**
* Sets the anchor element for the subsequent call to renderRows.
* @param {Element} anchor The anchor element.
*/
goog.ui.ac.Renderer.prototype.setAnchorElement = function(anchor) {
this.anchorElement_ = anchor;
};
/**
* @return {Element} The anchor element.
* @protected
*/
goog.ui.ac.Renderer.prototype.getAnchorElement = function() {
return this.anchorElement_;
};
/**
* Render the autocomplete UI
*
* @param {Array} rows Matching UI rows.
* @param {string} token Token we are currently matching against.
* @param {Element=} opt_target Current HTML node, will position popup beneath
* this node.
*/
goog.ui.ac.Renderer.prototype.renderRows = function(rows, token, opt_target) {
this.token_ = token;
this.rows_ = rows;
this.hilitedRow_ = -1;
this.startRenderingRows_ = goog.now();
this.target_ = opt_target;
this.rowDivs_ = [];
this.redraw();
};
/**
* Hide the object.
*/
goog.ui.ac.Renderer.prototype.dismiss = function() {
if (this.target_) {
goog.a11y.aria.setActiveDescendant(this.target_, null);
}
if (this.visible_) {
this.visible_ = false;
// Clear ARIA popup role for the target input box.
if (this.target_) {
goog.a11y.aria.setState(this.target_,
goog.a11y.aria.State.HASPOPUP,
false);
}
if (this.menuFadeDuration_ > 0) {
goog.dispose(this.animation_);
this.animation_ = new goog.fx.dom.FadeOutAndHide(this.element_,
this.menuFadeDuration_);
this.animation_.play();
} else {
goog.style.setElementShown(this.element_, false);
}
}
};
/**
* Show the object.
*/
goog.ui.ac.Renderer.prototype.show = function() {
if (!this.visible_) {
this.visible_ = true;
// Set ARIA roles and states for the target input box.
if (this.target_) {
goog.a11y.aria.setRole(this.target_,
goog.a11y.aria.Role.COMBOBOX);
goog.a11y.aria.setState(this.target_,
goog.a11y.aria.State.AUTOCOMPLETE,
'list');
goog.a11y.aria.setState(this.target_,
goog.a11y.aria.State.HASPOPUP,
true);
}
if (this.menuFadeDuration_ > 0) {
goog.dispose(this.animation_);
this.animation_ = new goog.fx.dom.FadeInAndShow(this.element_,
this.menuFadeDuration_);
this.animation_.play();
} else {
goog.style.setElementShown(this.element_, true);
}
}
};
/**
* @return {boolean} True if the object is visible.
*/
goog.ui.ac.Renderer.prototype.isVisible = function() {
return this.visible_;
};
/**
* Sets the 'active' class of the nth item.
* @param {number} index Index of the item to highlight.
*/
goog.ui.ac.Renderer.prototype.hiliteRow = function(index) {
var rowDiv = index >= 0 && index < this.rowDivs_.length ?
this.rowDivs_[index] : undefined;
var evtObj = {type: goog.ui.ac.AutoComplete.EventType.ROW_HILITE,
rowNode: rowDiv};
if (this.dispatchEvent(evtObj)) {
this.hiliteNone();
this.hilitedRow_ = index;
if (rowDiv) {
goog.dom.classes.add(rowDiv, this.activeClassName,
this.legacyActiveClassName_);
if (this.target_) {
goog.a11y.aria.setActiveDescendant(this.target_, rowDiv);
}
goog.style.scrollIntoContainerView(rowDiv, this.element_);
}
}
};
/**
* Removes the 'active' class from the currently selected row.
*/
goog.ui.ac.Renderer.prototype.hiliteNone = function() {
if (this.hilitedRow_ >= 0) {
goog.dom.classes.remove(this.rowDivs_[this.hilitedRow_],
this.activeClassName, this.legacyActiveClassName_);
}
};
/**
* Sets the 'active' class of the item with a given id.
* @param {number} id Id of the row to hilight. If id is -1 then no rows get
* hilited.
*/
goog.ui.ac.Renderer.prototype.hiliteId = function(id) {
if (id == -1) {
this.hiliteRow(-1);
} else {
for (var i = 0; i < this.rows_.length; i++) {
if (this.rows_[i].id == id) {
this.hiliteRow(i);
return;
}
}
}
};
/**
* Sets CSS classes on autocomplete conatainer element.
*
* @param {Element} elt The container element.
* @private
*/
goog.ui.ac.Renderer.prototype.setMenuClasses_ = function(elt) {
goog.dom.classes.add(elt, this.className);
};
/**
* If the main HTML element hasn't been made yet, creates it and appends it
* to the parent.
* @private
*/
goog.ui.ac.Renderer.prototype.maybeCreateElement_ = function() {
if (!this.element_) {
// Make element and add it to the parent
var el = this.dom_.createDom('div', {style: 'display:none'});
this.element_ = el;
this.setMenuClasses_(el);
goog.a11y.aria.setRole(el, goog.a11y.aria.Role.LISTBOX);
el.id = goog.ui.IdGenerator.getInstance().getNextUniqueId();
this.dom_.appendChild(this.parent_, el);
// Add this object as an event handler
goog.events.listen(el, goog.events.EventType.CLICK,
this.handleClick_, false, this);
goog.events.listen(el, goog.events.EventType.MOUSEDOWN,
this.handleMouseDown_, false, this);
goog.events.listen(el, goog.events.EventType.MOUSEOVER,
this.handleMouseOver_, false, this);
}
};
/**
* Redraw (or draw if this is the first call) the rendered auto-complete drop
* down.
*/
goog.ui.ac.Renderer.prototype.redraw = function() {
// Create the element if it doesn't yet exist
this.maybeCreateElement_();
// For top aligned with target (= bottom aligned element),
// we need to hide and then add elements while hidden to prevent
// visible repositioning
if (this.topAlign_) {
this.element_.style.visibility = 'hidden';
}
if (this.widthProvider_) {
var width = this.widthProvider_.clientWidth + 'px';
this.element_.style.minWidth = width;
}
// Remove the current child nodes
this.rowDivs_.length = 0;
this.dom_.removeChildren(this.element_);
// Generate the new rows (use forEach so we can change rows_ from an
// array to a different datastructure if required)
if (this.customRenderer_ && this.customRenderer_.render) {
this.customRenderer_.render(this, this.element_, this.rows_, this.token_);
} else {
var curRow = null;
goog.array.forEach(this.rows_, function(row) {
row = this.renderRowHtml(row, this.token_);
if (this.topAlign_) {
// Aligned with top of target = best match at bottom
this.element_.insertBefore(row, curRow);
} else {
this.dom_.appendChild(this.element_, row);
}
curRow = row;
}, this);
}
// Don't show empty result sets
if (this.rows_.length == 0) {
this.dismiss();
return;
} else {
this.show();
}
this.reposition();
// Make the autocompleter unselectable, so that it
// doesn't steal focus from the input field when clicked.
goog.style.setUnselectable(this.element_, true);
};
/**
* @return {goog.positioning.Corner} The anchor corner to position the popup at.
* @protected
*/
goog.ui.ac.Renderer.prototype.getAnchorCorner = function() {
var anchorCorner = this.rightAlign_ ?
goog.positioning.Corner.BOTTOM_RIGHT :
goog.positioning.Corner.BOTTOM_LEFT;
if (this.topAlign_) {
anchorCorner = goog.positioning.flipCornerVertical(anchorCorner);
}
return anchorCorner;
};
/**
* Repositions the auto complete popup relative to the location node, if it
* exists and the auto position has been set.
*/
goog.ui.ac.Renderer.prototype.reposition = function() {
if (this.target_ && this.reposition_) {
var anchorElement = this.anchorElement_ || this.target_;
var anchorCorner = this.getAnchorCorner();
goog.positioning.positionAtAnchor(
anchorElement, anchorCorner,
this.element_, goog.positioning.flipCornerVertical(anchorCorner),
null, null, goog.positioning.Overflow.ADJUST_X_EXCEPT_OFFSCREEN);
if (this.topAlign_) {
// This flickers, but is better than the alternative of positioning
// in the wrong place and then moving.
this.element_.style.visibility = 'visible';
}
}
};
/**
* Sets whether the renderer should try to determine where to position the
* drop down.
* @param {boolean} auto Whether to autoposition the drop down.
*/
goog.ui.ac.Renderer.prototype.setAutoPosition = function(auto) {
this.reposition_ = auto;
};
/**
* @return {boolean} Whether the drop down will be autopositioned.
* @protected
*/
goog.ui.ac.Renderer.prototype.getAutoPosition = function() {
return this.reposition_;
};
/**
* @return {Element} The target element.
* @protected
*/
goog.ui.ac.Renderer.prototype.getTarget = function() {
return this.target_;
};
/**
* Disposes of the renderer and its associated HTML.
* @override
* @protected
*/
goog.ui.ac.Renderer.prototype.disposeInternal = function() {
if (this.element_) {
goog.events.unlisten(this.element_, goog.events.EventType.CLICK,
this.handleClick_, false, this);
goog.events.unlisten(this.element_, goog.events.EventType.MOUSEDOWN,
this.handleMouseDown_, false, this);
goog.events.unlisten(this.element_, goog.events.EventType.MOUSEOVER,
this.handleMouseOver_, false, this);
this.dom_.removeNode(this.element_);
this.element_ = null;
this.visible_ = false;
}
goog.dispose(this.animation_);
this.parent_ = null;
goog.base(this, 'disposeInternal');
};
/**
* Generic function that takes a row and renders a DOM structure for that row.
*
* Normally this will only be matching a maximum of 20 or so items. Even with
* 40 rows, DOM this building is fine.
*
* @param {Object} row Object representing row.
* @param {string} token Token to highlight.
* @param {Node} node The node to render into.
* @private
*/
goog.ui.ac.Renderer.prototype.renderRowContents_ =
function(row, token, node) {
node.innerHTML = goog.string.htmlEscape(row.data.toString());
};
/**
* Goes through a node and all of its child nodes, replacing HTML text that
* matches a token with <b>token</b>.
*
* @param {Node} node Node to match.
* @param {string|Array.<string>} tokenOrArray Token to match or array of tokens
* to match. By default, only the first match will be highlighted. If
* highlightAllTokens is set, then all tokens appearing at the start of a
* word, in whatever order and however many times, will be highlighted.
* @private
*/
goog.ui.ac.Renderer.prototype.hiliteMatchingText_ =
function(node, tokenOrArray) {
if (node.nodeType == goog.dom.NodeType.TEXT) {
var rest = null;
if (goog.isArray(tokenOrArray) &&
tokenOrArray.length > 1 &&
!this.highlightAllTokens_) {
rest = goog.array.slice(tokenOrArray, 1);
}
var token = this.getTokenRegExp_(tokenOrArray);
if (token.length == 0) return;
var text = node.nodeValue;
// Create a regular expression to match a token at the beginning of a line
// or preceeded by non-alpha-numeric characters
// NOTE(user): When using word matches, this used to have
// a (^|\\W+) clause where it now has \\b but it caused various
// browsers to hang on really long strings. It is also
// excessive, because .*?\W+ is the same as .*?\b since \b already
// checks that the character before the token is a non-word character
// (the only time the regexp is different is if token begins with a
// non-word character), and ^ matches the start of the line or following
// a line terminator character, which is also \W. The initial group cannot
// just be .*? as it will miss line terminators (which is what the \W+
// clause used to match). Instead we use [\s\S] to match every character,
// including line terminators.
var re = this.matchWordBoundary_ ?
new RegExp('([\\s\\S]*?)\\b(' + token + ')', 'gi') :
new RegExp('([\\s\\S]*?)(' + token + ')', 'gi');
var textNodes = [];
var lastIndex = 0;
// Find all matches
// Note: text.split(re) has inconsistencies between IE and FF, so
// manually recreated the logic
var match = re.exec(text);
var numMatches = 0;
while (match) {
numMatches++;
textNodes.push(match[1]);
textNodes.push(match[2]);
lastIndex = re.lastIndex;
match = re.exec(text);
}
textNodes.push(text.substring(lastIndex));
// Replace the tokens with bolded text. Each pair of textNodes
// (starting at index idx) includes a node of text before the bolded
// token, and a node (at idx + 1) consisting of what should be
// enclosed in bold tags.
if (textNodes.length > 1) {
var maxNumToBold = !this.highlightAllTokens_ ? 1 : numMatches;
for (var i = 0; i < maxNumToBold; i++) {
var idx = 2 * i;
node.nodeValue = textNodes[idx];
var boldTag = this.dom_.createElement('b');
boldTag.className = this.highlightedClassName;
this.dom_.appendChild(boldTag,
this.dom_.createTextNode(textNodes[idx + 1]));
boldTag = node.parentNode.insertBefore(boldTag, node.nextSibling);
node.parentNode.insertBefore(this.dom_.createTextNode(''),
boldTag.nextSibling);
node = boldTag.nextSibling;
}
// Append the remaining text nodes to the end.
var remainingTextNodes = goog.array.slice(textNodes, maxNumToBold * 2);
node.nodeValue = remainingTextNodes.join('');
} else if (rest) {
this.hiliteMatchingText_(node, rest);
}
} else {
var child = node.firstChild;
while (child) {
var nextChild = child.nextSibling;
this.hiliteMatchingText_(child, tokenOrArray);
child = nextChild;
}
}
};
/**
* Transforms a token into a string ready to be put into the regular expression
* in hiliteMatchingText_.
* @param {string|Array.<string>} tokenOrArray The token or array to get the
* regex string from.
* @return {string} The regex-ready token.
* @private
*/
goog.ui.ac.Renderer.prototype.getTokenRegExp_ = function(tokenOrArray) {
var token = '';
if (!tokenOrArray) {
return token;
}
if (goog.isArray(tokenOrArray)) {
// Remove invalid tokens from the array, which may leave us with nothing.
tokenOrArray = goog.array.filter(tokenOrArray, function(str) {
return !goog.string.isEmptySafe(str);
});
}
// If highlighting all tokens, join them with '|' so the regular expression
// will match on any of them.
if (this.highlightAllTokens_) {
if (goog.isArray(tokenOrArray)) {
var tokenArray = goog.array.map(tokenOrArray, goog.string.regExpEscape);
token = tokenArray.join('|');
} else {
// Remove excess whitespace from the string so bars will separate valid
// tokens in the regular expression.
token = goog.string.collapseWhitespace(tokenOrArray);
token = goog.string.regExpEscape(token);
token = token.replace(/ /g, '|');
}
} else {
// Not highlighting all matching tokens. If tokenOrArray is a string, use
// that as the token. If it is an array, use the first element in the
// array.
// TODO(user): why is this this way?. We should match against all
// tokens in the array, but only accept the first match.
if (goog.isArray(tokenOrArray)) {
token = tokenOrArray.length > 0 ?
goog.string.regExpEscape(tokenOrArray[0]) : '';
} else {
// For the single-match string token, we refuse to match anything if
// the string begins with a non-word character, as matches by definition
// can only occur at the start of a word. (This also handles the
// goog.string.isEmptySafe(tokenOrArray) case.)
if (!/^\W/.test(tokenOrArray)) {
token = goog.string.regExpEscape(tokenOrArray);
}
}
}
return token;
};
/**
* Render a row by creating a div and then calling row rendering callback or
* default row handler
*
* @param {Object} row Object representing row.
* @param {string} token Token to highlight.
* @return {Element} An element with the rendered HTML.
*/
goog.ui.ac.Renderer.prototype.renderRowHtml = function(row, token) {
// Create and return the node
var node = this.dom_.createDom('div', {
className: this.rowClassName,
id: goog.ui.IdGenerator.getInstance().getNextUniqueId()
});
goog.a11y.aria.setRole(node, goog.a11y.aria.Role.OPTION);
if (this.customRenderer_ && this.customRenderer_.renderRow) {
this.customRenderer_.renderRow(row, token, node);
} else {
this.renderRowContents_(row, token, node);
}
if (token && this.useStandardHighlighting_) {
this.hiliteMatchingText_(node, token);
}
goog.dom.classes.add(node, this.rowClassName);
this.rowDivs_.push(node);
return node;
};
/**
* Given an event target looks up through the parents till it finds a div. Once
* found it will then look to see if that is one of the childnodes, if it is
* then the index is returned, otherwise -1 is returned.
* @param {Element} et HtmlElement.
* @return {number} Index corresponding to event target.
* @private
*/
goog.ui.ac.Renderer.prototype.getRowFromEventTarget_ = function(et) {
while (et && et != this.element_ &&
!goog.dom.classes.has(et, this.rowClassName)) {
et = /** @type {Element} */ (et.parentNode);
}
return et ? goog.array.indexOf(this.rowDivs_, et) : -1;
};
/**
* Handle the click events. These are redirected to the AutoComplete object
* which then makes a callback to select the correct row.
* @param {goog.events.Event} e Browser event object.
* @private
*/
goog.ui.ac.Renderer.prototype.handleClick_ = function(e) {
var index = this.getRowFromEventTarget_(/** @type {Element} */ (e.target));
if (index >= 0) {
this.dispatchEvent(/** @lends {goog.events.Event.prototype} */ ({
type: goog.ui.ac.AutoComplete.EventType.SELECT,
row: this.rows_[index].id
}));
}
e.stopPropagation();
};
/**
* Handle the mousedown event and prevent the AC from losing focus.
* @param {goog.events.Event} e Browser event object.
* @private
*/
goog.ui.ac.Renderer.prototype.handleMouseDown_ = function(e) {
e.stopPropagation();
e.preventDefault();
};
/**
* Handle the mousing events. These are redirected to the AutoComplete object
* which then makes a callback to set the correctly highlighted row. This is
* because the AutoComplete can move the focus as well, and there is no sense
* duplicating the code
* @param {goog.events.Event} e Browser event object.
* @private
*/
goog.ui.ac.Renderer.prototype.handleMouseOver_ = function(e) {
var index = this.getRowFromEventTarget_(/** @type {Element} */ (e.target));
if (index >= 0) {
if ((goog.now() - this.startRenderingRows_) <
goog.ui.ac.Renderer.DELAY_BEFORE_MOUSEOVER) {
return;
}
this.dispatchEvent({
type: goog.ui.ac.AutoComplete.EventType.HILITE,
row: this.rows_[index].id
});
}
};
/**
* Class allowing different implementations to custom render the autocomplete.
* Extending classes should override the render function.
* @constructor
*/
goog.ui.ac.Renderer.CustomRenderer = function() {
};
/**
* Renders the autocomplete box. May be set to null.
* @type {function(goog.ui.ac.Renderer, Element, Array, string)|
* null|undefined}
* param {goog.ui.ac.Renderer} renderer The autocomplete renderer.
* param {Element} element The main element that controls the rendered
* autocomplete.
* param {Array} rows The current set of rows being displayed.
* param {string} token The current token that has been entered.
*/
goog.ui.ac.Renderer.CustomRenderer.prototype.render = function(
renderer, element, rows, token) {
};
/**
* Generic function that takes a row and renders a DOM structure for that row.
* @param {Object} row Object representing row.
* @param {string} token Token to highlight.
* @param {Node} node The node to render into.
*/
goog.ui.ac.Renderer.CustomRenderer.prototype.renderRow =
function(row, token, node) {
};
| 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 the interactions between an
* auto-complete object and a text-input or textarea.
*
* IME note:
*
* We used to suspend autocomplete while there are IME preedit characters, but
* now for parity with Search we do not. We still detect the beginning and end
* of IME entry because we need to listen to more events while an IME commit is
* happening, but we update continuously as the user types.
*
* IMEs vary across operating systems, browsers, and even input languages. This
* class tries to handle IME for:
* - Windows x {FF3, IE7, Chrome} x MS IME 2002 (Japanese)
* - Mac x {FF3, Safari3} x Kotoeri (Japanese)
* - Linux x {FF3} x UIM + Anthy (Japanese)
*
* TODO(user): We cannot handle {Mac, Linux} x FF3 correctly.
* TODO(user): We need to support Windows x Google IME.
*
* This class was tested with hiragana input. The event sequence when inputting
* 'ai<enter>' with IME on (which commits two characters) is as follows:
*
* Notation: [key down code, key press, key up code]
* key code or +: event fired
* -: event not fired
*
* - Win/FF3: [WIN_IME, +, A], [-, -, ENTER]
* Note: No events are fired for 'i'.
*
* - Win/IE7: [WIN_IME, -, A], [WIN_IME, -, I], [WIN_IME, -, ENTER]
*
* - Win/Chrome: Same as Win/IE7
*
* - Mac/FF3: [A, -, A], [I, -, I], [ENTER, -, ENTER]
*
* - Mac/Safari3: Same as Win/IE7
*
* - Linux/FF3: No events are generated.
*
* With IME off,
*
* - ALL: [A, +, A], [I, +, I], [ENTER, +, ENTER]
* Note: Key code of key press event varies across configuration.
*
* With Microsoft Pinyin IME 3.0 (Simplified Chinese),
*
* - Win/IE7: Same as Win/IE7 with MS IME 2002 (Japanese)
*
* The issue with this IME is that the key sequence that ends preedit is not
* a single ENTER key up.
* - ENTER key up following either ENTER or SPACE ends preedit.
* - SPACE key up following even number of LEFT, RIGHT, or SPACE (any
* combination) ends preedit.
* TODO(user): We only support SPACE-then-ENTER sequence.
* TODO(mpd): With the change to autocomplete during IME, this might not be an
* issue. Remove this comment once tested.
*
* With Microsoft Korean IME 2002,
*
* - Win/IE7: Same as Win/IE7 with MS IME 2002 (Japanese), but there is no
* sequence that ends the preedit.
*
* The following is the algorithm we use to detect IME preedit:
*
* - WIN_IME key down starts predit.
* - (1) ENTER key up or (2) CTRL-M key up ends preedit.
* - Any key press not immediately following WIN_IME key down signifies that
* preedit has ended.
*
* If you need to change this algorithm, please note the OS, browser, language,
* and behavior above so that we can avoid regressions. Contact mpd or yuzo
* if you have questions or concerns.
*
*/
goog.provide('goog.ui.ac.InputHandler');
goog.require('goog.Disposable');
goog.require('goog.Timer');
goog.require('goog.a11y.aria');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.selection');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.events.KeyHandler');
goog.require('goog.events.KeyHandler.EventType');
goog.require('goog.string');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');
/**
* Class for managing the interaction between an auto-complete object and a
* text-input or textarea.
*
* @param {?string=} opt_separators Separators to split multiple entries.
* If none passed, uses ',' and ';'.
* @param {?string=} opt_literals Characters used to delimit text literals.
* @param {?boolean=} opt_multi Whether to allow multiple entries
* (Default: true).
* @param {?number=} opt_throttleTime Number of milliseconds to throttle
* keyevents with (Default: 150). Use -1 to disable updates on typing. Note
* that typing the separator will update autocomplete suggestions.
* @constructor
* @extends {goog.Disposable}
*/
goog.ui.ac.InputHandler = function(opt_separators, opt_literals,
opt_multi, opt_throttleTime) {
goog.Disposable.call(this);
var throttleTime = opt_throttleTime || 150;
/**
* Whether this input accepts multiple values
* @type {boolean}
* @private
*/
this.multi_ = opt_multi != null ? opt_multi : true;
// Set separators depends on this.multi_ being set correctly
this.setSeparators(opt_separators ||
goog.ui.ac.InputHandler.STANDARD_LIST_SEPARATORS);
/**
* Characters that are used to delimit literal text. Separarator characters
* found within literal text are not processed as separators
* @type {string}
* @private
*/
this.literals_ = opt_literals || '';
/**
* Whether to prevent the default behavior (moving focus to another element)
* when tab is pressed. This occurs by default only for multi-value mode.
* @type {boolean}
* @private
*/
this.preventDefaultOnTab_ = this.multi_;
/**
* A timer object used to monitor for changes when an element is active.
*
* TODO(user): Consider tuning the throttle time, so that it takes into
* account the length of the token. When the token is short it is likely to
* match lots of rows, therefore we want to check less frequently. Even
* something as simple as <3-chars = 150ms, then 100ms otherwise.
*
* @type {goog.Timer}
* @private
*/
this.timer_ = throttleTime > 0 ? new goog.Timer(throttleTime) : null;
/**
* Event handler used by the input handler to manage events.
* @type {goog.events.EventHandler}
* @private
*/
this.eh_ = new goog.events.EventHandler(this);
/**
* Event handler to help us find an input element that already has the focus.
* @type {goog.events.EventHandler}
* @private
*/
this.activateHandler_ = new goog.events.EventHandler(this);
/**
* The keyhandler used for listening on most key events. This takes care of
* abstracting away some of the browser differences.
* @type {goog.events.KeyHandler}
* @private
*/
this.keyHandler_ = new goog.events.KeyHandler();
/**
* The last key down key code.
* @type {number}
* @private
*/
this.lastKeyCode_ = -1; // Initialize to a non-existent value.
};
goog.inherits(goog.ui.ac.InputHandler, goog.Disposable);
/**
* Whether or not we need to pause the execution of the blur handler in order
* to allow the execution of the selection handler to run first. This is
* currently true when running on IOS version prior to 4.2, since we need
* some special logic for these devices to handle bug 4484488.
* @type {boolean}
* @private
*/
goog.ui.ac.InputHandler.REQUIRES_ASYNC_BLUR_ =
(goog.userAgent.product.IPHONE || goog.userAgent.product.IPAD) &&
// Check the webkit version against the version for iOS 4.2.1.
!goog.userAgent.isVersion('533.17.9');
/**
* Standard list separators.
* @type {string}
* @const
*/
goog.ui.ac.InputHandler.STANDARD_LIST_SEPARATORS = ',;';
/**
* Literals for quotes.
* @type {string}
* @const
*/
goog.ui.ac.InputHandler.QUOTE_LITERALS = '"';
/**
* The AutoComplete instance this inputhandler is associated with.
* @type {goog.ui.ac.AutoComplete}
*/
goog.ui.ac.InputHandler.prototype.ac_;
/**
* Characters that can be used to split multiple entries in an input string
* @type {string}
* @private
*/
goog.ui.ac.InputHandler.prototype.separators_;
/**
* The separator we use to reconstruct the string
* @type {string}
* @private
*/
goog.ui.ac.InputHandler.prototype.defaultSeparator_;
/**
* Regular expression used from trimming tokens or null for no trimming.
* @type {RegExp}
* @private
*/
goog.ui.ac.InputHandler.prototype.trimmer_;
/**
* Regular expression to test whether a separator exists
* @type {RegExp}
* @private
*/
goog.ui.ac.InputHandler.prototype.separatorCheck_;
/**
* Should auto-completed tokens be wrapped in whitespace? Used in selectRow.
* @type {boolean}
* @private
*/
goog.ui.ac.InputHandler.prototype.whitespaceWrapEntries_ = true;
/**
* Should the occurrence of a literal indicate a token boundary?
* @type {boolean}
* @private
*/
goog.ui.ac.InputHandler.prototype.generateNewTokenOnLiteral_ = true;
/**
* Whether to flip the orientation of up & down for hiliting next
* and previous autocomplete entries.
* @type {boolean}
* @private
*/
goog.ui.ac.InputHandler.prototype.upsideDown_ = false;
/**
* If we're in 'multi' mode, does typing a separator force the updating of
* suggestions?
* For example, if somebody finishes typing "obama, hillary,", should the last
* comma trigger updating suggestions in a guaranteed manner? Especially useful
* when the suggestions depend on complete keywords. Note that "obama, hill"
* (a leading sub-string of "obama, hillary" will lead to different and possibly
* irrelevant suggestions.
* @type {boolean}
* @private
*/
goog.ui.ac.InputHandler.prototype.separatorUpdates_ = true;
/**
* If we're in 'multi' mode, does typing a separator force the current term to
* autocomplete?
* For example, if 'tomato' is a suggested completion and the user has typed
* 'to,', do we autocomplete to turn that into 'tomato,'?
* @type {boolean}
* @private
*/
goog.ui.ac.InputHandler.prototype.separatorSelects_ = true;
/**
* The id of the currently active timeout, so it can be cleared if required.
* @type {?number}
* @private
*/
goog.ui.ac.InputHandler.prototype.activeTimeoutId_ = null;
/**
* The element that is currently active.
* @type {Element}
* @private
*/
goog.ui.ac.InputHandler.prototype.activeElement_ = null;
/**
* The previous value of the active element.
* @type {string}
* @private
*/
goog.ui.ac.InputHandler.prototype.lastValue_ = '';
/**
* Flag used to indicate that the IME key has been seen and we need to wait for
* the up event.
* @type {boolean}
* @private
*/
goog.ui.ac.InputHandler.prototype.waitingForIme_ = false;
/**
* Flag used to indicate that the user just selected a row and we should
* therefore ignore the change of the input value.
* @type {boolean}
* @private
*/
goog.ui.ac.InputHandler.prototype.rowJustSelected_ = false;
/**
* Flag indicating whether the result list should be updated continuously
* during typing or only after a short pause.
* @type {boolean}
* @private
*/
goog.ui.ac.InputHandler.prototype.updateDuringTyping_ = true;
/**
* Attach an instance of an AutoComplete
* @param {goog.ui.ac.AutoComplete} ac Autocomplete object.
*/
goog.ui.ac.InputHandler.prototype.attachAutoComplete = function(ac) {
this.ac_ = ac;
};
/**
* Returns the associated autocomplete instance.
* @return {goog.ui.ac.AutoComplete} The associated autocomplete instance.
*/
goog.ui.ac.InputHandler.prototype.getAutoComplete = function() {
return this.ac_;
};
/**
* Returns the current active element.
* @return {Element} The currently active element.
*/
goog.ui.ac.InputHandler.prototype.getActiveElement = function() {
return this.activeElement_;
};
/**
* Returns the value of the current active element.
* @return {string} The value of the current active element.
*/
goog.ui.ac.InputHandler.prototype.getValue = function() {
return this.activeElement_.value;
};
/**
* Sets the value of the current active element.
* @param {string} value The new value.
*/
goog.ui.ac.InputHandler.prototype.setValue = function(value) {
this.activeElement_.value = value;
};
/**
* Returns the current cursor position.
* @return {number} The index of the cursor position.
*/
goog.ui.ac.InputHandler.prototype.getCursorPosition = function() {
return goog.dom.selection.getStart(this.activeElement_);
};
/**
* Sets the cursor at the given position.
* @param {number} pos The index of the cursor position.
*/
goog.ui.ac.InputHandler.prototype.setCursorPosition = function(pos) {
goog.dom.selection.setStart(this.activeElement_, pos);
goog.dom.selection.setEnd(this.activeElement_, pos);
};
/**
* Attaches the input handler to a target element. The target element
* should be a textarea, input box, or other focusable element with the
* same interface.
* @param {Element|goog.events.EventTarget} target An element to attach the
* input handler too.
*/
goog.ui.ac.InputHandler.prototype.attachInput = function(target) {
if (goog.dom.isElement(target)) {
var el = /** @type {!Element} */ (target);
goog.a11y.aria.setState(el, 'haspopup', true);
}
this.eh_.listen(target, goog.events.EventType.FOCUS, this.handleFocus);
this.eh_.listen(target, goog.events.EventType.BLUR, this.handleBlur);
if (!this.activeElement_) {
this.activateHandler_.listen(
target, goog.events.EventType.KEYDOWN,
this.onKeyDownOnInactiveElement_);
// Don't wait for a focus event if the element already has focus.
if (goog.dom.isElement(target)) {
var ownerDocument = goog.dom.getOwnerDocument(
/** @type {Element} */ (target));
if (goog.dom.getActiveElement(ownerDocument) == target) {
this.processFocus(/** @type {Element} */ (target));
}
}
}
};
/**
* Detaches the input handler from the provided element.
* @param {Element|goog.events.EventTarget} target An element to detach the
* input handler from.
*/
goog.ui.ac.InputHandler.prototype.detachInput = function(target) {
if (target == this.activeElement_) {
this.handleBlur();
}
this.eh_.unlisten(target, goog.events.EventType.FOCUS, this.handleFocus);
this.eh_.unlisten(target, goog.events.EventType.BLUR, this.handleBlur);
if (!this.activeElement_) {
this.activateHandler_.unlisten(
target, goog.events.EventType.KEYDOWN,
this.onKeyDownOnInactiveElement_);
}
};
/**
* Attaches the input handler to multiple elements.
* @param {...Element} var_args Elements to attach the input handler too.
*/
goog.ui.ac.InputHandler.prototype.attachInputs = function(var_args) {
for (var i = 0; i < arguments.length; i++) {
this.attachInput(arguments[i]);
}
};
/**
* Detaches the input handler from multuple elements.
* @param {...Element} var_args Variable arguments for elements to unbind from.
*/
goog.ui.ac.InputHandler.prototype.detachInputs = function(var_args) {
for (var i = 0; i < arguments.length; i++) {
this.detachInput(arguments[i]);
}
};
/**
* Selects the given row. Implements the SelectionHandler interface.
* @param {Object} row The row to select.
* @param {boolean=} opt_multi Should this be treated as a single or multi-token
* auto-complete? Overrides previous setting of opt_multi on constructor.
* @return {boolean} Whether to suppress the update event.
*/
goog.ui.ac.InputHandler.prototype.selectRow = function(row, opt_multi) {
this.setTokenText(row.toString(), opt_multi);
return false;
};
/**
* Sets the text of the current token without updating the autocomplete
* choices.
* @param {string} tokenText The text for the current token.
* @param {boolean=} opt_multi Should this be treated as a single or multi-token
* auto-complete? Overrides previous setting of opt_multi on constructor.
* @protected
*/
goog.ui.ac.InputHandler.prototype.setTokenText =
function(tokenText, opt_multi) {
if (goog.isDef(opt_multi) ? opt_multi : this.multi_) {
var index = this.getTokenIndex_(this.getValue(), this.getCursorPosition());
// Break up the current input string.
var entries = this.splitInput_(this.getValue());
// Get the new value, ignoring whitespace associated with the entry.
var replaceValue = tokenText;
// Only add punctuation if there isn't already a separator available.
if (!this.separatorCheck_.test(replaceValue)) {
replaceValue = goog.string.trimRight(replaceValue) +
this.defaultSeparator_;
}
// Ensure there's whitespace wrapping the entries, if whitespaceWrapEntries_
// has been set to true.
if (this.whitespaceWrapEntries_) {
if (index != 0 && !goog.string.isEmpty(entries[index - 1])) {
replaceValue = ' ' + replaceValue;
}
// Add a space only if it's the last token; otherwise, we assume the
// next token already has the proper spacing.
if (index == entries.length - 1) {
replaceValue = replaceValue + ' ';
}
}
// If the token needs changing, then update the input box and move the
// cursor to the correct position.
if (replaceValue != entries[index]) {
// Replace the value in the array.
entries[index] = replaceValue;
var el = this.activeElement_;
// If there is an uncommitted IME in Firefox or IE 9, setting the value
// fails and results in actually clearing the value that's already in the
// input.
// The FF bug is http://bugzilla.mozilla.org/show_bug.cgi?id=549674
// Blurring before setting the value works around this problem. We'd like
// to do this only if there is an uncommitted IME, but this isn't possible
// to detect. Since text editing is finicky we restrict this
// workaround to Firefox and IE 9 where it's necessary.
if (goog.userAgent.GECKO ||
(goog.userAgent.IE && goog.userAgent.isVersion('9'))) {
el.blur();
}
// Join the array and replace the contents of the input.
el.value = entries.join('');
// Calculate which position to put the cursor at.
var pos = 0;
for (var i = 0; i <= index; i++) {
pos += entries[i].length;
}
// Set the cursor.
el.focus();
this.setCursorPosition(pos);
}
} else {
this.setValue(tokenText);
}
// Avoid triggering an autocomplete just because the value changed.
this.rowJustSelected_ = true;
};
/** @override */
goog.ui.ac.InputHandler.prototype.disposeInternal = function() {
goog.ui.ac.InputHandler.superClass_.disposeInternal.call(this);
if (this.activeTimeoutId_ != null) {
// Need to check against null explicitly because 0 is a valid value.
window.clearTimeout(this.activeTimeoutId_);
}
this.eh_.dispose();
delete this.eh_;
this.activateHandler_.dispose();
this.keyHandler_.dispose();
};
/**
* Sets the entry separator characters.
*
* @param {string} separators The separator characters to set.
*/
goog.ui.ac.InputHandler.prototype.setSeparators = function(separators) {
this.separators_ = separators;
this.defaultSeparator_ = this.separators_.substring(0, 1);
var wspaceExp = this.multi_ ? '[\\s' + this.separators_ + ']+' : '[\\s]+';
this.trimmer_ = new RegExp('^' + wspaceExp + '|' + wspaceExp + '$', 'g');
this.separatorCheck_ = new RegExp('\\s*[' + this.separators_ + ']$');
};
/**
* Sets whether to flip the orientation of up & down for hiliting next
* and previous autocomplete entries.
* @param {boolean} upsideDown Whether the orientation is upside down.
*/
goog.ui.ac.InputHandler.prototype.setUpsideDown = function(upsideDown) {
this.upsideDown_ = upsideDown;
};
/**
* Sets whether auto-completed tokens should be wrapped with whitespace.
* @param {boolean} newValue boolean value indicating whether or not
* auto-completed tokens should be wrapped with whitespace.
*/
goog.ui.ac.InputHandler.prototype.setWhitespaceWrapEntries =
function(newValue) {
this.whitespaceWrapEntries_ = newValue;
};
/**
* Sets whether new tokens should be generated from literals. That is, should
* hello'world be two tokens, assuming ' is a literal?
* @param {boolean} newValue boolean value indicating whether or not
* new tokens should be generated from literals.
*/
goog.ui.ac.InputHandler.prototype.setGenerateNewTokenOnLiteral =
function(newValue) {
this.generateNewTokenOnLiteral_ = newValue;
};
/**
* Sets the regular expression used to trim the tokens before passing them to
* the matcher: every substring that matches the given regular expression will
* be removed. This can also be set to null to disable trimming.
* @param {RegExp} trimmer Regexp to use for trimming or null to disable it.
*/
goog.ui.ac.InputHandler.prototype.setTrimmingRegExp = function(trimmer) {
this.trimmer_ = trimmer;
};
/**
* Sets whether we will prevent the default input behavior (moving focus to the
* next focusable element) on TAB.
* @param {boolean} newValue Whether to preventDefault on TAB.
*/
goog.ui.ac.InputHandler.prototype.setPreventDefaultOnTab = function(newValue) {
this.preventDefaultOnTab_ = newValue;
};
/**
* Sets whether separators perform autocomplete.
* @param {boolean} newValue Whether to autocomplete on separators.
*/
goog.ui.ac.InputHandler.prototype.setSeparatorCompletes = function(newValue) {
this.separatorUpdates_ = newValue;
this.separatorSelects_ = newValue;
};
/**
* Sets whether separators perform autocomplete.
* @param {boolean} newValue Whether to autocomplete on separators.
*/
goog.ui.ac.InputHandler.prototype.setSeparatorSelects = function(newValue) {
this.separatorSelects_ = newValue;
};
/**
* Gets the time to wait before updating the results. If the update during
* typing flag is switched on, this delay counts from the last update,
* otherwise from the last keypress.
* @return {number} Throttle time in milliseconds.
*/
goog.ui.ac.InputHandler.prototype.getThrottleTime = function() {
return this.timer_ ? this.timer_.getInterval() : -1;
};
/**
* Sets whether a row has just been selected.
* @param {boolean} justSelected Whether or not the row has just been selected.
*/
goog.ui.ac.InputHandler.prototype.setRowJustSelected = function(justSelected) {
this.rowJustSelected_ = justSelected;
};
/**
* Sets the time to wait before updating the results.
* @param {number} time New throttle time in milliseconds.
*/
goog.ui.ac.InputHandler.prototype.setThrottleTime = function(time) {
if (time < 0) {
this.timer_.dispose();
this.timer_ = null;
return;
}
if (this.timer_) {
this.timer_.setInterval(time);
} else {
this.timer_ = new goog.Timer(time);
}
};
/**
* Gets whether the result list is updated during typing.
* @return {boolean} Value of the flag.
*/
goog.ui.ac.InputHandler.prototype.getUpdateDuringTyping = function() {
return this.updateDuringTyping_;
};
/**
* Sets whether the result list should be updated during typing.
* @param {boolean} value New value of the flag.
*/
goog.ui.ac.InputHandler.prototype.setUpdateDuringTyping = function(value) {
this.updateDuringTyping_ = value;
};
/**
* Handles a key event.
* @param {goog.events.BrowserEvent} e Browser event object.
* @return {boolean} True if the key event was handled.
* @protected
*/
goog.ui.ac.InputHandler.prototype.handleKeyEvent = function(e) {
switch (e.keyCode) {
// If the menu is open and 'down' caused a change then prevent the default
// action and prevent scrolling. If the box isn't a multi autocomplete
// and the menu isn't open, we force it open now.
case goog.events.KeyCodes.DOWN:
if (this.ac_.isOpen()) {
this.moveDown_();
e.preventDefault();
return true;
} else if (!this.multi_) {
this.update(true);
e.preventDefault();
return true;
}
break;
// If the menu is open and 'up' caused a change then prevent the default
// action and prevent scrolling.
case goog.events.KeyCodes.UP:
if (this.ac_.isOpen()) {
this.moveUp_();
e.preventDefault();
return true;
}
break;
// If tab key is pressed, select the current highlighted item. The default
// action is also prevented if the input is a multi input, to prevent the
// user tabbing out of the field.
case goog.events.KeyCodes.TAB:
if (this.ac_.isOpen() && !e.shiftKey) {
// Ensure the menu is up to date before completing.
this.update();
if (this.ac_.selectHilited() && this.preventDefaultOnTab_) {
e.preventDefault();
return true;
}
} else {
this.ac_.dismiss();
}
break;
// On enter, just select the highlighted row.
case goog.events.KeyCodes.ENTER:
if (this.ac_.isOpen()) {
// Ensure the menu is up to date before completing.
this.update();
if (this.ac_.selectHilited()) {
e.preventDefault();
e.stopPropagation();
return true;
}
} else {
this.ac_.dismiss();
}
break;
// On escape tell the autocomplete to dismiss.
case goog.events.KeyCodes.ESC:
if (this.ac_.isOpen()) {
this.ac_.dismiss();
e.preventDefault();
e.stopPropagation();
return true;
}
break;
// The IME keycode indicates an IME sequence has started, we ignore all
// changes until we get an enter key-up.
case goog.events.KeyCodes.WIN_IME:
if (!this.waitingForIme_) {
this.startWaitingForIme_();
return true;
}
break;
default:
if (this.timer_ && !this.updateDuringTyping_) {
// Waits throttle time before sending the request again.
this.timer_.stop();
this.timer_.start();
}
}
return this.handleSeparator_(e);
};
/**
* Handles a key event for a separator key.
* @param {goog.events.BrowserEvent} e Browser event object.
* @return {boolean} True if the key event was handled.
* @private
*/
goog.ui.ac.InputHandler.prototype.handleSeparator_ = function(e) {
var isSeparatorKey = this.multi_ && e.charCode &&
this.separators_.indexOf(String.fromCharCode(e.charCode)) != -1;
if (this.separatorUpdates_ && isSeparatorKey) {
this.update();
}
if (this.separatorSelects_ && isSeparatorKey) {
if (this.ac_.selectHilited()) {
e.preventDefault();
return true;
}
}
return false;
};
/**
* @return {boolean} Whether this inputhandler need to listen on key-up.
* @protected
*/
goog.ui.ac.InputHandler.prototype.needKeyUpListener = function() {
return false;
};
/**
* Handles the key up event. Registered only if needKeyUpListener returns true.
* @param {goog.events.Event} e The keyup event.
* @return {boolean} Whether an action was taken or not.
* @protected
*/
goog.ui.ac.InputHandler.prototype.handleKeyUp = function(e) {
return false;
};
/**
* Adds the necessary input event handlers.
* @private
*/
goog.ui.ac.InputHandler.prototype.addEventHandlers_ = function() {
this.keyHandler_.attach(this.activeElement_);
this.eh_.listen(
this.keyHandler_, goog.events.KeyHandler.EventType.KEY, this.onKey_);
if (this.needKeyUpListener()) {
this.eh_.listen(this.activeElement_,
goog.events.EventType.KEYUP, this.handleKeyUp);
}
this.eh_.listen(this.activeElement_,
goog.events.EventType.MOUSEDOWN, this.onMouseDown_);
// IE also needs a keypress to check if the user typed a separator
if (goog.userAgent.IE) {
this.eh_.listen(this.activeElement_,
goog.events.EventType.KEYPRESS, this.onIeKeyPress_);
}
};
/**
* Removes the necessary input event handlers.
* @private
*/
goog.ui.ac.InputHandler.prototype.removeEventHandlers_ = function() {
this.eh_.unlisten(
this.keyHandler_, goog.events.KeyHandler.EventType.KEY, this.onKey_);
this.keyHandler_.detach();
this.eh_.unlisten(this.activeElement_,
goog.events.EventType.KEYUP, this.handleKeyUp);
this.eh_.unlisten(this.activeElement_,
goog.events.EventType.MOUSEDOWN, this.onMouseDown_);
if (goog.userAgent.IE) {
this.eh_.unlisten(this.activeElement_,
goog.events.EventType.KEYPRESS, this.onIeKeyPress_);
}
if (this.waitingForIme_) {
this.stopWaitingForIme_();
}
};
/**
* Handles an element getting focus.
* @param {goog.events.Event} e Browser event object.
* @protected
*/
goog.ui.ac.InputHandler.prototype.handleFocus = function(e) {
this.processFocus(/** @type {Element} */ (e.target || null));
};
/**
* Registers handlers for the active element when it receives focus.
* @param {Element} target The element to focus.
* @protected
*/
goog.ui.ac.InputHandler.prototype.processFocus = function(target) {
this.activateHandler_.removeAll();
if (this.ac_) {
this.ac_.cancelDelayedDismiss();
}
// Double-check whether the active element has actually changed.
// This is a fix for Safari 3, which fires spurious focus events.
if (target != this.activeElement_) {
this.activeElement_ = target;
if (this.timer_) {
this.timer_.start();
this.eh_.listen(this.timer_, goog.Timer.TICK, this.onTick_);
}
this.lastValue_ = this.getValue();
this.addEventHandlers_();
}
};
/**
* Handles an element blurring.
* @param {goog.events.Event=} opt_e Browser event object.
* @protected
*/
goog.ui.ac.InputHandler.prototype.handleBlur = function(opt_e) {
// Phones running iOS prior to version 4.2.
if (goog.ui.ac.InputHandler.REQUIRES_ASYNC_BLUR_) {
// @bug 4484488 This is required so that the menu works correctly on
// iOS prior to version 4.2. Otherwise, the blur action closes the menu
// before the menu button click can be processed.
// In order to fix the bug, we set a timeout to process the blur event, so
// that any pending selection event can be processed first.
this.activeTimeoutId_ =
window.setTimeout(goog.bind(this.processBlur_, this), 0);
return;
} else {
this.processBlur_();
}
};
/**
* Helper function that does the logic to handle an element blurring.
* @private
*/
goog.ui.ac.InputHandler.prototype.processBlur_ = function() {
// it's possible that a blur event could fire when there's no active element,
// in the case where attachInput was called on an input that already had
// the focus
if (this.activeElement_) {
this.removeEventHandlers_();
this.activeElement_ = null;
if (this.timer_) {
this.timer_.stop();
this.eh_.unlisten(this.timer_, goog.Timer.TICK, this.onTick_);
}
if (this.ac_) {
// Pause dismissal slightly to take into account any other events that
// might fire on the renderer (e.g. a click will lose the focus).
this.ac_.dismissOnDelay();
}
}
};
/**
* Handles the timer's tick event. Calculates the current token, and reports
* any update to the autocomplete.
* @param {goog.events.Event} e Browser event object.
* @private
*/
goog.ui.ac.InputHandler.prototype.onTick_ = function(e) {
this.update();
};
/**
* Handles typing in an inactive input element. Activate it.
* @param {goog.events.BrowserEvent} e Browser event object.
* @private
*/
goog.ui.ac.InputHandler.prototype.onKeyDownOnInactiveElement_ = function(e) {
this.handleFocus(e);
};
/**
* Handles typing in the active input element. Checks if the key is a special
* key and does the relevent action as appropriate.
* @param {goog.events.BrowserEvent} e Browser event object.
* @private
*/
goog.ui.ac.InputHandler.prototype.onKey_ = function(e) {
this.lastKeyCode_ = e.keyCode;
if (this.ac_) {
this.handleKeyEvent(e);
}
};
/**
* Handles a KEYPRESS event generated by typing in the active input element.
* Checks if IME input is ended.
* @param {goog.events.BrowserEvent} e Browser event object.
* @private
*/
goog.ui.ac.InputHandler.prototype.onKeyPress_ = function(e) {
if (this.waitingForIme_ &&
this.lastKeyCode_ != goog.events.KeyCodes.WIN_IME) {
this.stopWaitingForIme_();
}
};
/**
* Handles the key-up event. This is only ever used by Mac FF or when we are in
* an IME entry scenario.
* @param {goog.events.BrowserEvent} e Browser event object.
* @private
*/
goog.ui.ac.InputHandler.prototype.onKeyUp_ = function(e) {
if (this.waitingForIme_ &&
(e.keyCode == goog.events.KeyCodes.ENTER ||
(e.keyCode == goog.events.KeyCodes.M && e.ctrlKey))) {
this.stopWaitingForIme_();
}
};
/**
* Handles mouse-down event.
* @param {goog.events.BrowserEvent} e Browser event object.
* @private
*/
goog.ui.ac.InputHandler.prototype.onMouseDown_ = function(e) {
if (this.ac_) {
this.handleMouseDown(e);
}
};
/**
* For subclasses to override to handle the mouse-down event.
* @param {goog.events.BrowserEvent} e Browser event object.
* @protected
*/
goog.ui.ac.InputHandler.prototype.handleMouseDown = function(e) {
};
/**
* Starts waiting for IME.
* @private
*/
goog.ui.ac.InputHandler.prototype.startWaitingForIme_ = function() {
if (this.waitingForIme_) {
return;
}
this.eh_.listen(
this.activeElement_, goog.events.EventType.KEYUP, this.onKeyUp_);
this.eh_.listen(
this.activeElement_, goog.events.EventType.KEYPRESS, this.onKeyPress_);
this.waitingForIme_ = true;
};
/**
* Stops waiting for IME.
* @private
*/
goog.ui.ac.InputHandler.prototype.stopWaitingForIme_ = function() {
if (!this.waitingForIme_) {
return;
}
this.waitingForIme_ = false;
this.eh_.unlisten(
this.activeElement_, goog.events.EventType.KEYPRESS, this.onKeyPress_);
this.eh_.unlisten(
this.activeElement_, goog.events.EventType.KEYUP, this.onKeyUp_);
};
/**
* Handles the key-press event for IE, checking to see if the user typed a
* separator character.
* @param {goog.events.BrowserEvent} e Browser event object.
* @private
*/
goog.ui.ac.InputHandler.prototype.onIeKeyPress_ = function(e) {
this.handleSeparator_(e);
};
/**
* Checks if an update has occurred and notified the autocomplete of the new
* token.
* @param {boolean=} opt_force If true the menu will be forced to update.
*/
goog.ui.ac.InputHandler.prototype.update = function(opt_force) {
if (this.activeElement_ &&
(opt_force || this.getValue() != this.lastValue_)) {
if (opt_force || !this.rowJustSelected_) {
var token = this.parseToken();
if (this.ac_) {
this.ac_.setTarget(this.activeElement_);
this.ac_.setToken(token, this.getValue());
}
}
this.lastValue_ = this.getValue();
}
this.rowJustSelected_ = false;
};
/**
* Parses a text area or input box for the currently highlighted token.
* @return {string} Token to complete.
* @protected
*/
goog.ui.ac.InputHandler.prototype.parseToken = function() {
return this.parseToken_();
};
/**
* Moves hilite up. May hilite next or previous depending on orientation.
* @return {boolean} True if successful.
* @private
*/
goog.ui.ac.InputHandler.prototype.moveUp_ = function() {
return this.upsideDown_ ? this.ac_.hiliteNext() : this.ac_.hilitePrev();
};
/**
* Moves hilite down. May hilite next or previous depending on orientation.
* @return {boolean} True if successful.
* @private
*/
goog.ui.ac.InputHandler.prototype.moveDown_ = function() {
return this.upsideDown_ ? this.ac_.hilitePrev() : this.ac_.hiliteNext();
};
/**
* Parses a text area or input box for the currently highlighted token.
* @return {string} Token to complete.
* @private
*/
goog.ui.ac.InputHandler.prototype.parseToken_ = function() {
var caret = this.getCursorPosition();
var text = this.getValue();
return this.trim_(this.splitInput_(text)[this.getTokenIndex_(text, caret)]);
};
/**
* Trims a token of characters that we want to ignore
* @param {string} text string to trim.
* @return {string} Trimmed string.
* @private
*/
goog.ui.ac.InputHandler.prototype.trim_ = function(text) {
return this.trimmer_ ? String(text).replace(this.trimmer_, '') : text;
};
/**
* Gets the index of the currently highlighted token
* @param {string} text string to parse.
* @param {number} caret Position of cursor in string.
* @return {number} Index of token.
* @private
*/
goog.ui.ac.InputHandler.prototype.getTokenIndex_ = function(text, caret) {
// Split up the input string into multiple entries
var entries = this.splitInput_(text);
// Short-circuit to select the last entry
if (caret == text.length) return entries.length - 1;
// Calculate which of the entries the cursor is currently in
var current = 0;
for (var i = 0, pos = 0; i < entries.length && pos <= caret; i++) {
pos += entries[i].length;
current = i;
}
// Get the token for the current item
return current;
};
/**
* Splits an input string of text at the occurance of a character in
* {@link goog.ui.ac.InputHandler.prototype.separators_} and creates
* an array of tokens. Each token may contain additional whitespace and
* formatting marks. If necessary use
* {@link goog.ui.ac.InputHandler.prototype.trim_} to clean up the
* entries.
*
* @param {string} text Input text.
* @return {Array} Parsed array.
* @private
*/
goog.ui.ac.InputHandler.prototype.splitInput_ = function(text) {
if (!this.multi_) {
return [text];
}
var arr = String(text).split('');
var parts = [];
var cache = [];
for (var i = 0, inLiteral = false; i < arr.length; i++) {
if (this.literals_ && this.literals_.indexOf(arr[i]) != -1) {
if (this.generateNewTokenOnLiteral_ && !inLiteral) {
parts.push(cache.join(''));
cache.length = 0;
}
cache.push(arr[i]);
inLiteral = !inLiteral;
} else if (!inLiteral && this.separators_.indexOf(arr[i]) != -1) {
cache.push(arr[i]);
parts.push(cache.join(''));
cache.length = 0;
} else {
cache.push(arr[i]);
}
}
parts.push(cache.join(''));
return parts;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A class for representing menu separators.
* @see goog.ui.Menu
*
*/
goog.provide('goog.ui.MenuSeparator');
goog.require('goog.ui.MenuSeparatorRenderer');
goog.require('goog.ui.Separator');
goog.require('goog.ui.registry');
/**
* Class representing a menu separator. A menu separator extends {@link
* goog.ui.Separator} by always setting its renderer to {@link
* goog.ui.MenuSeparatorRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper used for
* document interactions.
* @constructor
* @extends {goog.ui.Separator}
*/
goog.ui.MenuSeparator = function(opt_domHelper) {
goog.ui.Separator.call(this, goog.ui.MenuSeparatorRenderer.getInstance(),
opt_domHelper);
};
goog.inherits(goog.ui.MenuSeparator, goog.ui.Separator);
// Register a decorator factory function for goog.ui.MenuSeparators.
goog.ui.registry.setDecoratorByClassName(
goog.ui.MenuSeparatorRenderer.CSS_CLASS,
function() {
// Separator defaults to using MenuSeparatorRenderer.
return new goog.ui.Separator();
});
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A toggle button control. Extends {@link goog.ui.Button} by
* providing checkbox-like semantics.
*
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.ui.ToggleButton');
goog.require('goog.ui.Button');
goog.require('goog.ui.Component');
goog.require('goog.ui.CustomButtonRenderer');
goog.require('goog.ui.registry');
/**
* A toggle button, with checkbox-like semantics. Rendered using
* {@link goog.ui.CustomButtonRenderer} by default, though any
* {@link goog.ui.ButtonRenderer} would work.
*
* @param {goog.ui.ControlContent} content Text caption or existing DOM
* structure to display as the button's caption.
* @param {goog.ui.ButtonRenderer=} opt_renderer Renderer used to render or
* decorate the button; defaults to {@link goog.ui.CustomButtonRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
* document interaction.
* @constructor
* @extends {goog.ui.Button}
*/
goog.ui.ToggleButton = function(content, opt_renderer, opt_domHelper) {
goog.ui.Button.call(this, content, opt_renderer ||
goog.ui.CustomButtonRenderer.getInstance(), opt_domHelper);
this.setSupportedState(goog.ui.Component.State.CHECKED, true);
};
goog.inherits(goog.ui.ToggleButton, goog.ui.Button);
// Register a decorator factory function for goog.ui.ToggleButtons.
goog.ui.registry.setDecoratorByClassName(
goog.getCssName('goog-toggle-button'), function() {
// ToggleButton defaults to using CustomButtonRenderer.
return new goog.ui.ToggleButton(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 Renderer for toolbar separators.
*
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.ui.ToolbarSeparatorRenderer');
goog.require('goog.dom.classes');
goog.require('goog.ui.INLINE_BLOCK_CLASSNAME');
goog.require('goog.ui.MenuSeparatorRenderer');
/**
* Renderer for toolbar separators.
* @constructor
* @extends {goog.ui.MenuSeparatorRenderer}
*/
goog.ui.ToolbarSeparatorRenderer = function() {
goog.ui.MenuSeparatorRenderer.call(this);
};
goog.inherits(goog.ui.ToolbarSeparatorRenderer, goog.ui.MenuSeparatorRenderer);
goog.addSingletonGetter(goog.ui.ToolbarSeparatorRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.ToolbarSeparatorRenderer.CSS_CLASS =
goog.getCssName('goog-toolbar-separator');
/**
* Returns a styled toolbar separator implemented by the following DOM:
* <div class="goog-toolbar-separator goog-inline-block"> </div>
* Overrides {@link goog.ui.MenuSeparatorRenderer#createDom}.
* @param {goog.ui.Control} separator goog.ui.Separator to render.
* @return {Element} Root element for the separator.
* @override
*/
goog.ui.ToolbarSeparatorRenderer.prototype.createDom = function(separator) {
// 00A0 is
return separator.getDomHelper().createDom('div',
this.getCssClass() + ' ' + goog.ui.INLINE_BLOCK_CLASSNAME,
'\u00A0');
};
/**
* Takes an existing element, and decorates it with the separator. Overrides
* {@link goog.ui.MenuSeparatorRenderer#decorate}.
* @param {goog.ui.Control} separator goog.ui.Separator to decorate the element.
* @param {Element} element Element to decorate.
* @return {Element} Decorated element.
* @override
*/
goog.ui.ToolbarSeparatorRenderer.prototype.decorate = function(separator,
element) {
element = goog.ui.ToolbarSeparatorRenderer.superClass_.decorate.call(this,
separator, element);
goog.dom.classes.add(element, goog.ui.INLINE_BLOCK_CLASSNAME);
return element;
};
/**
* Returns the CSS class to be applied to the root element of components
* rendered using this renderer.
* @return {string} Renderer-specific CSS class.
* @override
*/
goog.ui.ToolbarSeparatorRenderer.prototype.getCssClass = function() {
return goog.ui.ToolbarSeparatorRenderer.CSS_CLASS;
};
| 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 Generic keyboard shortcut handler.
*
* @author eae@google.com (Emil A Eklund)
* @see ../demos/keyboardshortcuts.html
*/
goog.provide('goog.ui.KeyboardShortcutEvent');
goog.provide('goog.ui.KeyboardShortcutHandler');
goog.provide('goog.ui.KeyboardShortcutHandler.EventType');
goog.require('goog.Timer');
goog.require('goog.events');
goog.require('goog.events.Event');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.events.KeyNames');
goog.require('goog.object');
/**
* Component for handling keyboard shortcuts. A shortcut is registered and bound
* to a specific identifier. Once the shortcut is triggered an event is fired
* with the identifier for the shortcut. This allows keyboard shortcuts to be
* customized without modifying the code that listens for them.
*
* Supports keyboard shortcuts triggered by a single key, a stroke stroke (key
* plus at least one modifier) and a sequence of keys or strokes.
*
* @param {goog.events.EventTarget|EventTarget} keyTarget Event target that the
* key event listener is attached to, typically the applications root
* container.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.ui.KeyboardShortcutHandler = function(keyTarget) {
goog.events.EventTarget.call(this);
/**
* Registered keyboard shortcuts tree. Stored as a map with the keyCode and
* modifier(s) as the key and either a list of further strokes or the shortcut
* task identifier as the value.
* @type {Object}
* @see #makeKey_
* @private
*/
this.shortcuts_ = {};
/**
* List of the last sequence of strokes. Object contains time last key was
* pressed and an array of strokes, represented by numeric value.
* @type {Object}
* @private
*/
this.lastKeys_ = {
strokes: [],
time: 0
};
/**
* List of numeric key codes for keys that are safe to always regarded as
* shortcuts, even if entered in a textarea or input field.
* @type {Object}
* @private
*/
this.globalKeys_ = goog.object.createSet(
goog.ui.KeyboardShortcutHandler.DEFAULT_GLOBAL_KEYS_);
/**
* List of input types that should only accept ENTER as a shortcut.
* @type {Object}
* @private
*/
this.textInputs_ = goog.object.createSet(
goog.ui.KeyboardShortcutHandler.DEFAULT_TEXT_INPUTS_);
/**
* Whether to always prevent the default action if a shortcut event is fired.
* @type {boolean}
* @private
*/
this.alwaysPreventDefault_ = true;
/**
* Whether to always stop propagation if a shortcut event is fired.
* @type {boolean}
* @private
*/
this.alwaysStopPropagation_ = false;
/**
* Whether to treat all shortcuts as if they had been passed
* to setGlobalKeys().
* @type {boolean}
* @private
*/
this.allShortcutsAreGlobal_ = false;
/**
* Whether to treat shortcuts with modifiers as if they had been passed
* to setGlobalKeys(). Ignored if allShortcutsAreGlobal_ is true. Applies
* only to form elements (not content-editable).
* @type {boolean}
* @private
*/
this.modifierShortcutsAreGlobal_ = true;
this.initializeKeyListener(keyTarget);
};
goog.inherits(goog.ui.KeyboardShortcutHandler, goog.events.EventTarget);
/**
* Maximum allowed delay, in milliseconds, allowed between the first and second
* key in a key sequence.
* @type {number}
*/
goog.ui.KeyboardShortcutHandler.MAX_KEY_SEQUENCE_DELAY = 1500; // 1.5 sec
/**
* Bit values for modifier keys.
* @enum {number}
*/
goog.ui.KeyboardShortcutHandler.Modifiers = {
NONE: 0,
SHIFT: 1,
CTRL: 2,
ALT: 4,
META: 8
};
/**
* Keys marked as global by default.
* @type {Array.<goog.events.KeyCodes>}
* @private
*/
goog.ui.KeyboardShortcutHandler.DEFAULT_GLOBAL_KEYS_ = [
goog.events.KeyCodes.ESC,
goog.events.KeyCodes.F1,
goog.events.KeyCodes.F2,
goog.events.KeyCodes.F3,
goog.events.KeyCodes.F4,
goog.events.KeyCodes.F5,
goog.events.KeyCodes.F6,
goog.events.KeyCodes.F7,
goog.events.KeyCodes.F8,
goog.events.KeyCodes.F9,
goog.events.KeyCodes.F10,
goog.events.KeyCodes.F11,
goog.events.KeyCodes.F12,
goog.events.KeyCodes.PAUSE
];
/**
* Text input types to allow only ENTER shortcuts.
* Web Forms 2.0 for HTML5: Section 4.10.7 from 29 May 2012.
* @type {Array.<string>}
* @private
*/
goog.ui.KeyboardShortcutHandler.DEFAULT_TEXT_INPUTS_ = [
'color',
'date',
'datetime',
'datetime-local',
'email',
'month',
'number',
'password',
'search',
'tel',
'text',
'time',
'url',
'week'
];
/**
* Events.
* @enum {string}
*/
goog.ui.KeyboardShortcutHandler.EventType = {
SHORTCUT_TRIGGERED: 'shortcut',
SHORTCUT_PREFIX: 'shortcut_'
};
/**
* Cache for name to key code lookup.
* @type {Object}
* @private
*/
goog.ui.KeyboardShortcutHandler.nameToKeyCodeCache_;
/**
* Target on which to listen for key events.
* @type {goog.events.EventTarget|EventTarget}
* @private
*/
goog.ui.KeyboardShortcutHandler.prototype.keyTarget_;
/**
* Due to a bug in the way that Gecko v1.8 on Mac handles
* cut/copy/paste key events using the meta key, it is necessary to
* fake the keydown for the action key (C,V,X) by capturing it on keyup.
* Because users will often release the meta key a slight moment
* before they release the action key, we need this variable that will
* store whether the meta key has been released recently.
* It will be cleared after a short delay in the key handling logic.
* @type {boolean}
* @private
*/
goog.ui.KeyboardShortcutHandler.prototype.metaKeyRecentlyReleased_;
/**
* Whether a key event is a printable-key event. Windows uses ctrl+alt
* (alt-graph) keys to type characters on European keyboards. For such keys, we
* cannot identify whether these keys are used for typing characters when
* receiving keydown events. Therefore, we set this flag when we receive their
* respective keypress events and fire shortcut events only when we do not
* receive them.
* @type {boolean}
* @private
*/
goog.ui.KeyboardShortcutHandler.prototype.isPrintableKey_;
/**
* Static method for getting the key code for a given key.
* @param {string} name Name of key.
* @return {number} The key code.
*/
goog.ui.KeyboardShortcutHandler.getKeyCode = function(name) {
// Build reverse lookup object the first time this method is called.
if (!goog.ui.KeyboardShortcutHandler.nameToKeyCodeCache_) {
var map = {};
for (var key in goog.events.KeyNames) {
map[goog.events.KeyNames[key]] = key;
}
goog.ui.KeyboardShortcutHandler.nameToKeyCodeCache_ = map;
}
// Check if key is in cache.
return goog.ui.KeyboardShortcutHandler.nameToKeyCodeCache_[name];
};
/**
* Sets whether to always prevent the default action when a shortcut event is
* fired. If false, the default action is prevented only if preventDefault is
* called on either of the corresponding SHORTCUT_TRIGGERED or SHORTCUT_PREFIX
* events. If true, the default action is prevented whenever a shortcut event
* is fired. The default value is true.
* @param {boolean} alwaysPreventDefault Whether to always call preventDefault.
*/
goog.ui.KeyboardShortcutHandler.prototype.setAlwaysPreventDefault = function(
alwaysPreventDefault) {
this.alwaysPreventDefault_ = alwaysPreventDefault;
};
/**
* Returns whether the default action will always be prevented when a shortcut
* event is fired. The default value is true.
* @see #setAlwaysPreventDefault
* @return {boolean} Whether preventDefault will always be called.
*/
goog.ui.KeyboardShortcutHandler.prototype.getAlwaysPreventDefault = function() {
return this.alwaysPreventDefault_;
};
/**
* Sets whether to always stop propagation for the event when fired. If false,
* the propagation is stopped only if stopPropagation is called on either of the
* corresponding SHORT_CUT_TRIGGERED or SHORTCUT_PREFIX events. If true, the
* event is prevented from propagating beyond its target whenever it is fired.
* The default value is false.
* @param {boolean} alwaysStopPropagation Whether to always call
* stopPropagation.
*/
goog.ui.KeyboardShortcutHandler.prototype.setAlwaysStopPropagation = function(
alwaysStopPropagation) {
this.alwaysStopPropagation_ = alwaysStopPropagation;
};
/**
* Returns whether the event will always be stopped from propagating beyond its
* target when a shortcut event is fired. The default value is false.
* @see #setAlwaysStopPropagation
* @return {boolean} Whether stopPropagation will always be called.
*/
goog.ui.KeyboardShortcutHandler.prototype.getAlwaysStopPropagation =
function() {
return this.alwaysStopPropagation_;
};
/**
* Sets whether to treat all shortcuts (including modifier shortcuts) as if the
* keys had been passed to the setGlobalKeys function.
* @param {boolean} allShortcutsGlobal Whether to treat all shortcuts as global.
*/
goog.ui.KeyboardShortcutHandler.prototype.setAllShortcutsAreGlobal = function(
allShortcutsGlobal) {
this.allShortcutsAreGlobal_ = allShortcutsGlobal;
};
/**
* Returns whether all shortcuts (including modifier shortcuts) are treated as
* if the keys had been passed to the setGlobalKeys function.
* @see #setAllShortcutsAreGlobal
* @return {boolean} Whether all shortcuts are treated as globals.
*/
goog.ui.KeyboardShortcutHandler.prototype.getAllShortcutsAreGlobal =
function() {
return this.allShortcutsAreGlobal_;
};
/**
* Sets whether to treat shortcuts with modifiers as if the keys had been
* passed to the setGlobalKeys function. Ignored if you have called
* setAllShortcutsAreGlobal(true). Applies only to form elements (not
* content-editable).
* @param {boolean} modifierShortcutsGlobal Whether to treat shortcuts with
* modifiers as global.
*/
goog.ui.KeyboardShortcutHandler.prototype.setModifierShortcutsAreGlobal =
function(modifierShortcutsGlobal) {
this.modifierShortcutsAreGlobal_ = modifierShortcutsGlobal;
};
/**
* Returns whether shortcuts with modifiers are treated as if the keys had been
* passed to the setGlobalKeys function. Ignored if you have called
* setAllShortcutsAreGlobal(true). Applies only to form elements (not
* content-editable).
* @see #setModifierShortcutsAreGlobal
* @return {boolean} Whether shortcuts with modifiers are treated as globals.
*/
goog.ui.KeyboardShortcutHandler.prototype.getModifierShortcutsAreGlobal =
function() {
return this.modifierShortcutsAreGlobal_;
};
/**
* Registers a keyboard shortcut.
* @param {string} identifier Identifier for the task performed by the keyboard
* combination. Multiple shortcuts can be provided for the same
* task by specifying the same identifier.
* @param {...(number|string|Array.<number>)} var_args See below.
*
* param {number} keyCode Numeric code for key
* param {number=} opt_modifiers Bitmap indicating required modifier keys.
* goog.ui.KeyboardShortcutHandler.Modifiers.SHIFT, CONTROL,
* ALT, or META.
*
* The last two parameters can be repeated any number of times to create a
* shortcut using a sequence of strokes. Instead of varagrs the second parameter
* could also be an array where each element would be ragarded as a parameter.
*
* A string representation of the shortcut can be supplied instead of the last
* two parameters. In that case the method only takes two arguments, the
* identifier and the string.
*
* Examples:
* g registerShortcut(str, G_KEYCODE)
* Ctrl+g registerShortcut(str, G_KEYCODE, CTRL)
* Ctrl+Shift+g registerShortcut(str, G_KEYCODE, CTRL | SHIFT)
* Ctrl+g a registerShortcut(str, G_KEYCODE, CTRL, A_KEYCODE)
* Ctrl+g Shift+a registerShortcut(str, G_KEYCODE, CTRL, A_KEYCODE, SHIFT)
* g a registerShortcut(str, G_KEYCODE, NONE, A_KEYCODE)
*
* Examples using string representation for shortcuts:
* g registerShortcut(str, 'g')
* Ctrl+g registerShortcut(str, 'ctrl+g')
* Ctrl+Shift+g registerShortcut(str, 'ctrl+shift+g')
* Ctrl+g a registerShortcut(str, 'ctrl+g a')
* Ctrl+g Shift+a registerShortcut(str, 'ctrl+g shift+a')
* g a registerShortcut(str, 'g a').
*/
goog.ui.KeyboardShortcutHandler.prototype.registerShortcut = function(
identifier, var_args) {
// Add shortcut to shortcuts_ tree
goog.ui.KeyboardShortcutHandler.setShortcut_(
this.shortcuts_, this.interpretStrokes_(1, arguments), identifier);
};
/**
* Unregisters a keyboard shortcut by keyCode and modifiers or string
* representation of sequence.
*
* param {number} keyCode Numeric code for key
* param {number=} opt_modifiers Bitmap indicating required modifier keys.
* goog.ui.KeyboardShortcutHandler.Modifiers.SHIFT, CONTROL,
* ALT, or META.
*
* The two parameters can be repeated any number of times to create a shortcut
* using a sequence of strokes.
*
* A string representation of the shortcut can be supplied instead see
* {@link #registerShortcut} for syntax. In that case the method only takes one
* argument.
*
* @param {...(number|string|Array.<number>)} var_args String representation, or
* array or list of alternating key codes and modifiers.
*/
goog.ui.KeyboardShortcutHandler.prototype.unregisterShortcut = function(
var_args) {
// Remove shortcut from tree
goog.ui.KeyboardShortcutHandler.setShortcut_(
this.shortcuts_, this.interpretStrokes_(0, arguments), null);
};
/**
* Verifies if a particular keyboard shortcut is registered already. It has
* the same interface as the unregistering of shortcuts.
*
* param {number} keyCode Numeric code for key
* param {number=} opt_modifiers Bitmap indicating required modifier keys.
* goog.ui.KeyboardShortcutHandler.Modifiers.SHIFT, CONTROL,
* ALT, or META.
*
* The two parameters can be repeated any number of times to create a shortcut
* using a sequence of strokes.
*
* A string representation of the shortcut can be supplied instead see
* {@link #registerShortcut} for syntax. In that case the method only takes one
* argument.
*
* @param {...(number|string|Array.<number>)} var_args String representation, or
* array or list of alternating key codes and modifiers.
* @return {boolean} Whether the specified keyboard shortcut is registered.
*/
goog.ui.KeyboardShortcutHandler.prototype.isShortcutRegistered = function(
var_args) {
return this.checkShortcut_(this.interpretStrokes_(0, arguments));
};
/**
* Parses the variable arguments for registerShortcut and unregisterShortcut.
* @param {number} initialIndex The first index of "args" to treat as
* variable arguments.
* @param {Object} args The "arguments" array passed
* to registerShortcut or unregisterShortcut. Please see the comments in
* registerShortcut for list of allowed forms.
* @return {Array.<Object>} The sequence of objects containing the
* keyCode and modifiers of each key in sequence.
* @private
*/
goog.ui.KeyboardShortcutHandler.prototype.interpretStrokes_ = function(
initialIndex, args) {
var strokes;
// Build strokes array from string.
if (goog.isString(args[initialIndex])) {
strokes = goog.ui.KeyboardShortcutHandler.parseStringShortcut(
args[initialIndex]);
// Build strokes array from arguments list or from array.
} else {
var strokesArgs = args, i = initialIndex;
if (goog.isArray(args[initialIndex])) {
strokesArgs = args[initialIndex];
i = 0;
}
strokes = [];
for (; i < strokesArgs.length; i += 2) {
strokes.push({
keyCode: strokesArgs[i],
modifiers: strokesArgs[i + 1]
});
}
}
return strokes;
};
/**
* Unregisters all keyboard shortcuts.
*/
goog.ui.KeyboardShortcutHandler.prototype.unregisterAll = function() {
this.shortcuts_ = {};
};
/**
* Sets the global keys; keys that are safe to always regarded as shortcuts,
* even if entered in a textarea or input field.
* @param {Array.<number>} keys List of keys.
*/
goog.ui.KeyboardShortcutHandler.prototype.setGlobalKeys = function(keys) {
this.globalKeys_ = goog.object.createSet(keys);
};
/**
* @return {Array.<string>} The global keys, i.e. keys that are safe to always
* regard as shortcuts, even if entered in a textarea or input field.
*/
goog.ui.KeyboardShortcutHandler.prototype.getGlobalKeys = function() {
return goog.object.getKeys(this.globalKeys_);
};
/** @override */
goog.ui.KeyboardShortcutHandler.prototype.disposeInternal = function() {
goog.ui.KeyboardShortcutHandler.superClass_.disposeInternal.call(this);
this.unregisterAll();
this.clearKeyListener();
};
/**
* Returns event type for a specific shortcut.
* @param {string} identifier Identifier for the shortcut task.
* @return {string} Theh event type.
*/
goog.ui.KeyboardShortcutHandler.prototype.getEventType =
function(identifier) {
return goog.ui.KeyboardShortcutHandler.EventType.SHORTCUT_PREFIX + identifier;
};
/**
* Builds stroke array from string representation of shortcut.
* @param {string} s String representation of shortcut.
* @return {Array.<Object>} The stroke array.
*/
goog.ui.KeyboardShortcutHandler.parseStringShortcut = function(s) {
// Normalize whitespace and force to lower case.
s = s.replace(/[ +]*\+[ +]*/g, '+').replace(/[ ]+/g, ' ').toLowerCase();
// Build strokes array from string, space separates strokes, plus separates
// individual keys.
var groups = s.split(' ');
var strokes = [];
for (var group, i = 0; group = groups[i]; i++) {
var keys = group.split('+');
var keyCode, modifiers = goog.ui.KeyboardShortcutHandler.Modifiers.NONE;
for (var key, j = 0; key = keys[j]; j++) {
switch (key) {
case 'shift':
modifiers |= goog.ui.KeyboardShortcutHandler.Modifiers.SHIFT;
continue;
case 'ctrl':
modifiers |= goog.ui.KeyboardShortcutHandler.Modifiers.CTRL;
continue;
case 'alt':
modifiers |= goog.ui.KeyboardShortcutHandler.Modifiers.ALT;
continue;
case 'meta':
modifiers |= goog.ui.KeyboardShortcutHandler.Modifiers.META;
continue;
}
keyCode = goog.ui.KeyboardShortcutHandler.getKeyCode(key);
break;
}
strokes.push({keyCode: keyCode, modifiers: modifiers});
}
return strokes;
};
/**
* Adds a key event listener that triggers {@link #handleKeyDown_} when keys
* are pressed.
* @param {goog.events.EventTarget|EventTarget} keyTarget Event target that the
* event listener should be attached to.
* @protected
*/
goog.ui.KeyboardShortcutHandler.prototype.initializeKeyListener =
function(keyTarget) {
this.keyTarget_ = keyTarget;
goog.events.listen(this.keyTarget_, goog.events.EventType.KEYDOWN,
this.handleKeyDown_, false, this);
// Firefox 2 on mac does not fire a keydown event in conjunction with a meta
// key if the action involves cutting/copying/pasting text.
// In this case we capture the keyup (which is fired) and fake as
// if the user had pressed the key to begin with.
if (goog.userAgent.MAC &&
goog.userAgent.GECKO && goog.userAgent.isVersion('1.8')) {
goog.events.listen(this.keyTarget_, goog.events.EventType.KEYUP,
this.handleMacGeckoKeyUp_, false, this);
}
// Windows uses ctrl+alt keys (a.k.a. alt-graph keys) for typing characters
// on European keyboards (e.g. ctrl+alt+e for an an euro sign.) Unfortunately,
// Windows browsers except Firefox does not have any methods except listening
// keypress and keyup events to identify if ctrl+alt keys are really used for
// inputting characters. Therefore, we listen to these events and prevent
// firing shortcut-key events if ctrl+alt keys are used for typing characters.
if (goog.userAgent.WINDOWS && !goog.userAgent.GECKO) {
goog.events.listen(this.keyTarget_, goog.events.EventType.KEYPRESS,
this.handleWindowsKeyPress_, false, this);
goog.events.listen(this.keyTarget_, goog.events.EventType.KEYUP,
this.handleWindowsKeyUp_, false, this);
}
};
/**
* Handler for when a keyup event is fired in Mac FF2 (Gecko 1.8).
* @param {goog.events.BrowserEvent} e The key event.
* @private
*/
goog.ui.KeyboardShortcutHandler.prototype.handleMacGeckoKeyUp_ = function(e) {
// Due to a bug in the way that Gecko v1.8 on Mac handles
// cut/copy/paste key events using the meta key, it is necessary to
// fake the keydown for the action keys (C,V,X) by capturing it on keyup.
// This is because the keydown events themselves are not fired by the
// browser in this case.
// Because users will often release the meta key a slight moment
// before they release the action key, we need to store whether the
// meta key has been released recently to avoid "flaky" cutting/pasting
// behavior.
if (e.keyCode == goog.events.KeyCodes.MAC_FF_META) {
this.metaKeyRecentlyReleased_ = true;
goog.Timer.callOnce(function() {
this.metaKeyRecentlyReleased_ = false;
}, 400, this);
return;
}
var metaKey = e.metaKey || this.metaKeyRecentlyReleased_;
if ((e.keyCode == goog.events.KeyCodes.C ||
e.keyCode == goog.events.KeyCodes.X ||
e.keyCode == goog.events.KeyCodes.V) && metaKey) {
e.metaKey = metaKey;
this.handleKeyDown_(e);
}
};
/**
* Returns whether this event is possibly used for typing a printable character.
* Windows uses ctrl+alt (a.k.a. alt-graph) keys for typing characters on
* European keyboards. Since only Firefox provides a method that can identify
* whether ctrl+alt keys are used for typing characters, we need to check
* whether Windows sends a keypress event to prevent firing shortcut event if
* this event is used for typing characters.
* @param {goog.events.BrowserEvent} e The key event.
* @return {boolean} Whether this event is a possible printable-key event.
* @private
*/
goog.ui.KeyboardShortcutHandler.prototype.isPossiblePrintableKey_ =
function(e) {
return goog.userAgent.WINDOWS && !goog.userAgent.GECKO &&
e.ctrlKey && e.altKey && !e.shiftKey;
};
/**
* Handler for when a keypress event is fired on Windows.
* @param {goog.events.BrowserEvent} e The key event.
* @private
*/
goog.ui.KeyboardShortcutHandler.prototype.handleWindowsKeyPress_ = function(e) {
// When this keypress event consists of a printable character, set the flag to
// prevent firing shortcut key events when we receive the succeeding keyup
// event. We accept all Unicode characters except control ones since this
// keyCode may be a non-ASCII character.
if (e.keyCode > 0x20 && this.isPossiblePrintableKey_(e)) {
this.isPrintableKey_ = true;
}
};
/**
* Handler for when a keyup event is fired on Windows.
* @param {goog.events.BrowserEvent} e The key event.
* @private
*/
goog.ui.KeyboardShortcutHandler.prototype.handleWindowsKeyUp_ = function(e) {
// For possible printable-key events, try firing a shortcut-key event only
// when this event is not used for typing a character.
if (!this.isPrintableKey_ && this.isPossiblePrintableKey_(e)) {
this.handleKeyDown_(e);
}
};
/**
* Removes the listener that was added by link {@link #initializeKeyListener}.
* @protected
*/
goog.ui.KeyboardShortcutHandler.prototype.clearKeyListener = function() {
goog.events.unlisten(this.keyTarget_, goog.events.EventType.KEYDOWN,
this.handleKeyDown_, false, this);
if (goog.userAgent.MAC &&
goog.userAgent.GECKO && goog.userAgent.isVersion('1.8')) {
goog.events.unlisten(this.keyTarget_, goog.events.EventType.KEYUP,
this.handleMacGeckoKeyUp_, false, this);
}
if (goog.userAgent.WINDOWS && !goog.userAgent.GECKO) {
goog.events.unlisten(this.keyTarget_, goog.events.EventType.KEYPRESS,
this.handleWindowsKeyPress_, false, this);
goog.events.unlisten(this.keyTarget_, goog.events.EventType.KEYUP,
this.handleWindowsKeyUp_, false, this);
}
this.keyTarget_ = null;
};
/**
* Adds or removes a stroke node to/from the given parent node.
* @param {Object} parent Parent node to add/remove stroke to/from.
* @param {Array.<Object>} strokes Array of strokes for shortcut.
* @param {?string} identifier Identifier for the task performed by shortcut or
* null to clear.
* @private
*/
goog.ui.KeyboardShortcutHandler.setShortcut_ = function(parent,
strokes,
identifier) {
var stroke = strokes.shift();
var key = goog.ui.KeyboardShortcutHandler.makeKey_(stroke.keyCode,
stroke.modifiers);
var node = parent[key];
if (node && identifier && (strokes.length == 0 || goog.isString(node))) {
throw Error('Keyboard shortcut conflicts with existing shortcut');
}
if (strokes.length) {
if (!node) {
node = parent[key] = {};
}
goog.ui.KeyboardShortcutHandler.setShortcut_(node,
strokes,
identifier);
}
else {
parent[key] = identifier;
}
};
/**
* Returns shortcut for a specific set of strokes.
* @param {Array.<number>} strokes Strokes array.
* @param {number=} opt_index Index in array to start with.
* @param {Object=} opt_list List to search for shortcut in.
* @return {string|Object} The shortcut.
* @private
*/
goog.ui.KeyboardShortcutHandler.prototype.getShortcut_ = function(
strokes, opt_index, opt_list) {
var list = opt_list || this.shortcuts_;
var index = opt_index || 0;
var stroke = strokes[index];
var node = list[stroke];
if (node && !goog.isString(node) && strokes.length - index > 1) {
return this.getShortcut_(strokes, index + 1, node);
}
return node;
};
/**
* Checks if a particular keyboard shortcut is registered.
* @param {Array.<Object>} strokes Strokes array.
* @return {boolean} True iff the keyboard is registred.
* @private
*/
goog.ui.KeyboardShortcutHandler.prototype.checkShortcut_ = function(strokes) {
var node = this.shortcuts_;
while (strokes.length > 0 && node) {
var stroke = strokes.shift();
var key = goog.ui.KeyboardShortcutHandler.makeKey_(stroke.keyCode,
stroke.modifiers);
node = node[key];
if (goog.isString(node)) {
return true;
}
}
return false;
};
/**
* Constructs key from key code and modifiers.
*
* The lower 8 bits are used for the key code, the following 3 for modifiers and
* the remaining bits are unused.
*
* @param {number} keyCode Numeric key code.
* @param {number} modifiers Required modifiers.
* @return {number} The key.
* @private
*/
goog.ui.KeyboardShortcutHandler.makeKey_ = function(keyCode, modifiers) {
// Make sure key code is just 8 bits and OR it with the modifiers left shifted
// 8 bits.
return (keyCode & 255) | (modifiers << 8);
};
/**
* Keypress handler.
* @param {goog.events.BrowserEvent} event Keypress event.
* @private
*/
goog.ui.KeyboardShortcutHandler.prototype.handleKeyDown_ = function(event) {
if (!this.isValidShortcut_(event)) {
return;
}
// For possible printable-key events, we cannot identify whether the events
// are used for typing characters until we receive respective keyup events.
// Therefore, we handle this event when we receive a succeeding keyup event
// to verify this event is not used for typing characters.
if (event.type == 'keydown' && this.isPossiblePrintableKey_(event)) {
this.isPrintableKey_ = false;
return;
}
var keyCode = goog.userAgent.GECKO ?
goog.events.KeyCodes.normalizeGeckoKeyCode(event.keyCode) :
event.keyCode;
var modifiers =
(event.shiftKey ? goog.ui.KeyboardShortcutHandler.Modifiers.SHIFT : 0) |
(event.ctrlKey ? goog.ui.KeyboardShortcutHandler.Modifiers.CTRL : 0) |
(event.altKey ? goog.ui.KeyboardShortcutHandler.Modifiers.ALT : 0) |
(event.metaKey ? goog.ui.KeyboardShortcutHandler.Modifiers.META : 0);
var stroke = goog.ui.KeyboardShortcutHandler.makeKey_(keyCode, modifiers);
// Check if any previous strokes where entered within the acceptable time
// period.
var node, shortcut;
var now = goog.now();
if (this.lastKeys_.strokes.length && now - this.lastKeys_.time <=
goog.ui.KeyboardShortcutHandler.MAX_KEY_SEQUENCE_DELAY) {
node = this.getShortcut_(this.lastKeys_.strokes);
} else {
this.lastKeys_.strokes.length = 0;
}
// Check if this stroke triggers a shortcut, either on its own or combined
// with previous strokes.
node = node ? node[stroke] : this.shortcuts_[stroke];
if (!node) {
node = this.shortcuts_[stroke];
this.lastKeys_.strokes = [];
}
// Check if stroke triggers a node.
if (node && goog.isString(node)) {
shortcut = node;
}
// Entered stroke(s) are a part of a sequence, store stroke and record
// time to allow the following stroke(s) to trigger the shortcut.
else if (node) {
this.lastKeys_.strokes.push(stroke);
this.lastKeys_.time = now;
// Prevent default action so find-as-you-type doesn't steal keyboard focus.
if (goog.userAgent.GECKO) {
event.preventDefault();
}
}
// No strokes for sequence, clear stored strokes.
else {
this.lastKeys_.strokes.length = 0;
}
// Dispatch keyboard shortcut event if a shortcut was triggered. In addition
// to the generic keyboard shortcut event a more specifc fine grained one,
// specific for the shortcut identifier, is fired.
if (shortcut) {
if (this.alwaysPreventDefault_) {
event.preventDefault();
}
if (this.alwaysStopPropagation_) {
event.stopPropagation();
}
var types = goog.ui.KeyboardShortcutHandler.EventType;
// Dispatch SHORTCUT_TRIGGERED event
var target = /** @type {Node} */ (event.target);
var triggerEvent = new goog.ui.KeyboardShortcutEvent(
types.SHORTCUT_TRIGGERED, shortcut, target);
var retVal = this.dispatchEvent(triggerEvent);
// Dispatch SHORTCUT_PREFIX_<identifier> event
var prefixEvent = new goog.ui.KeyboardShortcutEvent(
types.SHORTCUT_PREFIX + shortcut, shortcut, target);
retVal &= this.dispatchEvent(prefixEvent);
// The default action is prevented if 'preventDefault' was
// called on either event, or if a listener returned false.
if (!retVal) {
event.preventDefault();
}
// Clear stored strokes
this.lastKeys_.strokes.length = 0;
}
};
/**
* Checks if a given keypress event may be treated as a shortcut.
* @param {goog.events.BrowserEvent} event Keypress event.
* @return {boolean} Whether to attempt to process the event as a shortcut.
* @private
*/
goog.ui.KeyboardShortcutHandler.prototype.isValidShortcut_ = function(event) {
var keyCode = event.keyCode;
// Ignore Ctrl, Shift and ALT
if (keyCode == goog.events.KeyCodes.SHIFT ||
keyCode == goog.events.KeyCodes.CTRL ||
keyCode == goog.events.KeyCodes.ALT) {
return false;
}
var el = /** @type {Element} */ (event.target);
var isFormElement =
el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' ||
el.tagName == 'BUTTON' || el.tagName == 'SELECT';
var isContentEditable = !isFormElement && (el.isContentEditable ||
(el.ownerDocument && el.ownerDocument.designMode == 'on'));
if (!isFormElement && !isContentEditable) {
return true;
}
// Always allow keys registered as global to be used (typically Esc, the
// F-keys and other keys that are not typically used to manipulate text).
if (this.globalKeys_[keyCode] || this.allShortcutsAreGlobal_) {
return true;
}
if (isContentEditable) {
// For events originating from an element in editing mode we only let
// global key codes through.
return false;
}
// Event target is one of (TEXTAREA, INPUT, BUTTON, SELECT).
// Allow modifier shortcuts, unless we shouldn't.
if (this.modifierShortcutsAreGlobal_ && (
event.altKey || event.ctrlKey || event.metaKey)) {
return true;
}
// Allow ENTER to be used as shortcut for text inputs.
if (el.tagName == 'INPUT' && this.textInputs_[el.type]) {
return keyCode == goog.events.KeyCodes.ENTER;
}
// Checkboxes, radiobuttons and buttons. Allow all but SPACE as shortcut.
if (el.tagName == 'INPUT' || el.tagName == 'BUTTON') {
return keyCode != goog.events.KeyCodes.SPACE;
}
// Don't allow any additional shortcut keys for textareas or selects.
return false;
};
/**
* Object representing a keyboard shortcut event.
* @param {string} type Event type.
* @param {string} identifier Task identifier for the triggered shortcut.
* @param {Node|goog.events.EventTarget} target Target the original key press
* event originated from.
* @extends {goog.events.Event}
* @constructor
*/
goog.ui.KeyboardShortcutEvent = function(type, identifier, target) {
goog.events.Event.call(this, type, target);
/**
* Task identifier for the triggered shortcut
* @type {string}
*/
this.identifier = identifier;
};
goog.inherits(goog.ui.KeyboardShortcutEvent, 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 Provides a function that decorates an element based on its CSS
* class name.
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.ui.decorate');
goog.require('goog.ui.registry');
/**
* Decorates the element with a suitable {@link goog.ui.Component} instance, if
* a matching decorator is found.
* @param {Element} element Element to decorate.
* @return {goog.ui.Component?} New component instance, decorating the element.
*/
goog.ui.decorate = function(element) {
var decorator = goog.ui.registry.getDecorator(element);
if (decorator) {
decorator.decorate(element);
}
return decorator;
};
| 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 base menu bar factory. Can be bound to an existing
* HTML structure or can generate its own DOM.
*
* To decorate, the menu bar should be bound to an element containing children
* with the classname 'goog-menu-button'. See menubar.html for example.
*
* @see ../demos/menubar.html
*/
goog.provide('goog.ui.menuBar');
goog.require('goog.ui.Container');
goog.require('goog.ui.MenuBarRenderer');
/**
* The menuBar factory creates a new menu bar.
* @param {goog.ui.ContainerRenderer=} opt_renderer Renderer used to render or
* decorate the menu bar; defaults to {@link goog.ui.MenuBarRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for document
* interaction.
* @return {goog.ui.Container} The created menu bar.
*/
goog.ui.menuBar.create = function(opt_renderer, opt_domHelper) {
return new goog.ui.Container(
null,
opt_renderer ? opt_renderer : goog.ui.MenuBarRenderer.getInstance(),
opt_domHelper);
};
| 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 PopupBase class.
*
*/
goog.provide('goog.ui.PopupBase');
goog.provide('goog.ui.PopupBase.EventType');
goog.provide('goog.ui.PopupBase.Type');
goog.require('goog.Timer');
goog.require('goog.dom');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.fx.Transition');
goog.require('goog.fx.Transition.EventType');
goog.require('goog.style');
goog.require('goog.userAgent');
/**
* The PopupBase class provides functionality for showing and hiding a generic
* container element. It also provides the option for hiding the popup element
* if the user clicks outside the popup or the popup loses focus.
*
* @constructor
* @extends {goog.events.EventTarget}
* @param {Element=} opt_element A DOM element for the popup.
* @param {goog.ui.PopupBase.Type=} opt_type Type of popup.
*/
goog.ui.PopupBase = function(opt_element, opt_type) {
goog.events.EventTarget.call(this);
/**
* An event handler to manage the events easily
* @type {goog.events.EventHandler}
* @private
*/
this.handler_ = new goog.events.EventHandler(this);
this.setElement(opt_element || null);
if (opt_type) {
this.setType(opt_type);
}
};
goog.inherits(goog.ui.PopupBase, goog.events.EventTarget);
/**
* Constants for type of Popup
* @enum {string}
*/
goog.ui.PopupBase.Type = {
TOGGLE_DISPLAY: 'toggle_display',
MOVE_OFFSCREEN: 'move_offscreen'
};
/**
* The popup dom element that this Popup wraps.
* @type {Element}
* @private
*/
goog.ui.PopupBase.prototype.element_ = null;
/**
* Whether the Popup dismisses itself it the user clicks outside of it or the
* popup loses focus
* @type {boolean}
* @private
*/
goog.ui.PopupBase.prototype.autoHide_ = true;
/**
* Clicks outside the popup but inside this element will cause the popup to
* hide if autoHide_ is true. If this is null, then the entire document is used.
* For example, you can use a body-size div so that clicks on the browser
* scrollbar do not dismiss the popup.
* @type {Element}
* @private
*/
goog.ui.PopupBase.prototype.autoHideRegion_ = null;
/**
* Whether the popup is currently being shown.
* @type {boolean}
* @private
*/
goog.ui.PopupBase.prototype.isVisible_ = false;
/**
* Whether the popup should hide itself asynchrously. This was added because
* there are cases where hiding the element in mouse down handler in IE can
* cause textinputs to get into a bad state if the element that had focus is
* hidden.
* @type {boolean}
* @private
*/
goog.ui.PopupBase.prototype.shouldHideAsync_ = false;
/**
* The time when the popup was last shown.
* @type {number}
* @private
*/
goog.ui.PopupBase.prototype.lastShowTime_ = -1;
/**
* The time when the popup was last hidden.
* @type {number}
* @private
*/
goog.ui.PopupBase.prototype.lastHideTime_ = -1;
/**
* Whether to hide when the escape key is pressed.
* @type {boolean}
* @private
*/
goog.ui.PopupBase.prototype.hideOnEscape_ = false;
/**
* Whether to enable cross-iframe dismissal.
* @type {boolean}
* @private
*/
goog.ui.PopupBase.prototype.enableCrossIframeDismissal_ = true;
/**
* The type of popup
* @type {goog.ui.PopupBase.Type}
* @private
*/
goog.ui.PopupBase.prototype.type_ = goog.ui.PopupBase.Type.TOGGLE_DISPLAY;
/**
* Transition to play on showing the popup.
* @type {goog.fx.Transition|undefined}
* @private
*/
goog.ui.PopupBase.prototype.showTransition_;
/**
* Transition to play on hiding the popup.
* @type {goog.fx.Transition|undefined}
* @private
*/
goog.ui.PopupBase.prototype.hideTransition_;
/**
* Constants for event type fired by Popup
*
* @enum {string}
*/
goog.ui.PopupBase.EventType = {
BEFORE_SHOW: 'beforeshow',
SHOW: 'show',
BEFORE_HIDE: 'beforehide',
HIDE: 'hide'
};
/**
* A time in ms used to debounce events that happen right after each other.
*
* A note about why this is necessary. There are two cases to consider.
* First case, a popup will usually see a focus event right after it's launched
* because it's typical for it to be launched in a mouse-down event which will
* then move focus to the launching button. We don't want to think this is a
* separate user action moving focus. Second case, a user clicks on the
* launcher button to close the menu. In that case, we'll close the menu in the
* focus event and then show it again because of the mouse down event, even
* though the intention is to just close the menu. This workaround appears to
* be the least intrusive fix.
*
* @type {number}
*/
goog.ui.PopupBase.DEBOUNCE_DELAY_MS = 150;
/**
* @return {goog.ui.PopupBase.Type} The type of popup this is.
*/
goog.ui.PopupBase.prototype.getType = function() {
return this.type_;
};
/**
* Specifies the type of popup to use.
*
* @param {goog.ui.PopupBase.Type} type Type of popup.
*/
goog.ui.PopupBase.prototype.setType = function(type) {
this.type_ = type;
};
/**
* Returns whether the popup should hide itself asynchronously using a timeout
* instead of synchronously.
* @return {boolean} Whether to hide async.
*/
goog.ui.PopupBase.prototype.shouldHideAsync = function() {
return this.shouldHideAsync_;
};
/**
* Sets whether the popup should hide itself asynchronously using a timeout
* instead of synchronously.
* @param {boolean} b Whether to hide async.
*/
goog.ui.PopupBase.prototype.setShouldHideAsync = function(b) {
this.shouldHideAsync_ = b;
};
/**
* Returns the dom element that should be used for the popup.
*
* @return {Element} The popup element.
*/
goog.ui.PopupBase.prototype.getElement = function() {
return this.element_;
};
/**
* Specifies the dom element that should be used for the popup.
*
* @param {Element} elt A DOM element for the popup.
*/
goog.ui.PopupBase.prototype.setElement = function(elt) {
this.ensureNotVisible_();
this.element_ = elt;
};
/**
* Returns whether the Popup dismisses itself when the user clicks outside of
* it.
* @return {boolean} Whether the Popup autohides on an external click.
*/
goog.ui.PopupBase.prototype.getAutoHide = function() {
return this.autoHide_;
};
/**
* Sets whether the Popup dismisses itself when the user clicks outside of it.
* @param {boolean} autoHide Whether to autohide on an external click.
*/
goog.ui.PopupBase.prototype.setAutoHide = function(autoHide) {
this.ensureNotVisible_();
this.autoHide_ = autoHide;
};
/**
* @return {boolean} Whether the Popup autohides on the escape key.
*/
goog.ui.PopupBase.prototype.getHideOnEscape = function() {
return this.hideOnEscape_;
};
/**
* Sets whether the Popup dismisses itself on the escape key.
* @param {boolean} hideOnEscape Whether to autohide on the escape key.
*/
goog.ui.PopupBase.prototype.setHideOnEscape = function(hideOnEscape) {
this.ensureNotVisible_();
this.hideOnEscape_ = hideOnEscape;
};
/**
* @return {boolean} Whether cross iframe dismissal is enabled.
*/
goog.ui.PopupBase.prototype.getEnableCrossIframeDismissal = function() {
return this.enableCrossIframeDismissal_;
};
/**
* Sets whether clicks in other iframes should dismiss this popup. In some
* cases it should be disabled, because it can cause spurious
* @param {boolean} enable Whether to enable cross iframe dismissal.
*/
goog.ui.PopupBase.prototype.setEnableCrossIframeDismissal = function(enable) {
this.enableCrossIframeDismissal_ = enable;
};
/**
* Returns the region inside which the Popup dismisses itself when the user
* clicks, or null if it's the entire document.
* @return {Element} The DOM element for autohide, or null if it hasn't been
* set.
*/
goog.ui.PopupBase.prototype.getAutoHideRegion = function() {
return this.autoHideRegion_;
};
/**
* Sets the region inside which the Popup dismisses itself when the user
* clicks.
* @param {Element} element The DOM element for autohide.
*/
goog.ui.PopupBase.prototype.setAutoHideRegion = function(element) {
this.autoHideRegion_ = element;
};
/**
* Sets transition animation on showing and hiding the popup.
* @param {goog.fx.Transition=} opt_showTransition Transition to play on
* showing the popup.
* @param {goog.fx.Transition=} opt_hideTransition Transition to play on
* hiding the popup.
*/
goog.ui.PopupBase.prototype.setTransition = function(
opt_showTransition, opt_hideTransition) {
this.showTransition_ = opt_showTransition;
this.hideTransition_ = opt_hideTransition;
};
/**
* Returns the time when the popup was last shown.
*
* @return {number} time in ms since epoch when the popup was last shown, or
* -1 if the popup was never shown.
*/
goog.ui.PopupBase.prototype.getLastShowTime = function() {
return this.lastShowTime_;
};
/**
* Returns the time when the popup was last hidden.
*
* @return {number} time in ms since epoch when the popup was last hidden, or
* -1 if the popup was never hidden or is currently showing.
*/
goog.ui.PopupBase.prototype.getLastHideTime = function() {
return this.lastHideTime_;
};
/**
* Helper to throw exception if the popup is showing.
* @private
*/
goog.ui.PopupBase.prototype.ensureNotVisible_ = function() {
if (this.isVisible_) {
throw Error('Can not change this state of the popup while showing.');
}
};
/**
* Returns whether the popup is currently visible.
*
* @return {boolean} whether the popup is currently visible.
*/
goog.ui.PopupBase.prototype.isVisible = function() {
return this.isVisible_;
};
/**
* Returns whether the popup is currently visible or was visible within about
* 150 ms ago. This is used by clients to handle a very specific, but common,
* popup scenario. The button that launches the popup should close the popup
* on mouse down if the popup is alrady open. The problem is that the popup
* closes itself during the capture phase of the mouse down and thus the button
* thinks it's hidden and this should show it again. This method provides a
* good heuristic for clients. Typically in their event handler they will have
* code that is:
*
* if (menu.isOrWasRecentlyVisible()) {
* menu.setVisible(false);
* } else {
* ... // code to position menu and initialize other state
* menu.setVisible(true);
* }
* @return {boolean} Whether the popup is currently visible or was visible
* within about 150 ms ago.
*/
goog.ui.PopupBase.prototype.isOrWasRecentlyVisible = function() {
return this.isVisible_ ||
(goog.now() - this.lastHideTime_ <
goog.ui.PopupBase.DEBOUNCE_DELAY_MS);
};
/**
* Sets whether the popup should be visible. After this method
* returns, isVisible() will always return the new state, even if
* there is a transition.
*
* @param {boolean} visible Desired visibility state.
*/
goog.ui.PopupBase.prototype.setVisible = function(visible) {
// Make sure that any currently running transition is stopped.
if (this.showTransition_) this.showTransition_.stop();
if (this.hideTransition_) this.hideTransition_.stop();
if (visible) {
this.show_();
} else {
this.hide_();
}
};
/**
* Repositions the popup according to the current state.
* Should be overriden by subclases.
*/
goog.ui.PopupBase.prototype.reposition = goog.nullFunction;
/**
* Does the work to show the popup.
* @private
*/
goog.ui.PopupBase.prototype.show_ = function() {
// Ignore call if we are already showing.
if (this.isVisible_) {
return;
}
// Give derived classes and handlers a chance to customize popup.
if (!this.onBeforeShow()) {
return;
}
// Allow callers to set the element in the BEFORE_SHOW event.
if (!this.element_) {
throw Error('Caller must call setElement before trying to show the popup');
}
// Call reposition after onBeforeShow, as it may change the style and/or
// content of the popup and thereby affecting the size which is used for the
// viewport calculation.
this.reposition();
var doc = goog.dom.getOwnerDocument(this.element_);
if (this.hideOnEscape_) {
// Handle the escape keys. Listen in the capture phase so that we can
// stop the escape key from propagating to other elements. For example,
// if there is a popup within a dialog box, we want the popup to be
// dismissed first, rather than the dialog.
this.handler_.listen(doc, goog.events.EventType.KEYDOWN,
this.onDocumentKeyDown_, true);
}
// Set up event handlers.
if (this.autoHide_) {
// Even if the popup is not in the focused document, we want to
// close it on mousedowns in the document it's in.
this.handler_.listen(doc, goog.events.EventType.MOUSEDOWN,
this.onDocumentMouseDown_, true);
if (goog.userAgent.IE) {
// We want to know about deactivates/mousedowns on the document with focus
// The top-level document won't get a deactivate event if the focus is
// in an iframe and the deactivate fires within that iframe.
// The active element in the top-level document will remain the iframe
// itself.
var activeElement;
/** @preserveTry */
try {
activeElement = doc.activeElement;
} catch (e) {
// There is an IE browser bug which can cause just the reading of
// document.activeElement to throw an Unspecified Error. This
// may have to do with loading a popup within a hidden iframe.
}
while (activeElement && activeElement.nodeName == 'IFRAME') {
/** @preserveTry */
try {
var tempDoc = goog.dom.getFrameContentDocument(activeElement);
} catch (e) {
// The frame is on a different domain that its parent document
// This way, we grab the lowest-level document object we can get
// a handle on given cross-domain security.
break;
}
doc = tempDoc;
activeElement = doc.activeElement;
}
// Handle mousedowns in the focused document in case the user clicks
// on the activeElement (in which case the popup should hide).
this.handler_.listen(doc, goog.events.EventType.MOUSEDOWN,
this.onDocumentMouseDown_, true);
// If the active element inside the focused document changes, then
// we probably need to hide the popup.
this.handler_.listen(doc, goog.events.EventType.DEACTIVATE,
this.onDocumentBlur_);
} else {
this.handler_.listen(doc, goog.events.EventType.BLUR,
this.onDocumentBlur_);
}
}
// Make the popup visible.
if (this.type_ == goog.ui.PopupBase.Type.TOGGLE_DISPLAY) {
this.showPopupElement();
} else if (this.type_ == goog.ui.PopupBase.Type.MOVE_OFFSCREEN) {
this.reposition();
}
this.isVisible_ = true;
// If there is transition to play, we play it and fire SHOW event after
// the transition is over.
if (this.showTransition_) {
goog.events.listenOnce(
/** @type {goog.events.EventTarget} */ (this.showTransition_),
goog.fx.Transition.EventType.END, this.onShow_, false, this);
this.showTransition_.play();
} else {
// Notify derived classes and handlers.
this.onShow_();
}
};
/**
* Hides the popup. This call is idempotent.
*
* @param {Object=} opt_target Target of the event causing the hide.
* @return {boolean} Whether the popup was hidden and not cancelled.
* @private
*/
goog.ui.PopupBase.prototype.hide_ = function(opt_target) {
// Give derived classes and handlers a chance to cancel hiding.
if (!this.isVisible_ || !this.onBeforeHide_(opt_target)) {
return false;
}
// Remove any listeners we attached when showing the popup.
if (this.handler_) {
this.handler_.removeAll();
}
// Set visibility to hidden even if there is a transition.
this.isVisible_ = false;
this.lastHideTime_ = goog.now();
// If there is transition to play, we play it and only hide the element
// (and fire HIDE event) after the transition is over.
if (this.hideTransition_) {
goog.events.listenOnce(
/** @type {goog.events.EventTarget} */ (this.hideTransition_),
goog.fx.Transition.EventType.END,
goog.partial(this.continueHidingPopup_, opt_target), false, this);
this.hideTransition_.play();
} else {
this.continueHidingPopup_(opt_target);
}
return true;
};
/**
* Continues hiding the popup. This is a continuation from hide_. It is
* a separate method so that we can add a transition before hiding.
* @param {Object=} opt_target Target of the event causing the hide.
* @private
*/
goog.ui.PopupBase.prototype.continueHidingPopup_ = function(opt_target) {
// Hide the popup.
if (this.type_ == goog.ui.PopupBase.Type.TOGGLE_DISPLAY) {
if (this.shouldHideAsync_) {
goog.Timer.callOnce(this.hidePopupElement_, 0, this);
} else {
this.hidePopupElement_();
}
} else if (this.type_ == goog.ui.PopupBase.Type.MOVE_OFFSCREEN) {
this.moveOffscreen_();
}
// Notify derived classes and handlers.
this.onHide_(opt_target);
};
/**
* Shows the popup element.
* @protected
*/
goog.ui.PopupBase.prototype.showPopupElement = function() {
this.element_.style.visibility = 'visible';
goog.style.setElementShown(this.element_, true);
};
/**
* Hides the popup element.
* @private
*/
goog.ui.PopupBase.prototype.hidePopupElement_ = function() {
this.element_.style.visibility = 'hidden';
goog.style.setElementShown(this.element_, false);
};
/**
* Hides the popup by moving it offscreen.
*
* @private
*/
goog.ui.PopupBase.prototype.moveOffscreen_ = function() {
this.element_.style.top = '-10000px';
};
/**
* Called before the popup is shown. Derived classes can override to hook this
* event but should make sure to call the parent class method.
*
* @return {boolean} If anyone called preventDefault on the event object (or
* if any of the handlers returns false this will also return false.
* @protected
*/
goog.ui.PopupBase.prototype.onBeforeShow = function() {
return this.dispatchEvent(goog.ui.PopupBase.EventType.BEFORE_SHOW);
};
/**
* Called after the popup is shown. Derived classes can override to hook this
* event but should make sure to call the parent class method.
* @protected
* @suppress {underscore}
*/
goog.ui.PopupBase.prototype.onShow_ = function() {
this.lastShowTime_ = goog.now();
this.lastHideTime_ = -1;
this.dispatchEvent(goog.ui.PopupBase.EventType.SHOW);
};
/**
* Called before the popup is hidden. Derived classes can override to hook this
* event but should make sure to call the parent class method.
*
* @param {Object=} opt_target Target of the event causing the hide.
* @return {boolean} If anyone called preventDefault on the event object (or
* if any of the handlers returns false this will also return false.
* @protected
* @suppress {underscore}
*/
goog.ui.PopupBase.prototype.onBeforeHide_ = function(opt_target) {
return this.dispatchEvent({
type: goog.ui.PopupBase.EventType.BEFORE_HIDE,
target: opt_target
});
};
/**
* Called after the popup is hidden. Derived classes can override to hook this
* event but should make sure to call the parent class method.
* @param {Object=} opt_target Target of the event causing the hide.
* @protected
* @suppress {underscore}
*/
goog.ui.PopupBase.prototype.onHide_ = function(opt_target) {
this.dispatchEvent({
type: goog.ui.PopupBase.EventType.HIDE,
target: opt_target
});
};
/**
* Mouse down handler for the document on capture phase. Used to hide the
* popup for auto-hide mode.
*
* @param {goog.events.BrowserEvent} e The event object.
* @private
*/
goog.ui.PopupBase.prototype.onDocumentMouseDown_ = function(e) {
var target = /** @type {Node} */ (e.target);
if (!goog.dom.contains(this.element_, target) &&
(!this.autoHideRegion_ || goog.dom.contains(
this.autoHideRegion_, target)) &&
!this.shouldDebounce_()) {
// Mouse click was outside popup, so hide.
this.hide_(target);
}
};
/**
* Handles key-downs on the document to handle the escape key.
*
* @param {goog.events.BrowserEvent} e The event object.
* @private
*/
goog.ui.PopupBase.prototype.onDocumentKeyDown_ = function(e) {
if (e.keyCode == goog.events.KeyCodes.ESC) {
if (this.hide_(e.target)) {
// Eat the escape key, but only if this popup was actually closed.
e.preventDefault();
e.stopPropagation();
}
}
};
/**
* Deactivate handler(IE) and blur handler (other browsers) for document.
* Used to hide the popup for auto-hide mode.
*
* @param {goog.events.BrowserEvent} e The event object.
* @private
*/
goog.ui.PopupBase.prototype.onDocumentBlur_ = function(e) {
if (!this.enableCrossIframeDismissal_) {
return;
}
var doc = goog.dom.getOwnerDocument(this.element_);
// Ignore blur events if the active element is still inside the popup or if
// there is no longer an active element. For example, a widget like a
// goog.ui.Button might programatically blur itself before losing tabIndex.
if (goog.userAgent.IE || goog.userAgent.OPERA) {
var activeElement = doc.activeElement;
if (!activeElement || goog.dom.contains(this.element_,
activeElement) || activeElement.tagName == 'BODY') {
return;
}
// Ignore blur events not for the document itself in non-IE browsers.
} else if (e.target != doc) {
return;
}
// Debounce the initial focus move.
if (this.shouldDebounce_()) {
return;
}
this.hide_();
};
/**
* @return {boolean} Whether the time since last show is less than the debounce
* delay.
* @private
*/
goog.ui.PopupBase.prototype.shouldDebounce_ = function() {
return goog.now() - this.lastShowTime_ < goog.ui.PopupBase.DEBOUNCE_DELAY_MS;
};
/** @override */
goog.ui.PopupBase.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
this.handler_.dispose();
goog.dispose(this.showTransition_);
goog.dispose(this.hideTransition_);
delete this.element_;
delete this.handler_;
};
| 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 Scroll behavior that can be added onto a container.
* @author gboyer@google.com (Garry Boyer)
*/
goog.provide('goog.ui.ContainerScroller');
goog.require('goog.Timer');
goog.require('goog.events.EventHandler');
goog.require('goog.style');
goog.require('goog.ui.Component');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.Container.EventType');
/**
* Plug-on scrolling behavior for a container.
*
* Use this to style containers, such as pop-up menus, to be scrolling, and
* automatically keep the highlighted element visible.
*
* To use this, first style your container with the desired overflow
* properties and height to achieve vertical scrolling. Also, the scrolling
* div should have no vertical padding, for two reasons: it is difficult to
* compensate for, and is generally not what you want due to the strange way
* CSS handles padding on the scrolling dimension.
*
* The container must already be rendered before this may be constructed.
*
* @param {!goog.ui.Container} container The container to attach behavior to.
* @constructor
* @extends {goog.Disposable}
*/
goog.ui.ContainerScroller = function(container) {
goog.Disposable.call(this);
/**
* The container that we are bestowing scroll behavior on.
* @type {!goog.ui.Container}
* @private
*/
this.container_ = container;
/**
* Event handler for this object.
* @type {!goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler(this);
this.eventHandler_.listen(container, goog.ui.Component.EventType.HIGHLIGHT,
this.onHighlight_);
this.eventHandler_.listen(container, goog.ui.Component.EventType.ENTER,
this.onEnter_);
this.eventHandler_.listen(container, goog.ui.Container.EventType.AFTER_SHOW,
this.onAfterShow_);
this.eventHandler_.listen(container, goog.ui.Component.EventType.HIDE,
this.onHide_);
// TODO(gboyer): Allow a ContainerScroller to be attached with a Container
// before the container is rendered.
this.doScrolling_(true);
};
goog.inherits(goog.ui.ContainerScroller, goog.Disposable);
/**
* The last target the user hovered over.
*
* @see #onEnter_
* @type {goog.ui.Component}
* @private
*/
goog.ui.ContainerScroller.prototype.lastEnterTarget_ = null;
/**
* The scrollTop of the container before it was hidden.
* Used to restore the scroll position when the container is shown again.
* @type {?number}
* @private
*/
goog.ui.ContainerScroller.prototype.scrollTopBeforeHide_ = null;
/**
* Whether we are disabling the default handler for hovering.
*
* @see #onEnter_
* @see #temporarilyDisableHover_
* @type {boolean}
* @private
*/
goog.ui.ContainerScroller.prototype.disableHover_ = false;
/**
* Handles hover events on the container's children.
*
* Helps enforce two constraints: scrolling should not cause mouse highlights,
* and mouse highlights should not cause scrolling.
*
* @param {goog.events.Event} e The container's ENTER event.
* @private
*/
goog.ui.ContainerScroller.prototype.onEnter_ = function(e) {
if (this.disableHover_) {
// The container was scrolled recently. Since the mouse may be over the
// container, stop the default action of the ENTER event from causing
// highlights.
e.preventDefault();
} else {
// The mouse is moving and causing hover events. Stop the resulting
// highlight (if it happens) from causing a scroll.
this.lastEnterTarget_ = /** @type {goog.ui.Component} */ (e.target);
}
};
/**
* Handles highlight events on the container's children.
* @param {goog.events.Event} e The container's highlight event.
* @private
*/
goog.ui.ContainerScroller.prototype.onHighlight_ = function(e) {
this.doScrolling_();
};
/**
* Handles AFTER_SHOW events on the container. Makes the container
* scroll to the previously scrolled position (if there was one),
* then adjust it to make the highlighted element be in view (if there is one).
* If there was no previous scroll position, then center the highlighted
* element (if there is one).
* @param {goog.events.Event} e The container's AFTER_SHOW event.
* @private
*/
goog.ui.ContainerScroller.prototype.onAfterShow_ = function(e) {
if (this.scrollTopBeforeHide_ != null) {
this.container_.getElement().scrollTop = this.scrollTopBeforeHide_;
// Make sure the highlighted item is still visible, in case the list
// or its hilighted item has changed.
this.doScrolling_(false);
} else {
this.doScrolling_(true);
}
};
/**
* Handles hide events on the container. Clears out the last enter target,
* since it is no longer applicable, and remembers the scroll position of
* the menu so that it can be restored when the menu is reopened.
* @param {goog.events.Event} e The container's hide event.
* @private
*/
goog.ui.ContainerScroller.prototype.onHide_ = function(e) {
if (e.target == this.container_) {
this.lastEnterTarget_ = null;
this.scrollTopBeforeHide_ = this.container_.getElement().scrollTop;
}
};
/**
* Centers the currently highlighted item, if this is scrollable.
* @param {boolean=} opt_center Whether to center the highlighted element
* rather than simply ensure it is in view. Useful for the first
* render.
* @private
*/
goog.ui.ContainerScroller.prototype.doScrolling_ = function(opt_center) {
var highlighted = this.container_.getHighlighted();
// Only scroll if we're visible and there is a highlighted item.
if (this.container_.isVisible() && highlighted &&
highlighted != this.lastEnterTarget_) {
var element = this.container_.getElement();
goog.style.scrollIntoContainerView(highlighted.getElement(), element,
opt_center);
this.temporarilyDisableHover_();
this.lastEnterTarget_ = null;
}
};
/**
* Temporarily disables hover events from changing highlight.
* @see #onEnter_
* @private
*/
goog.ui.ContainerScroller.prototype.temporarilyDisableHover_ = function() {
this.disableHover_ = true;
goog.Timer.callOnce(function() {
this.disableHover_ = false;
}, 0, this);
};
/** @override */
goog.ui.ContainerScroller.prototype.disposeInternal = function() {
goog.ui.ContainerScroller.superClass_.disposeInternal.call(this);
this.eventHandler_.dispose();
this.lastEnterTarget_ = null;
};
| 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 toolbar-style renderer for {@link goog.ui.ColorMenuButton}.
*
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.ui.ToolbarColorMenuButtonRenderer');
goog.require('goog.dom.classes');
goog.require('goog.ui.ColorMenuButtonRenderer');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.MenuButtonRenderer');
goog.require('goog.ui.ToolbarMenuButtonRenderer');
/**
* Toolbar-style renderer for {@link goog.ui.ColorMenuButton}s.
* @constructor
* @extends {goog.ui.ToolbarMenuButtonRenderer}
*/
goog.ui.ToolbarColorMenuButtonRenderer = function() {
goog.ui.ToolbarMenuButtonRenderer.call(this);
};
goog.inherits(goog.ui.ToolbarColorMenuButtonRenderer,
goog.ui.ToolbarMenuButtonRenderer);
goog.addSingletonGetter(goog.ui.ToolbarColorMenuButtonRenderer);
/**
* Overrides the superclass implementation by wrapping the caption text or DOM
* structure in a color indicator element. Creates the following DOM structure:
* <div class="goog-inline-block goog-toolbar-menu-button-caption">
* <div class="goog-color-menu-button-indicator">
* Contents...
* </div>
* </div>
* @param {goog.ui.ControlContent} content Text caption or DOM structure.
* @param {goog.dom.DomHelper} dom DOM helper, used for document interaction.
* @return {Element} Caption element.
* @see goog.ui.ToolbarColorMenuButtonRenderer#createColorIndicator
* @override
*/
goog.ui.ToolbarColorMenuButtonRenderer.prototype.createCaption = function(
content, dom) {
return goog.ui.MenuButtonRenderer.wrapCaption(
goog.ui.ColorMenuButtonRenderer.wrapCaption(content, dom),
this.getCssClass(),
dom);
};
/**
* Takes a color menu button control's root element and a value object
* (which is assumed to be a color), and updates the button's DOM to reflect
* the new color. Overrides {@link goog.ui.ButtonRenderer#setValue}.
* @param {Element} element The button control's root element (if rendered).
* @param {*} value New value; assumed to be a color spec string.
* @override
*/
goog.ui.ToolbarColorMenuButtonRenderer.prototype.setValue = function(element,
value) {
if (element) {
goog.ui.ColorMenuButtonRenderer.setCaptionValue(
this.getContentElement(element), value);
}
};
/**
* Initializes the button's DOM when it enters the document. Overrides the
* superclass implementation by making sure the button's color indicator is
* initialized.
* @param {goog.ui.Control} button goog.ui.ColorMenuButton whose DOM is to be
* initialized as it enters the document.
* @override
*/
goog.ui.ToolbarColorMenuButtonRenderer.prototype.initializeDom = function(
button) {
this.setValue(button.getElement(), button.getValue());
goog.dom.classes.add(button.getElement(),
goog.getCssName('goog-toolbar-color-menu-button'));
goog.ui.ToolbarColorMenuButtonRenderer.superClass_.initializeDom.call(this,
button);
};
| 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 Default renderer for {@link goog.ui.Button}s.
*
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.ui.ButtonRenderer');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.Role');
goog.require('goog.a11y.aria.State');
goog.require('goog.asserts');
goog.require('goog.ui.ButtonSide');
goog.require('goog.ui.Component.State');
goog.require('goog.ui.ControlRenderer');
/**
* Default renderer for {@link goog.ui.Button}s. Extends the superclass with
* the following button-specific API methods:
* <ul>
* <li>{@code getValue} - returns the button element's value
* <li>{@code setValue} - updates the button element to reflect its new value
* <li>{@code getTooltip} - returns the button element's tooltip text
* <li>{@code setTooltip} - updates the button element's tooltip text
* <li>{@code setCollapsed} - removes one or both of the button element's
* borders
* </ul>
* For alternate renderers, see {@link goog.ui.NativeButtonRenderer},
* {@link goog.ui.CustomButtonRenderer}, and {@link goog.ui.FlatButtonRenderer}.
* @constructor
* @extends {goog.ui.ControlRenderer}
*/
goog.ui.ButtonRenderer = function() {
goog.ui.ControlRenderer.call(this);
};
goog.inherits(goog.ui.ButtonRenderer, goog.ui.ControlRenderer);
goog.addSingletonGetter(goog.ui.ButtonRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.ButtonRenderer.CSS_CLASS = goog.getCssName('goog-button');
/**
* Returns the ARIA role to be applied to buttons.
* @return {goog.a11y.aria.Role|undefined} ARIA role.
* @override
*/
goog.ui.ButtonRenderer.prototype.getAriaRole = function() {
return goog.a11y.aria.Role.BUTTON;
};
/**
* Updates the button's ARIA (accessibility) state if the button is being
* treated as a checkbox.
* @param {Element} element Element whose ARIA state is to be updated.
* @param {goog.ui.Component.State} state Component state being enabled or
* disabled.
* @param {boolean} enable Whether the state is being enabled or disabled.
* @protected
* @override
*/
goog.ui.ButtonRenderer.prototype.updateAriaState = function(element, state,
enable) {
// If button has CHECKED state, assign ARIA atrribute aria-pressed
if (state == goog.ui.Component.State.CHECKED) {
goog.asserts.assert(element,
'The button DOM element cannot be null.');
goog.a11y.aria.setState(element, goog.a11y.aria.State.PRESSED, enable);
} else {
goog.ui.ButtonRenderer.superClass_.updateAriaState.call(this, element,
state, enable);
}
};
/** @override */
goog.ui.ButtonRenderer.prototype.createDom = function(button) {
var element = goog.ui.ButtonRenderer.superClass_.createDom.call(this, button);
var tooltip = button.getTooltip();
if (tooltip) {
this.setTooltip(element, tooltip);
}
var value = button.getValue();
if (value) {
this.setValue(element, value);
}
// If this is a toggle button, set ARIA state
if (button.isSupportedState(goog.ui.Component.State.CHECKED)) {
this.updateAriaState(element, goog.ui.Component.State.CHECKED,
button.isChecked());
}
return element;
};
/** @override */
goog.ui.ButtonRenderer.prototype.decorate = function(button, element) {
// The superclass implementation takes care of common attributes; we only
// need to set the value and the tooltip.
element = goog.ui.ButtonRenderer.superClass_.decorate.call(this, button,
element);
button.setValueInternal(this.getValue(element));
button.setTooltipInternal(this.getTooltip(element));
// If this is a toggle button, set ARIA state
if (button.isSupportedState(goog.ui.Component.State.CHECKED)) {
this.updateAriaState(element, goog.ui.Component.State.CHECKED,
button.isChecked());
}
return element;
};
/**
* Takes a button's root element, and returns the value associated with it.
* No-op in the base class.
* @param {Element} element The button's root element.
* @return {string|undefined} The button's value (undefined if none).
*/
goog.ui.ButtonRenderer.prototype.getValue = goog.nullFunction;
/**
* Takes a button's root element and a value, and updates the element to reflect
* the new value. No-op in the base class.
* @param {Element} element The button's root element.
* @param {string} value New value.
*/
goog.ui.ButtonRenderer.prototype.setValue = goog.nullFunction;
/**
* Takes a button's root element, and returns its tooltip text.
* @param {Element} element The button's root element.
* @return {string|undefined} The tooltip text.
*/
goog.ui.ButtonRenderer.prototype.getTooltip = function(element) {
return element.title;
};
/**
* Takes a button's root element and a tooltip string, and updates the element
* with the new tooltip.
* @param {Element} element The button's root element.
* @param {string} tooltip New tooltip text.
* @protected
*/
goog.ui.ButtonRenderer.prototype.setTooltip = function(element, tooltip) {
if (element) {
element.title = tooltip || '';
}
};
/**
* Collapses the border on one or both sides of the button, allowing it to be
* combined with the adjacent button(s), forming a single UI componenet with
* multiple targets.
* @param {goog.ui.Button} button Button to update.
* @param {number} sides Bitmap of one or more {@link goog.ui.ButtonSide}s for
* which borders should be collapsed.
* @protected
*/
goog.ui.ButtonRenderer.prototype.setCollapsed = function(button, sides) {
var isRtl = button.isRightToLeft();
var collapseLeftClassName =
goog.getCssName(this.getStructuralCssClass(), 'collapse-left');
var collapseRightClassName =
goog.getCssName(this.getStructuralCssClass(), 'collapse-right');
button.enableClassName(isRtl ? collapseRightClassName : collapseLeftClassName,
!!(sides & goog.ui.ButtonSide.START));
button.enableClassName(isRtl ? collapseLeftClassName : collapseRightClassName,
!!(sides & goog.ui.ButtonSide.END));
};
/** @override */
goog.ui.ButtonRenderer.prototype.getCssClass = function() {
return goog.ui.ButtonRenderer.CSS_CLASS;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A palette control. A palette is a grid that the user can
* highlight or select via the keyboard or the mouse.
*
* @author attila@google.com (Attila Bodis)
* @see ../demos/palette.html
*/
goog.provide('goog.ui.Palette');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.math.Size');
goog.require('goog.ui.Component');
goog.require('goog.ui.Control');
goog.require('goog.ui.PaletteRenderer');
goog.require('goog.ui.SelectionModel');
/**
* A palette is a grid of DOM nodes that the user can highlight or select via
* the keyboard or the mouse. The selection state of the palette is controlled
* an ACTION event. Event listeners may retrieve the selected item using the
* {@link #getSelectedItem} or {@link #getSelectedIndex} method.
*
* Use this class as the base for components like color palettes or emoticon
* pickers. Use {@link #setContent} to set/change the items in the palette
* after construction. See palette.html demo for example usage.
*
* @param {Array.<Node>} items Array of DOM nodes to be displayed as items
* in the palette grid (limited to one per cell).
* @param {goog.ui.PaletteRenderer=} opt_renderer Renderer used to render or
* decorate the palette; defaults to {@link goog.ui.PaletteRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
* document interaction.
* @constructor
* @extends {goog.ui.Control}
*/
goog.ui.Palette = function(items, opt_renderer, opt_domHelper) {
goog.base(this, items,
opt_renderer || goog.ui.PaletteRenderer.getInstance(), opt_domHelper);
this.setAutoStates(goog.ui.Component.State.CHECKED |
goog.ui.Component.State.SELECTED | goog.ui.Component.State.OPENED, false);
/**
* A fake component for dispatching events on palette cell changes.
* @type {!goog.ui.Palette.CurrentCell_}
* @private
*/
this.currentCellControl_ = new goog.ui.Palette.CurrentCell_();
this.currentCellControl_.setParentEventTarget(this);
};
goog.inherits(goog.ui.Palette, goog.ui.Control);
/**
* Events fired by the palette object
* @enum {string}
*/
goog.ui.Palette.EventType = {
AFTER_HIGHLIGHT: goog.events.getUniqueId('afterhighlight')
};
/**
* Palette dimensions (columns x rows). If the number of rows is undefined,
* it is calculated on first use.
* @type {goog.math.Size}
* @private
*/
goog.ui.Palette.prototype.size_ = null;
/**
* Index of the currently highlighted item (-1 if none).
* @type {number}
* @private
*/
goog.ui.Palette.prototype.highlightedIndex_ = -1;
/**
* Selection model controlling the palette's selection state.
* @type {goog.ui.SelectionModel}
* @private
*/
goog.ui.Palette.prototype.selectionModel_ = null;
// goog.ui.Component / goog.ui.Control implementation.
/** @override */
goog.ui.Palette.prototype.disposeInternal = function() {
goog.ui.Palette.superClass_.disposeInternal.call(this);
if (this.selectionModel_) {
this.selectionModel_.dispose();
this.selectionModel_ = null;
}
this.size_ = null;
this.currentCellControl_.dispose();
};
/**
* Overrides {@link goog.ui.Control#setContentInternal} by also updating the
* grid size and the selection model. Considered protected.
* @param {goog.ui.ControlContent} content Array of DOM nodes to be displayed
* as items in the palette grid (one item per cell).
* @protected
* @override
*/
goog.ui.Palette.prototype.setContentInternal = function(content) {
var items = /** @type {Array.<Node>} */ (content);
goog.ui.Palette.superClass_.setContentInternal.call(this, items);
// Adjust the palette size.
this.adjustSize_();
// Add the items to the selection model, replacing previous items (if any).
if (this.selectionModel_) {
// We already have a selection model; just replace the items.
this.selectionModel_.clear();
this.selectionModel_.addItems(items);
} else {
// Create a selection model, initialize the items, and hook up handlers.
this.selectionModel_ = new goog.ui.SelectionModel(items);
this.selectionModel_.setSelectionHandler(goog.bind(this.selectItem_,
this));
this.getHandler().listen(this.selectionModel_,
goog.events.EventType.SELECT, this.handleSelectionChange);
}
// In all cases, clear the highlight.
this.highlightedIndex_ = -1;
};
/**
* Overrides {@link goog.ui.Control#getCaption} to return the empty string,
* since palettes don't have text captions.
* @return {string} The empty string.
* @override
*/
goog.ui.Palette.prototype.getCaption = function() {
return '';
};
/**
* Overrides {@link goog.ui.Control#setCaption} to be a no-op, since palettes
* don't have text captions.
* @param {string} caption Ignored.
* @override
*/
goog.ui.Palette.prototype.setCaption = function(caption) {
// Do nothing.
};
// Palette event handling.
/**
* Handles mouseover events. Overrides {@link goog.ui.Control#handleMouseOver}
* by determining which palette item (if any) was moused over, highlighting it,
* and un-highlighting any previously-highlighted item.
* @param {goog.events.BrowserEvent} e Mouse event to handle.
* @override
*/
goog.ui.Palette.prototype.handleMouseOver = function(e) {
goog.ui.Palette.superClass_.handleMouseOver.call(this, e);
var item = this.getRenderer().getContainingItem(this, e.target);
if (item && e.relatedTarget && goog.dom.contains(item, e.relatedTarget)) {
// Ignore internal mouse moves.
return;
}
if (item != this.getHighlightedItem()) {
this.setHighlightedItem(item);
}
};
/**
* Handles mouseout events. Overrides {@link goog.ui.Control#handleMouseOut}
* by determining the palette item that the mouse just left (if any), and
* making sure it is un-highlighted.
* @param {goog.events.BrowserEvent} e Mouse event to handle.
* @override
*/
goog.ui.Palette.prototype.handleMouseOut = function(e) {
goog.ui.Palette.superClass_.handleMouseOut.call(this, e);
var item = this.getRenderer().getContainingItem(this, e.target);
if (item && e.relatedTarget && goog.dom.contains(item, e.relatedTarget)) {
// Ignore internal mouse moves.
return;
}
if (item == this.getHighlightedItem()) {
this.setHighlightedItem(null);
}
};
/**
* Handles mousedown events. Overrides {@link goog.ui.Control#handleMouseDown}
* by ensuring that the item on which the user moused down is highlighted.
* @param {goog.events.Event} e Mouse event to handle.
* @override
*/
goog.ui.Palette.prototype.handleMouseDown = function(e) {
goog.ui.Palette.superClass_.handleMouseDown.call(this, e);
if (this.isActive()) {
// Make sure we move the highlight to the cell on which the user moused
// down.
var item = this.getRenderer().getContainingItem(this, e.target);
if (item != this.getHighlightedItem()) {
this.setHighlightedItem(item);
}
}
};
/**
* Selects the currently highlighted palette item (triggered by mouseup or by
* keyboard action). Overrides {@link goog.ui.Control#performActionInternal}
* by selecting the highlighted item and dispatching an ACTION event.
* @param {goog.events.Event} e Mouse or key event that triggered the action.
* @return {boolean} True if the action was allowed to proceed, false otherwise.
* @override
*/
goog.ui.Palette.prototype.performActionInternal = function(e) {
var item = this.getHighlightedItem();
if (item) {
this.setSelectedItem(item);
return goog.base(this, 'performActionInternal', e);
}
return false;
};
/**
* Handles keyboard events dispatched while the palette has focus. Moves the
* highlight on arrow keys, and selects the highlighted item on Enter or Space.
* Returns true if the event was handled, false otherwise. In particular, if
* the user attempts to navigate out of the grid, the highlight isn't changed,
* and this method returns false; it is then up to the parent component to
* handle the event (e.g. by wrapping the highlight around). Overrides {@link
* goog.ui.Control#handleKeyEvent}.
* @param {goog.events.KeyEvent} e Key event to handle.
* @return {boolean} True iff the key event was handled by the component.
* @override
*/
goog.ui.Palette.prototype.handleKeyEvent = function(e) {
var items = this.getContent();
var numItems = items ? items.length : 0;
var numColumns = this.size_.width;
// If the component is disabled or the palette is empty, bail.
if (numItems == 0 || !this.isEnabled()) {
return false;
}
// User hit ENTER or SPACE; trigger action.
if (e.keyCode == goog.events.KeyCodes.ENTER ||
e.keyCode == goog.events.KeyCodes.SPACE) {
return this.performActionInternal(e);
}
// User hit HOME or END; move highlight.
if (e.keyCode == goog.events.KeyCodes.HOME) {
this.setHighlightedIndex(0);
return true;
} else if (e.keyCode == goog.events.KeyCodes.END) {
this.setHighlightedIndex(numItems - 1);
return true;
}
// If nothing is highlighted, start from the selected index. If nothing is
// selected either, highlightedIndex is -1.
var highlightedIndex = this.highlightedIndex_ < 0 ? this.getSelectedIndex() :
this.highlightedIndex_;
switch (e.keyCode) {
case goog.events.KeyCodes.LEFT:
if (highlightedIndex == -1) {
highlightedIndex = numItems;
}
if (highlightedIndex > 0) {
this.setHighlightedIndex(highlightedIndex - 1);
e.preventDefault();
return true;
}
break;
case goog.events.KeyCodes.RIGHT:
if (highlightedIndex < numItems - 1) {
this.setHighlightedIndex(highlightedIndex + 1);
e.preventDefault();
return true;
}
break;
case goog.events.KeyCodes.UP:
if (highlightedIndex == -1) {
highlightedIndex = numItems + numColumns - 1;
}
if (highlightedIndex >= numColumns) {
this.setHighlightedIndex(highlightedIndex - numColumns);
e.preventDefault();
return true;
}
break;
case goog.events.KeyCodes.DOWN:
if (highlightedIndex == -1) {
highlightedIndex = -numColumns;
}
if (highlightedIndex < numItems - numColumns) {
this.setHighlightedIndex(highlightedIndex + numColumns);
e.preventDefault();
return true;
}
break;
}
return false;
};
/**
* Handles selection change events dispatched by the selection model.
* @param {goog.events.Event} e Selection event to handle.
*/
goog.ui.Palette.prototype.handleSelectionChange = function(e) {
// No-op in the base class.
};
// Palette management.
/**
* Returns the size of the palette grid.
* @return {goog.math.Size} Palette size (columns x rows).
*/
goog.ui.Palette.prototype.getSize = function() {
return this.size_;
};
/**
* Sets the size of the palette grid to the given size. Callers can either
* pass a single {@link goog.math.Size} or a pair of numbers (first the number
* of columns, then the number of rows) to this method. In both cases, the
* number of rows is optional and will be calculated automatically if needed.
* It is an error to attempt to change the size of the palette after it has
* been rendered.
* @param {goog.math.Size|number} size Either a size object or the number of
* columns.
* @param {number=} opt_rows The number of rows (optional).
*/
goog.ui.Palette.prototype.setSize = function(size, opt_rows) {
if (this.getElement()) {
throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
}
this.size_ = goog.isNumber(size) ?
new goog.math.Size(size, /** @type {number} */ (opt_rows)) : size;
// Adjust size, if needed.
this.adjustSize_();
};
/**
* Returns the 0-based index of the currently highlighted palette item, or -1
* if no item is highlighted.
* @return {number} Index of the highlighted item (-1 if none).
*/
goog.ui.Palette.prototype.getHighlightedIndex = function() {
return this.highlightedIndex_;
};
/**
* Returns the currently highlighted palette item, or null if no item is
* highlighted.
* @return {Node} The highlighted item (undefined if none).
*/
goog.ui.Palette.prototype.getHighlightedItem = function() {
var items = this.getContent();
return items && items[this.highlightedIndex_];
};
/**
* @return {Element} The highlighted cell.
* @private
*/
goog.ui.Palette.prototype.getHighlightedCellElement_ = function() {
return this.getRenderer().getCellForItem(this.getHighlightedItem());
};
/**
* Highlights the item at the given 0-based index, or removes the highlight
* if the argument is -1 or out of range. Any previously-highlighted item
* will be un-highlighted.
* @param {number} index 0-based index of the item to highlight.
*/
goog.ui.Palette.prototype.setHighlightedIndex = function(index) {
if (index != this.highlightedIndex_) {
this.highlightIndex_(this.highlightedIndex_, false);
this.highlightedIndex_ = index;
this.highlightIndex_(index, true);
this.dispatchEvent(goog.ui.Palette.EventType.AFTER_HIGHLIGHT);
}
};
/**
* Highlights the given item, or removes the highlight if the argument is null
* or invalid. Any previously-highlighted item will be un-highlighted.
* @param {Node|undefined} item Item to highlight.
*/
goog.ui.Palette.prototype.setHighlightedItem = function(item) {
var items = /** @type {Array.<Node>} */ (this.getContent());
this.setHighlightedIndex(items ? goog.array.indexOf(items, item) : -1);
};
/**
* Returns the 0-based index of the currently selected palette item, or -1
* if no item is selected.
* @return {number} Index of the selected item (-1 if none).
*/
goog.ui.Palette.prototype.getSelectedIndex = function() {
return this.selectionModel_ ? this.selectionModel_.getSelectedIndex() : -1;
};
/**
* Returns the currently selected palette item, or null if no item is selected.
* @return {Node} The selected item (null if none).
*/
goog.ui.Palette.prototype.getSelectedItem = function() {
return this.selectionModel_ ?
/** @type {Node} */ (this.selectionModel_.getSelectedItem()) : null;
};
/**
* Selects the item at the given 0-based index, or clears the selection
* if the argument is -1 or out of range. Any previously-selected item
* will be deselected.
* @param {number} index 0-based index of the item to select.
*/
goog.ui.Palette.prototype.setSelectedIndex = function(index) {
if (this.selectionModel_) {
this.selectionModel_.setSelectedIndex(index);
}
};
/**
* Selects the given item, or clears the selection if the argument is null or
* invalid. Any previously-selected item will be deselected.
* @param {Node} item Item to select.
*/
goog.ui.Palette.prototype.setSelectedItem = function(item) {
if (this.selectionModel_) {
this.selectionModel_.setSelectedItem(item);
}
};
/**
* Private helper; highlights or un-highlights the item at the given index
* based on the value of the Boolean argument. This implementation simply
* applies highlight styling to the cell containing the item to be highighted.
* Does nothing if the palette hasn't been rendered yet.
* @param {number} index 0-based index of item to highlight or un-highlight.
* @param {boolean} highlight If true, the item is highlighted; otherwise it
* is un-highlighted.
* @private
*/
goog.ui.Palette.prototype.highlightIndex_ = function(index, highlight) {
if (this.getElement()) {
var items = this.getContent();
if (items && index >= 0 && index < items.length) {
var cellEl = this.getHighlightedCellElement_();
if (this.currentCellControl_.getElement() != cellEl) {
this.currentCellControl_.setElementInternal(cellEl);
}
if (this.currentCellControl_.tryHighlight(highlight)) {
this.getRenderer().highlightCell(this, items[index], highlight);
}
}
}
};
/**
* Private helper; selects or deselects the given item based on the value of
* the Boolean argument. This implementation simply applies selection styling
* to the cell containing the item to be selected. Does nothing if the palette
* hasn't been rendered yet.
* @param {Node} item Item to select or deselect.
* @param {boolean} select If true, the item is selected; otherwise it is
* deselected.
* @private
*/
goog.ui.Palette.prototype.selectItem_ = function(item, select) {
if (this.getElement()) {
this.getRenderer().selectCell(this, item, select);
}
};
/**
* Calculates and updates the size of the palette based on any preset values
* and the number of palette items. If there is no preset size, sets the
* palette size to the smallest square big enough to contain all items. If
* there is a preset number of columns, increases the number of rows to hold
* all items if needed. (If there are too many rows, does nothing.)
* @private
*/
goog.ui.Palette.prototype.adjustSize_ = function() {
var items = this.getContent();
if (items) {
if (this.size_ && this.size_.width) {
// There is already a size set; honor the number of columns (if >0), but
// increase the number of rows if needed.
var minRows = Math.ceil(items.length / this.size_.width);
if (!goog.isNumber(this.size_.height) || this.size_.height < minRows) {
this.size_.height = minRows;
}
} else {
// No size has been set; size the grid to the smallest square big enough
// to hold all items (hey, why not?).
var length = Math.ceil(Math.sqrt(items.length));
this.size_ = new goog.math.Size(length, length);
}
} else {
// No items; set size to 0x0.
this.size_ = new goog.math.Size(0, 0);
}
};
/**
* A component to represent the currently highlighted cell.
* @constructor
* @extends {goog.ui.Control}
* @private
*/
goog.ui.Palette.CurrentCell_ = function() {
goog.base(this, null);
this.setDispatchTransitionEvents(goog.ui.Component.State.HOVER, true);
};
goog.inherits(goog.ui.Palette.CurrentCell_, goog.ui.Control);
/**
* @param {boolean} highlight Whether to highlight or unhighlight the component.
* @return {boolean} Whether it was successful.
*/
goog.ui.Palette.CurrentCell_.prototype.tryHighlight = function(highlight) {
this.setHighlighted(highlight);
return this.isHighlighted() == highlight;
};
| 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 Animated zippy widget implementation.
*
* @author eae@google.com (Emil A Eklund)
* @see ../demos/zippy.html
*/
goog.provide('goog.ui.AnimatedZippy');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.fx.Animation');
goog.require('goog.fx.Animation.EventType');
goog.require('goog.fx.Transition.EventType');
goog.require('goog.fx.easing');
goog.require('goog.ui.Zippy');
goog.require('goog.ui.ZippyEvent');
/**
* Zippy widget. Expandable/collapsible container, clicking the header toggles
* the visibility of the content.
*
* @param {Element|string|null} header Header element, either element
* reference, string id or null if no header exists.
* @param {Element|string} content Content element, either element reference or
* string id.
* @param {boolean=} opt_expanded Initial expanded/visibility state. Defaults to
* false.
* @constructor
* @extends {goog.ui.Zippy}
*/
goog.ui.AnimatedZippy = function(header, content, opt_expanded) {
// Create wrapper element and move content into it.
var elWrapper = goog.dom.createDom('div', {'style': 'overflow:hidden'});
var elContent = goog.dom.getElement(content);
elContent.parentNode.replaceChild(elWrapper, elContent);
elWrapper.appendChild(elContent);
/**
* Content wrapper, used for animation.
* @type {Element}
* @private
*/
this.elWrapper_ = elWrapper;
/**
* Reference to animation or null if animation is not active.
* @type {goog.fx.Animation}
* @private
*/
this.anim_ = null;
// Call constructor of super class.
goog.ui.Zippy.call(this, header, elContent, opt_expanded);
// Set initial state.
// NOTE: Set the class names as well otherwise animated zippys
// start with empty class names.
var expanded = this.isExpanded();
this.elWrapper_.style.display = expanded ? '' : 'none';
this.updateHeaderClassName(expanded);
};
goog.inherits(goog.ui.AnimatedZippy, goog.ui.Zippy);
/**
* Duration of expand/collapse animation, in milliseconds.
* @type {number}
*/
goog.ui.AnimatedZippy.prototype.animationDuration = 500;
/**
* Acceleration function for expand/collapse animation.
* @type {!Function}
*/
goog.ui.AnimatedZippy.prototype.animationAcceleration = goog.fx.easing.easeOut;
/**
* @return {boolean} Whether the zippy is in the process of being expanded or
* collapsed.
*/
goog.ui.AnimatedZippy.prototype.isBusy = function() {
return this.anim_ != null;
};
/**
* Sets expanded state.
*
* @param {boolean} expanded Expanded/visibility state.
* @override
*/
goog.ui.AnimatedZippy.prototype.setExpanded = function(expanded) {
if (this.isExpanded() == expanded && !this.anim_) {
return;
}
// Reset display property of wrapper to allow content element to be
// measured.
if (this.elWrapper_.style.display == 'none') {
this.elWrapper_.style.display = '';
}
// Measure content element.
var h = this.getContentElement().offsetHeight;
// Stop active animation (if any) and determine starting height.
var startH = 0;
if (this.anim_) {
expanded = this.isExpanded();
goog.events.removeAll(this.anim_);
this.anim_.stop(false);
var marginTop = parseInt(this.getContentElement().style.marginTop, 10);
startH = h - Math.abs(marginTop);
} else {
startH = expanded ? 0 : h;
}
// Updates header class name after the animation has been stopped.
this.updateHeaderClassName(expanded);
// Set up expand/collapse animation.
this.anim_ = new goog.fx.Animation([0, startH],
[0, expanded ? h : 0],
this.animationDuration,
this.animationAcceleration);
var events = [goog.fx.Transition.EventType.BEGIN,
goog.fx.Animation.EventType.ANIMATE,
goog.fx.Transition.EventType.END];
goog.events.listen(this.anim_, events, this.onAnimate_, false, this);
goog.events.listen(this.anim_,
goog.fx.Transition.EventType.END,
goog.bind(this.onAnimationCompleted_, this, expanded));
// Start animation.
this.anim_.play(false);
};
/**
* Called during animation
*
* @param {goog.events.Event} e The event.
* @private
*/
goog.ui.AnimatedZippy.prototype.onAnimate_ = function(e) {
var contentElement = this.getContentElement();
var h = contentElement.offsetHeight;
contentElement.style.marginTop = (e.y - h) + 'px';
};
/**
* Called once the expand/collapse animation has completed.
*
* @param {boolean} expanded Expanded/visibility state.
* @private
*/
goog.ui.AnimatedZippy.prototype.onAnimationCompleted_ = function(expanded) {
// Fix wrong end position if the content has changed during the animation.
if (expanded) {
this.getContentElement().style.marginTop = '0';
}
goog.events.removeAll(this.anim_);
this.setExpandedInternal(expanded);
this.anim_ = null;
if (!expanded) {
this.elWrapper_.style.display = 'none';
}
// Fire toggle event.
this.dispatchEvent(new goog.ui.ZippyEvent(goog.ui.Zippy.Events.TOGGLE,
this, expanded));
};
| 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 a JS storage class implementing the HTML5 Storage
* interface.
*/
goog.require('goog.structs.Map');
goog.provide('goog.testing.MockStorage');
/**
* A JS storage instance, implementing the HMTL5 Storage interface.
* See http://www.w3.org/TR/webstorage/ for details.
*
* @constructor
* @implements {Storage}
*/
goog.testing.MockStorage = function() {
/**
* The underlying storage object.
* @type {goog.structs.Map}
* @private
*/
this.store_ = new goog.structs.Map();
/**
* The number of elements in the storage.
* @type {number}
*/
this.length = 0;
};
/**
* Sets an item to the storage.
* @param {string} key Storage key.
* @param {*} value Storage value. Must be convertible to string.
* @override
*/
goog.testing.MockStorage.prototype.setItem = function(key, value) {
this.store_.set(key, String(value));
this.length = this.store_.getCount();
};
/**
* Gets an item from the storage. The item returned is the "structured clone"
* of the value from setItem. In practice this means it's the value cast to a
* string.
* @param {string} key Storage key.
* @return {?string} Storage value for key; null if does not exist.
* @override
*/
goog.testing.MockStorage.prototype.getItem = function(key) {
var val = this.store_.get(key);
// Enforce that getItem returns string values.
return (val != null) ? /** @type {string} */ (val) : null;
};
/**
* Removes and item from the storage.
* @param {string} key Storage key.
* @override
*/
goog.testing.MockStorage.prototype.removeItem = function(key) {
this.store_.remove(key);
this.length = this.store_.getCount();
};
/**
* Clears the storage.
* @override
*/
goog.testing.MockStorage.prototype.clear = function() {
this.store_.clear();
this.length = 0;
};
/**
* Returns the key at the given index.
* @param {number} index The index for the key.
* @return {?string} Key at the given index, null if not found.
* @override
*/
goog.testing.MockStorage.prototype.key = function(index) {
return this.store_.getKeys()[index] || null;
};
| 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 allow for expected unit test failures.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.testing.ExpectedFailures');
goog.require('goog.debug.DivConsole');
goog.require('goog.debug.Logger');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.style');
goog.require('goog.testing.JsUnitException');
goog.require('goog.testing.TestCase');
goog.require('goog.testing.asserts');
/**
* Helper class for allowing some unit tests to fail, particularly designed to
* mark tests that should be fixed on a given browser.
*
* <pre>
* var expectedFailures = new goog.testing.ExpectedFailures();
*
* function tearDown() {
* expectedFailures.handleTearDown();
* }
*
* function testSomethingThatBreaksInWebKit() {
* expectedFailures.expectFailureFor(goog.userAgent.WEBKIT);
*
* try {
* ...
* assert(somethingThatFailsInWebKit);
* ...
* } catch (e) {
* expectedFailures.handleException(e);
* }
* }
* </pre>
*
* @constructor
*/
goog.testing.ExpectedFailures = function() {
goog.testing.ExpectedFailures.setUpConsole_();
this.reset_();
};
/**
* The lazily created debugging console.
* @type {goog.debug.DivConsole?}
* @private
*/
goog.testing.ExpectedFailures.console_ = null;
/**
* Logger for the expected failures.
* @type {goog.debug.Logger}
* @private
*/
goog.testing.ExpectedFailures.prototype.logger_ =
goog.debug.Logger.getLogger('goog.testing.ExpectedFailures');
/**
* Whether or not we are expecting failure.
* @type {boolean}
* @private
*/
goog.testing.ExpectedFailures.prototype.expectingFailure_;
/**
* The string to emit upon an expected failure.
* @type {string}
* @private
*/
goog.testing.ExpectedFailures.prototype.failureMessage_;
/**
* An array of suppressed failures.
* @type {Array}
* @private
*/
goog.testing.ExpectedFailures.prototype.suppressedFailures_;
/**
* Sets up the debug console, if it isn't already set up.
* @private
*/
goog.testing.ExpectedFailures.setUpConsole_ = function() {
if (!goog.testing.ExpectedFailures.console_) {
var xButton = goog.dom.createDom(goog.dom.TagName.DIV, {
'style': 'position: absolute; border-left:1px solid #333;' +
'border-bottom:1px solid #333; right: 0; top: 0; width: 1em;' +
'height: 1em; cursor: pointer; background-color: #cde;' +
'text-align: center; color: black'
}, 'X');
var div = goog.dom.createDom(goog.dom.TagName.DIV, {
'style': 'position: absolute; border: 1px solid #333; right: 10px;' +
'top : 10px; width: 400px; display: none'
}, xButton);
document.body.appendChild(div);
goog.events.listen(xButton, goog.events.EventType.CLICK, function() {
goog.style.setElementShown(div, false);
});
goog.testing.ExpectedFailures.console_ = new goog.debug.DivConsole(div);
goog.testing.ExpectedFailures.prototype.logger_.addHandler(
goog.bind(goog.style.setElementShown, null, div, true));
goog.testing.ExpectedFailures.prototype.logger_.addHandler(
goog.bind(goog.testing.ExpectedFailures.console_.addLogRecord,
goog.testing.ExpectedFailures.console_));
}
};
/**
* Register to expect failure for the given condition. Multiple calls to this
* function act as a boolean OR. The first applicable message will be used.
* @param {boolean} condition Whether to expect failure.
* @param {string=} opt_message Descriptive message of this expected failure.
*/
goog.testing.ExpectedFailures.prototype.expectFailureFor = function(
condition, opt_message) {
this.expectingFailure_ = this.expectingFailure_ || condition;
if (condition) {
this.failureMessage_ = this.failureMessage_ || opt_message || '';
}
};
/**
* Determines if the given exception was expected.
* @param {Object} ex The exception to check.
* @return {boolean} Whether the exception was expected.
*/
goog.testing.ExpectedFailures.prototype.isExceptionExpected = function(ex) {
return this.expectingFailure_ && ex instanceof goog.testing.JsUnitException;
};
/**
* Handle an exception, suppressing it if it is a unit test failure that we
* expected.
* @param {Error} ex The exception to handle.
*/
goog.testing.ExpectedFailures.prototype.handleException = function(ex) {
if (this.isExceptionExpected(ex)) {
this.logger_.info('Suppressing test failure in ' +
goog.testing.TestCase.currentTestName + ':' +
(this.failureMessage_ ? '\n(' + this.failureMessage_ + ')' : ''),
ex);
this.suppressedFailures_.push(ex);
return;
}
// Rethrow the exception if we weren't expecting it or if it is a normal
// exception.
throw ex;
};
/**
* Run the given function, catching any expected failures.
* @param {Function} func The function to run.
* @param {boolean=} opt_lenient Whether to ignore if the expected failures
* didn't occur. In this case a warning will be logged in handleTearDown.
*/
goog.testing.ExpectedFailures.prototype.run = function(func, opt_lenient) {
try {
func();
} catch (ex) {
this.handleException(ex);
}
if (!opt_lenient && this.expectingFailure_ &&
!this.suppressedFailures_.length) {
fail(this.getExpectationMessage_());
}
};
/**
* @return {string} A warning describing an expected failure that didn't occur.
* @private
*/
goog.testing.ExpectedFailures.prototype.getExpectationMessage_ = function() {
return 'Expected a test failure in \'' +
goog.testing.TestCase.currentTestName + '\' but the test passed.';
};
/**
* Handle the tearDown phase of a test, alerting the user if an expected test
* was not suppressed.
*/
goog.testing.ExpectedFailures.prototype.handleTearDown = function() {
if (this.expectingFailure_ && !this.suppressedFailures_.length) {
this.logger_.warning(this.getExpectationMessage_());
}
this.reset_();
};
/**
* Reset internal state.
* @private
*/
goog.testing.ExpectedFailures.prototype.reset_ = function() {
this.expectingFailure_ = false;
this.failureMessage_ = '';
this.suppressedFailures_ = [];
};
| 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 Helper class for recording the calls of a function.
*
* Example:
* <pre>
* var stubs = new goog.testing.PropertyReplacer();
*
* function tearDown() {
* stubs.reset();
* }
*
* function testShuffle() {
* stubs.set(Math, 'random', goog.testing.recordFunction(Math.random));
* var arr = shuffle([1, 2, 3, 4, 5]);
* assertSameElements([1, 2, 3, 4, 5], arr);
* assertEquals(4, Math.random.getCallCount());
* }
*
* function testOpenDialog() {
* stubs.set(goog.ui, 'Dialog',
* goog.testing.recordConstructor(goog.ui.Dialog));
* openConfirmDialog();
* var lastDialogInstance = goog.ui.Dialog.getLastCall().getThis();
* assertEquals('confirm', lastDialogInstance.getTitle());
* }
* </pre>
*
*/
goog.provide('goog.testing.FunctionCall');
goog.provide('goog.testing.recordConstructor');
goog.provide('goog.testing.recordFunction');
/**
* Wraps the function into another one which calls the inner function and
* records its calls. The recorded function will have 3 static methods:
* {@code getCallCount}, {@code getCalls} and {@code getLastCall} but won't
* inherit the original function's prototype and static fields.
*
* @param {!Function=} opt_f The function to wrap and record. Defaults to
* {@link goog.nullFunction}.
* @return {!Function} The wrapped function.
*/
goog.testing.recordFunction = function(opt_f) {
var f = opt_f || goog.nullFunction;
var calls = [];
function recordedFunction() {
try {
var ret = f.apply(this, arguments);
calls.push(new goog.testing.FunctionCall(f, this, arguments, ret, null));
return ret;
} catch (err) {
calls.push(new goog.testing.FunctionCall(f, this, arguments, undefined,
err));
throw err;
}
}
/**
* @return {number} Total number of calls.
*/
recordedFunction.getCallCount = function() {
return calls.length;
};
/**
* @return {!Array.<!goog.testing.FunctionCall>} All calls of the recorded
* function.
*/
recordedFunction.getCalls = function() {
return calls;
};
/**
* @return {goog.testing.FunctionCall} Last call of the recorded function or
* null if it hasn't been called.
*/
recordedFunction.getLastCall = function() {
return calls[calls.length - 1] || null;
};
/**
* Returns and removes the last call of the recorded function.
* @return {goog.testing.FunctionCall} Last call of the recorded function or
* null if it hasn't been called.
*/
recordedFunction.popLastCall = function() {
return calls.pop() || null;
};
/**
* Resets the recorded function and removes all calls.
*/
recordedFunction.reset = function() {
calls.length = 0;
};
return recordedFunction;
};
/**
* Same as {@link goog.testing.recordFunction} but the recorded function will
* have the same prototype and static fields as the original one. It can be
* used with constructors.
*
* @param {!Function} ctor The function to wrap and record.
* @return {!Function} The wrapped function.
*/
goog.testing.recordConstructor = function(ctor) {
var recordedConstructor = goog.testing.recordFunction(ctor);
recordedConstructor.prototype = ctor.prototype;
goog.mixin(recordedConstructor, ctor);
return recordedConstructor;
};
/**
* Struct for a single function call.
* @param {!Function} func The called function.
* @param {!Object} thisContext {@code this} context of called function.
* @param {!Arguments} args Arguments of the called function.
* @param {*} ret Return value of the function or undefined in case of error.
* @param {*} error The error thrown by the function or null if none.
* @constructor
*/
goog.testing.FunctionCall = function(func, thisContext, args, ret, error) {
this.function_ = func;
this.thisContext_ = thisContext;
this.arguments_ = Array.prototype.slice.call(args);
this.returnValue_ = ret;
this.error_ = error;
};
/**
* @return {!Function} The called function.
*/
goog.testing.FunctionCall.prototype.getFunction = function() {
return this.function_;
};
/**
* @return {!Object} {@code this} context of called function. It is the same as
* the created object if the function is a constructor.
*/
goog.testing.FunctionCall.prototype.getThis = function() {
return this.thisContext_;
};
/**
* @return {!Array} Arguments of the called function.
*/
goog.testing.FunctionCall.prototype.getArguments = function() {
return this.arguments_;
};
/**
* Returns the nth argument of the called function.
* @param {number} index 0-based index of the argument.
* @return {*} The argument value or undefined if there is no such argument.
*/
goog.testing.FunctionCall.prototype.getArgument = function(index) {
return this.arguments_[index];
};
/**
* @return {*} Return value of the function or undefined in case of error.
*/
goog.testing.FunctionCall.prototype.getReturnValue = function() {
return this.returnValue_;
};
/**
* @return {*} The error thrown by the function or null if none.
*/
goog.testing.FunctionCall.prototype.getError = function() {
return this.error_;
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides a fake storage mechanism for testing.
*/
goog.provide('goog.testing.storage.FakeMechanism');
goog.setTestOnly('goog.testing.storage.FakeMechanism');
goog.require('goog.storage.mechanism.IterableMechanism');
goog.require('goog.structs.Map');
/**
* Creates a fake iterable mechanism.
*
* @constructor
* @extends {goog.storage.mechanism.IterableMechanism}
*/
goog.testing.storage.FakeMechanism = function() {
/**
* @type {goog.structs.Map}
* @private
*/
this.storage_ = new goog.structs.Map();
};
goog.inherits(goog.testing.storage.FakeMechanism,
goog.storage.mechanism.IterableMechanism);
/** @override */
goog.testing.storage.FakeMechanism.prototype.set = function(key, value) {
this.storage_.set(key, value);
};
/** @override */
goog.testing.storage.FakeMechanism.prototype.get = function(key) {
return /** @type {?string} */ (
this.storage_.get(key, null /* default value */));
};
/** @override */
goog.testing.storage.FakeMechanism.prototype.remove = function(key) {
this.storage_.remove(key);
};
/** @override */
goog.testing.storage.FakeMechanism.prototype.__iterator__ = function(opt_keys) {
return this.storage_.__iterator__(opt_keys);
};
| 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 Sample code to instantiate a few goog.ui.Buttons. The
* size of the resulting jsbinary for this sample file is tracked using
* Greenspan (http://go/greenspan).
*
*/
goog.provide('goog.ui.benchmarks.jsbinarysizebutton');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.ui.Button');
goog.require('goog.ui.ButtonSide');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.CustomButton');
function drawButtons() {
function logEvent(e) {
}
// Create a simple button programmatically
var b1 = new goog.ui.Button('Hello!');
b1.render(goog.dom.getElement('b1'));
b1.setTooltip('I changed the tooltip.');
goog.events.listen(b1, goog.ui.Component.EventType.ACTION, logEvent);
// Create some custom buttons programatically.
var disabledButton, leftButton, centerButton, rightButton;
var customButtons = [
new goog.ui.CustomButton('Button'),
new goog.ui.CustomButton('Another Button'),
disabledButton = new goog.ui.CustomButton('Disabled Button'),
new goog.ui.CustomButton('Yet Another Button'),
leftButton = new goog.ui.CustomButton('Left'),
centerButton = new goog.ui.CustomButton('Center'),
rightButton = new goog.ui.CustomButton('Right')
];
disabledButton.setEnabled(false);
leftButton.setCollapsed(goog.ui.ButtonSide.END);
centerButton.setCollapsed(goog.ui.ButtonSide.BOTH);
rightButton.setCollapsed(goog.ui.ButtonSide.START);
goog.array.forEach(customButtons, function(b) {
b.render(goog.dom.getElement('cb1'));
goog.events.listen(b, goog.ui.Component.EventType.ACTION, logEvent);
});
}
goog.exportSymbol('drawButtons', drawButtons);
| 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 Sample code to render a simple goog.ui.Toolbar. The
* size of the resulting jsbinary for this sample file is tracked using
* Greenspan (http://go/greenspan).
*
*/
/** @suppress {extraProvide} */
goog.provide('goog.ui.benchmarks.jsbinarysizetoolbar');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.object');
goog.require('goog.ui.Option');
goog.require('goog.ui.Toolbar');
goog.require('goog.ui.ToolbarButton');
goog.require('goog.ui.ToolbarSelect');
goog.require('goog.ui.ToolbarSeparator');
function drawToolbar() {
function logEvent(e) {
}
var EVENTS = goog.object.getValues(goog.ui.Component.EventType);
// Create the toolbar
var t1 = new goog.ui.Toolbar();
// Add a button
t1.addChild(new goog.ui.ToolbarButton('Button'), true);
t1.getChildAt(0).setTooltip('This is a tooltip for a button');
// Add a separator
t1.addChild(new goog.ui.ToolbarSeparator(), true);
// Create the select menu
var s1 = new goog.ui.ToolbarSelect('Select font');
goog.array.forEach(['Normal', 'Times', 'Courier New', 'Georgia', 'Trebuchet',
'Verdana'],
function(label) {
var item = new goog.ui.Option(label);
s1.addItem(item);
});
s1.setTooltip('Font');
t1.addChild(s1, true);
goog.events.listen(t1, EVENTS, logEvent);
t1.render(goog.dom.getElement('toolbar'));
}
goog.exportSymbol('drawToolbar', drawToolbar);
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file defines base classes used for creating mocks in
* JavaScript. The API was inspired by EasyMock.
*
* The basic API is:
* <ul>
* <li>Create an object to be mocked
* <li>Create a mock object, passing in the above object to the constructor
* <li>Set expectations by calling methods on the mock object
* <li>Call $replay() on the mock object
* <li>Pass the mock to code that will make real calls on it
* <li>Call $verify() to make sure that expectations were met
* </ul>
*
* For examples, please see the unit tests for LooseMock and StrictMock.
*
* Still TODO
* implement better (and pluggable) argument matching
* Have the exceptions for LooseMock show the number of expected/actual calls
* loose and strict mocks share a lot of code - move it to the base class
*
*/
goog.provide('goog.testing.Mock');
goog.provide('goog.testing.MockExpectation');
goog.require('goog.array');
goog.require('goog.object');
goog.require('goog.testing.JsUnitException');
goog.require('goog.testing.MockInterface');
goog.require('goog.testing.mockmatchers');
/**
* This is a class that represents an expectation.
* @param {string} name The name of the method for this expectation.
* @constructor
*/
goog.testing.MockExpectation = function(name) {
/**
* The name of the method that is expected to be called.
* @type {string}
*/
this.name = name;
/**
* An array of error messages for expectations not met.
* @type {Array}
*/
this.errorMessages = [];
};
/**
* The minimum number of times this method should be called.
* @type {number}
*/
goog.testing.MockExpectation.prototype.minCalls = 1;
/**
* The maximum number of times this method should be called.
* @type {number}
*/
goog.testing.MockExpectation.prototype.maxCalls = 1;
/**
* The value that this method should return.
* @type {*}
*/
goog.testing.MockExpectation.prototype.returnValue;
/**
* The value that will be thrown when the method is called
* @type {*}
*/
goog.testing.MockExpectation.prototype.exceptionToThrow;
/**
* The arguments that are expected to be passed to this function
* @type {Array.<*>}
*/
goog.testing.MockExpectation.prototype.argumentList;
/**
* The number of times this method is called by real code.
* @type {number}
*/
goog.testing.MockExpectation.prototype.actualCalls = 0;
/**
* The number of times this method is called during the verification phase.
* @type {number}
*/
goog.testing.MockExpectation.prototype.verificationCalls = 0;
/**
* The function which will be executed when this method is called.
* Method arguments will be passed to this function, and return value
* of this function will be returned by the method.
* @type {Function}
*/
goog.testing.MockExpectation.prototype.toDo;
/**
* Allow expectation failures to include messages.
* @param {string} message The failure message.
*/
goog.testing.MockExpectation.prototype.addErrorMessage = function(message) {
this.errorMessages.push(message);
};
/**
* Get the error messages seen so far.
* @return {string} Error messages separated by \n.
*/
goog.testing.MockExpectation.prototype.getErrorMessage = function() {
return this.errorMessages.join('\n');
};
/**
* Get how many error messages have been seen so far.
* @return {number} Count of error messages.
*/
goog.testing.MockExpectation.prototype.getErrorMessageCount = function() {
return this.errorMessages.length;
};
/**
* The base class for a mock object.
* @param {Object|Function} objectToMock The object that should be mocked, or
* the constructor of an object to mock.
* @param {boolean=} opt_mockStaticMethods An optional argument denoting that
* a mock should be constructed from the static functions of a class.
* @param {boolean=} opt_createProxy An optional argument denoting that
* a proxy for the target mock should be created.
* @constructor
* @implements {goog.testing.MockInterface}
*/
goog.testing.Mock = function(objectToMock, opt_mockStaticMethods,
opt_createProxy) {
if (!goog.isObject(objectToMock) && !goog.isFunction(objectToMock)) {
throw new Error('objectToMock must be an object or constructor.');
}
if (opt_createProxy && !opt_mockStaticMethods &&
goog.isFunction(objectToMock)) {
/** @constructor */
var tempCtor = function() {};
goog.inherits(tempCtor, objectToMock);
this.$proxy = new tempCtor();
} else if (opt_createProxy && opt_mockStaticMethods &&
goog.isFunction(objectToMock)) {
throw Error('Cannot create a proxy when opt_mockStaticMethods is true');
} else if (opt_createProxy && !goog.isFunction(objectToMock)) {
throw Error('Must have a constructor to create a proxy');
}
if (goog.isFunction(objectToMock) && !opt_mockStaticMethods) {
this.$initializeFunctions_(objectToMock.prototype);
} else {
this.$initializeFunctions_(objectToMock);
}
this.$argumentListVerifiers_ = {};
};
/**
* Option that may be passed when constructing function, method, and
* constructor mocks. Indicates that the expected calls should be accepted in
* any order.
* @const
* @type {number}
*/
goog.testing.Mock.LOOSE = 1;
/**
* Option that may be passed when constructing function, method, and
* constructor mocks. Indicates that the expected calls should be accepted in
* the recorded order only.
* @const
* @type {number}
*/
goog.testing.Mock.STRICT = 0;
/**
* This array contains the name of the functions that are part of the base
* Object prototype.
* Basically a copy of goog.object.PROTOTYPE_FIELDS_.
* @const
* @type {!Array.<string>}
* @private
*/
goog.testing.Mock.PROTOTYPE_FIELDS_ = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
/**
* A proxy for the mock. This can be used for dependency injection in lieu of
* the mock if the test requires a strict instanceof check.
* @type {Object}
*/
goog.testing.Mock.prototype.$proxy = null;
/**
* Map of argument name to optional argument list verifier function.
* @type {Object}
*/
goog.testing.Mock.prototype.$argumentListVerifiers_;
/**
* Whether or not we are in recording mode.
* @type {boolean}
* @private
*/
goog.testing.Mock.prototype.$recording_ = true;
/**
* The expectation currently being created. All methods that modify the
* current expectation return the Mock object for easy chaining, so this is
* where we keep track of the expectation that's currently being modified.
* @type {goog.testing.MockExpectation}
* @protected
*/
goog.testing.Mock.prototype.$pendingExpectation;
/**
* First exception thrown by this mock; used in $verify.
* @type {Object}
* @private
*/
goog.testing.Mock.prototype.$threwException_ = null;
/**
* Initializes the functions on the mock object.
* @param {Object} objectToMock The object being mocked.
* @private
*/
goog.testing.Mock.prototype.$initializeFunctions_ = function(objectToMock) {
// Gets the object properties.
var enumerableProperties = goog.object.getKeys(objectToMock);
// The non enumerable properties are added if they override the ones in the
// Object prototype. This is due to the fact that IE8 does not enumerate any
// of the prototype Object functions even when overriden and mocking these is
// sometimes needed.
for (var i = 0; i < goog.testing.Mock.PROTOTYPE_FIELDS_.length; i++) {
var prop = goog.testing.Mock.PROTOTYPE_FIELDS_[i];
// Look at b/6758711 if you're considering adding ALL properties to ALL
// mocks.
if (objectToMock[prop] !== Object.prototype[prop]) {
enumerableProperties.push(prop);
}
}
// Adds the properties to the mock.
for (var i = 0; i < enumerableProperties.length; i++) {
var prop = enumerableProperties[i];
if (typeof objectToMock[prop] == 'function') {
this[prop] = goog.bind(this.$mockMethod, this, prop);
if (this.$proxy) {
this.$proxy[prop] = goog.bind(this.$mockMethod, this, prop);
}
}
}
};
/**
* Registers a verfifier function to use when verifying method argument lists.
* @param {string} methodName The name of the method for which the verifierFn
* should be used.
* @param {Function} fn Argument list verifier function. Should take 2 argument
* arrays as arguments, and return true if they are considered equivalent.
* @return {goog.testing.Mock} This mock object.
*/
goog.testing.Mock.prototype.$registerArgumentListVerifier = function(methodName,
fn) {
this.$argumentListVerifiers_[methodName] = fn;
return this;
};
/**
* The function that replaces all methods on the mock object.
* @param {string} name The name of the method being mocked.
* @return {*} In record mode, returns the mock object. In replay mode, returns
* whatever the creator of the mock set as the return value.
*/
goog.testing.Mock.prototype.$mockMethod = function(name) {
try {
// Shift off the name argument so that args contains the arguments to
// the mocked method.
var args = goog.array.slice(arguments, 1);
if (this.$recording_) {
this.$pendingExpectation = new goog.testing.MockExpectation(name);
this.$pendingExpectation.argumentList = args;
this.$recordExpectation();
return this;
} else {
return this.$recordCall(name, args);
}
} catch (ex) {
this.$recordAndThrow(ex);
}
};
/**
* Records the currently pending expectation, intended to be overridden by a
* subclass.
* @protected
*/
goog.testing.Mock.prototype.$recordExpectation = function() {};
/**
* Records an actual method call, intended to be overridden by a
* subclass. The subclass must find the pending expectation and return the
* correct value.
* @param {string} name The name of the method being called.
* @param {Array} args The arguments to the method.
* @return {*} The return expected by the mock.
* @protected
*/
goog.testing.Mock.prototype.$recordCall = function(name, args) {
return undefined;
};
/**
* If the expectation expects to throw, this method will throw.
* @param {goog.testing.MockExpectation} expectation The expectation.
*/
goog.testing.Mock.prototype.$maybeThrow = function(expectation) {
if (typeof expectation.exceptionToThrow != 'undefined') {
throw expectation.exceptionToThrow;
}
};
/**
* If this expectation defines a function to be called,
* it will be called and its result will be returned.
* Otherwise, if the expectation expects to throw, it will throw.
* Otherwise, this method will return defined value.
* @param {goog.testing.MockExpectation} expectation The expectation.
* @param {Array} args The arguments to the method.
* @return {*} The return value expected by the mock.
*/
goog.testing.Mock.prototype.$do = function(expectation, args) {
if (typeof expectation.toDo == 'undefined') {
this.$maybeThrow(expectation);
return expectation.returnValue;
} else {
return expectation.toDo.apply(this, args);
}
};
/**
* Specifies a return value for the currently pending expectation.
* @param {*} val The return value.
* @return {goog.testing.Mock} This mock object.
*/
goog.testing.Mock.prototype.$returns = function(val) {
this.$pendingExpectation.returnValue = val;
return this;
};
/**
* Specifies a value for the currently pending expectation to throw.
* @param {*} val The value to throw.
* @return {goog.testing.Mock} This mock object.
*/
goog.testing.Mock.prototype.$throws = function(val) {
this.$pendingExpectation.exceptionToThrow = val;
return this;
};
/**
* Specifies a function to call for currently pending expectation.
* Note, that using this method overrides declarations made
* using $returns() and $throws() methods.
* @param {Function} func The function to call.
* @return {goog.testing.Mock} This mock object.
*/
goog.testing.Mock.prototype.$does = function(func) {
this.$pendingExpectation.toDo = func;
return this;
};
/**
* Allows the expectation to be called 0 or 1 times.
* @return {goog.testing.Mock} This mock object.
*/
goog.testing.Mock.prototype.$atMostOnce = function() {
this.$pendingExpectation.minCalls = 0;
this.$pendingExpectation.maxCalls = 1;
return this;
};
/**
* Allows the expectation to be called any number of times, as long as it's
* called once.
* @return {goog.testing.Mock} This mock object.
*/
goog.testing.Mock.prototype.$atLeastOnce = function() {
this.$pendingExpectation.maxCalls = Infinity;
return this;
};
/**
* Allows the expectation to be called any number of times.
* @return {goog.testing.Mock} This mock object.
*/
goog.testing.Mock.prototype.$anyTimes = function() {
this.$pendingExpectation.minCalls = 0;
this.$pendingExpectation.maxCalls = Infinity;
return this;
};
/**
* Specifies the number of times the expectation should be called.
* @param {number} times The number of times this method will be called.
* @return {goog.testing.Mock} This mock object.
*/
goog.testing.Mock.prototype.$times = function(times) {
this.$pendingExpectation.minCalls = times;
this.$pendingExpectation.maxCalls = times;
return this;
};
/**
* Switches from recording to replay mode.
* @override
*/
goog.testing.Mock.prototype.$replay = function() {
this.$recording_ = false;
};
/**
* Resets the state of this mock object. This clears all pending expectations
* without verifying, and puts the mock in recording mode.
* @override
*/
goog.testing.Mock.prototype.$reset = function() {
this.$recording_ = true;
this.$threwException_ = null;
delete this.$pendingExpectation;
};
/**
* Throws an exception and records that an exception was thrown.
* @param {string} comment A short comment about the exception.
* @param {?string=} opt_message A longer message about the exception.
* @throws {Object} JsUnitException object.
* @protected
*/
goog.testing.Mock.prototype.$throwException = function(comment, opt_message) {
this.$recordAndThrow(new goog.testing.JsUnitException(comment, opt_message));
};
/**
* Throws an exception and records that an exception was thrown.
* @param {Object} ex Exception.
* @throws {Object} #ex.
* @protected
*/
goog.testing.Mock.prototype.$recordAndThrow = function(ex) {
// If it's an assert exception, record it.
if (ex['isJsUnitException']) {
var testRunner = goog.global['G_testRunner'];
if (testRunner) {
var logTestFailureFunction = testRunner['logTestFailure'];
if (logTestFailureFunction) {
logTestFailureFunction.call(testRunner, ex);
}
}
if (!this.$threwException_) {
// Only remember first exception thrown.
this.$threwException_ = ex;
}
}
throw ex;
};
/**
* Verify that all of the expectations were met. Should be overridden by
* subclasses.
* @override
*/
goog.testing.Mock.prototype.$verify = function() {
if (this.$threwException_) {
throw this.$threwException_;
}
};
/**
* Verifies that a method call matches an expectation.
* @param {goog.testing.MockExpectation} expectation The expectation to check.
* @param {string} name The name of the called method.
* @param {Array.<*>?} args The arguments passed to the mock.
* @return {boolean} Whether the call matches the expectation.
*/
goog.testing.Mock.prototype.$verifyCall = function(expectation, name, args) {
if (expectation.name != name) {
return false;
}
var verifierFn =
this.$argumentListVerifiers_.hasOwnProperty(expectation.name) ?
this.$argumentListVerifiers_[expectation.name] :
goog.testing.mockmatchers.flexibleArrayMatcher;
return verifierFn(expectation.argumentList, args, expectation);
};
/**
* Render the provided argument array to a string to help
* clients with debugging tests.
* @param {Array.<*>?} args The arguments passed to the mock.
* @return {string} Human-readable string.
*/
goog.testing.Mock.prototype.$argumentsAsString = function(args) {
var retVal = [];
for (var i = 0; i < args.length; i++) {
try {
retVal.push(goog.typeOf(args[i]));
} catch (e) {
retVal.push('[unknown]');
}
}
return '(' + retVal.join(', ') + ')';
};
/**
* Throw an exception based on an incorrect method call.
* @param {string} name Name of method called.
* @param {Array.<*>?} args Arguments passed to the mock.
* @param {goog.testing.MockExpectation=} opt_expectation Expected next call,
* if any.
*/
goog.testing.Mock.prototype.$throwCallException = function(name, args,
opt_expectation) {
var errorStringBuffer = [];
var actualArgsString = this.$argumentsAsString(args);
var expectedArgsString = opt_expectation ?
this.$argumentsAsString(opt_expectation.argumentList) : '';
if (opt_expectation && opt_expectation.name == name) {
errorStringBuffer.push('Bad arguments to ', name, '().\n',
'Actual: ', actualArgsString, '\n',
'Expected: ', expectedArgsString, '\n',
opt_expectation.getErrorMessage());
} else {
errorStringBuffer.push('Unexpected call to ', name,
actualArgsString, '.');
if (opt_expectation) {
errorStringBuffer.push('\nNext expected call was to ',
opt_expectation.name,
expectedArgsString);
}
}
this.$throwException(errorStringBuffer.join(''));
};
| 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 Matchers to be used with the mock utilities. They allow for
* flexible matching by type. Custom matchers can be created by passing a
* matcher function into an ArgumentMatcher instance.
*
* For examples, please see the unit test.
*
*/
goog.provide('goog.testing.mockmatchers');
goog.provide('goog.testing.mockmatchers.ArgumentMatcher');
goog.provide('goog.testing.mockmatchers.IgnoreArgument');
goog.provide('goog.testing.mockmatchers.InstanceOf');
goog.provide('goog.testing.mockmatchers.ObjectEquals');
goog.provide('goog.testing.mockmatchers.RegexpMatch');
goog.provide('goog.testing.mockmatchers.SaveArgument');
goog.provide('goog.testing.mockmatchers.TypeOf');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.testing.asserts');
/**
* A simple interface for executing argument matching. A match in this case is
* testing to see if a supplied object fits a given criteria. True is returned
* if the given criteria is met.
* @param {Function=} opt_matchFn A function that evaluates a given argument
* and returns true if it meets a given criteria.
* @param {?string=} opt_matchName The name expressing intent as part of
* an error message for when a match fails.
* @constructor
*/
goog.testing.mockmatchers.ArgumentMatcher =
function(opt_matchFn, opt_matchName) {
/**
* A function that evaluates a given argument and returns true if it meets a
* given criteria.
* @type {Function}
* @private
*/
this.matchFn_ = opt_matchFn || null;
/**
* A string indicating the match intent (e.g. isBoolean or isString).
* @type {?string}
* @private
*/
this.matchName_ = opt_matchName || null;
};
/**
* A function that takes a match argument and an optional MockExpectation
* which (if provided) will get error information and returns whether or
* not it matches.
* @param {*} toVerify The argument that should be verified.
* @param {goog.testing.MockExpectation?=} opt_expectation The expectation
* for this match.
* @return {boolean} Whether or not a given argument passes verification.
*/
goog.testing.mockmatchers.ArgumentMatcher.prototype.matches =
function(toVerify, opt_expectation) {
if (this.matchFn_) {
var isamatch = this.matchFn_(toVerify);
if (!isamatch && opt_expectation) {
if (this.matchName_) {
opt_expectation.addErrorMessage('Expected: ' +
this.matchName_ + ' but was: ' + _displayStringForValue(toVerify));
} else {
opt_expectation.addErrorMessage('Expected: missing mockmatcher' +
' description but was: ' +
_displayStringForValue(toVerify));
}
}
return isamatch;
} else {
throw Error('No match function defined for this mock matcher');
}
};
/**
* A matcher that verifies that an argument is an instance of a given class.
* @param {Function} ctor The class that will be used for verification.
* @constructor
* @extends {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.InstanceOf = function(ctor) {
goog.testing.mockmatchers.ArgumentMatcher.call(this,
function(obj) {
return obj instanceof ctor;
// NOTE: Browser differences on ctor.toString() output
// make using that here problematic. So for now, just let
// people know the instanceOf() failed without providing
// browser specific details...
}, 'instanceOf()');
};
goog.inherits(goog.testing.mockmatchers.InstanceOf,
goog.testing.mockmatchers.ArgumentMatcher);
/**
* A matcher that verifies that an argument is of a given type (e.g. "object").
* @param {string} type The type that a given argument must have.
* @constructor
* @extends {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.TypeOf = function(type) {
goog.testing.mockmatchers.ArgumentMatcher.call(this,
function(obj) {
return goog.typeOf(obj) == type;
}, 'typeOf(' + type + ')');
};
goog.inherits(goog.testing.mockmatchers.TypeOf,
goog.testing.mockmatchers.ArgumentMatcher);
/**
* A matcher that verifies that an argument matches a given RegExp.
* @param {RegExp} regexp The regular expression that the argument must match.
* @constructor
* @extends {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.RegexpMatch = function(regexp) {
goog.testing.mockmatchers.ArgumentMatcher.call(this,
function(str) {
return regexp.test(str);
}, 'match(' + regexp + ')');
};
goog.inherits(goog.testing.mockmatchers.RegexpMatch,
goog.testing.mockmatchers.ArgumentMatcher);
/**
* A matcher that always returns true. It is useful when the user does not care
* for some arguments.
* For example: mockFunction('username', 'password', IgnoreArgument);
* @constructor
* @extends {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.IgnoreArgument = function() {
goog.testing.mockmatchers.ArgumentMatcher.call(this,
function() {
return true;
}, 'true');
};
goog.inherits(goog.testing.mockmatchers.IgnoreArgument,
goog.testing.mockmatchers.ArgumentMatcher);
/**
* A matcher that verifies that the argument is an object that equals the given
* expected object, using a deep comparison.
* @param {Object} expectedObject An object to match against when
* verifying the argument.
* @constructor
* @extends {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.ObjectEquals = function(expectedObject) {
goog.testing.mockmatchers.ArgumentMatcher.call(this,
function(matchObject) {
assertObjectEquals('Expected equal objects', expectedObject,
matchObject);
return true;
}, 'objectEquals(' + expectedObject + ')');
};
goog.inherits(goog.testing.mockmatchers.ObjectEquals,
goog.testing.mockmatchers.ArgumentMatcher);
/** @override */
goog.testing.mockmatchers.ObjectEquals.prototype.matches =
function(toVerify, opt_expectation) {
// Override the default matches implementation to capture the exception thrown
// by assertObjectEquals (if any) and add that message to the expectation.
try {
return goog.testing.mockmatchers.ObjectEquals.superClass_.matches.call(
this, toVerify, opt_expectation);
} catch (e) {
if (opt_expectation) {
opt_expectation.addErrorMessage(e.message);
}
return false;
}
};
/**
* A matcher that saves the argument that it is verifying so that your unit test
* can perform extra tests with this argument later. For example, if the
* argument is a callback method, the unit test can then later call this
* callback to test the asynchronous portion of the call.
* @param {goog.testing.mockmatchers.ArgumentMatcher|Function=} opt_matcher
* Argument matcher or matching function that will be used to validate the
* argument. By default, argument will always be valid.
* @param {?string=} opt_matchName The name expressing intent as part of
* an error message for when a match fails.
* @constructor
* @extends {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.SaveArgument = function(opt_matcher, opt_matchName) {
goog.testing.mockmatchers.ArgumentMatcher.call(
this, /** @type {Function} */ (opt_matcher), opt_matchName);
if (opt_matcher instanceof goog.testing.mockmatchers.ArgumentMatcher) {
/**
* Delegate match requests to this matcher.
* @type {goog.testing.mockmatchers.ArgumentMatcher}
* @private
*/
this.delegateMatcher_ = opt_matcher;
} else if (!opt_matcher) {
this.delegateMatcher_ = goog.testing.mockmatchers.ignoreArgument;
}
};
goog.inherits(goog.testing.mockmatchers.SaveArgument,
goog.testing.mockmatchers.ArgumentMatcher);
/** @override */
goog.testing.mockmatchers.SaveArgument.prototype.matches = function(
toVerify, opt_expectation) {
this.arg = toVerify;
if (this.delegateMatcher_) {
return this.delegateMatcher_.matches(toVerify, opt_expectation);
}
return goog.testing.mockmatchers.SaveArgument.superClass_.matches.call(
this, toVerify, opt_expectation);
};
/**
* Saved argument that was verified.
* @type {*}
*/
goog.testing.mockmatchers.SaveArgument.prototype.arg;
/**
* An instance of the IgnoreArgument matcher. Returns true for all matches.
* @type {goog.testing.mockmatchers.IgnoreArgument}
*/
goog.testing.mockmatchers.ignoreArgument =
new goog.testing.mockmatchers.IgnoreArgument();
/**
* A matcher that verifies that an argument is an array.
* @type {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.isArray =
new goog.testing.mockmatchers.ArgumentMatcher(goog.isArray,
'isArray');
/**
* A matcher that verifies that an argument is a array-like. A NodeList is an
* example of a collection that is very close to an array.
* @type {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.isArrayLike =
new goog.testing.mockmatchers.ArgumentMatcher(goog.isArrayLike,
'isArrayLike');
/**
* A matcher that verifies that an argument is a date-like.
* @type {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.isDateLike =
new goog.testing.mockmatchers.ArgumentMatcher(goog.isDateLike,
'isDateLike');
/**
* A matcher that verifies that an argument is a string.
* @type {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.isString =
new goog.testing.mockmatchers.ArgumentMatcher(goog.isString,
'isString');
/**
* A matcher that verifies that an argument is a boolean.
* @type {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.isBoolean =
new goog.testing.mockmatchers.ArgumentMatcher(goog.isBoolean,
'isBoolean');
/**
* A matcher that verifies that an argument is a number.
* @type {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.isNumber =
new goog.testing.mockmatchers.ArgumentMatcher(goog.isNumber,
'isNumber');
/**
* A matcher that verifies that an argument is a function.
* @type {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.isFunction =
new goog.testing.mockmatchers.ArgumentMatcher(goog.isFunction,
'isFunction');
/**
* A matcher that verifies that an argument is an object.
* @type {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.isObject =
new goog.testing.mockmatchers.ArgumentMatcher(goog.isObject,
'isObject');
/**
* A matcher that verifies that an argument is like a DOM node.
* @type {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.mockmatchers.isNodeLike =
new goog.testing.mockmatchers.ArgumentMatcher(goog.dom.isNodeLike,
'isNodeLike');
/**
* A function that checks to see if an array matches a given set of
* expectations. The expectations array can be a mix of ArgumentMatcher
* implementations and values. True will be returned if values are identical or
* if a matcher returns a positive result.
* @param {Array} expectedArr An array of expectations which can be either
* values to check for equality or ArgumentMatchers.
* @param {Array} arr The array to match.
* @param {goog.testing.MockExpectation?=} opt_expectation The expectation
* for this match.
* @return {boolean} Whether or not the given array matches the expectations.
*/
goog.testing.mockmatchers.flexibleArrayMatcher =
function(expectedArr, arr, opt_expectation) {
return goog.array.equals(expectedArr, arr, function(a, b) {
var errCount = 0;
if (opt_expectation) {
errCount = opt_expectation.getErrorMessageCount();
}
var isamatch = a === b ||
a instanceof goog.testing.mockmatchers.ArgumentMatcher &&
a.matches(b, opt_expectation);
var failureMessage = null;
if (!isamatch) {
failureMessage = goog.testing.asserts.findDifferences(a, b);
isamatch = !failureMessage;
}
if (!isamatch && opt_expectation) {
// If the error count changed, the match sent out an error
// message. If the error count has not changed, then
// we need to send out an error message...
if (errCount == opt_expectation.getErrorMessageCount()) {
// Use the _displayStringForValue() from assert.js
// for consistency...
if (!failureMessage) {
failureMessage = 'Expected: ' + _displayStringForValue(a) +
' but was: ' + _displayStringForValue(b);
}
opt_expectation.addErrorMessage(failureMessage);
}
}
return isamatch;
});
};
| 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 test runner is a singleton object that is used to execute
* a goog.testing.TestCases, display the results, and expose the results to
* Selenium for automation. If a TestCase hasn't been registered with the
* runner by the time window.onload occurs, the testRunner will try to auto-
* discover JsUnit style test pages.
*
* The hooks for selenium are :-
* - Boolean G_testRunner.isFinished()
* - Boolean G_testRunner.isSuccess()
* - String G_testRunner.getReport()
* - number G_testRunner.getRunTime()
*
* Testing code should not have dependencies outside of goog.testing so as to
* reduce the chance of masking missing dependencies.
*
*/
goog.provide('goog.testing.TestRunner');
goog.require('goog.testing.TestCase');
/**
* Construct a test runner.
*
* NOTE(user): This is currently pretty weird, I'm essentially trying to
* create a wrapper that the Selenium test can hook into to query the state of
* the running test case, while making goog.testing.TestCase general.
*
* @constructor
*/
goog.testing.TestRunner = function() {
/**
* Errors that occurred in the window.
* @type {Array.<string>}
*/
this.errors = [];
};
/**
* Reference to the active test case.
* @type {goog.testing.TestCase?}
*/
goog.testing.TestRunner.prototype.testCase = null;
/**
* Whether the test runner has been initialized yet.
* @type {boolean}
*/
goog.testing.TestRunner.prototype.initialized = false;
/**
* Element created in the document to add test results to.
* @type {Element}
* @private
*/
goog.testing.TestRunner.prototype.logEl_ = null;
/**
* Function to use when filtering errors.
* @type {(function(string))?}
* @private
*/
goog.testing.TestRunner.prototype.errorFilter_ = null;
/**
* Whether an empty test case counts as an error.
* @type {boolean}
* @private
*/
goog.testing.TestRunner.prototype.strict_ = true;
/**
* Initializes the test runner.
* @param {goog.testing.TestCase} testCase The test case to initialize with.
*/
goog.testing.TestRunner.prototype.initialize = function(testCase) {
if (this.testCase && this.testCase.running) {
throw Error('The test runner is already waiting for a test to complete');
}
this.testCase = testCase;
testCase.setTestRunner(this);
this.initialized = true;
};
/**
* By default, the test runner is strict, and fails if it runs an empty
* test case.
* @param {boolean} strict Whether the test runner should fail on an empty
* test case.
*/
goog.testing.TestRunner.prototype.setStrict = function(strict) {
this.strict_ = strict;
};
/**
* @return {boolean} Whether the test runner should fail on an empty
* test case.
*/
goog.testing.TestRunner.prototype.isStrict = function() {
return this.strict_;
};
/**
* Returns true if the test runner is initialized.
* Used by Selenium Hooks.
* @return {boolean} Whether the test runner is active.
*/
goog.testing.TestRunner.prototype.isInitialized = function() {
return this.initialized;
};
/**
* Returns true if the test runner is finished.
* Used by Selenium Hooks.
* @return {boolean} Whether the test runner is active.
*/
goog.testing.TestRunner.prototype.isFinished = function() {
return this.errors.length > 0 ||
this.initialized && !!this.testCase && this.testCase.started &&
!this.testCase.running;
};
/**
* Returns true if the test case didn't fail.
* Used by Selenium Hooks.
* @return {boolean} Whether the current test returned successfully.
*/
goog.testing.TestRunner.prototype.isSuccess = function() {
return !this.hasErrors() && !!this.testCase && this.testCase.isSuccess();
};
/**
* Returns true if the test case runner has errors that were caught outside of
* the test case.
* @return {boolean} Whether there were JS errors.
*/
goog.testing.TestRunner.prototype.hasErrors = function() {
return this.errors.length > 0;
};
/**
* Logs an error that occurred. Used in the case of environment setting up
* an onerror handler.
* @param {string} msg Error message.
*/
goog.testing.TestRunner.prototype.logError = function(msg) {
if (!this.errorFilter_ || this.errorFilter_.call(null, msg)) {
this.errors.push(msg);
}
};
/**
* Log failure in current running test.
* @param {Error} ex Exception.
*/
goog.testing.TestRunner.prototype.logTestFailure = function(ex) {
var testName = /** @type {string} */ (goog.testing.TestCase.currentTestName);
if (this.testCase) {
this.testCase.logError(testName, ex);
} else {
// NOTE: Do not forget to log the original exception raised.
throw new Error('Test runner not initialized with a test case. Original ' +
'exception: ' + ex.message);
}
};
/**
* Sets a function to use as a filter for errors.
* @param {function(string)} fn Filter function.
*/
goog.testing.TestRunner.prototype.setErrorFilter = function(fn) {
this.errorFilter_ = fn;
};
/**
* Returns a report of the test case that ran.
* Used by Selenium Hooks.
* @param {boolean=} opt_verbose If true results will include data about all
* tests, not just what failed.
* @return {string} A report summary of the test.
*/
goog.testing.TestRunner.prototype.getReport = function(opt_verbose) {
var report = [];
if (this.testCase) {
report.push(this.testCase.getReport(opt_verbose));
}
if (this.errors.length > 0) {
report.push('JavaScript errors detected by test runner:');
report.push.apply(report, this.errors);
report.push('\n');
}
return report.join('\n');
};
/**
* Returns the amount of time it took for the test to run.
* Used by Selenium Hooks.
* @return {number} The run time, in milliseconds.
*/
goog.testing.TestRunner.prototype.getRunTime = function() {
return this.testCase ? this.testCase.getRunTime() : 0;
};
/**
* Returns the number of script files that were loaded in order to run the test.
* @return {number} The number of script files.
*/
goog.testing.TestRunner.prototype.getNumFilesLoaded = function() {
return this.testCase ? this.testCase.getNumFilesLoaded() : 0;
};
/**
* Executes a test case and prints the results to the window.
*/
goog.testing.TestRunner.prototype.execute = function() {
if (!this.testCase) {
throw Error('The test runner must be initialized with a test case before ' +
'execute can be called.');
}
this.testCase.setCompletedCallback(goog.bind(this.onComplete_, this));
this.testCase.runTests();
};
/**
* Writes the results to the document when the test case completes.
* @private
*/
goog.testing.TestRunner.prototype.onComplete_ = function() {
var log = this.testCase.getReport(true);
if (this.errors.length > 0) {
log += '\n' + this.errors.join('\n');
}
if (!this.logEl_) {
var el = document.getElementById('closureTestRunnerLog');
if (el == null) {
el = document.createElement('div');
document.body.appendChild(el);
}
this.logEl_ = el;
}
// Remove all children from the log element.
var logEl = this.logEl_;
while (logEl.firstChild) {
logEl.removeChild(logEl.firstChild);
}
// Highlight the page to indicate the overall outcome.
this.writeLog(log);
var runAgainLink = document.createElement('a');
runAgainLink.style.display = 'block';
runAgainLink.style.fontSize = 'small';
runAgainLink.href = '';
runAgainLink.onclick = goog.bind(function() {
this.execute();
return false;
}, this);
runAgainLink.innerHTML = 'Run again without reloading';
logEl.appendChild(runAgainLink);
};
/**
* Writes a nicely formatted log out to the document.
* @param {string} log The string to write.
*/
goog.testing.TestRunner.prototype.writeLog = function(log) {
var lines = log.split('\n');
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var color;
var isFailOrError = /FAILED/.test(line) || /ERROR/.test(line);
if (/PASSED/.test(line)) {
color = 'darkgreen';
} else if (isFailOrError) {
color = 'darkred';
} else {
color = '#333';
}
var div = document.createElement('div');
if (line.substr(0, 2) == '> ') {
// The stack trace may contain links so it has to be interpreted as HTML.
div.innerHTML = line;
} else {
div.appendChild(document.createTextNode(line));
}
if (isFailOrError) {
var testNameMatch = /(\S+) (\[[^\]]*] )?: (FAILED|ERROR)/.exec(line);
if (testNameMatch) {
// Build a URL to run the test individually. If this test was already
// part of another subset test, we need to overwrite the old runTests
// query parameter. We also need to do this without bringing in any
// extra dependencies, otherwise we could mask missing dependency bugs.
var newSearch = 'runTests=' + testNameMatch[1];
var search = window.location.search;
if (search) {
var oldTests = /runTests=([^&]*)/.exec(search);
if (oldTests) {
newSearch = search.substr(0, oldTests.index) +
newSearch +
search.substr(oldTests.index + oldTests[0].length);
} else {
newSearch = search + '&' + newSearch;
}
} else {
newSearch = '?' + newSearch;
}
var href = window.location.href;
var hash = window.location.hash;
if (hash && hash.charAt(0) != '#') {
hash = '#' + hash;
}
href = href.split('#')[0].split('?')[0] + newSearch + hash;
// Add the link.
var a = document.createElement('A');
a.innerHTML = '(run individually)';
a.style.fontSize = '0.8em';
a.href = href;
div.appendChild(document.createTextNode(' '));
div.appendChild(a);
}
}
div.style.color = color;
div.style.font = 'normal 100% monospace';
if (i == 0) {
// Highlight the first line as a header that indicates the test outcome.
div.style.padding = '20px';
div.style.marginBottom = '10px';
if (isFailOrError) {
div.style.border = '5px solid ' + color;
div.style.backgroundColor = '#ffeeee';
} else {
div.style.border = '1px solid black';
div.style.backgroundColor = '#eeffee';
}
}
try {
div.style.whiteSpace = 'pre-wrap';
} catch (e) {
// NOTE(brenneman): IE raises an exception when assigning to pre-wrap.
// Thankfully, it doesn't collapse whitespace when using monospace fonts,
// so it will display correctly if we ignore the exception.
}
if (i < 2) {
div.style.fontWeight = 'bold';
}
this.logEl_.appendChild(div);
}
};
/**
* Logs a message to the current test case.
* @param {string} s The text to output to the log.
*/
goog.testing.TestRunner.prototype.log = function(s) {
if (this.testCase) {
this.testCase.log(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 Test helpers to compare goog.proto2.Messages.
*
*/
goog.provide('goog.testing.proto2');
goog.require('goog.proto2.Message');
goog.require('goog.testing.asserts');
/**
* Compares two goog.proto2.Message instances of the same type.
* @param {!goog.proto2.Message} expected First message.
* @param {!goog.proto2.Message} actual Second message.
* @param {string} path Path to the messages.
* @return {string} A string describing where they differ. Empty string if they
* are equal.
* @private
*/
goog.testing.proto2.findDifferences_ = function(expected, actual, path) {
var fields = expected.getDescriptor().getFields();
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
var newPath = (path ? path + '/' : '') + field.getName();
if (expected.has(field) && !actual.has(field)) {
return newPath + ' should be present';
}
if (!expected.has(field) && actual.has(field)) {
return newPath + ' should not be present';
}
if (expected.has(field)) {
var isComposite = field.isCompositeType();
if (field.isRepeated()) {
var expectedCount = expected.countOf(field);
var actualCount = actual.countOf(field);
if (expectedCount != actualCount) {
return newPath + ' should have ' + expectedCount + ' items, ' +
'but has ' + actualCount;
}
for (var j = 0; j < expectedCount; j++) {
var expectedItem = expected.get(field, j);
var actualItem = actual.get(field, j);
if (isComposite) {
var itemDiff = goog.testing.proto2.findDifferences_(
/** @type {!goog.proto2.Message} */ (expectedItem),
/** @type {!goog.proto2.Message} */ (actualItem),
newPath + '[' + j + ']');
if (itemDiff) {
return itemDiff;
}
} else {
if (expectedItem != actualItem) {
return newPath + '[' + j + '] should be ' + expectedItem +
', but was ' + actualItem;
}
}
}
} else {
var expectedValue = expected.get(field);
var actualValue = actual.get(field);
if (isComposite) {
var diff = goog.testing.proto2.findDifferences_(
/** @type {!goog.proto2.Message} */ (expectedValue),
/** @type {!goog.proto2.Message} */ (actualValue),
newPath);
if (diff) {
return diff;
}
} else {
if (expectedValue != actualValue) {
return newPath + ' should be ' + expectedValue + ', but was ' +
actualValue;
}
}
}
}
}
return '';
};
/**
* Compares two goog.proto2.Message objects. Gives more readable output than
* assertObjectEquals on mismatch.
* @param {!goog.proto2.Message} expected Expected proto2 message.
* @param {!goog.proto2.Message} actual Actual proto2 message.
* @param {string=} opt_failureMessage Failure message when the values don't
* match.
*/
goog.testing.proto2.assertEquals = function(expected, actual,
opt_failureMessage) {
var failureSummary = opt_failureMessage || '';
if (!(expected instanceof goog.proto2.Message) ||
!(actual instanceof goog.proto2.Message)) {
goog.testing.asserts.raiseException(failureSummary,
'Bad arguments were passed to goog.testing.proto2.assertEquals');
}
if (expected.constructor != actual.constructor) {
goog.testing.asserts.raiseException(failureSummary,
'Message type mismatch: ' + expected.getDescriptor().getFullName() +
' != ' + actual.getDescriptor().getFullName());
}
var diff = goog.testing.proto2.findDifferences_(expected, actual, '');
if (diff) {
goog.testing.asserts.raiseException(failureSummary, diff);
}
};
| 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 Generic queue for writing unit tests.
*/
goog.provide('goog.testing.TestQueue');
/**
* Generic queue for writing unit tests
* @constructor
*/
goog.testing.TestQueue = function() {
/**
* Events that have accumulated
* @type {Array.<Object>}
* @private
*/
this.events_ = [];
};
/**
* Adds a new event onto the queue.
* @param {Object} event The event to queue.
*/
goog.testing.TestQueue.prototype.enqueue = function(event) {
this.events_.push(event);
};
/**
* Returns whether the queue is empty.
* @return {boolean} Whether the queue is empty.
*/
goog.testing.TestQueue.prototype.isEmpty = function() {
return this.events_.length == 0;
};
/**
* Gets the next event from the queue. Throws an exception if the queue is
* empty.
* @param {string=} opt_comment Comment if the queue is empty.
* @return {Object} The next event from the queue.
*/
goog.testing.TestQueue.prototype.dequeue = function(opt_comment) {
if (this.isEmpty()) {
throw Error('Handler is empty: ' + opt_comment);
}
return this.events_.shift();
};
| 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 Mock blob object.
*
*/
goog.provide('goog.testing.fs.Blob');
goog.require('goog.crypt.base64');
/**
* A mock Blob object. The data is stored as a string.
*
* @param {string=} opt_data The string data encapsulated by the blob.
* @param {string=} opt_type The mime type of the blob.
* @constructor
*/
goog.testing.fs.Blob = function(opt_data, opt_type) {
/**
* @see http://www.w3.org/TR/FileAPI/#dfn-type
* @type {string}
*/
this.type = opt_type || '';
this.setDataInternal(opt_data || '');
};
/**
* The string data encapsulated by the blob.
* @type {string}
* @private
*/
goog.testing.fs.Blob.prototype.data_;
/**
* @see http://www.w3.org/TR/FileAPI/#dfn-size
* @type {number}
*/
goog.testing.fs.Blob.prototype.size;
/**
* @see http://www.w3.org/TR/FileAPI/#dfn-slice
* @param {number} start The start byte offset.
* @param {number} length The number of bytes to slice.
* @param {string=} opt_contentType The type of the resulting Blob.
* @return {!goog.testing.fs.Blob} The result of the slice operation.
*/
goog.testing.fs.Blob.prototype.slice = function(
start, length, opt_contentType) {
start = Math.max(0, start);
return new goog.testing.fs.Blob(
this.data_.substring(start, start + Math.max(length, 0)),
opt_contentType);
};
/**
* @return {string} The string data encapsulated by the blob.
* @override
*/
goog.testing.fs.Blob.prototype.toString = function() {
return this.data_;
};
/**
* @return {ArrayBuffer} The string data encapsulated by the blob as an
* ArrayBuffer.
*/
goog.testing.fs.Blob.prototype.toArrayBuffer = function() {
var buf = new ArrayBuffer(this.data_.length * 2);
var arr = new Uint16Array(buf);
for (var i = 0; i < this.data_.length; i++) {
arr[i] = this.data_.charCodeAt(i);
}
return buf;
};
/**
* @return {string} The string data encapsulated by the blob as a data: URI.
*/
goog.testing.fs.Blob.prototype.toDataUrl = function() {
return 'data:' + this.type + ';base64,' +
goog.crypt.base64.encodeString(this.data_);
};
/**
* Sets the internal contents of the blob. This should only be called by other
* functions inside the {@code goog.testing.fs} namespace.
*
* @param {string} data The data for this Blob.
*/
goog.testing.fs.Blob.prototype.setDataInternal = function(data) {
this.data_ = data;
this.size = data.length;
};
| 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 Mock ProgressEvent object.
*
*/
goog.provide('goog.testing.fs.ProgressEvent');
goog.require('goog.events.Event');
/**
* A mock progress event.
*
* @param {!goog.fs.FileSaver.EventType|!goog.fs.FileReader.EventType} type
* Event type.
* @param {number} loaded The number of bytes processed.
* @param {number} total The total data that was to be processed, in bytes.
* @constructor
* @extends {goog.events.Event}
*/
goog.testing.fs.ProgressEvent = function(type, loaded, total) {
goog.base(this, type);
/**
* The number of bytes processed.
* @type {number}
* @private
*/
this.loaded_ = loaded;
/**
* The total data that was to be procesed, in bytes.
* @type {number}
* @private
*/
this.total_ = total;
};
goog.inherits(goog.testing.fs.ProgressEvent, goog.events.Event);
/**
* @see {goog.fs.ProgressEvent#isLengthComputable}
* @return {boolean} True if the length is known.
*/
goog.testing.fs.ProgressEvent.prototype.isLengthComputable = function() {
return true;
};
/**
* @see {goog.fs.ProgressEvent#getLoaded}
* @return {number} The number of bytes loaded or written.
*/
goog.testing.fs.ProgressEvent.prototype.getLoaded = function() {
return this.loaded_;
};
/**
* @see {goog.fs.ProgressEvent#getTotal}
* @return {number} The total bytes to load or write.
*/
goog.testing.fs.ProgressEvent.prototype.getTotal = function() {
return this.total_;
};
| 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 Mock implementations of the Closure HTML5 FileSystem wrapper
* classes. These implementations are designed to be usable in any browser, so
* they use none of the native FileSystem-related objects.
*
*/
goog.provide('goog.testing.fs');
goog.require('goog.Timer');
goog.require('goog.array');
goog.require('goog.async.Deferred');
goog.require('goog.fs');
goog.require('goog.testing.fs.Blob');
goog.require('goog.testing.fs.FileSystem');
/**
* Get a filesystem object. Since these are mocks, there's no difference between
* temporary and persistent filesystems.
*
* @param {number} size Ignored.
* @return {!goog.async.Deferred} The deferred
* {@link goog.testing.fs.FileSystem}.
*/
goog.testing.fs.getTemporary = function(size) {
var d = new goog.async.Deferred();
goog.Timer.callOnce(
goog.bind(d.callback, d, new goog.testing.fs.FileSystem()));
return d;
};
/**
* Get a filesystem object. Since these are mocks, there's no difference between
* temporary and persistent filesystems.
*
* @param {number} size Ignored.
* @return {!goog.async.Deferred} The deferred
* {@link goog.testing.fs.FileSystem}.
*/
goog.testing.fs.getPersistent = function(size) {
return goog.testing.fs.getTemporary(size);
};
/**
* Which object URLs have been granted for fake blobs.
* @type {!Object.<boolean>}
* @private
*/
goog.testing.fs.objectUrls_ = {};
/**
* Create a fake object URL for a given fake blob. This can be used as a real
* URL, and it can be created and revoked normally.
*
* @param {!goog.testing.fs.Blob} blob The blob for which to create the URL.
* @return {string} The URL.
*/
goog.testing.fs.createObjectUrl = function(blob) {
var url = blob.toDataUrl();
goog.testing.fs.objectUrls_[url] = true;
return url;
};
/**
* Remove a URL that was created for a fake blob.
*
* @param {string} url The URL to revoke.
*/
goog.testing.fs.revokeObjectUrl = function(url) {
delete goog.testing.fs.objectUrls_[url];
};
/**
* Return whether or not a URL has been granted for the given blob.
*
* @param {!goog.testing.fs.Blob} blob The blob to check.
* @return {boolean} Whether a URL has been granted.
*/
goog.testing.fs.isObjectUrlGranted = function(blob) {
return (blob.toDataUrl()) in goog.testing.fs.objectUrls_;
};
/**
* Concatenates one or more values together and converts them to a fake blob.
*
* @param {...(string|!goog.testing.fs.Blob)} var_args The values that will make
* up the resulting blob.
* @return {!goog.testing.fs.Blob} The blob.
*/
goog.testing.fs.getBlob = function(var_args) {
return new goog.testing.fs.Blob(goog.array.map(arguments, String).join(''));
};
/**
* Returns the string value of a fake blob.
*
* @param {!goog.testing.fs.Blob} blob The blob to convert to a string.
* @param {string=} opt_encoding Ignored.
* @return {!goog.async.Deferred} The deferred string value of the blob.
*/
goog.testing.fs.blobToString = function(blob, opt_encoding) {
var d = new goog.async.Deferred();
goog.Timer.callOnce(goog.bind(d.callback, d, blob.toString()));
return d;
};
/**
* Installs goog.testing.fs in place of the standard goog.fs. After calling
* this, code that uses goog.fs should work without issue using goog.testing.fs.
*
* @param {!goog.testing.PropertyReplacer} stubs The property replacer for
* stubbing out the original goog.fs functions.
*/
goog.testing.fs.install = function(stubs) {
// Prevent warnings that goog.fs may get optimized away. It's true this is
// unsafe in compiled code, but it's only meant for tests.
var fs = goog.getObjectByName('goog.fs');
stubs.replace(fs, 'getTemporary', goog.testing.fs.getTemporary);
stubs.replace(fs, 'getPersistent', goog.testing.fs.getPersistent);
stubs.replace(fs, 'createObjectUrl', goog.testing.fs.createObjectUrl);
stubs.replace(fs, 'revokeObjectUrl', goog.testing.fs.revokeObjectUrl);
stubs.replace(fs, 'getBlob', goog.testing.fs.getBlob);
stubs.replace(fs, 'blobToString', goog.testing.fs.blobToString);
};
| 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 Mock filesystem objects. These are all in the same file to
* avoid circular dependency issues.
*
*/
goog.provide('goog.testing.fs.DirectoryEntry');
goog.provide('goog.testing.fs.Entry');
goog.provide('goog.testing.fs.FileEntry');
goog.require('goog.Timer');
goog.require('goog.array');
goog.require('goog.async.Deferred');
goog.require('goog.fs.DirectoryEntry');
goog.require('goog.fs.DirectoryEntry.Behavior');
goog.require('goog.fs.Error');
goog.require('goog.functions');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.testing.fs.File');
goog.require('goog.testing.fs.FileWriter');
/**
* A mock filesystem entry object.
*
* @param {!goog.testing.fs.FileSystem} fs The filesystem containing this entry.
* @param {!goog.testing.fs.DirectoryEntry} parent The directory entry directly
* containing this entry.
* @param {string} name The name of this entry.
* @constructor
*/
goog.testing.fs.Entry = function(fs, parent, name) {
/**
* This entry's filesystem.
* @type {!goog.testing.fs.FileSystem}
* @private
*/
this.fs_ = fs;
/**
* The name of this entry.
* @type {string}
* @private
*/
this.name_ = name;
/**
* The parent of this entry.
* @type {!goog.testing.fs.DirectoryEntry}
*/
this.parent = parent;
};
/**
* Whether or not this entry has been deleted.
* @type {boolean}
*/
goog.testing.fs.Entry.prototype.deleted = false;
/**
* @see {goog.fs.Entry#isFile}
* @return {boolean}
*/
goog.testing.fs.Entry.prototype.isFile = goog.abstractMethod;
/**
* @see {goog.fs.Entry#isDirectory}
* @return {boolean}
*/
goog.testing.fs.Entry.prototype.isDirectory = goog.abstractMethod;
/**
* @see {goog.fs.Entry#getName}
* @return {string}
*/
goog.testing.fs.Entry.prototype.getName = function() {
return this.name_;
};
/**
* @see {goog.fs.Entry#getFullPath}
* @return {string}
*/
goog.testing.fs.Entry.prototype.getFullPath = function() {
if (this.getName() == '' || this.parent.getName() == '') {
// The root directory has an empty name
return '/' + this.name_;
} else {
return this.parent.getFullPath() + '/' + this.name_;
}
};
/**
* @see {goog.fs.Entry#getFileSystem}
* @return {!goog.testing.fs.FileSystem}
*/
goog.testing.fs.Entry.prototype.getFileSystem = function() {
return this.fs_;
};
/**
* @see {goog.fs.Entry#getLastModified}
* @return {!goog.async.Deferred}
*/
goog.testing.fs.Entry.prototype.getLastModified = goog.abstractMethod;
/**
* @see {goog.fs.Entry#getMetadata}
* @return {!goog.async.Deferred}
*/
goog.testing.fs.Entry.prototype.getMetadata = goog.abstractMethod;
/**
* @see {goog.fs.Entry#moveTo}
* @param {!goog.testing.fs.DirectoryEntry} parent
* @param {string=} opt_newName
* @return {!goog.async.Deferred}
*/
goog.testing.fs.Entry.prototype.moveTo = function(parent, opt_newName) {
var msg = 'moving ' + this.getFullPath() + ' into ' + parent.getFullPath() +
(opt_newName ? ', renaming to ' + opt_newName : '');
var newFile;
return this.checkNotDeleted(msg).
addCallback(function() { return this.copyTo(parent, opt_newName); }).
addCallback(function(file) {
newFile = file;
return this.remove();
}).addCallback(function() { return newFile; });
};
/**
* @see {goog.fs.Entry#copyTo}
* @param {!goog.testing.fs.DirectoryEntry} parent
* @param {string=} opt_newName
* @return {!goog.async.Deferred}
*/
goog.testing.fs.Entry.prototype.copyTo = function(parent, opt_newName) {
var msg = 'copying ' + this.getFullPath() + ' into ' + parent.getFullPath() +
(opt_newName ? ', renaming to ' + opt_newName : '');
return this.checkNotDeleted(msg).addCallback(function() {
var name = opt_newName || this.getName();
var entry = this.clone();
parent.children[name] = entry;
parent.lastModifiedTimestamp_ = goog.now();
entry.name_ = name;
entry.parent = parent;
return entry;
});
};
/**
* @return {!goog.testing.fs.Entry} A shallow copy of this entry object.
*/
goog.testing.fs.Entry.prototype.clone = goog.abstractMethod;
/**
* @see {goog.fs.Entry#toUrl}
* @return {string}
*/
goog.testing.fs.Entry.prototype.toUrl = function(opt_mimetype) {
return 'fakefilesystem:' + this.getFullPath();
};
/**
* @see {goog.fs.Entry#remove}
* @return {!goog.async.Deferred}
*/
goog.testing.fs.Entry.prototype.remove = function() {
var msg = 'removing ' + this.getFullPath();
return this.checkNotDeleted(msg).addCallback(function() {
delete this.parent.children[this.getName()];
this.parent.lastModifiedTimestamp_ = goog.now();
this.deleted = true;
return;
});
};
/**
* @see {goog.fs.Entry#getParent}
* @return {!goog.async.Deferred}
*/
goog.testing.fs.Entry.prototype.getParent = function() {
var msg = 'getting parent of ' + this.getFullPath();
return this.checkNotDeleted(msg).
addCallback(function() { return this.parent; });
};
/**
* Return a deferred that will call its errback if this entry has been deleted.
* In addition, the deferred will only run after a timeout of 0, and all its
* callbacks will run with the entry as "this".
*
* @param {string} action The name of the action being performed. For error
* reporting.
* @return {!goog.async.Deferred} The deferred that will be called after a
* timeout of 0.
* @protected
*/
goog.testing.fs.Entry.prototype.checkNotDeleted = function(action) {
var d = new goog.async.Deferred(undefined, this);
goog.Timer.callOnce(function() {
if (this.deleted) {
d.errback(new goog.fs.Error(goog.fs.Error.ErrorCode.NOT_FOUND, action));
} else {
d.callback();
}
}, 0, this);
return d;
};
/**
* A mock directory entry object.
*
* @param {!goog.testing.fs.FileSystem} fs The filesystem containing this entry.
* @param {goog.testing.fs.DirectoryEntry} parent The directory entry directly
* containing this entry. If this is null, that means this is the root
* directory and so is its own parent.
* @param {string} name The name of this entry.
* @param {!Object.<!goog.testing.fs.Entry>} children The map of child names to
* entry objects.
* @constructor
* @extends {goog.testing.fs.Entry}
*/
goog.testing.fs.DirectoryEntry = function(fs, parent, name, children) {
goog.base(this, fs, parent || this, name);
/**
* The map of child names to entry objects.
* @type {!Object.<!goog.testing.fs.Entry>}
*/
this.children = children;
/**
* The modification time of the directory. Measured using goog.now, which may
* be overridden with mock time providers.
* @type {number}
* @private
*/
this.lastModifiedTimestamp_ = goog.now();
};
goog.inherits(goog.testing.fs.DirectoryEntry, goog.testing.fs.Entry);
/**
* Constructs and returns the metadata object for this entry.
* @return {{modificationTime: Date}} The metadata object.
* @private
*/
goog.testing.fs.DirectoryEntry.prototype.getMetadata_ = function() {
return {
'modificationTime': new Date(this.lastModifiedTimestamp_)
};
};
/** @override */
goog.testing.fs.DirectoryEntry.prototype.isFile = function() {
return false;
};
/** @override */
goog.testing.fs.DirectoryEntry.prototype.isDirectory = function() {
return true;
};
/** @override */
goog.testing.fs.DirectoryEntry.prototype.getLastModified = function() {
var msg = 'reading last modified date for ' + this.getFullPath();
return this.checkNotDeleted(msg).
addCallback(function() {return new Date(this.lastModifiedTimestamp_)});
};
/** @override */
goog.testing.fs.DirectoryEntry.prototype.getMetadata = function() {
var msg = 'reading metadata for ' + this.getFullPath();
return this.checkNotDeleted(msg).
addCallback(function() {return this.getMetadata_()});
};
/** @override */
goog.testing.fs.DirectoryEntry.prototype.clone = function() {
return new goog.testing.fs.DirectoryEntry(
this.getFileSystem(), this.parent, this.getName(), this.children);
};
/** @override */
goog.testing.fs.DirectoryEntry.prototype.remove = function() {
if (!goog.object.isEmpty(this.children)) {
var d = new goog.async.Deferred();
goog.Timer.callOnce(function() {
d.errback(new goog.fs.Error(
goog.fs.Error.ErrorCode.INVALID_MODIFICATION,
'removing ' + this.getFullPath()));
}, 0, this);
return d;
} else {
return goog.base(this, 'remove');
}
};
/**
* @see {goog.fs.DirectoryEntry#getFile}
* @param {string} path
* @param {goog.fs.DirectoryEntry.Behavior=} opt_behavior
* @return {!goog.async.Deferred}
*/
goog.testing.fs.DirectoryEntry.prototype.getFile = function(
path, opt_behavior) {
var msg = 'loading file ' + path + ' from ' + this.getFullPath();
opt_behavior = opt_behavior || goog.fs.DirectoryEntry.Behavior.DEFAULT;
return this.checkNotDeleted(msg).addCallback(function() {
try {
return goog.async.Deferred.succeed(this.getFileSync(path, opt_behavior));
} catch (e) {
return goog.async.Deferred.fail(e);
}
});
};
/**
* @see {goog.fs.DirectoryEntry#getDirectory}
* @param {string} path
* @param {goog.fs.DirectoryEntry.Behavior=} opt_behavior
* @return {!goog.async.Deferred}
*/
goog.testing.fs.DirectoryEntry.prototype.getDirectory = function(
path, opt_behavior) {
var msg = 'loading directory ' + path + ' from ' + this.getFullPath();
opt_behavior = opt_behavior || goog.fs.DirectoryEntry.Behavior.DEFAULT;
return this.checkNotDeleted(msg).addCallback(function() {
try {
return goog.async.Deferred.succeed(
this.getDirectorySync(path, opt_behavior));
} catch (e) {
return goog.async.Deferred.fail(e);
}
});
};
/**
* Get a file entry synchronously, without waiting for a Deferred to resolve.
*
* @param {string} path The path to the file, relative to this directory.
* @param {goog.fs.DirectoryEntry.Behavior=} opt_behavior The behavior for
* loading the file.
* @return {!goog.testing.fs.FileEntry} The loaded file.
*/
goog.testing.fs.DirectoryEntry.prototype.getFileSync = function(
path, opt_behavior) {
opt_behavior = opt_behavior || goog.fs.DirectoryEntry.Behavior.DEFAULT;
return (/** @type {!goog.testing.fs.FileEntry} */ (this.getEntry_(
path, opt_behavior, true /* isFile */,
goog.bind(function(parent, name) {
return new goog.testing.fs.FileEntry(
this.getFileSystem(), parent, name, '');
}, this))));
};
/**
* Creates a file synchronously. This is a shorthand for getFileSync, useful for
* setting up tests.
*
* @param {string} path The path to the file, relative to this directory.
* @return {!goog.testing.fs.FileEntry} The created file.
*/
goog.testing.fs.DirectoryEntry.prototype.createFileSync = function(path) {
return this.getFileSync(path, goog.fs.DirectoryEntry.Behavior.CREATE);
};
/**
* Get a directory synchronously, without waiting for a Deferred to resolve.
*
* @param {string} path The path to the directory, relative to this one.
* @param {goog.fs.DirectoryEntry.Behavior=} opt_behavior The behavior for
* loading the directory.
* @return {!goog.testing.fs.DirectoryEntry} The loaded directory.
*/
goog.testing.fs.DirectoryEntry.prototype.getDirectorySync = function(
path, opt_behavior) {
opt_behavior = opt_behavior || goog.fs.DirectoryEntry.Behavior.DEFAULT;
return (/** @type {!goog.testing.fs.DirectoryEntry} */ (this.getEntry_(
path, opt_behavior, false /* isFile */,
goog.bind(function(parent, name) {
return new goog.testing.fs.DirectoryEntry(
this.getFileSystem(), parent, name, {});
}, this))));
};
/**
* Creates a directory synchronously. This is a shorthand for getFileSync,
* useful for setting up tests.
*
* @param {string} path The path to the directory, relative to this directory.
* @return {!goog.testing.fs.DirectoryEntry} The created directory.
*/
goog.testing.fs.DirectoryEntry.prototype.createDirectorySync = function(path) {
return this.getDirectorySync(path, goog.fs.DirectoryEntry.Behavior.CREATE);
};
/**
* Get a file or directory entry from a path. This handles parsing the path for
* subdirectories and throwing appropriate errors should something go wrong.
*
* @param {string} path The path to the entry, relative to this directory.
* @param {goog.fs.DirectoryEntry.Behavior} behavior The behavior for loading
* the entry.
* @param {boolean} isFile Whether a file or directory is being loaded.
* @param {function(!goog.testing.fs.DirectoryEntry, string) :
* !goog.testing.fs.Entry} createFn
* The function for creating the entry if it doesn't yet exist. This is
* passed the parent entry and the name of the new entry.
* @return {!goog.testing.fs.Entry} The loaded entry.
* @private
*/
goog.testing.fs.DirectoryEntry.prototype.getEntry_ = function(
path, behavior, isFile, createFn) {
// Filter out leading, trailing, and duplicate slashes.
var components = goog.array.filter(path.split('/'), goog.functions.identity);
var basename = /** @type {string} */ (goog.array.peek(components)) || '';
var dir = goog.string.startsWith(path, '/') ?
this.getFileSystem().getRoot() : this;
goog.array.forEach(components.slice(0, -1), function(p) {
var subdir = dir.children[p];
if (!subdir) {
throw new goog.fs.Error(
goog.fs.Error.ErrorCode.NOT_FOUND,
'loading ' + path + ' from ' + this.getFullPath() + ' (directory ' +
dir.getFullPath() + '/' + p + ')');
}
dir = subdir;
}, this);
// If there is no basename, the path must resolve to the root directory.
var entry = basename ? dir.children[basename] : dir;
if (!entry) {
if (behavior == goog.fs.DirectoryEntry.Behavior.DEFAULT) {
throw new goog.fs.Error(
goog.fs.Error.ErrorCode.NOT_FOUND,
'loading ' + path + ' from ' + this.getFullPath());
} else {
goog.asserts.assert(
behavior == goog.fs.DirectoryEntry.Behavior.CREATE ||
behavior == goog.fs.DirectoryEntry.Behavior.CREATE_EXCLUSIVE);
entry = createFn(dir, basename);
dir.children[basename] = entry;
this.lastModifiedTimestamp_ = goog.now();
return entry;
}
} else if (behavior == goog.fs.DirectoryEntry.Behavior.CREATE_EXCLUSIVE) {
throw new goog.fs.Error(
goog.fs.Error.ErrorCode.PATH_EXISTS,
'loading ' + path + ' from ' + this.getFullPath());
} else if (entry.isFile() != isFile) {
throw new goog.fs.Error(
goog.fs.Error.ErrorCode.TYPE_MISMATCH,
'loading ' + path + ' from ' + this.getFullPath());
} else {
if (behavior == goog.fs.DirectoryEntry.Behavior.CREATE) {
this.lastModifiedTimestamp_ = goog.now();
}
return entry;
}
};
/**
* Returns whether this directory has a child with the given name.
*
* @param {string} name The name of the entry to check for.
* @return {boolean} Whether or not this has a child with the given name.
*/
goog.testing.fs.DirectoryEntry.prototype.hasChild = function(name) {
return name in this.children;
};
/**
* @see {goog.fs.DirectoryEntry.removeRecursively}
* @return {!goog.async.Deferred}
*/
goog.testing.fs.DirectoryEntry.prototype.removeRecursively = function() {
var msg = 'removing ' + this.getFullPath() + ' recursively';
return this.checkNotDeleted(msg).addCallback(function() {
var d = goog.async.Deferred.succeed(null);
goog.object.forEach(this.children, function(child) {
d.awaitDeferred(
child.isDirectory() ? child.removeRecursively() : child.remove());
});
d.addCallback(function() { return this.remove(); }, this);
return d;
});
};
/**
* @see {goog.fs.DirectoryEntry#listDirectory}
* @return {!goog.async.Deferred}
*/
goog.testing.fs.DirectoryEntry.prototype.listDirectory = function() {
var msg = 'listing ' + this.getFullPath();
return this.checkNotDeleted(msg).addCallback(function() {
return goog.object.getValues(this.children);
});
};
/**
* @see {goog.fs.DirectoryEntry#createPath}
* @return {!goog.async.Deferred}
*/
goog.testing.fs.DirectoryEntry.prototype.createPath =
// This isn't really type-safe.
/** @type {!Function} */ (goog.fs.DirectoryEntry.prototype.createPath);
/**
* A mock file entry object.
*
* @param {!goog.testing.fs.FileSystem} fs The filesystem containing this entry.
* @param {!goog.testing.fs.DirectoryEntry} parent The directory entry directly
* containing this entry.
* @param {string} name The name of this entry.
* @param {string} data The data initially contained in the file.
* @constructor
* @extends {goog.testing.fs.Entry}
*/
goog.testing.fs.FileEntry = function(fs, parent, name, data) {
goog.base(this, fs, parent, name);
/**
* The internal file blob referenced by this file entry.
* @type {!goog.testing.fs.File}
* @private
*/
this.file_ = new goog.testing.fs.File(name, new Date(goog.now()), data);
/**
* The metadata for file.
* @type {{modificationTime: Date}}
* @private
*/
this.metadata_ = {
'modificationTime': this.file_.lastModifiedDate
};
};
goog.inherits(goog.testing.fs.FileEntry, goog.testing.fs.Entry);
/** @override */
goog.testing.fs.FileEntry.prototype.isFile = function() {
return true;
};
/** @override */
goog.testing.fs.FileEntry.prototype.isDirectory = function() {
return false;
};
/** @override */
goog.testing.fs.FileEntry.prototype.clone = function() {
return new goog.testing.fs.FileEntry(
this.getFileSystem(), this.parent,
this.getName(), this.fileSync().toString());
};
/** @override */
goog.testing.fs.FileEntry.prototype.getLastModified = function() {
return this.file().addCallback(function(file) {
return file.lastModifiedDate;
});
};
/** @override */
goog.testing.fs.FileEntry.prototype.getMetadata = function() {
var msg = 'getting metadata for ' + this.getFullPath();
return this.checkNotDeleted(msg).addCallback(function() {
return this.metadata_;
});
};
/**
* @see {goog.fs.FileEntry#createWriter}
* @return {!goog.async.Deferred}
*/
goog.testing.fs.FileEntry.prototype.createWriter = function() {
var d = new goog.async.Deferred();
goog.Timer.callOnce(
goog.bind(d.callback, d, new goog.testing.fs.FileWriter(this)));
return d;
};
/**
* @see {goog.fs.FileEntry#file}
* @return {!goog.async.Deferred}
*/
goog.testing.fs.FileEntry.prototype.file = function() {
var msg = 'getting file for ' + this.getFullPath();
return this.checkNotDeleted(msg).addCallback(function() {
return this.fileSync();
});
};
/**
* Get the internal file representation synchronously, without waiting for a
* Deferred to resolve.
*
* @return {!goog.testing.fs.File} The internal file blob referenced by this
* FileEntry.
*/
goog.testing.fs.FileEntry.prototype.fileSync = function() {
return this.file_;
};
| 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 Mock FileReader object.
*
*/
goog.provide('goog.testing.fs.FileReader');
goog.require('goog.Timer');
goog.require('goog.events.EventTarget');
goog.require('goog.fs.Error');
goog.require('goog.fs.FileReader.EventType');
goog.require('goog.fs.FileReader.ReadyState');
goog.require('goog.testing.fs.File');
goog.require('goog.testing.fs.ProgressEvent');
/**
* A mock FileReader object. This emits the same events as
* {@link goog.fs.FileReader}.
*
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.testing.fs.FileReader = function() {
goog.base(this);
/**
* The current state of the reader.
* @type {goog.fs.FileReader.ReadyState}
* @private
*/
this.readyState_ = goog.fs.FileReader.ReadyState.INIT;
};
goog.inherits(goog.testing.fs.FileReader, goog.events.EventTarget);
/**
* The most recent error experienced by this reader.
* @type {goog.fs.Error}
* @private
*/
goog.testing.fs.FileReader.prototype.error_;
/**
* Whether the current operation has been aborted.
* @type {boolean}
* @private
*/
goog.testing.fs.FileReader.prototype.aborted_ = false;
/**
* The blob this reader is reading from.
* @type {goog.testing.fs.Blob}
* @private
*/
goog.testing.fs.FileReader.prototype.blob_;
/**
* The possible return types.
* @enum {number}
*/
goog.testing.fs.FileReader.ReturnType = {
/**
* Used when reading as text.
*/
TEXT: 1,
/**
* Used when reading as binary string.
*/
BINARY_STRING: 2,
/**
* Used when reading as array buffer.
*/
ARRAY_BUFFER: 3,
/**
* Used when reading as data URL.
*/
DATA_URL: 4
};
/**
* The return type we're reading.
* @type {goog.testing.fs.FileReader.ReturnType}
* @private
*/
goog.testing.fs.FileReader.returnType_;
/**
* @see {goog.fs.FileReader#getReadyState}
* @return {goog.fs.FileReader.ReadyState} The current ready state.
*/
goog.testing.fs.FileReader.prototype.getReadyState = function() {
return this.readyState_;
};
/**
* @see {goog.fs.FileReader#getError}
* @return {goog.fs.Error} The current error.
*/
goog.testing.fs.FileReader.prototype.getError = function() {
return this.error_;
};
/**
* @see {goog.fs.FileReader#abort}
*/
goog.testing.fs.FileReader.prototype.abort = function() {
if (this.readyState_ != goog.fs.FileReader.ReadyState.LOADING) {
var msg = 'aborting read';
throw new goog.fs.Error(goog.fs.Error.ErrorCode.INVALID_STATE, msg);
}
this.aborted_ = true;
};
/**
* @see {goog.fs.FileReader#getResult}
* @return {*} The result of the file read.
*/
goog.testing.fs.FileReader.prototype.getResult = function() {
if (this.readyState_ != goog.fs.FileReader.ReadyState.DONE) {
return undefined;
}
if (this.error_) {
return undefined;
}
if (this.returnType_ == goog.testing.fs.FileReader.ReturnType.TEXT) {
return this.blob_.toString();
} else if (this.returnType_ ==
goog.testing.fs.FileReader.ReturnType.ARRAY_BUFFER) {
return this.blob_.toArrayBuffer();
} else if (this.returnType_ ==
goog.testing.fs.FileReader.ReturnType.BINARY_STRING) {
return this.blob_.toString();
} else if (this.returnType_ ==
goog.testing.fs.FileReader.ReturnType.DATA_URL) {
return this.blob_.toDataUrl();
} else {
return undefined;
}
};
/**
* Fires the read events.
* @param {!goog.testing.fs.Blob} blob The blob to read from.
* @private
*/
goog.testing.fs.FileReader.prototype.read_ = function(blob) {
this.blob_ = blob;
if (this.readyState_ == goog.fs.FileReader.ReadyState.LOADING) {
var msg = 'reading file';
throw new goog.fs.Error(goog.fs.Error.ErrorCode.INVALID_STATE, msg);
}
this.readyState_ = goog.fs.FileReader.ReadyState.LOADING;
goog.Timer.callOnce(function() {
if (this.aborted_) {
this.abort_(blob.size);
return;
}
this.progressEvent_(goog.fs.FileReader.EventType.LOAD_START, 0, blob.size);
this.progressEvent_(goog.fs.FileReader.EventType.LOAD, blob.size / 2,
blob.size);
this.progressEvent_(goog.fs.FileReader.EventType.LOAD, blob.size,
blob.size);
this.readyState_ = goog.fs.FileReader.ReadyState.DONE;
this.progressEvent_(goog.fs.FileReader.EventType.LOAD, blob.size,
blob.size);
this.progressEvent_(goog.fs.FileReader.EventType.LOAD_END, blob.size,
blob.size);
}, 0, this);
};
/**
* @see {goog.fs.FileReader#readAsBinaryString}
* @param {!goog.testing.fs.Blob} blob The blob to read.
*/
goog.testing.fs.FileReader.prototype.readAsBinaryString = function(blob) {
this.returnType_ = goog.testing.fs.FileReader.ReturnType.BINARY_STRING;
this.read_(blob);
};
/**
* @see {goog.fs.FileReader#readAsArrayBuffer}
* @param {!goog.testing.fs.Blob} blob The blob to read.
*/
goog.testing.fs.FileReader.prototype.readAsArrayBuffer = function(blob) {
this.returnType_ = goog.testing.fs.FileReader.ReturnType.ARRAY_BUFFER;
this.read_(blob);
};
/**
* @see {goog.fs.FileReader#readAsText}
* @param {!goog.testing.fs.Blob} blob The blob to read.
* @param {string=} opt_encoding The name of the encoding to use.
*/
goog.testing.fs.FileReader.prototype.readAsText = function(blob, opt_encoding) {
this.returnType_ = goog.testing.fs.FileReader.ReturnType.TEXT;
this.read_(blob);
};
/**
* @see {goog.fs.FileReader#readAsDataUrl}
* @param {!goog.testing.fs.Blob} blob The blob to read.
*/
goog.testing.fs.FileReader.prototype.readAsDataUrl = function(blob) {
this.returnType_ = goog.testing.fs.FileReader.ReturnType.DATA_URL;
this.read_(blob);
};
/**
* Abort the current action and emit appropriate events.
*
* @param {number} total The total data that was to be processed, in bytes.
* @private
*/
goog.testing.fs.FileReader.prototype.abort_ = function(total) {
this.error_ = new goog.fs.Error(
goog.fs.Error.ErrorCode.ABORT, 'reading file');
this.progressEvent_(goog.fs.FileReader.EventType.ERROR, 0, total);
this.progressEvent_(goog.fs.FileReader.EventType.ABORT, 0, total);
this.readyState_ = goog.fs.FileReader.ReadyState.DONE;
this.progressEvent_(goog.fs.FileReader.EventType.LOAD_END, 0, total);
this.aborted_ = false;
};
/**
* Dispatch a progress event.
*
* @param {goog.fs.FileReader.EventType} type The event type.
* @param {number} loaded The number of bytes processed.
* @param {number} total The total data that was to be processed, in bytes.
* @private
*/
goog.testing.fs.FileReader.prototype.progressEvent_ = function(type, loaded,
total) {
this.dispatchEvent(new goog.testing.fs.ProgressEvent(type, loaded, total));
};
| 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 Mock filesystem object.
*
*/
goog.provide('goog.testing.fs.FileSystem');
goog.require('goog.testing.fs.DirectoryEntry');
/**
* A mock filesystem object.
*
* @param {string=} opt_name The name of the filesystem.
* @constructor
*/
goog.testing.fs.FileSystem = function(opt_name) {
/**
* The name of the filesystem.
* @type {string}
* @private
*/
this.name_ = opt_name || 'goog.testing.fs.FileSystem';
/**
* The root entry of the filesystem.
* @type {!goog.testing.fs.DirectoryEntry}
* @private
*/
this.root_ = new goog.testing.fs.DirectoryEntry(this, null, '', {});
};
/**
* @see {goog.fs.FileSystem#getName}
* @return {string}
*/
goog.testing.fs.FileSystem.prototype.getName = function() {
return this.name_;
};
/**
* @see {goog.fs.FileSystem#getRoot}
* @return {!goog.testing.fs.DirectoryEntry}
*/
goog.testing.fs.FileSystem.prototype.getRoot = function() {
return this.root_;
};
| 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 Mock file object.
*
*/
goog.provide('goog.testing.fs.File');
goog.require('goog.testing.fs.Blob');
/**
* A mock file object.
*
* @param {string} name The name of the file.
* @param {Date=} opt_lastModified The last modified date for this file. May be
* null if file modification dates are not supported.
* @param {string=} opt_data The string data encapsulated by the blob.
* @param {string=} opt_type The mime type of the blob.
* @constructor
* @extends {goog.testing.fs.Blob}
*/
goog.testing.fs.File = function(name, opt_lastModified, opt_data, opt_type) {
goog.base(this, opt_data, opt_type);
/**
* @see http://www.w3.org/TR/FileAPI/#dfn-name
* @type {string}
*/
this.name = name;
/**
* @see http://www.w3.org/TR/FileAPI/#dfn-lastModifiedDate
* @type {Date}
*/
this.lastModifiedDate = opt_lastModified || null;
};
goog.inherits(goog.testing.fs.File, goog.testing.fs.Blob);
| 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 Mock FileWriter object.
*
*/
goog.provide('goog.testing.fs.FileWriter');
goog.require('goog.Timer');
goog.require('goog.events.Event');
goog.require('goog.events.EventTarget');
goog.require('goog.fs.Error');
goog.require('goog.fs.FileSaver.EventType');
goog.require('goog.fs.FileSaver.ReadyState');
goog.require('goog.string');
goog.require('goog.testing.fs.File');
goog.require('goog.testing.fs.ProgressEvent');
/**
* A mock FileWriter object. This emits the same events as
* {@link goog.fs.FileSaver} and {@link goog.fs.FileWriter}.
*
* @param {!goog.testing.fs.FileEntry} fileEntry The file entry to write to.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.testing.fs.FileWriter = function(fileEntry) {
goog.base(this);
/**
* The file entry to which to write.
* @type {!goog.testing.fs.FileEntry}
* @private
*/
this.fileEntry_ = fileEntry;
/**
* The file blob to write to.
* @type {!goog.testing.fs.File}
* @private
*/
this.file_ = fileEntry.fileSync();
/**
* The current state of the writer.
* @type {goog.fs.FileSaver.ReadyState}
* @private
*/
this.readyState_ = goog.fs.FileSaver.ReadyState.INIT;
};
goog.inherits(goog.testing.fs.FileWriter, goog.events.EventTarget);
/**
* The most recent error experienced by this writer.
* @type {goog.fs.Error}
* @private
*/
goog.testing.fs.FileWriter.prototype.error_;
/**
* Whether the current operation has been aborted.
* @type {boolean}
* @private
*/
goog.testing.fs.FileWriter.prototype.aborted_ = false;
/**
* The current position in the file.
* @type {number}
* @private
*/
goog.testing.fs.FileWriter.prototype.position_ = 0;
/**
* @see {goog.fs.FileSaver#getReadyState}
* @return {goog.fs.FileSaver.ReadyState} The ready state.
*/
goog.testing.fs.FileWriter.prototype.getReadyState = function() {
return this.readyState_;
};
/**
* @see {goog.fs.FileSaver#getError}
* @return {goog.fs.Error} The error.
*/
goog.testing.fs.FileWriter.prototype.getError = function() {
return this.error_;
};
/**
* @see {goog.fs.FileWriter#getPosition}
* @return {number} The position.
*/
goog.testing.fs.FileWriter.prototype.getPosition = function() {
return this.position_;
};
/**
* @see {goog.fs.FileWriter#getLength}
* @return {number} The length.
*/
goog.testing.fs.FileWriter.prototype.getLength = function() {
return this.file_.size;
};
/**
* @see {goog.fs.FileSaver#abort}
*/
goog.testing.fs.FileWriter.prototype.abort = function() {
if (this.readyState_ != goog.fs.FileSaver.ReadyState.WRITING) {
var msg = 'aborting save of ' + this.fileEntry_.getFullPath();
throw new goog.fs.Error(goog.fs.Error.ErrorCode.INVALID_STATE, msg);
}
this.aborted_ = true;
};
/**
* @see {goog.fs.FileWriter#write}
* @param {!goog.testing.fs.Blob} blob The blob to write.
*/
goog.testing.fs.FileWriter.prototype.write = function(blob) {
if (this.readyState_ == goog.fs.FileSaver.ReadyState.WRITING) {
var msg = 'writing to ' + this.fileEntry_.getFullPath();
throw new goog.fs.Error(goog.fs.Error.ErrorCode.INVALID_STATE, msg);
}
this.readyState_ = goog.fs.FileSaver.ReadyState.WRITING;
goog.Timer.callOnce(function() {
if (this.aborted_) {
this.abort_(blob.size);
return;
}
this.progressEvent_(goog.fs.FileSaver.EventType.WRITE_START, 0, blob.size);
var fileString = this.file_.toString();
this.file_.setDataInternal(
fileString.substring(0, this.position_) + blob.toString() +
fileString.substring(this.position_ + blob.size, fileString.length));
this.position_ += blob.size;
this.progressEvent_(
goog.fs.FileSaver.EventType.WRITE, blob.size, blob.size);
this.readyState_ = goog.fs.FileSaver.ReadyState.DONE;
this.progressEvent_(
goog.fs.FileSaver.EventType.WRITE_END, blob.size, blob.size);
}, 0, this);
};
/**
* @see {goog.fs.FileWriter#truncate}
* @param {number} size The size to truncate to.
*/
goog.testing.fs.FileWriter.prototype.truncate = function(size) {
if (this.readyState_ == goog.fs.FileSaver.ReadyState.WRITING) {
var msg = 'truncating ' + this.fileEntry_.getFullPath();
throw new goog.fs.Error(goog.fs.Error.ErrorCode.INVALID_STATE, msg);
}
this.readyState_ = goog.fs.FileSaver.ReadyState.WRITING;
goog.Timer.callOnce(function() {
if (this.aborted_) {
this.abort_(size);
return;
}
this.progressEvent_(goog.fs.FileSaver.EventType.WRITE_START, 0, size);
var fileString = this.file_.toString();
if (size > fileString.length) {
this.file_.setDataInternal(
fileString + goog.string.repeat('\0', size - fileString.length));
} else {
this.file_.setDataInternal(fileString.substring(0, size));
}
this.position_ = Math.min(this.position_, size);
this.progressEvent_(goog.fs.FileSaver.EventType.WRITE, size, size);
this.readyState_ = goog.fs.FileSaver.ReadyState.DONE;
this.progressEvent_(goog.fs.FileSaver.EventType.WRITE_END, size, size);
}, 0, this);
};
/**
* @see {goog.fs.FileWriter#seek}
* @param {number} offset The offset to seek to.
*/
goog.testing.fs.FileWriter.prototype.seek = function(offset) {
if (this.readyState_ == goog.fs.FileSaver.ReadyState.WRITING) {
var msg = 'truncating ' + this.fileEntry_.getFullPath();
throw new goog.fs.Error(goog.fs.Error.ErrorCode.INVALID_STATE, msg);
}
if (offset < 0) {
this.position_ = Math.max(0, this.file_.size + offset);
} else {
this.position_ = Math.min(offset, this.file_.size);
}
};
/**
* Abort the current action and emit appropriate events.
*
* @param {number} total The total data that was to be processed, in bytes.
* @private
*/
goog.testing.fs.FileWriter.prototype.abort_ = function(total) {
this.error_ = new goog.fs.Error(
goog.fs.Error.ErrorCode.ABORT, 'saving ' + this.fileEntry_.getFullPath());
this.progressEvent_(goog.fs.FileSaver.EventType.ERROR, 0, total);
this.progressEvent_(goog.fs.FileSaver.EventType.ABORT, 0, total);
this.readyState_ = goog.fs.FileSaver.ReadyState.DONE;
this.progressEvent_(goog.fs.FileSaver.EventType.WRITE_END, 0, total);
this.aborted_ = false;
};
/**
* Dispatch a progress event.
*
* @param {goog.fs.FileSaver.EventType} type The type of the event.
* @param {number} loaded The number of bytes processed.
* @param {number} total The total data that was to be processed, in bytes.
* @private
*/
goog.testing.fs.FileWriter.prototype.progressEvent_ = function(
type, loaded, total) {
// On write, update the last modified date to the current (real or mock) time.
if (type == goog.fs.FileSaver.EventType.WRITE) {
this.file_.lastModifiedDate = new Date(goog.now());
}
this.dispatchEvent(new goog.testing.fs.ProgressEvent(type, loaded, total));
};
| 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 An interface that all mocks should share.
* @author nicksantos@google.com (Nick Santos)
*/
goog.provide('goog.testing.MockInterface');
/** @interface */
goog.testing.MockInterface = function() {};
/**
* Write down all the expected functions that have been called on the
* mock so far. From here on out, future function calls will be
* compared against this list.
*/
goog.testing.MockInterface.prototype.$replay = function() {};
/**
* Reset the mock.
*/
goog.testing.MockInterface.prototype.$reset = function() {};
/**
* Assert that the expected function calls match the actual calls.
*/
goog.testing.MockInterface.prototype.$verify = function() {};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Testing utilities for DOM related tests.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.testing.graphics');
goog.require('goog.graphics.Path.Segment');
goog.require('goog.testing.asserts');
/**
* Array mapping numeric segment constant to a descriptive character.
* @type {Array.<string>}
* @private
*/
goog.testing.graphics.SEGMENT_NAMES_ = function() {
var arr = [];
arr[goog.graphics.Path.Segment.MOVETO] = 'M';
arr[goog.graphics.Path.Segment.LINETO] = 'L';
arr[goog.graphics.Path.Segment.CURVETO] = 'C';
arr[goog.graphics.Path.Segment.ARCTO] = 'A';
arr[goog.graphics.Path.Segment.CLOSE] = 'X';
return arr;
}();
/**
* Test if the given path matches the expected array of commands and parameters.
* @param {Array.<string|number>} expected The expected array of commands and
* parameters.
* @param {goog.graphics.Path} path The path to test against.
*/
goog.testing.graphics.assertPathEquals = function(expected, path) {
var actual = [];
path.forEachSegment(function(seg, args) {
actual.push(goog.testing.graphics.SEGMENT_NAMES_[seg]);
Array.prototype.push.apply(actual, args);
});
assertEquals(expected.length, actual.length);
for (var i = 0; i < expected.length; i++) {
if (goog.isNumber(expected[i])) {
assertTrue(goog.isNumber(actual[i]));
assertRoughlyEquals(expected[i], actual[i], 0.01);
} else {
assertEquals(expected[i], actual[i]);
}
}
};
| 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 Event Simulation.
*
* Utility functions for simulating events at the Closure level. All functions
* in this package generate events by calling goog.events.fireListeners,
* rather than interfacing with the browser directly. This is intended for
* testing purposes, and should not be used in production code.
*
* The decision to use Closure events and dispatchers instead of the browser's
* native events and dispatchers was conscious and deliberate. Native event
* dispatchers have their own set of quirks and edge cases. Pure JS dispatchers
* are more robust and transparent.
*
* If you think you need a testing mechanism that uses native Event objects,
* please, please email closure-tech first to explain your use case before you
* sink time into this.
*
* @author nicksantos@google.com (Nick Santos)
*/
goog.provide('goog.testing.events');
goog.provide('goog.testing.events.Event');
goog.require('goog.Disposable');
goog.require('goog.dom.NodeType');
goog.require('goog.events');
goog.require('goog.events.BrowserEvent');
goog.require('goog.events.BrowserFeature');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.events.Listenable');
goog.require('goog.object');
goog.require('goog.style');
goog.require('goog.userAgent');
/**
* goog.events.BrowserEvent expects an Event so we provide one for JSCompiler.
*
* This clones a lot of the functionality of goog.events.Event. This used to
* use a mixin, but the mixin results in confusing the two types when compiled.
*
* @param {string} type Event Type.
* @param {Object=} opt_target Reference to the object that is the target of
* this event.
* @constructor
* @extends {Event}
*/
goog.testing.events.Event = function(type, opt_target) {
this.type = type;
this.target = /** @type {EventTarget} */ (opt_target || null);
this.currentTarget = this.target;
};
/**
* Whether to cancel the event in internal capture/bubble processing for IE.
* @type {boolean}
* @suppress {underscore} Technically public, but referencing this outside
* this package is strongly discouraged.
*/
goog.testing.events.Event.prototype.propagationStopped_ = false;
/** @override */
goog.testing.events.Event.prototype.defaultPrevented = false;
/**
* Return value for in internal capture/bubble processing for IE.
* @type {boolean}
* @suppress {underscore} Technically public, but referencing this outside
* this package is strongly discouraged.
*/
goog.testing.events.Event.prototype.returnValue_ = true;
/** @override */
goog.testing.events.Event.prototype.stopPropagation = function() {
this.propagationStopped_ = true;
};
/** @override */
goog.testing.events.Event.prototype.preventDefault = function() {
this.defaultPrevented = true;
this.returnValue_ = false;
};
/**
* A static helper function that sets the mouse position to the event.
* @param {Event} event A simulated native event.
* @param {goog.math.Coordinate=} opt_coords Mouse position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @private
*/
goog.testing.events.setEventClientXY_ = function(event, opt_coords) {
if (!opt_coords && event.target &&
event.target.nodeType == goog.dom.NodeType.ELEMENT) {
try {
opt_coords =
goog.style.getClientPosition(/** @type {Element} **/ (event.target));
} catch (ex) {
// IE sometimes throws if it can't get the position.
}
}
event.clientX = opt_coords ? opt_coords.x : 0;
event.clientY = opt_coords ? opt_coords.y : 0;
// Pretend the browser window is at (0, 0).
event.screenX = event.clientX;
event.screenY = event.clientY;
};
/**
* Simulates a mousedown, mouseup, and then click on the given event target,
* with the left mouse button.
* @param {EventTarget} target The target for the event.
* @param {goog.events.BrowserEvent.MouseButton=} opt_button Mouse button;
* defaults to {@code goog.events.BrowserEvent.MouseButton.LEFT}.
* @param {goog.math.Coordinate=} opt_coords Mouse position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @param {Object=} opt_eventProperties Event properties to be mixed into the
* BrowserEvent.
* @return {boolean} The returnValue of the sequence: false if preventDefault()
* was called on any of the events, true otherwise.
*/
goog.testing.events.fireClickSequence =
function(target, opt_button, opt_coords, opt_eventProperties) {
// Fire mousedown, mouseup, and click. Then return the bitwise AND of the 3.
return !!(goog.testing.events.fireMouseDownEvent(
target, opt_button, opt_coords, opt_eventProperties) &
goog.testing.events.fireMouseUpEvent(
target, opt_button, opt_coords, opt_eventProperties) &
goog.testing.events.fireClickEvent(
target, opt_button, opt_coords, opt_eventProperties));
};
/**
* Simulates the sequence of events fired by the browser when the user double-
* clicks the given target.
* @param {EventTarget} target The target for the event.
* @param {goog.math.Coordinate=} opt_coords Mouse position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @param {Object=} opt_eventProperties Event properties to be mixed into the
* BrowserEvent.
* @return {boolean} The returnValue of the sequence: false if preventDefault()
* was called on any of the events, true otherwise.
*/
goog.testing.events.fireDoubleClickSequence = function(
target, opt_coords, opt_eventProperties) {
// Fire mousedown, mouseup, click, mousedown, mouseup, click, dblclick.
// Then return the bitwise AND of the 7.
var btn = goog.events.BrowserEvent.MouseButton.LEFT;
return !!(goog.testing.events.fireMouseDownEvent(
target, btn, opt_coords, opt_eventProperties) &
goog.testing.events.fireMouseUpEvent(
target, btn, opt_coords, opt_eventProperties) &
goog.testing.events.fireClickEvent(
target, btn, opt_coords, opt_eventProperties) &
// IE fires a selectstart instead of the second mousedown in a
// dblclick, but we don't care about selectstart.
(goog.userAgent.IE ||
goog.testing.events.fireMouseDownEvent(
target, btn, opt_coords, opt_eventProperties)) &
goog.testing.events.fireMouseUpEvent(
target, btn, opt_coords, opt_eventProperties) &
// IE doesn't fire the second click in a dblclick.
(goog.userAgent.IE ||
goog.testing.events.fireClickEvent(
target, btn, opt_coords, opt_eventProperties)) &
goog.testing.events.fireDoubleClickEvent(
target, opt_coords, opt_eventProperties));
};
/**
* Simulates a complete keystroke (keydown, keypress, and keyup). Note that
* if preventDefault is called on the keydown, the keypress will not fire.
*
* @param {EventTarget} target The target for the event.
* @param {number} keyCode The keycode of the key pressed.
* @param {Object=} opt_eventProperties Event properties to be mixed into the
* BrowserEvent.
* @return {boolean} The returnValue of the sequence: false if preventDefault()
* was called on any of the events, true otherwise.
*/
goog.testing.events.fireKeySequence = function(
target, keyCode, opt_eventProperties) {
return goog.testing.events.fireNonAsciiKeySequence(target, keyCode, keyCode,
opt_eventProperties);
};
/**
* Simulates a complete keystroke (keydown, keypress, and keyup) when typing
* a non-ASCII character. Same as fireKeySequence, the keypress will not fire
* if preventDefault is called on the keydown.
*
* @param {EventTarget} target The target for the event.
* @param {number} keyCode The keycode of the keydown and keyup events.
* @param {number} keyPressKeyCode The keycode of the keypress event.
* @param {Object=} opt_eventProperties Event properties to be mixed into the
* BrowserEvent.
* @return {boolean} The returnValue of the sequence: false if preventDefault()
* was called on any of the events, true otherwise.
*/
goog.testing.events.fireNonAsciiKeySequence = function(
target, keyCode, keyPressKeyCode, opt_eventProperties) {
var keydown =
new goog.testing.events.Event(goog.events.EventType.KEYDOWN, target);
var keyup =
new goog.testing.events.Event(goog.events.EventType.KEYUP, target);
var keypress =
new goog.testing.events.Event(goog.events.EventType.KEYPRESS, target);
keydown.keyCode = keyup.keyCode = keyCode;
keypress.keyCode = keyPressKeyCode;
if (opt_eventProperties) {
goog.object.extend(keydown, opt_eventProperties);
goog.object.extend(keyup, opt_eventProperties);
goog.object.extend(keypress, opt_eventProperties);
}
// Fire keydown, keypress, and keyup. Note that if the keydown is
// prevent-defaulted, then the keypress will not fire on IE.
var result = true;
if (!goog.testing.events.isBrokenGeckoMacActionKey_(keydown)) {
result = goog.testing.events.fireBrowserEvent(keydown);
}
if (goog.events.KeyCodes.firesKeyPressEvent(
keyCode, undefined, keydown.shiftKey, keydown.ctrlKey,
keydown.altKey) &&
!(goog.userAgent.IE && !result)) {
result &= goog.testing.events.fireBrowserEvent(keypress);
}
return !!(result & goog.testing.events.fireBrowserEvent(keyup));
};
/**
* @param {goog.testing.events.Event} e The event.
* @return {boolean} Whether this is the Gecko/Mac's Meta-C/V/X, which
* is broken and requires special handling.
* @private
*/
goog.testing.events.isBrokenGeckoMacActionKey_ = function(e) {
return goog.userAgent.MAC && goog.userAgent.GECKO &&
(e.keyCode == goog.events.KeyCodes.C ||
e.keyCode == goog.events.KeyCodes.X ||
e.keyCode == goog.events.KeyCodes.V) && e.metaKey;
};
/**
* Simulates a mouseover event on the given target.
* @param {EventTarget} target The target for the event.
* @param {EventTarget} relatedTarget The related target for the event (e.g.,
* the node that the mouse is being moved out of).
* @param {goog.math.Coordinate=} opt_coords Mouse position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
*/
goog.testing.events.fireMouseOverEvent = function(target, relatedTarget,
opt_coords) {
var mouseover =
new goog.testing.events.Event(goog.events.EventType.MOUSEOVER, target);
mouseover.relatedTarget = relatedTarget;
goog.testing.events.setEventClientXY_(mouseover, opt_coords);
return goog.testing.events.fireBrowserEvent(mouseover);
};
/**
* Simulates a mousemove event on the given target.
* @param {EventTarget} target The target for the event.
* @param {goog.math.Coordinate=} opt_coords Mouse position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
*/
goog.testing.events.fireMouseMoveEvent = function(target, opt_coords) {
var mousemove =
new goog.testing.events.Event(goog.events.EventType.MOUSEMOVE, target);
goog.testing.events.setEventClientXY_(mousemove, opt_coords);
return goog.testing.events.fireBrowserEvent(mousemove);
};
/**
* Simulates a mouseout event on the given target.
* @param {EventTarget} target The target for the event.
* @param {EventTarget} relatedTarget The related target for the event (e.g.,
* the node that the mouse is being moved into).
* @param {goog.math.Coordinate=} opt_coords Mouse position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
*/
goog.testing.events.fireMouseOutEvent = function(target, relatedTarget,
opt_coords) {
var mouseout =
new goog.testing.events.Event(goog.events.EventType.MOUSEOUT, target);
mouseout.relatedTarget = relatedTarget;
goog.testing.events.setEventClientXY_(mouseout, opt_coords);
return goog.testing.events.fireBrowserEvent(mouseout);
};
/**
* Simulates a mousedown event on the given target.
* @param {EventTarget} target The target for the event.
* @param {goog.events.BrowserEvent.MouseButton=} opt_button Mouse button;
* defaults to {@code goog.events.BrowserEvent.MouseButton.LEFT}.
* @param {goog.math.Coordinate=} opt_coords Mouse position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @param {Object=} opt_eventProperties Event properties to be mixed into the
* BrowserEvent.
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
*/
goog.testing.events.fireMouseDownEvent =
function(target, opt_button, opt_coords, opt_eventProperties) {
var button = opt_button || goog.events.BrowserEvent.MouseButton.LEFT;
button = !goog.events.BrowserFeature.HAS_W3C_BUTTON ?
goog.events.BrowserEvent.IEButtonMap[button] : button;
return goog.testing.events.fireMouseButtonEvent_(
goog.events.EventType.MOUSEDOWN, target, button, opt_coords,
opt_eventProperties);
};
/**
* Simulates a mouseup event on the given target.
* @param {EventTarget} target The target for the event.
* @param {goog.events.BrowserEvent.MouseButton=} opt_button Mouse button;
* defaults to {@code goog.events.BrowserEvent.MouseButton.LEFT}.
* @param {goog.math.Coordinate=} opt_coords Mouse position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @param {Object=} opt_eventProperties Event properties to be mixed into the
* BrowserEvent.
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
*/
goog.testing.events.fireMouseUpEvent =
function(target, opt_button, opt_coords, opt_eventProperties) {
var button = opt_button || goog.events.BrowserEvent.MouseButton.LEFT;
button = !goog.events.BrowserFeature.HAS_W3C_BUTTON ?
goog.events.BrowserEvent.IEButtonMap[button] : button;
return goog.testing.events.fireMouseButtonEvent_(
goog.events.EventType.MOUSEUP, target, button, opt_coords,
opt_eventProperties);
};
/**
* Simulates a click event on the given target. IE only supports click with
* the left mouse button.
* @param {EventTarget} target The target for the event.
* @param {goog.events.BrowserEvent.MouseButton=} opt_button Mouse button;
* defaults to {@code goog.events.BrowserEvent.MouseButton.LEFT}.
* @param {goog.math.Coordinate=} opt_coords Mouse position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @param {Object=} opt_eventProperties Event properties to be mixed into the
* BrowserEvent.
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
*/
goog.testing.events.fireClickEvent =
function(target, opt_button, opt_coords, opt_eventProperties) {
return goog.testing.events.fireMouseButtonEvent_(goog.events.EventType.CLICK,
target, opt_button, opt_coords, opt_eventProperties);
};
/**
* Simulates a double-click event on the given target. Always double-clicks
* with the left mouse button since no browser supports double-clicking with
* any other buttons.
* @param {EventTarget} target The target for the event.
* @param {goog.math.Coordinate=} opt_coords Mouse position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @param {Object=} opt_eventProperties Event properties to be mixed into the
* BrowserEvent.
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
*/
goog.testing.events.fireDoubleClickEvent =
function(target, opt_coords, opt_eventProperties) {
return goog.testing.events.fireMouseButtonEvent_(
goog.events.EventType.DBLCLICK, target,
goog.events.BrowserEvent.MouseButton.LEFT, opt_coords,
opt_eventProperties);
};
/**
* Helper function to fire a mouse event.
* with the left mouse button since no browser supports double-clicking with
* any other buttons.
* @param {string} type The event type.
* @param {EventTarget} target The target for the event.
* @param {number=} opt_button Mouse button; defaults to
* {@code goog.events.BrowserEvent.MouseButton.LEFT}.
* @param {goog.math.Coordinate=} opt_coords Mouse position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @param {Object=} opt_eventProperties Event properties to be mixed into the
* BrowserEvent.
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
* @private
*/
goog.testing.events.fireMouseButtonEvent_ =
function(type, target, opt_button, opt_coords, opt_eventProperties) {
var e =
new goog.testing.events.Event(type, target);
e.button = opt_button || goog.events.BrowserEvent.MouseButton.LEFT;
goog.testing.events.setEventClientXY_(e, opt_coords);
if (opt_eventProperties) {
goog.object.extend(e, opt_eventProperties);
}
return goog.testing.events.fireBrowserEvent(e);
};
/**
* Simulates a contextmenu event on the given target.
* @param {EventTarget} target The target for the event.
* @param {goog.math.Coordinate=} opt_coords Mouse position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
*/
goog.testing.events.fireContextMenuEvent = function(target, opt_coords) {
var button = (goog.userAgent.MAC && goog.userAgent.WEBKIT) ?
goog.events.BrowserEvent.MouseButton.LEFT :
goog.events.BrowserEvent.MouseButton.RIGHT;
var contextmenu =
new goog.testing.events.Event(goog.events.EventType.CONTEXTMENU, target);
contextmenu.button = !goog.events.BrowserFeature.HAS_W3C_BUTTON ?
goog.events.BrowserEvent.IEButtonMap[button] : button;
contextmenu.ctrlKey = goog.userAgent.MAC;
goog.testing.events.setEventClientXY_(contextmenu, opt_coords);
return goog.testing.events.fireBrowserEvent(contextmenu);
};
/**
* Simulates a mousedown, contextmenu, and the mouseup on the given event
* target, with the right mouse button.
* @param {EventTarget} target The target for the event.
* @param {goog.math.Coordinate=} opt_coords Mouse position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @return {boolean} The returnValue of the sequence: false if preventDefault()
* was called on any of the events, true otherwise.
*/
goog.testing.events.fireContextMenuSequence = function(target, opt_coords) {
var props = goog.userAgent.MAC ? {ctrlKey: true} : {};
var button = (goog.userAgent.MAC && goog.userAgent.WEBKIT) ?
goog.events.BrowserEvent.MouseButton.LEFT :
goog.events.BrowserEvent.MouseButton.RIGHT;
var result = goog.testing.events.fireMouseDownEvent(target,
button, opt_coords, props);
if (goog.userAgent.WINDOWS) {
// All browsers are consistent on Windows.
result &= goog.testing.events.fireMouseUpEvent(target,
button, opt_coords) &
goog.testing.events.fireContextMenuEvent(target, opt_coords);
} else {
result &= goog.testing.events.fireContextMenuEvent(target, opt_coords);
// GECKO on Mac and Linux always fires the mouseup after the contextmenu.
// WEBKIT is really weird.
//
// On Linux, it sometimes fires mouseup, but most of the time doesn't.
// It's really hard to reproduce consistently. I think there's some
// internal race condition. If contextmenu is preventDefaulted, then
// mouseup always fires.
//
// On Mac, it always fires mouseup and then fires a click.
result &= goog.testing.events.fireMouseUpEvent(target,
button, opt_coords, props);
if (goog.userAgent.WEBKIT && goog.userAgent.MAC) {
result &= goog.testing.events.fireClickEvent(
target, button, opt_coords, props);
}
}
return !!result;
};
/**
* Simulates a popstate event on the given target.
* @param {EventTarget} target The target for the event.
* @param {Object} state History state object.
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
*/
goog.testing.events.firePopStateEvent = function(target, state) {
var e = new goog.testing.events.Event(goog.events.EventType.POPSTATE, target);
e.state = state;
return goog.testing.events.fireBrowserEvent(e);
};
/**
* Simulate a focus event on the given target.
* @param {EventTarget} target The target for the event.
* @return {boolean} The value returned by firing the focus browser event,
* which returns false iff 'preventDefault' was invoked.
*/
goog.testing.events.fireFocusEvent = function(target) {
var e = new goog.testing.events.Event(
goog.events.EventType.FOCUS, target);
return goog.testing.events.fireBrowserEvent(e);
};
/**
* Simulates an event's capturing and bubbling phases.
* @param {Event} event A simulated native event. It will be wrapped in a
* normalized BrowserEvent and dispatched to Closure listeners on all
* ancestors of its target (inclusive).
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
*/
goog.testing.events.fireBrowserEvent = function(event) {
event.returnValue_ = true;
// generate a list of ancestors
var ancestors = [];
for (var current = event.target; current; current = current.parentNode) {
ancestors.push(current);
}
// dispatch capturing listeners
for (var j = ancestors.length - 1;
j >= 0 && !event.propagationStopped_;
j--) {
goog.events.fireListeners(ancestors[j], event.type, true,
new goog.events.BrowserEvent(event, ancestors[j]));
}
// dispatch bubbling listeners
for (var j = 0;
j < ancestors.length && !event.propagationStopped_;
j++) {
goog.events.fireListeners(ancestors[j], event.type, false,
new goog.events.BrowserEvent(event, ancestors[j]));
}
return event.returnValue_;
};
/**
* Simulates a touchstart event on the given target.
* @param {EventTarget} target The target for the event.
* @param {goog.math.Coordinate=} opt_coords Touch position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @param {Object=} opt_eventProperties Event properties to be mixed into the
* BrowserEvent.
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
*/
goog.testing.events.fireTouchStartEvent = function(
target, opt_coords, opt_eventProperties) {
// TODO: Support multi-touch events with array of coordinates.
var touchstart =
new goog.testing.events.Event(goog.events.EventType.TOUCHSTART, target);
goog.testing.events.setEventClientXY_(touchstart, opt_coords);
return goog.testing.events.fireBrowserEvent(touchstart);
};
/**
* Simulates a touchmove event on the given target.
* @param {EventTarget} target The target for the event.
* @param {goog.math.Coordinate=} opt_coords Touch position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @param {Object=} opt_eventProperties Event properties to be mixed into the
* BrowserEvent.
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
*/
goog.testing.events.fireTouchMoveEvent = function(
target, opt_coords, opt_eventProperties) {
// TODO: Support multi-touch events with array of coordinates.
var touchmove =
new goog.testing.events.Event(goog.events.EventType.TOUCHMOVE, target);
goog.testing.events.setEventClientXY_(touchmove, opt_coords);
return goog.testing.events.fireBrowserEvent(touchmove);
};
/**
* Simulates a touchend event on the given target.
* @param {EventTarget} target The target for the event.
* @param {goog.math.Coordinate=} opt_coords Touch position. Defaults to event's
* target's position (if available), otherwise (0, 0).
* @param {Object=} opt_eventProperties Event properties to be mixed into the
* BrowserEvent.
* @return {boolean} The returnValue of the event: false if preventDefault() was
* called on it, true otherwise.
*/
goog.testing.events.fireTouchEndEvent = function(
target, opt_coords, opt_eventProperties) {
// TODO: Support multi-touch events with array of coordinates.
var touchend =
new goog.testing.events.Event(goog.events.EventType.TOUCHEND, target);
goog.testing.events.setEventClientXY_(touchend, opt_coords);
return goog.testing.events.fireBrowserEvent(touchend);
};
/**
* Simulates a simple touch sequence on the given target.
* @param {EventTarget} target The target for the event.
* @param {goog.math.Coordinate=} opt_coords Touch position. Defaults to event
* target's position (if available), otherwise (0, 0).
* @param {Object=} opt_eventProperties Event properties to be mixed into the
* BrowserEvent.
* @return {boolean} The returnValue of the sequence: false if preventDefault()
* was called on any of the events, true otherwise.
*/
goog.testing.events.fireTouchSequence = function(
target, opt_coords, opt_eventProperties) {
// TODO: Support multi-touch events with array of coordinates.
// Fire touchstart, touchmove, touchend then return the bitwise AND of the 3.
return !!(goog.testing.events.fireTouchStartEvent(
target, opt_coords, opt_eventProperties) &
goog.testing.events.fireTouchEndEvent(
target, opt_coords, opt_eventProperties));
};
/**
* Mixins a listenable into the given object. This turns the object
* into a goog.events.Listenable. This is useful, for example, when
* you need to mock a implementation of listenable and still want it
* to work with goog.events.
* @param {!Object} obj The object to mixin into.
*/
goog.testing.events.mixinListenable = function(obj) {
var listenable = new goog.events.EventTarget();
if (goog.events.Listenable.USE_LISTENABLE_INTERFACE) {
listenable.setTargetForTesting(obj);
var listenablePrototype = goog.events.EventTarget.prototype;
var disposablePrototype = goog.Disposable.prototype;
for (var key in listenablePrototype) {
if (listenablePrototype.hasOwnProperty(key) ||
disposablePrototype.hasOwnProperty(key)) {
var member = listenablePrototype[key];
if (goog.isFunction(member)) {
obj[key] = goog.bind(member, listenable);
} else {
obj[key] = member;
}
}
}
} else {
goog.mixin(obj, listenable);
}
};
| 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 observer.
*
* Provides an event observer that holds onto events that it handles. This
* can be used in unit testing to verify an event target's events --
* that the order count, types, etc. are correct.
*
* Example usage:
* <pre>
* var observer = new goog.testing.events.EventObserver();
* var widget = new foo.Widget();
* goog.events.listen(widget, ['select', 'submit'], observer);
* // Simulate user action of 3 select events and 2 submit events.
* assertEquals(3, observer.getEvents('select').length);
* assertEquals(2, observer.getEvents('submit').length);
* </pre>
*
* @author nnaze@google.com (Nathan Naze)
*/
goog.provide('goog.testing.events.EventObserver');
goog.require('goog.array');
/**
* Event observer. Implements a handleEvent interface so it may be used as
* a listener in listening functions and methods.
* @see goog.events.listen
* @see goog.events.EventHandler
* @constructor
*/
goog.testing.events.EventObserver = function() {
/**
* A list of events handled by the observer in order of handling, oldest to
* newest.
* @type {!Array.<!goog.events.Event>}
* @private
*/
this.events_ = [];
};
/**
* Handles an event and remembers it. Event listening functions and methods
* will call this method when this observer is used as a listener.
* @see goog.events.listen
* @see goog.events.EventHandler
* @param {!goog.events.Event} e Event to handle.
*/
goog.testing.events.EventObserver.prototype.handleEvent = function(e) {
this.events_.push(e);
};
/**
* @param {string=} opt_type If given, only return events of this type.
* @return {!Array.<!goog.events.Event>} The events handled, oldest to newest.
*/
goog.testing.events.EventObserver.prototype.getEvents = function(opt_type) {
var events = goog.array.clone(this.events_);
if (opt_type) {
events = goog.array.filter(events, function(event) {
return event.type == opt_type;
});
}
return events;
};
| 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 Mock matchers for event related arguments.
*/
goog.provide('goog.testing.events.EventMatcher');
goog.require('goog.events.Event');
goog.require('goog.testing.mockmatchers.ArgumentMatcher');
/**
* A matcher that verifies that an argument is a {@code goog.events.Event} of a
* particular type.
* @param {string} type The single type the event argument must be of.
* @constructor
* @extends {goog.testing.mockmatchers.ArgumentMatcher}
*/
goog.testing.events.EventMatcher = function(type) {
goog.testing.mockmatchers.ArgumentMatcher.call(this,
function(obj) {
return obj instanceof goog.events.Event &&
obj.type == type;
}, 'isEventOfType(' + type + ')');
};
goog.inherits(goog.testing.events.EventMatcher,
goog.testing.mockmatchers.ArgumentMatcher);
| 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 NetworkStatusMonitor test double.
* @author dbk@google.com (David Barrett-Kahn)
*/
goog.provide('goog.testing.events.OnlineHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.net.NetworkStatusMonitor');
/**
* NetworkStatusMonitor test double.
* @param {boolean} initialState The initial online state of the mock.
* @constructor
* @extends {goog.net.NetworkStatusMonitor}
*/
goog.testing.events.OnlineHandler = function(initialState) {
goog.base(this);
/**
* Whether the mock is online.
* @type {boolean}
* @private
*/
this.online_ = initialState;
};
goog.inherits(goog.testing.events.OnlineHandler, goog.net.NetworkStatusMonitor);
/** @override */
goog.testing.events.OnlineHandler.prototype.isOnline = function() {
return this.online_;
};
/**
* Sets the online state.
* @param {boolean} newOnlineState The new online state.
*/
goog.testing.events.OnlineHandler.prototype.setOnline =
function(newOnlineState) {
if (newOnlineState != this.online_) {
this.online_ = newOnlineState;
this.dispatchEvent(newOnlineState ?
goog.net.NetworkStatusMonitor.EventType.ONLINE :
goog.net.NetworkStatusMonitor.EventType.OFFLINE);
}
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file defines a factory that can be used to mock and
* replace an entire class. This allows for mocks to be used effectively with
* "new" instead of having to inject all instances. Essentially, a given class
* is replaced with a proxy to either a loose or strict mock. Proxies locate
* the appropriate mock based on constructor arguments.
*
* The usage is:
* <ul>
* <li>Create a mock with one of the provided methods with a specifc set of
* constructor arguments
* <li>Set expectations by calling methods on the mock object
* <li>Call $replay() on the mock object
* <li>Instantiate the object as normal
* <li>Call $verify() to make sure that expectations were met
* <li>Call reset on the factory to revert all classes back to their original
* state
* </ul>
*
* For examples, please see the unit test.
*
*/
goog.provide('goog.testing.MockClassFactory');
goog.provide('goog.testing.MockClassRecord');
goog.require('goog.array');
goog.require('goog.object');
goog.require('goog.testing.LooseMock');
goog.require('goog.testing.StrictMock');
goog.require('goog.testing.TestCase');
goog.require('goog.testing.mockmatchers');
/**
* A record that represents all the data associated with a mock replacement of
* a given class.
* @param {Object} namespace The namespace in which the mocked class resides.
* @param {string} className The name of the class within the namespace.
* @param {Function} originalClass The original class implementation before it
* was replaced by a proxy.
* @param {Function} proxy The proxy that replaced the original class.
* @constructor
*/
goog.testing.MockClassRecord = function(namespace, className, originalClass,
proxy) {
/**
* A standard closure namespace (e.g. goog.foo.bar) that contains the mock
* class referenced by this MockClassRecord.
* @type {Object}
* @private
*/
this.namespace_ = namespace;
/**
* The name of the class within the provided namespace.
* @type {string}
* @private
*/
this.className_ = className;
/**
* The original class implementation.
* @type {Function}
* @private
*/
this.originalClass_ = originalClass;
/**
* The proxy being used as a replacement for the original class.
* @type {Function}
* @private
*/
this.proxy_ = proxy;
/**
* A mocks that will be constructed by their argument list. The entries are
* objects with the format {'args': args, 'mock': mock}.
* @type {Array.<Object>}
* @private
*/
this.instancesByArgs_ = [];
};
/**
* A mock associated with the static functions for a given class.
* @type {goog.testing.StrictMock|goog.testing.LooseMock|null}
* @private
*/
goog.testing.MockClassRecord.prototype.staticMock_ = null;
/**
* A getter for this record's namespace.
* @return {Object} The namespace.
*/
goog.testing.MockClassRecord.prototype.getNamespace = function() {
return this.namespace_;
};
/**
* A getter for this record's class name.
* @return {string} The name of the class referenced by this record.
*/
goog.testing.MockClassRecord.prototype.getClassName = function() {
return this.className_;
};
/**
* A getter for the original class.
* @return {Function} The original class implementation before mocking.
*/
goog.testing.MockClassRecord.prototype.getOriginalClass = function() {
return this.originalClass_;
};
/**
* A getter for the proxy being used as a replacement for the original class.
* @return {Function} The proxy.
*/
goog.testing.MockClassRecord.prototype.getProxy = function() {
return this.proxy_;
};
/**
* A getter for the static mock.
* @return {goog.testing.StrictMock|goog.testing.LooseMock|null} The static
* mock associated with this record.
*/
goog.testing.MockClassRecord.prototype.getStaticMock = function() {
return this.staticMock_;
};
/**
* A setter for the static mock.
* @param {goog.testing.StrictMock|goog.testing.LooseMock} staticMock A mock to
* associate with the static functions for the referenced class.
*/
goog.testing.MockClassRecord.prototype.setStaticMock = function(staticMock) {
this.staticMock_ = staticMock;
};
/**
* Adds a new mock instance mapping. The mapping connects a set of function
* arguments to a specific mock instance.
* @param {Array} args An array of function arguments.
* @param {goog.testing.StrictMock|goog.testing.LooseMock} mock A mock
* associated with the supplied arguments.
*/
goog.testing.MockClassRecord.prototype.addMockInstance = function(args, mock) {
this.instancesByArgs_.push({args: args, mock: mock});
};
/**
* Finds the mock corresponding to a given argument set. Throws an error if
* there is no appropriate match found.
* @param {Array} args An array of function arguments.
* @return {goog.testing.StrictMock|goog.testing.LooseMock|null} The mock
* corresponding to a given argument set.
*/
goog.testing.MockClassRecord.prototype.findMockInstance = function(args) {
for (var i = 0; i < this.instancesByArgs_.length; i++) {
var instanceArgs = this.instancesByArgs_[i].args;
if (goog.testing.mockmatchers.flexibleArrayMatcher(instanceArgs, args)) {
return this.instancesByArgs_[i].mock;
}
}
return null;
};
/**
* Resets this record by reverting all the mocked classes back to the original
* implementation and clearing out the mock instance list.
*/
goog.testing.MockClassRecord.prototype.reset = function() {
this.namespace_[this.className_] = this.originalClass_;
this.instancesByArgs_ = [];
};
/**
* A factory used to create new mock class instances. It is able to generate
* both static and loose mocks. The MockClassFactory is a singleton since it
* tracks the classes that have been mocked internally.
* @constructor
*/
goog.testing.MockClassFactory = function() {
if (goog.testing.MockClassFactory.instance_) {
return goog.testing.MockClassFactory.instance_;
}
/**
* A map from class name -> goog.testing.MockClassRecord.
* @type {Object}
* @private
*/
this.mockClassRecords_ = {};
goog.testing.MockClassFactory.instance_ = this;
};
/**
* A singleton instance of the MockClassFactory.
* @type {goog.testing.MockClassFactory?}
* @private
*/
goog.testing.MockClassFactory.instance_ = null;
/**
* The names of the fields that are defined on Object.prototype.
* @type {Array.<string>}
* @private
*/
goog.testing.MockClassFactory.PROTOTYPE_FIELDS_ = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
/**
* Iterates through a namespace to find the name of a given class. This is done
* solely to support compilation since string identifiers would break down.
* Tests usually aren't compiled, but the functionality is supported.
* @param {Object} namespace A javascript namespace (e.g. goog.testing).
* @param {Function} classToMock The class whose name should be returned.
* @return {string} The name of the class.
* @private
*/
goog.testing.MockClassFactory.prototype.getClassName_ = function(namespace,
classToMock) {
if (namespace === goog.global) {
namespace = goog.testing.TestCase.getGlobals();
}
for (var prop in namespace) {
if (namespace[prop] === classToMock) {
return prop;
}
}
throw Error('Class is not a part of the given namespace');
};
/**
* Returns whether or not a given class has been mocked.
* @param {string} className The name of the class.
* @return {boolean} Whether or not the given class name has a MockClassRecord.
* @private
*/
goog.testing.MockClassFactory.prototype.classHasMock_ = function(className) {
return !!this.mockClassRecords_[className];
};
/**
* Returns a proxy constructor closure. Since this is a constructor, "this"
* refers to the local scope of the constructed object thus bind cannot be
* used.
* @param {string} className The name of the class.
* @param {Function} mockFinder A bound function that returns the mock
* associated with a class given the constructor's argument list.
* @return {Function} A proxy constructor.
* @private
*/
goog.testing.MockClassFactory.prototype.getProxyCtor_ = function(className,
mockFinder) {
return function() {
this.$mock_ = mockFinder(className, arguments);
if (!this.$mock_) {
// The "arguments" variable is not a proper Array so it must be converted.
var args = Array.prototype.slice.call(arguments, 0);
throw Error('No mock found for ' + className + ' with arguments ' +
args.join(', '));
}
};
};
/**
* Returns a proxy function for a mock class instance. This function cannot
* be used with bind since "this" must refer to the scope of the proxy
* constructor.
* @param {string} fnName The name of the function that should be proxied.
* @return {Function} A proxy function.
* @private
*/
goog.testing.MockClassFactory.prototype.getProxyFunction_ = function(fnName) {
return function() {
return this.$mock_[fnName].apply(this.$mock_, arguments);
};
};
/**
* Find a mock instance for a given class name and argument list.
* @param {string} className The name of the class.
* @param {Array} args The argument list to match.
* @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock found for
* the given argument list.
* @private
*/
goog.testing.MockClassFactory.prototype.findMockInstance_ = function(className,
args) {
return this.mockClassRecords_[className].findMockInstance(args);
};
/**
* Create a proxy class. A proxy will pass functions to the mock for a class.
* The proxy class only covers prototype methods. A static mock is not build
* simultaneously since it might be strict or loose. The proxy class inherits
* from the target class in order to preserve instanceof checks.
* @param {Object} namespace A javascript namespace (e.g. goog.testing).
* @param {Function} classToMock The class that will be proxied.
* @param {string} className The name of the class.
* @return {Function} The proxy for provided class.
* @private
*/
goog.testing.MockClassFactory.prototype.createProxy_ = function(namespace,
classToMock, className) {
var proxy = this.getProxyCtor_(className,
goog.bind(this.findMockInstance_, this));
var protoToProxy = classToMock.prototype;
goog.inherits(proxy, classToMock);
for (var prop in protoToProxy) {
if (goog.isFunction(protoToProxy[prop])) {
proxy.prototype[prop] = this.getProxyFunction_(prop);
}
}
// For IE the for-in-loop does not contain any properties that are not
// enumerable on the prototype object (for example isPrototypeOf from
// Object.prototype) and it will also not include 'replace' on objects that
// extend String and change 'replace' (not that it is common for anyone to
// extend anything except Object).
// TODO (arv): Implement goog.object.getIterator and replace this loop.
goog.array.forEach(goog.testing.MockClassFactory.PROTOTYPE_FIELDS_,
function(field) {
if (Object.prototype.hasOwnProperty.call(protoToProxy, field)) {
proxy.prototype[field] = this.getProxyFunction_(field);
}
}, this);
this.mockClassRecords_[className] = new goog.testing.MockClassRecord(
namespace, className, classToMock, proxy);
namespace[className] = proxy;
return proxy;
};
/**
* Gets either a loose or strict mock for a given class based on a set of
* arguments.
* @param {Object} namespace A javascript namespace (e.g. goog.testing).
* @param {Function} classToMock The class that will be mocked.
* @param {boolean} isStrict Whether or not the mock should be strict.
* @param {goog.array.ArrayLike} ctorArgs The arguments associated with this
* instance's constructor.
* @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock created
* for the provided class.
* @private
*/
goog.testing.MockClassFactory.prototype.getMockClass_ =
function(namespace, classToMock, isStrict, ctorArgs) {
var className = this.getClassName_(namespace, classToMock);
// The namespace and classToMock variables should be removed from the
// passed in argument stack.
ctorArgs = goog.array.slice(ctorArgs, 2);
if (goog.isFunction(classToMock)) {
var mock = isStrict ? new goog.testing.StrictMock(classToMock) :
new goog.testing.LooseMock(classToMock);
if (!this.classHasMock_(className)) {
this.createProxy_(namespace, classToMock, className);
} else {
var instance = this.findMockInstance_(className, ctorArgs);
if (instance) {
throw Error('Mock instance already created for ' + className +
' with arguments ' + ctorArgs.join(', '));
}
}
this.mockClassRecords_[className].addMockInstance(ctorArgs, mock);
return mock;
} else {
throw Error('Cannot create a mock class for ' + className +
' of type ' + typeof classToMock);
}
};
/**
* Gets a strict mock for a given class.
* @param {Object} namespace A javascript namespace (e.g. goog.testing).
* @param {Function} classToMock The class that will be mocked.
* @param {...*} var_args The arguments associated with this instance's
* constructor.
* @return {goog.testing.StrictMock} The mock created for the provided class.
*/
goog.testing.MockClassFactory.prototype.getStrictMockClass =
function(namespace, classToMock, var_args) {
return /** @type {goog.testing.StrictMock} */ (this.getMockClass_(namespace,
classToMock, true, arguments));
};
/**
* Gets a loose mock for a given class.
* @param {Object} namespace A javascript namespace (e.g. goog.testing).
* @param {Function} classToMock The class that will be mocked.
* @param {...*} var_args The arguments associated with this instance's
* constructor.
* @return {goog.testing.LooseMock} The mock created for the provided class.
*/
goog.testing.MockClassFactory.prototype.getLooseMockClass =
function(namespace, classToMock, var_args) {
return /** @type {goog.testing.LooseMock} */ (this.getMockClass_(namespace,
classToMock, false, arguments));
};
/**
* Creates either a loose or strict mock for the static functions of a given
* class.
* @param {Function} classToMock The class whose static functions will be
* mocked. This should be the original class and not the proxy.
* @param {string} className The name of the class.
* @param {Function} proxy The proxy that will replace the original class.
* @param {boolean} isStrict Whether or not the mock should be strict.
* @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock created
* for the static functions of the provided class.
* @private
*/
goog.testing.MockClassFactory.prototype.createStaticMock_ =
function(classToMock, className, proxy, isStrict) {
var mock = isStrict ? new goog.testing.StrictMock(classToMock, true) :
new goog.testing.LooseMock(classToMock, false, true);
for (var prop in classToMock) {
if (goog.isFunction(classToMock[prop])) {
proxy[prop] = goog.bind(mock.$mockMethod, mock, prop);
} else if (classToMock[prop] !== classToMock.prototype) {
proxy[prop] = classToMock[prop];
}
}
this.mockClassRecords_[className].setStaticMock(mock);
return mock;
};
/**
* Gets either a loose or strict mock for the static functions of a given class.
* @param {Object} namespace A javascript namespace (e.g. goog.testing).
* @param {Function} classToMock The class whose static functions will be
* mocked. This should be the original class and not the proxy.
* @param {boolean} isStrict Whether or not the mock should be strict.
* @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock created
* for the static functions of the provided class.
* @private
*/
goog.testing.MockClassFactory.prototype.getStaticMock_ = function(namespace,
classToMock, isStrict) {
var className = this.getClassName_(namespace, classToMock);
if (goog.isFunction(classToMock)) {
if (!this.classHasMock_(className)) {
var proxy = this.createProxy_(namespace, classToMock, className);
var mock = this.createStaticMock_(classToMock, className, proxy,
isStrict);
return mock;
}
if (!this.mockClassRecords_[className].getStaticMock()) {
var proxy = this.mockClassRecords_[className].getProxy();
var originalClass = this.mockClassRecords_[className].getOriginalClass();
var mock = this.createStaticMock_(originalClass, className, proxy,
isStrict);
return mock;
} else {
var mock = this.mockClassRecords_[className].getStaticMock();
var mockIsStrict = mock instanceof goog.testing.StrictMock;
if (mockIsStrict != isStrict) {
var mockType = mock instanceof goog.testing.StrictMock ? 'strict' :
'loose';
var requestedType = isStrict ? 'strict' : 'loose';
throw Error('Requested a ' + requestedType + ' static mock, but a ' +
mockType + ' mock already exists.');
}
return mock;
}
} else {
throw Error('Cannot create a mock for the static functions of ' +
className + ' of type ' + typeof classToMock);
}
};
/**
* Gets a strict mock for the static functions of a given class.
* @param {Object} namespace A javascript namespace (e.g. goog.testing).
* @param {Function} classToMock The class whose static functions will be
* mocked. This should be the original class and not the proxy.
* @return {goog.testing.StrictMock} The mock created for the static functions
* of the provided class.
*/
goog.testing.MockClassFactory.prototype.getStrictStaticMock =
function(namespace, classToMock) {
return /** @type {goog.testing.StrictMock} */ (this.getStaticMock_(namespace,
classToMock, true));
};
/**
* Gets a loose mock for the static functions of a given class.
* @param {Object} namespace A javascript namespace (e.g. goog.testing).
* @param {Function} classToMock The class whose static functions will be
* mocked. This should be the original class and not the proxy.
* @return {goog.testing.LooseMock} The mock created for the static functions
* of the provided class.
*/
goog.testing.MockClassFactory.prototype.getLooseStaticMock =
function(namespace, classToMock) {
return /** @type {goog.testing.LooseMock} */ (this.getStaticMock_(namespace,
classToMock, false));
};
/**
* Resests the factory by reverting all mocked classes to their original
* implementations and removing all MockClassRecords.
*/
goog.testing.MockClassFactory.prototype.reset = function() {
goog.object.forEach(this.mockClassRecords_, function(record) {
record.reset();
});
this.mockClassRecords_ = {};
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview An XhrIo pool that uses a single mock XHR object for testing.
*
*/
goog.provide('goog.testing.net.XhrIoPool');
goog.require('goog.net.XhrIoPool');
goog.require('goog.testing.net.XhrIo');
/**
* A pool containing a single mock XhrIo object.
*
* @param {goog.testing.net.XhrIo=} opt_xhr The mock XhrIo object.
* @constructor
* @extends {goog.net.XhrIoPool}
*/
goog.testing.net.XhrIoPool = function(opt_xhr) {
/**
* The mock XhrIo object.
* @type {!goog.testing.net.XhrIo}
* @private
*/
this.xhr_ = opt_xhr || new goog.testing.net.XhrIo();
// Run this after setting xhr_ because xhr_ is used to initialize the pool.
goog.base(this, undefined, 1, 1);
};
goog.inherits(goog.testing.net.XhrIoPool, goog.net.XhrIoPool);
/**
* @override
* @suppress {invalidCasts}
*/
goog.testing.net.XhrIoPool.prototype.createObject = function() {
return (/** @type {!goog.net.XhrIo} */ (this.xhr_));
};
/**
* Get the mock XhrIo used by this pool.
*
* @return {!goog.testing.net.XhrIo} The mock XhrIo.
*/
goog.testing.net.XhrIoPool.prototype.getXhr = function() {
return this.xhr_;
};
| 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 XhrIo for unit testing.
*/
goog.provide('goog.testing.net.XhrIo');
goog.require('goog.array');
goog.require('goog.dom.xml');
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.XhrIo');
goog.require('goog.net.XmlHttp');
goog.require('goog.object');
goog.require('goog.structs.Map');
/**
* Mock implementation of goog.net.XhrIo. 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.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.testing.net.XhrIo = function(opt_testQueue) {
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();
/**
* Queue of events write to.
* @type {goog.testing.TestQueue?}
* @private
*/
this.testQueue_ = opt_testQueue || null;
};
goog.inherits(goog.testing.net.XhrIo, goog.events.EventTarget);
/**
* Alias this enum here to make mocking of goog.net.XhrIo easier.
* @enum {string}
*/
goog.testing.net.XhrIo.ResponseType = goog.net.XhrIo.ResponseType;
/**
* All non-disposed instances of goog.testing.net.XhrIo created
* by {@link goog.testing.net.XhrIo.send} are in this Array.
* @see goog.testing.net.XhrIo.cleanup
* @type {Array.<goog.testing.net.XhrIo>}
* @private
*/
goog.testing.net.XhrIo.sendInstances_ = [];
/**
* Returns an Array containing all non-disposed instances of
* goog.testing.net.XhrIo created by {@link goog.testing.net.XhrIo.send}.
* @return {Array} Array of goog.testing.net.XhrIo instances.
*/
goog.testing.net.XhrIo.getSendInstances = function() {
return goog.testing.net.XhrIo.sendInstances_;
};
/**
* Disposes all non-disposed instances of goog.testing.net.XhrIo created by
* {@link goog.testing.net.XhrIo.send}.
* @see goog.net.XhrIo.cleanup
*/
goog.testing.net.XhrIo.cleanup = function() {
var instances = goog.testing.net.XhrIo.sendInstances_;
while (instances.length) {
instances.pop().dispose();
}
};
/**
* Simulates the static XhrIo send method.
* @param {string} 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 {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.testing.net.XhrIo.send = function(url, opt_callback, opt_method,
opt_content, opt_headers,
opt_timeoutInterval) {
var x = new goog.testing.net.XhrIo();
goog.testing.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.testing.net.XhrIo.cleanupSend_, x));
if (opt_timeoutInterval) {
x.setTimeoutInterval(opt_timeoutInterval);
}
x.send(url, opt_method, opt_content, opt_headers);
};
/**
* Disposes of the specified goog.testing.net.XhrIo created by
* {@link goog.testing.net.XhrIo.send} and removes it from
* {@link goog.testing.net.XhrIo.pendingStaticSendInstances_}.
* @param {goog.testing.net.XhrIo} XhrIo An XhrIo created by
* {@link goog.testing.net.XhrIo.send}.
* @private
*/
goog.testing.net.XhrIo.cleanupSend_ = function(XhrIo) {
XhrIo.dispose();
goog.array.remove(goog.testing.net.XhrIo.sendInstances_, XhrIo);
};
/**
* Stores the simulated response headers for the requests which are sent through
* this XhrIo.
* @type {Object}
* @private
*/
goog.testing.net.XhrIo.prototype.responseHeaders_;
/**
* Whether MockXhrIo is active.
* @type {boolean}
* @private
*/
goog.testing.net.XhrIo.prototype.active_ = false;
/**
* Last URI that was requested.
* @type {string}
* @private
*/
goog.testing.net.XhrIo.prototype.lastUri_ = '';
/**
* Last HTTP method that was requested.
* @type {string|undefined}
* @private
*/
goog.testing.net.XhrIo.prototype.lastMethod_;
/**
* Last POST content that was requested.
* @type {string|undefined}
* @private
*/
goog.testing.net.XhrIo.prototype.lastContent_;
/**
* Additional headers that were requested in the last query.
* @type {Object|goog.structs.Map|undefined}
* @private
*/
goog.testing.net.XhrIo.prototype.lastHeaders_;
/**
* Last error code.
* @type {goog.net.ErrorCode}
* @private
*/
goog.testing.net.XhrIo.prototype.lastErrorCode_ =
goog.net.ErrorCode.NO_ERROR;
/**
* Last error message.
* @type {string}
* @private
*/
goog.testing.net.XhrIo.prototype.lastError_ = '';
/**
* The response object.
* @type {string|Document}
* @private
*/
goog.testing.net.XhrIo.prototype.response_ = '';
/**
* Mock ready state.
* @type {number}
* @private
*/
goog.testing.net.XhrIo.prototype.readyState_ =
goog.net.XmlHttp.ReadyState.UNINITIALIZED;
/**
* 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.testing.net.XhrIo.prototype.timeoutInterval_ = 0;
/**
* Window timeout ID used to cancel the timeout event handler if the request
* completes successfully.
* @type {Object}
* @private
*/
goog.testing.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.testing.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://dev.w3.org/2006/webapi/XMLHttpRequest-2/#withcredentials
*
* @type {boolean}
* @private
*/
goog.testing.net.XhrIo.prototype.withCredentials_ = false;
/**
* Whether there's currently an underlying XHR object.
* @type {boolean}
* @private
*/
goog.testing.net.XhrIo.prototype.xhr_ = 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.testing.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.testing.net.XhrIo.prototype.setTimeoutInterval = function(ms) {
this.timeoutInterval_ = Math.max(0, ms);
};
/**
* Causes timeout events to be fired.
*/
goog.testing.net.XhrIo.prototype.simulateTimeout = function() {
this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;
this.dispatchEvent(goog.net.EventType.TIMEOUT);
this.abort(goog.net.ErrorCode.TIMEOUT);
};
/**
* 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.testing.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.testing.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.testing.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.testing.net.XhrIo.prototype.getWithCredentials = function() {
return this.withCredentials_;
};
/**
* Abort the current XMLHttpRequest
* @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -
* defaults to ABORT.
*/
goog.testing.net.XhrIo.prototype.abort = function(opt_failureCode) {
if (this.active_) {
try {
this.active_ = false;
this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.ABORT);
} finally {
this.simulateReady();
}
}
};
/**
* Simulates the XhrIo send.
* @param {string} url Uri to make request too.
* @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.
*/
goog.testing.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_ = url;
this.lastMethod_ = opt_method || 'GET';
this.lastContent_ = opt_content;
this.lastHeaders_ = opt_headers;
if (this.testQueue_) {
this.testQueue_.enqueue(['s', url, opt_method, opt_content, opt_headers]);
}
this.xhr_ = true;
this.active_ = true;
this.readyState_ = goog.net.XmlHttp.ReadyState.UNINITIALIZED;
this.simulateReadyStateChange(goog.net.XmlHttp.ReadyState.LOADING);
};
/**
* Creates a new XHR object.
* @return {XMLHttpRequest|GearsHttpRequest} The newly created XHR object.
* @protected
*/
goog.testing.net.XhrIo.prototype.createXhr = function() {
return goog.net.XmlHttp();
};
/**
* Simulates changing to the new ready state.
* @param {number} readyState Ready state to change to.
*/
goog.testing.net.XhrIo.prototype.simulateReadyStateChange =
function(readyState) {
if (readyState < this.readyState_) {
throw Error('Readystate cannot go backwards');
}
// INTERACTIVE can be dispatched repeatedly as more data is reported.
if (readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE &&
readyState == this.readyState_) {
this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);
return;
}
while (this.readyState_ < readyState) {
this.readyState_++;
this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);
if (this.readyState_ == goog.net.XmlHttp.ReadyState.COMPLETE) {
this.active_ = false;
this.dispatchEvent(goog.net.EventType.COMPLETE);
}
}
};
/**
* Simulate receiving some bytes but the request not fully completing, and
* the XHR entering the 'INTERACTIVE' state.
* @param {string} partialResponse A string to append to the response text.
* @param {Object=} opt_headers Simulated response headers.
*/
goog.testing.net.XhrIo.prototype.simulatePartialResponse =
function(partialResponse, opt_headers) {
this.response_ += partialResponse;
this.responseHeaders_ = opt_headers || {};
this.statusCode_ = 200;
this.simulateReadyStateChange(goog.net.XmlHttp.ReadyState.INTERACTIVE);
};
/**
* Simulates receiving a response.
* @param {number} statusCode Simulated status code.
* @param {string|Document|null} response Simulated response.
* @param {Object=} opt_headers Simulated response headers.
*/
goog.testing.net.XhrIo.prototype.simulateResponse = function(statusCode,
response, opt_headers) {
this.statusCode_ = statusCode;
this.response_ = response || '';
this.responseHeaders_ = opt_headers || {};
try {
if (this.isSuccess()) {
this.simulateReadyStateChange(goog.net.XmlHttp.ReadyState.COMPLETE);
this.dispatchEvent(goog.net.EventType.SUCCESS);
} else {
this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;
this.lastError_ = this.getStatusText() + ' [' + this.getStatus() + ']';
this.simulateReadyStateChange(goog.net.XmlHttp.ReadyState.COMPLETE);
this.dispatchEvent(goog.net.EventType.ERROR);
}
} finally {
this.simulateReady();
}
};
/**
* Simulates the Xhr is ready for the next request.
*/
goog.testing.net.XhrIo.prototype.simulateReady = function() {
this.active_ = false;
this.xhr_ = false;
this.dispatchEvent(goog.net.EventType.READY);
};
/**
* @return {boolean} Whether there is an active request.
*/
goog.testing.net.XhrIo.prototype.isActive = function() {
return !!this.xhr_;
};
/**
* Has the request completed.
* @return {boolean} Whether the request has completed.
*/
goog.testing.net.XhrIo.prototype.isComplete = function() {
return this.readyState_ == goog.net.XmlHttp.ReadyState.COMPLETE;
};
/**
* Has the request compeleted with a success.
* @return {boolean} Whether the request compeleted successfully.
*/
goog.testing.net.XhrIo.prototype.isSuccess = function() {
switch (this.getStatus()) {
case goog.net.HttpStatus.OK:
case goog.net.HttpStatus.NO_CONTENT:
case goog.net.HttpStatus.NOT_MODIFIED:
return true;
default:
return false;
}
};
/**
* Returns the readystate.
* @return {number} goog.net.XmlHttp.ReadyState.*.
*/
goog.testing.net.XhrIo.prototype.getReadyState = function() {
return this.readyState_;
};
/**
* 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.testing.net.XhrIo.prototype.getStatus = function() {
return this.statusCode_;
};
/**
* 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.testing.net.XhrIo.prototype.getStatusText = function() {
return '';
};
/**
* Gets the last error message.
* @return {goog.net.ErrorCode} Last error code.
*/
goog.testing.net.XhrIo.prototype.getLastErrorCode = function() {
return this.lastErrorCode_;
};
/**
* Gets the last error message.
* @return {string} Last error message.
*/
goog.testing.net.XhrIo.prototype.getLastError = function() {
return this.lastError_;
};
/**
* Gets the last URI that was requested.
* @return {string} Last URI.
*/
goog.testing.net.XhrIo.prototype.getLastUri = function() {
return this.lastUri_;
};
/**
* Gets the last HTTP method that was requested.
* @return {string|undefined} Last HTTP method used by send.
*/
goog.testing.net.XhrIo.prototype.getLastMethod = function() {
return this.lastMethod_;
};
/**
* Gets the last POST content that was requested.
* @return {string|undefined} Last POST content or undefined if last request was
* a GET.
*/
goog.testing.net.XhrIo.prototype.getLastContent = function() {
return this.lastContent_;
};
/**
* Gets the headers of the last request.
* @return {Object|goog.structs.Map|undefined} Last headers manually set in send
* call or undefined if no additional headers were specified.
*/
goog.testing.net.XhrIo.prototype.getLastRequestHeaders = function() {
return this.lastHeaders_;
};
/**
* Gets 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.
*/
goog.testing.net.XhrIo.prototype.getResponseText = function() {
return goog.isString(this.response_) ? this.response_ :
goog.dom.xml.serialize(this.response_);
};
/**
* Gets the response body from the Xhr object. Will only return correct result
* when called from the context of a callback.
* @return {Object} Binary result from the server or null.
*/
goog.testing.net.XhrIo.prototype.getResponseBody = function() {
return null;
};
/**
* Gets 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} JavaScript object.
*/
goog.testing.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {
var responseText = this.getResponseText();
if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {
responseText = responseText.substring(opt_xssiPrefix.length);
}
return goog.json.parse(responseText);
};
/**
* Gets the response XML from the Xhr object. Will only return correct result
* when called from the context of a callback.
* @return {Document} Result from the server if it was XML.
*/
goog.testing.net.XhrIo.prototype.getResponseXml = function() {
// NOTE(user): I haven't found out how to check in Internet Explorer
// whether the response is XML document, so I do it the other way around.
return goog.isString(this.response_) ? null : this.response_;
};
/**
* Get the response as the type specificed by {@link #setResponseType}. At time
* of writing, this is only supported in very recent versions of WebKit
* (10.0.612.1 dev and later).
*
* @return {*} The response.
*/
goog.testing.net.XhrIo.prototype.getResponse = function() {
return this.response_;
};
/**
* 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.testing.net.XhrIo.prototype.getResponseHeader = function(key) {
return this.isComplete() ? this.responseHeaders_[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 string containing all the response headers.
*/
goog.testing.net.XhrIo.prototype.getAllResponseHeaders = function() {
if (!this.isComplete()) {
return '';
}
var headers = [];
goog.object.forEach(this.responseHeaders_, function(value, name) {
headers.push(name + ': ' + value);
});
return headers.join('\n');
};
| 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 for creating stubs for testing.
*
*/
goog.provide('goog.testing.PropertyReplacer');
goog.require('goog.userAgent');
/**
* Helper class for stubbing out variables and object properties for unit tests.
* This class can change the value of some variables before running the test
* cases, and to reset them in the tearDown phase.
* See googletest.StubOutForTesting as an analogy in Python:
* http://protobuf.googlecode.com/svn/trunk/python/stubout.py
*
* Example usage:
* <pre>var stubs = new goog.testing.PropertyReplacer();
*
* function setUp() {
* // Mock functions used in all test cases.
* stubs.set(Math, 'random', function() {
* return 4; // Chosen by fair dice roll. Guaranteed to be random.
* });
* }
*
* function tearDown() {
* stubs.reset();
* }
*
* function testThreeDice() {
* // Mock a constant used only in this test case.
* stubs.set(goog.global, 'DICE_COUNT', 3);
* assertEquals(12, rollAllDice());
* }</pre>
*
* Constraints on altered objects:
* <ul>
* <li>DOM subclasses aren't supported.
* <li>The value of the objects' constructor property must either be equal to
* the real constructor or kept untouched.
* </ul>
*
* @constructor
*/
goog.testing.PropertyReplacer = function() {
/**
* Stores the values changed by the set() method in chronological order.
* Its items are objects with 3 fields: 'object', 'key', 'value'. The
* original value for the given key in the given object is stored under the
* 'value' key.
* @type {Array.<Object>}
* @private
*/
this.original_ = [];
};
/**
* Indicates that a key didn't exist before having been set by the set() method.
* @type {Object}
* @private
*/
goog.testing.PropertyReplacer.NO_SUCH_KEY_ = {};
/**
* Tells if the given key exists in the object. Ignores inherited fields.
* @param {Object|Function} obj The JavaScript or native object or function
* whose key is to be checked.
* @param {string} key The key to check.
* @return {boolean} Whether the object has the key as own key.
* @private
*/
goog.testing.PropertyReplacer.hasKey_ = function(obj, key) {
if (!(key in obj)) {
return false;
}
// hasOwnProperty is only reliable with JavaScript objects. It returns false
// for built-in DOM attributes.
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return true;
}
// In all browsers except Opera obj.constructor never equals to Object if
// obj is an instance of a native class. In Opera we have to fall back on
// examining obj.toString().
if (obj.constructor == Object &&
(!goog.userAgent.OPERA ||
Object.prototype.toString.call(obj) == '[object Object]')) {
return false;
}
try {
// Firefox hack to consider "className" part of the HTML elements or
// "body" part of document. Although they are defined in the prototype of
// HTMLElement or Document, accessing them this way throws an exception.
// <pre>
// var dummy = document.body.constructor.prototype.className
// [Exception... "Cannot modify properties of a WrappedNative"]
// </pre>
var dummy = obj.constructor.prototype[key];
} catch (e) {
return true;
}
return !(key in obj.constructor.prototype);
};
/**
* Deletes a key from an object. Sets it to undefined or empty string if the
* delete failed.
* @param {Object|Function} obj The object or function to delete a key from.
* @param {string} key The key to delete.
* @private
*/
goog.testing.PropertyReplacer.deleteKey_ = function(obj, key) {
try {
delete obj[key];
// Delete has no effect for built-in properties of DOM nodes in FF.
if (!goog.testing.PropertyReplacer.hasKey_(obj, key)) {
return;
}
} catch (e) {
// IE throws TypeError when trying to delete properties of native objects
// (e.g. DOM nodes or window), even if they have been added by JavaScript.
}
obj[key] = undefined;
if (obj[key] == 'undefined') {
// Some properties such as className in IE are always evaluated as string
// so undefined will become 'undefined'.
obj[key] = '';
}
};
/**
* Adds or changes a value in an object while saving its original state.
* @param {Object|Function} obj The JavaScript or native object or function to
* alter. See the constraints in the class description.
* @param {string} key The key to change the value for.
* @param {*} value The new value to set.
*/
goog.testing.PropertyReplacer.prototype.set = function(obj, key, value) {
var origValue = goog.testing.PropertyReplacer.hasKey_(obj, key) ? obj[key] :
goog.testing.PropertyReplacer.NO_SUCH_KEY_;
this.original_.push({object: obj, key: key, value: origValue});
obj[key] = value;
};
/**
* Changes an existing value in an object to another one of the same type while
* saving its original state. The advantage of {@code replace} over {@link #set}
* is that {@code replace} protects against typos and erroneously passing tests
* after some members have been renamed during a refactoring.
* @param {Object|Function} obj The JavaScript or native object or function to
* alter. See the constraints in the class description.
* @param {string} key The key to change the value for. It has to be present
* either in {@code obj} or in its prototype chain.
* @param {*} value The new value to set. It has to have the same type as the
* original value. The types are compared with {@link goog.typeOf}.
* @throws {Error} In case of missing key or type mismatch.
*/
goog.testing.PropertyReplacer.prototype.replace = function(obj, key, value) {
if (!(key in obj)) {
throw Error('Cannot replace missing property "' + key + '" in ' + obj);
}
if (goog.typeOf(obj[key]) != goog.typeOf(value)) {
throw Error('Cannot replace property "' + key + '" in ' + obj +
' with a value of different type');
}
this.set(obj, key, value);
};
/**
* Builds an object structure for the provided namespace path. Doesn't
* overwrite those prefixes of the path that are already objects or functions.
* @param {string} path The path to create or alter, e.g. 'goog.ui.Menu'.
* @param {*} value The value to set.
*/
goog.testing.PropertyReplacer.prototype.setPath = function(path, value) {
var parts = path.split('.');
var obj = goog.global;
for (var i = 0; i < parts.length - 1; i++) {
var part = parts[i];
if (part == 'prototype' && !obj[part]) {
throw Error('Cannot set the prototype of ' + parts.slice(0, i).join('.'));
}
if (!goog.isObject(obj[part]) && !goog.isFunction(obj[part])) {
this.set(obj, part, {});
}
obj = obj[part];
}
this.set(obj, parts[parts.length - 1], value);
};
/**
* Deletes the key from the object while saving its original value.
* @param {Object|Function} obj The JavaScript or native object or function to
* alter. See the constraints in the class description.
* @param {string} key The key to delete.
*/
goog.testing.PropertyReplacer.prototype.remove = function(obj, key) {
if (goog.testing.PropertyReplacer.hasKey_(obj, key)) {
this.original_.push({object: obj, key: key, value: obj[key]});
goog.testing.PropertyReplacer.deleteKey_(obj, key);
}
};
/**
* Resets all changes made by goog.testing.PropertyReplacer.prototype.set.
*/
goog.testing.PropertyReplacer.prototype.reset = function() {
for (var i = this.original_.length - 1; i >= 0; i--) {
var original = this.original_[i];
if (original.value == goog.testing.PropertyReplacer.NO_SUCH_KEY_) {
goog.testing.PropertyReplacer.deleteKey_(original.object, original.key);
} else {
original.object[original.key] = original.value;
}
delete this.original_[i];
}
this.original_.length = 0;
};
| 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 Helper for passing property names as string literals in
* compiled test code.
*
*/
goog.provide('goog.testing.ObjectPropertyString');
/**
* Object to pass a property name as a string literal and its containing object
* when the JSCompiler is rewriting these names. This should only be used in
* test code.
*
* @param {Object} object The containing object.
* @param {Object|string} propertyString Property name as a string literal.
* @constructor
*/
goog.testing.ObjectPropertyString = function(object, propertyString) {
this.object_ = object;
this.propertyString_ = /** @type {string} */ (propertyString);
};
/**
* @type {Object}
* @private
*/
goog.testing.ObjectPropertyString.prototype.object_;
/**
* @type {string}
* @private
*/
goog.testing.ObjectPropertyString.prototype.propertyString_;
/**
* @return {Object} The object.
*/
goog.testing.ObjectPropertyString.prototype.getObject = function() {
return this.object_;
};
/**
* @return {string} The property string.
*/
goog.testing.ObjectPropertyString.prototype.getPropertyString = function() {
return this.propertyString_;
};
| 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 LooseMock of goog.dom.AbstractRange.
*
*/
goog.provide('goog.testing.MockRange');
goog.require('goog.dom.AbstractRange');
goog.require('goog.testing.LooseMock');
/**
* LooseMock of goog.dom.AbstractRange. Useful because the mock framework cannot
* simply create a mock out of an abstract class, and cannot create a mock out
* of classes that implements __iterator__ because it relies on the default
* behavior of iterating through all of an object's properties.
* @constructor
* @extends {goog.testing.LooseMock}
*/
goog.testing.MockRange = function() {
goog.testing.LooseMock.call(this, goog.testing.MockRange.ConcreteRange_);
};
goog.inherits(goog.testing.MockRange, goog.testing.LooseMock);
// *** Private helper class ************************************************* //
/**
* Concrete subclass of goog.dom.AbstractRange that simply sets the abstract
* method __iterator__ to undefined so that javascript defaults to iterating
* through all of the object's properties.
* @constructor
* @extends {goog.dom.AbstractRange}
* @private
*/
goog.testing.MockRange.ConcreteRange_ = function() {
goog.dom.AbstractRange.call(this);
};
goog.inherits(goog.testing.MockRange.ConcreteRange_, goog.dom.AbstractRange);
/**
* Undefine the iterator so the mock framework can loop through this class'
* properties.
* @override
*/
goog.testing.MockRange.ConcreteRange_.prototype.__iterator__ =
// This isn't really type-safe.
/** @type {?} */ (undefined);
| 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 allows for simple text editing tests.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.testing.editor.TestHelper');
goog.require('goog.Disposable');
goog.require('goog.dom');
goog.require('goog.dom.Range');
goog.require('goog.editor.BrowserFeature');
goog.require('goog.editor.node');
goog.require('goog.editor.plugins.AbstractBubblePlugin');
goog.require('goog.testing.dom');
/**
* Create a new test controller.
* @param {Element} root The root editable element.
* @constructor
* @extends {goog.Disposable}
*/
goog.testing.editor.TestHelper = function(root) {
if (!root) {
throw Error('Null root');
}
goog.Disposable.call(this);
/**
* Convenience variable for root DOM element.
* @type {!Element}
* @private
*/
this.root_ = root;
/**
* The starting HTML of the editable element.
* @type {string}
* @private
*/
this.savedHtml_ = '';
};
goog.inherits(goog.testing.editor.TestHelper, goog.Disposable);
/**
* Selects a new root element.
* @param {Element} root The root editable element.
*/
goog.testing.editor.TestHelper.prototype.setRoot = function(root) {
if (!root) {
throw Error('Null root');
}
this.root_ = root;
};
/**
* Make the root element editable. Alse saves its HTML to be restored
* in tearDown.
*/
goog.testing.editor.TestHelper.prototype.setUpEditableElement = function() {
this.savedHtml_ = this.root_.innerHTML;
if (goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) {
this.root_.contentEditable = true;
} else {
this.root_.ownerDocument.designMode = 'on';
}
this.root_.setAttribute('g_editable', 'true');
};
/**
* Reset the element previously initialized, restoring its HTML and making it
* non editable.
*/
goog.testing.editor.TestHelper.prototype.tearDownEditableElement = function() {
if (goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE) {
this.root_.contentEditable = false;
} else {
this.root_.ownerDocument.designMode = 'off';
}
goog.dom.removeChildren(this.root_);
this.root_.innerHTML = this.savedHtml_;
this.root_.removeAttribute('g_editable');
if (goog.editor.plugins && goog.editor.plugins.AbstractBubblePlugin) {
// Remove old bubbles.
for (var key in goog.editor.plugins.AbstractBubblePlugin.bubbleMap_) {
goog.editor.plugins.AbstractBubblePlugin.bubbleMap_[key].dispose();
}
// Ensure we get a new bubble for each test.
goog.editor.plugins.AbstractBubblePlugin.bubbleMap_ = {};
}
};
/**
* Assert that the html in 'root' is substantially similar to htmlPattern.
* This method tests for the same set of styles, and for the same order of
* nodes. Breaking whitespace nodes are ignored. Elements can be annotated
* with classnames corresponding to keys in goog.userAgent and will be
* expected to show up in that user agent and expected not to show up in
* others.
* @param {string} htmlPattern The pattern to match.
*/
goog.testing.editor.TestHelper.prototype.assertHtmlMatches = function(
htmlPattern) {
goog.testing.dom.assertHtmlContentsMatch(htmlPattern, this.root_);
};
/**
* Finds the first text node descendant of root with the given content.
* @param {string|RegExp} textOrRegexp The text to find, or a regular
* expression to find a match of.
* @return {Node} The first text node that matches, or null if none is found.
*/
goog.testing.editor.TestHelper.prototype.findTextNode = function(textOrRegexp) {
return goog.testing.dom.findTextNode(textOrRegexp, this.root_);
};
/**
* Select from the given from offset in the given from node to the given
* to offset in the optionally given to node. If nodes are passed in, uses them,
* otherwise uses findTextNode to find the nodes to select. Selects a caret
* if opt_to and opt_toOffset are not given.
* @param {Node|string} from Node or text of the node to start the selection at.
* @param {number} fromOffset Offset within the above node to start the
* selection at.
* @param {Node|string=} opt_to Node or text of the node to end the selection
* at.
* @param {number=} opt_toOffset Offset within the above node to end the
* selection at.
*/
goog.testing.editor.TestHelper.prototype.select = function(from, fromOffset,
opt_to, opt_toOffset) {
var end;
var start = end = goog.isString(from) ? this.findTextNode(from) : from;
var endOffset;
var startOffset = endOffset = fromOffset;
if (opt_to && goog.isNumber(opt_toOffset)) {
end = goog.isString(opt_to) ? this.findTextNode(opt_to) : opt_to;
endOffset = opt_toOffset;
}
goog.dom.Range.createFromNodes(start, startOffset, end, endOffset).select();
};
/** @override */
goog.testing.editor.TestHelper.prototype.disposeInternal = function() {
if (goog.editor.node.isEditableContainer(this.root_)) {
this.tearDownEditableElement();
}
delete this.root_;
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 Mock of goog.editor.field.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.testing.editor.FieldMock');
goog.require('goog.dom');
goog.require('goog.dom.Range');
goog.require('goog.editor.Field');
goog.require('goog.testing.LooseMock');
goog.require('goog.testing.mockmatchers');
/**
* Mock of goog.editor.Field.
* @param {Window=} opt_window Window the field would edit. Defaults to
* {@code window}.
* @param {Window=} opt_appWindow "AppWindow" of the field, which can be
* different from {@code opt_window} when mocking a field that uses an
* iframe. Defaults to {@code opt_window}.
* @param {goog.dom.AbstractRange=} opt_range An object (mock or real) to be
* returned by getRange(). If ommitted, a new goog.dom.Range is created
* from the window every time getRange() is called.
* @constructor
* @extends {goog.testing.LooseMock}
* @suppress {missingProperties} Mocks do not fit in the type system well.
*/
goog.testing.editor.FieldMock =
function(opt_window, opt_appWindow, opt_range) {
goog.testing.LooseMock.call(this, goog.editor.Field);
opt_window = opt_window || window;
opt_appWindow = opt_appWindow || opt_window;
this.getAppWindow();
this.$anyTimes();
this.$returns(opt_appWindow);
this.getRange();
this.$anyTimes();
this.$does(function() {
return opt_range || goog.dom.Range.createFromWindow(opt_window);
});
this.getEditableDomHelper();
this.$anyTimes();
this.$returns(goog.dom.getDomHelper(opt_window.document));
this.usesIframe();
this.$anyTimes();
this.getBaseZindex();
this.$anyTimes();
this.$returns(0);
this.restoreSavedRange(goog.testing.mockmatchers.ignoreArgument);
this.$anyTimes();
this.$does(function(range) {
if (range) {
range.restore();
}
this.focus();
});
// These methods cannot be set on the prototype, because the prototype
// gets stepped on by the mock framework.
var inModalMode = false;
/**
* @return {boolean} Whether we're in modal interaction mode.
*/
this.inModalMode = function() {
return inModalMode;
};
/**
* @param {boolean} mode Sets whether we're in modal interaction mode.
*/
this.setModalMode = function(mode) {
inModalMode = mode;
};
};
goog.inherits(goog.testing.editor.FieldMock, goog.testing.LooseMock);
| 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 Testing utilities for editor specific DOM related tests.
*
*/
goog.provide('goog.testing.editor.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.TagIterator');
goog.require('goog.dom.TagWalkType');
goog.require('goog.iter');
goog.require('goog.string');
goog.require('goog.testing.asserts');
/**
* Returns the previous (in document order) node from the given node that is a
* non-empty text node, or null if none is found or opt_stopAt is not an
* ancestor of node. Note that if the given node has children, the search will
* start from the end tag of the node, meaning all its descendants will be
* included in the search, unless opt_skipDescendants is true.
* @param {Node} node Node to start searching from.
* @param {Node=} opt_stopAt Node to stop searching at (search will be
* restricted to this node's subtree), defaults to the body of the document
* containing node.
* @param {boolean=} opt_skipDescendants Whether to skip searching the given
* node's descentants.
* @return {Text} The previous (in document order) node from the given node
* that is a non-empty text node, or null if none is found.
*/
goog.testing.editor.dom.getPreviousNonEmptyTextNode = function(
node, opt_stopAt, opt_skipDescendants) {
return goog.testing.editor.dom.getPreviousNextNonEmptyTextNodeHelper_(
node, opt_stopAt, opt_skipDescendants, true);
};
/**
* Returns the next (in document order) node from the given node that is a
* non-empty text node, or null if none is found or opt_stopAt is not an
* ancestor of node. Note that if the given node has children, the search will
* start from the start tag of the node, meaning all its descendants will be
* included in the search, unless opt_skipDescendants is true.
* @param {Node} node Node to start searching from.
* @param {Node=} opt_stopAt Node to stop searching at (search will be
* restricted to this node's subtree), defaults to the body of the document
* containing node.
* @param {boolean=} opt_skipDescendants Whether to skip searching the given
* node's descentants.
* @return {Text} The next (in document order) node from the given node that
* is a non-empty text node, or null if none is found or opt_stopAt is not
* an ancestor of node.
*/
goog.testing.editor.dom.getNextNonEmptyTextNode = function(
node, opt_stopAt, opt_skipDescendants) {
return goog.testing.editor.dom.getPreviousNextNonEmptyTextNodeHelper_(
node, opt_stopAt, opt_skipDescendants, false);
};
/**
* Helper that returns the previous or next (in document order) node from the
* given node that is a non-empty text node, or null if none is found or
* opt_stopAt is not an ancestor of node. Note that if the given node has
* children, the search will start from the end or start tag of the node
* (depending on whether it's searching for the previous or next node), meaning
* all its descendants will be included in the search, unless
* opt_skipDescendants is true.
* @param {Node} node Node to start searching from.
* @param {Node=} opt_stopAt Node to stop searching at (search will be
* restricted to this node's subtree), defaults to the body of the document
* containing node.
* @param {boolean=} opt_skipDescendants Whether to skip searching the given
* node's descentants.
* @param {boolean=} opt_isPrevious Whether to search for the previous non-empty
* text node instead of the next one.
* @return {Text} The next (in document order) node from the given node that
* is a non-empty text node, or null if none is found or opt_stopAt is not
* an ancestor of node.
* @private
*/
goog.testing.editor.dom.getPreviousNextNonEmptyTextNodeHelper_ = function(
node, opt_stopAt, opt_skipDescendants, opt_isPrevious) {
opt_stopAt = opt_stopAt || node.ownerDocument.body;
// Initializing the iterator to iterate over the children of opt_stopAt
// makes it stop only when it finishes iterating through all of that
// node's children, even though we will start at a different node and exit
// that starting node's subtree in the process.
var iter = new goog.dom.TagIterator(opt_stopAt, opt_isPrevious);
// TODO(user): Move this logic to a new method in TagIterator such as
// skipToNode().
// Then we set the iterator to start at the given start node, not opt_stopAt.
var walkType; // Let TagIterator set the initial walk type by default.
var depth = goog.testing.editor.dom.getRelativeDepth_(node, opt_stopAt);
if (depth == -1) {
return null; // Fail because opt_stopAt is not an ancestor of node.
}
if (node.nodeType == goog.dom.NodeType.ELEMENT) {
if (opt_skipDescendants) {
// Specifically set the initial walk type so that we skip the descendant
// subtree by starting at the start if going backwards or at the end if
// going forwards.
walkType = opt_isPrevious ? goog.dom.TagWalkType.START_TAG :
goog.dom.TagWalkType.END_TAG;
} else {
// We're starting "inside" an element node so the depth needs to be one
// deeper than the node's actual depth. That's how TagIterator works!
depth++;
}
}
iter.setPosition(node, walkType, depth);
// Advance the iterator so it skips the start node.
try {
iter.next();
} catch (e) {
return null; // It could have been a leaf node.
}
// Now just get the first non-empty text node the iterator finds.
var filter = goog.iter.filter(iter,
goog.testing.editor.dom.isNonEmptyTextNode_);
try {
return /** @type {Text} */ (filter.next());
} catch (e) { // No next item is available so return null.
return null;
}
};
/**
* Returns whether the given node is a non-empty text node.
* @param {Node} node Node to be checked.
* @return {boolean} Whether the given node is a non-empty text node.
* @private
*/
goog.testing.editor.dom.isNonEmptyTextNode_ = function(node) {
return !!node && node.nodeType == goog.dom.NodeType.TEXT && node.length > 0;
};
/**
* Returns the depth of the given node relative to the given parent node, or -1
* if the given node is not a descendant of the given parent node. E.g. if
* node == parentNode returns 0, if node.parentNode == parentNode returns 1,
* etc.
* @param {Node} node Node whose depth to get.
* @param {Node} parentNode Node relative to which the depth should be
* calculated.
* @return {number} The depth of the given node relative to the given parent
* node, or -1 if the given node is not a descendant of the given parent
* node.
* @private
*/
goog.testing.editor.dom.getRelativeDepth_ = function(node, parentNode) {
var depth = 0;
while (node) {
if (node == parentNode) {
return depth;
}
node = node.parentNode;
depth++;
}
return -1;
};
/**
* Assert that the range is surrounded by the given strings. This is useful
* because different browsers can place the range endpoints inside different
* nodes even when visually the range looks the same. Also, there may be empty
* text nodes in the way (again depending on the browser) making it difficult to
* use assertRangeEquals.
* @param {string} before String that should occur immediately before the start
* point of the range. If this is the empty string, assert will only succeed
* if there is no text before the start point of the range.
* @param {string} after String that should occur immediately after the end
* point of the range. If this is the empty string, assert will only succeed
* if there is no text after the end point of the range.
* @param {goog.dom.AbstractRange} range The range to be tested.
* @param {Node=} opt_stopAt Node to stop searching at (search will be
* restricted to this node's subtree).
*/
goog.testing.editor.dom.assertRangeBetweenText = function(before,
after,
range,
opt_stopAt) {
var previousText =
goog.testing.editor.dom.getTextFollowingRange_(range, true, opt_stopAt);
if (before == '') {
assertNull('Expected nothing before range but found <' + previousText + '>',
previousText);
} else {
assertNotNull('Expected <' + before + '> before range but found nothing',
previousText);
assertTrue('Expected <' + before + '> before range but found <' +
previousText + '>',
goog.string.endsWith(
/** @type {string} */ (previousText), before));
}
var nextText =
goog.testing.editor.dom.getTextFollowingRange_(range, false, opt_stopAt);
if (after == '') {
assertNull('Expected nothing after range but found <' + nextText + '>',
nextText);
} else {
assertNotNull('Expected <' + after + '> after range but found nothing',
nextText);
assertTrue('Expected <' + after + '> after range but found <' +
nextText + '>',
goog.string.startsWith(
/** @type {string} */ (nextText), after));
}
};
/**
* Returns the text that follows the given range, where the term "follows" means
* "comes immediately before the start of the range" if isBefore is true, and
* "comes immediately after the end of the range" if isBefore is false, or null
* if no non-empty text node is found.
* @param {goog.dom.AbstractRange} range The range to search from.
* @param {boolean} isBefore Whether to search before the range instead of
* after it.
* @param {Node=} opt_stopAt Node to stop searching at (search will be
* restricted to this node's subtree).
* @return {?string} The text that follows the given range, or null if no
* non-empty text node is found.
* @private
*/
goog.testing.editor.dom.getTextFollowingRange_ = function(range,
isBefore,
opt_stopAt) {
var followingTextNode;
var endpointNode = isBefore ? range.getStartNode() : range.getEndNode();
var endpointOffset = isBefore ? range.getStartOffset() : range.getEndOffset();
var getFollowingTextNode =
isBefore ? goog.testing.editor.dom.getPreviousNonEmptyTextNode :
goog.testing.editor.dom.getNextNonEmptyTextNode;
if (endpointNode.nodeType == goog.dom.NodeType.TEXT) {
// Range endpoint is in a text node.
var endText = endpointNode.nodeValue;
if (isBefore ? endpointOffset > 0 : endpointOffset < endText.length) {
// There is text in this node following the endpoint so return the portion
// that follows the endpoint.
return isBefore ? endText.substr(0, endpointOffset) :
endText.substr(endpointOffset);
} else {
// There is no text following the endpoint so look for the follwing text
// node.
followingTextNode = getFollowingTextNode(endpointNode, opt_stopAt);
return followingTextNode && followingTextNode.nodeValue;
}
} else {
// Range endpoint is in an element node.
var numChildren = endpointNode.childNodes.length;
if (isBefore ? endpointOffset > 0 : endpointOffset < numChildren) {
// There is at least one child following the endpoint.
var followingChild =
endpointNode.childNodes[isBefore ? endpointOffset - 1 :
endpointOffset];
if (goog.testing.editor.dom.isNonEmptyTextNode_(followingChild)) {
// The following child has text so return that.
return followingChild.nodeValue;
} else {
// The following child has no text so look for the following text node.
followingTextNode = getFollowingTextNode(followingChild, opt_stopAt);
return followingTextNode && followingTextNode.nodeValue;
}
} else {
// There is no child following the endpoint, so search from the endpoint
// node, but don't search its children because they are not following the
// endpoint!
followingTextNode = getFollowingTextNode(endpointNode, opt_stopAt, true);
return followingTextNode && followingTextNode.nodeValue;
}
}
};
| 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 Tools for parsing and pretty printing error stack traces.
*
*/
goog.provide('goog.testing.stacktrace');
goog.provide('goog.testing.stacktrace.Frame');
/**
* Class representing one stack frame.
* @param {string} context Context object, empty in case of global functions or
* if the browser doesn't provide this information.
* @param {string} name Function name, empty in case of anonymous functions.
* @param {string} alias Alias of the function if available. For example the
* function name will be 'c' and the alias will be 'b' if the function is
* defined as <code>a.b = function c() {};</code>.
* @param {string} args Arguments of the function in parentheses if available.
* @param {string} path File path or URL including line number and optionally
* column number separated by colons.
* @constructor
*/
goog.testing.stacktrace.Frame = function(context, name, alias, args, path) {
this.context_ = context;
this.name_ = name;
this.alias_ = alias;
this.args_ = args;
this.path_ = path;
};
/**
* @return {string} The function name or empty string if the function is
* anonymous and the object field which it's assigned to is unknown.
*/
goog.testing.stacktrace.Frame.prototype.getName = function() {
return this.name_;
};
/**
* @return {boolean} Whether the stack frame contains an anonymous function.
*/
goog.testing.stacktrace.Frame.prototype.isAnonymous = function() {
return !this.name_ || this.context_ == '[object Object]';
};
/**
* Brings one frame of the stack trace into a common format across browsers.
* @return {string} Pretty printed stack frame.
*/
goog.testing.stacktrace.Frame.prototype.toCanonicalString = function() {
var htmlEscape = goog.testing.stacktrace.htmlEscape_;
var deobfuscate = goog.testing.stacktrace.maybeDeobfuscateFunctionName_;
var canonical = [
this.context_ ? htmlEscape(this.context_) + '.' : '',
this.name_ ? htmlEscape(deobfuscate(this.name_)) : 'anonymous',
htmlEscape(this.args_),
this.alias_ ? ' [as ' + htmlEscape(deobfuscate(this.alias_)) + ']' : ''
];
if (this.path_) {
canonical.push(' at ');
// If Closure Inspector is installed and running, then convert the line
// into a source link for displaying the code in Firebug.
if (goog.testing.stacktrace.isClosureInspectorActive_()) {
var lineNumber = this.path_.match(/\d+$/)[0];
canonical.push('<a href="" onclick="CLOSURE_INSPECTOR___.showLine(\'',
htmlEscape(this.path_), '\', \'', lineNumber, '\'); return false">',
htmlEscape(this.path_), '</a>');
} else {
canonical.push(htmlEscape(this.path_));
}
}
return canonical.join('');
};
/**
* Maximum number of steps while the call chain is followed.
* @type {number}
* @private
*/
goog.testing.stacktrace.MAX_DEPTH_ = 20;
/**
* Maximum length of a string that can be matched with a RegExp on
* Firefox 3x. Exceeding this approximate length will cause string.match
* to exceed Firefox's stack quota. This situation can be encountered
* when goog.globalEval is invoked with a long argument; such as
* when loading a module.
* @type {number}
* @private
*/
goog.testing.stacktrace.MAX_FIREFOX_FRAMESTRING_LENGTH_ = 500000;
/**
* RegExp pattern for JavaScript identifiers. We don't support Unicode
* identifiers defined in ECMAScript v3.
* @type {string}
* @private
*/
goog.testing.stacktrace.IDENTIFIER_PATTERN_ = '[a-zA-Z_$][\\w$]*';
/**
* RegExp pattern for function name alias in the Chrome stack trace.
* @type {string}
* @private
*/
goog.testing.stacktrace.CHROME_ALIAS_PATTERN_ =
'(?: \\[as (' + goog.testing.stacktrace.IDENTIFIER_PATTERN_ + ')\\])?';
/**
* RegExp pattern for function names and constructor calls in the Chrome stack
* trace.
* @type {string}
* @private
*/
goog.testing.stacktrace.CHROME_FUNCTION_NAME_PATTERN_ =
'(?:new )?(?:' + goog.testing.stacktrace.IDENTIFIER_PATTERN_ +
'|<anonymous>)';
/**
* RegExp pattern for function call in the Chrome stack trace.
* Creates 3 submatches with context object (optional), function name and
* function alias (optional).
* @type {string}
* @private
*/
goog.testing.stacktrace.CHROME_FUNCTION_CALL_PATTERN_ =
' (?:(.*?)\\.)?(' + goog.testing.stacktrace.CHROME_FUNCTION_NAME_PATTERN_ +
')' + goog.testing.stacktrace.CHROME_ALIAS_PATTERN_;
/**
* RegExp pattern for an URL + position inside the file.
* @type {string}
* @private
*/
goog.testing.stacktrace.URL_PATTERN_ =
'((?:http|https|file)://[^\\s)]+|javascript:.*)';
/**
* RegExp pattern for an URL + line number + column number in Chrome.
* The URL is either in submatch 1 or submatch 2.
* @type {string}
* @private
*/
goog.testing.stacktrace.CHROME_URL_PATTERN_ = ' (?:' +
'\\(unknown source\\)' + '|' +
'\\(native\\)' + '|' +
'\\((?:eval at )?' + goog.testing.stacktrace.URL_PATTERN_ + '\\)' + '|' +
goog.testing.stacktrace.URL_PATTERN_ + ')';
/**
* Regular expression for parsing one stack frame in Chrome.
* @type {!RegExp}
* @private
*/
goog.testing.stacktrace.CHROME_STACK_FRAME_REGEXP_ = new RegExp('^ at' +
'(?:' + goog.testing.stacktrace.CHROME_FUNCTION_CALL_PATTERN_ + ')?' +
goog.testing.stacktrace.CHROME_URL_PATTERN_ + '$');
/**
* RegExp pattern for function call in the Firefox stack trace.
* Creates 2 submatches with function name (optional) and arguments.
* @type {string}
* @private
*/
goog.testing.stacktrace.FIREFOX_FUNCTION_CALL_PATTERN_ =
'(' + goog.testing.stacktrace.IDENTIFIER_PATTERN_ + ')?' +
'(\\(.*\\))?@';
/**
* Regular expression for parsing one stack frame in Firefox.
* @type {!RegExp}
* @private
*/
goog.testing.stacktrace.FIREFOX_STACK_FRAME_REGEXP_ = new RegExp('^' +
goog.testing.stacktrace.FIREFOX_FUNCTION_CALL_PATTERN_ +
'(?::0|' + goog.testing.stacktrace.URL_PATTERN_ + ')$');
/**
* RegExp pattern for an anonymous function call in an Opera stack frame.
* Creates 2 (optional) submatches: the context object and function name.
* @type {string}
* @const
* @private
*/
goog.testing.stacktrace.OPERA_ANONYMOUS_FUNCTION_NAME_PATTERN_ =
'<anonymous function(?:\\: ' +
'(?:(' + goog.testing.stacktrace.IDENTIFIER_PATTERN_ +
'(?:\\.' + goog.testing.stacktrace.IDENTIFIER_PATTERN_ + ')*)\\.)?' +
'(' + goog.testing.stacktrace.IDENTIFIER_PATTERN_ + '))?>';
/**
* RegExp pattern for a function call in an Opera stack frame.
* Creates 4 (optional) submatches: the function name (if not anonymous),
* the aliased context object and function name (if anonymous), and the
* function call arguments.
* @type {string}
* @const
* @private
*/
goog.testing.stacktrace.OPERA_FUNCTION_CALL_PATTERN_ =
'(?:(?:(' + goog.testing.stacktrace.IDENTIFIER_PATTERN_ + ')|' +
goog.testing.stacktrace.OPERA_ANONYMOUS_FUNCTION_NAME_PATTERN_ +
')(\\(.*\\)))?@';
/**
* Regular expression for parsing on stack frame in Opera 11.68+
* @type {!RegExp}
* @const
* @private
*/
goog.testing.stacktrace.OPERA_STACK_FRAME_REGEXP_ = new RegExp('^' +
goog.testing.stacktrace.OPERA_FUNCTION_CALL_PATTERN_ +
goog.testing.stacktrace.URL_PATTERN_ + '?$');
/**
* Regular expression for finding the function name in its source.
* @type {!RegExp}
* @private
*/
goog.testing.stacktrace.FUNCTION_SOURCE_REGEXP_ = new RegExp(
'^function (' + goog.testing.stacktrace.IDENTIFIER_PATTERN_ + ')');
/**
* RegExp pattern for function call in a IE stack trace. This expression allows
* for identifiers like 'Anonymous function', 'eval code', and 'Global code'.
* @type {string}
* @const
* @private
*/
goog.testing.stacktrace.IE_FUNCTION_CALL_PATTERN_ = '(' +
goog.testing.stacktrace.IDENTIFIER_PATTERN_ + '(?:\\s+\\w+)*)';
/**
* Regular expression for parsing a stack frame in IE.
* @type {!RegExp}
* @const
* @private
*/
goog.testing.stacktrace.IE_STACK_FRAME_REGEXP_ = new RegExp('^ at ' +
goog.testing.stacktrace.IE_FUNCTION_CALL_PATTERN_ +
'\\s*\\((eval code:[^)]*|' + goog.testing.stacktrace.URL_PATTERN_ +
')\\)?$');
/**
* Creates a stack trace by following the call chain. Based on
* {@link goog.debug.getStacktrace}.
* @return {!Array.<!goog.testing.stacktrace.Frame>} Stack frames.
* @private
*/
goog.testing.stacktrace.followCallChain_ = function() {
var frames = [];
var fn = arguments.callee.caller;
var depth = 0;
while (fn && depth < goog.testing.stacktrace.MAX_DEPTH_) {
var fnString = Function.prototype.toString.call(fn);
var match = fnString.match(goog.testing.stacktrace.FUNCTION_SOURCE_REGEXP_);
var functionName = match ? match[1] : '';
var argsBuilder = ['('];
if (fn.arguments) {
for (var i = 0; i < fn.arguments.length; i++) {
var arg = fn.arguments[i];
if (i > 0) {
argsBuilder.push(', ');
}
if (goog.isString(arg)) {
argsBuilder.push('"', arg, '"');
} else {
// Some args are mocks, and we don't want to fail from them not having
// expected a call to toString, so instead insert a static string.
if (arg && arg['$replay']) {
argsBuilder.push('goog.testing.Mock');
} else {
argsBuilder.push(String(arg));
}
}
}
} else {
// Opera 10 doesn't know the arguments of native functions.
argsBuilder.push('unknown');
}
argsBuilder.push(')');
var args = argsBuilder.join('');
frames.push(new goog.testing.stacktrace.Frame('', functionName, '', args,
''));
/** @preserveTry */
try {
fn = fn.caller;
} catch (e) {
break;
}
depth++;
}
return frames;
};
/**
* Parses one stack frame.
* @param {string} frameStr The stack frame as string.
* @return {goog.testing.stacktrace.Frame} Stack frame object or null if the
* parsing failed.
* @private
*/
goog.testing.stacktrace.parseStackFrame_ = function(frameStr) {
var m = frameStr.match(goog.testing.stacktrace.CHROME_STACK_FRAME_REGEXP_);
if (m) {
return new goog.testing.stacktrace.Frame(m[1] || '', m[2] || '', m[3] || '',
'', m[4] || m[5] || '');
}
if (frameStr.length >
goog.testing.stacktrace.MAX_FIREFOX_FRAMESTRING_LENGTH_) {
return goog.testing.stacktrace.parseLongFirefoxFrame_(frameStr);
}
m = frameStr.match(goog.testing.stacktrace.FIREFOX_STACK_FRAME_REGEXP_);
if (m) {
return new goog.testing.stacktrace.Frame('', m[1] || '', '', m[2] || '',
m[3] || '');
}
m = frameStr.match(goog.testing.stacktrace.OPERA_STACK_FRAME_REGEXP_);
if (m) {
return new goog.testing.stacktrace.Frame(m[2] || '', m[1] || m[3] || '',
'', m[4] || '', m[5] || '');
}
m = frameStr.match(goog.testing.stacktrace.IE_STACK_FRAME_REGEXP_);
if (m) {
return new goog.testing.stacktrace.Frame('', m[1] || '', '', '',
m[2] || '');
}
return null;
};
/**
* Parses a long firefox stack frame.
* @param {string} frameStr The stack frame as string.
* @return {!goog.testing.stacktrace.Frame} Stack frame object.
* @private
*/
goog.testing.stacktrace.parseLongFirefoxFrame_ = function(frameStr) {
var firstParen = frameStr.indexOf('(');
var lastAmpersand = frameStr.lastIndexOf('@');
var lastColon = frameStr.lastIndexOf(':');
var functionName = '';
if ((firstParen >= 0) && (firstParen < lastAmpersand)) {
functionName = frameStr.substring(0, firstParen);
}
var loc = '';
if ((lastAmpersand >= 0) && (lastAmpersand + 1 < lastColon)) {
loc = frameStr.substring(lastAmpersand + 1);
}
var args = '';
if ((firstParen >= 0 && lastAmpersand > 0) &&
(firstParen < lastAmpersand)) {
args = frameStr.substring(firstParen, lastAmpersand);
}
return new goog.testing.stacktrace.Frame('', functionName, '', args, loc);
};
/**
* Function to deobfuscate function names.
* @type {function(string): string}
* @private
*/
goog.testing.stacktrace.deobfuscateFunctionName_;
/**
* Sets function to deobfuscate function names.
* @param {function(string): string} fn function to deobfuscate function names.
*/
goog.testing.stacktrace.setDeobfuscateFunctionName = function(fn) {
goog.testing.stacktrace.deobfuscateFunctionName_ = fn;
};
/**
* Deobfuscates a compiled function name with the function passed to
* {@link #setDeobfuscateFunctionName}. Returns the original function name if
* the deobfuscator hasn't been set.
* @param {string} name The function name to deobfuscate.
* @return {string} The deobfuscated function name.
* @private
*/
goog.testing.stacktrace.maybeDeobfuscateFunctionName_ = function(name) {
return goog.testing.stacktrace.deobfuscateFunctionName_ ?
goog.testing.stacktrace.deobfuscateFunctionName_(name) : name;
};
/**
* @return {boolean} Whether the Closure Inspector is active.
* @private
*/
goog.testing.stacktrace.isClosureInspectorActive_ = function() {
return Boolean(goog.global['CLOSURE_INSPECTOR___'] &&
goog.global['CLOSURE_INSPECTOR___']['supportsJSUnit']);
};
/**
* Escapes the special character in HTML.
* @param {string} text Plain text.
* @return {string} Escaped text.
* @private
*/
goog.testing.stacktrace.htmlEscape_ = function(text) {
return text.replace(/&/g, '&').
replace(/</g, '<').
replace(/>/g, '>').
replace(/"/g, '"');
};
/**
* Converts the stack frames into canonical format. Chops the beginning and the
* end of it which come from the testing environment, not from the test itself.
* @param {!Array.<goog.testing.stacktrace.Frame>} frames The frames.
* @return {string} Canonical, pretty printed stack trace.
* @private
*/
goog.testing.stacktrace.framesToString_ = function(frames) {
// Removes the anonymous calls from the end of the stack trace (they come
// from testrunner.js, testcase.js and asserts.js), so the stack trace will
// end with the test... method.
var lastIndex = frames.length - 1;
while (frames[lastIndex] && frames[lastIndex].isAnonymous()) {
lastIndex--;
}
// Removes the beginning of the stack trace until the call of the private
// _assert function (inclusive), so the stack trace will begin with a public
// asserter. Does nothing if _assert is not present in the stack trace.
var privateAssertIndex = -1;
for (var i = 0; i < frames.length; i++) {
if (frames[i] && frames[i].getName() == '_assert') {
privateAssertIndex = i;
break;
}
}
var canonical = [];
for (var i = privateAssertIndex + 1; i <= lastIndex; i++) {
canonical.push('> ');
if (frames[i]) {
canonical.push(frames[i].toCanonicalString());
} else {
canonical.push('(unknown)');
}
canonical.push('\n');
}
return canonical.join('');
};
/**
* Parses the browser's native stack trace.
* @param {string} stack Stack trace.
* @return {!Array.<goog.testing.stacktrace.Frame>} Stack frames. The
* unrecognized frames will be nulled out.
* @private
*/
goog.testing.stacktrace.parse_ = function(stack) {
var lines = stack.replace(/\s*$/, '').split('\n');
var frames = [];
for (var i = 0; i < lines.length; i++) {
frames.push(goog.testing.stacktrace.parseStackFrame_(lines[i]));
}
return frames;
};
/**
* Brings the stack trace into a common format across browsers.
* @param {string} stack Browser-specific stack trace.
* @return {string} Same stack trace in common format.
*/
goog.testing.stacktrace.canonicalize = function(stack) {
var frames = goog.testing.stacktrace.parse_(stack);
return goog.testing.stacktrace.framesToString_(frames);
};
/**
* Gets the native stack trace if available otherwise follows the call chain.
* @return {string} The stack trace in canonical format.
*/
goog.testing.stacktrace.get = function() {
var stack = '';
// IE10 will only create a stack trace when the Error is thrown.
// We use null.x() to throw an exception because the closure compiler may
// replace "throw" with a function call in an attempt to minimize the binary
// size, which in turn has the side effect of adding an unwanted stack frame.
try {
null.x();
} catch (e) {
stack = e.stack;
}
var frames = stack ? goog.testing.stacktrace.parse_(stack) :
goog.testing.stacktrace.followCallChain_();
return goog.testing.stacktrace.framesToString_(frames);
};
goog.exportSymbol('setDeobfuscateFunctionName',
goog.testing.stacktrace.setDeobfuscateFunctionName);
| JavaScript |
// Copyright 2010 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A wrapper for MockControl that provides mocks and assertions
* for testing asynchronous code. All assertions will only be verified when
* $verifyAll is called on the wrapped MockControl.
*
* This class is meant primarily for testing code that exposes asynchronous APIs
* without being truly asynchronous (using asynchronous primitives like browser
* events or timeouts). This is often the case when true asynchronous
* depedencies have been mocked out. This means that it doesn't rely on
* AsyncTestCase or DeferredTestCase, although it can be used with those as
* well.
*
* Example usage:
*
* <pre>
* var mockControl = new goog.testing.MockControl();
* var asyncMockControl = new goog.testing.async.MockControl(mockControl);
*
* myAsyncObject.onSuccess(asyncMockControl.asyncAssertEquals(
* 'callback should run and pass the correct value',
* 'http://someurl.com');
* asyncMockControl.assertDeferredEquals(
* 'deferred object should be resolved with the correct value',
* 'http://someurl.com',
* myAsyncObject.getDeferredUrl());
* asyncMockControl.run();
* mockControl.$verifyAll();
* </pre>
*
*/
goog.provide('goog.testing.async.MockControl');
goog.require('goog.asserts');
goog.require('goog.async.Deferred');
goog.require('goog.debug');
goog.require('goog.testing.asserts');
goog.require('goog.testing.mockmatchers.IgnoreArgument');
/**
* Provides asynchronous mocks and assertions controlled by a parent
* MockControl.
*
* @param {goog.testing.MockControl} mockControl The parent MockControl.
* @constructor
*/
goog.testing.async.MockControl = function(mockControl) {
/**
* The parent MockControl.
* @type {goog.testing.MockControl}
* @private
*/
this.mockControl_ = mockControl;
};
/**
* Returns a function that will assert that it will be called, and run the given
* callback when it is.
*
* @param {string} name The name of the callback mock.
* @param {function(...[*]) : *} callback The wrapped callback. This will be
* called when the returned function is called.
* @param {Object=} opt_selfObj The object which this should point to when the
* callback is run.
* @return {!Function} The mock callback.
* @suppress {missingProperties} Mocks do not fit in the type system well.
*/
goog.testing.async.MockControl.prototype.createCallbackMock = function(
name, callback, opt_selfObj) {
goog.asserts.assert(
goog.isString(name),
'name parameter ' + goog.debug.deepExpose(name) + ' should be a string');
var ignored = new goog.testing.mockmatchers.IgnoreArgument();
// Use everyone's favorite "double-cast" trick to subvert the type system.
var obj = /** @type {Object} */ (this.mockControl_.createFunctionMock(name));
var fn = /** @type {Function} */ (obj);
fn(ignored).$does(function(args) {
if (opt_selfObj) {
callback = goog.bind(callback, opt_selfObj);
}
return callback.apply(this, args);
});
fn.$replay();
return function() { return fn(arguments); };
};
/**
* Returns a function that will assert that its arguments are equal to the
* arguments given to asyncAssertEquals. In addition, the function also asserts
* that it will be called.
*
* @param {string} message A message to print if the arguments are wrong.
* @param {...*} var_args The arguments to assert.
* @return {function(...[*]) : void} The mock callback.
*/
goog.testing.async.MockControl.prototype.asyncAssertEquals = function(
message, var_args) {
var expectedArgs = Array.prototype.slice.call(arguments, 1);
return this.createCallbackMock('asyncAssertEquals', function() {
assertObjectEquals(
message, expectedArgs, Array.prototype.slice.call(arguments));
});
};
/**
* Asserts that a deferred object will have an error and call its errback
* function.
* @param {goog.async.Deferred} deferred The deferred object.
* @param {function() : void} fn A function wrapping the code in which the error
* will occur.
*/
goog.testing.async.MockControl.prototype.assertDeferredError = function(
deferred, fn) {
deferred.addErrback(this.createCallbackMock(
'assertDeferredError', function() {}));
goog.testing.asserts.callWithoutLogging(fn);
};
/**
* Asserts that a deferred object will call its callback with the given value.
*
* @param {string} message A message to print if the arguments are wrong.
* @param {goog.async.Deferred|*} expected The expected value. If this is a
* deferred object, then the expected value is the deferred value.
* @param {goog.async.Deferred|*} actual The actual value. If this is a deferred
* object, then the actual value is the deferred value. Either this or
* 'expected' must be deferred.
*/
goog.testing.async.MockControl.prototype.assertDeferredEquals = function(
message, expected, actual) {
if (expected instanceof goog.async.Deferred &&
actual instanceof goog.async.Deferred) {
// Assert that the first deferred is resolved.
expected.addCallback(this.createCallbackMock(
'assertDeferredEquals', function(exp) {
// Assert that the second deferred is resolved, and that the value is
// as expected.
actual.addCallback(this.asyncAssertEquals(message, exp));
}, this));
} else if (expected instanceof goog.async.Deferred) {
expected.addCallback(this.createCallbackMock(
'assertDeferredEquals', function(exp) {
assertObjectEquals(message, exp, actual);
}));
} else if (actual instanceof goog.async.Deferred) {
actual.addCallback(this.asyncAssertEquals(message, expected));
} else {
throw Error('Either expected or actual must be deferred');
}
};
| 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 Performance timer.
*
* {@see goog.testing.benchmark} for an easy way to use this functionality.
*
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.testing.PerformanceTimer');
goog.provide('goog.testing.PerformanceTimer.Task');
goog.require('goog.array');
goog.require('goog.async.Deferred');
goog.require('goog.math');
/**
* Creates a performance timer that runs test functions a number of times to
* generate timing samples, and provides performance statistics (minimum,
* maximum, average, and standard deviation).
* @param {number=} opt_numSamples Number of times to run the test function;
* defaults to 10.
* @param {number=} opt_timeoutInterval Number of milliseconds after which the
* test is to be aborted; defaults to 5 seconds (5,000ms).
* @constructor
*/
goog.testing.PerformanceTimer = function(opt_numSamples, opt_timeoutInterval) {
/**
* Number of times the test function is to be run; defaults to 10.
* @type {number}
* @private
*/
this.numSamples_ = opt_numSamples || 10;
/**
* Number of milliseconds after which the test is to be aborted; defaults to
* 5,000ms.
* @type {number}
* @private
*/
this.timeoutInterval_ = opt_timeoutInterval || 5000;
/**
* Whether to discard outliers (i.e. the smallest and the largest values)
* from the sample set before computing statistics. Defaults to false.
* @type {boolean}
* @private
*/
this.discardOutliers_ = false;
};
/**
* @return {number} The number of times the test function will be run.
*/
goog.testing.PerformanceTimer.prototype.getNumSamples = function() {
return this.numSamples_;
};
/**
* Sets the number of times the test function will be run.
* @param {number} numSamples Number of times to run the test function.
*/
goog.testing.PerformanceTimer.prototype.setNumSamples = function(numSamples) {
this.numSamples_ = numSamples;
};
/**
* @return {number} The number of milliseconds after which the test times out.
*/
goog.testing.PerformanceTimer.prototype.getTimeoutInterval = function() {
return this.timeoutInterval_;
};
/**
* Sets the number of milliseconds after which the test times out.
* @param {number} timeoutInterval Timeout interval in ms.
*/
goog.testing.PerformanceTimer.prototype.setTimeoutInterval = function(
timeoutInterval) {
this.timeoutInterval_ = timeoutInterval;
};
/**
* Sets whether to ignore the smallest and the largest values when computing
* stats.
* @param {boolean} discard Whether to discard outlier values.
*/
goog.testing.PerformanceTimer.prototype.setDiscardOutliers = function(discard) {
this.discardOutliers_ = discard;
};
/**
* @return {boolean} Whether outlier values are discarded prior to computing
* stats.
*/
goog.testing.PerformanceTimer.prototype.isDiscardOutliers = function() {
return this.discardOutliers_;
};
/**
* Executes the test function the required number of times (or until the
* test run exceeds the timeout interval, whichever comes first). Returns
* an object containing the following:
* <pre>
* {
* 'average': average execution time (ms)
* 'count': number of executions (may be fewer than expected due to timeout)
* 'maximum': longest execution time (ms)
* 'minimum': shortest execution time (ms)
* 'standardDeviation': sample standard deviation (ms)
* 'total': total execution time (ms)
* }
* </pre>
*
* @param {Function} testFn Test function whose performance is to
* be measured.
* @return {Object} Object containing performance stats.
*/
goog.testing.PerformanceTimer.prototype.run = function(testFn) {
return this.runTask(new goog.testing.PerformanceTimer.Task(
/** @type {goog.testing.PerformanceTimer.TestFunction} */ (testFn)));
};
/**
* Executes the test function of the specified task as described in
* {@code run}. In addition, if specified, the set up and tear down functions of
* the task are invoked before and after each invocation of the test function.
* @see goog.testing.PerformanceTimer#run
* @param {goog.testing.PerformanceTimer.Task} task A task describing the test
* function to invoke.
* @return {Object} Object containing performance stats.
*/
goog.testing.PerformanceTimer.prototype.runTask = function(task) {
var samples = [];
var testStart = goog.now();
var totalRunTime = 0;
var testFn = task.getTest();
var setUpFn = task.getSetUp();
var tearDownFn = task.getTearDown();
for (var i = 0; i < this.numSamples_ && totalRunTime <= this.timeoutInterval_;
i++) {
setUpFn();
var sampleStart = goog.now();
testFn();
var sampleEnd = goog.now();
tearDownFn();
samples[i] = sampleEnd - sampleStart;
totalRunTime = sampleEnd - testStart;
}
return this.finishTask_(samples);
};
/**
* Finishes the run of a task by creating a result object from samples, in the
* format described in {@code run}.
* @see goog.testing.PerformanceTimer#run
* @return {Object} Object containing performance stats.
* @private
*/
goog.testing.PerformanceTimer.prototype.finishTask_ = function(samples) {
if (this.discardOutliers_ && samples.length > 2) {
goog.array.remove(samples, Math.min.apply(null, samples));
goog.array.remove(samples, Math.max.apply(null, samples));
}
return goog.testing.PerformanceTimer.createResults(samples);
};
/**
* Executes the test function of the specified task asynchronously. The test
* function is expected to take a callback as input and has to call it to signal
* that it's done. In addition, if specified, the setUp and tearDown functions
* of the task are invoked before and after each invocation of the test
* function. Note that setUp/tearDown functions take a callback as input and
* must call this callback when they are done.
* @see goog.testing.PerformanceTimer#run
* @param {goog.testing.PerformanceTimer.Task} task A task describing the test
* function to invoke.
* @return {!goog.async.Deferred} The deferred result, eventually an object
* containing performance stats.
*/
goog.testing.PerformanceTimer.prototype.runAsyncTask = function(task) {
var samples = [];
var testStart = goog.now();
var testFn = task.getTest();
var setUpFn = task.getSetUp();
var tearDownFn = task.getTearDown();
// Note that this uses a separate code path from runTask() because
// implementing runTask() in terms of runAsyncTask() could easily cause
// a stack overflow if there are many iterations.
var result = new goog.async.Deferred();
this.runAsyncTaskSample_(testFn, setUpFn, tearDownFn, result, samples,
testStart);
return result;
};
/**
* Runs a task once, waits for the test function to complete asynchronously
* and starts another run if not enough samples have been collected. Otherwise
* finishes this task.
* @param {goog.testing.PerformanceTimer.TestFunction} testFn The test function.
* @param {goog.testing.PerformanceTimer.TestFunction} setUpFn The set up
* function that will be called once before the test function is run.
* @param {goog.testing.PerformanceTimer.TestFunction} tearDownFn The set up
* function that will be called once after the test function completed.
* @param {!goog.async.Deferred} result The deferred result, eventually an
* object containing performance stats.
* @param {!Array.<number>} samples The time samples from all runs of the test
* function so far.
* @param {number} testStart The timestamp when the first sample was started.
* @private
*/
goog.testing.PerformanceTimer.prototype.runAsyncTaskSample_ = function(testFn,
setUpFn, tearDownFn, result, samples, testStart) {
var timer = this;
timer.handleOptionalDeferred_(setUpFn, function() {
var sampleStart = goog.now();
timer.handleOptionalDeferred_(testFn, function() {
var sampleEnd = goog.now();
timer.handleOptionalDeferred_(tearDownFn, function() {
samples.push(sampleEnd - sampleStart);
var totalRunTime = sampleEnd - testStart;
if (samples.length < timer.numSamples_ &&
totalRunTime <= timer.timeoutInterval_) {
timer.runAsyncTaskSample_(testFn, setUpFn, tearDownFn, result,
samples, testStart);
} else {
result.callback(timer.finishTask_(samples));
}
});
});
});
};
/**
* Execute a function that optionally returns a deferred object and continue
* with the given continuation function only once the deferred object has a
* result.
* @param {goog.testing.PerformanceTimer.TestFunction} deferredFactory The
* function that optionally returns a deferred object.
* @param {function()} continuationFunction The function that should be called
* after the optional deferred has a result.
* @private
*/
goog.testing.PerformanceTimer.prototype.handleOptionalDeferred_ = function(
deferredFactory, continuationFunction) {
var deferred = deferredFactory();
if (deferred) {
deferred.addCallback(continuationFunction);
} else {
continuationFunction();
}
};
/**
* Creates a performance timer results object by analyzing a given array of
* sample timings.
* @param {Array.<number>} samples The samples to analyze.
* @return {Object} Object containing performance stats.
*/
goog.testing.PerformanceTimer.createResults = function(samples) {
return {
'average': goog.math.average.apply(null, samples),
'count': samples.length,
'maximum': Math.max.apply(null, samples),
'minimum': Math.min.apply(null, samples),
'standardDeviation': goog.math.standardDeviation.apply(null, samples),
'total': goog.math.sum.apply(null, samples)
};
};
/**
* A test function whose performance should be measured or a setUp/tearDown
* function. It may optionally return a deferred object. If it does so, the
* test harness will assume the function is asynchronous and it must signal
* that it's done by setting an (empty) result on the deferred object. If the
* function doesn't return anything, the test harness will assume it's
* synchronous.
* @typedef {function():(goog.async.Deferred|undefined)}
*/
goog.testing.PerformanceTimer.TestFunction;
/**
* A task for the performance timer to measure. Callers can specify optional
* setUp and tearDown methods to control state before and after each run of the
* test function.
* @param {goog.testing.PerformanceTimer.TestFunction} test Test function whose
* performance is to be measured.
* @constructor
*/
goog.testing.PerformanceTimer.Task = function(test) {
/**
* The test function to time.
* @type {goog.testing.PerformanceTimer.TestFunction}
* @private
*/
this.test_ = test;
};
/**
* An optional set up function to run before each invocation of the test
* function.
* @type {goog.testing.PerformanceTimer.TestFunction}
* @private
*/
goog.testing.PerformanceTimer.Task.prototype.setUp_ = goog.nullFunction;
/**
* An optional tear down function to run after each invocation of the test
* function.
* @type {goog.testing.PerformanceTimer.TestFunction}
* @private
*/
goog.testing.PerformanceTimer.Task.prototype.tearDown_ = goog.nullFunction;
/**
* @return {goog.testing.PerformanceTimer.TestFunction} The test function to
* time.
*/
goog.testing.PerformanceTimer.Task.prototype.getTest = function() {
return this.test_;
};
/**
* Specifies a set up function to be invoked before each invocation of the test
* function.
* @param {goog.testing.PerformanceTimer.TestFunction} setUp The set up
* function.
* @return {goog.testing.PerformanceTimer.Task} This task.
*/
goog.testing.PerformanceTimer.Task.prototype.withSetUp = function(setUp) {
this.setUp_ = setUp;
return this;
};
/**
* @return {goog.testing.PerformanceTimer.TestFunction} The set up function or
* the default no-op function if none was specified.
*/
goog.testing.PerformanceTimer.Task.prototype.getSetUp = function() {
return this.setUp_;
};
/**
* Specifies a tear down function to be invoked after each invocation of the
* test function.
* @param {goog.testing.PerformanceTimer.TestFunction} tearDown The tear down
* function.
* @return {goog.testing.PerformanceTimer.Task} This task.
*/
goog.testing.PerformanceTimer.Task.prototype.withTearDown = function(tearDown) {
this.tearDown_ = tearDown;
return this;
};
/**
* @return {goog.testing.PerformanceTimer.TestFunction} The tear down function
* or the default no-op function if none was specified.
*/
goog.testing.PerformanceTimer.Task.prototype.getTearDown = function() {
return this.tearDown_;
};
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.