diff options
Diffstat (limited to 'contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base')
215 files changed, 0 insertions, 71694 deletions
diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/abstractspellchecker.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/abstractspellchecker.js.svn-base deleted file mode 100644 index 62919f8..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/abstractspellchecker.js.svn-base +++ /dev/null @@ -1,1071 +0,0 @@ -// 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.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_ = 'goog-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; - - -/** - * Marker for the text that does not need to be included in the processing. - * - * For rich text editor this is the class name for the element. - * For plain text editor this is a RegExp that matches the excluded text. - * - * Used exclusively by the derived classes - * - * @type {RegExp|string|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. - */ -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; -}; - - -/** - * Sets the marker for the excluded text. - * - * {@see goog.ui.AbstractSpellChecker.prototype.excludeMarker_} - * - * @param {RegExp|string|null} marker RegExp for plain text or class name 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.wordElements_ = {}; - - 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_; -}; - - -/** - * 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. - * @private - */ -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.dom.a11y.setRole(el, 'menuitem'); - goog.dom.a11y.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. - * @private - */ -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 -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/activitymonitor.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/activitymonitor.js.svn-base deleted file mode 100644 index c7816c3..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/activitymonitor.js.svn-base +++ /dev/null @@ -1,286 +0,0 @@ -// 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. - * - * @constructor - * @extends {goog.events.EventTarget} - */ -goog.ui.ActivityMonitor = function(opt_domHelper) { - goog.events.EventTarget.call(this); - - /** - * Array of documents that are being listened to. - * @type {Array.<Document>} - * @private - */ - this.documents_ = []; - - /** - * 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.MOUSEUP, - goog.events.EventType.MOUSEMOVE]; - - -/** - * 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); - this.eventHandler_.listen( - doc, goog.ui.ActivityMonitor.userEventTypesDocuments_, - this.handleEvent_, true); - this.eventHandler_.listen( - doc, goog.ui.ActivityMonitor.userEventTypesBody_, - this.handleEvent_, true); -}; - - -/** - * 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); - this.eventHandler_.unlisten( - doc, goog.ui.ActivityMonitor.userEventTypesDocuments_, - this.handleEvent_, true); - this.eventHandler_.unlisten( - doc, goog.ui.ActivityMonitor.userEventTypesBody_, - this.handleEvent_, true); -}; - - -/** - * 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) { - this.updateIdleTime_(goog.now(), /** @type {string} */ (e.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'); -}; - - -/** - * Does the work of updating the idle time and firing an event - * @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. - * @private - */ -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_; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/activitymonitor_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/activitymonitor_test.html.svn-base deleted file mode 100644 index dbc43a1..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/activitymonitor_test.html.svn-base +++ /dev/null @@ -1,44 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2006 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.ActivityMonitor</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.ActivityMonitor'); -</script> -</head> -<body> -<script> - - // Override goog.now in order to test idle timer. - var testTime = 0; - goog.now = function() { - return testTime; - }; - - - function testIdle() { - var activityMonitor = new goog.ui.ActivityMonitor(); - assertEquals(activityMonitor.getLastEventTime(), 0); - - testTime = 1000; - activityMonitor.resetTimer(); - assertEquals(activityMonitor.getLastEventTime(), 1000); - assertEquals(activityMonitor.getIdleTime(), 0); - - testTime = 2000; - assertEquals(activityMonitor.getLastEventTime(), 1000); - assertEquals(activityMonitor.getIdleTime(), 1000); - } -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/advancedtooltip.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/advancedtooltip.js.svn-base deleted file mode 100644 index 5a9c283..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/advancedtooltip.js.svn-base +++ /dev/null @@ -1,370 +0,0 @@ -// 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 Advanced tooltip widget implementation. - * - * @author eae@google.com (Emil A Eklund) - * @see ../demos/advancedtooltip.html - */ - -goog.provide('goog.ui.AdvancedTooltip'); - -goog.require('goog.events.EventType'); -goog.require('goog.math.Coordinate'); -goog.require('goog.ui.Tooltip'); -goog.require('goog.userAgent'); - - - -/** - * Advanced tooltip widget with cursor tracking abilities. Works like a regular - * tooltip but can track the cursor position and direction to determine if the - * tooltip should be dismissed or remain open. - * - * @param {Element|string=} opt_el Element to display tooltip for, either - * element reference or string id. - * @param {?string=} opt_str Text message to display in tooltip. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Tooltip} - */ -goog.ui.AdvancedTooltip = function(opt_el, opt_str, opt_domHelper) { - goog.ui.Tooltip.call(this, opt_el, opt_str, goog.dom.isNodeLike(opt_el) ? - goog.dom.getDomHelper(/** @type {Node} */(opt_el)) : opt_domHelper); -}; -goog.inherits(goog.ui.AdvancedTooltip, goog.ui.Tooltip); - - -/** - * Whether to track the cursor and thereby close the tooltip if it moves away - * from the tooltip and keep it open if it moves towards it. - * - * @type {boolean} - * @private - */ -goog.ui.AdvancedTooltip.prototype.cursorTracking_ = false; - - -/** - * Delay in milliseconds before tooltips are hidden if cursor tracking is - * enabled and the cursor is moving away from the tooltip. - * - * @type {number} - * @private - */ -goog.ui.AdvancedTooltip.prototype.cursorTrackingHideDelayMs_ = 100; - - -/** - * Box object representing a margin around the tooltip where the cursor is - * allowed without dismissing the tooltip. - * - * @type {goog.math.Box} - * @private - */ -goog.ui.AdvancedTooltip.prototype.hotSpotPadding_; - - -/** - * Bounding box. - * - * @type {goog.math.Box} - * @private - */ -goog.ui.AdvancedTooltip.prototype.boundingBox_; - - -/** - * Bounding box including padding. If the cursor moves outside of it the tooltip - * is closed. - * Only used if a cursor padding has been specified. - * - * @type {goog.math.Box} - * @private - */ -goog.ui.AdvancedTooltip.prototype.paddingBox_; - - -/** - * Anchor bounding box. - * - * @type {goog.math.Box} - * @private - */ -goog.ui.AdvancedTooltip.prototype.anchorBox_; - - -/** - * Whether the cursor tracking is active. - * - * @type {boolean} - * @private - */ -goog.ui.AdvancedTooltip.prototype.tracking_ = false; - - -/** - * Sets margin around the tooltip where the cursor is allowed without dismissing - * the tooltip. - * - * @param {goog.math.Box=} opt_box The margin around the tooltip. - */ -goog.ui.AdvancedTooltip.prototype.setHotSpotPadding = function(opt_box) { - this.hotSpotPadding_ = opt_box || null; -}; - - -/** - * @return {goog.math.Box} box The margin around the tooltip where the cursor is - * allowed without dismissing the tooltip. - */ -goog.ui.AdvancedTooltip.prototype.getHotSpotPadding = function() { - return this.hotSpotPadding_; -}; - - -/** - * Sets whether to track the cursor and thereby close the tooltip if it moves - * away from the tooltip and keep it open if it moves towards it. - * - * @param {boolean} b Whether to track the cursor. - */ -goog.ui.AdvancedTooltip.prototype.setCursorTracking = function(b) { - this.cursorTracking_ = b; -}; - - -/** - * @return {boolean} Whether to track the cursor and thereby close the tooltip - * if it moves away from the tooltip and keep it open if it moves towards - * it. - */ -goog.ui.AdvancedTooltip.prototype.getCursorTracking = function() { - return this.cursorTracking_; -}; - - -/** - * Sets delay in milliseconds before tooltips are hidden if cursor tracking is - * enabled and the cursor is moving away from the tooltip. - * - * @param {number} delay The delay in milliseconds. - */ -goog.ui.AdvancedTooltip.prototype.setCursorTrackingHideDelayMs = - function(delay) { - this.cursorTrackingHideDelayMs_ = delay; -}; - - -/** - * @return {number} The delay in milliseconds before tooltips are hidden if - * cursor tracking is enabled and the cursor is moving away from the - * tooltip. - */ -goog.ui.AdvancedTooltip.prototype.getCursorTrackingHideDelayMs = function() { - return this.cursorTrackingHideDelayMs_; -}; - - -/** - * Called after the popup is shown. - * @protected - * @suppress {underscore} - * @override - */ -goog.ui.AdvancedTooltip.prototype.onShow_ = function() { - goog.ui.AdvancedTooltip.superClass_.onShow_.call(this); - - this.boundingBox_ = goog.style.getBounds(this.getElement()).toBox(); - if (this.anchor) { - this.anchorBox_ = goog.style.getBounds(this.anchor).toBox(); - } - - this.tracking_ = this.cursorTracking_; - goog.events.listen(this.getDomHelper().getDocument(), - goog.events.EventType.MOUSEMOVE, - this.handleMouseMove, false, this); -}; - - -/** - * Called after the popup is hidden. - * @protected - * @suppress {underscore} - * @override - */ -goog.ui.AdvancedTooltip.prototype.onHide_ = function() { - goog.events.unlisten(this.getDomHelper().getDocument(), - goog.events.EventType.MOUSEMOVE, - this.handleMouseMove, false, this); - - this.paddingBox_ = null; - this.boundingBox_ = null; - this.anchorBox_ = null; - this.tracking_ = false; - - goog.ui.AdvancedTooltip.superClass_.onHide_.call(this); -}; - - -/** - * Returns true if the mouse is in the tooltip. - * @return {boolean} True if the mouse is in the tooltip. - */ -goog.ui.AdvancedTooltip.prototype.isMouseInTooltip = function() { - return this.isCoordinateInTooltip(this.cursorPosition); -}; - - -/** - * Checks whether the supplied coordinate is inside the tooltip, including - * padding if any. - * @param {goog.math.Coordinate} coord Coordinate being tested. - * @return {boolean} Whether the coord is in the tooltip. - */ -goog.ui.AdvancedTooltip.prototype.isCoordinateInTooltip = function(coord) { - // Check if coord is inside the bounding box of the tooltip - if (this.paddingBox_) { - return this.paddingBox_.contains(coord); - } - - return goog.ui.AdvancedTooltip.superClass_.isCoordinateInTooltip.call(this, - coord); -}; - - -/** - * Checks if supplied coordinate is in the tooltip, its triggering anchor, or - * a tooltip that has been triggered by a child of this tooltip. - * Called from handleMouseMove to determine if hide timer should be started, - * and from maybeHide to determine if tooltip should be hidden. - * @param {goog.math.Coordinate} coord Coordinate being tested. - * @return {boolean} Whether coordinate is in the anchor, the tooltip, or any - * tooltip whose anchor is a child of this tooltip. - * @private - */ -goog.ui.AdvancedTooltip.prototype.isCoordinateActive_ = function(coord) { - if ((this.anchorBox_ && this.anchorBox_.contains(coord)) || - this.isCoordinateInTooltip(coord)) { - return true; - } - - // Check if mouse might be in active child element. - var childTooltip = this.getChildTooltip(); - return !!childTooltip && childTooltip.isCoordinateInTooltip(coord); -}; - - -/** - * Called by timer from mouse out handler. Hides tooltip if cursor is still - * outside element and tooltip. - * @param {Element} el Anchor when hide timer was started. - */ -goog.ui.AdvancedTooltip.prototype.maybeHide = function(el) { - this.hideTimer = undefined; - if (el == this.anchor) { - // Check if cursor is inside the bounding box of the tooltip or the element - // that triggered it, or if tooltip is active (possibly due to receiving - // the focus), or if there is a nested tooltip being shown. - if (!this.isCoordinateActive_(this.cursorPosition) && - !this.getActiveElement() && - !this.hasActiveChild()) { - // Under certain circumstances gecko fires ghost mouse events with the - // coordinates 0, 0 regardless of the cursors position. - if (goog.userAgent.GECKO && this.cursorPosition.x == 0 && - this.cursorPosition.y == 0) { - return; - } - this.setVisible(false); - } - } -}; - - -/** - * Handler for mouse move events. - * - * @param {goog.events.BrowserEvent} event Event object. - * @protected - */ -goog.ui.AdvancedTooltip.prototype.handleMouseMove = function(event) { - var startTimer = this.isVisible(); - if (this.boundingBox_) { - var scroll = this.getDomHelper().getDocumentScroll(); - var c = new goog.math.Coordinate(event.clientX + scroll.x, - event.clientY + scroll.y); - if (this.isCoordinateActive_(c)) { - startTimer = false; - } else if (this.tracking_) { - var prevDist = goog.math.Box.distance(this.boundingBox_, - this.cursorPosition); - var currDist = goog.math.Box.distance(this.boundingBox_, c); - startTimer = currDist >= prevDist; - } - } - - if (startTimer) { - this.startHideTimer(); - - // Even though the mouse coordinate is not on the tooltip (or nested child), - // they may have an active element because of a focus event. Don't let - // that prevent us from taking down the tooltip(s) on this mouse move. - this.setActiveElement(null); - var childTooltip = this.getChildTooltip(); - if (childTooltip) { - childTooltip.setActiveElement(null); - } - } else if (this.getState() == goog.ui.Tooltip.State.WAITING_TO_HIDE) { - this.clearHideTimer(); - } - - goog.ui.AdvancedTooltip.superClass_.handleMouseMove.call(this, event); -}; - - -/** - * Handler for mouse over events for the tooltip element. - * - * @param {goog.events.BrowserEvent} event Event object. - * @protected - */ -goog.ui.AdvancedTooltip.prototype.handleTooltipMouseOver = function(event) { - if (this.getActiveElement() != this.getElement()) { - this.tracking_ = false; - this.setActiveElement(this.getElement()); - - if (!this.paddingBox_ && this.hotSpotPadding_) { - this.paddingBox_ = this.boundingBox_.clone().expand(this.hotSpotPadding_); - } - } -}; - - -/** - * Override hide delay with cursor tracking hide delay while tracking. - * @return {number} Hide delay to use. - */ -goog.ui.AdvancedTooltip.prototype.getHideDelayMs = function() { - return this.tracking_ ? this.cursorTrackingHideDelayMs_ : - goog.base(this, 'getHideDelayMs'); -}; - - -/** - * Forces the recalculation of the hotspot on the next mouse over event. - */ -goog.ui.AdvancedTooltip.prototype.resetHotSpot = function() { - this.paddingBox_ = null; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/advancedtooltip_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/advancedtooltip_test.html.svn-base deleted file mode 100644 index fbaed5f..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/advancedtooltip_test.html.svn-base +++ /dev/null @@ -1,274 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.AdvancedTooltip</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.events.EventType'); - goog.require('goog.math.Box'); - goog.require('goog.math.Coordinate'); - goog.require('goog.style'); - goog.require('goog.testing.MockClock'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.AdvancedTooltip'); - goog.require('goog.userAgent'); - </script> -</head> -<body> - - -<p> - <span id="hovertarget">Hover Here For Popup - <span id="childtarget">Child of target</span> - </span> -</p> - -<p id="notpopup">Content</p> - -<script type="text/javascript"> - var att; - var clock; - var anchor; - var elsewhere; - var popup; - - var SHOWDELAY = 50; - var HIDEDELAY = 250; - var TRACKINGDELAY = 100; - - function isWindowTooSmall() { - // Firefox 3 fails if the window is too small. - return goog.userAgent.GECKO && - (window.innerWidth < 350 || window.innerHeight < 100); - } - - function setUp() { - popup = goog.dom.createDom('span', - {id: 'popup', style: 'position:absolute;top:300;left:300'}, 'Hello'); - att = new goog.ui.AdvancedTooltip('hovertarget'); - att.setElement(popup); - att.setCursorTracking(true); - att.setHotSpotPadding(new goog.math.Box(10, 10, 10, 10)); - att.setShowDelayMs(SHOWDELAY); - att.setHideDelayMs(HIDEDELAY); - att.setCursorTrackingHideDelayMs(TRACKINGDELAY); - att.setMargin(new goog.math.Box(300, 0, 0, 300)); - - clock = new goog.testing.MockClock(true); - - anchor = goog.dom.getElement('hovertarget'); - elsewhere = goog.dom.getElement('notpopup'); - } - - function tearDown() { - // tooltip needs to be hidden as well as disposed of so that it doesn't - // leave global state hanging around to trip up other tests. - if (att.isVisible()) { - att.onHide_(); - } - att.dispose(); - clock.uninstall(); - } - - function assertVisible(msg, element) { - if (element) { - assertEquals(msg, 'visible', element.style.visibility); - } else { - assertEquals('visible', msg.style.visibility); - } - } - - function assertHidden(msg, element) { - if (element) { - assertEquals(msg, 'hidden', element.style.visibility); - } else { - assertEquals('hidden', msg.style.visibility); - } - } - - /** - * Helper function to fire events related to moving a mouse from one element - * to another. Fires mouseout, mouseover, and mousemove event. - * @param {Element} from Element the mouse is moving from. - * @param {Element} to Element the mouse is moving to. - */ - function fireMouseEvents(from, to) { - goog.testing.events.fireMouseOutEvent(from, to); - goog.testing.events.fireMouseOverEvent(to, from); - var bounds = goog.style.getBounds(to); - goog.testing.events.fireMouseMoveEvent( - document, new goog.math.Coordinate(bounds.left + 1, bounds.top + 1)); - } - - function testCursorTracking() { - if (isWindowTooSmall()) { - return; - } - - var oneThirdOfTheWay, twoThirdsOfTheWay; - - oneThirdOfTheWay = new goog.math.Coordinate(100, 100); - twoThirdsOfTheWay = new goog.math.Coordinate(200, 200); - - goog.testing.events.fireMouseOverEvent(anchor, elsewhere); - clock.tick(SHOWDELAY); - assertVisible('Mouse over anchor should show popup', popup); - - goog.testing.events.fireMouseOutEvent(anchor, elsewhere); - goog.testing.events.fireMouseMoveEvent(document, oneThirdOfTheWay); - clock.tick(HIDEDELAY); - assertVisible("Moving mouse towards popup shouldn't hide it", popup); - - goog.testing.events.fireMouseMoveEvent(document, twoThirdsOfTheWay); - goog.testing.events.fireMouseMoveEvent(document, oneThirdOfTheWay); - clock.tick(TRACKINGDELAY); - assertHidden('Moving mouse away from popup should hide it', popup); - - goog.testing.events.fireMouseMoveEvent(document, twoThirdsOfTheWay); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.FOCUS, anchor)); - clock.tick(SHOWDELAY); - assertVisible('Set focus shows popup', popup); - goog.testing.events.fireMouseMoveEvent(document, oneThirdOfTheWay); - clock.tick(TRACKINGDELAY); - assertHidden('Mouse move after focus should hide popup', popup); - } - - function testPadding() { - if (isWindowTooSmall()) { - return; - } - - goog.testing.events.fireMouseOverEvent(anchor, elsewhere); - clock.tick(SHOWDELAY); - - var attBounds = goog.style.getBounds(popup); - var inPadding = new goog.math.Coordinate(attBounds.left - 5, - attBounds.top - 5); - var outOfPadding = new goog.math.Coordinate(attBounds.left - 15, - attBounds.top - 15); - - fireMouseEvents(anchor, popup); - goog.testing.events.fireMouseOutEvent(popup, elsewhere); - goog.testing.events.fireMouseMoveEvent(document, inPadding); - clock.tick(HIDEDELAY); - assertVisible("Mouse out of popup but within padding shouldn't hide it", - popup); - - goog.testing.events.fireMouseMoveEvent(document, outOfPadding); - clock.tick(HIDEDELAY); - assertHidden("Mouse move beyond popup padding should hide it", popup); - } - - - function testAnchorWithChild() { - var child = goog.dom.getElement('childtarget'); - - fireMouseEvents(elsewhere, anchor); - fireMouseEvents(anchor, child); - clock.tick(SHOWDELAY); - assertVisible('Mouse into child of anchor should still show popup', popup); - - fireMouseEvents(child, anchor); - clock.tick(HIDEDELAY); - assertVisible('Mouse from child to anchor should still show popup', popup); - } - - function testNestedTooltip() { - if (!isWindowTooSmall()) { - checkNestedTooltips(false); - } - } - - function testNestedAdvancedTooltip() { - if (!isWindowTooSmall()) { - checkNestedTooltips(true); - } - } - - function checkNestedTooltips(useAdvancedTooltip) { - popup.appendChild(goog.dom.createDom( - 'span', {id: 'nestedAnchor'}, 'Nested Anchor')); - var nestedAnchor = goog.dom.getElement('nestedAnchor'); - var nestedTooltip; - if (useAdvancedTooltip) { - nestedTooltip = new goog.ui.AdvancedTooltip(nestedAnchor, 'popup'); - } else { - nestedTooltip = new goog.ui.Tooltip(nestedAnchor, 'popup'); - } - var nestedPopup = nestedTooltip.getElement(); - nestedTooltip.setShowDelayMs(SHOWDELAY); - nestedTooltip.setHideDelayMs(HIDEDELAY); - - fireMouseEvents(elsewhere, anchor); - clock.tick(SHOWDELAY); - fireMouseEvents(anchor, popup); - fireMouseEvents(popup, nestedAnchor); - clock.tick(SHOWDELAY + HIDEDELAY); - assertVisible('Mouse into nested anchor should show popup', nestedPopup); - assertVisible('Mouse into nested anchor should not hide parent', popup); - fireMouseEvents(nestedAnchor, elsewhere); - clock.tick(HIDEDELAY); - assertHidden('Mouse out of nested popup should hide it', nestedPopup); - clock.tick(HIDEDELAY); - assertHidden('Mouse out of nested popup should eventually hide parent', - popup); - - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.FOCUS, anchor)); - clock.tick(SHOWDELAY); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.BLUR, anchor)); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.FOCUS, nestedAnchor)); - clock.tick(SHOWDELAY + HIDEDELAY); - assertVisible("Moving focus to child anchor doesn't hide parent", popup); - assertVisible('Set focus shows nested popup', nestedPopup); - - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.BLUR, nestedAnchor)); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.FOCUS, anchor)); - clock.tick(HIDEDELAY + HIDEDELAY); - assertHidden('Lose focus hides nested popup', nestedPopup); - assertVisible( - "Moving focus from nested anchor to parent doesn't hide parent", popup); - - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.BLUR, anchor)); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.FOCUS, nestedAnchor)); - clock.tick(SHOWDELAY); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.BLUR, nestedAnchor)); - clock.tick(HIDEDELAY); - assertHidden('Lose focus hides nested popup', nestedPopup); - clock.tick(HIDEDELAY); - assertHidden('Nested anchor losing focus hides parent', popup); - - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.FOCUS, anchor)); - clock.tick(SHOWDELAY); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.BLUR, anchor)); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.FOCUS, nestedAnchor)); - clock.tick(SHOWDELAY); - var coordElsewhere = new goog.math.Coordinate(1, 1); - goog.testing.events.fireMouseMoveEvent(document, coordElsewhere); - clock.tick(HIDEDELAY); - assertHidden('Mouse move should hide parent with active child', popup); - assertHidden('Mouse move should hide nested popup', nestedPopup); - } -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/animatedzippy.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/animatedzippy.js.svn-base deleted file mode 100644 index 088352b..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/animatedzippy.js.svn-base +++ /dev/null @@ -1,195 +0,0 @@ -// 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. - */ -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)); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/animatedzippy_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/animatedzippy_test.html.svn-base deleted file mode 100644 index 8f3f375..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/animatedzippy_test.html.svn-base +++ /dev/null @@ -1,137 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2011 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.AnimatedZippy</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.dom.a11y'); - goog.require('goog.dom.a11y.State'); - goog.require('goog.events'); - goog.require('goog.functions'); - goog.require('goog.fx.Animation'); - goog.require('goog.fx.Transition.EventType'); - goog.require('goog.testing.PropertyReplacer'); - goog.require('goog.testing.asserts'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.AnimatedZippy'); - goog.require('goog.ui.Zippy.Events'); - </script> - <style type="text/css"> - - .demo { - border: solid 1px red; - margin: 0 0 20px 0; - } - - .demo h2 { - background-color: yellow; - border: solid 1px #ccc; - padding: 2px; - margin: 0; - fint-size: 100%; - } - - .demo div { - border: solid 1px #ccc; - padding: 2px; - } - - </style> -</head> -<body> - - -<div class="demo" id="d1"> - - <h2 id="t1">handler</h2> - - <div id="c1"> - sem. Suspendisse porta felis ac ipsum. Sed tincidunt dui vitae nulla. Ut - blandit. Nunc non neque. Mauris placerat. Vestibulum mollis tellus id dolor. - Phasellus ac dolor molestie nunc euismod aliquam. Mauris tellus ipsum, - fringilla id, tincidunt eu, vestibulum sit amet, metus. Quisque congue - varius - ligula. Quisque ornare mollis enim. Aliquam erat volutpat. Nulla mattis - venenatis magna. - </div> -</div> - - -<script> - - var animatedZippy; - var animatedZippyHeaderEl; - var propertyReplacer; - - function setUp() { - animatedZippyHeaderEl = goog.dom.getElement('t1'); - animatedZippy = new goog.ui.AnimatedZippy(animatedZippyHeaderEl, - goog.dom.getElement('c1')); - - propertyReplacer = new goog.testing.PropertyReplacer(); - } - - function tearDown() { - propertyReplacer.reset(); - animatedZippy.dispose(); - } - - function testConstructor() { - assertNotNull('must not be null', animatedZippy); - } - - function testExpandCollapse() { - var animationsPlayed = 0; - var toggleEventsFired = 0; - - propertyReplacer.replace(goog.fx.Animation.prototype, 'play', function() { - animationsPlayed++; - this.dispatchAnimationEvent(goog.fx.Transition.EventType.END); - }); - propertyReplacer.replace(goog.ui.AnimatedZippy.prototype, 'onAnimate_', - goog.functions.NULL); - - goog.events.listenOnce(animatedZippy, goog.ui.Zippy.Events.TOGGLE, - function(e) { - toggleEventsFired++; - assertTrue('TOGGLE event must be for expansion', e.expanded); - assertEquals('expanded must be true', true, - animatedZippy.isExpanded()); - assertEquals('aria-expanded must be true', 'true', - goog.dom.a11y.getState(animatedZippyHeaderEl, - goog.dom.a11y.State.EXPANDED)); - }); - - animatedZippy.expand(); - - goog.events.listenOnce(animatedZippy, goog.ui.Zippy.Events.TOGGLE, - function(e) { - toggleEventsFired++; - assertFalse('TOGGLE event must be for collapse', e.expanded); - assertEquals('expanded must be false', false, - animatedZippy.isExpanded()); - assertEquals('aria-expanded must be false', 'false', - goog.dom.a11y.getState(animatedZippyHeaderEl, - goog.dom.a11y.State.EXPANDED)); - }); - - animatedZippy.collapse(); - - assertEquals('animations must play', 2, animationsPlayed); - assertEquals('TOGGLE events must fire', 2, toggleEventsFired); - } - -</script> - -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/attachablemenu.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/attachablemenu.js.svn-base deleted file mode 100644 index ae75ab9..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/attachablemenu.js.svn-base +++ /dev/null @@ -1,464 +0,0 @@ -// 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 AttachableMenu class. - * - */ - -goog.provide('goog.ui.AttachableMenu'); - -goog.require('goog.dom.a11y'); -goog.require('goog.dom.a11y.State'); -goog.require('goog.events.KeyCodes'); -goog.require('goog.ui.ItemEvent'); -goog.require('goog.ui.MenuBase'); - - - -/** - * An implementation of a menu that can attach itself to DOM element that - * are annotated appropriately. - * - * The following attributes are used by the AttachableMenu - * - * menu-item - Should be set on DOM elements that function as items in the - * menu that can be selected. - * classNameSelected - A class that will be added to the element's class names - * when the item is selected via keyboard or mouse. - * - * @param {Element=} opt_element A DOM element for the popup. - * @constructor - * @extends {goog.ui.MenuBase} - * @deprecated Use goog.ui.PopupMenu. - */ -goog.ui.AttachableMenu = function(opt_element) { - goog.ui.MenuBase.call(this, opt_element); -}; -goog.inherits(goog.ui.AttachableMenu, goog.ui.MenuBase); - - -/** - * The currently selected element (mouse was moved over it or keyboard arrows) - * @type {Element} - * @private - */ -goog.ui.AttachableMenu.prototype.selectedElement_ = null; - - -/** - * Class name to append to a menu item's class when it's selected - * @type {string} - * @private - */ -goog.ui.AttachableMenu.prototype.itemClassName_ = 'menu-item'; - - -/** - * Class name to append to a menu item's class when it's selected - * @type {string} - * @private - */ -goog.ui.AttachableMenu.prototype.selectedItemClassName_ = 'menu-item-selected'; - - -/** - * Keep track of when the last key was pressed so that a keydown-scroll doesn't - * trigger a mouseover event - * @type {number} - * @private - */ -goog.ui.AttachableMenu.prototype.lastKeyDown_ = goog.now(); - - -/** @override */ -goog.ui.AttachableMenu.prototype.disposeInternal = function() { - goog.ui.AttachableMenu.superClass_.disposeInternal.call(this); - this.selectedElement_ = null; -}; - - -/** - * Sets the class name to use for menu items - * - * @return {string} The class name to use for items. - */ -goog.ui.AttachableMenu.prototype.getItemClassName = function() { - return this.itemClassName_; -}; - - -/** - * Sets the class name to use for menu items - * - * @param {string} name The class name to use for items. - */ -goog.ui.AttachableMenu.prototype.setItemClassName = function(name) { - this.itemClassName_ = name; -}; - - -/** - * Sets the class name to use for selected menu items - * todo(user) - reevaluate if we can simulate pseudo classes in IE - * - * @return {string} The class name to use for selected items. - */ -goog.ui.AttachableMenu.prototype.getSelectedItemClassName = function() { - return this.selectedItemClassName_; -}; - - -/** - * Sets the class name to use for selected menu items - * todo(user) - reevaluate if we can simulate pseudo classes in IE - * - * @param {string} name The class name to use for selected items. - */ -goog.ui.AttachableMenu.prototype.setSelectedItemClassName = function(name) { - this.selectedItemClassName_ = name; -}; - - -/** - * Returns the selected item - * - * @return {Element} The item selected or null if no item is selected. - */ -goog.ui.AttachableMenu.prototype.getSelectedItem = function() { - return this.selectedElement_; -}; - - -/** - * Sets the specified item as the selected element. - * - * @param {Element} elt The item to select. The type of this item is specific - * to the menu class. - */ -goog.ui.AttachableMenu.prototype.setSelectedItem = function(elt) { - if (this.selectedElement_) { - goog.dom.classes.remove(this.selectedElement_, this.selectedItemClassName_); - } - - this.selectedElement_ = elt; - - var el = this.getElement(); - if (this.selectedElement_) { - goog.dom.classes.add(this.selectedElement_, this.selectedItemClassName_); - - if (elt.id) { - // Update activedescendant to reflect the new selection. ARIA roles for - // menu and menuitem can be set statically (thru Soy templates, for - // example) whereas this needs to be updated as the selection changes. - goog.dom.a11y.setState(el, - goog.dom.a11y.State.ACTIVEDESCENDANT, - elt.id); - } - - var top = this.selectedElement_.offsetTop; - var height = this.selectedElement_.offsetHeight; - var scrollTop = el.scrollTop; - var scrollHeight = el.offsetHeight; - - // If the menu is scrollable this scrolls the selected item into view - // (this has no effect when the menu doesn't scroll) - if (top < scrollTop) { - el.scrollTop = top; - } else if (top + height > scrollTop + scrollHeight) { - el.scrollTop = top + height - scrollHeight; - } - } else { - // Clear off activedescendant to reflect no selection. - goog.dom.a11y.setState(el, - goog.dom.a11y.State.ACTIVEDESCENDANT, - ''); - } -}; - - -/** @override */ -goog.ui.AttachableMenu.prototype.showPopupElement = function() { - // The scroll position cannot be set for hidden (display: none) elements in - // gecko browsers. - var el = /** @type {Element} */ (this.getElement()); - goog.style.showElement(el, true); - el.scrollTop = 0; - el.style.visibility = 'visible'; -}; - - -/** - * Called after the menu is shown. - * @protected - * @suppress {underscore} - * @override - */ -goog.ui.AttachableMenu.prototype.onShow_ = function() { - goog.ui.AttachableMenu.superClass_.onShow_.call(this); - - // In IE, focusing the menu causes weird scrolling to happen. Focusing the - // first child makes the scroll behavior better, and the key handling still - // works. In FF, focusing the first child causes us to lose key events, so we - // still focus the menu. - var el = this.getElement(); - goog.userAgent.IE ? el.firstChild.focus() : - el.focus(); -}; - - -/** - * Returns the next or previous item. Used for up/down arrows. - * - * @param {boolean} prev True to go to the previous element instead of next. - * @return {Element} The next or previous element. - * @protected - */ -goog.ui.AttachableMenu.prototype.getNextPrevItem = function(prev) { - // first find the index of the next element - var elements = this.getElement().getElementsByTagName('*'); - var elementCount = elements.length; - var index; - // if there is a selected element, find its index and then inc/dec by one - if (this.selectedElement_) { - for (var i = 0; i < elementCount; i++) { - if (elements[i] == this.selectedElement_) { - index = prev ? i - 1 : i + 1; - break; - } - } - } - - // if no selected element, start from beginning or end - if (!goog.isDef(index)) { - index = prev ? elementCount - 1 : 0; - } - - // iterate forward or backwards through the elements finding the next - // menu item - for (var i = 0; i < elementCount; i++) { - var multiplier = prev ? -1 : 1; - var nextIndex = index + (multiplier * i) % elementCount; - - // if overflowed/underflowed, wrap around - if (nextIndex < 0) { - nextIndex += elementCount; - } else if (nextIndex >= elementCount) { - nextIndex -= elementCount; - } - - if (this.isMenuItem_(elements[nextIndex])) { - return elements[nextIndex]; - } - } - return null; -}; - - -/** - * Mouse over handler for the menu. - * @param {goog.events.Event} e The event object. - * @protected - */ -goog.ui.AttachableMenu.prototype.onMouseOver = function(e) { - var eltItem = this.getAncestorMenuItem_(/** @type {Element} */ (e.target)); - if (eltItem == null) { - return; - } - - // Stop the keydown triggering a mouseover in FF. - if (goog.now() - this.lastKeyDown_ > goog.ui.PopupBase.DEBOUNCE_DELAY_MS) { - this.setSelectedItem(eltItem); - } -}; - - -/** - * Mouse out handler for the menu. - * @param {goog.events.Event} e The event object. - * @protected - */ -goog.ui.AttachableMenu.prototype.onMouseOut = function(e) { - var eltItem = this.getAncestorMenuItem_(/** @type {Element} */ (e.target)); - if (eltItem == null) { - return; - } - - // Stop the keydown triggering a mouseout in FF. - if (goog.now() - this.lastKeyDown_ > goog.ui.PopupBase.DEBOUNCE_DELAY_MS) { - this.setSelectedItem(null); - } -}; - - -/** - * Mouse down handler for the menu. Prevents default to avoid text selection. - * @param {goog.events.Event} e The event object. - * @protected - */ -goog.ui.AttachableMenu.prototype.onMouseDown = goog.events.Event.preventDefault; - - -/** - * Mouse up handler for the menu. - * @param {goog.events.Event} e The event object. - * @protected - */ -goog.ui.AttachableMenu.prototype.onMouseUp = function(e) { - var eltItem = this.getAncestorMenuItem_(/** @type {Element} */ (e.target)); - if (eltItem == null) { - return; - } - this.setVisible(false); - this.onItemSelected_(eltItem); -}; - - -/** - * Key down handler for the menu. - * @param {goog.events.KeyEvent} e The event object. - * @protected - */ -goog.ui.AttachableMenu.prototype.onKeyDown = function(e) { - switch (e.keyCode) { - case goog.events.KeyCodes.DOWN: - this.setSelectedItem(this.getNextPrevItem(false)); - this.lastKeyDown_ = goog.now(); - break; - case goog.events.KeyCodes.UP: - this.setSelectedItem(this.getNextPrevItem(true)); - this.lastKeyDown_ = goog.now(); - break; - case goog.events.KeyCodes.ENTER: - if (this.selectedElement_) { - this.onItemSelected_(); - this.setVisible(false); - } - break; - case goog.events.KeyCodes.ESC: - this.setVisible(false); - break; - default: - if (e.charCode) { - var charStr = String.fromCharCode(e.charCode); - this.selectByName_(charStr, 1, true); - } - break; - } - // Prevent the browser's default keydown behaviour when the menu is open, - // e.g. keyboard scrolling. - e.preventDefault(); - - // Stop propagation to prevent application level keyboard shortcuts from - // firing. - e.stopPropagation(); - - this.dispatchEvent(e); -}; - - -/** - * Find an item that has the given prefix and select it. - * - * @param {string} prefix The entered prefix, so far. - * @param {number=} opt_direction 1 to search forward from the selection - * (default), -1 to search backward (e.g. to go to the previous match). - * @param {boolean=} opt_skip True if should skip the current selection, - * unless no other item has the given prefix. - * @private - */ -goog.ui.AttachableMenu.prototype.selectByName_ = - function(prefix, opt_direction, opt_skip) { - var elements = this.getElement().getElementsByTagName('*'); - var elementCount = elements.length; - var index; - - if (elementCount == 0) { - return; - } - - if (!this.selectedElement_ || - (index = goog.array.indexOf(elements, this.selectedElement_)) == -1) { - // no selection or selection isn't known => start at the beginning - index = 0; - } - - var start = index; - var re = new RegExp('^' + goog.string.regExpEscape(prefix), 'i'); - var skip = opt_skip && this.selectedElement_; - var dir = opt_direction || 1; - - do { - if (elements[index] != skip && this.isMenuItem_(elements[index])) { - var name = goog.dom.getTextContent(elements[index]); - if (name.match(re)) { - break; - } - } - index += dir; - if (index == elementCount) { - index = 0; - } else if (index < 0) { - index = elementCount - 1; - } - } while (index != start); - - if (this.selectedElement_ != elements[index]) { - this.setSelectedItem(elements[index]); - } -}; - - -/** - * Dispatch an ITEM_ACTION event when an item is selected - * @param {Object=} opt_item Item selected. - * @private - */ -goog.ui.AttachableMenu.prototype.onItemSelected_ = function(opt_item) { - this.dispatchEvent(new goog.ui.ItemEvent(goog.ui.MenuBase.Events.ITEM_ACTION, - this, opt_item || this.selectedElement_)); -}; - - -/** - * Returns whether the specified element is a menu item. - * @param {Element|undefined} elt The element to find a menu item ancestor of. - * @return {boolean} Whether the specified element is a menu item. - * @private - */ -goog.ui.AttachableMenu.prototype.isMenuItem_ = function(elt) { - return !!elt && goog.dom.classes.has(elt, this.itemClassName_); -}; - - -/** - * Returns the menu-item scoping the specified element, or null if there is - * none. - * @param {Element|undefined} elt The element to find a menu item ancestor of. - * @return {Element} The menu-item scoping the specified element, or null if - * there is none. - * @private - */ -goog.ui.AttachableMenu.prototype.getAncestorMenuItem_ = function(elt) { - if (elt) { - var ownerDocumentBody = goog.dom.getOwnerDocument(elt).body; - while (elt != null && elt != ownerDocumentBody) { - if (this.isMenuItem_(elt)) { - return elt; - } - elt = /** @type {Element} */ (elt.parentNode); - } - } - return null; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/basicmenu.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/basicmenu.js.svn-base deleted file mode 100644 index c72d641..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/basicmenu.js.svn-base +++ /dev/null @@ -1,930 +0,0 @@ -// 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 A basic menu that accepts a set of items. The ITEM_EVENT - * instead of returning the DOM node returns a reference to the menu item. - * - * NOTE: This class has been deprecated. Please use goog.ui.Menu, - * goog.ui.PopupMenu, and if you need submenus goog.ui.SubMenu. - * - * - */ - -goog.provide('goog.ui.BasicMenu'); -goog.provide('goog.ui.BasicMenu.Item'); -goog.provide('goog.ui.BasicMenu.Separator'); - -goog.require('goog.array'); -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.events.EventType'); -goog.require('goog.positioning'); -goog.require('goog.positioning.AnchoredPosition'); -goog.require('goog.positioning.Corner'); -goog.require('goog.ui.AttachableMenu'); -goog.require('goog.ui.ItemEvent'); - - - -/** - * Class that extends AttachableMenu and creates a simple menu, purely from - * code.The ITEM_EVENT instead of returning the DOM node returns a reference the - * menu item. - * - * @param {string=} opt_class Optional class for menu element, Default: 'menu'. - * @param {Element=} opt_parent Optional parent element, otherwise it will be - * added to the end of the document body. - * @constructor - * @extends {goog.ui.AttachableMenu} - */ -goog.ui.BasicMenu = function(opt_class, opt_parent) { - var cls = opt_class || 'menu'; - var parent = opt_parent || goog.dom.getDocument().body; - - /** - * Menu element - * @type {Element} - * @private - */ - this.element_ = goog.dom.createDom('div', {'tabIndex': 0, 'class': cls}); - - goog.dom.a11y.setRole(this.element_, 'menu'); - goog.dom.a11y.setState(this.element_, 'haspopup', true); - - parent.appendChild(this.element_); - goog.ui.AttachableMenu.call(this, this.element_); - - /** - * Parent menu - * @type {goog.ui.BasicMenu} - * @private - */ - this.parentMenu_ = null; - - /** - * Array of menu items - * @type {Array} - * @private - */ - this.items_ = []; - - /** - * The active item. - * @type {goog.ui.BasicMenu.Item} - * @private - */ - this.activeItem_; -}; -goog.inherits(goog.ui.BasicMenu, goog.ui.AttachableMenu); - - -/** - * Key for the event used to trigger the menu - * @type {?number} - * @private - */ -goog.ui.BasicMenu.prototype.evtKey_ = null; - - -/** - * Key for the window resize event listener - * @type {?number} - * @private - */ -goog.ui.BasicMenu.prototype.resizeEvtKey_ = null; - - -/** - * Z-index used for top level menu. - * @type {number} - * @private - */ -goog.ui.BasicMenu.prototype.zIndex_ = 10; - - -/** - * A time in ms used to delay opening/closing submenus when the selection - * changes. - * - * @type {number} - * @private - */ -goog.ui.BasicMenu.SUBMENU_ACTIVATION_DELAY_MS_ = 300; - - -/** - * @return {number} The z-index. - */ -goog.ui.BasicMenu.prototype.getZIndex = function() { - return this.zIndex_; -}; - - -/** - * Sets the z-index. The change will take effect the next time - * setVisible(true) is called. - * - * @param {number} zIndex The new z-index. - */ -goog.ui.BasicMenu.prototype.setZIndex = function(zIndex) { - this.zIndex_ = zIndex; -}; - - -/** - * Add a menu item. - * - * @param {goog.ui.BasicMenu.Item} item Menu Item. - */ -goog.ui.BasicMenu.prototype.add = function(item) { - var el = this.getElement(); - if (!el) { - throw Error('setElement() called before create()'); - } - if (item.getMenu()) { - throw Error('Menu item already added to a menu'); - } - - item.setMenu_(this); - this.items_.push(item); - el.appendChild(item.create()); -}; - - -/** - * Add a menu item at a specific index. - * @param {goog.ui.BasicMenu.Item} item Menu Item. - * @param {number} index The index to insert at. - */ -goog.ui.BasicMenu.prototype.insertAt = function(item, index) { - var el = this.getElement(); - if (!el) { - throw Error('setElement() called before create()'); - } - if (item.getMenu()) { - throw Error('Menu item already added to a menu'); - } - - item.setMenu_(this); - goog.array.insertAt(this.items_, item, index); - el.insertBefore(item.create(), el.childNodes[index]); -}; - - -/** - * Remove a menu item. - * @param {goog.ui.BasicMenu.Item} item Menu Item. - */ -goog.ui.BasicMenu.prototype.remove = function(item) { - item.remove(); - item.setMenu_(null); - goog.array.remove(this.items_, item); -}; - - -/** - * Remove a menu item from a particular index. - * @param {number} index Index of menu item to remove. - */ -goog.ui.BasicMenu.prototype.removeAt = function(index) { - this.remove(this.items_[index]); -}; - - -/** - * Sets focus to the menu's base element. - */ -goog.ui.BasicMenu.prototype.focus = function() { - this.element_.focus(); -}; - - -/** - * Sets menu's parent menu in case it's a submenu. - * @param {goog.ui.BasicMenu} parent Parent menu. - * @private - */ -goog.ui.BasicMenu.prototype.setParentMenu_ = function(parent) { - this.parentMenu_ = parent; - this.setParentEventTarget(parent); -}; - - -/** - * @return {goog.ui.BasicMenu} The menu's parent menu in case it's a submenu. - */ -goog.ui.BasicMenu.prototype.getParentMenu = function() { - return this.parentMenu_; -}; - - -/** - * Anchor the menu position to an element, and attach a click event. - * @param {Element} el Element to anchor menu to. - * @param {goog.positioning.Corner=} opt_pos Corner: Default Bottom-left. - * @param {goog.events.EventType=} opt_eventType Event that triggers menu. - * Default click. - */ -goog.ui.BasicMenu.prototype.setAnchorElement = function(el, opt_pos, - opt_eventType) { - if (this.evtKey_) { - goog.events.unlistenByKey(this.evtKey_); - } - - // Reset properties related to showing/hiding the menu as their state is only - // applicable when bound to the anchor element original triggering the menu. - if (this.anchorElement_ != el) { - this.clickToClose_ = false; - this.lastHideTime_ = -1; - } - - var eventType = opt_eventType || goog.events.EventType.CLICK; - this.evtKey_ = goog.events.listen(el, eventType, this.openMenu_, false, this); - this.resizeEvtKey_ = goog.events.listen(window, - goog.events.EventType.RESIZE, this.onResize_, false, this); - this.setPosition(new goog.positioning.AnchoredPosition(el, - goog.isDef(opt_pos) ? opt_pos : goog.positioning.Corner.BOTTOM_START)); - this.anchorElement_ = el; -}; - - -/** @override */ -goog.ui.BasicMenu.prototype.disposeInternal = function() { - for (var i = 0; i < this.items_.length; i++) { - this.items_[i].dispose(); - } - goog.events.unlistenByKey(this.evtKey_); - goog.events.unlistenByKey(this.resizeEvtKey_); - goog.dom.removeNode(this.element_); - delete this.element_; - this.anchorElement_ = null; - goog.ui.BasicMenu.superClass_.disposeInternal.call(this); -}; - - -/** - * Sets whether the popup should be visible. - * @param {boolean} visible Show menu?. -* @param {boolean=} opt_bubble Bubble to parent menu?. - */ -goog.ui.BasicMenu.prototype.setVisible = function(visible, opt_bubble) { - // Ignore setVisible(true) if already visible - if (this.isOrWasRecentlyVisible() && visible) { - return; - } - - if (visible == false) { - - // Close submenus recursively. goog.ui.BasicMenu.Item.closeSubmenu calls - // goog.ui.BasicMenu.setVisible(false) for the submenu. - if (this.activeItem_) { - this.activeItem_.closeSubmenu(); - goog.ui.AttachableMenu.prototype.setSelectedItem.call(this, null); - } - - // Set focus to parent for submenus. - if (this.parentMenu_ && !opt_bubble) { - this.parentMenu_.focus(); - } - } - else { - if (this.parentMenu_) { - this.zIndex_ = this.parentMenu_.getZIndex() + 1; - } - this.element_.style.zIndex = this.zIndex_; - } - - if (opt_bubble && this.parentMenu_) { - this.parentMenu_.setVisible(visible, opt_bubble); - } - - // Clear activation timer - if (this.activationTimer_) { - window.clearTimeout(this.activationTimer_); - this.activationTimer_ = null; - } - - this.activeItem_ = null; - goog.ui.PopupBase.prototype.setVisible.call(this, visible); -}; - - -/** - * Select menu item by index. - * @param {number} index Index of item to select, zero based. - */ -goog.ui.BasicMenu.prototype.setSelectedIndex = function(index) { - this.setSelectedItem(index == -1 ? null : this.element_.childNodes[index]); -}; - - -/** - * Select menu item by element reference and active it (open/close submenus) - * with a slight delay. - * @param {Element} el Element for item to select. - * @param {boolean=} opt_keyEvent Was item selected using keyboard? In that case - * open submenus are closed immediately and new submenus are not opened - * automatically. - * @private - */ -goog.ui.BasicMenu.prototype.itemSelectionHandler_ = function(el, opt_keyEvent) { - // Highlight menu item - if (el || !this.activeItem_ || !this.activeItem_.hasOpenSubmenu()) { - goog.ui.AttachableMenu.prototype.setSelectedItem.call(this, el); - } - - var item = el ? this.getItemForElement_(el) : null; - - if (item && item != this.activeItem_) { - - if (opt_keyEvent && this.activeItem_) { - this.activeItem_.closeSubmenu(); - this.activeItem_ = null; - } - - // Clear previous timer, if any - if (this.activationTimer_) { - window.clearTimeout(this.activationTimer_); - this.activationTimer_ = null; - } - - // Call selectItem_ with delay - if (!opt_keyEvent) { - this.activationTimer_ = window.setTimeout( - goog.bind(this.selectItem_, this, item), - goog.ui.BasicMenu.SUBMENU_ACTIVATION_DELAY_MS_); - } - - // Select anchor element in parent menu (to prevent submenu from closing). - if (this.parentMenu_) { - this.parentMenu_.setSelectedItem(this.anchorElement_); - this.element_.focus(); - } - } -}; - - -/** - * Select menu item by element reference and activate it immediately. - * @param {Element|goog.ui.BasicMenu.Item} arg Element Item to select or element - * for it. - */ -goog.ui.BasicMenu.prototype.setSelectedItem = function(arg) { - var el, item; - if (!arg) { - el = null; - item = null; - } else if (arg instanceof goog.ui.BasicMenu.Item) { - item = arg; - el = item.element_; - } else { - el = arg; - item = this.getItemForElement_(el); - } - - if (el || !this.activeItem_ || !this.activeItem_.hasOpenSubmenu()) { - goog.ui.AttachableMenu.prototype.setSelectedItem.call(this, el); - } - - if (item == this.activeItem_) { - return; - } - - if (this.activeItem_ && el) { - this.activeItem_.closeSubmenu(); - } - - if (el) { - // TODO(user): var item declared earlier - item = this.getItemForElement_(el); - if (item.hasSubmenu()) { - item.openSubmenu(); - item.getSubmenu().focus(); - } - this.activeItem_ = item; - } -}; - - -/** - * @return {goog.ui.BasicMenu.Item} The selected item. - */ -goog.ui.BasicMenu.prototype.getSelectedItem = function() { - return this.selectedElement_ ? this.items_[goog.array.indexOf( - this.element_.childNodes, this.selectedElement_)] : null; -}; - - -/** - * Select menu item, triggered by a delayed call from itemSelectionHandler_. - * Opens submenu associated with selected/active item and/or closes any other - * open submenus. - * @param {goog.ui.BasicMenu.Item} item Menu item to select. - * @private - */ -goog.ui.BasicMenu.prototype.selectItem_ = function(item) { - // Clear timer - if (this.activationTimer_) { - window.clearTimeout(this.activationTimer_); - this.activationTimer_ = null; - } - - var selectedItem = this.getItemForElement_(this.selectedElement_); - if (selectedItem != item) { - return; - } - - if (this.activeItem_ && item) { - this.activeItem_.closeSubmenu(); - } - - if (item.hasSubmenu()) { - item.openSubmenu(); - item.getSubmenu().focus(); - } - else { - this.element_.focus(); - } - - this.activeItem_ = item; -}; - - -/** - * Activates a menu item, opens submenu or triggers the select event and closes - * the menu if no submenu is available for item. - * @param {Element} el Element for item to activate. - * @private - */ -goog.ui.BasicMenu.prototype.activateItem_ = function(el) { - var item = this.getItemForElement_(el); - - if (item.hasSubmenu()) { - item.openSubmenu(); - var submenu = item.getSubmenu(); - submenu.focus(); - this.activeItem_ = item; - } - else { - this.setVisible(false, true); - this.dispatchEvent(new goog.ui.ItemEvent( - goog.ui.MenuBase.Events.ITEM_ACTION, this, item)); - } -}; - - -/** - * Anchor triggered, open menu unless it was just closed by the mousedown part - * of the click. - * - * @private - */ -goog.ui.BasicMenu.prototype.openMenu_ = function() { - if (!this.clickToClose_) { - this.setVisible(true); - } - this.clickToClose_ = false; -}; - - -/** - * Returns whether the specified element is contained inside the menu, including - * open submenus. - * @param {Element} el Element to check. - * @return {boolean} Whether the specified element is contained inside the menu, - * including open submenus. - * @private - */ -goog.ui.BasicMenu.prototype.containsElement_ = function(el) { - if (goog.dom.contains(this.element_, el)) { - return true; - } - - if (this.activeItem_ && this.activeItem_.hasSubmenu()) { - return this.activeItem_.getSubmenu().containsElement_(el); - } - - return false; -}; - - -/** - * Mouse down handler for the document on capture phase. Hides the menu. - * @param {goog.events.BrowserEvent} e The event object. - * @private - */ -goog.ui.BasicMenu.prototype.onDocumentMouseDown_ = function(e) { - // Mousedown on anchor element, set clickToClose_ to true to prevent the - // mouseup event from opening the menu. - if (this.anchorElement_ == e.target || - goog.dom.contains(this.anchorElement_, /** @type {Node} */ (e.target))) { - this.clickToClose_ = true; - } - - // Mousedown outside menu, close it. - var rootMenu = this; - while (rootMenu.parentMenu_) { - rootMenu = rootMenu.parentMenu_; - } - if (!rootMenu.containsElement_(/** @type {Element} */ (e.target))) { - this.hide_(); - } -}; - - -/** - * Mouse over handler for the menu. - * @param {goog.events.Event} e The event object. - * @protected - */ -goog.ui.BasicMenu.prototype.onMouseOver = function(e) { - var eltItem = this.getAncestorMenuItem_(/** @type {Element} */ (e.target)); - if (eltItem == null) { - return; - } - - this.itemSelectionHandler_(eltItem); -}; - - -/** - * Mouse out handler for the menu. - * @param {goog.events.Event} e The event object. - * @protected - */ -goog.ui.BasicMenu.prototype.onMouseOut = function(e) { - var eltItem = this.getAncestorMenuItem_(/** @type {Element} */ (e.target)); - if (eltItem == null) { - return; - } - - this.itemSelectionHandler_(null); -}; - - -/** - * Overloaded document focus handler. Prevents the default action which is to - * close the menu on focus change, which is not desirable for hierarchical - * menus. - * @param {goog.events.Event} e The event object. - * @private - */ -goog.ui.BasicMenu.prototype.onDocumentFocus_ = function(e) { - -}; - - -/** - * Mouse up handler for the menu. - * @param {goog.events.Event} e The event object. - * @protected - */ -goog.ui.BasicMenu.prototype.onMouseUp = function(e) { - var eltItem = this.getAncestorMenuItem_(/** @type {Element} */ (e.target)); - if (eltItem != null) { - this.activateItem_(eltItem); - } -}; - - -/** - * Window resize handler. - * @private - */ -goog.ui.BasicMenu.prototype.onResize_ = function() { - if (!this.isDisposed() && this.isVisible()) { - this.reposition(); - } -}; - - -/** - * Key down handler for the menu. - * @param {goog.events.KeyEvent} e The event object. - * @protected - */ -goog.ui.BasicMenu.prototype.onKeyDown = function(e) { - var handled = false; - - switch (e.keyCode) { - case 37: // Left - if (this.parentMenu_) { - this.setVisible(false); // setVisible(false) calls focus on the parent - } - handled = true; - break; - case 39: // Right - var item = this.getItemForElement_(this.selectedElement_); - if (this.selectedElement_ && item.hasSubmenu()) { - this.activateItem_(this.selectedElement_); - item.getSubmenu().setSelectedIndex(0); - } - handled = true; - break; - case 40: // Down - this.itemSelectionHandler_(this.getNextPrevItem(false), true); - handled = true; - break; - case 38: // Up - this.itemSelectionHandler_(this.getNextPrevItem(true), true); - handled = true; - break; - case 13: // Enter - if (this.selectedElement_) { - this.activateItem_(this.selectedElement_); - } - handled = true; - break; - case 27: // Esc - this.setVisible(false); - handled = true; - break; - } - - // Prevent the browser's default keydown behaviour when the menu is open, - // e.g. keyboard scrolling - if (handled) { - e.preventDefault(); - } -}; - - -/** - * Called after the menu is shown. - * @protected - * @suppress {underscore} - * @override - */ -goog.ui.BasicMenu.prototype.onShow_ = function() { - goog.ui.BasicMenu.superClass_.onShow_.call(this); - this.setSelectedItem(null); - - var rtl = goog.style.isRightToLeft(this.element_); - goog.dom.classes.enable(this.element_, goog.getCssName('goog-rtl'), rtl); - - if (!this.parentMenu_) { - this.element_.focus(); - } -}; - - -/** - * Returns the menu item a given element is associated with. - * @param {Element} el Element. - * @return {goog.ui.BasicMenu.Item} The menu item a given element is associated - * with. - * @private - */ -goog.ui.BasicMenu.prototype.getItemForElement_ = function(el) { - var index = -1; - for (var node = el; node; node = goog.dom.getPreviousElementSibling(node)) { - index++; - } - return index == -1 ? null : this.items_[index]; -}; - - - -/** - * A menu item - * - * @param {?string} caption Html caption that gets shown in the menu. - * @param {Object=} opt_value The value that gets returned in the ItemEvent. - * @param {goog.ui.BasicMenu=} opt_submenu Optional menu that this item is the - * anchor for. - * @constructor - * @extends {goog.Disposable} - */ -goog.ui.BasicMenu.Item = function(caption, opt_value, opt_submenu) { - goog.Disposable.call(this); - - /** - * HTML Caption that gets displayed in the menu - * @type {string} - * @private - */ - this.caption_ = String(caption); - - /** - * Value associated with the menu option. - * @type {*} - * @private - */ - this.value_ = opt_value || caption; - - /** - * Reference to the sub menu that this item is the anchor for. - * @type {goog.ui.BasicMenu} - * @private - */ - this.submenu_ = opt_submenu || null; - - /** - * Reference to the menu that this item is attached to. - * @type {goog.ui.BasicMenu} - * @private - */ - this.menu_ = null; - - /** - * Menu item element - * @type {Element} - * @private - */ - this.element_ = null; -}; -goog.inherits(goog.ui.BasicMenu.Item, goog.Disposable); - - -/** - * @return {string} The caption. - */ -goog.ui.BasicMenu.Item.prototype.getCaption = function() { - return this.caption_; -}; - - -/** - * @return {*} The value associated with menu item. - */ -goog.ui.BasicMenu.Item.prototype.getValue = function() { - return this.value_; -}; - - -/** - * Updates caption. - * @param {string} caption Desired caption. - */ -goog.ui.BasicMenu.Item.prototype.setCaption = function(caption) { - this.caption_ = caption; - if (this.element_) { - this.element_.firstChild.nodeValue = caption; - } -}; - - -/** - * Sets value associated with menu item. - * @param {Object} value Desired value. - */ -goog.ui.BasicMenu.Item.prototype.setValue = function(value) { - this.value_ = value; -}; - - -/** @override */ -goog.ui.BasicMenu.Item.prototype.disposeInternal = function() { - goog.ui.BasicMenu.Item.superClass_.disposeInternal.call(this); - this.remove(); - if (this.submenu_) { - this.submenu_.dispose(); - } -}; - - -/** - * Set the parent menu for this menu item. - * @param {goog.ui.BasicMenu} menu Parent menu. - * @private - */ -goog.ui.BasicMenu.Item.prototype.setMenu_ = function(menu) { - this.menu_ = menu; - if (this.submenu_) { - this.submenu_.setParentMenu_(menu); - } -}; - - -/** - * @return {goog.ui.BasicMenu} The parent menu for this menu item. - * @protected - */ -goog.ui.BasicMenu.Item.prototype.getMenu = function() { - return this.menu_; -}; - - -/** - * Returns the DOM element(s) for the menu item. Should be treated as package - * scope. - * @return {Element} The DOM element(s) for the menu item. - */ -goog.ui.BasicMenu.Item.prototype.create = function() { - if (!this.menu_) { - throw Error('MenuItem is not attached to a menu'); - } - var leftArrow, rightArrow; - if (this.submenu_) { - rightArrow = goog.dom.createDom('span', - goog.getCssName('goog-menu-arrow-right'), '\u25b6'); - leftArrow = goog.dom.createDom('span', - goog.getCssName('goog-menu-arrow-left'), '\u25c0'); - } - - this.element_ = goog.dom.createDom('div', this.menu_.getItemClassName(), - this.caption_, leftArrow, rightArrow); - - return this.element_; -}; - - -/** - * Removes DOM element(s) for item. - */ -goog.ui.BasicMenu.Item.prototype.remove = function() { - goog.dom.removeNode(this.element_); - this.element_ = null; -}; - - -/** - * @return {boolean} Whether the menu item has has submenu. - */ -goog.ui.BasicMenu.Item.prototype.hasSubmenu = function() { - return this.submenu_ != null; -}; - - -/** - * @return {boolean} Whether the menu item has has submenu that's open. - */ -goog.ui.BasicMenu.Item.prototype.hasOpenSubmenu = function() { - return this.hasSubmenu() ? this.submenu_.isOrWasRecentlyVisible() : false; -}; - - -/** - * @return {goog.ui.BasicMenu} The submenu associated with the item. - */ -goog.ui.BasicMenu.Item.prototype.getSubmenu = function() { - return this.submenu_; -}; - - -/** - * Opens the item's submenu. - */ -goog.ui.BasicMenu.Item.prototype.openSubmenu = function() { - if (this.submenu_) { - var submenu = this.submenu_; - - // If the submenu is pinned at a TOP position, infer - // that we want to anchor at the opposite corresponding - // absolute/relative horizontal position. - var pinComplement = goog.positioning.flipCornerHorizontal( - submenu.getPinnedCorner()); - submenu.setAnchorElement(this.element_, pinComplement); - submenu.setVisible(true); - } -}; - - -/** - * Closes the item's submenu. - */ -goog.ui.BasicMenu.Item.prototype.closeSubmenu = function() { - if (this.submenu_) { - this.submenu_.setVisible(false); - } -}; - - - -/** - * A menu separator - * - * @constructor - * @extends {goog.ui.BasicMenu.Item} - */ -goog.ui.BasicMenu.Separator = function() { - goog.ui.BasicMenu.Item.call(this, null); -}; -goog.inherits(goog.ui.BasicMenu.Separator, goog.ui.BasicMenu.Item); - - -/** - * Returns the DOM element(s) for the separator. Should be treated as having - * package scope. - * @return {Element} The DOM element(s) for the separator. - */ -goog.ui.BasicMenu.Separator.prototype.create = function() { - if (!this.menu_) { - throw Error('MenuSeparator is not attached to a menu'); - } - this.element_ = goog.dom.createElement('hr'); - goog.dom.a11y.setRole(this.element_, 'separator'); - return this.element_; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/bidiinput.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/bidiinput.js.svn-base deleted file mode 100644 index b540f07..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/bidiinput.js.svn-base +++ /dev/null @@ -1,165 +0,0 @@ -// 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 - */ -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 - */ -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. - * 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; - var dir = ''; // Default for no direction, inherit from document - if (goog.i18n.bidi.startsWithRtl(text) || - goog.i18n.bidi.startsWithLtr(text)) { - if (goog.i18n.bidi.detectRtlDirectionality(text)) { - dir = 'rtl'; - } else { - dir = 'ltr'; - } - } - element.dir = 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); - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/bubble.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/bubble.js.svn-base deleted file mode 100644 index 56baf2a..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/bubble.js.svn-base +++ /dev/null @@ -1,475 +0,0 @@ -// 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.dom'); -goog.require('goog.events'); -goog.require('goog.events.Event'); -goog.require('goog.events.EventType'); -goog.require('goog.math.Box'); -goog.require('goog.positioning'); -goog.require('goog.positioning.AbsolutePosition'); -goog.require('goog.positioning.AbstractPosition'); -goog.require('goog.positioning.AnchoredPosition'); -goog.require('goog.positioning.Corner'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.Popup'); -goog.require('goog.ui.Popup.AnchoredPosition'); - - - -/** - * 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 {?number} - * @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 4;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 -]; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/button.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/button.js.svn-base deleted file mode 100644 index ae20743..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/button.js.svn-base +++ /dev/null @@ -1,209 +0,0 @@ -// 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 button control. This implementation extends {@link - * goog.ui.Control}. - * - * @author attila@google.com (Attila Bodis) - * @see ../demos/button.html - */ - -goog.provide('goog.ui.Button'); -goog.provide('goog.ui.Button.Side'); - -goog.require('goog.events.KeyCodes'); -goog.require('goog.ui.ButtonRenderer'); -goog.require('goog.ui.ButtonSide'); -goog.require('goog.ui.Control'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.NativeButtonRenderer'); - - - -/** - * A button control, rendered as a native browser button by default. - * - * @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.NativeButtonRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for - * document interaction. - * @constructor - * @extends {goog.ui.Control} - */ -goog.ui.Button = function(content, opt_renderer, opt_domHelper) { - goog.ui.Control.call(this, content, opt_renderer || - goog.ui.NativeButtonRenderer.getInstance(), opt_domHelper); -}; -goog.inherits(goog.ui.Button, goog.ui.Control); - - -/** - * Constants for button sides, see {@link goog.ui.Button.prototype.setCollapsed} - * for details. Aliased from goog.ui.ButtonSide to support legacy users without - * creating a circular dependency in {@link goog.ui.ButtonRenderer}. - * @enum {number} - * @deprecated use {@link goog.ui.ButtonSide} instead. - */ -goog.ui.Button.Side = goog.ui.ButtonSide; - - -/** - * Value associated with the button. - * @type {*} - * @private - */ -goog.ui.Button.prototype.value_; - - -/** - * Tooltip text for the button, displayed on hover. - * @type {string|undefined} - * @private - */ -goog.ui.Button.prototype.tooltip_; - - -// goog.ui.Button API implementation. - - -/** - * Returns the value associated with the button. - * @return {*} Button value (undefined if none). - */ -goog.ui.Button.prototype.getValue = function() { - return this.value_; -}; - - -/** - * Sets the value associated with the button, and updates its DOM. - * @param {*} value New button value. - */ -goog.ui.Button.prototype.setValue = function(value) { - this.value_ = value; - this.getRenderer().setValue(this.getElement(), value); -}; - - -/** - * Sets the value associated with the button. Unlike {@link #setValue}, - * doesn't update the button's DOM. Considered protected; to be called only - * by renderer code during element decoration. - * @param {*} value New button value. - * @protected - */ -goog.ui.Button.prototype.setValueInternal = function(value) { - this.value_ = value; -}; - - -/** - * Returns the tooltip for the button. - * @return {string|undefined} Tooltip text (undefined if none). - */ -goog.ui.Button.prototype.getTooltip = function() { - return this.tooltip_; -}; - - -/** - * Sets the tooltip for the button, and updates its DOM. - * @param {string} tooltip New tooltip text. - */ -goog.ui.Button.prototype.setTooltip = function(tooltip) { - this.tooltip_ = tooltip; - this.getRenderer().setTooltip(this.getElement(), tooltip); -}; - - -/** - * Sets the tooltip for the button. Unlike {@link #setTooltip}, doesn't update - * the button's DOM. Considered protected; to be called only by renderer code - * during element decoration. - * @param {string} tooltip New tooltip text. - * @protected - */ -goog.ui.Button.prototype.setTooltipInternal = function(tooltip) { - this.tooltip_ = tooltip; -}; - - -/** - * Collapses the border on one or both sides of the button, allowing it to be - * combined with the adjancent button(s), forming a single UI componenet with - * multiple targets. - * @param {number} sides Bitmap of one or more {@link goog.ui.ButtonSide}s for - * which borders should be collapsed. - */ -goog.ui.Button.prototype.setCollapsed = function(sides) { - this.getRenderer().setCollapsed(this, sides); -}; - - -// goog.ui.Control & goog.ui.Component API implementation. - - -/** @override */ -goog.ui.Button.prototype.disposeInternal = function() { - goog.ui.Button.superClass_.disposeInternal.call(this); - delete this.value_; - delete this.tooltip_; -}; - - -/** @override */ -goog.ui.Button.prototype.enterDocument = function() { - goog.ui.Button.superClass_.enterDocument.call(this); - if (this.isSupportedState(goog.ui.Component.State.FOCUSED)) { - var keyTarget = this.getKeyEventTarget(); - if (keyTarget) { - this.getHandler().listen(keyTarget, goog.events.EventType.KEYUP, - this.handleKeyEventInternal); - } - } -}; - - -/** - * Attempts to handle a keyboard event; returns true if the event was handled, - * false otherwise. If the button is enabled and the Enter/Space key was - * pressed, handles the event by dispatching an {@code ACTION} event, - * and returns true. Overrides {@link goog.ui.Control#handleKeyEventInternal}. - * @param {goog.events.KeyEvent} e Key event to handle. - * @return {boolean} Whether the key event was handled. - * @protected - * @override - */ -goog.ui.Button.prototype.handleKeyEventInternal = function(e) { - if (e.keyCode == goog.events.KeyCodes.ENTER && - e.type == goog.events.KeyHandler.EventType.KEY || - e.keyCode == goog.events.KeyCodes.SPACE && - e.type == goog.events.EventType.KEYUP) { - return this.performActionInternal(e); - } - // Return true for space keypress (even though the event is handled on keyup) - // as preventDefault needs to be called up keypress to take effect in IE and - // WebKit. - return e.keyCode == goog.events.KeyCodes.SPACE; -}; - - -// Register a decorator factory function for goog.ui.Buttons. -goog.ui.registry.setDecoratorByClassName(goog.ui.ButtonRenderer.CSS_CLASS, - function() { - return new goog.ui.Button(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/button_perf.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/button_perf.html.svn-base deleted file mode 100644 index 859b47d..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/button_perf.html.svn-base +++ /dev/null @@ -1,176 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Performance Tests - goog.ui.Button</title> - <link rel="stylesheet" type="text/css" href="../testing/performancetable.css" /> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.events.EventHandler'); - goog.require('goog.events.EventType'); - goog.require('goog.testing.PerformanceTable'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Button'); - </script> -</head> -<body> - <h1>goog.ui.Button Performance Tests</h1> - <p> - <b>User-agent:</b> <script>document.write(navigator.userAgent);</script> - </p> - <div id="perfTable"></div> - <hr> - <div id="renderSandbox"></div> - <div id="decorateSandbox"></div> - <script> - // The sandboxen. - var renderSandbox = goog.dom.getElement('renderSandbox'); - var decorateSandbox = goog.dom.getElement('decorateSandbox'); - - // Arrays of rendered/decorated buttons (so we can dispose of them). - var renderedButtons; - var decoratedButtons; - - // 0-based index of the button currently being rendered/decorated. - var renderIndex; - var decorateIndex; - - // Element currently being decorated. - var elementToDecorate; - - // Number of buttons to create/decorate per test run. - var SAMPLES_PER_RUN = 200; - - // The performance table. - var table; - - function setUpPage() { - table = new goog.testing.PerformanceTable( - goog.dom.getElement('perfTable')); - } - - // Sets up a render test. - function setUpRenderTest() { - renderedButtons = []; - renderIndex = 0; - } - - // Cleans up after a render test. - function cleanUpAfterRenderTest() { - for (var i = 0, count = renderedButtons.length; i < count; i++) { - renderedButtons[i].dispose(); - } - renderedButtons = null; - goog.dom.removeChildren(renderSandbox); - } - - // Sets up a decorate test. - function setUpDecorateTest(opt_count) { - var count = opt_count || 1000; - for (var i = 0; i < count; i++) { - decorateSandbox.appendChild(goog.dom.createDom('button', 'goog-button', - 'W00t!')); - } - elementToDecorate = decorateSandbox.firstChild; - decoratedButtons = []; - decorateIndex = 0; - } - - // Cleans up after a decorate test. - function cleanUpAfterDecorateTest() { - for (var i = 0, count = decoratedButtons.length; i < count; i++) { - decoratedButtons[i].dispose(); - } - decoratedButtons = null; - goog.dom.removeChildren(decorateSandbox); - } - - // Renders the given number of buttons. Since children are appended to - // the same parent element in each performance test run, we keep track of - // the current index via the global renderIndex variable. - function renderButtons(count, autoDetectBiDi) { - for (var i = 0; i < count; i++) { - var button = new goog.ui.Button('W00t!'); - if (!autoDetectBiDi) { - button.setRightToLeft(false); - } - button.render(renderSandbox); - renderedButtons[renderIndex++] = button; - } - } - - // Decorates "count" buttons. The decorate sandbox contains enough child - // elements for the whole test, but we only decorate up to "count" elements - // per test run, so we need to keep track of where we are via the global - // decorateIndex and elementToDecorate variables. - function decorateButtons(count, autoDetectBiDi) { - for (var i = 0; i < count; i++) { - var next = elementToDecorate.nextSibling; - var button = new goog.ui.Button(); - if (!autoDetectBiDi) { - button.setRightToLeft(false); - } - button.decorate(elementToDecorate); - decoratedButtons[decorateIndex++] = button; - elementToDecorate = next; - } - } - - function testRender() { - setUpRenderTest(); - table.run( - goog.partial(renderButtons, SAMPLES_PER_RUN, true), - 'Render ' + SAMPLES_PER_RUN + ' buttons (default)'); - cleanUpAfterRenderTest(); - assertEquals('The expected number of buttons must have been rendered', - SAMPLES_PER_RUN * table.getTimer().getNumSamples(), renderIndex); - } - - function testDecorate() { - setUpDecorateTest(SAMPLES_PER_RUN * table.getTimer().getNumSamples()); - table.run( - goog.partial(decorateButtons, SAMPLES_PER_RUN, true), - 'Decorate ' + SAMPLES_PER_RUN + ' buttons (default)'); - cleanUpAfterDecorateTest(); - assertEquals('The expected number of buttons must have been decorated', - SAMPLES_PER_RUN * table.getTimer().getNumSamples(), - decorateIndex); - assertNull('All buttons must have been decorated', elementToDecorate); - } - - function testRenderNoBiDiAutoDetect() { - setUpRenderTest(); - table.run( - goog.partial(renderButtons, SAMPLES_PER_RUN, false), - 'Render ' + SAMPLES_PER_RUN + ' buttons (no BiDi auto-detect)'); - cleanUpAfterRenderTest(); - assertEquals('The expected number of buttons must have been rendered', - SAMPLES_PER_RUN * table.getTimer().getNumSamples(), - renderIndex); - } - - function testDecorateNoBiDiAutoDetect() { - setUpDecorateTest(SAMPLES_PER_RUN * table.getTimer().getNumSamples()); - table.run( - goog.partial(decorateButtons, SAMPLES_PER_RUN, false), - 'Decorate ' + SAMPLES_PER_RUN + ' buttons (no BiDi auto-detect)'); - cleanUpAfterDecorateTest(); - assertEquals('The expected number of buttons must have been decorated', - SAMPLES_PER_RUN * table.getTimer().getNumSamples(), - decorateIndex); - assertNull('All buttons must have been decorated', elementToDecorate); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/button_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/button_test.html.svn-base deleted file mode 100644 index d0737fb..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/button_test.html.svn-base +++ /dev/null @@ -1,257 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: nicksantos@google.com (Nick Santos) -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.Button</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Button'); - goog.require('goog.ui.ButtonSide'); - goog.require('goog.ui.ButtonRenderer'); - goog.require('goog.ui.NativeButtonRenderer'); - </script> -</head> -<body> - <p>Here's a button defined in markup:</p> - <button id="demoButton">Foo</button> - <div id="sandbox"></div> - <script> - var sandbox = goog.dom.getElement('sandbox'); - var button; - var clonedButtonDom; - var demoButtonElement; - - function setUp() { - button = new goog.ui.Button(); - demoButtonElement = goog.dom.getElement('demoButton'); - clonedButtonDom = demoButtonElement.cloneNode(true); - } - - function tearDown() { - button.dispose(); - demoButtonElement.parentNode.replaceChild(clonedButtonDom, - demoButtonElement); - goog.dom.removeChildren(sandbox); - } - - function testConstructor() { - assertNotNull('Button must not be null', button); - assertEquals('Renderer must default to expected value', - goog.ui.NativeButtonRenderer.getInstance(), button.getRenderer()); - - var fakeDomHelper = {}; - var testButton = new goog.ui.Button('Hello', - goog.ui.ButtonRenderer.getInstance(), fakeDomHelper); - assertEquals('Content must have expected value', 'Hello', - testButton.getContent()); - assertEquals('Renderer must have expected value', - goog.ui.ButtonRenderer.getInstance(), testButton.getRenderer()); - assertEquals('DOM helper must have expected value', fakeDomHelper, - testButton.getDomHelper()); - testButton.dispose(); - } - - function testGetSetValue() { - assertUndefined('Button\'s value must default to undefined', - button.getValue()); - button.setValue(17); - assertEquals('Button must have expected value', 17, button.getValue()); - button.render(sandbox); - assertEquals('Button element must have expected value', '17', - button.getElement().value); - button.setValue('foo'); - assertEquals('Button element must have updated value', 'foo', - button.getElement().value); - button.setValueInternal('bar'); - assertEquals('Button must have new internal value', 'bar', - button.getValue()); - assertEquals('Button element must be unchanged', 'foo', - button.getElement().value); - } - - function testGetSetTooltip() { - assertUndefined('Button\'s tooltip must default to undefined', - button.getTooltip()); - button.setTooltip('Hello'); - assertEquals('Button must have expected tooltip', 'Hello', - button.getTooltip()); - button.render(sandbox); - assertEquals('Button element must have expected title', 'Hello', - button.getElement().title); - button.setTooltip('Goodbye'); - assertEquals('Button element must have updated title', 'Goodbye', - button.getElement().title); - button.setTooltipInternal('World'); - assertEquals('Button must have new internal tooltip', 'World', - button.getTooltip()); - assertEquals('Button element must be unchanged', 'Goodbye', - button.getElement().title); - } - - function testSetCollapsed() { - assertNull('Button must not have any collapsed styling by default', - button.getExtraClassNames()); - button.setCollapsed(goog.ui.ButtonSide.START); - assertSameElements('Button must have the start side collapsed', - ['goog-button-collapse-left'], button.getExtraClassNames()); - button.render(sandbox); - assertSameElements('Button element must have the start side collapsed', - ['goog-button', 'goog-button-collapse-left'], - goog.dom.classes.get(button.getElement())); - button.setCollapsed(goog.ui.ButtonSide.BOTH); - assertSameElements('Button must have both sides collapsed', - ['goog-button-collapse-left', 'goog-button-collapse-right'], - button.getExtraClassNames()); - assertSameElements('Button element must have both sides collapsed', [ - 'goog-button', - 'goog-button-collapse-left', - 'goog-button-collapse-right' - ], goog.dom.classes.get(button.getElement())); - } - - function testDispose() { - assertFalse('Button must not have been disposed of', button.isDisposed()); - button.render(sandbox); - button.setValue('foo'); - button.setTooltip('bar'); - button.dispose(); - assertTrue('Button must have been disposed of', button.isDisposed()); - assertUndefined('Button\'s value must have been deleted', - button.getValue()); - assertUndefined('Button\'s tooltip must have been deleted', - button.getTooltip()); - } - - function testBasicButtonBehavior() { - var dispatchedActionCount = 0; - var handleAction = function() { - dispatchedActionCount++; - }; - goog.events.listen(button, goog.ui.Component.EventType.ACTION, - handleAction); - - button.decorate(demoButtonElement); - goog.testing.events.fireClickSequence(demoButtonElement); - assertEquals('Button must have dispatched ACTION on click', 1, - dispatchedActionCount); - - dispatchedActionCount = 0; - var e = new goog.events.Event(goog.events.KeyHandler.EventType.KEY, - button); - e.keyCode = goog.events.KeyCodes.ENTER; - button.handleKeyEvent(e); - assertEquals('Enabled button must have dispatched ACTION on Enter key', 1, - dispatchedActionCount); - - dispatchedActionCount = 0; - e = new goog.events.Event(goog.events.EventType.KEYUP, button); - e.keyCode = goog.events.KeyCodes.SPACE; - button.handleKeyEvent(e); - assertEquals('Enabled button must have dispatched ACTION on Space key', 1, - dispatchedActionCount); - - goog.events.unlisten(button, goog.ui.Component.EventType.ACTION, - handleAction); - } - - function testDisabledButtonBehavior() { - var dispatchedActionCount = 0; - var handleAction = function() { - dispatchedActionCount++; - }; - goog.events.listen(button, goog.ui.Component.EventType.ACTION, - handleAction); - - button.setEnabled(false); - - dispatchedActionCount = 0; - button.handleKeyEvent({keyCode: goog.events.KeyCodes.ENTER}); - assertEquals('Disabled button must not dispatch ACTION on Enter key', - 0, dispatchedActionCount); - - dispatchedActionCount = 0; - button.handleKeyEvent({ - keyCode: goog.events.KeyCodes.SPACE, - type: goog.events.EventType.KEYUP - }); - assertEquals('Disabled button must not have dispatched ACTION on Space', - 0, dispatchedActionCount); - - goog.events.unlisten(button, goog.ui.Component.EventType.ACTION, - handleAction); - } - - function testSpaceFireActionOnKeyUp() { - var dispatchedActionCount = 0; - var handleAction = function() { - dispatchedActionCount++; - }; - goog.events.listen(button, goog.ui.Component.EventType.ACTION, - handleAction); - - dispatchedActionCount = 0; - e = new goog.events.Event(goog.events.KeyHandler.EventType.KEY, button); - e.keyCode = goog.events.KeyCodes.SPACE; - button.handleKeyEvent(e); - assertEquals('Button must not have dispatched ACTION on Space keypress', - 0, dispatchedActionCount); - assertEquals('The default action (scrolling) must have been prevented ' + - 'for Space keypress', - false, - e.returnValue_); - - - dispatchedActionCount = 0; - e = new goog.events.Event(goog.events.EventType.KEYUP, button); - e.keyCode = goog.events.KeyCodes.SPACE; - button.handleKeyEvent(e); - assertEquals('Button must have dispatched ACTION on Space keyup', - 1, dispatchedActionCount); - - goog.events.unlisten(button, goog.ui.Component.EventType.ACTION, - handleAction); - } - - function testEnterFireActionOnKeyPress() { - var dispatchedActionCount = 0; - var handleAction = function() { - dispatchedActionCount++; - }; - goog.events.listen(button, goog.ui.Component.EventType.ACTION, - handleAction); - - dispatchedActionCount = 0; - e = new goog.events.Event(goog.events.KeyHandler.EventType.KEY, button); - e.keyCode = goog.events.KeyCodes.ENTER; - button.handleKeyEvent(e); - assertEquals('Button must have dispatched ACTION on Enter keypress', - 1, dispatchedActionCount); - - dispatchedActionCount = 0; - e = new goog.events.Event(goog.events.EventType.KEYUP, button); - e.keyCode = goog.events.KeyCodes.ENTER; - button.handleKeyEvent(e); - assertEquals('Button must not have dispatched ACTION on Enter keyup', - 0, dispatchedActionCount); - - goog.events.unlisten(button, goog.ui.Component.EventType.ACTION, - handleAction); - } - - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/buttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/buttonrenderer.js.svn-base deleted file mode 100644 index 5d8c621..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/buttonrenderer.js.svn-base +++ /dev/null @@ -1,208 +0,0 @@ -// 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.dom.a11y'); -goog.require('goog.dom.a11y.Role'); -goog.require('goog.dom.a11y.State'); -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.dom.a11y.Role|undefined} ARIA role. - * @override - */ -goog.ui.ButtonRenderer.prototype.getAriaRole = function() { - return goog.dom.a11y.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.dom.a11y.setState(element, goog.dom.a11y.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. - * @protected - */ -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; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/buttonrenderer_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/buttonrenderer_test.html.svn-base deleted file mode 100644 index 0ff42c0..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/buttonrenderer_test.html.svn-base +++ /dev/null @@ -1,199 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.ButtonRenderer</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom.a11y'); - goog.require('goog.dom.a11y.Role'); - goog.require('goog.dom.a11y.State'); - goog.require('goog.dom.classes'); - goog.require('goog.style'); - goog.require('goog.testing.ExpectedFailures'); - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.ui.rendererasserts'); - goog.require('goog.ui.Button'); - goog.require('goog.ui.ButtonRenderer'); - goog.require('goog.ui.ButtonSide'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var button, buttonRenderer, testRenderer; - var sandbox = goog.dom.getElement('sandbox'); - var expectedFailures = new goog.testing.ExpectedFailures(); - - /** - * A subclass of ButtonRenderer that overrides - * {@code getStructuralCssClass} for testing purposes. - * @constructor - * @extends {goog.ui.ControlRenderer} - */ - function TestRenderer() { - goog.ui.ButtonRenderer.call(this); - }; - goog.inherits(TestRenderer, goog.ui.ButtonRenderer); - goog.addSingletonGetter(TestRenderer); - - /** {@override} */ - TestRenderer.prototype.getStructuralCssClass = function() { - return 'goog-base'; - }; - - function setUp() { - buttonRenderer = goog.ui.ButtonRenderer.getInstance(); - button = new goog.ui.Button('Hello', buttonRenderer); - testRenderer = TestRenderer.getInstance(); - } - - function tearDown() { - button.dispose(); - goog.dom.removeChildren(sandbox); - expectedFailures.handleTearDown(); - } - - function testConstructor() { - assertNotNull('ButtonRenderer singleton instance must not be null', - buttonRenderer); - } - - function testGetAriaRole() { - assertEquals('ButtonRenderer\'s ARIA role must have expected value', - goog.dom.a11y.Role.BUTTON, buttonRenderer.getAriaRole()); - } - - function testCreateDom() { - var element = buttonRenderer.createDom(button); - assertNotNull('Element must not be null', element); - assertEquals('Element must be a DIV', 'DIV', element.tagName); - assertHTMLEquals('Element must have expected structure', - '<div class="goog-button">Hello</div>', - goog.dom.getOuterHtml(element)); - - button.setTooltip('Hello, world!'); - button.setValue('foo'); - element = buttonRenderer.createDom(button); - assertNotNull('Element must not be null', element); - assertEquals('Element must be a DIV', 'DIV', element.tagName); - assertSameElements('Element must have expected class name', - ['goog-button'], goog.dom.classes.get(element)); - assertEquals('Element must have expected title', 'Hello, world!', - element.title); - assertUndefined('Element must have no value', element.value); - assertEquals('Element must have expected contents', 'Hello', - element.innerHTML); - - button.setSupportedState(goog.ui.Component.State.CHECKED, true); - var element = buttonRenderer.createDom(button); - assertEquals('button\'s aria-pressed attribute must be false', 'false', - goog.dom.a11y.getState(element, goog.dom.a11y.State.PRESSED)); - } - - function testCreateDomAriaState() { - button.setSupportedState(goog.ui.Component.State.CHECKED, true); - button.setChecked(true); - var element = buttonRenderer.createDom(button); - - assertEquals('button\'s aria-pressed attribute must be true', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.PRESSED)); - } - - function testDecorate() { - sandbox.innerHTML = - '<div id="foo">Foo</div>\n' + - '<div id="bar" title="Hello, world!">Bar</div>\n' + - '<div id="toggle">Toggle</div>'; - - var foo = new goog.ui.Button(null, buttonRenderer); - foo.decorate(goog.dom.getElement('foo')); - assertEquals('foo\'s tooltip must be the empty string', '', - foo.getTooltip()); - foo.dispose(); - - var bar = new goog.ui.Button(null, buttonRenderer); - bar.decorate(goog.dom.getElement('bar')); - assertEquals('bar\'s tooltip must be initialized', 'Hello, world!', - bar.getTooltip()); - bar.dispose(); - - var toggle = new goog.ui.Button(null, buttonRenderer); - toggle.setSupportedState(goog.ui.Component.State.CHECKED, true); - var element = goog.dom.getElement('toggle'); - toggle.decorate(element); - assertEquals('toggle\'s aria-pressed attribute must be false', 'false', - goog.dom.a11y.getState(element, goog.dom.a11y.State.PRESSED)); - toggle.dispose(); - } - - function testCollapse() { - buttonRenderer.setCollapsed(button, goog.ui.ButtonSide.START); - assertSameElements('Button should have class to collapse start', - ['goog-button-collapse-left'], button.getExtraClassNames()); - buttonRenderer.setCollapsed(button, goog.ui.ButtonSide.END); - assertSameElements('Button should have class to collapse end', - ['goog-button-collapse-right'], button.getExtraClassNames()); - buttonRenderer.setCollapsed(button, goog.ui.ButtonSide.BOTH); - assertSameElements('Button should have classes to collapse both', - ['goog-button-collapse-left', 'goog-button-collapse-right'], - button.getExtraClassNames()); - } - - function testCollapseRtl() { - button.setRightToLeft(true); - buttonRenderer.setCollapsed(button, goog.ui.ButtonSide.START); - assertSameElements('Button should have class to collapse start', - ['goog-button-collapse-right'], button.getExtraClassNames()); - buttonRenderer.setCollapsed(button, goog.ui.ButtonSide.END); - assertSameElements('Button should have class to collapse end', - ['goog-button-collapse-left'], button.getExtraClassNames()); - buttonRenderer.setCollapsed(button, goog.ui.ButtonSide.BOTH); - assertSameElements('Button should have classes to collapse both', - ['goog-button-collapse-left', 'goog-button-collapse-right'], - button.getExtraClassNames()); - } - - function testCollapseWithStructuralClass() { - testRenderer.setCollapsed(button, goog.ui.ButtonSide.BOTH); - assertSameElements('Should use structural class for collapse classes', - ['goog-base-collapse-left', 'goog-base-collapse-right'], - button.getExtraClassNames()); - } - - function testUpdateAriaState() { - var element = buttonRenderer.createDom(button); - buttonRenderer.updateAriaState(element, goog.ui.Component.State.CHECKED, - true); - assertEquals('Button must have pressed ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.PRESSED)); - - // Test for updating a state other than CHECKED - buttonRenderer.updateAriaState(element, goog.ui.Component.State.DISABLED, - true); - assertEquals('Button must have disabled ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.DISABLED)); - - buttonRenderer.updateAriaState(element, goog.ui.Component.State.CHECKED, - false); - assertEquals('Control must no longer have pressed ARIA state', - 'false', - goog.dom.a11y.getState(element, goog.dom.a11y.State.PRESSED)); - } - - function testDoesntCallGetCssClassInConstructor() { - goog.testing.ui.rendererasserts. - assertNoGetCssClassCallsInConstructor(goog.ui.ButtonRenderer); - } - - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/buttonside.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/buttonside.js.svn-base deleted file mode 100644 index 189d145..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/buttonside.js.svn-base +++ /dev/null @@ -1,40 +0,0 @@ -// 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}. - * - */ - -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 -}; - - diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/cccbutton.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/cccbutton.js.svn-base deleted file mode 100644 index 971a3eb..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/cccbutton.js.svn-base +++ /dev/null @@ -1,281 +0,0 @@ -// Copyright 2006 The Closure Library Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview This class is now deprecated. Use {@link goog.ui.Button} and - * {@link goog.ui.CustomButtonRenderer} to create CCC-style buttons. See - * closure/demos/button.html for an example. - * - */ - -goog.provide('goog.ui.CccButton'); - -goog.require('goog.dom'); -goog.require('goog.dom.classes'); -goog.require('goog.events'); -goog.require('goog.events.Event'); -goog.require('goog.events.EventType'); -goog.require('goog.ui.DeprecatedButton'); -goog.require('goog.userAgent'); - - - -/** - * CCC-style implementation of a button. - * The Html structure of the button is: - * <pre> - * Element - * ------------------------ - * - a - * - b - * - b - * - b - * - text - * </pre> - * - * @param {string=} opt_class Optional class for component. - * Default: 'goog-cccbutton'. - * @param {boolean=} opt_noPoundSignInHref An optional argument that, when true, - * instructs the button to not use the href="#" to create the link. The - * side effect of this option being true is that clicking the button - * triggers the window's onunload or onbeforeunload handler in IE. The - * upside of setting this to true is that the page will not scroll when - * clicking this button in IE. - * - * @constructor - * @extends {goog.ui.DeprecatedButton} - * @deprecated Use {@link goog.ui.Button} instead. - */ -goog.ui.CccButton = function(opt_class, opt_noPoundSignInHref) { - var className = opt_class ? opt_class : goog.getCssName('goog-cccbutton'); - goog.ui.DeprecatedButton.call(this, className); - - /** - * Whether the 'a' element used for the button will use href='#' or instead - * use href='javascript:;'. - * @type {boolean} - * @private - */ - this.noPoundSignInHref_ = opt_noPoundSignInHref || false; -}; -goog.inherits(goog.ui.CccButton, goog.ui.DeprecatedButton); - - -/** - * Prefix for all ID's of this component. - * @type {string} - * @private - */ -goog.ui.CccButton.BASE_ID_ = 'goog.ui.CccButton.'; - - -/** - * Next unique instance ID for this component. - * @type {number} - * @private - */ -goog.ui.CccButton.nextId_ = 0; - - -/** - * Gets the next unique ID for the component. - * @return {string} The next unique ID for the component. - */ -goog.ui.CccButton.getNextUniqueId = function() { - return goog.ui.CccButton.BASE_ID_ + String(goog.ui.CccButton.nextId_++); -}; - - -/** - * Gets the next unique ID for the component. This method is used in the - * constructor to generate the unique ID for the component. - * - * NOTE: This method is placed on the prototype so that classes that inherit - * this class can override this method and have the ID automatically set by - * calling the parent class's constructor. - * - * @return {string} The next unique ID for the component. - * @private - */ -goog.ui.CccButton.prototype.getNextUniqueId_ = function() { - return goog.ui.CccButton.getNextUniqueId(); -}; - - -/** - * Element that directly contains the caption for the component. - * @type {Element} - * @private - */ -goog.ui.DeprecatedButton.prototype.captionEl_ = null; - - -/** - * Addition to base CSS class name to add when component is enabled. - * @type {string} - * @private - */ -goog.ui.CccButton.ENABLED_CLASS_ADDITION_ = '-enabled'; - - -/** - * Addition to base CSS class name to add when component is disabled. - * @type {string} - * @private - */ -goog.ui.CccButton.DISABLED_CLASS_ADDITION_ = '-disabled'; - - -/** - * Gets the CSS class to use for when enabled. - * @return {string} The CSS class name. - */ -goog.ui.CccButton.prototype.getEnabledClass = function() { - return this.class_ + goog.ui.CccButton.ENABLED_CLASS_ADDITION_; -}; - - -/** - * Gets the CSS class to use for when disabled. - * @return {string} The CSS class name. - */ -goog.ui.CccButton.prototype.getDisabledClass = function() { - return this.class_ + goog.ui.CccButton.DISABLED_CLASS_ADDITION_; -}; - - -/** - * Sets the caption for the component. - * @param {string} caption The caption. - */ -goog.ui.CccButton.prototype.setCaption = function(caption) { - this.caption_ = caption; - if (this.isRendered()) { - var element = this.captionEl_; - element.innerHTML = ''; - var domHelper = goog.dom.getDomHelper(element); - domHelper.appendChild(element, domHelper.createTextNode(caption)); - } -}; - - -/** - * Sets the enabled status of the component. - * @param {boolean} enable TRUE iff enable the button. Otherwise, disable. - */ -goog.ui.CccButton.prototype.setEnabled = function(enable) { - if (this.getEnabled() != enable && - this.dispatchEvent(goog.ui.DeprecatedButton.EventType.ENABLE)) { - if (this.isRendered()) { - // Swap the CSS class for enabled/disabled. - var element = this.getElement(); - var fromClass = !enable ? this.getEnabledClass() : - this.getDisabledClass(); - var toClass = enable ? this.getEnabledClass() : this.getDisabledClass(); - goog.dom.classes.swap(element, fromClass, toClass); - } - this.enabled_ = enable; - } -}; - - -/** - * Renders the component. Throws an Error if the component is already rendered. - * @param {Element=} opt_element Element to render the compponent into. - * If omitted, then the componenet is appended to - * the document. - */ -goog.ui.CccButton.prototype.render = function(opt_element) { - if (this.isRendered()) { - throw Error('Compenent already rendered'); - } - - // Get the DOM helper. - var domHelper = goog.dom.getDomHelper(opt_element); - - // Adding # was problematic in non-IE, cause of bug 572520. - var hrefString = goog.userAgent.IE ? '#' : 'javascript:;'; - hrefString = this.noPoundSignInHref_ ? 'javascript:;' : hrefString; - - // Create element. - var element = domHelper.createDom('a', - {title: this.tooltip_, className: this.class_ + ' ' + - (this.enabled_ ? this.getEnabledClass() : this.getDisabledClass()), - href: hrefString }, - domHelper.createDom('b', {}, - domHelper.createDom('b', {}, - this.captionEl_ = - domHelper.createDom('b', {}, this.caption_)))); - - // Append to parent. - var parentElement = opt_element || domHelper.getDocument().body; - domHelper.appendChild(parentElement, element); - - // Setup event handlers. - goog.events.listen(element, goog.events.EventType.CLICK, - this.onClick_, true, this); - - this.element_ = element; - this.rendered_ = true; -}; - - -/** - * Helper for checking if the structure of an element is valid for this - * component. - * @param {Element} element The element to check. - * @param {string} tag The tag name to check for. - * @return {boolean} Whether there is only one child and the child is of the - * given tag. - * @private - */ -goog.ui.CccButton.prototype.isValidButtonChildHelper_ = function(element, tag) { - var domHelper = goog.dom.getDomHelper(element); - var firstChild = element ? domHelper.getFirstElementChild(element) : null; - if (firstChild && firstChild.tagName.toLowerCase() == tag && - element.childNodes.length == 1) { - return true; - } - return false; -}; - - -/** - * Decorates the element for the UI component. - * @param {Element} element Element to decorate. - */ -goog.ui.CccButton.prototype.decorate = function(element) { - if (this.isRendered()) { - throw Error('Component already rendered'); - } else { - var domHelper = goog.dom.getDomHelper(element); - var firstElement = element ? domHelper.getFirstElementChild(element) : null; - var secondElement = firstElement ? - domHelper.getFirstElementChild(firstElement) : null; - // Check if the structure of the element is valid for this component. - if (element && element.tagName.toLowerCase() == 'a' && - this.isValidButtonChildHelper_(element, 'b') && - this.isValidButtonChildHelper_(firstElement, 'b') && - this.isValidButtonChildHelper_(secondElement, 'b')) { - // Setup properties. - this.element_ = element; - this.setCaption(secondElement.firstChild.innerHTML); - this.setTooltip(element.title); - this.class_ = element.className; - this.rendered_ = true; - } else { - throw Error('Invalid element to decorate'); - } - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/charcounter.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/charcounter.js.svn-base deleted file mode 100644 index 1903661..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/charcounter.js.svn-base +++ /dev/null @@ -1,201 +0,0 @@ -// 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 Character counter widget implementation. - * - * @author eae@google.com (Emil A Eklund) - * @see ../demos/charcounter.html - */ - -goog.provide('goog.ui.CharCounter'); -goog.provide('goog.ui.CharCounter.Display'); - -goog.require('goog.dom'); -goog.require('goog.events'); -goog.require('goog.events.EventTarget'); -goog.require('goog.events.InputHandler'); - - - -/** - * CharCounter widget. Counts the number of characters in a input field or a - * text box and displays the number of additional characters that may be - * entered before the maximum length is reached. - * - * @extends {goog.events.EventTarget} - * @param {HTMLInputElement|HTMLTextAreaElement} elInput Input or text area - * element to count the number of characters in. You can pass in null - * for this if you don't want to expose the number of chars remaining. - * @param {Element} elCount HTML element to display the remaining number of - * characters in. - * @param {number} maxLength The maximum length. - * @param {goog.ui.CharCounter.Display=} opt_displayMode Display mode for this - * char counter. Defaults to {@link goog.ui.CharCounter.Display.REMAINING}. - * @constructor - */ -goog.ui.CharCounter = function(elInput, elCount, maxLength, opt_displayMode) { - goog.events.EventTarget.call(this); - - /** - * Input or text area element to count the number of characters in. - * @type {HTMLInputElement|HTMLTextAreaElement} - * @private - */ - this.elInput_ = elInput; - - /** - * HTML element to display the remaining number of characters in. - * @type {Element} - * @private - */ - this.elCount_ = elCount; - - /** - * The maximum length. - * @type {number} - * @private - */ - this.maxLength_ = maxLength; - - /** - * The display mode for this char counter. - * @type {!goog.ui.CharCounter.Display} - * @private - */ - this.display_ = opt_displayMode || goog.ui.CharCounter.Display.REMAINING; - - elInput.maxLength = maxLength; - - /** - * The input handler that provides the input event. - * @type {goog.events.InputHandler} - * @private - */ - this.inputHandler_ = new goog.events.InputHandler(elInput); - - goog.events.listen(this.inputHandler_, - goog.events.InputHandler.EventType.INPUT, this.onChange_, false, this); - - this.checkLength_(); -}; -goog.inherits(goog.ui.CharCounter, goog.events.EventTarget); - - -/** - * Display mode for the char counter. - * @enum {number} - */ -goog.ui.CharCounter.Display = { - /** Widget displays the number of characters remaining (the default). */ - REMAINING: 0, - /** Widget displays the number of characters entered. */ - INCREMENTAL: 1 -}; - - -/** - * Sets the maximum length. - * - * @param {number} maxLength The maximum length. - */ -goog.ui.CharCounter.prototype.setMaxLength = function(maxLength) { - this.maxLength_ = maxLength; - this.elInput_.maxLength = maxLength; - this.checkLength_(); -}; - - -/** - * Returns the maximum length. - * - * @return {number} The maximum length. - */ -goog.ui.CharCounter.prototype.getMaxLength = function() { - return this.maxLength_; -}; - - -/** - * Sets the display mode. - * - * @param {!goog.ui.CharCounter.Display} displayMode The display mode. - */ -goog.ui.CharCounter.prototype.setDisplayMode = function(displayMode) { - this.display_ = displayMode; - this.checkLength_(); -}; - - -/** - * Returns the display mode. - * - * @return {!goog.ui.CharCounter.Display} The display mode. - */ -goog.ui.CharCounter.prototype.getDisplayMode = function() { - return this.display_; -}; - - -/** - * Change event handler for input field. - * - * @param {goog.events.BrowserEvent} event Change event. - * @private - */ -goog.ui.CharCounter.prototype.onChange_ = function(event) { - this.checkLength_(); -}; - - -/** - * Checks length of text in input field and updates the counter. Truncates text - * if the maximum lengths is exceeded. - * - * @private - */ -goog.ui.CharCounter.prototype.checkLength_ = function() { - var count = this.elInput_.value.length; - - // There's no maxlength property for textareas so instead we truncate the - // text if it gets too long. It's also used to truncate the text in a input - // field if the maximum length is changed. - if (count > this.maxLength_) { - - var scrollTop = this.elInput_.scrollTop; - var scrollLeft = this.elInput_.scrollLeft; - - this.elInput_.value = this.elInput_.value.substring(0, this.maxLength_); - count = this.maxLength_; - - this.elInput_.scrollTop = scrollTop; - this.elInput_.scrollLeft = scrollLeft; - } - - if (this.elCount_) { - var incremental = this.display_ == goog.ui.CharCounter.Display.INCREMENTAL; - goog.dom.setTextContent( - this.elCount_, - /** @type {string} */(incremental ? count : this.maxLength_ - count)); - } -}; - - -/** @override */ -goog.ui.CharCounter.prototype.disposeInternal = function() { - goog.ui.CharCounter.superClass_.disposeInternal.call(this); - delete this.elInput_; - this.inputHandler_.dispose(); - this.inputHandler_ = null; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/charpicker.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/charpicker.js.svn-base deleted file mode 100644 index 48bd23a..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/charpicker.js.svn-base +++ /dev/null @@ -1,807 +0,0 @@ -// 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 Character Picker widget for picking any Unicode character. - * - * @see ../demos/charpicker.html - */ - -goog.provide('goog.ui.CharPicker'); - -goog.require('goog.array'); -goog.require('goog.dom'); -goog.require('goog.events'); -goog.require('goog.events.EventHandler'); -goog.require('goog.events.EventType'); -goog.require('goog.events.InputHandler'); -goog.require('goog.events.KeyHandler'); -goog.require('goog.i18n.CharListDecompressor'); -goog.require('goog.i18n.uChar'); -goog.require('goog.structs.Set'); -goog.require('goog.style'); -goog.require('goog.ui.Button'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.ContainerScroller'); -goog.require('goog.ui.FlatButtonRenderer'); -goog.require('goog.ui.HoverCard'); -goog.require('goog.ui.LabelInput'); -goog.require('goog.ui.Menu'); -goog.require('goog.ui.MenuButton'); -goog.require('goog.ui.MenuItem'); -goog.require('goog.ui.Tooltip.ElementTooltipPosition'); - - - -/** - * Character Picker Class. This widget can be used to pick any Unicode - * character by traversing a category-subcategory structure or by inputing its - * hex value. - * - * See charpicker.html demo for example usage. - * @param {goog.i18n.CharPickerData} charPickerData Category names and charlist. - * @param {Array.<string>=} opt_recents List of characters to be displayed in - * resently selected characters area. - * @param {number=} opt_initCategory Sequence number of initial category. - * @param {number=} opt_initSubcategory Sequence number of initial subcategory. - * @param {number=} opt_rowCount Number of rows in the grid. - * @param {number=} opt_columnCount Number of columns in the grid. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Component} - */ -goog.ui.CharPicker = function(charPickerData, opt_recents, opt_initCategory, - opt_initSubcategory, opt_rowCount, - opt_columnCount, opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - - /** - * Object containing character lists and category names. - * @type {goog.i18n.CharPickerData} - * @private - */ - this.data_ = charPickerData; - - /** - * The category number to be used on widget init. - * @type {number} - * @private - */ - this.initCategory_ = opt_initCategory || 0; - - /** - * The subcategory number to be used on widget init. - * @type {number} - * @private - */ - this.initSubcategory_ = opt_initSubcategory || 0; - - /** - * Number of columns in the grid. - * @type {number} - * @private - */ - this.columnCount_ = opt_columnCount || 10; - - /** - * Number of entries to be added to the grid. - * @type {number} - * @private - */ - this.gridsize_ = (opt_rowCount || 10) * this.columnCount_; - - /** - * Number of the recently selected characters displayed. - * @type {number} - * @private - */ - this.recentwidth_ = this.columnCount_ + 1; - - /** - * List of recently used characters. - * @type {Array.<string>} - * @private - */ - this.recents_ = opt_recents || []; - - /** - * Handler for events. - * @type {goog.events.EventHandler} - * @private - */ - this.eventHandler_ = new goog.events.EventHandler(this); - - /** - * Decompressor used to get the list of characters from a base88 encoded - * character list. - * @type {Object} - * @private - */ - this.decompressor_ = new goog.i18n.CharListDecompressor(); -}; -goog.inherits(goog.ui.CharPicker, goog.ui.Component); - - -/** - * The last selected character. - * @type {?string} - * @private - */ -goog.ui.CharPicker.prototype.selectedChar_ = null; - - -/** - * Set of formatting characters whose display need to be swapped with nbsp - * to prevent layout issues. - * @type {goog.structs.Set} - * @private - */ -goog.ui.CharPicker.prototype.layoutAlteringChars_ = null; - - -/** - * The top category menu. - * @type {goog.ui.Menu} - * @private - */ -goog.ui.CharPicker.prototype.menu_ = null; - - -/** - * The top category menu button. - * @type {goog.ui.MenuButton} - * @private - */ -goog.ui.CharPicker.prototype.menubutton_ = null; - - -/** - * The subcategory menu. - * @type {goog.ui.Menu} - * @private - */ -goog.ui.CharPicker.prototype.submenu_ = null; - - -/** - * The subcategory menu button. - * @type {goog.ui.MenuButton} - * @private - */ -goog.ui.CharPicker.prototype.submenubutton_ = null; - - -/** - * The element representing the number of rows visible in the grid. - * This along with goog.ui.CharPicker.stick_ would help to create a scrollbar - * of right size. - * @type {Element} - * @private - */ -goog.ui.CharPicker.prototype.stickwrap_ = null; - - -/** - * The component containing all the buttons for each character in display. - * @type {goog.ui.Component} - * @private - */ -goog.ui.CharPicker.prototype.grid_ = null; - - -/** - * The component used for extra information about the character set displayed. - * @type {goog.ui.Component} - * @private - */ -goog.ui.CharPicker.prototype.notice_ = null; - - -/** - * Grid displaying recently selected characters. - * @type {goog.ui.Component} - * @private - */ -goog.ui.CharPicker.prototype.recentgrid_ = null; - - -/** - * Input field for entering the hex value of the character. - * @type {goog.ui.Component} - * @private - */ -goog.ui.CharPicker.prototype.input_ = null; - - -/** - * OK button for entering hex value of the character. - * @type {goog.ui.Component} - * @private - */ -goog.ui.CharPicker.prototype.okbutton_ = null; - - -/** - * Element displaying character in preview. - * @type {Element} - * @private - */ -goog.ui.CharPicker.prototype.zoomEl_ = null; - - -/** - * Element displaying character name or number in preview. - * @type {Element} - * @private - */ -goog.ui.CharPicker.prototype.unicodeEl_ = null; - - -/** - * Hover card for displaying the preview of a character. - * Preview would contain character in large size and its U+ notation. It would - * also display the name, if available. - * @type {goog.ui.HoverCard} - * @private - */ -goog.ui.CharPicker.prototype.hc_ = null; - - -/** - * Gets the last selected character. - * @return {?string} The last selected character. - */ -goog.ui.CharPicker.prototype.getSelectedChar = function() { - return this.selectedChar_; -}; - - -/** - * Gets the list of characters user selected recently. - * @return {Array.<string>} The recent character list. - */ -goog.ui.CharPicker.prototype.getRecentChars = function() { - return this.recents_; -}; - - -/** @override */ -goog.ui.CharPicker.prototype.createDom = function() { - goog.ui.CharPicker.superClass_.createDom.call(this); - - this.decorateInternal(this.getDomHelper().createElement('div')); -}; - - -/** @override */ -goog.ui.CharPicker.prototype.disposeInternal = function() { - this.hc_.dispose(); - this.hc_ = null; - this.eventHandler_.dispose(); - this.eventHandler_ = null; - goog.ui.CharPicker.superClass_.disposeInternal.call(this); -}; - - -/** @override */ -goog.ui.CharPicker.prototype.decorateInternal = function(element) { - goog.ui.CharPicker.superClass_.decorateInternal.call(this, element); - - // The chars below cause layout disruption or too narrow to hover: - // \u0020, \u00AD, \u2000 - \u200f, \u2028 - \u202f, \u3000, \ufeff - var chrs = this.decompressor_.toCharList(':2%C^O80V1H2s2G40Q%s0'); - this.layoutAlteringChars_ = new goog.structs.Set(chrs); - - this.menu_ = new goog.ui.Menu(); - - var categories = this.data_.categories; - for (var i = 0; i < this.data_.categories.length; i++) { - this.menu_.addChild(this.createMenuItem_(i, categories[i]), true); - } - - this.menubutton_ = new goog.ui.MenuButton('Category Menu', this.menu_); - this.addChild(this.menubutton_, true); - - this.submenu_ = new goog.ui.Menu(); - - this.submenubutton_ = new goog.ui.MenuButton('Subcategory Menu', - this.submenu_); - this.addChild(this.submenubutton_, true); - - // The containing compnent for grid component and the scroller. - var gridcontainer = new goog.ui.Component(); - this.addChild(gridcontainer, true); - - var stickwrap = new goog.ui.Component(); - gridcontainer.addChild(stickwrap, true); - this.stickwrap_ = stickwrap.getElement(); - - var stick = new goog.ui.Component(); - stickwrap.addChild(stick, true); - this.stick_ = stick.getElement(); - - this.grid_ = new goog.ui.Component(); - gridcontainer.addChild(this.grid_, true); - - this.notice_ = new goog.ui.Component(); - this.notice_.setElementInternal(goog.dom.createDom('div')); - this.addChild(this.notice_, true); - - // The component used for displaying 'Recent Selections' label. - /** - * @desc The text label above the list of recently selected characters. - */ - var MSG_CHAR_PICKER_RECENT_SELECTIONS = goog.getMsg('Recent Selections:'); - var recenttext = new goog.ui.Component(); - recenttext.setElementInternal(goog.dom.createDom('span', null, - MSG_CHAR_PICKER_RECENT_SELECTIONS)); - this.addChild(recenttext, true); - - this.recentgrid_ = new goog.ui.Component(); - this.addChild(this.recentgrid_, true); - - // The component used for displaying 'U+'. - var uplus = new goog.ui.Component(); - uplus.setElementInternal(goog.dom.createDom('span', null, 'U+')); - this.addChild(uplus, true); - - /** - * @desc The text inside the input box to specify the hex code of a character. - */ - var MSG_CHAR_PICKER_HEX_INPUT = goog.getMsg('Hex Input'); - this.input_ = new goog.ui.LabelInput(MSG_CHAR_PICKER_HEX_INPUT); - this.addChild(this.input_, true); - - this.okbutton_ = new goog.ui.Button('OK'); - this.addChild(this.okbutton_, true); - this.okbutton_.setEnabled(false); - - this.zoomEl_ = goog.dom.createDom('div', - {id: 'zoom', className: goog.getCssName('goog-char-picker-char-zoom')}); - - this.unicodeEl_ = goog.dom.createDom('div', - {id: 'unicode', className: goog.getCssName('goog-char-picker-unicode')}); - - var card = goog.dom.createDom('div', {'id': 'preview'}, this.zoomEl_, - this.unicodeEl_); - goog.style.showElement(card, false); - this.hc_ = new goog.ui.HoverCard({'DIV': 'char'}); - this.hc_.setElement(card); - var self = this; - - /** - * Function called by hover card just before it is visible to collect data. - */ - function onBeforeShow() { - var trigger = self.hc_.getAnchorElement(); - var ch = self.getChar_(trigger); - if (ch) { - self.zoomEl_.innerHTML = self.displayChar_(ch); - self.unicodeEl_.innerHTML = self.getTagFromChar_(ch); - } - } - - goog.events.listen(this.hc_, goog.ui.HoverCard.EventType.BEFORE_SHOW, - onBeforeShow); - - goog.dom.classes.add(element, goog.getCssName('goog-char-picker')); - goog.dom.classes.add(this.stick_, goog.getCssName('goog-stick')); - goog.dom.classes.add(this.stickwrap_, goog.getCssName('goog-stickwrap')); - goog.dom.classes.add(gridcontainer.getElement(), - goog.getCssName('goog-char-picker-grid-container')); - goog.dom.classes.add(this.grid_.getElement(), - goog.getCssName('goog-char-picker-grid')); - goog.dom.classes.add(this.recentgrid_.getElement(), - goog.getCssName('goog-char-picker-grid')); - goog.dom.classes.add(this.recentgrid_.getElement(), - goog.getCssName('goog-char-picker-recents')); - - goog.dom.classes.add(this.notice_.getElement(), - goog.getCssName('goog-char-picker-notice')); - goog.dom.classes.add(uplus.getElement(), - goog.getCssName('goog-char-picker-uplus')); - goog.dom.classes.add(this.input_.getElement(), - goog.getCssName('goog-char-picker-input-box')); - goog.dom.classes.add(this.okbutton_.getElement(), - goog.getCssName('goog-char-picker-okbutton')); - goog.dom.classes.add(card, goog.getCssName('goog-char-picker-hovercard')); - this.hc_.className = goog.getCssName('goog-char-picker-hovercard'); - - this.grid_.buttoncount = this.gridsize_; - this.recentgrid_.buttoncount = this.recentwidth_; - this.populateGridWithButtons_(this.grid_); - this.populateGridWithButtons_(this.recentgrid_); - - this.updateGrid_(this.recentgrid_, this.recents_); - this.setSelectedCategory_(this.initCategory_, this.initSubcategory_); - new goog.ui.ContainerScroller(this.menu_); - new goog.ui.ContainerScroller(this.submenu_); - - goog.dom.classes.add(this.menu_.getElement(), - goog.getCssName('goog-char-picker-menu')); - goog.dom.classes.add(this.submenu_.getElement(), - goog.getCssName('goog-char-picker-menu')); -}; - - -/** @override */ -goog.ui.CharPicker.prototype.enterDocument = function() { - goog.ui.CharPicker.superClass_.enterDocument.call(this); - var inputkh = new goog.events.InputHandler(this.input_.getElement()); - this.keyHandler_ = new goog.events.KeyHandler(this.input_.getElement()); - - // Stop the propagation of ACTION events at menu and submenu buttons. - // If stopped at capture phase, the button will not be set to normal state. - // If not stopped, the user widget will receive the event, which is - // undesired. User widget should receive an event only on the character - // click. - this.eventHandler_. - listen( - this.menubutton_, - goog.ui.Component.EventType.ACTION, - goog.events.Event.stopPropagation). - listen( - this.submenubutton_, - goog.ui.Component.EventType.ACTION, - goog.events.Event.stopPropagation). - listen( - this, - goog.ui.Component.EventType.ACTION, - this.handleSelectedItem_, - true). - listen( - inputkh, - goog.events.InputHandler.EventType.INPUT, - this.handleInput_). - listen( - this.keyHandler_, - goog.events.KeyHandler.EventType.KEY, - this.handleEnter_); - - goog.events.listen(this.okbutton_.getElement(), - goog.events.EventType.MOUSEDOWN, this.handleOkClick_, true, this); - - goog.events.listen(this.stickwrap_, goog.events.EventType.SCROLL, - this.handleScroll_, true, this); -}; - - -/** - * On scroll, updates the grid with characters correct to the scroll position. - * @param {goog.events.Event} e Scroll event to handle. - * @private - */ -goog.ui.CharPicker.prototype.handleScroll_ = function(e) { - var height = e.target.scrollHeight; - var top = e.target.scrollTop; - var itempos = Math.ceil(top * this.items.length / (this.columnCount_ * - height)) * this.columnCount_; - if (this.itempos != itempos) { - this.itempos = itempos; - this.modifyGridWithItems_(this.grid_, this.items, itempos); - } - e.stopPropagation(); -}; - - -/** - * On a menu click, sets correct character set in the grid; on a grid click - * accept the character as the selected one and adds to recent selection, if not - * already present. - * @param {goog.events.Event} e Event for the click on menus or grid. - * @private - */ -goog.ui.CharPicker.prototype.handleSelectedItem_ = function(e) { - if (e.target.getParent() == this.menu_) { - this.menu_.setVisible(false); - this.setSelectedCategory_(e.target.getValue()); - } else if (e.target.getParent() == this.submenu_) { - this.submenu_.setVisible(false); - this.setSelectedSubcategory_(e.target.getValue()); - } else if (e.target.getParent() == this.grid_) { - var button = e.target.getElement(); - this.selectedChar_ = this.getChar_(button); - this.updateRecents_(this.selectedChar_); - } else if (e.target.getParent() == this.recentgrid_) { - this.selectedChar_ = this.getChar_(e.target.getElement()); - } -}; - - -/** - * When user types the characters displays the preview. Enables the OK button, - * if the character is valid. - * @param {goog.events.Event} e Event for typing in input field. - * @private - */ -goog.ui.CharPicker.prototype.handleInput_ = function(e) { - var ch = this.getInputChar_(); - if (ch) { - var unicode = this.getTagFromChar_(ch); - this.zoomEl_.innerHTML = ch; - this.unicodeEl_.innerHTML = unicode; - var coord = - new goog.ui.Tooltip.ElementTooltipPosition(this.input_.getElement()); - this.hc_.setPosition(coord); - this.hc_.triggerForElement(this.input_.getElement()); - this.okbutton_.setEnabled(true); - } else { - this.hc_.cancelTrigger(); - this.hc_.setVisible(false); - this.okbutton_.setEnabled(false); - } -}; - - -/** - * On OK click accepts the character and updates the recent char list. - * @param {goog.events.Event=} opt_event Event for click on OK button. - * @return {boolean} Indicates whether to propagate event. - * @private - */ -goog.ui.CharPicker.prototype.handleOkClick_ = function(opt_event) { - var ch = this.getInputChar_(); - if (ch && ch.charCodeAt(0)) { - this.selectedChar_ = ch; - this.updateRecents_(ch); - return true; - } - return false; -}; - - -/** - * Behaves exactly like the OK button on Enter key. - * @param {goog.events.KeyEvent} e Event for enter on the input field. - * @return {boolean} Indicates whether to propagate event. - * @private - */ -goog.ui.CharPicker.prototype.handleEnter_ = function(e) { - if (e.keyCode == goog.events.KeyCodes.ENTER) { - return this.handleOkClick_() ? - this.dispatchEvent(goog.ui.Component.EventType.ACTION) : false; - } - return false; -}; - - -/** - * Gets the character from the event target. - * @param {Element} e Event target containing the 'char' attribute. - * @return {string} The character specified in the event. - * @private - */ -goog.ui.CharPicker.prototype.getChar_ = function(e) { - return e.getAttribute('char'); -}; - - -/** - * Creates a menu entry for either the category listing or subcategory listing. - * @param {number} id Id to be used for the entry. - * @param {string} caption Text displayed for the menu item. - * @return {goog.ui.MenuItem} Menu item to be added to the menu listing. - * @private - */ -goog.ui.CharPicker.prototype.createMenuItem_ = function(id, caption) { - var item = new goog.ui.MenuItem(caption); - item.setValue(id); - item.setVisible(true); - return item; -}; - - -/** - * Sets the category and updates the submenu items and grid accordingly. - * @param {number} category Category index used to index the data tables. - * @param {number=} opt_subcategory Subcategory index used with category index. - * @private - */ -goog.ui.CharPicker.prototype.setSelectedCategory_ = function(category, - opt_subcategory) { - this.category = category; - this.menubutton_.setCaption(this.data_.categories[category]); - while (this.submenu_.hasChildren()) { - this.submenu_.removeChildAt(0, true).dispose(); - } - - var subcategories = this.data_.subcategories[category]; - var charList = this.data_.charList[category]; - for (var i = 0; i < subcategories.length; i++) { - var subtitle = charList[i].length == 0; - var item = this.createMenuItem_(i, subcategories[i]); - this.submenu_.addChild(item, true); - } - this.setSelectedSubcategory_(opt_subcategory || 0); -}; - - -/** - * Sets the subcategory and updates the grid accordingly. - * @param {number} subcategory Sub-category index used to index the data tables. - * @private - */ -goog.ui.CharPicker.prototype.setSelectedSubcategory_ = function(subcategory) { - var subcategories = this.data_.subcategories; - var name = subcategories[this.category][subcategory]; - this.submenubutton_.setCaption(name); - this.setSelectedGrid_(this.category, subcategory); -}; - - -/** - * Updates the grid according to a given category and subcategory. - * @param {number} category Index to the category table. - * @param {number} subcategory Index to the subcategory table. - * @private - */ -goog.ui.CharPicker.prototype.setSelectedGrid_ = function(category, - subcategory) { - var charLists = this.data_.charList; - var charListStr = charLists[category][subcategory]; - var content = this.decompressor_.toCharList(charListStr); - this.updateGrid_(this.grid_, content); -}; - - -/** - * Updates the grid with new character list. - * @param {goog.ui.Component} grid The grid which is updated with a new set of - * characters. - * @param {Array.<string>} items Characters to be added to the grid. - * @private - */ -goog.ui.CharPicker.prototype.updateGrid_ = function(grid, items) { - if (grid == this.grid_) { - /** - * @desc The message used when there are invisible characters like space - * or format control characters. - */ - var MSG_PLEASE_HOVER = - goog.getMsg('Please hover over each cell for the character name.'); - - this.notice_.getElement().innerHTML = goog.i18n.uChar.toName(items[0]) ? - MSG_PLEASE_HOVER : ''; - this.items = items; - if (this.stickwrap_.offsetHeight > 0) { - this.stick_.style.height = - this.stickwrap_.offsetHeight * items.length / this.gridsize_ + 'px'; - } else { - // This is the last ditch effort if height is not avaialble. - // Maximum of 3em is assumed to the the cell height. Extra space after - // last character in the grid is OK. - this.stick_.style.height = 3 * this.columnCount_ * items.length / - this.gridsize_ + 'em'; - } - this.stickwrap_.scrollTop = 0; - } - - this.modifyGridWithItems_(grid, items, 0); -}; - - -/** - * Updates the grid with new character list for a given starting point. - * @param {goog.ui.Component} grid The grid which is updated with a new set of - * characters. - * @param {Array.<string>} items Characters to be added to the grid. - * @param {number} start The index from which the characters should be - * displayed. - * @private - */ -goog.ui.CharPicker.prototype.modifyGridWithItems_ = function(grid, items, - start) { - for (var buttonpos = 0, itempos = start; - buttonpos < grid.buttoncount && itempos < items.length; - buttonpos++, itempos++) { - this.modifyCharNode_(grid.getChildAt(buttonpos), items[itempos]); - } - - for (; buttonpos < grid.buttoncount; buttonpos++) { - grid.getChildAt(buttonpos).setVisible(false); - } - var first = grid.getChildAt(0); - goog.dom.setFocusableTabIndex(first.getElement(), true); -}; - - -/** - * Creates the grid for characters to displayed for selection. - * @param {goog.ui.Component} grid The grid which is updated with a new set of - * characters. - * @private - */ -goog.ui.CharPicker.prototype.populateGridWithButtons_ = function(grid) { - for (var i = 0; i < grid.buttoncount; i++) { - var button = new goog.ui.Button(' ', - goog.ui.FlatButtonRenderer.getInstance()); - grid.addChild(button, true); - button.setVisible(false); - - var buttonEl = button.getElement(); - goog.dom.a11y.setRole(buttonEl, 'gridcell'); - } -}; - - -/** - * Updates the grid cell with new character. - * @param {goog.ui.Component} button This button is proped up for new character. - * @param {string} ch Character to be displayed by the button. - * @private - */ -goog.ui.CharPicker.prototype.modifyCharNode_ = function(button, ch) { - var text = this.displayChar_(ch); - var buttonEl = button.getElement(); - buttonEl.innerHTML = text; - buttonEl.setAttribute('char', ch); - goog.dom.setFocusableTabIndex(buttonEl, false); - button.setVisible(true); -}; - - -/** - * Adds a given character to the recent character list. - * @param {string} character Character to be added to the recent list. - * @private - */ -goog.ui.CharPicker.prototype.updateRecents_ = function(character) { - if (character && character.charCodeAt(0) && - !goog.array.contains(this.recents_, character)) { - this.recents_.unshift(character); - if (this.recents_.length > this.recentwidth_) { - this.recents_.pop(); - } - this.updateGrid_(this.recentgrid_, this.recents_); - } -}; - - -/** - * Gets the user inputed unicode character. - * @return {string} Unicode character inputed by user. - * @private - */ -goog.ui.CharPicker.prototype.getInputChar_ = function() { - var text = this.input_.getValue(); - var code = parseInt(text, 16); - return /** @type {string} */ (goog.i18n.uChar.fromCharCode(code)); -}; - - -/** - * Gets the description text for the given character. - * @param {string} ch Character whose description is fetched. - * @return {string} The description of the given character. - * @private - */ -goog.ui.CharPicker.prototype.getTagFromChar_ = function(ch) { - var unicodetext = goog.i18n.uChar.toHexString(ch); - var name = goog.i18n.uChar.toName(ch); - if (name) { - unicodetext += ' ' + name; - } - return unicodetext; -}; - - -/** - * Gets the display character for the given character. - * @param {string} ch Character whose display is fetched. - * @return {string} The display of the given character. - * @private - */ -goog.ui.CharPicker.prototype.displayChar_ = function(ch) { - return this.layoutAlteringChars_.contains(ch) ? '\u00A0' : ch; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/checkbox.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/checkbox.js.svn-base deleted file mode 100644 index db4d7d7..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/checkbox.js.svn-base +++ /dev/null @@ -1,262 +0,0 @@ -// 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.dom.a11y'); -goog.require('goog.dom.a11y.State'); -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. - */ -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. - */ -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'); - } - goog.dom.a11y.setState(this.getElement(), - goog.dom.a11y.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(); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/checkbox_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/checkbox_test.html.svn-base deleted file mode 100644 index 89d64b9..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/checkbox_test.html.svn-base +++ /dev/null @@ -1,370 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2009 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.Checkbox</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.dom.a11y'); - goog.require('goog.dom.a11y.Role'); - goog.require('goog.dom.a11y.State'); - goog.require('goog.dom.classes'); - goog.require('goog.events'); - goog.require('goog.events.KeyCodes'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Checkbox'); - goog.require('goog.ui.Checkbox.State'); - goog.require('goog.ui.CheckboxRenderer'); - goog.require('goog.ui.Component.EventType'); - goog.require('goog.ui.Component.State'); - goog.require('goog.ui.ControlRenderer'); - goog.require('goog.ui.decorate'); - </script> -</head> -<body> -<div> - <span id="decorate" class="goog-checkbox"></span> - <span id="normal" class="goog-checkbox"></span> - <span id="checked" class="goog-checkbox goog-checkbox-checked"></span> - <span id="unchecked" class="goog-checkbox goog-checkbox-unchecked"></span> - <span id="undetermined" class="goog-checkbox goog-checkbox-undetermined"> - </span> - <span id="disabled" class="goog-checkbox goog-checkbox-disabled"></span> -</div> -<script type="text/javascript"> - var checkbox; - - function setUp() { - checkbox = new goog.ui.Checkbox(); - } - - function tearDown() { - checkbox.dispose(); - } - - function testClassNames() { - checkbox.createDom(); - - checkbox.setChecked(false); - assertSameElements('classnames of unchecked checkbox', - ['goog-checkbox', 'goog-checkbox-unchecked'], - goog.dom.classes.get(checkbox.getElement())); - - checkbox.setChecked(true); - assertSameElements('classnames of checked checkbox', - ['goog-checkbox', 'goog-checkbox-checked'], - goog.dom.classes.get(checkbox.getElement())); - - checkbox.setChecked(null); - assertSameElements('classnames of partially checked checkbox', - ['goog-checkbox', 'goog-checkbox-undetermined'], - goog.dom.classes.get(checkbox.getElement())); - - checkbox.setEnabled(false); - assertSameElements('classnames of partially checked disabled checkbox', - ['goog-checkbox', - 'goog-checkbox-undetermined', - 'goog-checkbox-disabled'], - goog.dom.classes.get(checkbox.getElement())); - } - - function testIsEnabled() { - assertTrue('enabled by default', checkbox.isEnabled()); - checkbox.setEnabled(false); - assertFalse('has been disabled', checkbox.isEnabled()); - } - - function testCheckedState() { - assertTrue('unchecked by default', !checkbox.isChecked() && - checkbox.isUnchecked() && !checkbox.isUndetermined()); - - checkbox.setChecked(true); - assertTrue('set to checked', checkbox.isChecked() && - !checkbox.isUnchecked() && !checkbox.isUndetermined()); - - checkbox.setChecked(null); - assertTrue('set to partially checked', !checkbox.isChecked() && - !checkbox.isUnchecked() && checkbox.isUndetermined()); - } - - function testToggle() { - checkbox.setChecked(null); - checkbox.toggle(); - assertTrue('undetermined -> checked', checkbox.getChecked()); - checkbox.toggle(); - assertFalse('checked -> unchecked', checkbox.getChecked()); - checkbox.toggle(); - assertTrue('unchecked -> checked', checkbox.getChecked()); - } - - function testEvents() { - checkbox.render(); - - var events = []; - goog.events.listen(checkbox, - [goog.ui.Component.EventType.CHECK, - goog.ui.Component.EventType.UNCHECK, - goog.ui.Component.EventType.CHANGE], - function(e) { - events.push(e.type); - }); - - checkbox.setEnabled(false); - goog.testing.events.fireClickSequence(checkbox.getElement()); - assertArrayEquals('disabled => no events', [], events); - assertFalse('checked state did not change', checkbox.getChecked()); - events = []; - - checkbox.setEnabled(true); - goog.testing.events.fireClickSequence(checkbox.getElement()); - assertArrayEquals('CHECK+CHANGE fired', ['check', 'change'], events); - assertTrue('checkbox became checked', checkbox.getChecked()); - events = []; - - goog.testing.events.fireClickSequence(checkbox.getElement()); - assertArrayEquals('UNCHECK+CHANGE fired', ['uncheck', 'change'], events); - assertFalse('checkbox became unchecked', checkbox.getChecked()); - events = []; - - goog.events.listen(checkbox, goog.ui.Component.EventType.CHECK, - function(e) { - e.preventDefault(); - }); - goog.testing.events.fireClickSequence(checkbox.getElement()); - assertArrayEquals('CHECK event fired', ['check'], events); - assertFalse('toggling has been prevented', checkbox.getChecked()); - } - - function testCheckboxAriaLabelledby() { - var label = goog.dom.createElement('div'); - var label2 = goog.dom.createElement('div', {id: checkbox.makeId('foo')}); - document.body.appendChild(label); - document.body.appendChild(label2); - try { - checkbox.setChecked(false); - checkbox.setLabel(label); - checkbox.render(label); - - assertEquals(label.id, - goog.dom.a11y.getState(checkbox.getElement(), - goog.dom.a11y.State.LABELLEDBY)); - - checkbox.setLabel(label2); - assertEquals(label2.id, - goog.dom.a11y.getState(checkbox.getElement(), - goog.dom.a11y.State.LABELLEDBY)); - } finally { - document.body.removeChild(label); - document.body.removeChild(label2); - } - } - - function testLabel() { - var label = goog.dom.createElement('div'); - document.body.appendChild(label); - try { - checkbox.setChecked(false); - checkbox.setLabel(label); - checkbox.render(label); - - // Clicking on label toggles checkbox. - goog.testing.events.fireClickSequence(label); - assertTrue('checkbox toggled if the label is clicked', - checkbox.getChecked()); - goog.testing.events.fireClickSequence(checkbox.getElement()); - assertFalse('checkbox toggled if it is clicked', checkbox.getChecked()); - - // Test that mouse events on the label have the correct effect on the - // checkbox state when it is enabled. - checkbox.setEnabled(true); - goog.testing.events.fireMouseOverEvent(label); - assertTrue(checkbox.hasState(goog.ui.Component.State.HOVER)); - assertContains('checkbox gets hover state on mouse over', - 'goog-checkbox-hover', goog.dom.classes.get(checkbox.getElement())); - goog.testing.events.fireMouseDownEvent(label); - assertTrue(checkbox.hasState(goog.ui.Component.State.ACTIVE)); - assertContains('checkbox gets active state on label mousedown', - 'goog-checkbox-active', goog.dom.classes.get(checkbox.getElement())); - goog.testing.events.fireMouseOutEvent(checkbox.getElement()); - assertFalse(checkbox.hasState(goog.ui.Component.State.HOVER)); - assertNotContains('checkbox does not have hover state after mouse out', - 'goog-checkbox-hover', goog.dom.classes.get(checkbox.getElement())); - assertFalse(checkbox.hasState(goog.ui.Component.State.ACTIVE)); - assertNotContains('checkbox does not have active state after mouse out', - 'goog-checkbox-active', goog.dom.classes.get(checkbox.getElement())); - - // Test label mouse events on disabled checkbox. - checkbox.setEnabled(false); - goog.testing.events.fireMouseOverEvent(label); - assertFalse(checkbox.hasState(goog.ui.Component.State.HOVER)); - assertNotContains( - 'disabled checkbox does not get hover state on mouseover', - 'goog-checkbox-hover', goog.dom.classes.get(checkbox.getElement())); - goog.testing.events.fireMouseDownEvent(label); - assertFalse(checkbox.hasState(goog.ui.Component.State.ACTIVE)); - assertNotContains('disabled checkbox does not get active state mousedown', - 'goog-checkbox-active', goog.dom.classes.get(checkbox.getElement())); - goog.testing.events.fireMouseOutEvent(checkbox.getElement()); - assertFalse(checkbox.hasState(goog.ui.Component.State.ACTIVE)); - assertNotContains('checkbox does not get stuck in hover state', - 'goog-checkbox-hover', goog.dom.classes.get(checkbox.getElement())); - - // Making the label null prevents it from affecting checkbox state. - checkbox.setEnabled(true); - checkbox.setLabel(null); - goog.testing.events.fireClickSequence(label); - assertFalse('label element deactivated', checkbox.getChecked()); - goog.testing.events.fireClickSequence(checkbox.getElement()); - assertTrue('checkbox still active', checkbox.getChecked()); - } finally { - document.body.removeChild(label); - } - } - - function testConstructor() { - assertEquals('state is unchecked', goog.ui.Checkbox.State.UNCHECKED, - checkbox.getChecked()); - - var testCheckboxWithState = new goog.ui.Checkbox( - goog.ui.Checkbox.State.UNDETERMINED); - assertNotNull('checkbox created with custom state', testCheckboxWithState); - assertEquals('checkbox state is undetermined', - goog.ui.Checkbox.State.UNDETERMINED, - testCheckboxWithState.getChecked()); - testCheckboxWithState.dispose(); - } - - function testCustomRenderer() { - var cssClass = 'my-custom-checkbox'; - var renderer = goog.ui.ControlRenderer.getCustomRenderer( - goog.ui.CheckboxRenderer, cssClass); - var customCheckbox = new goog.ui.Checkbox( - undefined, undefined, renderer); - customCheckbox.createDom(); - assertElementsEquals( - ['my-custom-checkbox', 'my-custom-checkbox-unchecked'], - goog.dom.classes.get(customCheckbox.getElement())); - customCheckbox.setChecked(true); - assertElementsEquals( - ['my-custom-checkbox', 'my-custom-checkbox-checked'], - goog.dom.classes.get(customCheckbox.getElement())); - customCheckbox.setChecked(null); - assertElementsEquals( - ['my-custom-checkbox', 'my-custom-checkbox-undetermined'], - goog.dom.classes.get(customCheckbox.getElement())); - customCheckbox.dispose(); - } - - function testGetAriaRole() { - checkbox.createDom(); - - assertEquals("Checkbox's ARIA role should be 'checkbox'", - goog.dom.a11y.Role.CHECKBOX, - goog.dom.a11y.getRole(checkbox.getElement())); - } - - function testCreateDomUpdateAriaState() { - checkbox.createDom(); - - assertEquals('Checkbox must have default false ARIA state aria-checked', - 'false', goog.dom.a11y.getState(checkbox.getElement(), - goog.dom.a11y.State.CHECKED)); - - checkbox.setChecked(goog.ui.Checkbox.State.CHECKED); - assertEquals('Checkbox must have true ARIA state aria-checked', 'true', - goog.dom.a11y.getState(checkbox.getElement(), - goog.dom.a11y.State.CHECKED)); - - checkbox.setChecked(goog.ui.Checkbox.State.UNCHECKED); - assertEquals('Checkbox must have false ARIA state aria-checked', 'false', - goog.dom.a11y.getState(checkbox.getElement(), - goog.dom.a11y.State.CHECKED)); - - checkbox.setChecked(goog.ui.Checkbox.State.UNDETERMINED); - assertEquals('Checkbox must have mixed ARIA state aria-checked', 'mixed', - goog.dom.a11y.getState(checkbox.getElement(), - goog.dom.a11y.State.CHECKED)); - } - - function testDecorateUpdateAriaState() { - var decorateSpan = goog.dom.getElement('decorate'); - checkbox.decorate(decorateSpan); - - assertEquals('Checkbox must have default false ARIA state aria-checked', - 'false', goog.dom.a11y.getState(checkbox.getElement(), - goog.dom.a11y.State.CHECKED)); - - checkbox.setChecked(goog.ui.Checkbox.State.CHECKED); - assertEquals('Checkbox must have true ARIA state aria-checked', 'true', - goog.dom.a11y.getState(checkbox.getElement(), - goog.dom.a11y.State.CHECKED)); - - checkbox.setChecked(goog.ui.Checkbox.State.UNCHECKED); - assertEquals('Checkbox must have false ARIA state aria-checked', 'false', - goog.dom.a11y.getState(checkbox.getElement(), - goog.dom.a11y.State.CHECKED)); - - checkbox.setChecked(goog.ui.Checkbox.State.UNDETERMINED); - assertEquals('Checkbox must have mixed ARIA state aria-checked', 'mixed', - goog.dom.a11y.getState(checkbox.getElement(), - goog.dom.a11y.State.CHECKED)); - } - - function testSpaceKey() { - var normalSpan = goog.dom.getElement('normal'); - - checkbox.decorate(normalSpan); - assertEquals('default state is unchecked', - goog.ui.Checkbox.State.UNCHECKED, checkbox.getChecked()); - goog.testing.events.fireKeySequence(normalSpan, goog.events.KeyCodes.SPACE); - assertEquals('SPACE toggles checkbox to be checked', - goog.ui.Checkbox.State.CHECKED, checkbox.getChecked()); - goog.testing.events.fireKeySequence(normalSpan, goog.events.KeyCodes.SPACE); - assertEquals('another SPACE toggles checkbox to be unchecked', - goog.ui.Checkbox.State.UNCHECKED, checkbox.getChecked()); - - // Enter for example doesn't work - goog.testing.events.fireKeySequence(normalSpan, goog.events.KeyCodes.ENTER); - assertEquals('Enter leaves checkbox unchecked', - goog.ui.Checkbox.State.UNCHECKED, checkbox.getChecked()); - } - - function testDecorate() { - var normalSpan = goog.dom.getElement('normal'); - var checkedSpan = goog.dom.getElement('checked'); - var uncheckedSpan = goog.dom.getElement('unchecked'); - var undeterminedSpan = goog.dom.getElement('undetermined'); - var disabledSpan = goog.dom.getElement('disabled'); - - validateCheckBox(normalSpan, goog.ui.Checkbox.State.UNCHECKED); - validateCheckBox(checkedSpan, goog.ui.Checkbox.State.CHECKED); - validateCheckBox(uncheckedSpan, goog.ui.Checkbox.State.UNCHECKED); - validateCheckBox(undeterminedSpan, goog.ui.Checkbox.State.UNDETERMINED); - validateCheckBox(disabledSpan, goog.ui.Checkbox.State.UNCHECKED, true); - } - - function validateCheckBox(span, state, opt_disabled) { - var testCheckbox = goog.ui.decorate(span); - assertNotNull('checkbox created', testCheckbox); - assertEquals('decorate was successful', - goog.ui.Checkbox, testCheckbox.constructor); - assertEquals('checkbox state should be: ' + state, state, - testCheckbox.getChecked()); - assertEquals('checkbox is ' + (!opt_disabled ? 'enabled' : 'disabled'), - !opt_disabled, testCheckbox.isEnabled()); - testCheckbox.dispose(); - } - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/checkboxmenuitem.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/checkboxmenuitem.js.svn-base deleted file mode 100644 index c66127e..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/checkboxmenuitem.js.svn-base +++ /dev/null @@ -1,54 +0,0 @@ -// 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 menu item class that supports checkbox semantics. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.CheckBoxMenuItem'); - -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.MenuItem'); -goog.require('goog.ui.registry'); - - - -/** - * Class representing a checkbox menu item. This is just a convenience class - * that extends {@link goog.ui.MenuItem} by making it checkable. - * - * @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 {*=} opt_model Data/model associated with the menu item. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper used for - * document interactions. - * @constructor - * @extends {goog.ui.MenuItem} - */ -goog.ui.CheckBoxMenuItem = function(content, opt_model, opt_domHelper) { - goog.ui.MenuItem.call(this, content, opt_model, opt_domHelper); - this.setCheckable(true); -}; -goog.inherits(goog.ui.CheckBoxMenuItem, goog.ui.MenuItem); - - -// Register a decorator factory function for goog.ui.CheckBoxMenuItems. -goog.ui.registry.setDecoratorByClassName( - goog.getCssName('goog-checkbox-menuitem'), function() { - // CheckBoxMenuItem defaults to using MenuItemRenderer. - return new goog.ui.CheckBoxMenuItem(null); -}); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/checkboxrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/checkboxrenderer.js.svn-base deleted file mode 100644 index 5866a18..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/checkboxrenderer.js.svn-base +++ /dev/null @@ -1,171 +0,0 @@ -// 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 Default renderer for {@link goog.ui.Checkbox}s. - * - */ - -goog.provide('goog.ui.CheckboxRenderer'); - -goog.require('goog.array'); -goog.require('goog.asserts'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.a11y.Role'); -goog.require('goog.dom.a11y.State'); -goog.require('goog.dom.classes'); -goog.require('goog.object'); -goog.require('goog.ui.ControlRenderer'); - - - -/** - * Default renderer for {@link goog.ui.Checkbox}s. Extends the superclass - * to support checkbox states: - * @constructor - * @extends {goog.ui.ControlRenderer} - */ -goog.ui.CheckboxRenderer = function() { - goog.base(this); -}; -goog.inherits(goog.ui.CheckboxRenderer, goog.ui.ControlRenderer); -goog.addSingletonGetter(goog.ui.CheckboxRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.CheckboxRenderer.CSS_CLASS = goog.getCssName('goog-checkbox'); - - -/** @override */ -goog.ui.CheckboxRenderer.prototype.createDom = function(checkbox) { - var element = checkbox.getDomHelper().createDom( - 'span', this.getClassNames(checkbox).join(' ')); - - var state = checkbox.getChecked(); - this.setCheckboxState(element, state); - - return element; -}; - - -/** @override */ -goog.ui.CheckboxRenderer.prototype.decorate = function(checkbox, element) { - // The superclass implementation takes care of common attributes; we only - // need to set the checkbox state. - element = goog.base(this, 'decorate', checkbox, element); - - var classes = goog.dom.classes.get(element); - // Update the checked state of the element based on its css classNames - // with the following order: undetermined -> checked -> unchecked. - var checked = goog.ui.Checkbox.State.UNCHECKED; - if (goog.array.contains(classes, - this.getClassForCheckboxState(goog.ui.Checkbox.State.UNDETERMINED))) { - checked = goog.ui.Checkbox.State.UNDETERMINED; - } else if (goog.array.contains(classes, - this.getClassForCheckboxState(goog.ui.Checkbox.State.CHECKED))) { - checked = goog.ui.Checkbox.State.CHECKED; - } else if (goog.array.contains(classes, - this.getClassForCheckboxState(goog.ui.Checkbox.State.UNCHECKED))) { - checked = goog.ui.Checkbox.State.UNCHECKED; - } - checkbox.setCheckedInternal(checked); - - goog.dom.a11y.setState(element, goog.dom.a11y.State.CHECKED, - this.ariaStateFromCheckState_(checked)); - - return element; -}; - - -/** - * Returns the ARIA role to be applied to checkboxes. - * @return {goog.dom.a11y.Role} ARIA role. - * @override - */ -goog.ui.CheckboxRenderer.prototype.getAriaRole = function() { - return goog.dom.a11y.Role.CHECKBOX; -}; - - -/** - * Updates the appearance of the control in response to a checkbox state - * change. - * @param {Element} element Checkbox element. - * @param {goog.ui.Checkbox.State} state Updated checkbox state. - */ -goog.ui.CheckboxRenderer.prototype.setCheckboxState = function( - element, state) { - if (element) { - var classToAdd = this.getClassForCheckboxState(state); - goog.asserts.assert(classToAdd); - if (goog.dom.classes.has(element, classToAdd)) { - return; - } - goog.object.forEach(goog.ui.Checkbox.State, function(state) { - var className = this.getClassForCheckboxState(state); - goog.dom.classes.enable(element, className, - className == classToAdd); - }, this); - goog.dom.a11y.setState(element, goog.dom.a11y.State.CHECKED, - this.ariaStateFromCheckState_(state)); - } -}; - - -/** - * Gets the checkbox's ARIA (accessibility) state from its checked state. - * @param {goog.ui.Checkbox.State} state Checkbox state. - * @return {string} The value of goog.dom.a11y.state.CHECKED. Either 'true', - * 'false', or 'mixed'. - * @private - */ -goog.ui.CheckboxRenderer.prototype.ariaStateFromCheckState_ = function(state) { - if (state == goog.ui.Checkbox.State.UNDETERMINED) { - return 'mixed'; - } else if (state == goog.ui.Checkbox.State.CHECKED) { - return 'true'; - } else { - return 'false'; - } -}; - - -/** @override */ -goog.ui.CheckboxRenderer.prototype.getCssClass = function() { - return goog.ui.CheckboxRenderer.CSS_CLASS; -}; - - -/** - * Takes a single {@link goog.ui.Checkbox.State}, and returns the - * corresponding CSS class name. - * @param {goog.ui.Checkbox.State} state Checkbox state. - * @return {string} CSS class representing the given state. - * @protected - */ -goog.ui.CheckboxRenderer.prototype.getClassForCheckboxState = function(state) { - var baseClass = this.getStructuralCssClass(); - if (state == goog.ui.Checkbox.State.CHECKED) { - return goog.getCssName(baseClass, 'checked'); - } else if (state == goog.ui.Checkbox.State.UNCHECKED) { - return goog.getCssName(baseClass, 'unchecked'); - } else if (state == goog.ui.Checkbox.State.UNDETERMINED) { - return goog.getCssName(baseClass, 'undetermined'); - } - throw Error('Invalid checkbox state: ' + state); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorbutton.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorbutton.js.svn-base deleted file mode 100644 index de4aa7b..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorbutton.js.svn-base +++ /dev/null @@ -1,58 +0,0 @@ -// 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 color button rendered via - * {@link goog.ui.ColorButtonRenderer}. - * - */ - -goog.provide('goog.ui.ColorButton'); - -goog.require('goog.ui.Button'); -goog.require('goog.ui.ColorButtonRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * A color button control. Identical to {@link goog.ui.Button}, except it - * defaults its renderer to {@link goog.ui.ColorButtonRenderer}. - * This button displays a particular color and is clickable. - * It is primarily useful with {@link goog.ui.ColorSplitBehavior} to cache the - * last selected color. - * - * @param {goog.ui.ControlContent} content Text caption or existing DOM - * structure to display as the button's caption. - * @param {goog.ui.ButtonRenderer=} opt_renderer Optional renderer used to - * render or decorate the button; defaults to - * {@link goog.ui.ColorButtonRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for - * document interaction. - * @constructor - * @extends {goog.ui.Button} - */ -goog.ui.ColorButton = function(content, opt_renderer, opt_domHelper) { - goog.ui.Button.call(this, content, opt_renderer || - goog.ui.ColorButtonRenderer.getInstance(), opt_domHelper); -}; -goog.inherits(goog.ui.ColorButton, goog.ui.Button); - -// Register a decorator factory function for goog.ui.ColorButtons. -goog.ui.registry.setDecoratorByClassName(goog.ui.ColorButtonRenderer.CSS_CLASS, - function() { - // ColorButton defaults to using ColorButtonRenderer. - return new goog.ui.ColorButton(null); - }); - diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorbutton_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorbutton_test.html.svn-base deleted file mode 100644 index 6d307cb..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorbutton_test.html.svn-base +++ /dev/null @@ -1,70 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2010 The Closure Library Authors. All Rights Reserved - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.ColorButton</title> -<script type="text/javascript" src="../base.js"></script> -<script type="text/javascript"> - goog.require('goog.array'); - goog.require('goog.dom'); - goog.require('goog.dom.classes'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.ColorButton'); - goog.require('goog.ui.decorate'); -</script> -</head> -<body> - -<div id="buttonDiv"></div> - -<script type="text/javascript"> - -var button, button2; -var buttonDiv; - -function setUp() { - buttonDiv = goog.dom.getElement('buttonDiv'); -} - -function tearDown() { - goog.dom.removeChildren(buttonDiv); - goog.dispose(button); - goog.dispose(button2); - button = null; - button2 = null; -} - -function testRender() { - button = new goog.ui.ColorButton('test'); - assertNotNull('button should be valid', button); - button.render(buttonDiv); - assertColorButton(button.getElement()); -} - -function testDecorate() { - var colorDiv = goog.dom.createDom('div', 'goog-color-button'); - goog.dom.appendChild(buttonDiv, colorDiv); - button2 = goog.ui.decorate(colorDiv); - assertNotNull('button should be valid', button2); - assertColorButton(button2.getElement()); -} - -function assertColorButton(div) { - assertTrue('button className contains goog-color-button', - goog.array.contains(goog.dom.classes.get(div), 'goog-color-button')); - var caption = div.firstChild.firstChild.firstChild; - assertTrue('caption className contains goog-color-button', - goog.array.contains(goog.dom.classes.get(caption), 'goog-color-button')); -} - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorbuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorbuttonrenderer.js.svn-base deleted file mode 100644 index 7d26aa6..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorbuttonrenderer.js.svn-base +++ /dev/null @@ -1,72 +0,0 @@ -// 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 Renderer for {@link goog.ui.ColorButton}s. - * - */ - -goog.provide('goog.ui.ColorButtonRenderer'); - -goog.require('goog.dom.classes'); -goog.require('goog.functions'); -goog.require('goog.ui.ColorMenuButtonRenderer'); - - - -/** - * Renderer for {@link goog.ui.ColorButton}s. - * Uses {@link goog.ui.ColorMenuButton}s but disables the dropdown. - * - * @constructor - * @extends {goog.ui.ColorMenuButtonRenderer} - */ -goog.ui.ColorButtonRenderer = function() { - goog.base(this); - - /** - * @override - */ - // TODO(user): enable disabling the dropdown in goog.ui.ColorMenuButton - this.createDropdown = goog.functions.NULL; - -}; -goog.inherits(goog.ui.ColorButtonRenderer, goog.ui.ColorMenuButtonRenderer); -goog.addSingletonGetter(goog.ui.ColorButtonRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. Additionally, applies class to the button's caption. - * @type {string} - */ -goog.ui.ColorButtonRenderer.CSS_CLASS = goog.getCssName('goog-color-button'); - - -/** @override */ -goog.ui.ColorButtonRenderer.prototype.createCaption = function(content, dom) { - var caption = goog.base(this, 'createCaption', content, dom); - goog.dom.classes.add(caption, goog.ui.ColorButtonRenderer.CSS_CLASS); - return caption; -}; - - -/** @override */ -goog.ui.ColorButtonRenderer.prototype.initializeDom = function(button) { - goog.base(this, 'initializeDom', button); - goog.dom.classes.add(button.getElement(), - goog.ui.ColorButtonRenderer.CSS_CLASS); -}; - - diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colormenubutton.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colormenubutton.js.svn-base deleted file mode 100644 index 9be17ed..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colormenubutton.js.svn-base +++ /dev/null @@ -1,213 +0,0 @@ -// 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 color menu button. Extends {@link goog.ui.MenuButton} by - * showing the currently selected color in the button caption. - * - * @author robbyw@google.com (Robby Walker) - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.ColorMenuButton'); - -goog.require('goog.array'); -goog.require('goog.object'); -goog.require('goog.ui.ColorMenuButtonRenderer'); -goog.require('goog.ui.ColorPalette'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.Menu'); -goog.require('goog.ui.MenuButton'); -goog.require('goog.ui.registry'); - - - -/** - * A color menu button control. Extends {@link goog.ui.MenuButton} by adding - * an API for getting and setting the currently selected color from a menu of - * color palettes. - * - * @param {goog.ui.ControlContent} content Text caption or existing DOM - * structure to display as the button's caption. - * @param {goog.ui.Menu=} opt_menu Menu to render under the button when clicked; - * should contain at least one {@link goog.ui.ColorPalette} if present. - * @param {goog.ui.MenuButtonRenderer=} opt_renderer Button renderer; - * defaults to {@link goog.ui.ColorMenuButtonRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for - * document interaction. - * @constructor - * @extends {goog.ui.MenuButton} - */ -goog.ui.ColorMenuButton = function(content, opt_menu, opt_renderer, - opt_domHelper) { - goog.ui.MenuButton.call(this, content, opt_menu, opt_renderer || - goog.ui.ColorMenuButtonRenderer.getInstance(), opt_domHelper); -}; -goog.inherits(goog.ui.ColorMenuButton, goog.ui.MenuButton); - - -/** - * Default color palettes. - * @type {!Object} - */ -goog.ui.ColorMenuButton.PALETTES = { - /** Default grayscale colors. */ - GRAYSCALE: [ - '#000', '#444', '#666', '#999', '#ccc', '#eee', '#f3f3f3', '#fff' - ], - - /** Default solid colors. */ - SOLID: [ - '#f00', '#f90', '#ff0', '#0f0', '#0ff', '#00f', '#90f', '#f0f' - ], - - /** Default pastel colors. */ - PASTEL: [ - '#f4cccc', '#fce5cd', '#fff2cc', '#d9ead3', '#d0e0e3', '#cfe2f3', '#d9d2e9', - '#ead1dc', - '#ea9999', '#f9cb9c', '#ffe599', '#b6d7a8', '#a2c4c9', '#9fc5e8', '#b4a7d6', - '#d5a6bd', - '#e06666', '#f6b26b', '#ffd966', '#93c47d', '#76a5af', '#6fa8dc', '#8e7cc3', - '#c27ba0', - '#cc0000', '#e69138', '#f1c232', '#6aa84f', '#45818e', '#3d85c6', '#674ea7', - '#a64d79', - '#990000', '#b45f06', '#bf9000', '#38761d', '#134f5c', '#0b5394', '#351c75', - '#741b47', - '#660000', '#783f04', '#7f6000', '#274e13', '#0c343d', '#073763', '#20124d', - '#4c1130' - ] -}; - - -/** - * Value for the "no color" menu item object in the color menu (if present). - * The {@link goog.ui.ColorMenuButton#handleMenuAction} method interprets - * ACTION events dispatched by an item with this value as meaning "clear the - * selected color." - * @type {string} - */ -goog.ui.ColorMenuButton.NO_COLOR = 'none'; - - -/** - * Factory method that creates and returns a new {@link goog.ui.Menu} instance - * containing default color palettes. - * @param {Array.<goog.ui.Control>=} opt_extraItems Optional extra menu items to - * add before the color palettes. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for - * document interaction. - * @return {goog.ui.Menu} Color menu. - */ -goog.ui.ColorMenuButton.newColorMenu = function(opt_extraItems, opt_domHelper) { - var menu = new goog.ui.Menu(opt_domHelper); - - if (opt_extraItems) { - goog.array.forEach(opt_extraItems, function(item) { - menu.addChild(item, true); - }); - } - - goog.object.forEach(goog.ui.ColorMenuButton.PALETTES, function(colors) { - var palette = new goog.ui.ColorPalette(colors, null, opt_domHelper); - palette.setSize(8); - menu.addChild(palette, true); - }); - - return menu; -}; - - -/** - * Returns the currently selected color (null if none). - * @return {?string} The selected color. - */ -goog.ui.ColorMenuButton.prototype.getSelectedColor = function() { - return /** @type {string} */ (this.getValue()); -}; - - -/** - * Sets the selected color, or clears the selected color if the argument is - * null or not any of the available color choices. - * @param {?string} color New color. - */ -goog.ui.ColorMenuButton.prototype.setSelectedColor = function(color) { - this.setValue(color); -}; - - -/** - * Sets the value associated with the color menu button. Overrides - * {@link goog.ui.Button#setValue} by interpreting the value as a color - * spec string. - * @param {?string} color New button value; should be a color spec string. - */ -goog.ui.ColorMenuButton.prototype.setValue = function(color) { - for (var i = 0, item; item = this.getItemAt(i); i++) { - if (typeof item.setSelectedColor == 'function') { - // This menu item looks like a color palette. - item.setSelectedColor(color); - } - } - goog.ui.ColorMenuButton.superClass_.setValue.call(this, color); -}; - - -/** - * Handles {@link goog.ui.Component.EventType.ACTION} events dispatched by - * the menu item clicked by the user. Updates the button, calls the superclass - * implementation to hide the menu, stops the propagation of the event, and - * dispatches an ACTION event on behalf of the button itself. Overrides - * {@link goog.ui.MenuButton#handleMenuAction}. - * @param {goog.events.Event} e Action event to handle. - */ -goog.ui.ColorMenuButton.prototype.handleMenuAction = function(e) { - if (typeof e.target.getSelectedColor == 'function') { - // User clicked something that looks like a color palette. - this.setValue(e.target.getSelectedColor()); - } else if (e.target.getValue() == goog.ui.ColorMenuButton.NO_COLOR) { - // User clicked the special "no color" menu item. - this.setValue(null); - } - goog.ui.ColorMenuButton.superClass_.handleMenuAction.call(this, e); - e.stopPropagation(); - this.dispatchEvent(goog.ui.Component.EventType.ACTION); -}; - - -/** - * Opens or closes the menu. Overrides {@link goog.ui.MenuButton#setOpen} by - * generating a default color menu on the fly if needed. - * @param {boolean} open Whether to open or close the menu. - * @param {goog.events.Event=} opt_e Mousedown event that caused the menu to - * be opened. - * @override - */ -goog.ui.ColorMenuButton.prototype.setOpen = function(open, opt_e) { - if (open && this.getItemCount() == 0) { - this.setMenu( - goog.ui.ColorMenuButton.newColorMenu(null, this.getDomHelper())); - this.setValue(/** @type {?string} */ (this.getValue())); - } - goog.ui.ColorMenuButton.superClass_.setOpen.call(this, open, opt_e); -}; - - -// Register a decorator factory function for goog.ui.ColorMenuButtons. -goog.ui.registry.setDecoratorByClassName( - goog.ui.ColorMenuButtonRenderer.CSS_CLASS, - function() { - return new goog.ui.ColorMenuButton(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colormenubuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colormenubuttonrenderer.js.svn-base deleted file mode 100644 index 61f828c..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colormenubuttonrenderer.js.svn-base +++ /dev/null @@ -1,144 +0,0 @@ -// 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. - */ -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. - */ -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; - - /** @preserveTry */ - try { - hexColor = goog.color.parse(/** @type {string} */ (value)).hex; - } catch (ex) { - hexColor = 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.ColorMenuButton} button Button whose DOM is to be - * initialized as it enters the document. - */ -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); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colormenubuttonrenderer_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colormenubuttonrenderer_test.html.svn-base deleted file mode 100644 index 04f3200..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colormenubuttonrenderer_test.html.svn-base +++ /dev/null @@ -1,88 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2009 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - - @author nicksantos@google.com (Nick Santos) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests for ColorMenuButtonRenderer</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.dom.classes'); - goog.require('goog.events'); - goog.require('goog.events.Event'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.ui.RendererHarness'); - goog.require('goog.testing.ui.rendererasserts'); - goog.require('goog.ui.ColorMenuButton'); - goog.require('goog.userAgent'); -</script> -</head> -<body> - -<div id='root'> - <!-- A parent to attach rendered buttons to --> - <div id='parent'></div> - - <!-- A button to decorate --> - <div id='decoratedButton'><div>Foo</div></div> -</div> - -<script> - -var harness; - -function setUp() { - harness = new goog.testing.ui.RendererHarness( - goog.ui.ColorMenuButtonRenderer.getInstance(), - goog.dom.getElement('parent'), - goog.dom.getElement('decoratedButton')); -} - -function tearDown() { - harness.dispose(); -} - -function testEquality() { - harness.attachControlAndRender( - new goog.ui.ColorMenuButton('Foo')); - harness.attachControlAndDecorate( - new goog.ui.ColorMenuButton()); - harness.assertDomMatches(); -} - -function testWrapCaption() { - var caption = goog.dom.createDom('div', null, 'Foo'); - var wrappedCaption = goog.ui.ColorMenuButtonRenderer.wrapCaption(caption, - goog.dom.getDomHelper()); - assertNotEquals('Caption should have been wrapped', caption, wrappedCaption); - assertEquals('Wrapped caption should have indicator css class', - 'goog-color-menu-button-indicator', wrappedCaption.className); -} - -function testSetCaptionValue() { - var caption = goog.dom.createDom('div', null, 'Foo'); - var wrappedCaption = goog.ui.ColorMenuButtonRenderer.wrapCaption(caption, - goog.dom.getDomHelper()); - goog.ui.ColorMenuButtonRenderer.setCaptionValue(wrappedCaption, 'red'); - - var expectedColor = goog.userAgent.IE ? '#ff0000' : 'rgb(255, 0, 0)'; - assertEquals(expectedColor, caption.style.borderBottomColor); -} - -function testDoesntCallGetCssClassInConstructor() { - goog.testing.ui.rendererasserts. - assertNoGetCssClassCallsInConstructor(goog.ui.ColorMenuButtonRenderer); -} -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorpalette.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorpalette.js.svn-base deleted file mode 100644 index 1da987c..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorpalette.js.svn-base +++ /dev/null @@ -1,162 +0,0 @@ -// 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 control for representing a palette of colors, that the user - * can highlight or select via the keyboard or the mouse. - * - */ - -goog.provide('goog.ui.ColorPalette'); - -goog.require('goog.array'); -goog.require('goog.color'); -goog.require('goog.dom'); -goog.require('goog.style'); -goog.require('goog.ui.Palette'); -goog.require('goog.ui.PaletteRenderer'); - - - -/** - * A color palette is a grid of color swatches that the user can highlight or - * select via the keyboard or the mouse. The selection state of the palette is - * controlled by a selection model. When the user makes a selection, the - * component fires an ACTION event. Event listeners may retrieve the selected - * color using the {@link #getSelectedColor} method. - * - * @param {Array.<string>=} opt_colors Array of colors in any valid CSS color - * format. - * @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.Palette} - */ -goog.ui.ColorPalette = function(opt_colors, opt_renderer, opt_domHelper) { - /** - * Array of colors to show in the palette. - * @type {Array.<string>} - * @private - */ - this.colors_ = opt_colors || []; - - goog.ui.Palette.call(this, null, - opt_renderer || goog.ui.PaletteRenderer.getInstance(), opt_domHelper); - - // Set the colors separately from the super call since we need the correct - // DomHelper to be initialized for this class. - this.setColors(this.colors_); -}; -goog.inherits(goog.ui.ColorPalette, goog.ui.Palette); - - -/** - * Array of normalized colors. Inited lazily as often never needed. - * @type {Array.<string>?} - * @private - */ -goog.ui.ColorPalette.prototype.normalizedColors_ = null; - - -/** - * Returns the array of colors represented in the color palette. - * @return {Array.<string>} Array of colors. - */ -goog.ui.ColorPalette.prototype.getColors = function() { - return this.colors_; -}; - - -/** - * Sets the colors that are contained in the palette. - * @param {Array.<string>} colors Array of colors in any valid CSS color format. - */ -goog.ui.ColorPalette.prototype.setColors = function(colors) { - this.colors_ = colors; - this.normalizedColors_ = null; - this.setContent(this.createColorNodes_()); -}; - - -/** - * @return {?string} The current selected color in hex, or null. - */ -goog.ui.ColorPalette.prototype.getSelectedColor = function() { - var selectedItem = /** @type {Element} */ (this.getSelectedItem()); - if (selectedItem) { - var color = goog.style.getStyle(selectedItem, 'background-color'); - return goog.ui.ColorPalette.parseColor_(color); - } else { - return null; - } -}; - - -/** - * Sets the selected color. Clears the selection if the argument is null or - * can't be parsed as a color. - * @param {?string} color The color to set as selected; null clears the - * selection. - */ -goog.ui.ColorPalette.prototype.setSelectedColor = function(color) { - var hexColor = goog.ui.ColorPalette.parseColor_(color); - if (!this.normalizedColors_) { - this.normalizedColors_ = goog.array.map(this.colors_, function(color) { - return goog.ui.ColorPalette.parseColor_(color); - }); - } - this.setSelectedIndex(hexColor ? - goog.array.indexOf(this.normalizedColors_, hexColor) : -1); -}; - - -/** - * @return {Array.<Node>} An array of DOM nodes for each color. - * @private - */ -goog.ui.ColorPalette.prototype.createColorNodes_ = function() { - return goog.array.map(this.colors_, function(color) { - var swatch = this.getDomHelper().createDom('div', { - 'class': goog.getCssName(this.getRenderer().getCssClass(), - 'colorswatch'), - 'style': 'background-color:' + color - }); - swatch.title = color.charAt(0) == '#' ? - 'RGB (' + goog.color.hexToRgb(color).join(', ') + ')' : color; - return swatch; - }, this); -}; - - -/** - * Takes a string, attempts to parse it as a color spec, and returns a - * normalized hex color spec if successful (null otherwise). - * @param {?string} color String possibly containing a color spec; may be null. - * @return {?string} Normalized hex color spec, or null if the argument can't - * be parsed as a color. - * @private - */ -goog.ui.ColorPalette.parseColor_ = function(color) { - if (color) { - /** @preserveTry */ - try { - return goog.color.parse(color).hex; - } catch (ex) { - // Fall through. - } - } - return null; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorpalette_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorpalette_test.html.svn-base deleted file mode 100644 index 26617cf..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorpalette_test.html.svn-base +++ /dev/null @@ -1,170 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- Author: attila@google.com (Attila Bodis) --> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.ColorPalette</title> - <script src="../base.js"></script> - <script> - goog.require('goog.color'); - goog.require('goog.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.ColorPalette'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var emptyPalette, samplePalette; - - function setUp() { - emptyPalette = new goog.ui.ColorPalette(); - samplePalette = new goog.ui.ColorPalette([ - 'red', '#00FF00', 'rgb(0, 0, 255)' - ]); - samplePalette.setSelectedColor('blue'); - } - - function tearDown() { - emptyPalette.dispose(); - samplePalette.dispose(); - document.getElementById('sandbox').innerHTML = ''; - } - - function testEmptyColorPalette() { - var colors = emptyPalette.getColors(); - assertNotNull(colors); - assertEquals(0, colors.length); - - var nodes = emptyPalette.getContent(); - assertNotNull(nodes); - assertEquals(0, nodes.length); - } - - function testSampleColorPalette() { - var colors = samplePalette.getColors(); - assertNotNull(colors); - assertEquals(3, colors.length); - assertEquals('red', colors[0]); - assertEquals('#00FF00', colors[1]); - assertEquals('rgb(0, 0, 255)', colors[2]); - - var nodes = samplePalette.getContent(); - assertNotNull(nodes); - assertEquals(3, nodes.length); - assertEquals('goog-palette-colorswatch', nodes[0].className); - assertEquals('goog-palette-colorswatch', nodes[1].className); - assertEquals('goog-palette-colorswatch', nodes[2].className); - assertEquals('#ff0000', - goog.color.parse(nodes[0].style.backgroundColor).hex); - assertEquals('#00ff00', - goog.color.parse(nodes[1].style.backgroundColor).hex); - assertEquals('#0000ff', - goog.color.parse(nodes[2].style.backgroundColor).hex); - } - - function testGetColors() { - var emptyColors = emptyPalette.getColors(); - assertNotNull(emptyColors); - assertEquals(0, emptyColors.length); - - var sampleColors = samplePalette.getColors(); - assertNotNull(sampleColors); - assertEquals(3, sampleColors.length); - assertEquals('red', sampleColors[0]); - assertEquals('#00FF00', sampleColors[1]); - assertEquals('rgb(0, 0, 255)', sampleColors[2]); - } - - function testSetColors() { - emptyPalette.setColors(['black', '#FFFFFF']); - - var colors = emptyPalette.getColors(); - assertNotNull(colors); - assertEquals(2, colors.length); - assertEquals('black', colors[0]); - assertEquals('#FFFFFF', colors[1]); - - var nodes = emptyPalette.getContent(); - assertNotNull(nodes); - assertEquals(2, nodes.length); - assertEquals('goog-palette-colorswatch', nodes[0].className); - assertEquals('goog-palette-colorswatch', nodes[1].className); - assertEquals('#000000', - goog.color.parse(nodes[0].style.backgroundColor).hex); - assertEquals('#ffffff', - goog.color.parse(nodes[1].style.backgroundColor).hex); - assertEquals('black', nodes[0].title); - assertEquals('RGB (255, 255, 255)', nodes[1].title); - - samplePalette.setColors(['#336699', 'cyan']); - - var newColors = samplePalette.getColors(); - assertNotNull(newColors); - assertEquals(2, newColors.length); - assertEquals('#336699', newColors[0]); - assertEquals('cyan', newColors[1]); - - var newNodes = samplePalette.getContent(); - assertNotNull(newNodes); - assertEquals(2, newNodes.length); - assertEquals('goog-palette-colorswatch', newNodes[0].className); - assertEquals('goog-palette-colorswatch', newNodes[1].className); - assertEquals('#336699', - goog.color.parse(newNodes[0].style.backgroundColor).hex); - assertEquals('#00ffff', - goog.color.parse(newNodes[1].style.backgroundColor).hex); - } - - function testRender() { - samplePalette.render(document.getElementById('sandbox')); - - assertTrue(samplePalette.isInDocument()); - - var elem = samplePalette.getElement(); - assertNotNull(elem); - assertEquals('DIV', elem.tagName); - assertEquals('goog-palette', elem.className); - - var table = elem.firstChild; - assertEquals('TABLE', table.tagName); - assertEquals('goog-palette-table', table.className); - - // TODO(attila): Each ColorPalette creates 12 listeners (13 on IE)! - assertEquals(goog.userAgent.IE ? 13 : 12, - goog.events.getTotalListenerCount()); - } - - function testGetSelectedColor() { - assertNull(emptyPalette.getSelectedColor()); - assertEquals('#0000ff', samplePalette.getSelectedColor()); - } - - function testSetSelectedColor() { - emptyPalette.setSelectedColor('red'); - assertNull(emptyPalette.getSelectedColor()); - - samplePalette.setSelectedColor('red'); - assertEquals('#ff0000', samplePalette.getSelectedColor()); - samplePalette.setSelectedColor(17); // Invalid color spec. - assertNull(samplePalette.getSelectedColor()); - - samplePalette.setSelectedColor('rgb(0, 255, 0)'); - assertEquals('#00ff00', samplePalette.getSelectedColor()); - samplePalette.setSelectedColor(false); // Invalid color spec. - assertNull(samplePalette.getSelectedColor()); - - samplePalette.setSelectedColor('#0000FF'); - assertEquals('#0000ff', samplePalette.getSelectedColor()); - samplePalette.setSelectedColor(null); // Invalid color spec. - assertNull(samplePalette.getSelectedColor()); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorpicker.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorpicker.js.svn-base deleted file mode 100644 index 8fce7db..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorpicker.js.svn-base +++ /dev/null @@ -1,344 +0,0 @@ -// 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 color picker component. A color picker can compose several - * instances of goog.ui.ColorPalette. - * - * NOTE: The ColorPicker is in a state of transition towards the common - * component/control/container interface we are developing. If the API changes - * we will do our best to update your code. The end result will be that a - * color picker will compose multiple color palettes. In the simple case this - * will be one grid, but may consistute 3 distinct grids, a custom color picker - * or even a color wheel. - * - */ - -goog.provide('goog.ui.ColorPicker'); -goog.provide('goog.ui.ColorPicker.EventType'); - -goog.require('goog.ui.ColorPalette'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.Component.State'); - - - -/** - * Create a new, empty color picker. - * - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @param {goog.ui.ColorPalette=} opt_colorPalette Optional color palette to - * use for this color picker. - * @extends {goog.ui.Component} - * @constructor - */ -goog.ui.ColorPicker = function(opt_domHelper, opt_colorPalette) { - goog.ui.Component.call(this, opt_domHelper); - - /** - * The color palette used inside the color picker. - * @type {goog.ui.ColorPalette?} - * @private - */ - this.colorPalette_ = opt_colorPalette || null; - - this.getHandler().listen( - this, goog.ui.Component.EventType.ACTION, this.onColorPaletteAction_); -}; -goog.inherits(goog.ui.ColorPicker, goog.ui.Component); - - -/** - * Default number of columns in the color palette. May be overridden by calling - * setSize. - * - * @type {number} - */ -goog.ui.ColorPicker.DEFAULT_NUM_COLS = 5; - - -/** - * Constants for event names. - * @enum {string} - */ -goog.ui.ColorPicker.EventType = { - CHANGE: 'change' -}; - - -/** - * Whether the component is focusable. - * @type {boolean} - * @private - */ -goog.ui.ColorPicker.prototype.focusable_ = true; - - -/** - * Gets the array of colors displayed by the color picker. - * Modifying this array will lead to unexpected behavior. - * @return {Array.<string>?} The colors displayed by this widget. - */ -goog.ui.ColorPicker.prototype.getColors = function() { - return this.colorPalette_ ? this.colorPalette_.getColors() : null; -}; - - -/** - * Sets the array of colors to be displayed by the color picker. - * @param {Array.<string>} colors The array of colors to be added. - */ -goog.ui.ColorPicker.prototype.setColors = function(colors) { - // TODO(user): Don't add colors directly, we should add palettes and the - // picker should support multiple palettes. - if (!this.colorPalette_) { - this.createColorPalette_(colors); - } else { - this.colorPalette_.setColors(colors); - } -}; - - -/** - * Sets the array of colors to be displayed by the color picker. - * @param {Array.<string>} colors The array of colors to be added. - * @deprecated Use setColors. - */ -goog.ui.ColorPicker.prototype.addColors = function(colors) { - this.setColors(colors); -}; - - -/** - * Sets the size of the palette. Will throw an error after the picker has been - * rendered. - * @param {goog.math.Size|number} size The size of the grid. - */ -goog.ui.ColorPicker.prototype.setSize = function(size) { - // TODO(user): The color picker should contain multiple palettes which will - // all be resized at this point. - if (!this.colorPalette_) { - this.createColorPalette_([]); - } - this.colorPalette_.setSize(size); -}; - - -/** - * Gets the number of columns displayed. - * @return {goog.math.Size?} The size of the grid. - */ -goog.ui.ColorPicker.prototype.getSize = function() { - return this.colorPalette_ ? this.colorPalette_.getSize() : null; -}; - - -/** - * Sets the number of columns. Will throw an error after the picker has been - * rendered. - * @param {number} n The number of columns. - * @deprecated Use setSize. - */ -goog.ui.ColorPicker.prototype.setColumnCount = function(n) { - this.setSize(n); -}; - - -/** - * @return {number} The index of the color selected. - */ -goog.ui.ColorPicker.prototype.getSelectedIndex = function() { - return this.colorPalette_ ? this.colorPalette_.getSelectedIndex() : -1; -}; - - -/** - * Sets which color is selected. A value that is out-of-range means that no - * color is selected. - * @param {number} ind The index in this.colors_ of the selected color. - */ -goog.ui.ColorPicker.prototype.setSelectedIndex = function(ind) { - if (this.colorPalette_) { - this.colorPalette_.setSelectedIndex(ind); - } -}; - - -/** - * Gets the color that is currently selected in this color picker. - * @return {?string} The hex string of the color selected, or null if no - * color is selected. - */ -goog.ui.ColorPicker.prototype.getSelectedColor = function() { - return this.colorPalette_ ? this.colorPalette_.getSelectedColor() : null; -}; - - -/** - * Sets which color is selected. Noop if the color palette hasn't been created - * yet. - * @param {string} color The selected color. - */ -goog.ui.ColorPicker.prototype.setSelectedColor = function(color) { - // TODO(user): This will set the color in the first available palette that - // contains it - if (this.colorPalette_) { - this.colorPalette_.setSelectedColor(color); - } -}; - - -/** - * Returns true if the component is focusable, false otherwise. The default - * is true. Focusable components always have a tab index and allocate a key - * handler to handle keyboard events while focused. - * @return {boolean} True iff the component is focusable. - */ -goog.ui.ColorPicker.prototype.isFocusable = function() { - return this.focusable_; -}; - - -/** - * Sets whether the component is focusable. The default is true. - * Focusable components always have a tab index and allocate a key handler to - * handle keyboard events while focused. - * @param {boolean} focusable True iff the component is focusable. - */ -goog.ui.ColorPicker.prototype.setFocusable = function(focusable) { - this.focusable_ = focusable; - if (this.colorPalette_) { - this.colorPalette_.setSupportedState(goog.ui.Component.State.FOCUSED, - focusable); - } -}; - - -/** - * ColorPickers cannot be used to decorate pre-existing html, since the - * structure they build is fairly complicated. - * @param {Element} element Element to decorate. - * @return {boolean} Returns always false. - */ -goog.ui.ColorPicker.prototype.canDecorate = function(element) { - return false; -}; - - -/** - * Renders the color picker inside the provided element. This will override the - * current content of the element. - * @override - */ -goog.ui.ColorPicker.prototype.enterDocument = function() { - goog.ui.ColorPicker.superClass_.enterDocument.call(this); - if (this.colorPalette_) { - this.colorPalette_.render(this.getElement()); - } - this.getElement().unselectable = 'on'; -}; - - -/** @override */ -goog.ui.ColorPicker.prototype.disposeInternal = function() { - goog.ui.ColorPicker.superClass_.disposeInternal.call(this); - if (this.colorPalette_) { - this.colorPalette_.dispose(); - this.colorPalette_ = null; - } -}; - - -/** - * Sets the focus to the color picker's palette. - */ -goog.ui.ColorPicker.prototype.focus = function() { - if (this.colorPalette_) { - this.colorPalette_.getElement().focus(); - } -}; - - -/** - * Handles actions from the color palette. - * - * @param {goog.events.Event} e The event. - * @private - */ -goog.ui.ColorPicker.prototype.onColorPaletteAction_ = function(e) { - e.stopPropagation(); - this.dispatchEvent(goog.ui.ColorPicker.EventType.CHANGE); -}; - - -/** - * Create a color palette for the color picker. - * @param {Array.<string>} colors Array of colors. - * @private - */ -goog.ui.ColorPicker.prototype.createColorPalette_ = function(colors) { - // TODO(user): The color picker should eventually just contain a number of - // palettes and manage the interactions between them. This will go away then. - var cp = new goog.ui.ColorPalette(colors, null, this.getDomHelper()); - cp.setSize(goog.ui.ColorPicker.DEFAULT_NUM_COLS); - cp.setSupportedState(goog.ui.Component.State.FOCUSED, this.focusable_); - // TODO(user): Use addChild(cp, true) and remove calls to render. - this.addChild(cp); - this.colorPalette_ = cp; - if (this.isInDocument()) { - this.colorPalette_.render(this.getElement()); - } -}; - - -/** - * Returns an unrendered instance of the color picker. The colors and layout - * are a simple color grid, the same as the old Gmail color picker. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @return {goog.ui.ColorPicker} The unrendered instance. - */ -goog.ui.ColorPicker.createSimpleColorGrid = function(opt_domHelper) { - var cp = new goog.ui.ColorPicker(opt_domHelper); - cp.setSize(7); - cp.setColors(goog.ui.ColorPicker.SIMPLE_GRID_COLORS); - return cp; -}; - - -/** - * Array of colors for a 7-cell wide simple-grid color picker. - * @type {Array.<string>} - */ -goog.ui.ColorPicker.SIMPLE_GRID_COLORS = [ - // grays - '#ffffff', '#cccccc', '#c0c0c0', '#999999', '#666666', '#333333', '#000000', - // reds - '#ffcccc', '#ff6666', '#ff0000', '#cc0000', '#990000', '#660000', '#330000', - // oranges - '#ffcc99', '#ff9966', '#ff9900', '#ff6600', '#cc6600', '#993300', '#663300', - // yellows - '#ffff99', '#ffff66', '#ffcc66', '#ffcc33', '#cc9933', '#996633', '#663333', - // olives - '#ffffcc', '#ffff33', '#ffff00', '#ffcc00', '#999900', '#666600', '#333300', - // greens - '#99ff99', '#66ff99', '#33ff33', '#33cc00', '#009900', '#006600', '#003300', - // turquoises - '#99ffff', '#33ffff', '#66cccc', '#00cccc', '#339999', '#336666', '#003333', - // blues - '#ccffff', '#66ffff', '#33ccff', '#3366ff', '#3333ff', '#000099', '#000066', - // purples - '#ccccff', '#9999ff', '#6666cc', '#6633ff', '#6600cc', '#333399', '#330099', - // violets - '#ffccff', '#ff99ff', '#cc66cc', '#cc33cc', '#993399', '#663366', '#330033' -]; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorsplitbehavior.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorsplitbehavior.js.svn-base deleted file mode 100644 index 824a9ea..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/colorsplitbehavior.js.svn-base +++ /dev/null @@ -1,61 +0,0 @@ -// 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 Behavior for combining a color button and a menu. - * - * @see ../demos/split.html - */ - -goog.provide('goog.ui.ColorSplitBehavior'); - -goog.require('goog.ui.ColorButton'); -goog.require('goog.ui.ColorMenuButton'); -goog.require('goog.ui.SplitBehavior'); - - - -/** - * Constructs a ColorSplitBehavior for combining a color button and a menu. - * To use this, provide a goog.ui.ColorButton which will be attached with - * a goog.ui.ColorMenuButton (with no caption). - * Whenever a color is selected from the ColorMenuButton, it will be placed in - * the ColorButton and the user can apply it over and over (by clicking the - * ColorButton). - * Primary use case - setting the color of text/background in a text editor. - * - * @param {!goog.ui.Button} colorButton A button to interact with a color menu - * button (preferably a goog.ui.ColorButton). - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for - * document interaction. - * @extends {goog.ui.SplitBehavior} - * @constructor - */ -goog.ui.ColorSplitBehavior = function(colorButton, opt_domHelper) { - goog.base(this, colorButton, - new goog.ui.ColorMenuButton(goog.ui.ColorSplitBehavior.ZERO_WIDTH_SPACE_), - goog.ui.SplitBehavior.DefaultHandlers.VALUE, - undefined, - opt_domHelper); -}; -goog.inherits(goog.ui.ColorSplitBehavior, goog.ui.SplitBehavior); - - -/** - * A zero width space character. - * @type {string} - * @private - */ -goog.ui.ColorSplitBehavior.ZERO_WIDTH_SPACE_ = '\uFEFF'; - diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/combobox.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/combobox.js.svn-base deleted file mode 100644 index 0cf5617..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/combobox.js.svn-base +++ /dev/null @@ -1,936 +0,0 @@ -// 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 combo box control that allows user input with - * auto-suggestion from a limited set of options. - * - * @see ../demos/combobox.html - */ - -goog.provide('goog.ui.ComboBox'); -goog.provide('goog.ui.ComboBoxItem'); - -goog.require('goog.Timer'); -goog.require('goog.debug.Logger'); -goog.require('goog.dom.classes'); -goog.require('goog.events'); -goog.require('goog.events.InputHandler'); -goog.require('goog.events.KeyCodes'); -goog.require('goog.events.KeyHandler'); -goog.require('goog.string'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.ItemEvent'); -goog.require('goog.ui.LabelInput'); -goog.require('goog.ui.Menu'); -goog.require('goog.ui.MenuItem'); -goog.require('goog.ui.registry'); -goog.require('goog.userAgent'); - - - -/** - * A ComboBox control. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @param {goog.ui.Menu=} opt_menu Optional menu. - * @extends {goog.ui.Component} - * @constructor - */ -goog.ui.ComboBox = function(opt_domHelper, opt_menu) { - goog.ui.Component.call(this, opt_domHelper); - - this.labelInput_ = new goog.ui.LabelInput(); - this.enabled_ = true; - - // TODO(user): Allow lazy creation of menus/menu items - this.menu_ = opt_menu || new goog.ui.Menu(this.getDomHelper()); - this.setupMenu_(); -}; -goog.inherits(goog.ui.ComboBox, goog.ui.Component); - - -/** - * Number of milliseconds to wait before dismissing combobox after blur. - * @type {number} - */ -goog.ui.ComboBox.BLUR_DISMISS_TIMER_MS = 250; - - -/** - * A logger to help debugging of combo box behavior. - * @type {goog.debug.Logger} - * @private - */ -goog.ui.ComboBox.prototype.logger_ = - goog.debug.Logger.getLogger('goog.ui.ComboBox'); - - -/** - * Whether the combo box is enabled. - * @type {boolean} - * @private - */ -goog.ui.ComboBox.prototype.enabled_; - - -/** - * Keyboard event handler to manage key events dispatched by the input element. - * @type {goog.events.KeyHandler} - * @private - */ -goog.ui.ComboBox.prototype.keyHandler_; - - -/** - * Input handler to take care of firing events when the user inputs text in - * the input. - * @type {goog.events.InputHandler?} - * @private - */ -goog.ui.ComboBox.prototype.inputHandler_ = null; - - -/** - * The last input token. - * @type {?string} - * @private - */ -goog.ui.ComboBox.prototype.lastToken_ = null; - - -/** - * A LabelInput control that manages the focus/blur state of the input box. - * @type {goog.ui.LabelInput?} - * @private - */ -goog.ui.ComboBox.prototype.labelInput_ = null; - - -/** - * Drop down menu for the combo box. Will be created at construction time. - * @type {goog.ui.Menu?} - * @private - */ -goog.ui.ComboBox.prototype.menu_ = null; - - -/** - * The cached visible count. - * @type {number} - * @private - */ -goog.ui.ComboBox.prototype.visibleCount_ = -1; - - -/** - * The input element. - * @type {Element} - * @private - */ -goog.ui.ComboBox.prototype.input_ = null; - - -/** - * The match function. The first argument for the match function will be - * a MenuItem's caption and the second will be the token to evaluate. - * @type {Function} - * @private - */ -goog.ui.ComboBox.prototype.matchFunction_ = goog.string.startsWith; - - -/** - * Element used as the combo boxes button. - * @type {Element} - * @private - */ -goog.ui.ComboBox.prototype.button_ = null; - - -/** - * Default text content for the input box when it is unchanged and unfocussed. - * @type {string} - * @private - */ -goog.ui.ComboBox.prototype.defaultText_ = ''; - - -/** - * Name for the input box created - * @type {string} - * @private - */ -goog.ui.ComboBox.prototype.fieldName_ = ''; - - -/** - * Timer identifier for delaying the dismissal of the combo menu. - * @type {?number} - * @private - */ -goog.ui.ComboBox.prototype.dismissTimer_ = null; - - -/** - * True if the unicode inverted triangle should be displayed in the dropdown - * button. Defaults to false. - * @type {boolean} useDropdownArrow - * @private - */ -goog.ui.ComboBox.prototype.useDropdownArrow_ = false; - - -/** - * Create the DOM objects needed for the combo box. A span and text input. - * @override - */ -goog.ui.ComboBox.prototype.createDom = function() { - this.input_ = this.getDomHelper().createDom( - 'input', {'name': this.fieldName_, 'autocomplete': 'off'}); - this.button_ = this.getDomHelper().createDom('span', - goog.getCssName('goog-combobox-button')); - this.setElementInternal(this.getDomHelper().createDom('span', - goog.getCssName('goog-combobox'), this.input_, this.button_)); - if (this.useDropdownArrow_) { - this.button_.innerHTML = '▼'; - goog.style.setUnselectable(this.button_, true /* unselectable */); - } - this.input_.setAttribute('label', this.defaultText_); - this.labelInput_.decorate(this.input_); - this.menu_.setFocusable(false); - if (!this.menu_.isInDocument()) { - this.addChild(this.menu_, true); - } -}; - - -/** - * Enables/Disables the combo box. - * @param {boolean} enabled Whether to enable (true) or disable (false) the - * combo box. - */ -goog.ui.ComboBox.prototype.setEnabled = function(enabled) { - this.enabled_ = enabled; - this.labelInput_.setEnabled(enabled); - goog.dom.classes.enable(this.getElement(), - goog.getCssName('goog-combobox-disabled'), !enabled); -}; - - -/** @override */ -goog.ui.ComboBox.prototype.enterDocument = function() { - goog.ui.ComboBox.superClass_.enterDocument.call(this); - - var handler = this.getHandler(); - handler.listen(this.getElement(), - goog.events.EventType.MOUSEDOWN, this.onComboMouseDown_); - handler.listen(this.getDomHelper().getDocument(), - goog.events.EventType.MOUSEDOWN, this.onDocClicked_); - - handler.listen(this.input_, - goog.events.EventType.BLUR, this.onInputBlur_); - - this.keyHandler_ = new goog.events.KeyHandler(this.input_); - handler.listen(this.keyHandler_, - goog.events.KeyHandler.EventType.KEY, this.handleKeyEvent); - - this.inputHandler_ = new goog.events.InputHandler(this.input_); - handler.listen(this.inputHandler_, - goog.events.InputHandler.EventType.INPUT, this.onInputEvent_); - - handler.listen(this.menu_, - goog.ui.Component.EventType.ACTION, this.onMenuSelected_); -}; - - -/** @override */ -goog.ui.ComboBox.prototype.exitDocument = function() { - this.keyHandler_.dispose(); - delete this.keyHandler_; - this.inputHandler_.dispose(); - this.inputHandler_ = null; - goog.ui.ComboBox.superClass_.exitDocument.call(this); -}; - - -/** - * Combo box currently can't decorate elements. - * @return {boolean} The value false. - */ -goog.ui.ComboBox.prototype.canDecorate = function() { - return false; -}; - - -/** @override */ -goog.ui.ComboBox.prototype.disposeInternal = function() { - goog.ui.ComboBox.superClass_.disposeInternal.call(this); - - this.clearDismissTimer_(); - - this.labelInput_.dispose(); - this.menu_.dispose(); - - this.labelInput_ = null; - this.menu_ = null; - this.input_ = null; - this.button_ = null; -}; - - -/** - * Dismisses the menu and resets the value of the edit field. - */ -goog.ui.ComboBox.prototype.dismiss = function() { - this.clearDismissTimer_(); - this.hideMenu_(); - this.menu_.setHighlightedIndex(-1); -}; - - -/** - * Adds a new menu item at the end of the menu. - * @param {goog.ui.MenuItem} item Menu item to add to the menu. - */ -goog.ui.ComboBox.prototype.addItem = function(item) { - this.menu_.addChild(item, true); - this.visibleCount_ = -1; -}; - - -/** - * Adds a new menu item at a specific index in the menu. - * @param {goog.ui.MenuItem} item Menu item to add to the menu. - * @param {number} n Index at which to insert the menu item. - */ -goog.ui.ComboBox.prototype.addItemAt = function(item, n) { - this.menu_.addChildAt(item, n, true); - this.visibleCount_ = -1; -}; - - -/** - * Removes an item from the menu and disposes it. - * @param {goog.ui.MenuItem} item The menu item to remove. - */ -goog.ui.ComboBox.prototype.removeItem = function(item) { - var child = this.menu_.removeChild(item, true); - if (child) { - child.dispose(); - this.visibleCount_ = -1; - } -}; - - -/** - * Remove all of the items from the ComboBox menu - */ -goog.ui.ComboBox.prototype.removeAllItems = function() { - for (var i = this.getItemCount() - 1; i >= 0; --i) { - this.removeItem(this.getItemAt(i)); - } -}; - - -/** - * Removes a menu item at a given index in the menu. - * @param {number} n Index of item. - */ -goog.ui.ComboBox.prototype.removeItemAt = function(n) { - var child = this.menu_.removeChildAt(n, true); - if (child) { - child.dispose(); - this.visibleCount_ = -1; - } -}; - - -/** - * Returns a reference to the menu item at a given index. - * @param {number} n Index of menu item. - * @return {goog.ui.MenuItem?} Reference to the menu item. - */ -goog.ui.ComboBox.prototype.getItemAt = function(n) { - return /** @type {goog.ui.MenuItem?} */(this.menu_.getChildAt(n)); -}; - - -/** - * Returns the number of items in the list, including non-visible items, - * such as separators. - * @return {number} Number of items in the menu for this combobox. - */ -goog.ui.ComboBox.prototype.getItemCount = function() { - return this.menu_.getChildCount(); -}; - - -/** - * @return {goog.ui.Menu} The menu that pops up. - */ -goog.ui.ComboBox.prototype.getMenu = function() { - return this.menu_; -}; - - -/** - * @return {number} The number of visible items in the menu. - * @private - */ -goog.ui.ComboBox.prototype.getNumberOfVisibleItems_ = function() { - if (this.visibleCount_ == -1) { - var count = 0; - for (var i = 0, n = this.menu_.getChildCount(); i < n; i++) { - var item = this.menu_.getChildAt(i); - if (!(item instanceof goog.ui.MenuSeparator) && item.isVisible()) { - count++; - } - } - this.visibleCount_ = count; - } - - this.logger_.info('getNumberOfVisibleItems() - ' + this.visibleCount_); - return this.visibleCount_; -}; - - -/** - * Sets the match function to be used when filtering the combo box menu. - * @param {Function} matchFunction The match function to be used when filtering - * the combo box menu. - */ -goog.ui.ComboBox.prototype.setMatchFunction = function(matchFunction) { - this.matchFunction_ = matchFunction; -}; - - -/** - * @return {Function} The match function for the combox box. - */ -goog.ui.ComboBox.prototype.getMatchFunction = function() { - return this.matchFunction_; -}; - - -/** - * Sets the default text for the combo box. - * @param {string} text The default text for the combo box. - */ -goog.ui.ComboBox.prototype.setDefaultText = function(text) { - this.defaultText_ = text; -}; - - -/** - * @return {string} text The default text for the combox box. - */ -goog.ui.ComboBox.prototype.getDefaultText = function() { - return this.defaultText_; -}; - - -/** - * Sets the field name for the combo box. - * @param {string} fieldName The field name for the combo box. - */ -goog.ui.ComboBox.prototype.setFieldName = function(fieldName) { - this.fieldName_ = fieldName; -}; - - -/** - * @return {string} The field name for the combo box. - */ -goog.ui.ComboBox.prototype.getFieldName = function() { - return this.fieldName_; -}; - - -/** - * Set to true if a unicode inverted triangle should be displayed in the - * dropdown button. - * This option defaults to false for backwards compatibility. - * @param {boolean} useDropdownArrow True to use the dropdown arrow. - */ -goog.ui.ComboBox.prototype.setUseDropdownArrow = function(useDropdownArrow) { - this.useDropdownArrow_ = !!useDropdownArrow; -}; - - -/** - * Sets the current value of the combo box. - * @param {string} value The new value. - */ -goog.ui.ComboBox.prototype.setValue = function(value) { - this.logger_.info('setValue() - ' + value); - if (this.labelInput_.getValue() != value) { - this.labelInput_.setValue(value); - this.handleInputChange_(); - } -}; - - -/** - * @return {string} The current value of the combo box. - */ -goog.ui.ComboBox.prototype.getValue = function() { - return this.labelInput_.getValue(); -}; - - -/** - * @return {string} HTML escaped token. - */ -goog.ui.ComboBox.prototype.getToken = function() { - // TODO(user): Remove HTML escaping and fix the existing calls. - return goog.string.htmlEscape(this.getTokenText_()); -}; - - -/** - * @return {string} The token for the current cursor position in the - * input box, when multi-input is disabled it will be the full input value. - * @private - */ -goog.ui.ComboBox.prototype.getTokenText_ = function() { - // TODO(user): Implement multi-input such that getToken returns a substring - // of the whole input delimited by commas. - return goog.string.trim(this.labelInput_.getValue().toLowerCase()); -}; - - -/** - * @private - */ -goog.ui.ComboBox.prototype.setupMenu_ = function() { - var sm = this.menu_; - sm.setVisible(false); - sm.setAllowAutoFocus(false); - sm.setAllowHighlightDisabled(true); -}; - - -/** - * Shows the menu if it isn't already showing. Also positions the menu - * correctly, resets the menu item visibilities and highlights the relevent - * item. - * @param {boolean} showAll Whether to show all items, with the first matching - * item highlighted. - * @private - */ -goog.ui.ComboBox.prototype.maybeShowMenu_ = function(showAll) { - var isVisible = this.menu_.isVisible(); - var numVisibleItems = this.getNumberOfVisibleItems_(); - - if (isVisible && numVisibleItems == 0) { - this.logger_.fine('no matching items, hiding'); - this.hideMenu_(); - - } else if (!isVisible && numVisibleItems > 0) { - if (showAll) { - this.logger_.fine('showing menu'); - this.setItemVisibilityFromToken_(''); - this.setItemHighlightFromToken_(this.getTokenText_()); - } - // In Safari 2.0, when clicking on the combox box, the blur event is - // received after the click event that invokes this function. Since we want - // to cancel the dismissal after the blur event is processed, we have to - // wait for all event processing to happen. - goog.Timer.callOnce(this.clearDismissTimer_, 1, this); - - this.showMenu_(); - this.positionMenu(); - } -}; - - -/** - * Positions the menu. - * @protected - */ -goog.ui.ComboBox.prototype.positionMenu = function() { - if (this.menu_) { - // TODO(user): Make it right-aligned for RTL. - var pos = goog.style.getPageOffset(this.getElement()); - this.menu_.setPosition(pos.x, pos.y + this.getElement().offsetHeight); - } -}; - - -/** - * Show the menu and add an active class to the combo box's element. - * @private - */ -goog.ui.ComboBox.prototype.showMenu_ = function() { - this.menu_.setVisible(true); - goog.dom.classes.add(this.getElement(), - goog.getCssName('goog-combobox-active')); -}; - - -/** - * Hide the menu and remove the active class from the combo box's element. - * @private - */ -goog.ui.ComboBox.prototype.hideMenu_ = function() { - this.menu_.setVisible(false); - goog.dom.classes.remove(this.getElement(), - goog.getCssName('goog-combobox-active')); -}; - - -/** - * Clears the dismiss timer if it's active. - * @private - */ -goog.ui.ComboBox.prototype.clearDismissTimer_ = function() { - if (this.dismissTimer_) { - goog.Timer.clear(this.dismissTimer_); - this.dismissTimer_ = null; - } -}; - - -/** - * Event handler for when the combo box area has been clicked. - * @param {goog.events.BrowserEvent} e The browser event. - * @private - */ -goog.ui.ComboBox.prototype.onComboMouseDown_ = function(e) { - // We only want this event on the element itself or the input or the button. - if (this.enabled_ && - (e.target == this.getElement() || e.target == this.input_ || - goog.dom.contains(this.button_, /** @type {Node} */ (e.target)))) { - if (this.menu_.isVisible()) { - this.logger_.fine('Menu is visible, dismissing'); - this.dismiss(); - } else { - this.logger_.fine('Opening dropdown'); - this.maybeShowMenu_(true); - if (goog.userAgent.OPERA) { - // select() doesn't focus <input> elements in Opera. - this.input_.focus(); - } - this.input_.select(); - this.menu_.setMouseButtonPressed(true); - // Stop the click event from stealing focus - e.preventDefault(); - } - } - // Stop the event from propagating outside of the combo box - e.stopPropagation(); -}; - - -/** - * Event handler for when the document is clicked. - * @param {goog.events.BrowserEvent} e The browser event. - * @private - */ -goog.ui.ComboBox.prototype.onDocClicked_ = function(e) { - if (!goog.dom.contains( - this.menu_.getElement(), /** @type {Node} */ (e.target))) { - this.logger_.info('onDocClicked_() - dismissing immediately'); - this.dismiss(); - } -}; - - -/** - * Handle the menu's select event. - * @param {goog.events.Event} e The event. - * @private - */ -goog.ui.ComboBox.prototype.onMenuSelected_ = function(e) { - this.logger_.info('onMenuSelected_()'); - var item = /** @type {!goog.ui.MenuItem} */ (e.target); - // Stop propagation of the original event and redispatch to allow the menu - // select to be cancelled at this level. i.e. if a menu item should cause - // some behavior such as a user prompt instead of assigning the caption as - // the value. - if (this.dispatchEvent(new goog.ui.ItemEvent( - goog.ui.Component.EventType.ACTION, this, item))) { - var caption = item.getCaption(); - this.logger_.fine('Menu selection: ' + caption + '. Dismissing menu'); - if (this.labelInput_.getValue() != caption) { - this.labelInput_.setValue(caption); - this.dispatchEvent(goog.ui.Component.EventType.CHANGE); - } - this.dismiss(); - } - e.stopPropagation(); -}; - - -/** - * Event handler for when the input box looses focus -- hide the menu - * @param {goog.events.BrowserEvent} e The browser event. - * @private - */ -goog.ui.ComboBox.prototype.onInputBlur_ = function(e) { - this.logger_.info('onInputBlur_() - delayed dismiss'); - this.clearDismissTimer_(); - this.dismissTimer_ = goog.Timer.callOnce( - this.dismiss, goog.ui.ComboBox.BLUR_DISMISS_TIMER_MS, this); -}; - - -/** - * Handles keyboard events from the input box. Returns true if the combo box - * was able to handle the event, false otherwise. - * @param {goog.events.KeyEvent} e Key event to handle. - * @return {boolean} Whether the event was handled by the combo box. - * @protected - * @suppress {visibility} performActionInternal - */ -goog.ui.ComboBox.prototype.handleKeyEvent = function(e) { - var isMenuVisible = this.menu_.isVisible(); - - // Give the menu a chance to handle the event. - if (isMenuVisible && this.menu_.handleKeyEvent(e)) { - return true; - } - - // The menu is either hidden or didn't handle the event. - var handled = false; - switch (e.keyCode) { - case goog.events.KeyCodes.ESC: - // If the menu is visible and the user hit Esc, dismiss the menu. - if (isMenuVisible) { - this.logger_.fine('Dismiss on Esc: ' + this.labelInput_.getValue()); - this.dismiss(); - handled = true; - } - break; - case goog.events.KeyCodes.TAB: - // If the menu is open and an option is highlighted, activate it. - if (isMenuVisible) { - var highlighted = this.menu_.getHighlighted(); - if (highlighted) { - this.logger_.fine('Select on Tab: ' + this.labelInput_.getValue()); - highlighted.performActionInternal(e); - handled = true; - } - } - break; - case goog.events.KeyCodes.UP: - case goog.events.KeyCodes.DOWN: - // If the menu is hidden and the user hit the up/down arrow, show it. - if (!isMenuVisible) { - this.logger_.fine('Up/Down - maybe show menu'); - this.maybeShowMenu_(true); - handled = true; - } - break; - } - - if (handled) { - e.preventDefault(); - } - - return handled; -}; - - -/** - * Handles the content of the input box changing. - * @param {goog.events.Event} e The INPUT event to handle. - * @private - */ -goog.ui.ComboBox.prototype.onInputEvent_ = function(e) { - // If the key event is text-modifying, update the menu. - this.logger_.fine('Key is modifying: ' + this.labelInput_.getValue()); - this.handleInputChange_(); -}; - - -/** - * Handles the content of the input box changing, either because of user - * interaction or programmatic changes. - * @private - */ -goog.ui.ComboBox.prototype.handleInputChange_ = function() { - var token = this.getTokenText_(); - this.setItemVisibilityFromToken_(token); - if (goog.dom.getActiveElement(this.getDomHelper().getDocument()) == - this.input_) { - // Do not alter menu visibility unless the user focus is currently on the - // combobox (otherwise programmatic changes may cause the menu to become - // visible). - this.maybeShowMenu_(false); - } - var highlighted = this.menu_.getHighlighted(); - if (token == '' || !highlighted || !highlighted.isVisible()) { - this.setItemHighlightFromToken_(token); - } - this.lastToken_ = token; - this.dispatchEvent(goog.ui.Component.EventType.CHANGE); -}; - - -/** - * Loops through all menu items setting their visibility according to a token. - * @param {string} token The token. - * @private - */ -goog.ui.ComboBox.prototype.setItemVisibilityFromToken_ = function(token) { - this.logger_.info('setItemVisibilityFromToken_() - ' + token); - var isVisibleItem = false; - var count = 0; - var recheckHidden = !this.matchFunction_(token, this.lastToken_); - - for (var i = 0, n = this.menu_.getChildCount(); i < n; i++) { - var item = this.menu_.getChildAt(i); - if (item instanceof goog.ui.MenuSeparator) { - // Ensure that separators are only shown if there is at least one visible - // item before them. - item.setVisible(isVisibleItem); - isVisibleItem = false; - } else if (item instanceof goog.ui.MenuItem) { - if (!item.isVisible() && !recheckHidden) continue; - - var caption = item.getCaption(); - var visible = this.isItemSticky_(item) || - caption && this.matchFunction_(caption.toLowerCase(), token); - if (typeof item.setFormatFromToken == 'function') { - item.setFormatFromToken(token); - } - item.setVisible(!!visible); - isVisibleItem = visible || isVisibleItem; - - } else { - // Assume all other items are correctly using their visibility. - isVisibleItem = item.isVisible() || isVisibleItem; - } - - if (!(item instanceof goog.ui.MenuSeparator) && item.isVisible()) { - count++; - } - } - - this.visibleCount_ = count; -}; - - -/** - * Highlights the first token that matches the given token. - * @param {string} token The token. - * @private - */ -goog.ui.ComboBox.prototype.setItemHighlightFromToken_ = function(token) { - this.logger_.info('setItemHighlightFromToken_() - ' + token); - - if (token == '') { - this.menu_.setHighlightedIndex(-1); - return; - } - - for (var i = 0, n = this.menu_.getChildCount(); i < n; i++) { - var item = this.menu_.getChildAt(i); - var caption = item.getCaption(); - if (caption && this.matchFunction_(caption.toLowerCase(), token)) { - this.menu_.setHighlightedIndex(i); - if (item.setFormatFromToken) { - item.setFormatFromToken(token); - } - return; - } - } - this.menu_.setHighlightedIndex(-1); -}; - - -/** - * Returns true if the item has an isSticky method and the method returns true. - * @param {goog.ui.MenuItem} item The item. - * @return {boolean} Whether the item has an isSticky method and the method - * returns true. - * @private - */ -goog.ui.ComboBox.prototype.isItemSticky_ = function(item) { - return typeof item.isSticky == 'function' && item.isSticky(); -}; - - - -/** - * Class for combo box items. - * @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 {Object=} opt_data Identifying data for the menu item. - * @param {goog.dom.DomHelper=} opt_domHelper Optional dom helper used for dom - * interactions. - * @constructor - * @extends {goog.ui.MenuItem} - */ -goog.ui.ComboBoxItem = function(content, opt_data, opt_domHelper) { - goog.ui.MenuItem.call(this, content, opt_data, opt_domHelper); -}; -goog.inherits(goog.ui.ComboBoxItem, goog.ui.MenuItem); - - -// Register a decorator factory function for goog.ui.ComboBoxItems. -goog.ui.registry.setDecoratorByClassName(goog.getCssName('goog-combobox-item'), - function() { - // ComboBoxItem defaults to using MenuItemRenderer. - return new goog.ui.ComboBoxItem(null); - }); - - -/** - * Whether the menu item is sticky, non-sticky items will be hidden as the - * user types. - * @type {boolean} - * @private - */ -goog.ui.ComboBoxItem.prototype.isSticky_ = false; - - -/** - * Sets the menu item to be sticky or not sticky. - * @param {boolean} sticky Whether the menu item should be sticky. - */ -goog.ui.ComboBoxItem.prototype.setSticky = function(sticky) { - this.isSticky_ = sticky; -}; - - -/** - * @return {boolean} Whether the menu item is sticky. - */ -goog.ui.ComboBoxItem.prototype.isSticky = function() { - return this.isSticky_; -}; - - -/** - * Sets the format for a menu item based on a token, bolding the token. - * @param {string} token The token. - */ -goog.ui.ComboBoxItem.prototype.setFormatFromToken = function(token) { - if (this.isEnabled()) { - var caption = this.getCaption(); - var index = caption.toLowerCase().indexOf(token); - if (index >= 0) { - var domHelper = this.getDomHelper(); - this.setContent([ - domHelper.createTextNode(caption.substr(0, index)), - domHelper.createDom('b', null, caption.substr(index, token.length)), - domHelper.createTextNode(caption.substr(index + token.length)) - ]); - } - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/combobox_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/combobox_test.html.svn-base deleted file mode 100644 index 06d0d6c..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/combobox_test.html.svn-base +++ /dev/null @@ -1,275 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - - @author gboyer@google.com (Garrett Boyer) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.ComboBox</title> -<style type='text/css'> -.goog-menu { - position: absolute; -} -</style> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.dom.TagName'); - goog.require('goog.dom.classes'); - goog.require('goog.events'); - goog.require('goog.events.KeyCodes'); - goog.require('goog.testing.MockClock'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.ComboBox'); -</script> -</head> -<body> - -<h2 style="color:red"> -This test is rudimentary. -The fact that it passes should not (yet) make you too confident. -</h2> - -<div id="combo"> -</div> - -<div id="menu"> - <div class="goog-combobox-item">Red</div> - <div class="goog-combobox-item">Green</div> - <div class="goog-combobox-item">Blue</div> -</div> - -<script> - -var comboBox; -var input; - -function setUp() { - goog.dom.getElement('combo').innerHTML = ''; - - comboBox = new goog.ui.ComboBox(); - comboBox.setDefaultText('Select a color...'); - comboBox.addItem(new goog.ui.ComboBoxItem('Red')); - comboBox.addItem(new goog.ui.ComboBoxItem('Maroon')); - comboBox.addItem(new goog.ui.ComboBoxItem('Gre<en')); - comboBox.addItem(new goog.ui.ComboBoxItem('Blue')); - comboBox.addItem(new goog.ui.ComboBoxItem('Royal Blue')); - comboBox.addItem(new goog.ui.ComboBoxItem('Yellow')); - comboBox.addItem(new goog.ui.ComboBoxItem('Magenta')); - comboBox.addItem(new goog.ui.ComboBoxItem('Mouve')); - comboBox.addItem(new goog.ui.ComboBoxItem('Grey')); - comboBox.render(goog.dom.getElement('combo')); - - input = comboBox.getElement().getElementsByTagName( - goog.dom.TagName.INPUT)[0]; -} - -function tearDown() { - comboBox.dispose(); - goog.events.removeAll(); -} - -function testGetMenu() { - assertTrue('Menu should be instance of goog.ui.Menu', - comboBox.getMenu() instanceof goog.ui.Menu); - assertEquals('Menu should have correct number of children', - 9, comboBox.getMenu().getChildCount()); -} - -function testMenuBeginsInvisible() { - assertFalse('Menu should begin invisible', comboBox.getMenu().isVisible()); -} - -function testClickCausesPopup() { - goog.testing.events.fireClickSequence(input); - assertTrue('Menu becomes visible after click', - comboBox.getMenu().isVisible()); -} - -function testUpKeyCausesPopup() { - goog.testing.events.fireKeySequence(input, goog.events.KeyCodes.UP); - assertTrue('Menu becomes visible after UP key', - comboBox.getMenu().isVisible()); -} - -function testActionSelectsItem() { - comboBox.getMenu().getItemAt(2).dispatchEvent( - goog.ui.Component.EventType.ACTION); - assertEquals('Gre<en', input.value); -} - -function testActionSelectsItemWithModel() { - var itemWithModel = new goog.ui.MenuItem('one', 1); - comboBox.addItem(itemWithModel); - itemWithModel.dispatchEvent(goog.ui.Component.EventType.ACTION); - assertEquals('one', comboBox.getValue()); -} - -function testRedisplayMenuAfterBackspace() { - input.value = 'mx'; - comboBox.onInputEvent_(); - input.value = 'm'; - comboBox.onInputEvent_(); - assertEquals('Three items should be displayed', - 3, comboBox.getNumberOfVisibleItems_()); -} - -function testExternallyCreatedMenu() { - var menu = new goog.ui.Menu(); - menu.decorate(goog.dom.getElement('menu')); - assertTrue('Menu items should be instances of goog.ui.ComboBoxItem', - menu.getChildAt(0) instanceof goog.ui.ComboBoxItem); - - comboBox = new goog.ui.ComboBox(null, menu); - comboBox.render(goog.dom.getElement('combo')); - - input = comboBox.getElement().getElementsByTagName( - goog.dom.TagName.INPUT)[0]; - menu.getItemAt(2).dispatchEvent( - goog.ui.Component.EventType.ACTION); - assertEquals('Blue', input.value); -} - -function testRecomputeVisibleCountAfterChangingItems() { - input.value = 'Black'; - comboBox.onInputEvent_(); - assertEquals('No items should be displayed', - 0, comboBox.getNumberOfVisibleItems_()); - comboBox.addItem(new goog.ui.ComboBoxItem('Black')); - assertEquals('One item should be displayed', - 1, comboBox.getNumberOfVisibleItems_()); - - input.value = 'Red'; - comboBox.onInputEvent_(); - assertEquals('One item should be displayed', - 1, comboBox.getNumberOfVisibleItems_()); - comboBox.removeItemAt(0); // Red - assertEquals('No items should be displayed', - 0, comboBox.getNumberOfVisibleItems_()); -} - -function testSetEnabled() { - // By default, everything should be enabled. - assertFalse('Text input should initially not be disabled', input.disabled); - assertFalse('Text input should initially not look disabled', - goog.dom.classes.has(input, - goog.getCssName(goog.ui.LabelInput.prototype.LABEL_CLASS_NAME, - 'disabled'))); - assertFalse('Combo box should initially not look disabled', - goog.dom.classes.has(comboBox.getElement(), - goog.getCssName('goog-combobox-disabled'))); - goog.testing.events.fireClickSequence(comboBox.getElement()); - assertTrue('Menu initially becomes visible after click', - comboBox.getMenu().isVisible()); - goog.testing.events.fireClickSequence(document); - assertFalse('Menu initially becomes invisible after document click', - comboBox.getMenu().isVisible()); - - comboBox.setEnabled(false); - assertTrue('Text input should be disabled after being disabled', - input.disabled); - assertTrue('Text input should appear disabled after being disabled', - goog.dom.classes.has(input, - goog.getCssName(goog.ui.LabelInput.prototype.LABEL_CLASS_NAME, - 'disabled'))); - assertTrue('Combo box should appear disabled after being disabled', - goog.dom.classes.has(comboBox.getElement(), - goog.getCssName('goog-combobox-disabled'))); - goog.testing.events.fireClickSequence(comboBox.getElement()); - assertFalse('Menu should not become visible after click if disabled', - comboBox.getMenu().isVisible()); - - comboBox.setEnabled(true); - assertFalse('Text input should not be disabled after being re-enabled', - input.disabled); - assertFalse('Text input should not appear disabled after being re-enabled', - goog.dom.classes.has(input, - goog.getCssName(goog.ui.LabelInput.prototype.LABEL_CLASS_NAME, - 'disabled'))); - assertFalse('Combo box should not appear disabled after being re-enabled', - goog.dom.classes.has(comboBox.getElement(), - goog.getCssName('goog-combobox-disabled'))); - goog.testing.events.fireClickSequence(comboBox.getElement()); - assertTrue('Menu becomes visible after click when re-enabled', - comboBox.getMenu().isVisible()); - goog.testing.events.fireClickSequence(document); - assertFalse('Menu becomes invisible after document click when re-enabled', - comboBox.getMenu().isVisible()); -} - -function testSetFormatFromToken() { - var item = new goog.ui.ComboBoxItem('ABc'); - item.setFormatFromToken('b'); - var div = goog.dom.createDom('div'); - new goog.ui.ControlRenderer().setContent(div, item.getContent()); - assertTrue(div.innerHTML == 'A<b>B</b>c' || div.innerHTML == 'A<B>B</B>c'); -} - -function testSetValue() { - var clock = new goog.testing.MockClock(/* autoInstall */ true); - - // Get the input focus. Note that both calls are needed to correctly - // simulate the focus (and setting document.activeElement) across all - // browsers. - input.focus(); - goog.testing.events.fireClickSequence(input); - - // Simulate text input. - input.value = 'Black'; - comboBox.onInputEvent_(); - clock.tick(); - assertEquals('No items should be displayed', - 0, comboBox.getNumberOfVisibleItems_()); - assertFalse('Menu should be invisible', comboBox.getMenu().isVisible()); - - // Programmatic change with the input focus causes the menu visibility to - // change if needed. - comboBox.setValue('Blue'); - clock.tick(); - assertTrue('Menu should be visible1', comboBox.getMenu().isVisible()); - assertEquals('One item should be displayed', - 1, comboBox.getNumberOfVisibleItems_()); - - // Simulate user input to ensure all the items are invisible again, then - // blur away. - input.value = 'Black'; - comboBox.onInputEvent_(); - clock.tick(); - input.blur(); - document.body.focus(); - clock.tick(goog.ui.ComboBox.BLUR_DISMISS_TIMER_MS); - assertEquals('No items should be displayed', - 0, comboBox.getNumberOfVisibleItems_()); - assertFalse('Menu should be invisible', comboBox.getMenu().isVisible()); - - // Programmatic change without the input focus does not pop up the menu, - // but still updates the list of visible items within it. - comboBox.setValue('Blue'); - clock.tick(); - assertFalse('Menu should be invisible', comboBox.getMenu().isVisible()); - assertEquals('Menu should contain one item', - 1, comboBox.getNumberOfVisibleItems_()); - - // Click on the combobox. The entire menu becomes visible, the last item - // (programmatically) set is highlighted. - goog.testing.events.fireClickSequence(comboBox.getElement()); - assertTrue('Menu should be visible2', comboBox.getMenu().isVisible()); - assertEquals('All items should be displayed', - comboBox.getMenu().getItemCount(), comboBox.getNumberOfVisibleItems_()); - assertEquals('The last item set should be highlighted', - /* Blue= */ 3, comboBox.getMenu().getHighlightedIndex()); - - clock.uninstall(); -} - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/component.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/component.js.svn-base deleted file mode 100644 index 8770be6..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/component.js.svn-base +++ /dev/null @@ -1,1231 +0,0 @@ -// 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_; -}; - - -/** - * 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() { - goog.ui.Component.superClass_.disposeInternal.call(this); - - 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; - // TODO(gboyer): delete this.dom_ breaks many unit tests. -}; - - -/** - * 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) { - 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}). - * </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 { - // We don't touch the DOM, but if the parent is in the document, the child - // isn't, and the child has a DOM, then we call enterDocument on the child. - if (this.inDocument_ && !child.inDocument_ && child.element_) { - 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} f The function to call for every child component; should - * take 2 arguments (the child and its index). - * @param {Object=} opt_obj Used as the 'this' object in f when called. - */ -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. - * - * @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. - */ -goog.ui.Component.prototype.removeChildren = function(opt_unrender) { - while (this.hasChildren()) { - this.removeChildAt(0, opt_unrender); - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/component_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/component_test.html.svn-base deleted file mode 100644 index 36a66a3..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/component_test.html.svn-base +++ /dev/null @@ -1,764 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2007 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.Component</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.dom.DomHelper'); - goog.require('goog.dom.NodeType'); - goog.require('goog.dom.TagName'); - goog.require('goog.events.EventTarget'); - goog.require('goog.string.StringBuffer'); - goog.require('goog.testing.PropertyReplacer'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Component'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var component; - var propertyReplacer = new goog.testing.PropertyReplacer(); - var sandbox = goog.dom.getElement('sandbox'); - - function setUp() { - component = new goog.ui.Component(); - } - - function tearDown() { - component.dispose(); - goog.dom.removeChildren(sandbox); - propertyReplacer.reset(); - } - - function testConstructor() { - assertTrue('Instance must be non-null and have the expected class', - component instanceof goog.ui.Component); - assertTrue('DOM helper must be non-null and have the expected class', - component.dom_ instanceof goog.dom.DomHelper); - - var fakeDom = {}; - var otherComponent = new goog.ui.Component(fakeDom); - assertEquals('DOM helper must refer to expected object', fakeDom, - otherComponent.dom_); - - otherComponent.dispose(); - } - - function testGetId() { - assertNull('Component ID should be initialized to null', component.id_); - var id = component.getId(); - assertNotNull('Component ID should be generated on demand', id); - assertEquals('Subsequent calls to getId() must return same value', id, - component.getId()); - } - - function testSetId() { - component.setId('myId'); - assertEquals('getId() must return explicitly set ID', 'myId', - component.getId()); - - var child = new goog.ui.Component(); - var childId = child.getId(); - component.addChild(child); - assertEquals('Parent component must find child by ID', child, - component.getChild(childId)); - - child.setId('someNewId'); - assertEquals('Parent component must find child by new ID', child, - component.getChild('someNewId')); - - child.dispose(); - } - - function testGetSetElement() { - assertNull('Element must be null by default', component.getElement()); - var element = goog.dom.createElement(goog.dom.TagName.DIV); - component.setElementInternal(element); - assertEquals('getElement() must return expected element', element, - component.getElement()); - } - - function testGetSetParent() { - assertNull('Parent must be null by default', component.getParent()); - - var parent = new goog.ui.Component(); - component.setParent(parent); - assertEquals('getParent() must return expected component', parent, - component.getParent()); - - component.setParent(null); - assertNull('Parent must be null', component.getParent()); - - assertThrows('Setting a component\'s parent to itself must throw error', - function() { - component.setParent(component); - }); - - parent.addChild(component); - assertEquals('getParent() must return expected component', parent, - component.getParent()); - assertThrows('Changing a child component\'s parent must throw error', - function() { - component.setParent(new goog.ui.Component()); - }); - - parent.dispose(); - } - - function testGetParentEventTarget() { - assertNull('Parent event target must be null by default', - component.getParentEventTarget()); - - var parent = new goog.ui.Component(); - component.setParent(parent); - assertEquals('Parent event target must be the parent component', parent, - component.getParentEventTarget()); - assertThrows('Directly setting the parent event target to other than ' + - 'the parent component when the parent component is set must throw ' + - 'error', - function() { - component.setParentEventTarget(new goog.ui.Component()); - }); - - parent.dispose(); - } - - function testSetParentEventTarget() { - var parentEventTarget = new goog.events.EventTarget(); - component.setParentEventTarget(parentEventTarget); - assertEquals('Parent component must be null', null, - component.getParent()); - - parentEventTarget.dispose(); - } - - function testGetDomHelper() { - var domHelper = new goog.dom.DomHelper(); - var component = new goog.ui.Component(domHelper); - assertEquals('Component must return the same DomHelper passed', domHelper, - component.getDomHelper()); - } - - function testIsInDocument() { - assertFalse('Component must not be in the document by default', - component.isInDocument()); - component.enterDocument(); - assertTrue('Component must be in the document', component.isInDocument()); - } - - function testCreateDom() { - assertNull('Component must not have DOM by default', - component.getElement()); - component.createDom(); - assertEquals('Component\'s DOM must be an element node', - goog.dom.NodeType.ELEMENT, component.getElement().nodeType); - } - - function testRender() { - assertFalse('Component must not be in the document by default', - component.isInDocument()); - assertNull('Component must not have DOM by default', - component.getElement()); - assertFalse('wasDecorated() must be false before component is rendered', - component.wasDecorated()); - - component.render(sandbox); - assertTrue('Rendered component must be in the document', - component.isInDocument()); - assertEquals('Component\'s element must be a child of the parent element', - sandbox, component.getElement().parentNode); - assertFalse('wasDecorated() must still be false for rendered component', - component.wasDecorated()); - - assertThrows('Trying to re-render component must throw error', - function() { - component.render(); - }); - } - - function testRender_NoParent() { - component.render(); - assertTrue('Rendered component must be in the document', - component.isInDocument()); - assertEquals('Component\'s element must be a child of the document body', - document.body, component.getElement().parentNode); - } - - function testRender_ParentNotInDocument() { - var parent = new goog.ui.Component(); - component.setParent(parent); - - assertFalse('Parent component must not be in the document', - parent.isInDocument()); - assertFalse('Child component must not be in the document', - component.isInDocument()); - assertNull('Child component must not have DOM', component.getElement()); - - component.render(); - assertFalse('Parent component must not be in the document', - parent.isInDocument()); - assertFalse('Child component must not be in the document', - component.isInDocument()); - assertNotNull('Child component must have DOM', component.getElement()); - - parent.dispose(); - } - - - function testRenderBefore() { - var sibling = goog.dom.createElement(goog.dom.TagName.DIV); - sandbox.appendChild(sibling); - - component.renderBefore(sibling); - assertTrue('Rendered component must be in the document', - component.isInDocument()); - assertEquals('Component\'s element must be a child of the parent element', - sandbox, component.getElement().parentNode); - assertEquals('Component\'s element must have expected nextSibling', - sibling, component.getElement().nextSibling); - } - - - function testRenderChild() { - var parent = new goog.ui.Component(); - - parent.createDom(); - assertFalse('Parent must not be in the document', parent.isInDocument()); - assertNotNull('Parent must have a DOM', parent.getElement()); - - parent.addChild(component); - assertFalse('Child must not be in the document', - component.isInDocument()); - assertNull('Child must not have a DOM', component.getElement()); - - component.render(parent.getElement()); - assertFalse('Parent must not be in the document', parent.isInDocument()); - assertFalse('Child must not be in the document if the parent isn\'t', - component.isInDocument()); - assertNotNull('Child must have a DOM', component.getElement()); - assertEquals('Child\'s element must be a child of the parent\'s element', - parent.getElement(), component.getElement().parentNode); - - parent.render(sandbox); - assertTrue('Parent must be in the document', parent.isInDocument()); - assertTrue('Child must be in the document', component.isInDocument()); - - parent.dispose(); - } - - function testDecorate() { - sandbox.innerHTML = '<div id="foo">Foo</div>'; - var foo = goog.dom.getElement('foo'); - - assertFalse('wasDecorated() must be false by default', - component.wasDecorated()); - - component.decorate(foo); - assertTrue('Component must be in the document', component.isInDocument()); - assertEquals('Component\'s element must be the decorated element', foo, - component.getElement()); - assertTrue('wasDecorated() must be true for decorated component', - component.wasDecorated()); - - assertThrows('Trying to decorate with a control already in the document' + - ' must throw error', - function() { - component.decorate(foo); - }); - } - - function testCannotDecorate() { - sandbox.innerHTML = '<div id="foo">Foo</div>'; - var foo = goog.dom.getElement('foo'); - - // Have canDecorate() return false. - propertyReplacer.set(component, 'canDecorate', function() { - return false; - }); - - assertThrows('Trying to decorate an element for which canDecorate()' + - ' returns false must throw error', - function() { - component.decorate(foo); - }); - } - - function testCanDecorate() { - assertTrue('canDecorate() must return true by default', - component.canDecorate(sandbox)); - } - - function testWasDecorated() { - assertFalse('wasDecorated() must return false by default', - component.wasDecorated()); - } - - function testDecorateInternal() { - assertNull('Element must be null by default', component.getElement()); - var element = goog.dom.createElement(goog.dom.TagName.DIV); - component.decorateInternal(element); - assertEquals('Element must have expected value', element, - component.getElement()); - } - - function testGetElementAndGetElementsByClass() { - sandbox.innerHTML = - '<ul id="task-list">' + - '<li class="task">Unclog drain' + - '</ul>' + - '<ul id="completed-tasks">' + - '<li id="groceries" class="task">Buy groceries' + - '<li class="task">Rotate tires' + - '<li class="task">Clean kitchen' + - '</ul>' + - assertNull( - 'Should be nothing to return before the component has a DOM', - component.getElementByClass('task')); - assertEquals('Should return an empty list before the component has a DOM', - 0, - component.getElementsByClass('task').length); - - component.decorate(goog.dom.getElement('completed-tasks')); - assertEquals( - 'getElementByClass() should return the first completed task', - 'groceries', - component.getElementByClass('task').id); - assertEquals( - 'getElementsByClass() should return only the completed tasks', - 3, - component.getElementsByClass('task').length); - } - - function testEnterExitDocument() { - var c1 = new goog.ui.Component(); - var c2 = new goog.ui.Component(); - - component.addChild(c1); - component.addChild(c2); - - component.createDom(); - c1.createDom(); - c2.createDom(); - - assertFalse('Parent must not be in the document', - component.isInDocument()); - assertFalse('Neither child must be in the document', - c1.isInDocument() || c2.isInDocument()); - - component.enterDocument(); - assertTrue('Parent must be in the document', component.isInDocument()); - assertTrue('Both children must be in the document', - c1.isInDocument() && c2.isInDocument()); - - component.exitDocument(); - assertFalse('Parent must not be in the document', - component.isInDocument()); - assertFalse('Neither child must be in the document', - c1.isInDocument() || c2.isInDocument()); - - c1.dispose(); - c2.dispose(); - } - - function testDispose() { - var c1, c2; - - component.createDom(); - component.addChild((c1 = new goog.ui.Component()), true); - component.addChild((c2 = new goog.ui.Component()), true); - - var element = component.getElement(); - var c1Element = c1.getElement(); - var c2Element = c2.getElement(); - - component.render(sandbox); - assertTrue('Parent must be in the document', component.isInDocument()); - assertEquals('Parent\'s element must be a child of the sandbox element', - sandbox, element.parentNode); - assertTrue('Both children must be in the document', - c1.isInDocument() && c2.isInDocument()); - assertEquals('First child\'s element must be a child of the parent\'s' + - ' element', element, c1Element.parentNode); - assertEquals('Second child\'s element must be a child of the parent\'s' + - ' element', element, c2Element.parentNode); - - assertFalse('Parent must not have been disposed of', - component.isDisposed()); - assertFalse('Neither child must have been disposed of', - c1.isDisposed() || c2.isDisposed()); - - component.dispose(); - assertTrue('Parent must have been disposed of', component.isDisposed()); - assertFalse('Parent must not be in the document', - component.isInDocument()); - assertNotEquals('Parent\'s element must no longer be a child of the' + - ' sandbox element', sandbox, element.parentNode); - assertTrue('Both children must have been disposed of', - c1.isDisposed() && c2.isDisposed()); - assertFalse('Neither child must be in the document', - c1.isInDocument() || c2.isInDocument()); - assertNotEquals('First child\'s element must no longer be a child of' + - ' the parent\'s element', element, c1Element.parentNode); - assertNotEquals('Second child\'s element must no longer be a child of' + - ' the parent\'s element', element, c2Element.parentNode); - } - - function testDispose_Decorated() { - sandbox.innerHTML = '<div id="foo">Foo</div>'; - var foo = goog.dom.getElement('foo'); - - component.decorate(foo); - assertTrue('Component must be in the document', component.isInDocument()); - assertFalse('Component must not have been disposed of', - component.isDisposed()); - assertEquals('Component\'s element must have expected value', foo, - component.getElement()); - assertEquals('Decorated element must be a child of the sandbox', sandbox, - foo.parentNode); - - component.dispose(); - assertFalse('Component must not be in the document', - component.isInDocument()); - assertTrue('Component must have been disposed of', - component.isDisposed()); - assertNull('Component\'s element must be null', component.getElement()); - assertEquals('Previously decorated element must still be a child of the' + - ' sandbox', sandbox, foo.parentNode); - } - - function testMakeIdAndGetFragmentFromId() { - assertEquals('Unique id must have expected value', - component.getId() + '.foo', component.makeId('foo')); - assertEquals('Fragment must have expected value', 'foo', - component.getFragmentFromId(component.makeId('foo'))); - } - - function testMakeIdsWithObject() { - var EnumDef = { - ENUM_1: 'enum 1', - ENUM_2: 'enum 2', - ENUM_3: 'enum 3' - }; - var ids = component.makeIds(EnumDef); - assertEquals(component.makeId(EnumDef.ENUM_1), ids.ENUM_1); - assertEquals(component.makeId(EnumDef.ENUM_2), ids.ENUM_2); - assertEquals(component.makeId(EnumDef.ENUM_3), ids.ENUM_3); - } - - function testGetElementByFragment() { - component.render(sandbox); - - var element = component.dom_.createDom('DIV', { - id: component.makeId('foo') - }, 'Hello'); - sandbox.appendChild(element); - - assertEquals('Element must have expected value', element, - component.getElementByFragment('foo')); - } - - function testGetSetModel() { - assertNull('Model must be null by default', component.getModel()); - - var model = 'someModel'; - component.setModel(model); - assertEquals('Model must have expected value', model, - component.getModel()); - - component.setModel(null); - assertNull('Model must be null', component.getModel()); - } - - function testAddChild() { - var child = new goog.ui.Component(); - child.setId('child'); - - assertFalse('Parent must not be in the document', - component.isInDocument()); - - component.addChild(child); - assertTrue('Parent must have children.', component.hasChildren()); - assertEquals('Child must have expected parent', component, - child.getParent()); - assertEquals('Parent must find child by ID', child, - component.getChild('child')); - } - - function testAddChild_Render() { - var child = new goog.ui.Component(); - - component.render(sandbox); - assertTrue('Parent must be in the document', component.isInDocument()); - assertEquals('Parent must be in the sandbox', sandbox, - component.getElement().parentNode); - - component.addChild(child, true); - assertTrue('Child must be in the document', child.isInDocument()); - assertEquals('Child element must be a child of the parent element', - component.getElement(), child.getElement().parentNode); - } - - function testAddChild_DomOnly() { - var child = new goog.ui.Component(); - - component.createDom(); - assertNotNull('Parent must have a DOM', component.getElement()); - assertFalse('Parent must not be in the document', - component.isInDocument()); - - component.addChild(child, true); - assertNotNull('Child must have a DOM', child.getElement()); - assertEquals('Child element must be a child of the parent element', - component.getElement(), child.getElement().parentNode); - assertFalse('Child must not be in the document', child.isInDocument()); - } - - function testAddChildAt() { - var a = new goog.ui.Component(); - var b = new goog.ui.Component(); - var c = new goog.ui.Component(); - var d = new goog.ui.Component(); - - a.setId('a'); - b.setId('b'); - c.setId('c'); - d.setId('d'); - - component.addChildAt(b, 0); - assertEquals('b', component.getChildIds().join('')); - component.addChildAt(d, 1); - assertEquals('bd', component.getChildIds().join('')); - component.addChildAt(a, 0); - assertEquals('abd', component.getChildIds().join('')); - component.addChildAt(c, 2); - assertEquals('abcd', component.getChildIds().join('')); - - assertEquals(a, component.getChildAt(0)); - assertEquals(b, component.getChildAt(1)); - assertEquals(c, component.getChildAt(2)); - assertEquals(d, component.getChildAt(3)); - - assertThrows('Adding child at out-of-bounds index must throw error', - function() { - component.addChildAt(new goog.ui.Component(), 5); - }); - } - - function testHasChildren() { - assertFalse('Component must not have children', component.hasChildren()); - - component.addChildAt(new goog.ui.Component(), 0); - assertTrue('Component must have children', component.hasChildren()); - - component.removeChildAt(0); - assertFalse('Component must not have children', component.hasChildren()); - } - - function testGetChildCount() { - assertEquals('Component must have 0 children', 0, - component.getChildCount()); - - component.addChild(new goog.ui.Component()); - assertEquals('Component must have 1 child', 1, - component.getChildCount()); - - component.addChild(new goog.ui.Component()); - assertEquals('Component must have 2 children', 2, - component.getChildCount()); - - component.removeChildAt(1); - assertEquals('Component must have 1 child', 1, - component.getChildCount()); - - component.removeChildAt(0); - assertEquals('Component must have 0 children', 0, - component.getChildCount()); - } - - function testGetChildIds() { - var a = new goog.ui.Component(); - var b = new goog.ui.Component(); - - a.setId('a'); - b.setId('b'); - - component.addChild(a); - assertEquals('a', component.getChildIds().join('')); - - component.addChild(b); - assertEquals('ab', component.getChildIds().join('')); - - var ids = component.getChildIds(); - ids.push('c'); - assertEquals('Changes to the array returned by getChildIds() must not' + - ' affect the component', 'ab', component.getChildIds().join('')); - } - - function testGetChild() { - assertNull('Parent must have no children', component.getChild('myId')); - - var c = new goog.ui.Component(); - c.setId('myId'); - component.addChild(c); - assertEquals('Parent must find child by ID', c, - component.getChild('myId')); - - c.setId('newId'); - assertNull('Parent must not find child by old ID', - component.getChild('myId')); - assertEquals('Parent must find child by new ID', c, - component.getChild('newId')); - } - - function testGetChildAt() { - var a = new goog.ui.Component(); - var b = new goog.ui.Component(); - - a.setId('a'); - b.setId('b'); - - component.addChildAt(a, 0); - assertEquals('Parent must find child by index', a, - component.getChildAt(0)); - - component.addChildAt(b, 1); - assertEquals('Parent must find child by index', b, - component.getChildAt(1)); - - assertNull('Parent must return null for out-of-bounds index', - component.getChildAt(3)); - } - - function testForEachChild() { - var invoked = false; - component.forEachChild(function(child) { - assertNotNull('Child must never be null', child); - invoked = true; - }); - assertFalse('forEachChild must not call its argument if the parent has ' + - 'no children', invoked); - - component.addChild(new goog.ui.Component()); - component.addChild(new goog.ui.Component()); - component.addChild(new goog.ui.Component()); - var sb = new goog.string.StringBuffer(); - component.forEachChild(function(child, index) { - // Note: This is just to test that 'this' is set correctly. - var count = this.getChildCount(); - sb.append(index + 1).append(' of ').append(count); - if (index < count - 1) { - sb.append(', '); - } - }, component); - assertEquals('1 of 3, 2 of 3, 3 of 3', sb.toString()); - } - - function testIndexOfChild() { - var a = new goog.ui.Component(); - var b = new goog.ui.Component(); - var c = new goog.ui.Component(); - - a.setId('a'); - b.setId('b'); - c.setId('c'); - - component.addChild(a); - assertEquals(0, component.indexOfChild(a)); - - component.addChild(b); - assertEquals(1, component.indexOfChild(b)); - - component.addChild(c); - assertEquals(2, component.indexOfChild(c)); - - assertEquals('indexOfChild must return -1 for nonexistent child', -1, - component.indexOfChild(new goog.ui.Component())); - } - - function testRemoveChild() { - var a = new goog.ui.Component(); - var b = new goog.ui.Component(); - var c = new goog.ui.Component(); - - a.setId('a'); - b.setId('b'); - c.setId('c'); - - component.addChild(a); - component.addChild(b); - component.addChild(c); - - assertEquals('Parent must remove and return child', c, - component.removeChild(c)); - assertNull('Parent must no longer contain this child', - component.getChild('c')); - - assertEquals('Parent must remove and return child by ID', b, - component.removeChild('b')); - assertNull('Parent must no longer contain this child', - component.getChild('b')); - - assertEquals('Parent must remove and return child by index', a, - component.removeChildAt(0)); - assertNull('Parent must no longer contain this child', - component.getChild('a')); - } - - function testMovingChildrenUsingAddChildAt() { - component.render(sandbox); - - var a = new goog.ui.Component(); - var b = new goog.ui.Component(); - var c = new goog.ui.Component(); - var d = new goog.ui.Component(); - a.setElementInternal(goog.dom.createElement('a')); - b.setElementInternal(goog.dom.createElement('b')); - c.setElementInternal(goog.dom.createElement('c')); - d.setElementInternal(goog.dom.createElement('d')); - - a.setId('a'); - b.setId('b'); - c.setId('c'); - d.setId('d'); - - component.addChild(a); - component.addChild(b); - component.addChild(c); - component.addChild(d); - - assertEquals('abcd', component.getChildIds().join('')); - assertEquals(a, component.getChildAt(0)); - assertEquals(b, component.getChildAt(1)); - assertEquals(c, component.getChildAt(2)); - assertEquals(d, component.getChildAt(3)); - - // Move child d to the top and b to the bottom. - component.addChildAt(d, 0); - component.addChildAt(b, 3); - - assertEquals('dacb', component.getChildIds().join('')); - assertEquals(d, component.getChildAt(0)); - assertEquals(a, component.getChildAt(1)); - assertEquals(c, component.getChildAt(2)); - assertEquals(b, component.getChildAt(3)); - - // Move child a to the top, and check that DOM nodes are in correct order. - component.addChildAt(a, 0); - assertEquals('adcb', component.getChildIds().join('')); - assertEquals(a, component.getChildAt(0)); - assertEquals(a.getElement(), component.getElement().childNodes[0]); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/container.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/container.js.svn-base deleted file mode 100644 index e0ce771..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/container.js.svn-base +++ /dev/null @@ -1,1297 +0,0 @@ -// 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 Base class for containers that host {@link goog.ui.Control}s, - * such as menus and toolbars. Provides default keyboard and mouse event - * handling and child management, based on a generalized version of - * {@link goog.ui.Menu}. - * - * @author attila@google.com (Attila Bodis) - * @see ../demos/container.html - */ -// TODO(attila): Fix code/logic duplication between this and goog.ui.Control. -// TODO(attila): Maybe pull common stuff all the way up into Component...? - -goog.provide('goog.ui.Container'); -goog.provide('goog.ui.Container.EventType'); -goog.provide('goog.ui.Container.Orientation'); - -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.a11y.State'); -goog.require('goog.events.EventType'); -goog.require('goog.events.KeyCodes'); -goog.require('goog.events.KeyHandler'); -goog.require('goog.events.KeyHandler.EventType'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.Component.Error'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.Component.State'); -goog.require('goog.ui.ContainerRenderer'); - - - -/** - * Base class for containers. Extends {@link goog.ui.Component} by adding - * the following: - * <ul> - * <li>a {@link goog.events.KeyHandler}, to simplify keyboard handling, - * <li>a pluggable <em>renderer</em> framework, to simplify the creation of - * containers without the need to subclass this class, - * <li>methods to manage child controls hosted in the container, - * <li>default mouse and keyboard event handling methods. - * </ul> - * @param {?goog.ui.Container.Orientation=} opt_orientation Container - * orientation; defaults to {@code VERTICAL}. - * @param {goog.ui.ContainerRenderer=} opt_renderer Renderer used to render or - * decorate the container; defaults to {@link goog.ui.ContainerRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for document - * interaction. - * @extends {goog.ui.Component} - * @constructor - */ -goog.ui.Container = function(opt_orientation, opt_renderer, opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - this.renderer_ = opt_renderer || goog.ui.ContainerRenderer.getInstance(); - this.orientation_ = opt_orientation || this.renderer_.getDefaultOrientation(); -}; -goog.inherits(goog.ui.Container, goog.ui.Component); - - -/** - * Container-specific events. - * @enum {string} - */ -goog.ui.Container.EventType = { - /** - * Dispatched after a goog.ui.Container becomes visible. Non-cancellable. - * NOTE(user): This event really shouldn't exist, because the - * goog.ui.Component.EventType.SHOW event should behave like this one. But the - * SHOW event for containers has been behaving as other components' - * BEFORE_SHOW event for a long time, and too much code relies on that old - * behavior to fix it now. - */ - AFTER_SHOW: 'aftershow', - - /** - * Dispatched after a goog.ui.Container becomes invisible. Non-cancellable. - */ - AFTER_HIDE: 'afterhide' -}; - - -/** - * Container orientation constants. - * @enum {string} - */ -goog.ui.Container.Orientation = { - HORIZONTAL: 'horizontal', - VERTICAL: 'vertical' -}; - - -/** - * Allows an alternative element to be set to receive key events, otherwise - * defers to the renderer's element choice. - * @type {Element|undefined} - * @private - */ -goog.ui.Container.prototype.keyEventTarget_ = null; - - -/** - * Keyboard event handler. - * @type {goog.events.KeyHandler?} - * @private - */ -goog.ui.Container.prototype.keyHandler_ = null; - - -/** - * Renderer for the container. Defaults to {@link goog.ui.ContainerRenderer}. - * @type {goog.ui.ContainerRenderer?} - * @private - */ -goog.ui.Container.prototype.renderer_ = null; - - -/** - * Container orientation; determines layout and default keyboard navigation. - * @type {?goog.ui.Container.Orientation} - * @private - */ -goog.ui.Container.prototype.orientation_ = null; - - -/** - * Whether the container is set to be visible. Defaults to true. - * @type {boolean} - * @private - */ -goog.ui.Container.prototype.visible_ = true; - - -/** - * Whether the container is enabled and reacting to keyboard and mouse events. - * Defaults to true. - * @type {boolean} - * @private - */ -goog.ui.Container.prototype.enabled_ = true; - - -/** - * Whether the container supports keyboard focus. Defaults to true. Focusable - * containers have a {@code tabIndex} and can be navigated to via the keyboard. - * @type {boolean} - * @private - */ -goog.ui.Container.prototype.focusable_ = true; - - -/** - * The 0-based index of the currently highlighted control in the container - * (-1 if none). - * @type {number} - * @private - */ -goog.ui.Container.prototype.highlightedIndex_ = -1; - - -/** - * The currently open (expanded) control in the container (null if none). - * @type {goog.ui.Control?} - * @private - */ -goog.ui.Container.prototype.openItem_ = null; - - -/** - * Whether the mouse button is held down. Defaults to false. This flag is set - * when the user mouses down over the container, and remains set until they - * release the mouse button. - * @type {boolean} - * @private - */ -goog.ui.Container.prototype.mouseButtonPressed_ = false; - - -/** - * Whether focus of child components should be allowed. Only effective if - * focusable_ is set to false. - * @type {boolean} - * @private - */ -goog.ui.Container.prototype.allowFocusableChildren_ = false; - - -/** - * Whether highlighting a child component should also open it. - * @type {boolean} - * @private - */ -goog.ui.Container.prototype.openFollowsHighlight_ = true; - - -/** - * Map of DOM IDs to child controls. Each key is the DOM ID of a child - * control's root element; each value is a reference to the child control - * itself. Used for looking up the child control corresponding to a DOM - * node in O(1) time. - * @type {Object} - * @private - */ -goog.ui.Container.prototype.childElementIdMap_ = null; - - -// Event handler and renderer management. - - -/** - * Returns the DOM element on which the container is listening for keyboard - * events (null if none). - * @return {Element} Element on which the container is listening for key - * events. - */ -goog.ui.Container.prototype.getKeyEventTarget = function() { - // Delegate to renderer, unless we've set an explicit target. - return this.keyEventTarget_ || this.renderer_.getKeyEventTarget(this); -}; - - -/** - * Attaches an element on which to listen for key events. - * @param {Element|undefined} element The element to attach, or null/undefined - * to attach to the default element. - */ -goog.ui.Container.prototype.setKeyEventTarget = function(element) { - if (this.focusable_) { - var oldTarget = this.getKeyEventTarget(); - var inDocument = this.isInDocument(); - - this.keyEventTarget_ = element; - var newTarget = this.getKeyEventTarget(); - - if (inDocument) { - // Unlisten for events on the old key target. Requires us to reset - // key target state temporarily. - this.keyEventTarget_ = oldTarget; - this.enableFocusHandling_(false); - this.keyEventTarget_ = element; - - // Listen for events on the new key target. - this.getKeyHandler().attach(newTarget); - this.enableFocusHandling_(true); - } - } else { - throw Error('Can\'t set key event target for container ' + - 'that doesn\'t support keyboard focus!'); - } -}; - - -/** - * Returns the keyboard event handler for this container, lazily created the - * first time this method is called. The keyboard event handler listens for - * keyboard events on the container's key event target, as determined by its - * renderer. - * @return {goog.events.KeyHandler} Keyboard event handler for this container. - */ -goog.ui.Container.prototype.getKeyHandler = function() { - return this.keyHandler_ || - (this.keyHandler_ = new goog.events.KeyHandler(this.getKeyEventTarget())); -}; - - -/** - * Returns the renderer used by this container to render itself or to decorate - * an existing element. - * @return {goog.ui.ContainerRenderer} Renderer used by the container. - */ -goog.ui.Container.prototype.getRenderer = function() { - return this.renderer_; -}; - - -/** - * Registers the given renderer with the container. Changing renderers after - * the container has already been rendered or decorated is an error. - * @param {goog.ui.ContainerRenderer} renderer Renderer used by the container. - */ -goog.ui.Container.prototype.setRenderer = function(renderer) { - if (this.getElement()) { - // Too late. - throw Error(goog.ui.Component.Error.ALREADY_RENDERED); - } - - this.renderer_ = renderer; -}; - - -// Standard goog.ui.Component implementation. - - -/** - * Creates the container's DOM. Overrides {@link goog.ui.Component#createDom}. - */ -goog.ui.Container.prototype.createDom = function() { - // Delegate to renderer. - this.setElementInternal(this.renderer_.createDom(this)); -}; - - -/** - * Returns the DOM element into which child components are to be rendered, - * or null if the container itself hasn't been rendered yet. Overrides - * {@link goog.ui.Component#getContentElement} by delegating to the renderer. - * @return {Element} Element to contain child elements (null if none). - */ -goog.ui.Container.prototype.getContentElement = function() { - // Delegate to renderer. - return this.renderer_.getContentElement(this.getElement()); -}; - - -/** - * Returns true if the given element can be decorated by this container. - * Overrides {@link goog.ui.Component#canDecorate}. - * @param {Element} element Element to decorate. - * @return {boolean} True iff the element can be decorated. - */ -goog.ui.Container.prototype.canDecorate = function(element) { - // Delegate to renderer. - return this.renderer_.canDecorate(element); -}; - - -/** - * Decorates the given element with this container. Overrides {@link - * goog.ui.Component#decorateInternal}. Considered protected. - * @param {Element} element Element to decorate. - */ -goog.ui.Container.prototype.decorateInternal = function(element) { - // Delegate to renderer. - this.setElementInternal(this.renderer_.decorate(this, element)); - // Check whether the decorated element is explicitly styled to be invisible. - if (element.style.display == 'none') { - this.visible_ = false; - } -}; - - -/** - * Configures the container after its DOM has been rendered, and sets up event - * handling. Overrides {@link goog.ui.Component#enterDocument}. - */ -goog.ui.Container.prototype.enterDocument = function() { - goog.ui.Container.superClass_.enterDocument.call(this); - - this.forEachChild(function(child) { - if (child.isInDocument()) { - this.registerChildId_(child); - } - }, this); - - var elem = this.getElement(); - - // Call the renderer's initializeDom method to initialize the container's DOM. - this.renderer_.initializeDom(this); - - // Initialize visibility (opt_force = true, so we don't dispatch events). - this.setVisible(this.visible_, true); - - // Handle events dispatched by child controls. - this.getHandler(). - listen(this, goog.ui.Component.EventType.ENTER, - this.handleEnterItem). - listen(this, goog.ui.Component.EventType.HIGHLIGHT, - this.handleHighlightItem). - listen(this, goog.ui.Component.EventType.UNHIGHLIGHT, - this.handleUnHighlightItem). - listen(this, goog.ui.Component.EventType.OPEN, this.handleOpenItem). - listen(this, goog.ui.Component.EventType.CLOSE, this.handleCloseItem). - - // Handle mouse events. - listen(elem, goog.events.EventType.MOUSEDOWN, this.handleMouseDown). - listen(goog.dom.getOwnerDocument(elem), goog.events.EventType.MOUSEUP, - this.handleDocumentMouseUp). - - // Handle mouse events on behalf of controls in the container. - listen(elem, [ - goog.events.EventType.MOUSEDOWN, - goog.events.EventType.MOUSEUP, - goog.events.EventType.MOUSEOVER, - goog.events.EventType.MOUSEOUT - ], this.handleChildMouseEvents); - - // If the container is focusable, set up keyboard event handling. - if (this.isFocusable()) { - this.enableFocusHandling_(true); - } -}; - - -/** - * Sets up listening for events applicable to focusable containers. - * @param {boolean} enable Whether to enable or disable focus handling. - * @private - */ -goog.ui.Container.prototype.enableFocusHandling_ = function(enable) { - var handler = this.getHandler(); - var keyTarget = this.getKeyEventTarget(); - if (enable) { - handler. - listen(keyTarget, goog.events.EventType.FOCUS, this.handleFocus). - listen(keyTarget, goog.events.EventType.BLUR, this.handleBlur). - listen(this.getKeyHandler(), goog.events.KeyHandler.EventType.KEY, - this.handleKeyEvent); - } else { - handler. - unlisten(keyTarget, goog.events.EventType.FOCUS, this.handleFocus). - unlisten(keyTarget, goog.events.EventType.BLUR, this.handleBlur). - unlisten(this.getKeyHandler(), goog.events.KeyHandler.EventType.KEY, - this.handleKeyEvent); - } -}; - - -/** - * Cleans up the container before its DOM is removed from the document, and - * removes event handlers. Overrides {@link goog.ui.Component#exitDocument}. - */ -goog.ui.Container.prototype.exitDocument = function() { - // {@link #setHighlightedIndex} has to be called before - // {@link goog.ui.Component#exitDocument}, otherwise it has no effect. - this.setHighlightedIndex(-1); - - if (this.openItem_) { - this.openItem_.setOpen(false); - } - - this.mouseButtonPressed_ = false; - - goog.ui.Container.superClass_.exitDocument.call(this); -}; - - -/** @override */ -goog.ui.Container.prototype.disposeInternal = function() { - goog.ui.Container.superClass_.disposeInternal.call(this); - - if (this.keyHandler_) { - this.keyHandler_.dispose(); - this.keyHandler_ = null; - } - - this.keyEventTarget_ = null; - this.childElementIdMap_ = null; - this.openItem_ = null; - this.renderer_ = null; -}; - - -// Default event handlers. - - -/** - * Handles ENTER events raised by child controls when they are navigated to. - * @param {goog.events.Event} e ENTER event to handle. - * @return {boolean} Whether to prevent handleMouseOver from handling - * the event. - */ -goog.ui.Container.prototype.handleEnterItem = function(e) { - // Allow the Control to highlight itself. - return true; -}; - - -/** - * Handles HIGHLIGHT events dispatched by items in the container when - * they are highlighted. - * @param {goog.events.Event} e Highlight event to handle. - */ -goog.ui.Container.prototype.handleHighlightItem = function(e) { - var index = this.indexOfChild(/** @type {goog.ui.Control} */ (e.target)); - if (index > -1 && index != this.highlightedIndex_) { - var item = this.getHighlighted(); - if (item) { - // Un-highlight previously highlighted item. - item.setHighlighted(false); - } - - this.highlightedIndex_ = index; - item = this.getHighlighted(); - - if (this.isMouseButtonPressed()) { - // Activate item when mouse button is pressed, to allow MacOS-style - // dragging to choose menu items. Although this should only truly - // happen if the highlight is due to mouse movements, there is little - // harm in doing it for keyboard or programmatic highlights. - item.setActive(true); - } - - // Update open item if open item needs follow highlight. - if (this.openFollowsHighlight_ && - this.openItem_ && item != this.openItem_) { - if (item.isSupportedState(goog.ui.Component.State.OPENED)) { - item.setOpen(true); - } else { - this.openItem_.setOpen(false); - } - } - } - goog.dom.a11y.setState(this.getElement(), - goog.dom.a11y.State.ACTIVEDESCENDANT, e.target.getElement().id); -}; - - -/** - * Handles UNHIGHLIGHT events dispatched by items in the container when - * they are unhighlighted. - * @param {goog.events.Event} e Unhighlight event to handle. - */ -goog.ui.Container.prototype.handleUnHighlightItem = function(e) { - if (e.target == this.getHighlighted()) { - this.highlightedIndex_ = -1; - } - goog.dom.a11y.setState(this.getElement(), - goog.dom.a11y.State.ACTIVEDESCENDANT, ''); -}; - - -/** - * Handles OPEN events dispatched by items in the container when they are - * opened. - * @param {goog.events.Event} e Open event to handle. - */ -goog.ui.Container.prototype.handleOpenItem = function(e) { - var item = /** @type {goog.ui.Control} */ (e.target); - if (item && item != this.openItem_ && item.getParent() == this) { - if (this.openItem_) { - this.openItem_.setOpen(false); - } - this.openItem_ = item; - } -}; - - -/** - * Handles CLOSE events dispatched by items in the container when they are - * closed. - * @param {goog.events.Event} e Close event to handle. - */ -goog.ui.Container.prototype.handleCloseItem = function(e) { - if (e.target == this.openItem_) { - this.openItem_ = null; - } -}; - - -/** - * Handles mousedown events over the container. The default implementation - * sets the "mouse button pressed" flag and, if the container is focusable, - * grabs keyboard focus. - * @param {goog.events.BrowserEvent} e Mousedown event to handle. - */ -goog.ui.Container.prototype.handleMouseDown = function(e) { - if (this.enabled_) { - this.setMouseButtonPressed(true); - } - - var keyTarget = this.getKeyEventTarget(); - if (keyTarget && goog.dom.isFocusableTabIndex(keyTarget)) { - // The container is configured to receive keyboard focus. - keyTarget.focus(); - } else { - // The control isn't configured to receive keyboard focus; prevent it - // from stealing focus or destroying the selection. - e.preventDefault(); - } -}; - - -/** - * Handles mouseup events over the document. The default implementation - * clears the "mouse button pressed" flag. - * @param {goog.events.BrowserEvent} e Mouseup event to handle. - */ -goog.ui.Container.prototype.handleDocumentMouseUp = function(e) { - this.setMouseButtonPressed(false); -}; - - -/** - * Handles mouse events originating from nodes belonging to the controls hosted - * in the container. Locates the child control based on the DOM node that - * dispatched the event, and forwards the event to the control for handling. - * @param {goog.events.BrowserEvent} e Mouse event to handle. - */ -goog.ui.Container.prototype.handleChildMouseEvents = function(e) { - var control = this.getOwnerControl(/** @type {Node} */ (e.target)); - if (control) { - // Child control identified; forward the event. - switch (e.type) { - case goog.events.EventType.MOUSEDOWN: - control.handleMouseDown(e); - break; - case goog.events.EventType.MOUSEUP: - control.handleMouseUp(e); - break; - case goog.events.EventType.MOUSEOVER: - control.handleMouseOver(e); - break; - case goog.events.EventType.MOUSEOUT: - control.handleMouseOut(e); - break; - } - } -}; - - -/** - * Returns the child control that owns the given DOM node, or null if no such - * control is found. - * @param {Node} node DOM node whose owner is to be returned. - * @return {goog.ui.Control?} Control hosted in the container to which the node - * belongs (if found). - * @protected - */ -goog.ui.Container.prototype.getOwnerControl = function(node) { - // Ensure that this container actually has child controls before - // looking up the owner. - if (this.childElementIdMap_) { - var elem = this.getElement(); - // See http://b/2964418 . IE9 appears to evaluate '!=' incorrectly, so - // using '!==' instead. - // TODO(user): Possibly revert this change if/when IE9 fixes the issue. - while (node && node !== elem) { - var id = node.id; - if (id in this.childElementIdMap_) { - return this.childElementIdMap_[id]; - } - node = node.parentNode; - } - } - return null; -}; - - -/** - * Handles focus events raised when the container's key event target receives - * keyboard focus. - * @param {goog.events.BrowserEvent} e Focus event to handle. - */ -goog.ui.Container.prototype.handleFocus = function(e) { - // No-op in the base class. -}; - - -/** - * Handles blur events raised when the container's key event target loses - * keyboard focus. The default implementation clears the highlight index. - * @param {goog.events.BrowserEvent} e Blur event to handle. - */ -goog.ui.Container.prototype.handleBlur = function(e) { - this.setHighlightedIndex(-1); - this.setMouseButtonPressed(false); - // If the container loses focus, and one of its children is open, close it. - if (this.openItem_) { - this.openItem_.setOpen(false); - } -}; - - -/** - * Attempts to handle a keyboard event, if the control is enabled, by calling - * {@link handleKeyEventInternal}. Considered protected; should only be used - * within this package and by subclasses. - * @param {goog.events.KeyEvent} e Key event to handle. - * @return {boolean} Whether the key event was handled. - */ -goog.ui.Container.prototype.handleKeyEvent = function(e) { - if (this.isEnabled() && this.isVisible() && - (this.getChildCount() != 0 || this.keyEventTarget_) && - this.handleKeyEventInternal(e)) { - e.preventDefault(); - e.stopPropagation(); - return true; - } - return false; -}; - - -/** - * Attempts to handle a keyboard event; returns true if the event was handled, - * false otherwise. If the container is enabled, and a child is highlighted, - * calls the child control's {@code handleKeyEvent} method to give the control - * a chance to handle the event first. - * @param {goog.events.KeyEvent} e Key event to handle. - * @return {boolean} Whether the event was handled by the container (or one of - * its children). - */ -goog.ui.Container.prototype.handleKeyEventInternal = function(e) { - // Give the highlighted control the chance to handle the key event. - var highlighted = this.getHighlighted(); - if (highlighted && typeof highlighted.handleKeyEvent == 'function' && - highlighted.handleKeyEvent(e)) { - return true; - } - - // Give the open control the chance to handle the key event. - if (this.openItem_ && this.openItem_ != highlighted && - typeof this.openItem_.handleKeyEvent == 'function' && - this.openItem_.handleKeyEvent(e)) { - return true; - } - - // Do not handle the key event if any modifier key is pressed. - if (e.shiftKey || e.ctrlKey || e.metaKey || e.altKey) { - return false; - } - - // Either nothing is highlighted, or the highlighted control didn't handle - // the key event, so attempt to handle it here. - switch (e.keyCode) { - case goog.events.KeyCodes.ESC: - if (this.isFocusable()) { - this.getKeyEventTarget().blur(); - } else { - return false; - } - break; - - case goog.events.KeyCodes.HOME: - this.highlightFirst(); - break; - - case goog.events.KeyCodes.END: - this.highlightLast(); - break; - - case goog.events.KeyCodes.UP: - if (this.orientation_ == goog.ui.Container.Orientation.VERTICAL) { - this.highlightPrevious(); - } else { - return false; - } - break; - - case goog.events.KeyCodes.LEFT: - if (this.orientation_ == goog.ui.Container.Orientation.HORIZONTAL) { - if (this.isRightToLeft()) { - this.highlightNext(); - } else { - this.highlightPrevious(); - } - } else { - return false; - } - break; - - case goog.events.KeyCodes.DOWN: - if (this.orientation_ == goog.ui.Container.Orientation.VERTICAL) { - this.highlightNext(); - } else { - return false; - } - break; - - case goog.events.KeyCodes.RIGHT: - if (this.orientation_ == goog.ui.Container.Orientation.HORIZONTAL) { - if (this.isRightToLeft()) { - this.highlightPrevious(); - } else { - this.highlightNext(); - } - } else { - return false; - } - break; - - default: - return false; - } - - return true; -}; - - -// Child component management. - - -/** - * Creates a DOM ID for the child control and registers it to an internal - * hash table to be able to find it fast by id. - * @param {goog.ui.Control} child The child control. Its root element has - * to be created yet. - * @private - */ -goog.ui.Container.prototype.registerChildId_ = function(child) { - // Map the DOM ID of the control's root element to the control itself. - var childElem = child.getElement(); - - // If the control's root element doesn't have a DOM ID assign one. - var id = childElem.id || (childElem.id = child.getId()); - - // Lazily create the child element ID map on first use. - if (!this.childElementIdMap_) { - this.childElementIdMap_ = {}; - } - this.childElementIdMap_[id] = child; -}; - - -/** - * Adds the specified control as the last child of this container. See - * {@link goog.ui.Container#addChildAt} for detailed semantics. - * @param {goog.ui.Control} child The new child control. - * @param {boolean=} opt_render Whether the new child should be rendered - * immediately after being added (defaults to false). - */ -goog.ui.Container.prototype.addChild = function(child, opt_render) { - goog.ui.Container.superClass_.addChild.call(this, child, opt_render); -}; - - -/** - * Overrides {@link goog.ui.Container#getChild} to make it clear that it - * only returns {@link goog.ui.Control}s. - * @param {string} id Child component ID. - * @return {goog.ui.Control} The child with the given ID; null if none. - * @override - */ -goog.ui.Container.prototype.getChild; - - -/** - * Overrides {@link goog.ui.Container#getChildAt} to make it clear that it - * only returns {@link goog.ui.Control}s. - * @param {number} index 0-based index. - * @return {goog.ui.Control} The child with the given ID; null if none. - * @override - */ -goog.ui.Container.prototype.getChildAt; - - -/** - * Adds the control as a child of this container at the given 0-based index. - * Overrides {@link goog.ui.Component#addChildAt} by also updating the - * container's highlight index. Since {@link goog.ui.Component#addChild} uses - * {@link #addChildAt} internally, we only need to override this method. - * @param {goog.ui.Control} control New child. - * @param {number} index Index at which the new child is to be added. - * @param {boolean=} opt_render Whether the new child should be rendered - * immediately after being added (defaults to false). - */ -goog.ui.Container.prototype.addChildAt = function(control, index, opt_render) { - // Make sure the child control dispatches HIGHLIGHT, UNHIGHLIGHT, OPEN, and - // CLOSE events, and that it doesn't steal keyboard focus. - control.setDispatchTransitionEvents(goog.ui.Component.State.HOVER, true); - control.setDispatchTransitionEvents(goog.ui.Component.State.OPENED, true); - if (this.isFocusable() || !this.isFocusableChildrenAllowed()) { - control.setSupportedState(goog.ui.Component.State.FOCUSED, false); - } - - // Disable mouse event handling by child controls. - control.setHandleMouseEvents(false); - - // Let the superclass implementation do the work. - goog.ui.Container.superClass_.addChildAt.call(this, control, index, - opt_render); - - if (control.isInDocument() && this.isInDocument()) { - this.registerChildId_(control); - } - - // Update the highlight index, if needed. - if (index <= this.highlightedIndex_) { - this.highlightedIndex_++; - } -}; - - -/** - * Removes a child control. Overrides {@link goog.ui.Component#removeChild} by - * updating the highlight index. Since {@link goog.ui.Component#removeChildAt} - * uses {@link #removeChild} internally, we only need to override this method. - * @param {string|goog.ui.Control} control The ID of the child to remove, or - * the control itself. - * @param {boolean=} opt_unrender Whether to call {@code exitDocument} on the - * removed control, and detach its DOM from the document (defaults to - * false). - * @return {goog.ui.Control} The removed control, if any. - */ -goog.ui.Container.prototype.removeChild = function(control, opt_unrender) { - control = goog.isString(control) ? this.getChild(control) : control; - - if (control) { - var index = this.indexOfChild(control); - if (index != -1) { - if (index == this.highlightedIndex_) { - control.setHighlighted(false); - } else if (index < this.highlightedIndex_) { - this.highlightedIndex_--; - } - } - - // Remove the mapping from the child element ID map. - var childElem = control.getElement(); - if (childElem && childElem.id && this.childElementIdMap_) { - goog.object.remove(this.childElementIdMap_, childElem.id); - } - } - - control = /** @type {goog.ui.Control} */ ( - goog.ui.Container.superClass_.removeChild.call(this, control, - opt_unrender)); - - // Re-enable mouse event handling (in case the control is reused elsewhere). - control.setHandleMouseEvents(true); - - return control; -}; - - -// Container state management. - - -/** - * Returns the container's orientation. - * @return {?goog.ui.Container.Orientation} Container orientation. - */ -goog.ui.Container.prototype.getOrientation = function() { - return this.orientation_; -}; - - -/** - * Sets the container's orientation. - * @param {goog.ui.Container.Orientation} orientation Container orientation. - */ -// TODO(attila): Do we need to support containers with dynamic orientation? -goog.ui.Container.prototype.setOrientation = function(orientation) { - if (this.getElement()) { - // Too late. - throw Error(goog.ui.Component.Error.ALREADY_RENDERED); - } - - this.orientation_ = orientation; -}; - - -/** - * Returns true if the container's visibility is set to visible, false if - * it is set to hidden. A container that is set to hidden is guaranteed - * to be hidden from the user, but the reverse isn't necessarily true. - * A container may be set to visible but can otherwise be obscured by another - * element, rendered off-screen, or hidden using direct CSS manipulation. - * @return {boolean} Whether the container is set to be visible. - */ -goog.ui.Container.prototype.isVisible = function() { - return this.visible_; -}; - - -/** - * Shows or hides the container. Does nothing if the container already has - * the requested visibility. Otherwise, dispatches a SHOW or HIDE event as - * appropriate, giving listeners a chance to prevent the visibility change. - * @param {boolean} visible Whether to show or hide the container. - * @param {boolean=} opt_force If true, doesn't check whether the container - * already has the requested visibility, and doesn't dispatch any events. - * @return {boolean} Whether the visibility was changed. - */ -goog.ui.Container.prototype.setVisible = function(visible, opt_force) { - if (opt_force || (this.visible_ != visible && this.dispatchEvent(visible ? - goog.ui.Component.EventType.SHOW : goog.ui.Component.EventType.HIDE))) { - this.visible_ = visible; - - var elem = this.getElement(); - if (elem) { - goog.style.showElement(elem, visible); - if (this.isFocusable()) { - // Enable keyboard access only for enabled & visible containers. - this.renderer_.enableTabIndex(this.getKeyEventTarget(), - this.enabled_ && this.visible_); - } - if (!opt_force) { - this.dispatchEvent(this.visible_ ? - goog.ui.Container.EventType.AFTER_SHOW : - goog.ui.Container.EventType.AFTER_HIDE); - } - } - - return true; - } - - return false; -}; - - -/** - * Returns true if the container is enabled, false otherwise. - * @return {boolean} Whether the container is enabled. - */ -goog.ui.Container.prototype.isEnabled = function() { - return this.enabled_; -}; - - -/** - * Enables/disables the container based on the {@code enable} argument. - * Dispatches an {@code ENABLED} or {@code DISABLED} event prior to changing - * the container's state, which may be caught and canceled to prevent the - * container from changing state. Also enables/disables child controls. - * @param {boolean} enable Whether to enable or disable the container. - */ -goog.ui.Container.prototype.setEnabled = function(enable) { - if (this.enabled_ != enable && this.dispatchEvent(enable ? - goog.ui.Component.EventType.ENABLE : - goog.ui.Component.EventType.DISABLE)) { - if (enable) { - // Flag the container as enabled first, then update children. This is - // because controls can't be enabled if their parent is disabled. - this.enabled_ = true; - this.forEachChild(function(child) { - // Enable child control unless it is flagged. - if (child.wasDisabled) { - delete child.wasDisabled; - } else { - child.setEnabled(true); - } - }); - } else { - // Disable children first, then flag the container as disabled. This is - // because controls can't be disabled if their parent is already disabled. - this.forEachChild(function(child) { - // Disable child control, or flag it if it's already disabled. - if (child.isEnabled()) { - child.setEnabled(false); - } else { - child.wasDisabled = true; - } - }); - this.enabled_ = false; - this.setMouseButtonPressed(false); - } - - if (this.isFocusable()) { - // Enable keyboard access only for enabled & visible components. - this.renderer_.enableTabIndex(this.getKeyEventTarget(), - enable && this.visible_); - } - } -}; - - -/** - * Returns true if the container is focusable, false otherwise. The default - * is true. Focusable containers always have a tab index and allocate a key - * handler to handle keyboard events while focused. - * @return {boolean} Whether the component is focusable. - */ -goog.ui.Container.prototype.isFocusable = function() { - return this.focusable_; -}; - - -/** - * Sets whether the container is focusable. The default is true. Focusable - * containers always have a tab index and allocate a key handler to handle - * keyboard events while focused. - * @param {boolean} focusable Whether the component is to be focusable. - */ -goog.ui.Container.prototype.setFocusable = function(focusable) { - if (focusable != this.focusable_ && this.isInDocument()) { - this.enableFocusHandling_(focusable); - } - this.focusable_ = focusable; - if (this.enabled_ && this.visible_) { - this.renderer_.enableTabIndex(this.getKeyEventTarget(), focusable); - } -}; - - -/** - * Returns true if the container allows children to be focusable, false - * otherwise. Only effective if the container is not focusable. - * @return {boolean} Whether children should be focusable. - */ -goog.ui.Container.prototype.isFocusableChildrenAllowed = function() { - return this.allowFocusableChildren_; -}; - - -/** - * Sets whether the container allows children to be focusable, false - * otherwise. Only effective if the container is not focusable. - * @param {boolean} focusable Whether the children should be focusable. - */ -goog.ui.Container.prototype.setFocusableChildrenAllowed = function(focusable) { - this.allowFocusableChildren_ = focusable; -}; - - -/** - * @return {boolean} Whether highlighting a child component should also open it. - */ -goog.ui.Container.prototype.isOpenFollowsHighlight = function() { - return this.openFollowsHighlight_; -}; - - -/** - * Sets whether highlighting a child component should also open it. - * @param {boolean} follow Whether highlighting a child component also opens it. - */ -goog.ui.Container.prototype.setOpenFollowsHighlight = function(follow) { - this.openFollowsHighlight_ = follow; -}; - - -// Highlight management. - - -/** - * Returns the index of the currently highlighted item (-1 if none). - * @return {number} Index of the currently highlighted item. - */ -goog.ui.Container.prototype.getHighlightedIndex = function() { - return this.highlightedIndex_; -}; - - -/** - * Highlights the item at the given 0-based index (if any). If another item - * was previously highlighted, it is un-highlighted. - * @param {number} index Index of item to highlight (-1 removes the current - * highlight). - */ -goog.ui.Container.prototype.setHighlightedIndex = function(index) { - var child = this.getChildAt(index); - if (child) { - child.setHighlighted(true); - } else if (this.highlightedIndex_ > -1) { - this.getHighlighted().setHighlighted(false); - } -}; - - -/** - * Highlights the given item if it exists and is a child of the container; - * otherwise un-highlights the currently highlighted item. - * @param {goog.ui.Control} item Item to highlight. - */ -goog.ui.Container.prototype.setHighlighted = function(item) { - this.setHighlightedIndex(this.indexOfChild(item)); -}; - - -/** - * Returns the currently highlighted item (if any). - * @return {goog.ui.Control?} Highlighted item (null if none). - */ -goog.ui.Container.prototype.getHighlighted = function() { - return this.getChildAt(this.highlightedIndex_); -}; - - -/** - * Highlights the first highlightable item in the container - */ -goog.ui.Container.prototype.highlightFirst = function() { - this.highlightHelper(function(index, max) { - return (index + 1) % max; - }, this.getChildCount() - 1); -}; - - -/** - * Highlights the last highlightable item in the container. - */ -goog.ui.Container.prototype.highlightLast = function() { - this.highlightHelper(function(index, max) { - index--; - return index < 0 ? max - 1 : index; - }, 0); -}; - - -/** - * Highlights the next highlightable item (or the first if nothing is currently - * highlighted). - */ -goog.ui.Container.prototype.highlightNext = function() { - this.highlightHelper(function(index, max) { - return (index + 1) % max; - }, this.highlightedIndex_); -}; - - -/** - * Highlights the previous highlightable item (or the last if nothing is - * currently highlighted). - */ -goog.ui.Container.prototype.highlightPrevious = function() { - this.highlightHelper(function(index, max) { - index--; - return index < 0 ? max - 1 : index; - }, this.highlightedIndex_); -}; - - -/** - * Helper function that manages the details of moving the highlight among - * child controls in response to keyboard events. - * @param {function(number, number) : number} fn Function that accepts the - * current and maximum indices, and returns the next index to check. - * @param {number} startIndex Start index. - * @return {boolean} Whether the highlight has changed. - * @protected - */ -goog.ui.Container.prototype.highlightHelper = function(fn, startIndex) { - // If the start index is -1 (meaning there's nothing currently highlighted), - // try starting from the currently open item, if any. - var curIndex = startIndex < 0 ? - this.indexOfChild(this.openItem_) : startIndex; - var numItems = this.getChildCount(); - - curIndex = fn.call(this, curIndex, numItems); - var visited = 0; - while (visited <= numItems) { - var control = this.getChildAt(curIndex); - if (control && this.canHighlightItem(control)) { - this.setHighlightedIndexFromKeyEvent(curIndex); - return true; - } - visited++; - curIndex = fn.call(this, curIndex, numItems); - } - return false; -}; - - -/** - * Returns whether the given item can be highlighted. - * @param {goog.ui.Control} item The item to check. - * @return {boolean} Whether the item can be highlighted. - * @protected - */ -goog.ui.Container.prototype.canHighlightItem = function(item) { - return item.isVisible() && item.isEnabled() && - item.isSupportedState(goog.ui.Component.State.HOVER); -}; - - -/** - * Helper method that sets the highlighted index to the given index in response - * to a keyboard event. The base class implementation simply calls the - * {@link #setHighlightedIndex} method, but subclasses can override this - * behavior as needed. - * @param {number} index Index of item to highlight. - * @protected - */ -goog.ui.Container.prototype.setHighlightedIndexFromKeyEvent = function(index) { - this.setHighlightedIndex(index); -}; - - -/** - * Returns the currently open (expanded) control in the container (null if - * none). - * @return {goog.ui.Control?} The currently open control. - */ -goog.ui.Container.prototype.getOpenItem = function() { - return this.openItem_; -}; - - -/** - * Returns true if the mouse button is pressed, false otherwise. - * @return {boolean} Whether the mouse button is pressed. - */ -goog.ui.Container.prototype.isMouseButtonPressed = function() { - return this.mouseButtonPressed_; -}; - - -/** - * Sets or clears the "mouse button pressed" flag. - * @param {boolean} pressed Whether the mouse button is presed. - */ -goog.ui.Container.prototype.setMouseButtonPressed = function(pressed) { - this.mouseButtonPressed_ = pressed; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/container_perf.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/container_perf.html.svn-base deleted file mode 100644 index 40486af..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/container_perf.html.svn-base +++ /dev/null @@ -1,55 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2009 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Performance Tests - goog.ui.Container</title> - <link rel="stylesheet" type="text/css" href="../testing/performancetable.css"/> - <script src="../base.js"></script> - <script> - goog.require('goog.testing.PerformanceTable'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Container'); - goog.require('goog.ui.Control'); - </script> -</head> -<body> - <h1>goog.ui.Container Performance Tests</h1> - <p> - <strong>User-agent:</strong> - <script>document.write(navigator.userAgent);</script> - </p> - <div id="perfTable"></div> - <hr> - - <script> - var table = new goog.testing.PerformanceTable( - goog.dom.getElement('perfTable')); - - // Number of controls to add to the container per test run. - var SAMPLES_PER_RUN = 500; - - function testContainerAddChild() { - var description = 'Add ' + SAMPLES_PER_RUN + - ' child controls to the container with immediate rendering'; - table.run(function() { - var container = new goog.ui.Container(); - for (var i = 0; i < SAMPLES_PER_RUN; i++) { - container.addChild(new goog.ui.Control(), true); - } - container.render(); - assertEquals('container child count', SAMPLES_PER_RUN, - container.getChildCount()); - container.dispose(); - }, description); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/container_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/container_test.html.svn-base deleted file mode 100644 index 9adfb3c..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/container_test.html.svn-base +++ /dev/null @@ -1,451 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.Container</title> - <script src="../base.js"></script> - <script> - goog.require('goog.Disposable'); - goog.require('goog.dom'); - goog.require('goog.dom.classes'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Container'); - goog.require('goog.ui.Container.EventType'); - goog.require('goog.ui.Control'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var sandbox = goog.dom.getElement('sandbox'); - var containerElement; - var container; - var keyContainer; - var listContainer; - - function setUp() { - container = new goog.ui.Container(); - keyContainer = null; - listContainer = null; - - sandbox.innerHTML = - '<div id="containerElement" class="goog-container">\n' + - ' <div class="goog-control">Hello</div>\n' + - ' <div class="goog-control">World</div>\n' + - '</div>'; - containerElement = goog.dom.getElement('containerElement'); - } - - function tearDown() { - goog.dom.removeChildren(sandbox); - container.dispose(); - goog.events.removeAll(); - goog.dispose(keyContainer); - goog.dispose(listContainer); - } - - function testDecorateHidden() { - containerElement.style.display = 'none'; - - assertTrue('Container must be visible', container.isVisible()); - container.decorate(containerElement); - assertFalse('Container must be hidden', container.isVisible()); - container.forEachChild(function(control) { - assertTrue('Child control ' + control.getId() + ' must report being ' + - 'visible, even if in a hidden container', control.isVisible()); - }); - } - - function testDecorateDisabled() { - goog.dom.classes.add(containerElement, 'goog-container-disabled'); - - assertTrue('Container must be enabled', container.isEnabled()); - container.decorate(containerElement); - assertFalse('Container must be disabled', container.isEnabled()); - container.forEachChild(function(control) { - assertFalse('Child control ' + control.getId() + ' must be disabled, ' + - 'because the host container is disabled', control.isEnabled()); - }); - } - - function testDecorateFocusableContainer() { - container.decorate(containerElement); - assertTrue('Container must be focusable', container.isFocusable()); - container.forEachChild(function(control) { - assertFalse('Child control ' + control.getId() + ' must not be ' + - 'focusable', - control.isSupportedState(goog.ui.Component.State.FOCUSED)); - }); - } - - function testDecorateFocusableChildrenContainer() { - container.setFocusable(false); - container.setFocusableChildrenAllowed(true); - container.decorate(containerElement); - assertFalse('Container must not be focusable', container.isFocusable()); - container.forEachChild(function(control) { - assertTrue('Child control ' + control.getId() + ' must be ' + - 'focusable', - control.isSupportedState(goog.ui.Component.State.FOCUSED)); - }); - } - - function testHighlightOnEnter() { - // This interaction test ensures that containers enforce that children - // get highlighted on mouseover, and that one and only one child may - // be highlighted at a time. Although integration tests aren't the - // best, it's difficult to test these event-based interactions due to - // their disposition toward the "misunderstood contract" problem. - - container.decorate(containerElement); - assertFalse('Child 0 should initially not be highlighted', - container.getChildAt(0).isHighlighted()); - - goog.testing.events.fireMouseOverEvent( - container.getChildAt(0).getElement(), sandbox); - assertTrue('Child 0 should become highlighted after a mouse over', - container.getChildAt(0).isHighlighted()); - - goog.testing.events.fireMouseOverEvent( - container.getChildAt(1).getElement(), - container.getChildAt(0).getElement()); - assertFalse('Child 0 should lose highlight when child 1 is moused ' + - 'over, even if no mouseout occurs.', - container.getChildAt(0).isHighlighted()); - assertTrue('Child 1 should now be highlighted.', - container.getChildAt(1).isHighlighted()); - } - - function testHighlightOnEnterPreventable() { - container.decorate(containerElement); - goog.events.listen(container, goog.ui.Component.EventType.ENTER, - function(event) { - event.preventDefault(); - }); - goog.testing.events.fireMouseOverEvent( - container.getChildAt(0).getElement(), sandbox); - assertFalse('Child 0 should not be highlighted if preventDefault called', - container.getChildAt(0).isHighlighted()); - } - - function testHighlightDisabled() { - // Another interaction test. Already tested in control_test. - container.decorate(containerElement); - container.getChildAt(0).setEnabled(false); - goog.testing.events.fireMouseOverEvent( - container.getChildAt(0).getElement(), sandbox); - assertFalse('Disabled children should not be highlighted', - container.getChildAt(0).isHighlighted()); - } - - function testGetOwnerControl() { - container.decorate(containerElement); - - assertEquals('Must return appropriate control given an element in the ' + - 'control.', - container.getChildAt(1), - container.getOwnerControl(container.getChildAt(1).getElement())); - - assertNull('Must return null for element not associated with control.', - container.getOwnerControl(document.body)); - assertNull('Must return null if given null node', - container.getOwnerControl(null)); - } - - function testShowEvent() { - container.decorate(containerElement); - container.setVisible(false); - var eventFired = false; - goog.events.listen(container, goog.ui.Component.EventType.SHOW, - function() { - assertFalse('Container must not be visible when SHOW event is ' + - 'fired', - container.isVisible()); - eventFired = true; - }); - container.setVisible(true); - assertTrue('SHOW event expected', eventFired); - } - - function testAfterShowEvent() { - container.decorate(containerElement); - container.setVisible(false); - var eventFired = false; - goog.events.listen(container, goog.ui.Container.EventType.AFTER_SHOW, - function() { - assertTrue('Container must be visible when AFTER_SHOW event is ' + - 'fired', - container.isVisible()); - eventFired = true; - }); - container.setVisible(true); - assertTrue('AFTER_SHOW event expected', eventFired); - } - - function testHideEvents() { - var events = []; - container.decorate(containerElement); - container.setVisible(true); - var eventFired = false; - goog.events.listen(container, goog.ui.Component.EventType.HIDE, - function(e) { - assertTrue( - 'Container must be visible when HIDE event is fired', - container.isVisible()); - events.push(e.type); - }); - goog.events.listen(container, goog.ui.Container.EventType.AFTER_HIDE, - function(e) { - assertFalse( - 'Container must not be visible when AFTER_HIDE event is fired', - container.isVisible()); - events.push(e.type); - }); - container.setVisible(false); - assertArrayEquals('HIDE event followed by AFTER_HIDE expected', [ - goog.ui.Component.EventType.HIDE, - goog.ui.Container.EventType.AFTER_HIDE - ], events); - } - - /** - * Test container to which the elements have to be added with - * {@code container.addChild(element, false)} - * @constructor - * @extends {goog.ui.Container} - */ - function ListContainer() { - goog.ui.Container.call(this); - } - goog.inherits(ListContainer, goog.ui.Container); - - /** @override */ - ListContainer.prototype.createDom = function() { - ListContainer.superClass_.createDom.call(this); - var ul = this.getDomHelper().createDom('ul'); - this.forEachChild(function(child) { - child.createDom(); - var childEl = child.getElement(); - ul.appendChild(this.getDomHelper().createDom('li', {}, childEl)); - }, this); - this.getContentElement().appendChild(ul); - }; - - function testGetOwnerControlWithNoRenderingInAddChild() { - listContainer = new ListContainer(); - var control = new goog.ui.Control('item'); - listContainer.addChild(control); - listContainer.render(); - var ownerControl = listContainer.getOwnerControl(control.getElement()); - - assertEquals('Control was added with addChild(control, false)', - control, ownerControl); - } - - /** - * Test container for tracking key events being handled. - * @constructor - * @extends {goog.ui.Container} - */ - function KeyHandlingContainer() { - goog.ui.Container.call(this); - this.keyEventsHandled = 0; - } - goog.inherits(KeyHandlingContainer, goog.ui.Container); - - /** @override */ - KeyHandlingContainer.prototype.handleKeyEventInternal = function() { - this.keyEventsHandled++; - return false; - }; - - function testHandleKeyEvent_onlyHandlesWhenVisible() { - keyContainer = new KeyHandlingContainer(); - keyContainer.decorate(containerElement); - - keyContainer.setVisible(false); - keyContainer.handleKeyEvent(new goog.events.Event()); - assertEquals('No key events should be handled', - 0, keyContainer.keyEventsHandled); - - keyContainer.setVisible(true); - keyContainer.handleKeyEvent(new goog.events.Event()); - assertEquals('One key event should be handled', - 1, keyContainer.keyEventsHandled); - } - - function testHandleKeyEvent_onlyHandlesWhenEnabled() { - keyContainer = new KeyHandlingContainer(); - keyContainer.decorate(containerElement); - keyContainer.setVisible(true); - - keyContainer.setEnabled(false); - keyContainer.handleKeyEvent(new goog.events.Event()); - assertEquals('No key events should be handled', - 0, keyContainer.keyEventsHandled); - - keyContainer.setEnabled(true); - keyContainer.handleKeyEvent(new goog.events.Event()); - assertEquals('One key event should be handled', - 1, keyContainer.keyEventsHandled); - } - - function testHandleKeyEvent_childlessContainersIgnoreKeyEvents() { - keyContainer = new KeyHandlingContainer(); - keyContainer.render(); - keyContainer.setVisible(true); - - keyContainer.handleKeyEvent(new goog.events.Event()); - assertEquals('No key events should be handled', - 0, keyContainer.keyEventsHandled); - - keyContainer.addChild(new goog.ui.Control()); - keyContainer.handleKeyEvent(new goog.events.Event()); - assertEquals('One key event should be handled', - 1, keyContainer.keyEventsHandled); - } - - function testHandleKeyEvent_alwaysHandlesWithKeyEventTarget() { - keyContainer = new KeyHandlingContainer(); - keyContainer.render(); - keyContainer.setKeyEventTarget(goog.dom.createDom('div')); - keyContainer.setVisible(true); - - keyContainer.handleKeyEvent(new goog.events.Event()); - assertEquals('One key events should be handled', - 1, keyContainer.keyEventsHandled); - } - - function testHandleKeyEventInternal_onlyHandlesUnmodified() { - container.setKeyEventTarget(sandbox); - var event = new goog.events.KeyEvent( - goog.events.KeyCodes.ESC, 0, false, null); - - var propertyNames = [ - 'shiftKey', - 'altKey', - 'ctrlKey', - 'metaKey' - ]; - - // Verify that the event is not handled whenever a modifier key is true. - for (var i = 0, propertyName; propertyName = propertyNames[i]; i++) { - assertTrue('Event should be handled when modifer key is not pressed.', - container.handleKeyEventInternal(event)); - event[propertyName] = true; - assertFalse('Event should not be handled when modifer key is pressed.', - container.handleKeyEventInternal(event)); - event[propertyName] = false; - } - } - - function testOpenFollowsHighlight() { - container.decorate(containerElement); - container.setOpenFollowsHighlight(true); - assertTrue('isOpenFollowsHighlight should return true', - container.isOpenFollowsHighlight()); - - // Make the children openable. - container.forEachChild(function(child) { - child.setSupportedState(goog.ui.Component.State.OPENED, true); - }); - // Open child 1 initially. - container.getChildAt(1).setOpen(true); - - assertFalse('Child 0 should initially not be highlighted', - container.getChildAt(0).isHighlighted()); - goog.testing.events.fireMouseOverEvent( - container.getChildAt(0).getElement(), sandbox); - assertTrue('Child 0 should become highlighted after a mouse over', - container.getChildAt(0).isHighlighted()); - assertTrue('Child 0 should become open after higlighted', - container.getChildAt(0).isOpen()); - assertFalse('Child 1 should become closed once 0 is open', - container.getChildAt(1).isOpen()); - assertEquals('OpenItem should be child 0', - container.getChildAt(0), container.getOpenItem()); - } - - function testOpenNotFollowsHighlight() { - container.decorate(containerElement); - container.setOpenFollowsHighlight(false); - assertFalse('isOpenFollowsHighlight should return false', - container.isOpenFollowsHighlight()); - - // Make the children openable. - container.forEachChild(function(child) { - child.setSupportedState(goog.ui.Component.State.OPENED, true); - }); - // Open child 1 initially. - container.getChildAt(1).setOpen(true); - - assertFalse('Child 0 should initially not be highlighted', - container.getChildAt(0).isHighlighted()); - goog.testing.events.fireMouseOverEvent( - container.getChildAt(0).getElement(), sandbox); - assertTrue('Child 0 should become highlighted after a mouse over', - container.getChildAt(0).isHighlighted()); - assertFalse('Child 0 should remain closed after higlighted', - container.getChildAt(0).isOpen()); - assertTrue('Child 1 should remain open', - container.getChildAt(1).isOpen()); - assertEquals('OpenItem should be child 1', - container.getChildAt(1), container.getOpenItem()); - } - - function testRemoveChild() { - goog.dom.removeChildren(containerElement); - container.decorate(containerElement); - - var a = new goog.ui.Control('A'); - var b = new goog.ui.Control('B'); - var c = new goog.ui.Control('C'); - - a.setId('a'); - b.setId('b'); - c.setId('c'); - - container.addChild(a, true); - container.addChild(b, true); - container.addChild(c, true); - - container.setHighlightedIndex(2); - - assertEquals('Parent must remove and return child by ID', b, - container.removeChild('b')); - assertNull('Parent must no longer contain this child', - container.getChild('b')); - assertEquals('Highlighted index must be decreased', 1, - container.getHighlightedIndex()); - assertTrue('The removed control must handle its own mouse events', - b.isHandleMouseEvents()); - - assertEquals('Parent must remove and return child', c, - container.removeChild(c)); - assertNull('Parent must no longer contain this child', - container.getChild('c')); - assertFalse('This child must no longer be highlighted', - c.isHighlighted()); - assertTrue('The removed control must handle its own mouse events', - c.isHandleMouseEvents()); - - assertEquals('Parent must remove and return child by index', a, - container.removeChildAt(0)); - assertNull('Parent must no longer contain this child', - container.getChild('a')); - assertTrue('The removed control must handle its own mouse events', - a.isHandleMouseEvents()); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/containerrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/containerrenderer.js.svn-base deleted file mode 100644 index dfd86a5..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/containerrenderer.js.svn-base +++ /dev/null @@ -1,372 +0,0 @@ -// 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 container renderers. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.ContainerRenderer'); - -goog.require('goog.array'); -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.classes'); -goog.require('goog.string'); -goog.require('goog.style'); -goog.require('goog.ui.Separator'); -goog.require('goog.ui.registry'); -goog.require('goog.userAgent'); - - - -/** - * Default renderer for {@link goog.ui.Container}. Can be used as-is, but - * subclasses of Container will probably want to use renderers specifically - * tailored for them by extending this class. - * @constructor - */ -goog.ui.ContainerRenderer = function() { -}; -goog.addSingletonGetter(goog.ui.ContainerRenderer); - - -/** - * 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 menu is: - * - * <pre> - * var myCustomRenderer = goog.ui.ContainerRenderer.getCustomRenderer( - * goog.ui.MenuRenderer, 'my-special-menu'); - * var newMenu = new goog.ui.Menu(opt_domHelper, myCustomRenderer); - * </pre> - * - * Your styles for the menu can now be: - * <pre> - * .my-special-menu { } - * </pre> - * - * <em>instead</em> of - * <pre> - * .CSS_MY_SPECIAL_MENU .goog-menu { } - * </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 want to create. - * @param {string} cssClassName The name of the CSS class for this renderer. - * @return {goog.ui.ContainerRenderer} An instance of the desired renderer with - * its getCssClass() method overridden to return the supplied custom CSS - * class name. - */ -goog.ui.ContainerRenderer.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 containers rendered - * by this renderer. - * @type {string} - */ -goog.ui.ContainerRenderer.CSS_CLASS = goog.getCssName('goog-container'); - - -/** - * Returns the ARIA role to be applied to the container. - * See http://wiki/Main/ARIA for more info. - * @return {undefined|string} ARIA role. - */ -goog.ui.ContainerRenderer.prototype.getAriaRole = function() { - // By default, the ARIA role is unspecified. - return undefined; -}; - - -/** - * Enables or disables the tab index of the element. Only elements with a - * valid tab index can receive focus. - * @param {Element} element Element whose tab index is to be changed. - * @param {boolean} enable Whether to add or remove the element's tab index. - */ -goog.ui.ContainerRenderer.prototype.enableTabIndex = function(element, enable) { - if (element) { - element.tabIndex = enable ? 0 : -1; - } -}; - - -/** - * Creates and returns the container's root element. The default - * simply creates a DIV and applies the renderer's own CSS class name to it. - * To be overridden in subclasses. - * @param {goog.ui.Container} container Container to render. - * @return {Element} Root element for the container. - */ -goog.ui.ContainerRenderer.prototype.createDom = function(container) { - return container.getDomHelper().createDom('div', - this.getClassNames(container).join(' ')); -}; - - -/** - * Returns the DOM element into which child components are to be rendered, - * or null if the container hasn't been rendered yet. - * @param {Element} element Root element of the container whose content element - * is to be returned. - * @return {Element} Element to contain child elements (null if none). - */ -goog.ui.ContainerRenderer.prototype.getContentElement = function(element) { - return element; -}; - - -/** - * Default implementation of {@code canDecorate}; returns true if the element - * is a DIV, false otherwise. - * @param {Element} element Element to decorate. - * @return {boolean} Whether the renderer can decorate the element. - */ -goog.ui.ContainerRenderer.prototype.canDecorate = function(element) { - return element.tagName == 'DIV'; -}; - - -/** - * Default implementation of {@code decorate} for {@link goog.ui.Container}s. - * Decorates the element with the container, and attempts to decorate its child - * elements. Returns the decorated element. - * @param {goog.ui.Container} container Container to decorate the element. - * @param {Element} element Element to decorate. - * @return {Element} Decorated element. - */ -goog.ui.ContainerRenderer.prototype.decorate = function(container, element) { - // Set the container's ID to the decorated element's DOM ID, if any. - if (element.id) { - container.setId(element.id); - } - - // Configure the container's state based on the CSS class names it has. - var baseClass = this.getCssClass(); - var hasBaseClass = false; - var classNames = goog.dom.classes.get(element); - if (classNames) { - goog.array.forEach(classNames, function(className) { - if (className == baseClass) { - hasBaseClass = true; - } else if (className) { - this.setStateFromClassName(container, className, baseClass); - } - }, this); - } - - if (!hasBaseClass) { - // Make sure the container's root element has the renderer's own CSS class. - goog.dom.classes.add(element, baseClass); - } - - // Decorate the element's children, if applicable. This should happen after - // the container's own state has been initialized, since how children are - // decorated may depend on the state of the container. - this.decorateChildren(container, this.getContentElement(element)); - - return element; -}; - - -/** - * Sets the container's state based on the given CSS class name, encountered - * during decoration. CSS class names that don't represent container states - * are ignored. Considered protected; subclasses should override this method - * to support more states and CSS class names. - * @param {goog.ui.Container} container Container to update. - * @param {string} className CSS class name. - * @param {string} baseClass Base class name used as the root of state-specific - * class names (typically the renderer's own class name). - * @protected - */ -goog.ui.ContainerRenderer.prototype.setStateFromClassName = function(container, - className, baseClass) { - if (className == goog.getCssName(baseClass, 'disabled')) { - container.setEnabled(false); - } else if (className == goog.getCssName(baseClass, 'horizontal')) { - container.setOrientation(goog.ui.Container.Orientation.HORIZONTAL); - } else if (className == goog.getCssName(baseClass, 'vertical')) { - container.setOrientation(goog.ui.Container.Orientation.VERTICAL); - } -}; - - -/** - * Takes a container and an element that may contain child elements, decorates - * the child elements, and adds the corresponding components to the container - * as child components. Any non-element child nodes (e.g. empty text nodes - * introduced by line breaks in the HTML source) are removed from the element. - * @param {goog.ui.Container} container Container whose children are to be - * discovered. - * @param {Element} element Element whose children are to be decorated. - * @param {Element=} opt_firstChild the first child to be decorated. - * @suppress {visibility} setElementInternal - */ -goog.ui.ContainerRenderer.prototype.decorateChildren = function(container, - element, opt_firstChild) { - if (element) { - var node = opt_firstChild || element.firstChild, next; - // Tag soup HTML may result in a DOM where siblings have different parents. - while (node && node.parentNode == element) { - // Get the next sibling here, since the node may be replaced or removed. - next = node.nextSibling; - if (node.nodeType == goog.dom.NodeType.ELEMENT) { - // Decorate element node. - var child = this.getDecoratorForChild(/** @type {Element} */(node)); - if (child) { - // addChild() may need to look at the element. - child.setElementInternal(/** @type {Element} */(node)); - // If the container is disabled, mark the child disabled too. See - // bug 1263729. Note that this must precede the call to addChild(). - if (!container.isEnabled()) { - child.setEnabled(false); - } - container.addChild(child); - child.decorate(/** @type {Element} */(node)); - } - } else if (!node.nodeValue || goog.string.trim(node.nodeValue) == '') { - // Remove empty text node, otherwise madness ensues (e.g. controls that - // use goog-inline-block will flicker and shift on hover on Gecko). - element.removeChild(node); - } - node = next; - } - } -}; - - -/** - * Inspects the element, and creates an instance of {@link goog.ui.Control} or - * an appropriate subclass best suited to decorate it. Returns the control (or - * null if no suitable class was found). This default implementation uses the - * element's CSS class to find the appropriate control class to instantiate. - * May be overridden in subclasses. - * @param {Element} element Element to decorate. - * @return {goog.ui.Control?} A new control suitable to decorate the element - * (null if none). - */ -goog.ui.ContainerRenderer.prototype.getDecoratorForChild = function(element) { - return (/** @type {goog.ui.Control} */ - goog.ui.registry.getDecorator(element)); -}; - - -/** - * Initializes the container's DOM when the container enters the document. - * Called from {@link goog.ui.Container#enterDocument}. - * @param {goog.ui.Container} container Container whose DOM is to be initialized - * as it enters the document. - */ -goog.ui.ContainerRenderer.prototype.initializeDom = function(container) { - var elem = container.getElement(); - - // Make sure the container's element isn't selectable. On Gecko, recursively - // marking each child element unselectable is expensive and unnecessary, so - // only mark the root element unselectable. - goog.style.setUnselectable(elem, true, goog.userAgent.GECKO); - - // IE doesn't support outline:none, so we have to use the hideFocus property. - if (goog.userAgent.IE) { - elem.hideFocus = true; - } - - // Set the ARIA role. - var ariaRole = this.getAriaRole(); - if (ariaRole) { - goog.dom.a11y.setRole(elem, ariaRole); - } -}; - - -/** - * Returns the element within the container's DOM that should receive keyboard - * focus (null if none). The default implementation returns the container's - * root element. - * @param {goog.ui.Container} container Container whose key event target is - * to be returned. - * @return {Element} Key event target (null if none). - */ -goog.ui.ContainerRenderer.prototype.getKeyEventTarget = function(container) { - return container.getElement(); -}; - - -/** - * Returns the CSS class to be applied to the root element of containers - * rendered using this renderer. - * @return {string} Renderer-specific CSS class. - */ -goog.ui.ContainerRenderer.prototype.getCssClass = function() { - return goog.ui.ContainerRenderer.CSS_CLASS; -}; - - -/** - * Returns all CSS class names applicable to the given container, based on its - * state. The array of class names returned includes the renderer's own CSS - * class, followed by a CSS class indicating the container's orientation, - * followed by any state-specific CSS classes. - * @param {goog.ui.Container} container Container whose CSS classes are to be - * returned. - * @return {Array.<string>} Array of CSS class names applicable to the - * container. - */ -goog.ui.ContainerRenderer.prototype.getClassNames = function(container) { - var baseClass = this.getCssClass(); - var isHorizontal = - container.getOrientation() == goog.ui.Container.Orientation.HORIZONTAL; - var classNames = [ - baseClass, - (isHorizontal ? - goog.getCssName(baseClass, 'horizontal') : - goog.getCssName(baseClass, 'vertical')) - ]; - if (!container.isEnabled()) { - classNames.push(goog.getCssName(baseClass, 'disabled')); - } - return classNames; -}; - - -/** - * Returns the default orientation of containers rendered or decorated by this - * renderer. The base class implementation returns {@code VERTICAL}. - * @return {goog.ui.Container.Orientation} Default orientation for containers - * created or decorated by this renderer. - */ -goog.ui.ContainerRenderer.prototype.getDefaultOrientation = function() { - return goog.ui.Container.Orientation.VERTICAL; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/containerrenderer_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/containerrenderer_test.html.svn-base deleted file mode 100644 index 6aa1ab2..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/containerrenderer_test.html.svn-base +++ /dev/null @@ -1,228 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.ContainerRenderer</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.testing.ExpectedFailures'); - goog.require('goog.testing.PropertyReplacer'); - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.ui.rendererasserts'); - goog.require('goog.ui.Container'); - goog.require('goog.ui.ContainerRenderer'); - goog.require('goog.ui.Control'); - goog.require('goog.ui.ControlRenderer'); - </script> -</head> -<body> - <div id="sandbox"></div> - - <script> - var renderer; - var expectedFailures = new goog.testing.ExpectedFailures(); - var stubs = new goog.testing.PropertyReplacer(); - - function setUp() { - var sandbox = goog.dom.getElement('sandbox'); - - sandbox.appendChild(goog.dom.createDom('span', { - id: 'noTabIndex' - }, 'Test')); - sandbox.appendChild(goog.dom.createDom('div', { - id: 'container', - 'class': 'goog-container-horizontal' - }, goog.dom.createDom('div', { - id: 'control', - 'class': 'goog-control' - }, 'Hello, world!'))); - - renderer = goog.ui.ContainerRenderer.getInstance(); - } - - function tearDown() { - goog.dom.getElement('sandbox').innerHTML = ''; - stubs.reset(); - expectedFailures.handleTearDown(); - } - - function testGetInstance() { - assertTrue('getInstance() must return a ContainerRenderer', - renderer instanceof goog.ui.ContainerRenderer); - assertEquals('getInstance() must return the same object each time', - renderer, goog.ui.ContainerRenderer.getInstance()); - } - - function testGetCustomRenderer() { - var cssClass = 'special-css-class'; - var containerRenderer = goog.ui.ContainerRenderer.getCustomRenderer( - goog.ui.ContainerRenderer, cssClass); - assertEquals( - 'Renderer should have returned the custom CSS class.', - cssClass, - containerRenderer.getCssClass()); - } - - function testGetAriaRole() { - assertUndefined('ARIA role must be undefined', renderer.getAriaRole()); - } - - function testEnableTabIndex() { - var container = goog.dom.getElement('container'); - assertFalse('Container must not have any tab index', - goog.dom.isFocusableTabIndex(container)); - - // WebKit on Mac doesn't support tabIndex for arbitrary DOM elements - // until version 527 or later. - expectedFailures.expectFailureFor(goog.userAgent.WEBKIT && - goog.userAgent.MAC && !goog.userAgent.isVersion('527')); - try { - renderer.enableTabIndex(container, true); - assertTrue('Container must have a tab index', - goog.dom.isFocusableTabIndex(container)); - assertEquals('Container\'s tab index must be 0', 0, container.tabIndex); - - renderer.enableTabIndex(container, false); - assertFalse('Container must not have a tab index', - goog.dom.isFocusableTabIndex(container)); - assertEquals('Container\'s tab index must be -1', -1, - container.tabIndex); - } catch (e) { - expectedFailures.handleException(e); - } - } - - function testCreateDom() { - var horizontal = new goog.ui.Container( - goog.ui.Container.Orientation.HORIZONTAL); - var element1 = renderer.createDom(horizontal); - assertEquals('Element must be a DIV', 'DIV', element1.tagName); - assertEquals('Element must have the expected class name', - 'goog-container goog-container-horizontal', - element1.className); - - var vertical = new goog.ui.Container( - goog.ui.Container.Orientation.VERTICAL); - var element2 = renderer.createDom(vertical); - assertEquals('Element must be a DIV', 'DIV', element2.tagName); - assertEquals('Element must have the expected class name', - 'goog-container goog-container-vertical', - element2.className); - } - - function testGetContentElement() { - assertNull('getContentElement() must return null if element is null', - renderer.getContentElement(null)); - var element = goog.dom.getElement('container'); - assertEquals('getContentElement() must return its argument', - element, renderer.getContentElement(element)); - } - - function testCanDecorate() { - assertFalse('canDecorate() must return false for a SPAN', - renderer.canDecorate(goog.dom.getElement('noTabIndex'))); - assertTrue('canDecorate() must return true for a DIV', - renderer.canDecorate(goog.dom.getElement('container'))); - } - - function testDecorate() { - var container = new goog.ui.Container(); - var element = goog.dom.getElement('container'); - - assertFalse('Container must not be in the document', - container.isInDocument()); - container.decorate(element); - assertTrue('Container must be in the document', - container.isInDocument()); - - assertEquals('Container\'s ID must match the decorated element\'s ID', - element.id, container.getId()); - assertEquals('Element must have the expected class name', - 'goog-container-horizontal goog-container', element.className); - assertEquals('Container must have one child', 1, - container.getChildCount()); - assertEquals('Child component\'s ID must be as expected', 'control', - container.getChildAt(0).getId()); - - assertThrows('Redecorating must throw error', function() { - container.decorate(element); - }); - } - - function testDecorateWithCustomContainerElement() { - var element = goog.dom.getElement('container'); - var alternateContainerElement = goog.dom.createElement('div'); - element.appendChild(alternateContainerElement); - - var container = new goog.ui.Container(); - stubs.set(renderer, 'getContentElement', function() { - return alternateContainerElement; - }); - - assertFalse('Container must not be in the document', - container.isInDocument()); - container.decorate(element); - assertTrue('Container must be in the document', - container.isInDocument()); - - assertEquals('Container\'s ID must match the decorated element\'s ID', - element.id, container.getId()); - assertEquals('Element must have the expected class name', - 'goog-container-horizontal goog-container', element.className); - assertEquals('Container must have 0 children', 0, - container.getChildCount()); - - assertThrows('Redecorating must throw error', function() { - container.decorate(element); - }); - } - - function testSetStateFromClassName() { - var container = new goog.ui.Container(); - - assertEquals('Container must be vertical', - goog.ui.Container.Orientation.VERTICAL, container.getOrientation()); - renderer.setStateFromClassName(container, 'goog-container-horizontal', - 'goog-container'); - assertEquals('Container must be horizontal', - goog.ui.Container.Orientation.HORIZONTAL, container.getOrientation()); - renderer.setStateFromClassName(container, 'goog-container-vertical', - 'goog-container'); - assertEquals('Container must be vertical', - goog.ui.Container.Orientation.VERTICAL, container.getOrientation()); - - assertTrue('Container must be enabled', container.isEnabled()); - renderer.setStateFromClassName(container, 'goog-container-disabled', - 'goog-container'); - assertFalse('Container must be disabled', container.isEnabled()); - } - - function testInitializeDom() { - var container = new goog.ui.Container(); - var element = goog.dom.getElement('container'); - container.decorate(element); - - assertTrue('Container\'s root element must be unselectable', - goog.style.isUnselectable(container.getElement())); - - assertEquals('On IE, container\'s root element must have hideFocus=true', - goog.userAgent.IE, !!container.getElement().hideFocus); - } - - function testDoesntCallGetCssClassInConstructor() { - goog.testing.ui.rendererasserts. - assertNoGetCssClassCallsInConstructor(goog.ui.ContainerRenderer); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/containerscroller.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/containerscroller.js.svn-base deleted file mode 100644 index 856a341..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/containerscroller.js.svn-base +++ /dev/null @@ -1,222 +0,0 @@ -// 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; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/containerscroller_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/containerscroller_test.html.svn-base deleted file mode 100644 index f36d441..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/containerscroller_test.html.svn-base +++ /dev/null @@ -1,214 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: gboyer@google.com (Garrett Boyer) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.ContainerScroller</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.testing.MockClock'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Container'); - goog.require('goog.ui.ContainerScroller'); - goog.require('goog.ui.Control'); -</script> -<style type="text/css"> -.goog-container { - height: 100px; - overflow-y: auto; - overflow-x: hidden; - position: relative; - /* Give a border and margin to ensure ContainerScroller is tolerant to - * them. It is, however, not tolerant to padding. */ - border: 11px solid #666; - margin: 7px 13px 17px 19px; -} -.goog-control { - font-size: 10px; - height: 14px; - padding: 3px; -} -</style> -</head> -<body> -<div id="sandbox" class="goog-container"> - <div class="goog-control" id="control-0">0</div> - <div class="goog-control" id="control-1">1</div> - <div class="goog-control" id="control-2">2</div> - <div class="goog-control" id="control-3">3</div> - <div class="goog-control" id="control-4">4</div> - <div class="goog-control" id="control-5">5</div> - <div class="goog-control" id="control-6">6</div> - <div class="goog-control" id="control-7">7</div> - <div class="goog-control" id="control-8">8</div> - <div class="goog-control" id="control-9">9</div> -</div> -<script> - -var sandbox = goog.dom.getElement('sandbox'); -var sandboxHtml = sandbox.innerHTML; -var container; -var mockClock; -var scroller; - -function setUp() { - container = new goog.ui.Container(); - container.decorate(sandbox); - container.getElement().scrollTop = 0; - mockClock = new goog.testing.MockClock(true); - scroller = null; -} - -function tearDown() { - container.dispose(); - if (scroller) { - scroller.dispose(); - } - // Tick one second to clear all the extra registered events. - mockClock.tick(1000); - mockClock.uninstall(); - sandbox.innerHTML = sandboxHtml; -} - -function testHighlightFirstStaysAtTop() { - scroller = new goog.ui.ContainerScroller(container); - container.getChildAt(0).setHighlighted(true); - assertEquals(0, container.getElement().scrollTop); -} - -function testHighlightSecondStaysAtTop() { - scroller = new goog.ui.ContainerScroller(container); - container.getChildAt(1).setHighlighted(true); - assertEquals(0, container.getElement().scrollTop); -} - -function testHighlightSecondLastScrollsNearTheBottom() { - scroller = new goog.ui.ContainerScroller(container); - container.getChildAt(8).setHighlighted(true); - assertEquals('Since scrolling is lazy, when highlighting the second' + - ' last, the item should be the last visible one.', - 80, container.getElement().scrollTop); -} - -function testHighlightLastScrollsToBottom() { - scroller = new goog.ui.ContainerScroller(container); - container.getChildAt(9).setHighlighted(true); - assertEquals(100, container.getElement().scrollTop); -} - -function testScrollRestoreIfStillVisible() { - scroller = new goog.ui.ContainerScroller(container); - container.getChildAt(9).setHighlighted(true); - var scrollTop = container.getElement().scrollTop; - container.setVisible(false); - container.setVisible(true); - assertEquals('Scroll position should be the same after restore, if it ' + - 'still makes highlighted item visible', - scrollTop, container.getElement().scrollTop); -} - -function testNoScrollRestoreIfNotVisible() { - scroller = new goog.ui.ContainerScroller(container); - container.getElement().scrollTop = 100; - container.setVisible(false); - container.getChildAt(0).setHighlighted(true); - container.setVisible(true); - assertNotEquals('Scroll position should not be the same after restore, if ' + - 'the scroll position when the menu was hidden no longer ' + - 'makes the highlighted item visible when the container is ' + - 'shown again', - 100, container.getElement().scrollTop); -} - -function testCenterOnHighlightedOnFirstOpen() { - container.setVisible(false); - scroller = new goog.ui.ContainerScroller(container); - container.getChildAt(4).setHighlighted(true); - container.setVisible(true); - // #2 should be at the top when 4 is centered, meaning a scroll top - // of 40 pixels. - assertEquals( - 'On the very first display of the scroller, the item should be ' + - 'centered, rather than just assured in view.', - 40, container.getElement().scrollTop); -} - -function testHighlightsAreIgnoredInResponseToScrolling() { - scroller = new goog.ui.ContainerScroller(container); - container.getChildAt(9).setHighlighted(true); - goog.testing.events.fireMouseOverEvent( - goog.dom.getElement('control-5'), - goog.dom.getElement('control-9')); - assertEquals('Mouseovers due to scrolls should be ignored', - 9, container.getHighlightedIndex()); -} - -function testHighlightsAreNotIgnoredWhenNotScrolling() { - scroller = new goog.ui.ContainerScroller(container); - container.getChildAt(5).setHighlighted(true); - mockClock.tick(1000); - goog.testing.events.fireMouseOutEvent( - goog.dom.getElement('control-5'), - goog.dom.getElement('control-6')); - goog.testing.events.fireMouseOverEvent( - goog.dom.getElement('control-6'), - goog.dom.getElement('control-5')); - assertEquals('Mousovers not due to scrolls should not be ignored', - 6, container.getHighlightedIndex()); -} - -function testFastSynchronousHighlightsNotIgnored() { - scroller = new goog.ui.ContainerScroller(container); - // Whereas subsequent highlights from mouseovers due to a scroll, should - // be ignored, they should not ignored if they are made synchronusly - // from the code and not from a mouseover. Imagine how bad it would be - // if you could only set the highligted index a certain number of - // times in the same execution context. - container.getChildAt(9).setHighlighted(true); - container.getChildAt(1).setHighlighted(true); - assertEquals('Synchronous highlights should NOT be ignored.', - 1, container.getHighlightedIndex()); - container.getChildAt(8).setHighlighted(true); - assertEquals('Synchronous highlights should NOT be ignored.', - 8, container.getHighlightedIndex()); -} - -function testInitialItemIsCentered() { - container.getChildAt(4).setHighlighted(true); - scroller = new goog.ui.ContainerScroller(container); - // #2 should be at the top when 4 is centered, meaning a scroll top - // of 40 pixels. - assertEquals( - 'On the very first attachment of the scroller, the item should be ' + - 'centered, rather than just assured in view.', - 40, container.getElement().scrollTop); -} - -function testInitialItemIsCenteredTopItem() { - container.getChildAt(0).setHighlighted(true); - scroller = new goog.ui.ContainerScroller(container); - assertEquals(0, container.getElement().scrollTop); -} - -function testHidingMenuItemsDoesntAffectContainerScroller() { - scroller = new goog.ui.ContainerScroller(container); - container.getElement = function() { - fail('getElement() must not be called when a control in the container is ' + - 'being hidden'); - }; - container.getChildAt(0).setVisible(false); -} - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/control.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/control.js.svn-base deleted file mode 100644 index 6652a8e..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/control.js.svn-base +++ /dev/null @@ -1,1371 +0,0 @@ -// 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 Base class for UI controls such as buttons, menus, menu items, - * toolbar buttons, etc. The implementation is based on a generalized version - * of {@link goog.ui.MenuItem}. - * TODO(attila): If the renderer framework works well, pull it into Component. - * - * @author attila@google.com (Attila Bodis) - * @see ../demos/control.html - * @see http://code.google.com/p/closure-library/wiki/IntroToControls - */ - -goog.provide('goog.ui.Control'); - -goog.require('goog.array'); -goog.require('goog.dom'); -goog.require('goog.events.BrowserEvent.MouseButton'); -goog.require('goog.events.Event'); -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.ui.Component'); -goog.require('goog.ui.Component.Error'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.Component.State'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.ControlRenderer'); -goog.require('goog.ui.decorate'); -goog.require('goog.ui.registry'); -goog.require('goog.userAgent'); - - - -/** - * Base class for UI controls. Extends {@link goog.ui.Component} by adding - * the following: - * <ul> - * <li>a {@link goog.events.KeyHandler}, to simplify keyboard handling, - * <li>a pluggable <em>renderer</em> framework, to simplify the creation of - * simple controls without the need to subclass this class, - * <li>the notion of component <em>content</em>, like a text caption or DOM - * structure displayed in the component (e.g. a button label), - * <li>getter and setter for component content, as well as a getter and - * setter specifically for caption text (for convenience), - * <li>support for hiding/showing the component, - <li>fine-grained control over supported states and state transition - events, and - * <li>default mouse and keyboard event handling. - * </ul> - * This class has sufficient built-in functionality for most simple UI controls. - * All controls dispatch SHOW, HIDE, ENTER, LEAVE, and ACTION events on show, - * hide, mouseover, mouseout, and user action, respectively. Additional states - * are also supported. See closure/demos/control.html - * for example usage. - * @param {goog.ui.ControlContent} content Text caption or DOM structure - * to display as the content of the component (if any). - * @param {goog.ui.ControlRenderer=} opt_renderer Renderer used to render or - * decorate the component; defaults to {@link goog.ui.ControlRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for - * document interaction. - * @constructor - * @extends {goog.ui.Component} - */ -goog.ui.Control = function(content, opt_renderer, opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - this.renderer_ = opt_renderer || - goog.ui.registry.getDefaultRenderer(this.constructor); - this.setContentInternal(content); -}; -goog.inherits(goog.ui.Control, goog.ui.Component); - - -// Renderer registry. -// TODO(attila): Refactor existing usages inside Google in a follow-up CL. - - -/** - * Maps a CSS class name to a function that returns a new instance of - * {@link goog.ui.Control} or a subclass thereof, suitable to decorate - * an element that has the specified CSS class. UI components that extend - * {@link goog.ui.Control} and want {@link goog.ui.Container}s to be able - * to discover and decorate elements using them should register a factory - * function via this API. - * @param {string} className CSS class name. - * @param {Function} decoratorFunction Function that takes no arguments and - * returns a new instance of a control to decorate an element with the - * given class. - * @deprecated Use {@link goog.ui.registry.setDecoratorByClassName} instead. - */ -goog.ui.Control.registerDecorator = goog.ui.registry.setDecoratorByClassName; - - -/** - * Takes an element and returns a new instance of {@link goog.ui.Control} - * or a subclass, suitable to decorate it (based on the element's CSS class). - * @param {Element} element Element to decorate. - * @return {goog.ui.Control?} New control instance to decorate the element - * (null if none). - * @deprecated Use {@link goog.ui.registry.getDecorator} instead. - */ -goog.ui.Control.getDecorator = - /** @type {function(Element): goog.ui.Control} */ ( - goog.ui.registry.getDecorator); - - -/** - * Takes an element, and decorates it with a {@link goog.ui.Control} instance - * if a suitable decorator is found. - * @param {Element} element Element to decorate. - * @return {goog.ui.Control?} New control instance that decorates the element - * (null if none). - * @deprecated Use {@link goog.ui.decorate} instead. - */ -goog.ui.Control.decorate = /** @type {function(Element): goog.ui.Control} */ ( - goog.ui.decorate); - - -/** - * Renderer associated with the component. - * @type {goog.ui.ControlRenderer|undefined} - * @private - */ -goog.ui.Control.prototype.renderer_; - - -/** - * Text caption or DOM structure displayed in the component. - * @type {goog.ui.ControlContent} - * @private - */ -goog.ui.Control.prototype.content_ = null; - - -/** - * Current component state; a bit mask of {@link goog.ui.Component.State}s. - * @type {number} - * @private - */ -goog.ui.Control.prototype.state_ = 0x00; - - -/** - * A bit mask of {@link goog.ui.Component.State}s this component supports. - * @type {number} - * @private - */ -goog.ui.Control.prototype.supportedStates_ = - goog.ui.Component.State.DISABLED | - goog.ui.Component.State.HOVER | - goog.ui.Component.State.ACTIVE | - goog.ui.Component.State.FOCUSED; - - -/** - * A bit mask of {@link goog.ui.Component.State}s for which this component - * provides default event handling. For example, a component that handles - * the HOVER state automatically will highlight itself on mouseover, whereas - * a component that doesn't handle HOVER automatically will only dispatch - * ENTER and LEAVE events but not call {@link setHighlighted} on itself. - * By default, components provide default event handling for all states. - * Controls hosted in containers (e.g. menu items in a menu, or buttons in a - * toolbar) will typically want to have their container manage their highlight - * state. Selectable controls managed by a selection model will also typically - * want their selection state to be managed by the model. - * @type {number} - * @private - */ -goog.ui.Control.prototype.autoStates_ = goog.ui.Component.State.ALL; - - -/** - * A bit mask of {@link goog.ui.Component.State}s for which this component - * dispatches state transition events. Because events are expensive, the - * default behavior is to not dispatch any state transition events at all. - * Use the {@link #setDispatchTransitionEvents} API to request transition - * events as needed. Subclasses may enable transition events by default. - * Controls hosted in containers or managed by a selection model will typically - * want to dispatch transition events. - * @type {number} - * @private - */ -goog.ui.Control.prototype.statesWithTransitionEvents_ = 0x00; - - -/** - * Component visibility. - * @type {boolean} - * @private - */ -goog.ui.Control.prototype.visible_ = true; - - -/** - * Keyboard event handler. - * @type {goog.events.KeyHandler} - * @private - */ -goog.ui.Control.prototype.keyHandler_; - - -/** - * Additional class name(s) to apply to the control's root element, if any. - * @type {Array.<string>?} - * @private - */ -goog.ui.Control.prototype.extraClassNames_ = null; - - -/** - * Whether the control should listen for and handle mouse events; defaults to - * true. - * @type {boolean} - * @private - */ -goog.ui.Control.prototype.handleMouseEvents_ = true; - - -/** - * Whether the control allows text selection within its DOM. Defaults to false. - * @type {boolean} - * @private - */ -goog.ui.Control.prototype.allowTextSelection_ = false; - - -/** - * The control's preferred ARIA role. - * @type {?goog.dom.a11y.Role} - * @private - */ -goog.ui.Control.prototype.preferredAriaRole_ = null; - - -// Event handler and renderer management. - - -/** - * Returns true if the control is configured to handle its own mouse events, - * false otherwise. Controls not hosted in {@link goog.ui.Container}s have - * to handle their own mouse events, but controls hosted in containers may - * allow their parent to handle mouse events on their behalf. Considered - * protected; should only be used within this package and by subclasses. - * @return {boolean} Whether the control handles its own mouse events. - */ -goog.ui.Control.prototype.isHandleMouseEvents = function() { - return this.handleMouseEvents_; -}; - - -/** - * Enables or disables mouse event handling for the control. Containers may - * use this method to disable mouse event handling in their child controls. - * Considered protected; should only be used within this package and by - * subclasses. - * @param {boolean} enable Whether to enable or disable mouse event handling. - */ -goog.ui.Control.prototype.setHandleMouseEvents = function(enable) { - if (this.isInDocument() && enable != this.handleMouseEvents_) { - // Already in the document; need to update event handler. - this.enableMouseEventHandling_(enable); - } - this.handleMouseEvents_ = enable; -}; - - -/** - * Returns the DOM element on which the control is listening for keyboard - * events (null if none). - * @return {Element} Element on which the control is listening for key - * events. - */ -goog.ui.Control.prototype.getKeyEventTarget = function() { - // Delegate to renderer. - return this.renderer_.getKeyEventTarget(this); -}; - - -/** - * Returns the keyboard event handler for this component, lazily created the - * first time this method is called. Considered protected; should only be - * used within this package and by subclasses. - * @return {goog.events.KeyHandler} Keyboard event handler for this component. - * @protected - */ -goog.ui.Control.prototype.getKeyHandler = function() { - return this.keyHandler_ || (this.keyHandler_ = new goog.events.KeyHandler()); -}; - - -/** - * Returns the renderer used by this component to render itself or to decorate - * an existing element. - * @return {goog.ui.ControlRenderer|undefined} Renderer used by the component - * (undefined if none). - */ -goog.ui.Control.prototype.getRenderer = function() { - return this.renderer_; -}; - - -/** - * Registers the given renderer with the component. Changing renderers after - * the component has entered the document is an error. - * @param {goog.ui.ControlRenderer} renderer Renderer used by the component. - * @throws {Error} If the control is already in the document. - */ -goog.ui.Control.prototype.setRenderer = function(renderer) { - if (this.isInDocument()) { - // Too late. - throw Error(goog.ui.Component.Error.ALREADY_RENDERED); - } - - if (this.getElement()) { - // The component has already been rendered, but isn't yet in the document. - // Replace the renderer and delete the current DOM, so it can be re-rendered - // using the new renderer the next time someone calls render(). - this.setElementInternal(null); - } - - this.renderer_ = renderer; -}; - - -// Support for additional styling. - - -/** - * Returns any additional class name(s) to be applied to the component's - * root element, or null if no extra class names are needed. - * @return {Array.<string>?} Additional class names to be applied to - * the component's root element (null if none). - */ -goog.ui.Control.prototype.getExtraClassNames = function() { - return this.extraClassNames_; -}; - - -/** - * Adds the given class name to the list of classes to be applied to the - * component's root element. - * @param {string} className Additional class name to be applied to the - * component's root element. - */ -goog.ui.Control.prototype.addClassName = function(className) { - if (className) { - if (this.extraClassNames_) { - if (!goog.array.contains(this.extraClassNames_, className)) { - this.extraClassNames_.push(className); - } - } else { - this.extraClassNames_ = [className]; - } - this.renderer_.enableExtraClassName(this, className, true); - } -}; - - -/** - * Removes the given class name from the list of classes to be applied to - * the component's root element. - * @param {string} className Class name to be removed from the component's root - * element. - */ -goog.ui.Control.prototype.removeClassName = function(className) { - if (className && this.extraClassNames_) { - goog.array.remove(this.extraClassNames_, className); - if (this.extraClassNames_.length == 0) { - this.extraClassNames_ = null; - } - this.renderer_.enableExtraClassName(this, className, false); - } -}; - - -/** - * Adds or removes the given class name to/from the list of classes to be - * applied to the component's root element. - * @param {string} className CSS class name to add or remove. - * @param {boolean} enable Whether to add or remove the class name. - */ -goog.ui.Control.prototype.enableClassName = function(className, enable) { - if (enable) { - this.addClassName(className); - } else { - this.removeClassName(className); - } -}; - - -// Standard goog.ui.Component implementation. - - -/** - * Creates the control's DOM. Overrides {@link goog.ui.Component#createDom} by - * delegating DOM manipulation to the control's renderer. - * @override - */ -goog.ui.Control.prototype.createDom = function() { - var element = this.renderer_.createDom(this); - this.setElementInternal(element); - - // Initialize ARIA role. - this.renderer_.setAriaRole(element, this.getPreferredAriaRole()); - - // Initialize text selection. - if (!this.isAllowTextSelection()) { - // The renderer is assumed to create selectable elements. Since making - // elements unselectable is expensive, only do it if needed (bug 1037090). - this.renderer_.setAllowTextSelection(element, false); - } - - // Initialize visibility. - if (!this.isVisible()) { - // The renderer is assumed to create visible elements. Since hiding - // elements can be expensive, only do it if needed (bug 1037105). - this.renderer_.setVisible(element, false); - } -}; - - -/** - * Returns the control's preferred ARIA role. This can be used by a control to - * override the role that would be assigned by the renderer. This is useful in - * cases where a different ARIA role is appropriate for a control because of the - * context in which it's used. E.g., a {@link goog.ui.MenuButton} added to a - * {@link goog.ui.Select} should have an ARIA role of LISTBOX and not MENUITEM. - * @return {?goog.dom.a11y.Role} This control's preferred ARIA role or null if - * no preferred ARIA role is set. - */ -goog.ui.Control.prototype.getPreferredAriaRole = function() { - return this.preferredAriaRole_; -}; - - -/** - * Sets the control's preferred ARIA role. This can be used to override the role - * that would be assigned by the renderer. This is useful in cases where a - * different ARIA role is appropriate for a control because of the - * context in which it's used. E.g., a {@link goog.ui.MenuButton} added to a - * {@link goog.ui.Select} should have an ARIA role of LISTBOX and not MENUITEM. - * @param {goog.dom.a11y.Role} role This control's preferred ARIA role. - */ -goog.ui.Control.prototype.setPreferredAriaRole = function(role) { - this.preferredAriaRole_ = role; -}; - - -/** - * Returns the DOM element into which child components are to be rendered, - * or null if the control itself hasn't been rendered yet. Overrides - * {@link goog.ui.Component#getContentElement} by delegating to the renderer. - * @return {Element} Element to contain child elements (null if none). - */ -goog.ui.Control.prototype.getContentElement = function() { - // Delegate to renderer. - return this.renderer_.getContentElement(this.getElement()); -}; - - -/** - * Returns true if the given element can be decorated by this component. - * Overrides {@link goog.ui.Component#canDecorate}. - * @param {Element} element Element to decorate. - * @return {boolean} Whether the element can be decorated by this component. - */ -goog.ui.Control.prototype.canDecorate = function(element) { - // Controls support pluggable renderers; delegate to the renderer. - return this.renderer_.canDecorate(element); -}; - - -/** - * Decorates the given element with this component. Overrides {@link - * goog.ui.Component#decorateInternal} by delegating DOM manipulation - * to the control's renderer. - * @param {Element} element Element to decorate. - * @protected - * @override - */ -goog.ui.Control.prototype.decorateInternal = function(element) { - element = this.renderer_.decorate(this, element); - this.setElementInternal(element); - - // Initialize ARIA role. - this.renderer_.setAriaRole(element, this.getPreferredAriaRole()); - - // Initialize text selection. - if (!this.isAllowTextSelection()) { - // Decorated elements are assumed to be selectable. Since making elements - // unselectable is expensive, only do it if needed (bug 1037090). - this.renderer_.setAllowTextSelection(element, false); - } - - // Initialize visibility based on the decorated element's styling. - this.visible_ = element.style.display != 'none'; -}; - - -/** - * Configures the component after its DOM has been rendered, and sets up event - * handling. Overrides {@link goog.ui.Component#enterDocument}. - * @override - */ -goog.ui.Control.prototype.enterDocument = function() { - goog.ui.Control.superClass_.enterDocument.call(this); - - // Call the renderer's initializeDom method to configure properties of the - // control's DOM that can only be done once it's in the document. - this.renderer_.initializeDom(this); - - // Initialize event handling if at least one state other than DISABLED is - // supported. - if (this.supportedStates_ & ~goog.ui.Component.State.DISABLED) { - // Initialize mouse event handling if the control is configured to handle - // its own mouse events. (Controls hosted in containers don't need to - // handle their own mouse events.) - if (this.isHandleMouseEvents()) { - this.enableMouseEventHandling_(true); - } - - // Initialize keyboard event handling if the control is focusable and has - // a key event target. (Controls hosted in containers typically aren't - // focusable, allowing their container to handle keyboard events for them.) - if (this.isSupportedState(goog.ui.Component.State.FOCUSED)) { - var keyTarget = this.getKeyEventTarget(); - if (keyTarget) { - var keyHandler = this.getKeyHandler(); - keyHandler.attach(keyTarget); - this.getHandler(). - listen(keyHandler, goog.events.KeyHandler.EventType.KEY, - this.handleKeyEvent). - listen(keyTarget, goog.events.EventType.FOCUS, - this.handleFocus). - listen(keyTarget, goog.events.EventType.BLUR, - this.handleBlur); - } - } - } -}; - - -/** - * Enables or disables mouse event handling on the control. - * @param {boolean} enable Whether to enable mouse event handling. - * @private - */ -goog.ui.Control.prototype.enableMouseEventHandling_ = function(enable) { - var handler = this.getHandler(); - var element = this.getElement(); - if (enable) { - handler. - listen(element, goog.events.EventType.MOUSEOVER, this.handleMouseOver). - listen(element, goog.events.EventType.MOUSEDOWN, this.handleMouseDown). - listen(element, goog.events.EventType.MOUSEUP, this.handleMouseUp). - listen(element, goog.events.EventType.MOUSEOUT, this.handleMouseOut); - if (goog.userAgent.IE) { - handler.listen(element, goog.events.EventType.DBLCLICK, - this.handleDblClick); - } - } else { - handler. - unlisten(element, goog.events.EventType.MOUSEOVER, - this.handleMouseOver). - unlisten(element, goog.events.EventType.MOUSEDOWN, - this.handleMouseDown). - unlisten(element, goog.events.EventType.MOUSEUP, this.handleMouseUp). - unlisten(element, goog.events.EventType.MOUSEOUT, this.handleMouseOut); - if (goog.userAgent.IE) { - handler.unlisten(element, goog.events.EventType.DBLCLICK, - this.handleDblClick); - } - } -}; - - -/** - * Cleans up the component before its DOM is removed from the document, and - * removes event handlers. Overrides {@link goog.ui.Component#exitDocument} - * by making sure that components that are removed from the document aren't - * focusable (i.e. have no tab index). - * @override - */ -goog.ui.Control.prototype.exitDocument = function() { - goog.ui.Control.superClass_.exitDocument.call(this); - if (this.keyHandler_) { - this.keyHandler_.detach(); - } - if (this.isVisible() && this.isEnabled()) { - this.renderer_.setFocusable(this, false); - } -}; - - -/** @override */ -goog.ui.Control.prototype.disposeInternal = function() { - goog.ui.Control.superClass_.disposeInternal.call(this); - if (this.keyHandler_) { - this.keyHandler_.dispose(); - delete this.keyHandler_; - } - delete this.renderer_; - this.content_ = null; - this.extraClassNames_ = null; -}; - - -// Component content management. - - -/** - * Returns the text caption or DOM structure displayed in the component. - * @return {goog.ui.ControlContent} Text caption or DOM structure - * comprising the component's contents. - */ -goog.ui.Control.prototype.getContent = function() { - return this.content_; -}; - - -/** - * Sets the component's content to the given text caption, element, or array of - * nodes. (If the argument is an array of nodes, it must be an actual array, - * not an array-like object.) - * @param {goog.ui.ControlContent} content Text caption or DOM - * structure to set as the component's contents. - */ -goog.ui.Control.prototype.setContent = function(content) { - // Controls support pluggable renderers; delegate to the renderer. - this.renderer_.setContent(this.getElement(), content); - - // setContentInternal needs to be after the renderer, since the implementation - // may depend on the content being in the DOM. - this.setContentInternal(content); -}; - - -/** - * Sets the component's content to the given text caption, element, or array - * of nodes. Unlike {@link #setContent}, doesn't modify the component's DOM. - * Called by renderers during element decoration. Considered protected; should - * only be used within this package and by subclasses. - * @param {goog.ui.ControlContent} content Text caption or DOM structure - * to set as the component's contents. - * @protected - */ -goog.ui.Control.prototype.setContentInternal = function(content) { - this.content_ = content; -}; - - -/** - * @return {string} Text caption of the control or empty string if none. - */ -goog.ui.Control.prototype.getCaption = function() { - var content = this.getContent(); - if (!content) { - return ''; - } - var caption = - goog.isString(content) ? content : - goog.isArray(content) ? goog.array.map(content, - goog.dom.getRawTextContent).join('') : - goog.dom.getTextContent(/** @type {!Node} */ (content)); - return goog.string.collapseBreakingSpaces(caption); -}; - - -/** - * Sets the text caption of the component. - * @param {string} caption Text caption of the component. - */ -goog.ui.Control.prototype.setCaption = function(caption) { - this.setContent(caption); -}; - - -// Component state management. - - -/** @override */ -goog.ui.Control.prototype.setRightToLeft = function(rightToLeft) { - // The superclass implementation ensures the control isn't in the document. - goog.ui.Control.superClass_.setRightToLeft.call(this, rightToLeft); - - var element = this.getElement(); - if (element) { - this.renderer_.setRightToLeft(element, rightToLeft); - } -}; - - -/** - * Returns true if the control allows text selection within its DOM, false - * otherwise. Controls that disallow text selection have the appropriate - * unselectable styling applied to their elements. Note that controls hosted - * in containers will report that they allow text selection even if their - * container disallows text selection. - * @return {boolean} Whether the control allows text selection. - */ -goog.ui.Control.prototype.isAllowTextSelection = function() { - return this.allowTextSelection_; -}; - - -/** - * Allows or disallows text selection within the control's DOM. - * @param {boolean} allow Whether the control should allow text selection. - */ -goog.ui.Control.prototype.setAllowTextSelection = function(allow) { - this.allowTextSelection_ = allow; - - var element = this.getElement(); - if (element) { - this.renderer_.setAllowTextSelection(element, allow); - } -}; - - -/** - * Returns true if the component's visibility is set to visible, false if - * it is set to hidden. A component that is set to hidden is guaranteed - * to be hidden from the user, but the reverse isn't necessarily true. - * A component may be set to visible but can otherwise be obscured by another - * element, rendered off-screen, or hidden using direct CSS manipulation. - * @return {boolean} Whether the component is visible. - */ -goog.ui.Control.prototype.isVisible = function() { - return this.visible_; -}; - - -/** - * Shows or hides the component. Does nothing if the component already has - * the requested visibility. Otherwise, dispatches a SHOW or HIDE event as - * appropriate, giving listeners a chance to prevent the visibility change. - * When showing a component that is both enabled and focusable, ensures that - * its key target has a tab index. When hiding a component that is enabled - * and focusable, blurs its key target and removes its tab index. - * @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. - */ -goog.ui.Control.prototype.setVisible = function(visible, opt_force) { - if (opt_force || (this.visible_ != visible && this.dispatchEvent(visible ? - goog.ui.Component.EventType.SHOW : goog.ui.Component.EventType.HIDE))) { - var element = this.getElement(); - if (element) { - this.renderer_.setVisible(element, visible); - } - if (this.isEnabled()) { - this.renderer_.setFocusable(this, visible); - } - this.visible_ = visible; - return true; - } - return false; -}; - - -/** - * Returns true if the component is enabled, false otherwise. - * @return {boolean} Whether the component is enabled. - */ -goog.ui.Control.prototype.isEnabled = function() { - return !this.hasState(goog.ui.Component.State.DISABLED); -}; - - -/** - * Returns true if the control has a parent that is itself disabled, false - * otherwise. - * @return {boolean} Whether the component is hosted in a disabled container. - * @private - */ -goog.ui.Control.prototype.isParentDisabled_ = function() { - var parent = this.getParent(); - return !!parent && typeof parent.isEnabled == 'function' && - !parent.isEnabled(); -}; - - -/** - * Enables or disables the component. Does nothing if this state transition - * is disallowed. If the component is both visible and focusable, updates its - * focused state and tab index as needed. If the component is being disabled, - * ensures that it is also deactivated and un-highlighted first. Note that the - * component's enabled/disabled state is "locked" as long as it is hosted in a - * {@link goog.ui.Container} that is itself disabled; this is to prevent clients - * from accidentally re-enabling a control that is in a disabled container. - * @param {boolean} enable Whether to enable or disable the component. - * @see #isTransitionAllowed - */ -goog.ui.Control.prototype.setEnabled = function(enable) { - if (!this.isParentDisabled_() && - this.isTransitionAllowed(goog.ui.Component.State.DISABLED, !enable)) { - if (!enable) { - this.setActive(false); - this.setHighlighted(false); - } - if (this.isVisible()) { - this.renderer_.setFocusable(this, enable); - } - this.setState(goog.ui.Component.State.DISABLED, !enable); - } -}; - - -/** - * Returns true if the component is currently highlighted, false otherwise. - * @return {boolean} Whether the component is highlighted. - */ -goog.ui.Control.prototype.isHighlighted = function() { - return this.hasState(goog.ui.Component.State.HOVER); -}; - - -/** - * Highlights or unhighlights the component. Does nothing if this state - * transition is disallowed. - * @param {boolean} highlight Whether to highlight or unhighlight the component. - * @see #isTransitionAllowed - */ -goog.ui.Control.prototype.setHighlighted = function(highlight) { - if (this.isTransitionAllowed(goog.ui.Component.State.HOVER, highlight)) { - this.setState(goog.ui.Component.State.HOVER, highlight); - } -}; - - -/** - * Returns true if the component is active (pressed), false otherwise. - * @return {boolean} Whether the component is active. - */ -goog.ui.Control.prototype.isActive = function() { - return this.hasState(goog.ui.Component.State.ACTIVE); -}; - - -/** - * Activates or deactivates the component. Does nothing if this state - * transition is disallowed. - * @param {boolean} active Whether to activate or deactivate the component. - * @see #isTransitionAllowed - */ -goog.ui.Control.prototype.setActive = function(active) { - if (this.isTransitionAllowed(goog.ui.Component.State.ACTIVE, active)) { - this.setState(goog.ui.Component.State.ACTIVE, active); - } -}; - - -/** - * Returns true if the component is selected, false otherwise. - * @return {boolean} Whether the component is selected. - */ -goog.ui.Control.prototype.isSelected = function() { - return this.hasState(goog.ui.Component.State.SELECTED); -}; - - -/** - * Selects or unselects the component. Does nothing if this state transition - * is disallowed. - * @param {boolean} select Whether to select or unselect the component. - * @see #isTransitionAllowed - */ -goog.ui.Control.prototype.setSelected = function(select) { - if (this.isTransitionAllowed(goog.ui.Component.State.SELECTED, select)) { - this.setState(goog.ui.Component.State.SELECTED, select); - } -}; - - -/** - * Returns true if the component is checked, false otherwise. - * @return {boolean} Whether the component is checked. - */ -goog.ui.Control.prototype.isChecked = function() { - return this.hasState(goog.ui.Component.State.CHECKED); -}; - - -/** - * Checks or unchecks the component. Does nothing if this state transition - * is disallowed. - * @param {boolean} check Whether to check or uncheck the component. - * @see #isTransitionAllowed - */ -goog.ui.Control.prototype.setChecked = function(check) { - if (this.isTransitionAllowed(goog.ui.Component.State.CHECKED, check)) { - this.setState(goog.ui.Component.State.CHECKED, check); - } -}; - - -/** - * Returns true if the component is styled to indicate that it has keyboard - * focus, false otherwise. Note that {@code isFocused()} returning true - * doesn't guarantee that the component's key event target has keyborad focus, - * only that it is styled as such. - * @return {boolean} Whether the component is styled to indicate as having - * keyboard focus. - */ -goog.ui.Control.prototype.isFocused = function() { - return this.hasState(goog.ui.Component.State.FOCUSED); -}; - - -/** - * Applies or removes styling indicating that the component has keyboard focus. - * Note that unlike the other "set" methods, this method is called as a result - * of the component's element having received or lost keyboard focus, not the - * other way around, so calling {@code setFocused(true)} doesn't guarantee that - * the component's key event target has keyboard focus, only that it is styled - * as such. - * @param {boolean} focused Whether to apply or remove styling to indicate that - * the component's element has keyboard focus. - */ -goog.ui.Control.prototype.setFocused = function(focused) { - if (this.isTransitionAllowed(goog.ui.Component.State.FOCUSED, focused)) { - this.setState(goog.ui.Component.State.FOCUSED, focused); - } -}; - - -/** - * Returns true if the component is open (expanded), false otherwise. - * @return {boolean} Whether the component is open. - */ -goog.ui.Control.prototype.isOpen = function() { - return this.hasState(goog.ui.Component.State.OPENED); -}; - - -/** - * Opens (expands) or closes (collapses) the component. Does nothing if this - * state transition is disallowed. - * @param {boolean} open Whether to open or close the component. - * @see #isTransitionAllowed - */ -goog.ui.Control.prototype.setOpen = function(open) { - if (this.isTransitionAllowed(goog.ui.Component.State.OPENED, open)) { - this.setState(goog.ui.Component.State.OPENED, open); - } -}; - - -/** - * Returns the component's state as a bit mask of {@link - * goog.ui.Component.State}s. - * @return {number} Bit mask representing component state. - */ -goog.ui.Control.prototype.getState = function() { - return this.state_; -}; - - -/** - * Returns true if the component is in the specified state, false otherwise. - * @param {goog.ui.Component.State} state State to check. - * @return {boolean} Whether the component is in the given state. - */ -goog.ui.Control.prototype.hasState = function(state) { - return !!(this.state_ & state); -}; - - -/** - * Sets or clears the given state on the component, and updates its styling - * accordingly. Does nothing if the component is already in the correct state - * or if it doesn't support the specified state. Doesn't dispatch any state - * transition events; use advisedly. - * @param {goog.ui.Component.State} state State to set or clear. - * @param {boolean} enable Whether to set or clear the state (if supported). - */ -goog.ui.Control.prototype.setState = function(state, enable) { - if (this.isSupportedState(state) && enable != this.hasState(state)) { - // Delegate actual styling to the renderer, since it is DOM-specific. - this.renderer_.setState(this, state, enable); - this.state_ = enable ? this.state_ | state : this.state_ & ~state; - } -}; - - -/** - * Sets the component's state to the state represented by a bit mask of - * {@link goog.ui.Component.State}s. Unlike {@link #setState}, doesn't - * update the component's styling, and doesn't reject unsupported states. - * Called by renderers during element decoration. Considered protected; - * should only be used within this package and by subclasses. - * @param {number} state Bit mask representing component state. - * @protected - */ -goog.ui.Control.prototype.setStateInternal = function(state) { - this.state_ = state; -}; - - -/** - * Returns true if the component supports the specified state, false otherwise. - * @param {goog.ui.Component.State} state State to check. - * @return {boolean} Whether the component supports the given state. - */ -goog.ui.Control.prototype.isSupportedState = function(state) { - return !!(this.supportedStates_ & state); -}; - - -/** - * Enables or disables support for the given state. Disabling support - * for a state while the component is in that state is an error. - * @param {goog.ui.Component.State} state State to support or de-support. - * @param {boolean} support Whether the component should support the state. - * @throws {Error} If disabling support for a state the control is currently in. - */ -goog.ui.Control.prototype.setSupportedState = function(state, support) { - if (this.isInDocument() && this.hasState(state) && !support) { - // Since we hook up event handlers in enterDocument(), this is an error. - throw Error(goog.ui.Component.Error.ALREADY_RENDERED); - } - - if (!support && this.hasState(state)) { - // We are removing support for a state that the component is currently in. - this.setState(state, false); - } - - this.supportedStates_ = support ? - this.supportedStates_ | state : this.supportedStates_ & ~state; -}; - - -/** - * Returns true if the component provides default event handling for the state, - * false otherwise. - * @param {goog.ui.Component.State} state State to check. - * @return {boolean} Whether the component provides default event handling for - * the state. - */ -goog.ui.Control.prototype.isAutoState = function(state) { - return !!(this.autoStates_ & state) && this.isSupportedState(state); -}; - - -/** - * Enables or disables automatic event handling for the given state(s). - * @param {number} states Bit mask of {@link goog.ui.Component.State}s for which - * default event handling is to be enabled or disabled. - * @param {boolean} enable Whether the component should provide default event - * handling for the state(s). - */ -goog.ui.Control.prototype.setAutoStates = function(states, enable) { - this.autoStates_ = enable ? - this.autoStates_ | states : this.autoStates_ & ~states; -}; - - -/** - * Returns true if the component is set to dispatch transition events for the - * given state, false otherwise. - * @param {goog.ui.Component.State} state State to check. - * @return {boolean} Whether the component dispatches transition events for - * the state. - */ -goog.ui.Control.prototype.isDispatchTransitionEvents = function(state) { - return !!(this.statesWithTransitionEvents_ & state) && - this.isSupportedState(state); -}; - - -/** - * Enables or disables transition events for the given state(s). Controls - * handle state transitions internally by default, and only dispatch state - * transition events if explicitly requested to do so by calling this method. - * @param {number} states Bit mask of {@link goog.ui.Component.State}s for - * which transition events should be enabled or disabled. - * @param {boolean} enable Whether transition events should be enabled. - */ -goog.ui.Control.prototype.setDispatchTransitionEvents = function(states, - enable) { - this.statesWithTransitionEvents_ = enable ? - this.statesWithTransitionEvents_ | states : - this.statesWithTransitionEvents_ & ~states; -}; - - -/** - * Returns true if the transition into or out of the given state is allowed to - * proceed, false otherwise. A state transition is allowed under the following - * conditions: - * <ul> - * <li>the component supports the state, - * <li>the component isn't already in the target state, - * <li>either the component is configured not to dispatch events for this - * state transition, or a transition event was dispatched and wasn't - * canceled by any event listener, and - * <li>the component hasn't been disposed of - * </ul> - * Considered protected; should only be used within this package and by - * subclasses. - * @param {goog.ui.Component.State} state State to/from which the control is - * transitioning. - * @param {boolean} enable Whether the control is entering or leaving the state. - * @return {boolean} Whether the state transition is allowed to proceed. - * @protected - */ -goog.ui.Control.prototype.isTransitionAllowed = function(state, enable) { - return this.isSupportedState(state) && - this.hasState(state) != enable && - (!(this.statesWithTransitionEvents_ & state) || this.dispatchEvent( - goog.ui.Component.getStateTransitionEvent(state, enable))) && - !this.isDisposed(); -}; - - -// Default event handlers, to be overridden in subclasses. - - -/** - * Handles mouseover events. Dispatches an ENTER event; if the event isn't - * canceled, the component is enabled, and it supports auto-highlighting, - * highlights the component. Considered protected; should only be used - * within this package and by subclasses. - * @param {goog.events.BrowserEvent} e Mouse event to handle. - */ -goog.ui.Control.prototype.handleMouseOver = function(e) { - // Ignore mouse moves between descendants. - if (!goog.ui.Control.isMouseEventWithinElement_(e, this.getElement()) && - this.dispatchEvent(goog.ui.Component.EventType.ENTER) && - this.isEnabled() && - this.isAutoState(goog.ui.Component.State.HOVER)) { - this.setHighlighted(true); - } -}; - - -/** - * Handles mouseout events. Dispatches a LEAVE event; if the event isn't - * canceled, and the component supports auto-highlighting, deactivates and - * un-highlights the component. Considered protected; should only be used - * within this package and by subclasses. - * @param {goog.events.BrowserEvent} e Mouse event to handle. - */ -goog.ui.Control.prototype.handleMouseOut = function(e) { - if (!goog.ui.Control.isMouseEventWithinElement_(e, this.getElement()) && - this.dispatchEvent(goog.ui.Component.EventType.LEAVE)) { - if (this.isAutoState(goog.ui.Component.State.ACTIVE)) { - // Deactivate on mouseout; otherwise we lose track of the mouse button. - this.setActive(false); - } - if (this.isAutoState(goog.ui.Component.State.HOVER)) { - this.setHighlighted(false); - } - } -}; - - -/** - * Checks if a mouse event (mouseover or mouseout) occured below an element. - * @param {goog.events.BrowserEvent} e Mouse event (should be mouseover or - * mouseout). - * @param {Element} elem The ancestor element. - * @return {boolean} Whether the event has a relatedTarget (the element the - * mouse is coming from) and it's a descendent of elem. - * @private - */ -goog.ui.Control.isMouseEventWithinElement_ = function(e, elem) { - // If relatedTarget is null, it means there was no previous element (e.g. - // the mouse moved out of the window). Assume this means that the mouse - // event was not within the element. - return !!e.relatedTarget && goog.dom.contains(elem, e.relatedTarget); -}; - - -/** - * Handles mousedown events. If the component is enabled, highlights and - * activates it. If the component isn't configured for keyboard access, - * prevents it from receiving keyboard focus. Considered protected; should - * only be used within this package andy by subclasses. - * @param {goog.events.Event} e Mouse event to handle. - */ -goog.ui.Control.prototype.handleMouseDown = function(e) { - if (this.isEnabled()) { - // Highlight enabled control on mousedown, regardless of the mouse button. - if (this.isAutoState(goog.ui.Component.State.HOVER)) { - this.setHighlighted(true); - } - - // For the left button only, activate the control, and focus its key event - // target (if supported). - if (e.isMouseActionButton()) { - if (this.isAutoState(goog.ui.Component.State.ACTIVE)) { - this.setActive(true); - } - if (this.renderer_.isFocusable(this)) { - this.getKeyEventTarget().focus(); - } - } - } - - // Cancel the default action unless the control allows text selection. - if (!this.isAllowTextSelection() && e.isMouseActionButton()) { - e.preventDefault(); - } -}; - - -/** - * Handles mouseup events. If the component is enabled, highlights it. If - * the component has previously been activated, performs its associated action - * by calling {@link performActionInternal}, then deactivates it. Considered - * protected; should only be used within this package and by subclasses. - * @param {goog.events.Event} e Mouse event to handle. - */ -goog.ui.Control.prototype.handleMouseUp = function(e) { - if (this.isEnabled()) { - if (this.isAutoState(goog.ui.Component.State.HOVER)) { - this.setHighlighted(true); - } - if (this.isActive() && - this.performActionInternal(e) && - this.isAutoState(goog.ui.Component.State.ACTIVE)) { - this.setActive(false); - } - } -}; - - -/** - * Handles dblclick events. Should only be registered if the user agent is - * IE. If the component is enabled, performs its associated action by calling - * {@link performActionInternal}. This is used to allow more performant - * buttons in IE. In IE, no mousedown event is fired when that mousedown will - * trigger a dblclick event. Because of this, a user clicking quickly will - * only cause ACTION events to fire on every other click. This is a workaround - * to generate ACTION events for every click. Unfortunately, this workaround - * won't ever trigger the ACTIVE state. This is roughly the same behaviour as - * if this were a 'button' element with a listener on mouseup. Considered - * protected; should only be used within this package and by subclasses. - * @param {goog.events.Event} e Mouse event to handle. - */ -goog.ui.Control.prototype.handleDblClick = function(e) { - if (this.isEnabled()) { - this.performActionInternal(e); - } -}; - - -/** - * Performs the appropriate action when the control is activated by the user. - * The default implementation first updates the checked and selected state of - * controls that support them, then dispatches an ACTION event. Considered - * protected; should only be used within this package and by subclasses. - * @param {goog.events.Event} e Event that triggered the action. - * @return {boolean} Whether the action is allowed to proceed. - * @protected - */ -goog.ui.Control.prototype.performActionInternal = function(e) { - if (this.isAutoState(goog.ui.Component.State.CHECKED)) { - this.setChecked(!this.isChecked()); - } - if (this.isAutoState(goog.ui.Component.State.SELECTED)) { - this.setSelected(true); - } - if (this.isAutoState(goog.ui.Component.State.OPENED)) { - this.setOpen(!this.isOpen()); - } - - var actionEvent = new goog.events.Event(goog.ui.Component.EventType.ACTION, - this); - if (e) { - actionEvent.altKey = e.altKey; - actionEvent.ctrlKey = e.ctrlKey; - actionEvent.metaKey = e.metaKey; - actionEvent.shiftKey = e.shiftKey; - actionEvent.platformModifierKey = e.platformModifierKey; - } - return this.dispatchEvent(actionEvent); -}; - - -/** - * Handles focus events on the component's key event target element. If the - * component is focusable, updates its state and styling to indicate that it - * now has keyboard focus. Considered protected; should only be used within - * this package and by subclasses. <b>Warning:</b> IE dispatches focus and - * blur events asynchronously! - * @param {goog.events.Event} e Focus event to handle. - */ -goog.ui.Control.prototype.handleFocus = function(e) { - if (this.isAutoState(goog.ui.Component.State.FOCUSED)) { - this.setFocused(true); - } -}; - - -/** - * Handles blur events on the component's key event target element. Always - * deactivates the component. In addition, if the component is focusable, - * updates its state and styling to indicate that it no longer has keyboard - * focus. Considered protected; should only be used within this package and - * by subclasses. <b>Warning:</b> IE dispatches focus and blur events - * asynchronously! - * @param {goog.events.Event} e Blur event to handle. - */ -goog.ui.Control.prototype.handleBlur = function(e) { - if (this.isAutoState(goog.ui.Component.State.ACTIVE)) { - this.setActive(false); - } - if (this.isAutoState(goog.ui.Component.State.FOCUSED)) { - this.setFocused(false); - } -}; - - -/** - * Attempts to handle a keyboard event, if the component is enabled and visible, - * by calling {@link handleKeyEventInternal}. Considered protected; should only - * be used within this package and by subclasses. - * @param {goog.events.KeyEvent} e Key event to handle. - * @return {boolean} Whether the key event was handled. - */ -goog.ui.Control.prototype.handleKeyEvent = function(e) { - if (this.isVisible() && this.isEnabled() && - this.handleKeyEventInternal(e)) { - e.preventDefault(); - e.stopPropagation(); - return true; - } - return false; -}; - - -/** - * Attempts to handle a keyboard event; returns true if the event was handled, - * false otherwise. Considered protected; should only be used within this - * package and by subclasses. - * @param {goog.events.KeyEvent} e Key event to handle. - * @return {boolean} Whether the key event was handled. - * @protected - */ -goog.ui.Control.prototype.handleKeyEventInternal = function(e) { - return e.keyCode == goog.events.KeyCodes.ENTER && - this.performActionInternal(e); -}; - - -// Register the default renderer for goog.ui.Controls. -goog.ui.registry.setDefaultRenderer(goog.ui.Control, goog.ui.ControlRenderer); - - -// Register a decorator factory function for goog.ui.Controls. -goog.ui.registry.setDecoratorByClassName(goog.ui.ControlRenderer.CSS_CLASS, - function() { - return new goog.ui.Control(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/control_perf.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/control_perf.html.svn-base deleted file mode 100644 index 901195b..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/control_perf.html.svn-base +++ /dev/null @@ -1,166 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Performance Tests - goog.ui.Control</title> - <link rel="stylesheet" type="text/css" href="../testing/performancetable.css" /> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.testing.PerformanceTable'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Control'); - </script> -</head> -<body> - <h1>goog.ui.Control Performance Tests</h1> - <p> - <b>User-agent:</b> <script>document.write(navigator.userAgent);</script> - </p> - <div id="perfTable"></div> - <hr> - <div id="renderSandbox"></div> - <div id="decorateSandbox"></div> - <script> - // The sandboxen. - var renderSandbox = goog.dom.getElement('renderSandbox'); - var decorateSandbox = goog.dom.getElement('decorateSandbox'); - - // Arrays of rendered/decorated controls (so we can dispose of them). - var renderedControls; - var decoratedControls; - - // 0-based index of the control currently being rendered/decorated. - var renderIndex; - var decorateIndex; - - // Element currently being decorated. - var elementToDecorate; - - // Number of controls to create/decorate per test run. - var SAMPLES_PER_RUN = 100; - - // The performance table. - var table; - - // Sets up a render test. - function setUpRenderTest() { - renderedControls = []; - renderIndex = 0; - } - - // Cleans up after a render test. - function cleanUpAfterRenderTest() { - for (var i = 0, count = renderedControls.length; i < count; i++) { - renderedControls[i].dispose(); - } - renderedControls = null; - goog.dom.removeChildren(renderSandbox); - } - - // Sets up a decorate test. - function setUpDecorateTest(opt_count) { - var count = opt_count || 1000; - for (var i = 0; i < count; i++) { - decorateSandbox.appendChild(goog.dom.createDom('div', 'goog-control', - 'W00t!')); - } - elementToDecorate = decorateSandbox.firstChild; - decoratedControls = []; - decorateIndex = 0; - } - - // Cleans up after a decorate test. - function cleanUpAfterDecorateTest() { - for (var i = 0, count = decoratedControls.length; i < count; i++) { - decoratedControls[i].dispose(); - } - decoratedControls = null; - goog.dom.removeChildren(decorateSandbox); - } - - // Renders the given number of controls. Since children are appended to - // the same parent element in each performance test run, we keep track of - // the current index via the global renderIndex variable. - function renderControls(count, autoDetectBiDi) { - for (var i = 0; i < count; i++) { - var control = new goog.ui.Control('W00t!'); - if (!autoDetectBiDi) { - control.setRightToLeft(false); - } - control.render(renderSandbox); - renderedControls[renderIndex++] = control; - } - } - - // Decorates "count" controls. The decorate sandbox contains enough child - // elements for the whole test, but we only decorate up to "count" elements - // per test run, so we need to keep track of where we are via the global - // decorateIndex and elementToDecorate variables. - function decorateControls(count, autoDetectBiDi) { - for (var i = 0; i < count; i++) { - var next = elementToDecorate.nextSibling; - var control = new goog.ui.Control(); - if (!autoDetectBiDi) { - control.setRightToLeft(false); - } - control.decorate(elementToDecorate); - decoratedControls[decorateIndex++] = control; - elementToDecorate = next; - } - } - - function setUpPage() { - table = new goog.testing.PerformanceTable( - goog.dom.getElement('perfTable')); - } - - function testRender() { - setUpRenderTest(); - table.run(goog.partial(renderControls, SAMPLES_PER_RUN, true), - 'Render ' + SAMPLES_PER_RUN + ' controls (default)'); - cleanUpAfterRenderTest(); - assertEquals('The expected number of controls must have been rendered', - SAMPLES_PER_RUN * table.getTimer().getNumSamples(), renderIndex); - } - - function testDecorate() { - setUpDecorateTest(SAMPLES_PER_RUN * table.getTimer().getNumSamples()); - table.run(goog.partial(decorateControls, SAMPLES_PER_RUN, true), - 'Decorate ' + SAMPLES_PER_RUN + ' controls (default)'); - cleanUpAfterDecorateTest(); - assertEquals('The expected number of controls must have been decorated', - SAMPLES_PER_RUN * table.getTimer().getNumSamples(), decorateIndex); - assertNull('All controls must have been decorated', elementToDecorate); - } - - function testRenderNoBiDiAutoDetect() { - setUpRenderTest(); - table.run(goog.partial(renderControls, SAMPLES_PER_RUN, false), - 'Render ' + SAMPLES_PER_RUN + ' controls (no BiDi auto-detect)'); - cleanUpAfterRenderTest(); - assertEquals('The expected number of controls must have been rendered', - SAMPLES_PER_RUN * table.getTimer().getNumSamples(), renderIndex); - } - - function testDecorateNoBiDiAutoDetect() { - setUpDecorateTest(SAMPLES_PER_RUN * table.getTimer().getNumSamples()); - table.run(goog.partial(decorateControls, SAMPLES_PER_RUN, false), - 'Decorate ' + SAMPLES_PER_RUN + ' controls (no BiDi auto-detect)'); - cleanUpAfterDecorateTest(); - assertEquals('The expected number of controls must have been decorated', - SAMPLES_PER_RUN * table.getTimer().getNumSamples(), decorateIndex); - assertNull('All controls must have been decorated', elementToDecorate); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/control_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/control_test.html.svn-base deleted file mode 100644 index 4ba947d..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/control_test.html.svn-base +++ /dev/null @@ -1,2142 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.Control</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.dom.classes'); - goog.require('goog.events'); - goog.require('goog.events.BrowserEvent.MouseButton'); - goog.require('goog.events.KeyCodes'); - goog.require('goog.object'); - goog.require('goog.style'); - goog.require('goog.testing.ExpectedFailures'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Component.EventType'); - goog.require('goog.ui.Component.State'); - goog.require('goog.ui.Control'); - goog.require('goog.ui.ControlRenderer'); - goog.require('goog.ui.registry'); - goog.require('goog.userAgent'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - - // Disabled due to problems on farm. - var testFocus = false; - - var control; - - var ALL_EVENTS = goog.object.getValues(goog.ui.Component.EventType); - var events = {}; - var expectedFailures = new goog.testing.ExpectedFailures(); - var sandbox = document.getElementById('sandbox'); - - /** - * A dummy renderer, for testing purposes. - * @constructor - * @extends {goog.ui.ControlRenderer} - */ - function TestRenderer() { - goog.ui.ControlRenderer.call(this); - } - goog.inherits(TestRenderer, goog.ui.ControlRenderer); - - /** - * Initializes the testcase prior to execution. - */ - function setUp() { - control = new goog.ui.Control('Hello'); - control.setDispatchTransitionEvents(goog.ui.Component.State.ALL, true); - goog.events.listen(control, ALL_EVENTS, countEvent); - } - - /** - * Cleans up after executing the testcase. - */ - function tearDown() { - control.dispose(); - expectedFailures.handleTearDown(); - goog.dom.removeChildren(sandbox); - goog.events.removeAll(); - resetEventCount(); - } - - /** - * Resets the global counter for events dispatched by test objects. - */ - function resetEventCount() { - goog.object.clear(events); - } - - /** - * Increments the global counter for events of this type. - * @param {goog.events.Event} e Event to count. - */ - function countEvent(e) { - var type = e.type; - var target = e.target; - - if (!events[target]) { - events[target] = {}; - } - - if (events[target][type]) { - events[target][type]++; - } else { - events[target][type] = 1; - } - } - - /** - * Returns the number of times test objects dispatched events of the given - * type since the global counter was last reset. - * @param {goog.ui.Control} target Event target. - * @param {string} type Event type. - * @return {number} Number of events of this type. - */ - function getEventCount(target, type) { - return events[target] && events[target][type] || 0; - } - - /** - * Returns true if no events were dispatched since the last reset. - * @return {boolean} Whether no events have been dispatched since the last - * reset. - */ - function noEventsDispatched() { - return !events || goog.object.isEmpty(events); - } - - /** - * Returns the number of event listeners created by the control. - * @param {goog.ui.Control} control Control whose event listers are to be - * counted. - * @return {number} Number of event listeners. - */ - function getListenerCount(control) { - return control.googUiComponentHandler_ ? - goog.object.getCount(control.getHandler().keys_) : 0; - } - - /** - * Simulates a mousedown event on the given element, including focusing it. - * @param {Element} element Element on which to simulate mousedown. - * @param {goog.events.BrowserEvent.MouseButton=} opt_button Mouse button; - * defaults to {@code goog.events.BrowserEvent.MouseButton.LEFT}. - * @return {boolean} Whether the event was allowed to proceed. - */ - function fireMouseDownAndFocus(element, opt_button) { - var result = goog.testing.events.fireMouseDownEvent(element, opt_button); - if (result) { - // Browsers move focus for all buttons, not just the left button. - element.focus(); - } - return result; - } - - - /** - * @return {boolean} Whether we're on Mac Safari 3.x. - */ - function isMacSafari3() { - return goog.userAgent.WEBKIT && goog.userAgent.MAC && - !goog.userAgent.isVersion('527'); - } - - /** - * Tests the {@link goog.ui.Control} constructor. - */ - function testConstructor() { - assertNotNull('Constructed control must not be null', control); - assertEquals('Content must have expected value', 'Hello', - control.getContent()); - assertEquals('Renderer must default to the registered renderer', - goog.ui.registry.getDefaultRenderer(goog.ui.Control), - control.getRenderer()); - - var content = goog.dom.createDom('div', null, 'Hello', - goog.dom.createDom('b', null, 'World')); - var testRenderer = new TestRenderer(); - var fakeDomHelper = {}; - var foo = new goog.ui.Control(content, testRenderer, fakeDomHelper); - assertNotNull('Constructed object must not be null', foo); - assertEquals('Content must have expected value', content, - foo.getContent()); - assertEquals('Renderer must have expected value', testRenderer, - foo.getRenderer()); - assertEquals('DOM helper must have expected value', fakeDomHelper, - foo.getDomHelper()); - foo.dispose(); - } - - /** - * Tests {@link goog.ui.Control#getHandler}. - */ - function testGetHandler() { - assertUndefined('Event handler must be undefined before getHandler() ' + - 'is called', control.googUiComponentHandler_); - var handler = control.getHandler(); - assertNotNull('Event handler must not be null', handler); - assertEquals('getHandler() must return the same instance if called again', - handler, control.getHandler()); - } - - /** - * Tests {@link goog.ui.Control#isHandleMouseEvents}. - */ - function testIsHandleMouseEvents() { - assertTrue('Controls must handle their own mouse events by default', - control.isHandleMouseEvents()); - } - - /** - * Tests {@link goog.ui.Control#setHandleMouseEvents}. - */ - function testSetHandleMouseEvents() { - assertTrue('Control must handle its own mouse events by default', - control.isHandleMouseEvents()); - control.setHandleMouseEvents(false); - assertFalse('Control must no longer handle its own mouse events', - control.isHandleMouseEvents()); - control.setHandleMouseEvents(true); - assertTrue('Control must once again handle its own mouse events', - control.isHandleMouseEvents()); - control.render(sandbox); - assertTrue('Rendered control must handle its own mouse events', - control.isHandleMouseEvents()); - control.setHandleMouseEvents(false); - assertFalse('Rendered control must no longer handle its own mouse events', - control.isHandleMouseEvents()); - control.setHandleMouseEvents(true); - assertTrue('Rendered control must once again handle its own mouse events', - control.isHandleMouseEvents()); - } - - /** - * Tests {@link goog.ui.Control#getKeyEventTarget}. - */ - function testGetKeyEventTarget() { - assertNull('Key event target of control without DOM must be null', - control.getKeyEventTarget()); - control.createDom(); - assertEquals('Key event target of control with DOM must be its element', - control.getElement(), control.getKeyEventTarget()); - } - - /** - * Tests {@link goog.ui.Control#getKeyHandler}. - */ - function testGetKeyHandler() { - assertUndefined('Key handler must be undefined before getKeyHandler() ' + - 'is called', control.keyHandler_); - var keyHandler = control.getKeyHandler(); - assertNotNull('Key handler must not be null', keyHandler); - assertEquals('getKeyHandler() must return the same instance if called ' + - 'again', keyHandler, control.getKeyHandler()); - } - - /** - * Tests {@link goog.ui.Control#getRenderer}. - */ - function testGetRenderer() { - assertEquals('Renderer must be the default registered renderer', - goog.ui.registry.getDefaultRenderer(goog.ui.Control), - control.getRenderer()); - } - - /** - * Tests {@link goog.ui.Control#setRenderer}. - */ - function testSetRenderer() { - control.createDom(); - assertNotNull('Control must have a DOM', control.getElement()); - assertFalse('Control must not be in the document', - control.isInDocument()); - assertEquals('Renderer must be the default registered renderer', - goog.ui.registry.getDefaultRenderer(goog.ui.Control), - control.getRenderer()); - - var testRenderer = new TestRenderer(); - control.setRenderer(testRenderer); - assertNull('Control must not have a DOM after its renderer is reset', - control.getElement()); - assertFalse('Control still must not be in the document', - control.isInDocument()); - assertEquals('Renderer must have expected value', testRenderer, - control.getRenderer()); - - control.render(sandbox); - assertTrue('Control must be in the document', control.isInDocument()); - - assertThrows('Resetting the renderer after the control has entered ' + - 'the document must throw error', - function() { - control.setRenderer({}); - }); - } - - /** - * Tests {@link goog.ui.Control#getExtraClassNames}. - */ - function testGetExtraClassNames() { - assertNull('Control must not have any extra class names by default', - control.getExtraClassNames()); - } - - /** - * Tests {@link goog.ui.Control#addExtraClassName} and - * {@link goog.ui.Control#removeExtraClassName}. - */ - function testAddRemoveClassName() { - assertNull('Control must not have any extra class names by default', - control.getExtraClassNames()); - control.addClassName('foo'); - assertArrayEquals('Control must have expected extra class names', - ['foo'], control.getExtraClassNames()); - assertNull('Control must not have a DOM', control.getElement()); - - control.createDom(); - assertSameElements('Control\'s element must have expected class names', - ['goog-control', 'foo'], - goog.dom.classes.get(control.getElement())); - - control.addClassName('bar'); - assertArrayEquals('Control must have expected extra class names', - ['foo', 'bar'], control.getExtraClassNames()); - assertSameElements('Control\'s element must have expected class names', - ['goog-control', 'foo', 'bar'], - goog.dom.classes.get(control.getElement())); - - control.addClassName('bar'); - assertArrayEquals('Adding the same class name again must be a no-op', - ['foo', 'bar'], control.getExtraClassNames()); - assertSameElements('Adding the same class name again must be a no-op', - ['goog-control', 'foo', 'bar'], - goog.dom.classes.get(control.getElement())); - - control.addClassName(null); - assertArrayEquals('Adding null class name must be a no-op', - ['foo', 'bar'], control.getExtraClassNames()); - assertSameElements('Adding null class name must be a no-op', - ['goog-control', 'foo', 'bar'], - goog.dom.classes.get(control.getElement())); - - control.removeClassName(null); - assertArrayEquals('Removing null class name must be a no-op', - ['foo', 'bar'], control.getExtraClassNames()); - assertSameElements('Removing null class name must be a no-op', - ['goog-control', 'foo', 'bar'], - goog.dom.classes.get(control.getElement())); - - control.removeClassName('foo'); - assertArrayEquals('Control must have expected extra class names', - ['bar'], control.getExtraClassNames()); - assertSameElements('Control\'s element must have expected class names', - ['goog-control', 'bar'], - goog.dom.classes.get(control.getElement())); - - control.removeClassName('bar'); - assertNull('Control must not have any extra class names', - control.getExtraClassNames()); - assertSameElements('Control\'s element must have expected class names', - ['goog-control'], - goog.dom.classes.get(control.getElement())); - } - - /** - * Tests {@link goog.ui.Control#enableClassName}. - */ - function testEnableClassName() { - assertNull('Control must not have any extra class names by default', - control.getExtraClassNames()); - - control.enableClassName('foo', true); - assertArrayEquals('Control must have expected extra class names', - ['foo'], control.getExtraClassNames()); - - control.enableClassName('bar', true); - assertArrayEquals('Control must have expected extra class names', - ['foo', 'bar'], control.getExtraClassNames()); - - control.enableClassName('bar', true); - assertArrayEquals('Enabling the same class name again must be a no-op', - ['foo', 'bar'], control.getExtraClassNames()); - - control.enableClassName(null); - assertArrayEquals('Enabling null class name must be a no-op', - ['foo', 'bar'], control.getExtraClassNames()); - - control.enableClassName('foo', false); - assertArrayEquals('Control must have expected extra class names', - ['bar'], control.getExtraClassNames()); - - control.enableClassName('bar', false); - assertNull('Control must not have any extra class names', - control.getExtraClassNames()); - } - - /** - * Tests {@link goog.ui.Control#createDom}. - */ - function testCreateDom() { - assertNull('Control must not have a DOM by default', - control.getElement()); - assertFalse('Control must not allow text selection by default', - control.isAllowTextSelection()); - assertTrue('Control must be visible by default', control.isVisible()); - - control.createDom(); - assertNotNull('Control must have a DOM', control.getElement()); - assertTrue('Control\'s element must be unselectable', - goog.style.isUnselectable(control.getElement())); - assertTrue('Control\'s element must be visible', - control.getElement().style.display != 'none'); - - control.setAllowTextSelection(true); - control.createDom(); - assertFalse('Control\'s element must be selectable', - goog.style.isUnselectable(control.getElement())); - - control.setVisible(false); - control.createDom(); - assertTrue('Control\'s element must be hidden', - control.getElement().style.display == 'none'); - } - - /** - * Tests {@link goog.ui.Control#getContentElement}. - */ - function testGetContentElement() { - assertNull('Unrendered control must not have a content element', - control.getContentElement()); - control.createDom(); - assertEquals('Control\'s content element must equal its root element', - control.getElement(), control.getContentElement()); - } - - /** - * Tests {@link goog.ui.Control#canDecorate}. - */ - function testCanDecorate() { - assertTrue(control.canDecorate(goog.dom.createElement('div'))); - } - - /** - * Tests {@link goog.ui.Control#decorateInternal}. - */ - function testDecorateInternal() { - sandbox.innerHTML = '<div id="foo">Hello, <b>World</b>!</div>'; - var foo = goog.dom.getElement('foo'); - control.decorate(foo); - assertEquals('Decorated control\'s element must have expected value', - foo, control.getElement()); - assertTrue('Element must be unselectable', - goog.style.isUnselectable(control.getElement())); - assertTrue('Element must be visible', - control.getElement().style.display != 'none'); - } - - /** - * Tests {@link goog.ui.Control#decorateInternal} with a control that - * allows text selection. - */ - function testDecorateInternalForSelectableControl() { - sandbox.innerHTML = '<div id="foo">Hello, <b>World</b>!</div>'; - var foo = goog.dom.getElement('foo'); - control.setAllowTextSelection(true); - control.decorate(foo); - assertEquals('Decorated control\'s element must have expected value', - foo, control.getElement()); - assertFalse('Element must be selectable', - goog.style.isUnselectable(control.getElement())); - assertTrue('Control must be visible', control.isVisible()); - } - - /** - * Tests {@link goog.ui.Control#decorateInternal} with a hidden element. - */ - function testDecorateInternalForHiddenElement() { - sandbox.innerHTML = '<div id="foo" style="display:none">Hello!</div>'; - var foo = goog.dom.getElement('foo'); - control.decorate(foo); - assertEquals('Decorated control\'s element must have expected value', - foo, control.getElement()); - assertTrue('Element must be unselectable', - goog.style.isUnselectable(control.getElement())); - assertFalse('Control must be hidden', control.isVisible()); - } - - /** - * Tests {@link goog.ui.Control#enterDocument}. - */ - function testEnterDocument() { - control.render(sandbox); - assertTrue('Control must be in the document', control.isInDocument()); - if (goog.userAgent.IE) { - assertEquals('Control must have 5 mouse & 3 key event listeners on IE', - 8, getListenerCount(control)); - } else { - assertEquals('Control must have 4 mouse and 3 key event listeners', 7, - getListenerCount(control)); - } - assertEquals('Control\'s key event handler must be attached to its ' + - 'key event target', control.getKeyEventTarget(), - control.getKeyHandler().element_); - } - - /** - * Tests {@link goog.ui.Control#enterDocument} for a control that doesn't - * handle mouse events. - */ - function testEnterDocumentForControlWithoutMouseHandling() { - control.setHandleMouseEvents(false); - control.render(sandbox); - assertTrue('Control must be in the document', control.isInDocument()); - assertEquals('Control must have 3 key event listeners', 3, - getListenerCount(control)); - assertEquals('Control\'s key event handler must be attached to its ' + - 'key event target', control.getKeyEventTarget(), - control.getKeyHandler().element_); - } - - /** - * Tests {@link goog.ui.Control#enterDocument} for a control that isn't - * focusable. - */ - function testEnterDocumentForNonFocusableControl() { - control.setSupportedState(goog.ui.Component.State.FOCUSED, false); - control.render(sandbox); - assertTrue('Control must be in the document', control.isInDocument()); - if (goog.userAgent.IE) { - assertEquals('Control must have 5 mouse event listeners on IE', 5, - getListenerCount(control)); - } else { - assertEquals('Control must have 4 mouse event listeners', 4, - getListenerCount(control)); - } - assertUndefined('Control must not have a key event handler', - control.keyHandler_); - } - - /** - * Tests {@link goog.ui.Control#enterDocument} for a control that doesn't - * need to do any event handling. - */ - function testEnterDocumentForControlWithoutEventHandlers() { - control.setHandleMouseEvents(false); - control.setSupportedState(goog.ui.Component.State.FOCUSED, false); - control.render(sandbox); - assertTrue('Control must be in the document', control.isInDocument()); - assertEquals('Control must have 0 event listeners', 0, - getListenerCount(control)); - assertUndefined('Control must not have an event handler', - control.googUiComponentHandler_); - assertUndefined('Control must not have a key event handler', - control.keyHandler_); - } - - /** - * Tests {@link goog.ui.Control#exitDocument}. - */ - function testExitDocument() { - control.render(sandbox); - assertTrue('Control must be in the document', control.isInDocument()); - if (goog.userAgent.IE) { - assertEquals('Control must have 5 mouse & 3 key event listeners on IE', - 8, getListenerCount(control)); - } else { - assertEquals('Control must have 4 mouse and 3 key event listeners', 7, - getListenerCount(control)); - } - assertEquals('Control\'s key event handler must be attached to its ' + - 'key event target', control.getKeyEventTarget(), - control.getKeyHandler().element_); - // Expected to fail on Mac Safari prior to version 527. - expectedFailures.expectFailureFor(isMacSafari3()); - try { - assertTrue('Control\'s element must support keyboard focus', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - } catch (e) { - expectedFailures.handleException(e); - } - - control.exitDocument(); - assertFalse('Control must no longer be in the document', - control.isInDocument()); - assertEquals('Control must have no event listeners', 0, - getListenerCount(control)); - assertNull('Control\'s key event handler must be unattached', - control.getKeyHandler().element_); - assertFalse('Control\'s element must no longer support keyboard focus', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - } - - /** - * Tests {@link goog.ui.Control#dispose}. - */ - function testDispose() { - control.render(sandbox); - var handler = control.getHandler(); - var keyHandler = control.getKeyHandler(); - control.dispose(); - assertFalse('Control must no longer be in the document', - control.isInDocument()); - assertTrue('Control must have been disposed of', control.isDisposed()); - assertUndefined('Renderer must have been deleted', control.getRenderer()); - assertNull('Content must be nulled out', control.getContent()); - assertTrue('Event handler must have been disposed of', - handler.isDisposed()); - assertUndefined('Event handler must have been deleted', - control.googUiComponentHandler_); - assertTrue('Key handler must have been disposed of', - keyHandler.isDisposed()); - assertUndefined('Key handler must have been deleted', - control.keyHandler_); - assertNull('Extra class names must have been nulled out', - control.getExtraClassNames()); - } - - /** - * Tests {@link goog.ui.Control#getContent}. - */ - function testGetContent() { - assertNull('Empty control must have null content', - (new goog.ui.Control(null)).getContent()); - assertEquals('Control must have expected content', 'Hello', - control.getContent()); - control.render(sandbox); - assertEquals('Control must have expected content after rendering', - 'Hello', control.getContent()); - } - - - /** - * Tests {@link goog.ui.Control#getContent}. - */ - function testGetContentForDecoratedControl() { - sandbox.innerHTML = - '<div id="empty"></div>\n' + - '<div id="text">Hello, world!</div>\n' + - '<div id="element"><span>Foo</span></div>\n' + - '<div id="nodelist">Hello, <b>world</b>!</div>\n'; - - var empty = new goog.ui.Control(null); - empty.decorate(goog.dom.getElement('empty')); - assertNull('Content of control decorating empty DIV must be null', - empty.getContent()); - empty.dispose(); - - var text = new goog.ui.Control(null); - text.decorate(goog.dom.getElement('text')); - assertEquals('Content of control decorating DIV with text contents ' + - 'must be as expected', 'Hello, world!', text.getContent().nodeValue); - text.dispose(); - - var element = new goog.ui.Control(null); - element.decorate(goog.dom.getElement('element')); - assertEquals('Content of control decorating DIV with element child ' + - 'must be as expected', goog.dom.getElement('element').firstChild, - element.getContent()); - element.dispose(); - - var nodelist = new goog.ui.Control(null); - nodelist.decorate(goog.dom.getElement('nodelist')); - assertSameElements('Content of control decorating DIV with mixed ' + - 'contents must be as expected', - goog.dom.getElement('nodelist').childNodes, nodelist.getContent()); - nodelist.dispose(); - } - - /** - * Tests {@link goog.ui.Control#setContent}. - */ - function testSetContent() { - control.setContent('Bye'); - assertEquals('Unrendered control control must have expected contents', - 'Bye', control.getContent()); - assertNull('No DOM must be created by setContent', control.getElement()); - - control.createDom(); - assertEquals('Rendered control\'s DOM must have expected contents', - 'Bye', control.getElement().innerHTML); - - control.setContent(null); - assertNull('Rendered control must have expected contents', - control.getContent()); - assertEquals('Rendered control\'s DOM must have expected contents', - '', control.getElement().innerHTML); - - control.setContent([goog.dom.createDom('div', null, - goog.dom.createDom('span', null, 'Hello')), 'World']); - assertHTMLEquals('Control\'s DOM must be updated', - '<div><span>Hello</span></div>World', control.getElement().innerHTML); - } - - /** - * Tests {@link goog.ui.Control#setContentInternal}. - */ - function testSetContentInternal() { - control.render(sandbox); - assertEquals('Control must have expected content after rendering', - 'Hello', control.getContent()); - control.setContentInternal('Bye'); - assertEquals('Control must have expected contents', - 'Bye', control.getContent()); - assertEquals('Control\'s DOM must be unchanged', 'Hello', - control.getElement().innerHTML); - } - - /** - * Tests {@link goog.ui.Control#getCaption}. - */ - function testGetCaption() { - assertEquals('Empty control\'s caption must be empty string', '', - (new goog.ui.Control(null)).getCaption()); - - assertEquals('Caption must have expected value', 'Hello', - control.getCaption()); - - sandbox.innerHTML = '<div id="nodelist">Hello, <b>world</b>!</div>'; - control.decorate(goog.dom.getElement('nodelist')); - assertEquals('Caption must have expected value', 'Hello, world!', - control.getCaption()); - - var arrayContent = goog.array.clone(goog.dom.htmlToDocumentFragment( - ' <b> foo</b><i> bar</i> ').childNodes); - control.setContent(arrayContent); - assertEquals('whitespaces must be normalized in the caption', - 'foo bar', control.getCaption()); - - control.setContent('\xa0foo'); - assertEquals('indenting spaces must be kept', '\xa0foo', - control.getCaption()); - } - - /** - * Tests {@link goog.ui.Control#setCaption}. - */ - function testSetCaption() { - control.setCaption('Hello, world!'); - assertEquals('Control must have a string caption "Hello, world!"', - 'Hello, world!', control.getCaption()); - } - - /** - * Tests {@link goog.ui.Control#setRightToLeft}. - */ - function testSetRightToLeft() { - control.createDom(); - assertFalse('Control\'s element must not have right-to-left class', - goog.dom.classes.has(control.getElement(), 'goog-control-rtl')); - control.setRightToLeft(true); - assertTrue('Control\'s element must have right-to-left class', - goog.dom.classes.has(control.getElement(), 'goog-control-rtl')); - control.render(sandbox); - assertThrows('Changing the render direction of a control already in ' + - 'the document is an error', - function() { - control.setRightToLeft(false); - }); - } - - /** - * Tests {@link goog.ui.Control#isAllowTextSelection}. - */ - function testIsAllowTextSelection() { - assertFalse('Controls must not allow text selection by default', - control.isAllowTextSelection()); - } - - /** - * Tests {@link goog.ui.Control#setAllowTextSelection}. - */ - function testSetAllowTextSelection() { - assertFalse('Controls must not allow text selection by default', - control.isAllowTextSelection()); - - control.setAllowTextSelection(true); - assertTrue('Control must allow text selection', - control.isAllowTextSelection()); - - control.setAllowTextSelection(false); - assertFalse('Control must no longer allow text selection', - control.isAllowTextSelection()); - - control.render(sandbox); - - assertFalse('Control must not allow text selection even after rendered', - control.isAllowTextSelection()); - - control.setAllowTextSelection(true); - assertTrue('Control must once again allow text selection', - control.isAllowTextSelection()); - } - - /** - * Tests {@link goog.ui.Control#isVisible}. - */ - function testIsVisible() { - assertTrue('Controls must be visible by default', control.isVisible()); - } - - /** - * Tests {@link goog.ui.Control#setVisible} before it is rendered. - */ - function testSetVisible() { - assertFalse('setVisible(true) must return false if already visible', - control.setVisible(true)); - assertTrue('No events must have been dispatched', noEventsDispatched()); - - assertTrue('setVisible(false) must return true if previously visible', - control.setVisible(false)); - assertEquals('One HIDE event must have been dispatched', - 1, getEventCount(control, goog.ui.Component.EventType.HIDE)); - assertFalse('Control must no longer be visible', control.isVisible()); - - assertTrue('setVisible(true) must return true if previously hidden', - control.setVisible(true)); - assertEquals('One SHOW event must have been dispatched', - 1, getEventCount(control, goog.ui.Component.EventType.SHOW)); - assertTrue('Control must be visible', control.isVisible()); - } - - /** - * Tests {@link goog.ui.Control#setVisible} after it is rendered. - */ - function testSetVisibleForRenderedControl() { - control.render(sandbox); - assertTrue('No events must have been dispatched during rendering', - noEventsDispatched()); - - assertFalse('setVisible(true) must return false if already visible', - control.setVisible(true)); - assertTrue('No events must have been dispatched', noEventsDispatched()); - assertTrue('Control\'s element must be visible', - control.getElement().style.display != 'none'); - - assertTrue('setVisible(false) must return true if previously visible', - control.setVisible(false)); - assertEquals('One HIDE event must have been dispatched', - 1, getEventCount(control, goog.ui.Component.EventType.HIDE)); - assertFalse('Control must no longer be visible', control.isVisible()); - assertTrue('Control\'s element must be hidden', - control.getElement().style.display == 'none'); - - assertTrue('setVisible(true) must return true if previously hidden', - control.setVisible(true)); - assertEquals('One SHOW event must have been dispatched', - 1, getEventCount(control, goog.ui.Component.EventType.SHOW)); - assertTrue('Control must be visible', control.isVisible()); - assertTrue('Control\'s element must be visible', - control.getElement().style.display != 'none'); - } - - /** - * Tests {@link goog.ui.Control#setVisible} for disabled non-focusable - * controls. - */ - function testSetVisibleForDisabledNonFocusableControl() { - // Hidden, disabled, non-focusable control becoming visible. - control.setEnabled(false); - control.setSupportedState(goog.ui.Component.State.FOCUSED, false); - control.render(sandbox); - assertTrue('Control must be visible', control.isVisible()); - assertFalse('Control must not have a tab index', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - - // Visible, disabled, non-focusable control becoming hidden. - control.getKeyEventTarget().focus(); - assertEquals('Control must not have dispatched FOCUS', 0, - getEventCount(control, goog.ui.Component.EventType.FOCUS)); - assertFalse('Control must not have keyboard focus', control.isFocused()); - control.setVisible(false); - assertFalse('Control must be hidden', control.isVisible()); - assertFalse('Control must not have a tab index', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - assertEquals('Control must have dispatched HIDE', 1, - getEventCount(control, goog.ui.Component.EventType.HIDE)); - assertEquals('Control must not have dispatched BLUR', 0, - getEventCount(control, goog.ui.Component.EventType.BLUR)); - } - - /** - * Tests {@link goog.ui.Control#setVisible} for disabled focusable controls. - */ - function testSetVisibleForDisabledFocusableControl() { - // Hidden, disabled, focusable control becoming visible. - control.setEnabled(false); - control.setSupportedState(goog.ui.Component.State.FOCUSED, true); - control.render(sandbox); - assertTrue('Control must be visible', control.isVisible()); - assertFalse('Control must not have a tab index', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - - // Visible, disabled, focusable control becoming hidden. - control.getKeyEventTarget().focus(); - assertEquals('Control must not have dispatched FOCUS', 0, - getEventCount(control, goog.ui.Component.EventType.FOCUS)); - assertFalse('Control must not have keyboard focus', control.isFocused()); - control.setVisible(false); - assertFalse('Control must be hidden', control.isVisible()); - assertFalse('Control must not have a tab index', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - assertEquals('Control must have dispatched HIDE', 1, - getEventCount(control, goog.ui.Component.EventType.HIDE)); - assertEquals('Control must not have dispatched BLUR', 0, - getEventCount(control, goog.ui.Component.EventType.BLUR)); - } - - /** - * Tests {@link goog.ui.Control#setVisible} for enabled non-focusable - * controls. - */ - function testSetVisibleForEnabledNonFocusableControl() { - // Hidden, enabled, non-focusable control becoming visible. - control.setEnabled(true); - control.setSupportedState(goog.ui.Component.State.FOCUSED, false); - control.render(sandbox); - assertTrue('Control must be visible', control.isVisible()); - assertFalse('Control must not have a tab index', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - - if (testFocus) { - // Visible, enabled, non-focusable control becoming hidden. - control.getKeyEventTarget().focus(); - assertEquals('Control must not have dispatched FOCUS', 0, - getEventCount(control, goog.ui.Component.EventType.FOCUS)); - assertFalse('Control must not have keyboard focus', - control.isFocused()); - control.setVisible(false); - assertFalse('Control must be hidden', control.isVisible()); - assertFalse('Control must not have a tab index', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - assertEquals('Control must have dispatched HIDE', 1, - getEventCount(control, goog.ui.Component.EventType.HIDE)); - assertEquals('Control must not have dispatched BLUR', 0, - getEventCount(control, goog.ui.Component.EventType.BLUR)); - } - } - - /** - * Tests {@link goog.ui.Control#setVisible} for enabled focusable controls. - */ - function testSetVisibleForEnabledFocusableControl() { - // Hidden, enabled, focusable control becoming visible. - control.setEnabled(true); - control.setSupportedState(goog.ui.Component.State.FOCUSED, true); - control.render(sandbox); - assertTrue('Control must be visible', control.isVisible()); - - if (testFocus) { - // Expected to fail on Mac Safari prior to version 527. - expectedFailures.expectFailureFor(isMacSafari3()); - try { - // Mac Safari currently doesn't support tabIndex on arbitrary - // elements. - assertTrue('Control must have a tab index', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - } catch (e) { - expectedFailures.handleException(e); - } - - // Visible, enabled, focusable control becoming hidden. - control.getKeyEventTarget().focus(); - - // Expected to fail on IE. - expectedFailures.expectFailureFor(goog.userAgent.IE); - try { - // IE dispatches focus and blur events asynchronously! - assertEquals('Control must have dispatched FOCUS', 1, - getEventCount(control, goog.ui.Component.EventType.FOCUS)); - assertTrue('Control must have keyboard focus', control.isFocused()); - } catch (e) { - expectedFailures.handleException(e); - } - - control.setVisible(false); - assertFalse('Control must be hidden', control.isVisible()); - assertFalse('Control must not have a tab index', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - assertEquals('Control must have dispatched HIDE', 1, - getEventCount(control, goog.ui.Component.EventType.HIDE)); - - // Expected to fail on IE. - expectedFailures.expectFailureFor(goog.userAgent.IE); - try { - // IE dispatches focus and blur events asynchronously! - assertEquals('Control must have dispatched BLUR', 1, - getEventCount(control, goog.ui.Component.EventType.BLUR)); - assertFalse('Control must no longer have keyboard focus', - control.isFocused()); - } catch (e) { - expectedFailures.handleException(e); - } - } - } - - /** - * Tests {@link goog.ui.Control#isEnabled}. - */ - function testIsEnabled() { - assertTrue('Controls must be enabled by default', control.isEnabled()); - } - - /** - * Tests {@link goog.ui.Control#setEnabled}. - */ - function testSetEnabled() { - control.render(sandbox); - control.setHighlighted(true); - control.setActive(true); - control.getKeyEventTarget().focus(); - - resetEventCount(); - - control.setEnabled(true); - assertTrue('No events must have been dispatched', noEventsDispatched()); - assertTrue('Control must be enabled', control.isEnabled()); - assertTrue('Control must be highlighted', control.isHighlighted()); - assertTrue('Control must be active', control.isActive()); - - if (testFocus) { - // Expected to fail on IE and Mac Safari 3. IE calls focus handlers - // asynchronously, and Mac Safari 3 doesn't support keyboard focus. - expectedFailures.expectFailureFor(goog.userAgent.IE); - expectedFailures.expectFailureFor(isMacSafari3()); - try { - assertTrue('Control must be focused', control.isFocused()); - } catch (e) { - expectedFailures.handleException(e); - } - } - - resetEventCount(); - - control.setEnabled(false); - assertEquals('One DISABLE event must have been dispatched', 1, - getEventCount(control, goog.ui.Component.EventType.DISABLE)); - assertFalse('Control must be disabled', control.isEnabled()); - assertFalse('Control must not be highlighed', control.isHighlighted()); - assertFalse('Control must not be active', control.isActive()); - assertFalse('Control must not be focused', control.isFocused()); - } - - /** - * Tests {@link goog.ui.Control#setEnabled} when the control has a parent. - */ - function testSetEnabledWithParent() { - var child = new goog.ui.Control(null); - child.setDispatchTransitionEvents(goog.ui.Component.State.ALL, true); - control.addChild(child, true /* opt_render */); - control.setEnabled(false); - - resetEventCount(); - - assertFalse('Parent must be disabled', control.isEnabled()); - assertTrue('Child must be enabled', child.isEnabled()); - - child.setEnabled(false); - assertTrue('No events must have been dispatched when child is disabled', - noEventsDispatched()); - assertTrue('Child must still be enabled', child.isEnabled()); - - resetEventCount(); - - control.setEnabled(true); - assertEquals('One ENABLE event must have been dispatched by the parent', - 1, getEventCount(control, goog.ui.Component.EventType.ENABLE)); - assertTrue('Parent must be enabled', control.isEnabled()); - assertTrue('Child must still be enabled', child.isEnabled()); - - resetEventCount(); - - child.setEnabled(false); - assertEquals('One DISABLE event must have been dispatched by the child', - 1, getEventCount(child, goog.ui.Component.EventType.DISABLE)); - assertTrue('Parent must still be enabled', control.isEnabled()); - assertFalse('Child must now be disabled', child.isEnabled()); - - resetEventCount(); - - control.setEnabled(false); - assertEquals('One DISABLE event must have been dispatched by the parent', - 1, getEventCount(control, goog.ui.Component.EventType.DISABLE)); - assertFalse('Parent must now be disabled', control.isEnabled()); - assertFalse('Child must still be disabled', child.isEnabled()); - - child.dispose(); - } - - /** - * Tests {@link goog.ui.Control#isHighlighted}. - */ - function testIsHighlighted() { - assertFalse('Controls must not be highlighted by default', - control.isHighlighted()); - } - - /** - * Tests {@link goog.ui.Control#setHighlighted}. - */ - function testSetHighlighted() { - control.setSupportedState(goog.ui.Component.State.HOVER, false); - - control.setHighlighted(true); - assertFalse('Control must not be highlighted, because it isn\'t ' + - 'highlightable', control.isHighlighted()); - assertTrue('Control must not have dispatched any events', - noEventsDispatched()); - - control.setSupportedState(goog.ui.Component.State.HOVER, true); - - control.setHighlighted(true); - assertTrue('Control must be highlighted', control.isHighlighted()); - assertEquals('Control must have dispatched a HIGHLIGHT event', 1, - getEventCount(control, goog.ui.Component.EventType.HIGHLIGHT)); - - control.setHighlighted(true); - assertTrue('Control must still be highlighted', control.isHighlighted()); - assertEquals('Control must not dispatch more HIGHLIGHT events', 1, - getEventCount(control, goog.ui.Component.EventType.HIGHLIGHT)); - - control.setHighlighted(false); - assertFalse('Control must not be highlighted', control.isHighlighted()); - assertEquals('Control must have dispatched an UNHIGHLIGHT event', 1, - getEventCount(control, goog.ui.Component.EventType.UNHIGHLIGHT)); - control.setEnabled(false); - assertFalse('Control must be disabled', control.isEnabled()); - - control.setHighlighted(true); - assertTrue('Control must be highlighted, even when disabled', - control.isHighlighted()); - assertEquals('Control must have dispatched another HIGHLIGHT event', 2, - getEventCount(control, goog.ui.Component.EventType.HIGHLIGHT)); - } - - /** - * Tests {@link goog.ui.Control#isActive}. - */ - function testIsActive() { - assertFalse('Controls must not be active by default', control.isActive()); - } - - /** - * Tests {@link goog.ui.Control#setActive}. - */ - function testSetActive() { - control.setSupportedState(goog.ui.Component.State.ACTIVE, false); - - control.setActive(true); - assertFalse('Control must not be active, because it isn\'t activateable', - control.isActive()); - assertTrue('Control must not have dispatched any events', - noEventsDispatched()); - - control.setSupportedState(goog.ui.Component.State.ACTIVE, true); - - control.setActive(true); - assertTrue('Control must be active', control.isActive()); - assertEquals('Control must have dispatched an ACTIVATE event', 1, - getEventCount(control, goog.ui.Component.EventType.ACTIVATE)); - - control.setActive(true); - assertTrue('Control must still be active', control.isActive()); - assertEquals('Control must not dispatch more ACTIVATE events', 1, - getEventCount(control, goog.ui.Component.EventType.ACTIVATE)); - - control.setEnabled(false); - assertFalse('Control must be disabled', control.isEnabled()); - assertFalse('Control must not be active', control.isActive()); - assertEquals('Control must have dispatched a DEACTIVATE event', 1, - getEventCount(control, goog.ui.Component.EventType.DEACTIVATE)); - } - - /** - * Tests disposing the control from an action event handler. - */ - function testDisposeOnAction() { - goog.events.listen(control, goog.ui.Component.EventType.ACTION, - function(e) { - control.dispose(); - }); - - // Control must not throw an exception if disposed of in an ACTION event - // handler. - control.performActionInternal(); - control.setActive(true); - assertTrue('Control should have been disposed of', control.isDisposed()); - } - - /** - * Tests {@link goog.ui.Control#isSelected}. - */ - function testIsSelected() { - assertFalse('Controls must not be selected by default', - control.isSelected()); - } - - /** - * Tests {@link goog.ui.Control#setSelected}. - */ - function testSetSelected() { - control.setSupportedState(goog.ui.Component.State.SELECTED, false); - - control.setSelected(true); - assertFalse('Control must not be selected, because it isn\'t selectable', - control.isSelected()); - assertTrue('Control must not have dispatched any events', - noEventsDispatched()); - - control.setSupportedState(goog.ui.Component.State.SELECTED, true); - - control.setSelected(true); - assertTrue('Control must be selected', control.isSelected()); - assertEquals('Control must have dispatched a SELECT event', 1, - getEventCount(control, goog.ui.Component.EventType.SELECT)); - - control.setSelected(true); - assertTrue('Control must still be selected', control.isSelected()); - assertEquals('Control must not dispatch more SELECT events', 1, - getEventCount(control, goog.ui.Component.EventType.SELECT)); - - control.setSelected(false); - assertFalse('Control must not be selected', control.isSelected()); - assertEquals('Control must have dispatched an UNSELECT event', 1, - getEventCount(control, goog.ui.Component.EventType.UNSELECT)); - control.setEnabled(false); - assertFalse('Control must be disabled', control.isEnabled()); - - control.setSelected(true); - assertTrue('Control must be selected, even when disabled', - control.isSelected()); - assertEquals('Control must have dispatched another SELECT event', 2, - getEventCount(control, goog.ui.Component.EventType.SELECT)); - } - - /** - * Tests {@link goog.ui.Control#isChecked}. - */ - function testIsChecked() { - assertFalse('Controls must not be checked by default', - control.isChecked()); - } - - /** - * Tests {@link goog.ui.Control#setChecked}. - */ - function testSetChecked() { - control.setSupportedState(goog.ui.Component.State.CHECKED, false); - - control.setChecked(true); - assertFalse('Control must not be checked, because it isn\'t checkable', - control.isChecked()); - assertTrue('Control must not have dispatched any events', - noEventsDispatched()); - - control.setSupportedState(goog.ui.Component.State.CHECKED, true); - - control.setChecked(true); - assertTrue('Control must be checked', control.isChecked()); - assertEquals('Control must have dispatched a CHECK event', 1, - getEventCount(control, goog.ui.Component.EventType.CHECK)); - - control.setChecked(true); - assertTrue('Control must still be checked', control.isChecked()); - assertEquals('Control must not dispatch more CHECK events', 1, - getEventCount(control, goog.ui.Component.EventType.CHECK)); - - control.setChecked(false); - assertFalse('Control must not be checked', control.isChecked()); - assertEquals('Control must have dispatched an UNCHECK event', 1, - getEventCount(control, goog.ui.Component.EventType.UNCHECK)); - control.setEnabled(false); - assertFalse('Control must be disabled', control.isEnabled()); - - control.setChecked(true); - assertTrue('Control must be checked, even when disabled', - control.isChecked()); - assertEquals('Control must have dispatched another CHECK event', 2, - getEventCount(control, goog.ui.Component.EventType.CHECK)); - } - - /** - * Tests {@link goog.ui.Control#isFocused}. - */ - function testIsFocused() { - assertFalse('Controls must not be focused by default', - control.isFocused()); - } - - /** - * Tests {@link goog.ui.Control#setFocused}. - */ - function testSetFocused() { - control.setSupportedState(goog.ui.Component.State.FOCUSED, false); - - control.setFocused(true); - assertFalse('Control must not be focused, because it isn\'t focusable', - control.isFocused()); - assertTrue('Control must not have dispatched any events', - noEventsDispatched()); - - control.setSupportedState(goog.ui.Component.State.FOCUSED, true); - - control.setFocused(true); - assertTrue('Control must be focused', control.isFocused()); - assertEquals('Control must have dispatched a FOCUS event', 1, - getEventCount(control, goog.ui.Component.EventType.FOCUS)); - - control.setFocused(true); - assertTrue('Control must still be focused', control.isFocused()); - assertEquals('Control must not dispatch more FOCUS events', 1, - getEventCount(control, goog.ui.Component.EventType.FOCUS)); - - control.setFocused(false); - assertFalse('Control must not be focused', control.isFocused()); - assertEquals('Control must have dispatched an BLUR event', 1, - getEventCount(control, goog.ui.Component.EventType.BLUR)); - control.setEnabled(false); - assertFalse('Control must be disabled', control.isEnabled()); - - control.setFocused(true); - assertTrue('Control must be focused, even when disabled', - control.isFocused()); - assertEquals('Control must have dispatched another FOCUS event', 2, - getEventCount(control, goog.ui.Component.EventType.FOCUS)); - } - - /** - * Tests {@link goog.ui.Control#isOpen}. - */ - function testIsOpen() { - assertFalse('Controls must not be open by default', control.isOpen()); - } - - /** - * Tests {@link goog.ui.Control#setOpen}. - */ - function testSetOpen() { - control.setSupportedState(goog.ui.Component.State.OPENED, false); - - control.setOpen(true); - assertFalse('Control must not be opened, because it isn\'t openable', - control.isOpen()); - assertTrue('Control must not have dispatched any events', - noEventsDispatched()); - - control.setSupportedState(goog.ui.Component.State.OPENED, true); - - control.setOpen(true); - assertTrue('Control must be opened', control.isOpen()); - assertEquals('Control must have dispatched a OPEN event', 1, - getEventCount(control, goog.ui.Component.EventType.OPEN)); - - control.setOpen(true); - assertTrue('Control must still be opened', control.isOpen()); - assertEquals('Control must not dispatch more OPEN events', 1, - getEventCount(control, goog.ui.Component.EventType.OPEN)); - - control.setOpen(false); - assertFalse('Control must not be opened', control.isOpen()); - assertEquals('Control must have dispatched an CLOSE event', 1, - getEventCount(control, goog.ui.Component.EventType.CLOSE)); - control.setEnabled(false); - assertFalse('Control must be disabled', control.isEnabled()); - - control.setOpen(true); - assertTrue('Control must be opened, even when disabled', - control.isOpen()); - assertEquals('Control must have dispatched another OPEN event', 2, - getEventCount(control, goog.ui.Component.EventType.OPEN)); - } - - /** - * Tests {@link goog.ui.Control#getState}. - */ - function testGetState() { - assertEquals('Controls must be in the default state', 0x00, - control.getState()); - } - - /** - * Tests {@link goog.ui.Control#hasState}. - */ - function testHasState() { - assertFalse('Control must not be disabled', - control.hasState(goog.ui.Component.State.DISABLED)); - assertFalse('Control must not be in the HOVER state', - control.hasState(goog.ui.Component.State.HOVER)); - assertFalse('Control must not be active', - control.hasState(goog.ui.Component.State.ACTIVE)); - assertFalse('Control must not be selected', - control.hasState(goog.ui.Component.State.SELECTED)); - assertFalse('Control must not be checked', - control.hasState(goog.ui.Component.State.CHECKED)); - assertFalse('Control must not be focused', - control.hasState(goog.ui.Component.State.FOCUSED)); - assertFalse('Control must not be open', - control.hasState(goog.ui.Component.State.OPEN)); - } - - /** - * Tests {@link goog.ui.Control#setState}. - */ - function testSetState() { - control.createDom(); - control.setSupportedState(goog.ui.Component.State.ACTIVE, false); - - assertFalse('Control must not be active', - control.hasState(goog.ui.Component.State.ACTIVE)); - control.setState(goog.ui.Component.State.ACTIVE, true); - assertFalse('Control must still be inactive (because it doesn\'t ' + - 'support the ACTIVE state)', - control.hasState(goog.ui.Component.State.ACTIVE)); - - control.setSupportedState(goog.ui.Component.State.ACTIVE, true); - - control.setState(goog.ui.Component.State.ACTIVE, true); - assertTrue('Control must be active', - control.hasState(goog.ui.Component.State.ACTIVE)); - assertTrue('Control must have the active CSS style', - goog.dom.classes.has(control.getElement(), 'goog-control-active')); - - control.setState(goog.ui.Component.State.ACTIVE, true); - assertTrue('Control must still be active', - control.hasState(goog.ui.Component.State.ACTIVE)); - assertTrue('Control must still have the active CSS style', - goog.dom.classes.has(control.getElement(), 'goog-control-active')); - - assertTrue('No events must have been dispatched', noEventsDispatched()); - } - - /** - * Tests {@link goog.ui.Control#setStateInternal}. - */ - function testSetStateInternal() { - control.setStateInternal(0x00); - assertEquals('State should be 0x00', 0x00, control.getState()); - control.setStateInternal(0x17); - assertEquals('State should be 0x17', 0x17, control.getState()); - } - - /** - * Tests {@link goog.ui.Control#isSupportedState}. - */ - function testIsSupportedState() { - assertTrue('Control must support DISABLED', - control.isSupportedState(goog.ui.Component.State.DISABLED)); - assertTrue('Control must support HOVER', - control.isSupportedState(goog.ui.Component.State.HOVER)); - assertTrue('Control must support ACTIVE', - control.isSupportedState(goog.ui.Component.State.ACTIVE)); - assertTrue('Control must support FOCUSED', - control.isSupportedState(goog.ui.Component.State.FOCUSED)); - assertFalse('Control must no support SELECTED', - control.isSupportedState(goog.ui.Component.State.SELECTED)); - assertFalse('Control must no support CHECKED', - control.isSupportedState(goog.ui.Component.State.CHECKED)); - assertFalse('Control must no support OPENED', - control.isSupportedState(goog.ui.Component.State.OPENED)); - } - - /** - * Tests {@link goog.ui.Control#setSupportedState}. - */ - function testSetSupportedState() { - control.setSupportedState(goog.ui.Component.State.HOVER, true); - assertTrue('Control must still support HOVER', - control.isSupportedState(goog.ui.Component.State.HOVER)); - - control.setSupportedState(goog.ui.Component.State.HOVER, false); - assertFalse('Control must no longer support HOVER', - control.isSupportedState(goog.ui.Component.State.HOVER)); - - control.setState(goog.ui.Component.State.ACTIVE, true); - control.setSupportedState(goog.ui.Component.State.ACTIVE, false); - assertFalse('Control must no longer support ACTIVE', - control.isSupportedState(goog.ui.Component.State.ACTIVE)); - assertFalse('Control must no longer be in the ACTIVE state', - control.hasState(goog.ui.Component.State.ACTIVE)); - - control.render(sandbox); - - control.setSupportedState(goog.ui.Component.State.FOCUSED, true); - control.setState(goog.ui.Component.State.FOCUSED, true); - - assertThrows('Must not be able to disable support for the FOCUSED ' + - "state for a control that's already in the document and focused", - function() { - control.setSupportedState(goog.ui.Component.State.FOCUSED, false); - }); - - assertTrue('No events must have been dispatched', noEventsDispatched()); - } - - - /** - * Tests {@link goog.ui.Control#isAutoState}. - */ - function testIsAutoState() { - assertTrue('Control must have DISABLED as an auto-state', - control.isAutoState(goog.ui.Component.State.DISABLED)); - assertTrue('Control must have HOVER as an auto-state', - control.isAutoState(goog.ui.Component.State.HOVER)); - assertTrue('Control must have ACTIVE as an auto-state', - control.isAutoState(goog.ui.Component.State.ACTIVE)); - assertTrue('Control must have FOCUSED as an auto-state', - control.isAutoState(goog.ui.Component.State.FOCUSED)); - - assertFalse('Control must not have SELECTED as an auto-state', - control.isAutoState(goog.ui.Component.State.SELECTED)); - assertFalse('Control must not have CHECKED as an auto-state', - control.isAutoState(goog.ui.Component.State.CHECKED)); - assertFalse('Control must not have OPENED as an auto-state', - control.isAutoState(goog.ui.Component.State.OPENED)); - - assertTrue('No events must have been dispatched', noEventsDispatched()); - } - - /** - * Tests {@link goog.ui.Control#setAutoStates}. - */ - function testSetAutoStates() { - control.setAutoStates(goog.ui.Component.State.HOVER, false); - assertFalse('Control must not have HOVER as an auto-state', - control.isAutoState(goog.ui.Component.State.HOVER)); - - control.setAutoStates(goog.ui.Component.State.ACTIVE | - goog.ui.Component.State.FOCUSED, false); - assertFalse('Control must not have ACTIVE as an auto-state', - control.isAutoState(goog.ui.Component.State.ACTIVE)); - assertFalse('Control must not have FOCUSED as an auto-state', - control.isAutoState(goog.ui.Component.State.FOCUSED)); - - control.setSupportedState(goog.ui.Component.State.FOCUSED, false); - control.setAutoStates(goog.ui.Component.State.FOCUSED, true); - assertFalse('Control must not have FOCUSED as an auto-state if it no ' + - 'longer supports FOCUSED', - control.isAutoState(goog.ui.Component.State.FOCUSED)); - - assertTrue('No events must have been dispatched', noEventsDispatched()); - } - - /** - * Tests {@link goog.ui.Control#isDispatchTransitionEvents}. - */ - function testIsDispatchTransitionEvents() { - assertTrue('Control must dispatch DISABLED transition events', - control.isDispatchTransitionEvents(goog.ui.Component.State.DISABLED)); - assertTrue('Control must dispatch HOVER transition events', - control.isDispatchTransitionEvents(goog.ui.Component.State.HOVER)); - assertTrue('Control must dispatch ACTIVE transition events', - control.isDispatchTransitionEvents(goog.ui.Component.State.ACTIVE)); - assertTrue('Control must dispatch FOCUSED transition events', - control.isDispatchTransitionEvents(goog.ui.Component.State.FOCUSED)); - - assertFalse('Control must not dispatch SELECTED transition events', - control.isDispatchTransitionEvents(goog.ui.Component.State.SELECTED)); - assertFalse('Control must not dispatch CHECKED transition events', - control.isDispatchTransitionEvents(goog.ui.Component.State.CHECKED)); - assertFalse('Control must not dispatch OPENED transition events', - control.isDispatchTransitionEvents(goog.ui.Component.State.OPENED)); - - assertTrue('No events must have been dispatched', noEventsDispatched()); - } - - /** - * Tests {@link goog.ui.Control#setDispatchTransitionEvents}. - */ - function testSetDispatchTransitionEvents() { - control.setDispatchTransitionEvents(goog.ui.Component.State.HOVER, false); - assertFalse('Control must not dispatch HOVER transition events', - control.isDispatchTransitionEvents(goog.ui.Component.State.HOVER)); - - control.setSupportedState(goog.ui.Component.State.SELECTED, true); - control.setDispatchTransitionEvents(goog.ui.Component.State.SELECTED, - true); - assertTrue('Control must dispatch SELECTED transition events', - control.isDispatchTransitionEvents(goog.ui.Component.State.SELECTED)); - - assertTrue('No events must have been dispatched', noEventsDispatched()); - } - - /** - * Tests {@link goog.ui.Control#isTransitionAllowed}. - */ - function testIsTransitionAllowed() { - assertTrue('Control must support the HOVER state', - control.isSupportedState(goog.ui.Component.State.HOVER)); - assertFalse('Control must not be in the HOVER state', - control.hasState(goog.ui.Component.State.HOVER)); - assertTrue('Control must dispatch HOVER transition events', - control.isDispatchTransitionEvents(goog.ui.Component.State.HOVER)); - - assertTrue('Control must be allowed to transition to the HOVER state', - control.isTransitionAllowed(goog.ui.Component.State.HOVER, true)); - assertEquals('Control must have dispatched one HIGHLIGHT event', 1, - getEventCount(control, goog.ui.Component.EventType.HIGHLIGHT)); - assertFalse('Control must not be highlighted', - control.hasState(goog.ui.Component.State.HOVER)); - - control.setState(goog.ui.Component.State.HOVER, true); - control.setDispatchTransitionEvents(goog.ui.Component.State.HOVER, false); - - assertTrue('Control must be allowed to transition from the HOVER state', - control.isTransitionAllowed(goog.ui.Component.State.HOVER, false)); - assertEquals('Control must not have dispatched any UNHIGHLIGHT events', 0, - getEventCount(control, goog.ui.Component.EventType.UNHIGHLIGHT)); - assertTrue('Control must still be highlighted', - control.hasState(goog.ui.Component.State.HOVER)); - - control.setSupportedState(goog.ui.Component.State.FOCUSED, false); - resetEventCount(); - - assertFalse('Control doesn\'t support the FOCUSED state', - control.isSupportedState(goog.ui.Component.State.FOCUSED)); - assertFalse('Control must not be FOCUSED', - control.hasState(goog.ui.Component.State.FOCUSED)); - assertFalse('Control must not be allowed to transition to the FOCUSED ' + - 'state', - control.isTransitionAllowed(goog.ui.Component.State.FOCUSED, true)); - assertEquals('Control must not have dispatched any FOCUS events', 0, - getEventCount(control, goog.ui.Component.EventType.FOCUS)); - - control.setEnabled(false); - resetEventCount(); - - assertTrue('Control must support the DISABLED state', - control.isSupportedState(goog.ui.Component.State.DISABLED)); - assertTrue('Control must be DISABLED', - control.hasState(goog.ui.Component.State.DISABLED)); - assertFalse('Control must not be allowed to transition to the DISABLED ' + - 'state, because it is already there', - control.isTransitionAllowed(goog.ui.Component.State.DISABLED, true)); - assertEquals('Control must not have dispatched any ENABLE events', 0, - getEventCount(control, goog.ui.Component.EventType.ENABLE)); - } - - /** - * Tests {@link goog.ui.Control#handleKeyEvent}. - */ - function testHandleKeyEvent() { - control.render(); - control.isVisible = control.isEnabled = function() { - return true; - }; - - - goog.testing.events.fireKeySequence( - control.getKeyEventTarget(), goog.events.KeyCodes.A); - - assertEquals('Control must not have dispatched an ACTION event', 0, - getEventCount(control, goog.ui.Component.EventType.ACTION)); - - goog.testing.events.fireKeySequence( - control.getKeyEventTarget(), goog.events.KeyCodes.ENTER); - assertEquals('Control must have dispatched an ACTION event', 1, - getEventCount(control, goog.ui.Component.EventType.ACTION)); - } - - - /** - * Tests {@link goog.ui.Control#performActionInternal}. - */ - function testPerformActionInternal() { - assertFalse('Control must not be checked', control.isChecked()); - assertFalse('Control must not be selected', control.isSelected()); - assertFalse('Control must not be open', control.isOpen()); - - control.performActionInternal(); - - assertFalse('Control must not be checked', control.isChecked()); - assertFalse('Control must not be selected', control.isSelected()); - assertFalse('Control must not be open', control.isOpen()); - assertEquals('Control must have dispatched an ACTION event', 1, - getEventCount(control, goog.ui.Component.EventType.ACTION)); - - control.setSupportedState(goog.ui.Component.State.CHECKED, true); - control.setSupportedState(goog.ui.Component.State.SELECTED, true); - control.setSupportedState(goog.ui.Component.State.OPENED, true); - - control.performActionInternal(); - - assertTrue('Control must be checked', control.isChecked()); - assertTrue('Control must be selected', control.isSelected()); - assertTrue('Control must be open', control.isOpen()); - assertEquals('Control must have dispatched a CHECK event', 1, - getEventCount(control, goog.ui.Component.EventType.CHECK)); - assertEquals('Control must have dispatched a SELECT event', 1, - getEventCount(control, goog.ui.Component.EventType.SELECT)); - assertEquals('Control must have dispatched a OPEN event', 1, - getEventCount(control, goog.ui.Component.EventType.OPEN)); - assertEquals('Control must have dispatched another ACTION event', 2, - getEventCount(control, goog.ui.Component.EventType.ACTION)); - - control.performActionInternal(); - - assertFalse('Control must not be checked', control.isChecked()); - assertTrue('Control must be selected', control.isSelected()); - assertFalse('Control must not be open', control.isOpen()); - assertEquals('Control must have dispatched an UNCHECK event', 1, - getEventCount(control, goog.ui.Component.EventType.UNCHECK)); - assertEquals('Control must not have dispatched an UNSELECT event', 0, - getEventCount(control, goog.ui.Component.EventType.UNSELECT)); - assertEquals('Control must have dispatched a CLOSE event', 1, - getEventCount(control, goog.ui.Component.EventType.CLOSE)); - assertEquals('Control must have dispatched another ACTION event', 3, - getEventCount(control, goog.ui.Component.EventType.ACTION)); - } - - /** - * Tests {@link goog.ui.Control#handleMouseOver}. - */ - function testHandleMouseOver() { - control.setContent(goog.dom.createDom('span', {id: 'caption'}, 'Hello')); - control.render(sandbox); - - var element = control.getElement(); - var caption = goog.dom.getElement('caption'); - - // Verify baseline assumptions. - assertTrue('Caption must be contained within the control', - goog.dom.contains(element, caption)); - assertTrue('Control must be enabled', control.isEnabled()); - assertTrue('HOVER must be an auto-state', - control.isAutoState(goog.ui.Component.State.HOVER)); - assertFalse('Control must not start out highlighted', - control.isHighlighted()); - - // Scenario 1: relatedTarget is contained within the control's DOM. - goog.testing.events.fireMouseOverEvent(element, caption); - assertTrue('No events must have been dispatched for internal mouse move', - noEventsDispatched()); - assertFalse('Control must not be highlighted for internal mouse move', - control.isHighlighted()); - resetEventCount(); - - // Scenario 2: preventDefault() is called on the ENTER event. - var key = goog.events.listen(control, goog.ui.Component.EventType.ENTER, - function(e) { - e.preventDefault(); - }); - goog.testing.events.fireMouseOverEvent(element, sandbox); - assertEquals('Control must have dispatched 1 ENTER event', 1, - getEventCount(control, goog.ui.Component.EventType.ENTER)); - assertFalse('Control must not be highlighted if ENTER is canceled', - control.isHighlighted()); - goog.events.unlistenByKey(key); - resetEventCount(); - - // Scenario 3: Control is disabled. - control.setEnabled(false); - goog.testing.events.fireMouseOverEvent(element, sandbox); - assertEquals('Control must dispatch ENTER event on mouseover even if ' + - 'disabled', 1, - getEventCount(control, goog.ui.Component.EventType.ENTER)); - assertFalse('Control must not be highlighted if it is disabled', - control.isHighlighted()); - control.setEnabled(true); - resetEventCount(); - - // Scenario 4: HOVER is not an auto-state. - control.setAutoStates(goog.ui.Component.State.HOVER, false); - goog.testing.events.fireMouseOverEvent(element, sandbox); - assertEquals('Control must dispatch ENTER event on mouseover even if ' + - 'HOVER is not an auto-state', 1, - getEventCount(control, goog.ui.Component.EventType.ENTER)); - assertFalse('Control must not be highlighted if HOVER isn\'t an auto-' + - 'state', control.isHighlighted()); - control.setAutoStates(goog.ui.Component.State.HOVER, true); - resetEventCount(); - - // Scenario 5: All is well. - goog.testing.events.fireMouseOverEvent(element, sandbox); - assertEquals('Control must dispatch ENTER event on mouseover', 1, - getEventCount(control, goog.ui.Component.EventType.ENTER)); - assertEquals('Control must dispatch HIGHLIGHT event on mouseover', 1, - getEventCount(control, goog.ui.Component.EventType.HIGHLIGHT)); - assertTrue('Control must be highlighted', control.isHighlighted()); - resetEventCount(); - - // Scenario 6: relatedTarget is null - control.setHighlighted(false); - goog.testing.events.fireMouseOverEvent(element, null); - assertEquals('Control must dispatch ENTER event on mouseover', 1, - getEventCount(control, goog.ui.Component.EventType.ENTER)); - assertEquals('Control must dispatch HIGHLIGHT event on mouseover', 1, - getEventCount(control, goog.ui.Component.EventType.HIGHLIGHT)); - assertTrue('Control must be highlighted', control.isHighlighted()); - resetEventCount(); - } - - /** - * Tests {@link goog.ui.Control#handleMouseOut}. - */ - function testHandleMouseOut() { - control.setContent(goog.dom.createDom('span', {id: 'caption'}, 'Hello')); - control.setHighlighted(true); - control.setActive(true); - - resetEventCount(); - - control.render(sandbox); - - var element = control.getElement(); - var caption = goog.dom.getElement('caption'); - - // Verify baseline assumptions. - assertTrue('Caption must be contained within the control', - goog.dom.contains(element, caption)); - assertTrue('Control must be enabled', control.isEnabled()); - assertTrue('HOVER must be an auto-state', - control.isAutoState(goog.ui.Component.State.HOVER)); - assertTrue('ACTIVE must be an auto-state', - control.isAutoState(goog.ui.Component.State.ACTIVE)); - assertTrue('Control must start out highlighted', control.isHighlighted()); - assertTrue('Control must start out active', control.isActive()); - - // Scenario 1: relatedTarget is contained within the control's DOM. - goog.testing.events.fireMouseOutEvent(element, caption); - assertTrue('No events must have been dispatched for internal mouse move', - noEventsDispatched()); - assertTrue('Control must not be un-highlighted for internal mouse move', - control.isHighlighted()); - assertTrue('Control must not be deactivated for internal mouse move', - control.isActive()); - resetEventCount(); - - // Scenario 2: preventDefault() is called on the LEAVE event. - var key = goog.events.listen(control, goog.ui.Component.EventType.LEAVE, - function(e) { - e.preventDefault(); - }); - goog.testing.events.fireMouseOutEvent(element, sandbox); - assertEquals('Control must have dispatched 1 LEAVE event', 1, - getEventCount(control, goog.ui.Component.EventType.LEAVE)); - assertTrue('Control must not be un-highlighted if LEAVE is canceled', - control.isHighlighted()); - assertTrue('Control must not be deactivated if LEAVE is canceled', - control.isActive()); - goog.events.unlistenByKey(key); - resetEventCount(); - - // Scenario 3: ACTIVE is not an auto-state. - control.setAutoStates(goog.ui.Component.State.ACTIVE, false); - goog.testing.events.fireMouseOutEvent(element, sandbox); - assertEquals('Control must dispatch LEAVE event on mouseout even if ' + - 'ACTIVE is not an auto-state', 1, - getEventCount(control, goog.ui.Component.EventType.LEAVE)); - assertTrue('Control must not be deactivated if ACTIVE isn\'t an auto-' + - 'state', control.isActive()); - assertFalse('Control must be un-highlighted even if ACTIVE isn\'t an ' + - 'auto-state', control.isHighlighted()); - control.setAutoStates(goog.ui.Component.State.ACTIVE, true); - control.setHighlighted(true); - resetEventCount(); - - // Scenario 4: HOVER is not an auto-state. - control.setAutoStates(goog.ui.Component.State.HOVER, false); - goog.testing.events.fireMouseOutEvent(element, sandbox); - assertEquals('Control must dispatch LEAVE event on mouseout even if ' + - 'HOVER is not an auto-state', 1, - getEventCount(control, goog.ui.Component.EventType.LEAVE)); - assertFalse('Control must be deactivated even if HOVER isn\'t an auto-' + - 'state', control.isActive()); - assertTrue('Control must not be un-highlighted if HOVER isn\'t an auto-' + - 'state', control.isHighlighted()); - control.setAutoStates(goog.ui.Component.State.HOVER, true); - control.setActive(true); - resetEventCount(); - - // Scenario 5: All is well. - goog.testing.events.fireMouseOutEvent(element, sandbox); - assertEquals('Control must dispatch LEAVE event on mouseout', 1, - getEventCount(control, goog.ui.Component.EventType.LEAVE)); - assertEquals('Control must dispatch DEACTIVATE event on mouseout', 1, - getEventCount(control, goog.ui.Component.EventType.DEACTIVATE)); - assertEquals('Control must dispatch UNHIGHLIGHT event on mouseout', 1, - getEventCount(control, goog.ui.Component.EventType.UNHIGHLIGHT)); - assertFalse('Control must be deactivated', control.isActive()); - assertFalse('Control must be unhighlighted', control.isHighlighted()); - resetEventCount(); - - // Scenario 6: relatedTarget is null - control.setActive(true); - control.setHighlighted(true); - goog.testing.events.fireMouseOutEvent(element, null); - assertEquals('Control must dispatch LEAVE event on mouseout', 1, - getEventCount(control, goog.ui.Component.EventType.LEAVE)); - assertEquals('Control must dispatch DEACTIVATE event on mouseout', 1, - getEventCount(control, goog.ui.Component.EventType.DEACTIVATE)); - assertEquals('Control must dispatch UNHIGHLIGHT event on mouseout', 1, - getEventCount(control, goog.ui.Component.EventType.UNHIGHLIGHT)); - assertFalse('Control must be deactivated', control.isActive()); - assertFalse('Control must be unhighlighted', control.isHighlighted()); - resetEventCount(); - } - - function testIsMouseEventWithinElement() { - var child = goog.dom.createElement('div'); - var parent = goog.dom.createDom('div', null, child); - var notChild = goog.dom.createElement('div'); - - var event = new goog.testing.events.Event('mouseout'); - event.relatedTarget = child; - assertTrue('Event is within element', - goog.ui.Control.isMouseEventWithinElement_(event, parent)); - - var event = new goog.testing.events.Event('mouseout'); - event.relatedTarget = notChild; - assertFalse('Event is not within element', - goog.ui.Control.isMouseEventWithinElement_(event, parent)); - } - - function testHandleMouseDown() { - control.render(sandbox); - assertFalse('preventDefault() must have been called for control that ' + - 'doesn\'t support text selection', - fireMouseDownAndFocus(control.getElement())); - assertTrue('Control must be highlighted', control.isHighlighted()); - assertTrue('Control must be active', control.isActive()); - - if (testFocus) { - // Expected to fail on IE and Mac Safari 3. IE calls focus handlers - // asynchronously, and Mac Safari 3 doesn't support keyboard focus. - expectedFailures.expectFailureFor(goog.userAgent.IE); - expectedFailures.expectFailureFor(isMacSafari3()); - try { - assertTrue('Control must be focused', control.isFocused()); - } catch (e) { - expectedFailures.handleException(e); - } - } - } - - function testHandleMouseDownForDisabledControl() { - control.setEnabled(false); - control.render(sandbox); - assertFalse('preventDefault() must have been called for control that ' + - 'doesn\'t support text selection', - fireMouseDownAndFocus(control.getElement())); - assertFalse('Control must not be highlighted', control.isHighlighted()); - assertFalse('Control must not be active', control.isActive()); - if (testFocus) { - assertFalse('Control must not be focused', control.isFocused()); - } - } - - function testHandleMouseDownForNoHoverAutoState() { - control.setAutoStates(goog.ui.Component.State.HOVER, false); - control.render(sandbox); - assertFalse('preventDefault() must have been called for control that ' + - 'doesn\'t support text selection', - fireMouseDownAndFocus(control.getElement())); - assertFalse('Control must not be highlighted', control.isHighlighted()); - assertTrue('Control must be active', control.isActive()); - - if (testFocus) { - // Expected to fail on IE and Mac Safari 3. IE calls focus handlers - // asynchronously, and Mac Safari 3 doesn't support keyboard focus. - expectedFailures.expectFailureFor(goog.userAgent.IE); - expectedFailures.expectFailureFor(isMacSafari3()); - try { - assertTrue('Control must be focused', control.isFocused()); - } catch (e) { - expectedFailures.handleException(e); - } - } - } - - function testHandleMouseDownForRightMouseButton() { - control.render(sandbox); - assertTrue('preventDefault() must not have been called for right ' + - 'mouse button', fireMouseDownAndFocus(control.getElement(), - goog.events.BrowserEvent.MouseButton.RIGHT)); - assertTrue('Control must be highlighted', control.isHighlighted()); - assertFalse('Control must not be active', control.isActive()); - - if (testFocus) { - // Expected to fail on IE and Mac Safari 3. IE calls focus handlers - // asynchronously, and Mac Safari 3 doesn't support keyboard focus. - expectedFailures.expectFailureFor(goog.userAgent.IE); - expectedFailures.expectFailureFor(isMacSafari3()); - try { - assertTrue('Control must be focused', control.isFocused()); - } catch (e) { - expectedFailures.handleException(e); - } - } - } - - function testHandleMouseDownForNoActiveAutoState() { - control.setAutoStates(goog.ui.Component.State.ACTIVE, false); - control.render(sandbox); - assertFalse('preventDefault() must have been called for control that ' + - 'doesn\'t support text selection', - fireMouseDownAndFocus(control.getElement())); - assertTrue('Control must be highlighted', control.isHighlighted()); - assertFalse('Control must not be active', control.isActive()); - - if (testFocus) { - // Expected to fail on IE and Mac Safari 3. IE calls focus handlers - // asynchronously, and Mac Safari 3 doesn't support keyboard focus. - expectedFailures.expectFailureFor(goog.userAgent.IE); - expectedFailures.expectFailureFor(isMacSafari3()); - try { - assertTrue('Control must be focused', control.isFocused()); - } catch (e) { - expectedFailures.handleException(e); - } - } - } - - function testHandleMouseDownForNonFocusableControl() { - control.setSupportedState(goog.ui.Component.State.FOCUSED, false); - control.render(sandbox); - assertFalse('preventDefault() must have been called for control that ' + - 'doesn\'t support text selection', - fireMouseDownAndFocus(control.getElement())); - assertTrue('Control must be highlighted', control.isHighlighted()); - assertTrue('Control must be active', control.isActive()); - assertFalse('Control must not be focused', control.isFocused()); - } - - // TODO(attila): Find out why this is flaky on FF2/Linux and FF1.5/Win. - //function testHandleMouseDownForSelectableControl() { - // control.setAllowTextSelection(true); - // control.render(sandbox); - // assertTrue('preventDefault() must not have been called for control ' + - // 'that supports text selection', - // fireMouseDownAndFocus(control.getElement())); - // assertTrue('Control must be highlighted', control.isHighlighted()); - // assertTrue('Control must be active', control.isActive()); - // // Expected to fail on IE and Mac Safari 3. IE calls focus handlers - // // asynchronously, and Mac Safari 3 doesn't support keyboard focus. - // expectedFailures.expectFailureFor(goog.userAgent.IE); - // expectedFailures.expectFailureFor(isMacSafari3()); - // try { - // assertTrue('Control must be focused', control.isFocused()); - // } catch (e) { - // expectedFailures.handleException(e); - // } - //} - - - /** - * Tests {@link goog.ui.Control#handleMouseUp}. - */ - function testHandleMouseUp() { - control.setActive(true); - - // Override performActionInternal() for testing purposes. - var actionPerformed = false; - control.performActionInternal = function() { - actionPerformed = true; - return true; - }; - - resetEventCount(); - - control.render(sandbox); - var element = control.getElement(); - - // Verify baseline assumptions. - assertTrue('Control must be enabled', control.isEnabled()); - assertTrue('HOVER must be an auto-state', - control.isAutoState(goog.ui.Component.State.HOVER)); - assertTrue('ACTIVE must be an auto-state', - control.isAutoState(goog.ui.Component.State.ACTIVE)); - assertFalse('Control must not start out highlighted', - control.isHighlighted()); - assertTrue('Control must start out active', control.isActive()); - - // Scenario 1: Control is disabled. - control.setEnabled(false); - goog.testing.events.fireMouseUpEvent(element); - assertFalse('Disabled control must not highlight on mouseup', - control.isHighlighted()); - assertFalse('No action must have been performed', actionPerformed); - control.setActive(true); - control.setEnabled(true); - - // Scenario 2: HOVER is not an auto-state. - control.setAutoStates(goog.ui.Component.State.HOVER, false); - goog.testing.events.fireMouseUpEvent(element); - assertFalse('Control must not highlight on mouseup if HOVER isn\'t an ' + - 'auto-state', control.isHighlighted()); - assertTrue('Action must have been performed even if HOVER isn\'t an ' + - 'auto-state', actionPerformed); - assertFalse('Control must have been deactivated on mouseup even if ' + - 'HOVER isn\'t an auto-state', control.isActive()); - actionPerformed = false; - control.setActive(true); - control.setAutoStates(goog.ui.Component.State.HOVER, true); - - // Scenario 3: Control is not active. - control.setActive(false); - goog.testing.events.fireMouseUpEvent(element); - assertTrue('Control must highlight on mouseup, even if inactive', - control.isHighlighted()); - assertFalse('No action must have been performed if control is inactive', - actionPerformed); - assertFalse('Inactive control must remain inactive after mouseup', - control.isActive()); - control.setHighlighted(false); - control.setActive(true); - - // Scenario 4: performActionInternal() returns false. - control.performActionInternal = function() { - actionPerformed = true; - return false; - }; - goog.testing.events.fireMouseUpEvent(element); - assertTrue('Control must highlight on mouseup, even if no action is ' + - 'performed', control.isHighlighted()); - assertTrue('performActionInternal must have been called', - actionPerformed); - assertTrue('Control must not deactivate if performActionInternal ' + - 'returns false', control.isActive()); - control.setHighlighted(false); - actionPerformed = false; - control.performActionInternal = function() { - actionPerformed = true; - return true; - }; - - // Scenario 5: ACTIVE is not an auto-state. - control.setAutoStates(goog.ui.Component.State.ACTIVE, false); - goog.testing.events.fireMouseUpEvent(element); - assertTrue('Control must highlight on mouseup even if ACTIVE isn\'t an ' + - 'auto-state', control.isHighlighted()); - assertTrue('Action must have been performed even if ACTIVE isn\'t an ' + - 'auto-state', actionPerformed); - assertTrue('Control must not have been deactivated on mouseup if ' + - 'ACTIVE isn\'t an auto-state', control.isActive()); - actionPerformed = false; - control.setHighlighted(false); - control.setAutoStates(goog.ui.Component.State.ACTIVE, true); - - // Scenario 6: All is well. - goog.testing.events.fireMouseUpEvent(element); - assertTrue('Control must highlight on mouseup', control.isHighlighted()); - assertTrue('Action must have been performed', actionPerformed); - assertFalse('Control must have been deactivated', control.isActive()); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/controlcontent.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/controlcontent.js.svn-base deleted file mode 100644 index c6f6571..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/controlcontent.js.svn-base +++ /dev/null @@ -1,28 +0,0 @@ -// 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 Type declaration for control content. - * - * @author nicksantos@google.com (Nick Santos) - */ -goog.provide('goog.ui.ControlContent'); - - -/** - * Type declaration for text caption or DOM structure to be used as the content - * of {@link goog.ui.Control}s. - * @typedef {string|Node|Array.<Node>|NodeList} - */ -goog.ui.ControlContent; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/controlrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/controlrenderer.js.svn-base deleted file mode 100644 index c88eac1..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/controlrenderer.js.svn-base +++ /dev/null @@ -1,844 +0,0 @@ -// 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.array'); -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.a11y.State'); -goog.require('goog.dom.classes'); -goog.require('goog.object'); -goog.require('goog.style'); -goog.require('goog.ui.Component.State'); -goog.require('goog.ui.ControlContent'); -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.dom.a11y.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.dom.a11y.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.dom.a11y.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.isEnabled()) { - this.updateAriaState(element, goog.ui.Component.State.DISABLED, - true); - } - if (control.isSelected()) { - this.updateAriaState(element, goog.ui.Component.State.SELECTED, - true); - } - 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.showElement(element, 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.dom.a11y.State.DISABLED, - goog.ui.Component.State.SELECTED, goog.dom.a11y.State.SELECTED, - goog.ui.Component.State.CHECKED, goog.dom.a11y.State.CHECKED, - goog.ui.Component.State.OPENED, goog.dom.a11y.State.EXPANDED); - } - var ariaState = goog.ui.ControlRenderer.ARIA_STATE_MAP_[state]; - if (ariaState) { - goog.dom.a11y.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_); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/controlrenderer_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/controlrenderer_test.html.svn-base deleted file mode 100644 index 3cf44e7..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/controlrenderer_test.html.svn-base +++ /dev/null @@ -1,985 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.ControlRenderer</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom.NodeType'); - goog.require('goog.dom.a11y'); - goog.require('goog.dom.a11y.Role'); - goog.require('goog.dom.a11y.State'); - goog.require('goog.dom.classes'); - goog.require('goog.style'); - goog.require('goog.testing.ExpectedFailures'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Component.State'); - goog.require('goog.ui.Control'); - goog.require('goog.ui.ControlRenderer'); - goog.require('goog.userAgent'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var control, controlRenderer, testRenderer; - var sandbox = goog.dom.getElement('sandbox'); - var expectedFailures = new goog.testing.ExpectedFailures(); - - /** - * A subclass of ControlRenderer that overrides {@code getAriaRole} and - * {@code getStructuralCssClass} for testing purposes. - * @constructor - * @extends {goog.ui.ControlRenderer} - */ - function TestRenderer() { - goog.ui.ControlRenderer.call(this); - }; - goog.inherits(TestRenderer, goog.ui.ControlRenderer); - goog.addSingletonGetter(TestRenderer); - - TestRenderer.CSS_CLASS = 'goog-button'; - - TestRenderer.IE6_CLASS_COMBINATIONS = [ - ['combined', 'goog-base-hover', 'goog-button'], - ['combined', 'goog-base-disabled', 'goog-button'], - ['combined', 'combined2', 'goog-base-hover', 'goog-base-rtl', - 'goog-button'] - ]; - - /** {@override} */ - TestRenderer.prototype.getAriaRole = function() { - return goog.dom.a11y.Role.BUTTON; - }; - - /** {@override} */ - TestRenderer.prototype.getCssClass = function() { - return TestRenderer.CSS_CLASS; - }; - - /** {@override} */ - TestRenderer.prototype.getStructuralCssClass = function() { - return 'goog-base'; - }; - - /** {@override} */ - TestRenderer.prototype.getIe6ClassCombinations = function() { - return TestRenderer.IE6_CLASS_COMBINATIONS; - }; - - /** - * @return {boolean} Whether we're on Mac Safari 3.x. - */ - function isMacSafari3() { - return goog.userAgent.WEBKIT && goog.userAgent.MAC && - !goog.userAgent.isVersion('527'); - } - - /** - * @return {boolean} Whether we're on IE6 or lower. - */ - function isIe6() { - return goog.userAgent.IE && !goog.userAgent.isVersion('7'); - } - - function setUp() { - control = new goog.ui.Control('Hello'); - controlRenderer = goog.ui.ControlRenderer.getInstance(); - testRenderer = TestRenderer.getInstance(); - } - - function tearDown() { - control.dispose(); - expectedFailures.handleTearDown(); - control = null; - controlRenderer = null; - testRenderer = null; - goog.dom.removeChildren(sandbox); - } - - function testConstructor() { - assertNotNull('ControlRenderer singleton instance must not be null', - controlRenderer); - assertNotNull('TestRenderer singleton instance must not be null', - testRenderer); - } - - function testGetCustomRenderer() { - var cssClass = 'special-css-class'; - var renderer = goog.ui.ControlRenderer.getCustomRenderer( - goog.ui.ControlRenderer, cssClass); - assertEquals( - 'Renderer should have returned the custom CSS class.', - cssClass, - renderer.getCssClass()); - } - - function testGetAriaRole() { - assertUndefined('ControlRenderer\'s ARIA role must be undefined', - controlRenderer.getAriaRole()); - assertEquals('TestRenderer\'s ARIA role must have expected value', - goog.dom.a11y.Role.BUTTON, testRenderer.getAriaRole()); - } - - function testCreateDom() { - assertHTMLEquals('ControlRenderer must create correct DOM', - '<div class="goog-control">Hello</div>', - goog.dom.getOuterHtml(controlRenderer.createDom(control))); - assertHTMLEquals('TestRenderer must create correct DOM', - '<div class="goog-button goog-base">Hello</div>', - goog.dom.getOuterHtml(testRenderer.createDom(control))); - } - - function testGetContentElement() { - assertEquals('getContentElement() must return its argument', sandbox, - controlRenderer.getContentElement(sandbox)); - } - - function testEnableExtraClassName() { - // enableExtraClassName() must be a no-op if control has no DOM. - controlRenderer.enableExtraClassName(control, 'foo', true); - - control.createDom(); - var element = control.getElement(); - - controlRenderer.enableExtraClassName(control, 'foo', true); - assertSameElements('Extra class name must have been added', - ['goog-control', 'foo'], goog.dom.classes.get(element)); - - controlRenderer.enableExtraClassName(control, 'foo', true); - assertSameElements('Enabling existing extra class name must be a no-op', - ['goog-control', 'foo'], goog.dom.classes.get(element)); - - controlRenderer.enableExtraClassName(control, 'bar', false); - assertSameElements('Disabling nonexistent class name must be a no-op', - ['goog-control', 'foo'], goog.dom.classes.get(element)); - - controlRenderer.enableExtraClassName(control, 'foo', false); - assertSameElements('Extra class name must have been removed', - ['goog-control'], goog.dom.classes.get(element)); - } - - function testCanDecorate() { - assertTrue('canDecorate() must return true', - controlRenderer.canDecorate()); - } - - function testDecorate() { - sandbox.innerHTML = '<div id="foo">Hello, world!</div>'; - var foo = goog.dom.getElement('foo'); - var element = controlRenderer.decorate(control, foo); - - assertEquals('decorate() must return its argument', foo, element); - assertEquals('Decorated control\'s ID must be set', 'foo', - control.getId()); - assertTrue('Decorated control\'s content must be a text node', - control.getContent().nodeType == goog.dom.NodeType.TEXT); - assertEquals('Decorated control\'s content must have expected value', - 'Hello, world!', control.getContent().nodeValue); - assertEquals('Decorated control\'s state must be as expected', 0x00, - control.getState()); - assertSameElements('Decorated element\'s classes must be as expected', - ['goog-control'], goog.dom.classes.get(element)); - } - - function testDecorateComplexDom() { - sandbox.innerHTML = '<div id="foo"><i>Hello</i>,<b>world</b>!</div>'; - var foo = goog.dom.getElement('foo'); - var element = controlRenderer.decorate(control, foo); - - assertEquals('decorate() must return its argument', foo, element); - assertEquals('Decorated control\'s ID must be set', 'foo', - control.getId()); - assertTrue('Decorated control\'s content must be an array', - goog.isArray(control.getContent())); - assertEquals('Decorated control\'s content must have expected length', 4, - control.getContent().length); - assertEquals('Decorated control\'s state must be as expected', 0x00, - control.getState()); - assertSameElements('Decorated element\'s classes must be as expected', - ['goog-control'], goog.dom.classes.get(element)); - } - - function testDecorateWithClasses() { - sandbox.innerHTML = - '<div id="foo" class="app goog-base-disabled goog-base-hover"></div>'; - var foo = goog.dom.getElement('foo'); - - control.addClassName('extra'); - var element = testRenderer.decorate(control, foo); - - assertEquals('decorate() must return its argument', foo, element); - assertEquals('Decorated control\'s ID must be set', 'foo', - control.getId()); - assertNull('Decorated control\'s content must be null', - control.getContent()); - assertEquals('Decorated control\'s state must be as expected', - goog.ui.Component.State.DISABLED | goog.ui.Component.State.HOVER, - control.getState()); - assertSameElements('Decorated element\'s classes must be as expected', [ - 'app', - 'extra', - 'goog-base', - 'goog-base-disabled', - 'goog-base-hover', - 'goog-button' - ], goog.dom.classes.get(element)); - } - - function testDecorateOptimization() { - // Temporarily replace goog.dom.classes.set(). - var goog$dom$classes$set = goog.dom.classes.set; - goog.dom.classes.set = function() { - fail('goog.dom.classes.set() must not be called'); - }; - - // Since foo has all required classes, goog.dom.classes.set() must not be - // called at all. - sandbox.innerHTML = '<div id="foo" class="goog-control">Foo</div>'; - controlRenderer.decorate(control, goog.dom.getElement('foo')); - - // Since bar has all required classes, goog.dom.classes.set() must not be - // called at all. - sandbox.innerHTML = '<div id="bar" class="goog-base goog-button">Bar' + - '</div>'; - testRenderer.decorate(control, goog.dom.getElement('bar')); - - // Since baz has all required classes, goog.dom.classes.set() must not be - // called at all. - sandbox.innerHTML = '<div id="baz" class="goog-base goog-button ' + - 'goog-button-disabled">Baz</div>'; - testRenderer.decorate(control, goog.dom.getElement('baz')); - - // Restore goog.dom.classes.set(). - goog.dom.classes.set = goog$dom$classes$set; - } - - function testInitializeDom() { - var renderer = new goog.ui.ControlRenderer(); - - // Replace setRightToLeft(). - renderer.setRightToLeft = function() { - fail('setRightToLeft() must not be called'); - }; - - // When a control with default render direction enters the document, - // setRightToLeft() must not be called. - control.setRenderer(renderer); - control.render(sandbox); - - // When a control in the default state (enabled, visible, focusable) - // enters the document, it must get a tab index. - // Expected to fail on Mac Safari 3, because it doesn't support tab index. - expectedFailures.expectFailureFor(isMacSafari3()); - try { - assertTrue('Enabled, visible, focusable control must have tab index', - goog.dom.isFocusableTabIndex(control.getElement())); - } catch (e) { - expectedFailures.handleException(e); - } - } - - function testInitializeDomDecorated() { - var renderer = new goog.ui.ControlRenderer(); - - // Replace setRightToLeft(). - renderer.setRightToLeft = function() { - fail('setRightToLeft() must not be called'); - }; - - sandbox.innerHTML = '<div id="foo" class="goog-control">Foo</div>'; - - // When a control with default render direction enters the document, - // setRightToLeft() must not be called. - control.setRenderer(renderer); - control.decorate(goog.dom.getElement('foo')); - - // When a control in the default state (enabled, visible, focusable) - // enters the document, it must get a tab index. - // Expected to fail on Mac Safari 3, because it doesn't support tab index. - expectedFailures.expectFailureFor(isMacSafari3()); - try { - assertTrue('Enabled, visible, focusable control must have tab index', - goog.dom.isFocusableTabIndex(control.getElement())); - } catch (e) { - expectedFailures.handleException(e); - } - } - - function testInitializeDomDisabledBiDi() { - var renderer = new goog.ui.ControlRenderer(); - - // Replace setFocusable(). - renderer.setFocusable = function() { - fail('setFocusable() must not be called'); - }; - - // When a disabled control enters the document, setFocusable() must not - // be called. - control.setEnabled(false); - control.setRightToLeft(true); - control.setRenderer(renderer); - control.render(sandbox); - - // When a right-to-left control enters the document, special stying must - // be applied. - assertSameElements('BiDi control must have right-to-left class', - ['goog-control', 'goog-control-disabled', 'goog-control-rtl'], - goog.dom.classes.get(control.getElement())); - } - - function testInitializeDomDisabledBiDiDecorated() { - var renderer = new goog.ui.ControlRenderer(); - - // Replace setFocusable(). - renderer.setFocusable = function() { - fail('setFocusable() must not be called'); - }; - - sandbox.innerHTML = - '<div dir="rtl">\n' + - ' <div id="foo" class="goog-control-disabled">Foo</div>\n' + - '</div>\n'; - - // When a disabled control enters the document, setFocusable() must not - // be called. - control.setRenderer(renderer); - control.decorate(goog.dom.getElement('foo')); - - // When a right-to-left control enters the document, special stying must - // be applied. - assertSameElements('BiDi control must have right-to-left class', - ['goog-control', 'goog-control-disabled', 'goog-control-rtl'], - goog.dom.classes.get(control.getElement())); - } - - function testSetAriaRole() { - sandbox.innerHTML = '<div id="foo">Foo</div><div id="bar">Bar</div>'; - - var foo = goog.dom.getElement('foo'); - controlRenderer.setAriaRole(foo); - assertEquals('ControlRenderer must not set ARIA role', '', - goog.dom.a11y.getRole(foo)); - - var bar = goog.dom.getElement('bar'); - testRenderer.setAriaRole(bar); - assertEquals('Element must have expected ARIA role', - goog.dom.a11y.Role.BUTTON, goog.dom.a11y.getRole(bar)); - } - - function testSetAllowTextSelection() { - sandbox.innerHTML = '<div id="foo"><span>Foo</span></div>'; - var foo = goog.dom.getElement('foo'); - - controlRenderer.setAllowTextSelection(foo, false); - assertTrue('Parent element must be unselectable on all browsers', - goog.style.isUnselectable(foo)); - if (goog.userAgent.IE || goog.userAgent.OPERA) { - assertTrue('On IE and Opera, child element must also be unselectable', - goog.style.isUnselectable(foo.firstChild)); - } else { - assertFalse('On browsers other than IE and Opera, the child element ' + - 'must not be unselectable', - goog.style.isUnselectable(foo.firstChild)); - } - - controlRenderer.setAllowTextSelection(foo, true); - assertFalse('Parent element must be selectable', - goog.style.isUnselectable(foo)); - assertFalse('Child element must be unselectable', - goog.style.isUnselectable(foo.firstChild)); - } - - function testSetRightToLeft() { - sandbox.innerHTML = '<div id="foo">Foo</div><div id="bar">Bar</div>'; - - var foo = goog.dom.getElement('foo'); - controlRenderer.setRightToLeft(foo, true); - assertSameElements('Element must have right-to-left class applied', - ['goog-control-rtl'], goog.dom.classes.get(foo)); - controlRenderer.setRightToLeft(foo, false); - assertSameElements('Element must not have right-to-left class applied', - [], goog.dom.classes.get(foo)); - - var bar = goog.dom.getElement('bar'); - testRenderer.setRightToLeft(bar, true); - assertSameElements('Element must have right-to-left class applied', - ['goog-base-rtl'], goog.dom.classes.get(bar)); - testRenderer.setRightToLeft(bar, false); - assertSameElements('Element must not have right-to-left class applied', - [], goog.dom.classes.get(bar)); - } - - function testIsFocusable() { - control.render(sandbox); - // Expected to fail on Mac Safari 3, because it doesn't support tab index. - expectedFailures.expectFailureFor(isMacSafari3()); - try { - assertTrue('Control\'s key event target must be focusable', - controlRenderer.isFocusable(control)); - } catch (e) { - expectedFailures.handleException(e); - } - } - - function testIsFocusableForNonFocusableControl() { - control.setSupportedState(goog.ui.Component.State.FOCUSED, false); - control.render(sandbox); - assertFalse('Non-focusable control\'s key event target must not be ' + - 'focusable', controlRenderer.isFocusable(control)); - } - - function testIsFocusableForControlWithoutKeyEventTarget() { - // Unrendered control has no key event target. - assertNull('Unrendered control must not have key event target', - control.getKeyEventTarget()); - assertFalse('isFocusable() must return null if no key event target', - controlRenderer.isFocusable(control)); - } - - function testSetFocusable() { - control.render(sandbox); - controlRenderer.setFocusable(control, false); - assertFalse('Control\'s key event target must not have tab index', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - controlRenderer.setFocusable(control, true); - // Expected to fail on Mac Safari 3, because it doesn't support tab index. - expectedFailures.expectFailureFor(isMacSafari3()); - try { - assertTrue('Control\'s key event target must have focusable tab index', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - } catch (e) { - expectedFailures.handleException(e); - } - } - - function testSetFocusableForNonFocusableControl() { - control.setSupportedState(goog.ui.Component.State.FOCUSED, false); - control.render(sandbox); - assertFalse('Non-focusable control\'s key event target must not be ' + - 'focusable', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - controlRenderer.setFocusable(control, true); - assertFalse('Non-focusable control\'s key event target must not be ' + - 'focusable, even after calling setFocusable(true)', - goog.dom.isFocusableTabIndex(control.getKeyEventTarget())); - } - - function testSetVisible() { - sandbox.innerHTML = '<div id="foo">Foo</div>'; - var foo = goog.dom.getElement('foo'); - assertTrue('Element must be visible', foo.style.display != 'none'); - controlRenderer.setVisible(foo, true); - assertTrue('Element must still be visible', foo.style.display != 'none'); - controlRenderer.setVisible(foo, false); - assertTrue('Element must be hidden', foo.style.display == 'none'); - } - - function testSetState() { - control.setRenderer(testRenderer); - control.createDom(); - var element = control.getElement(); - - assertSameElements('Control must have expected class names', - ['goog-button', 'goog-base'], goog.dom.classes.get(element)); - assertEquals('Control must not have disabled ARIA state', '', - goog.dom.a11y.getState(element, goog.dom.a11y.State.DISABLED)); - - testRenderer.setState(control, goog.ui.Component.State.DISABLED, true); - assertSameElements('Control must have disabled class name', - ['goog-button', 'goog-base', 'goog-base-disabled'], - goog.dom.classes.get(element)); - assertEquals('Control must have disabled ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.DISABLED)); - - testRenderer.setState(control, goog.ui.Component.State.DISABLED, false); - assertSameElements('Control must no longer have disabled class name', - ['goog-button', 'goog-base'], goog.dom.classes.get(element)); - assertEquals('Control must not have disabled ARIA state', - 'false', - goog.dom.a11y.getState(element, goog.dom.a11y.State.DISABLED)); - - testRenderer.setState(control, 0xFFFFFF, true); - assertSameElements('Class names must be unchanged for invalid state', - ['goog-button', 'goog-base'], goog.dom.classes.get(element)); - } - - function testUpdateAriaStateDisabled() { - control.createDom(); - var element = control.getElement(); - - controlRenderer.updateAriaState(element, goog.ui.Component.State.DISABLED, - true); - assertEquals('Control must have disabled ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.DISABLED)); - - controlRenderer.updateAriaState(element, goog.ui.Component.State.DISABLED, - false); - assertEquals('Control must no longer have disabled ARIA state', - 'false', - goog.dom.a11y.getState(element, goog.dom.a11y.State.DISABLED)); - } - - function testCreateDomAriaStateDisabled() { - control.setEnabled(false); - control.createDom(); - var element = control.getElement(); - - assertFalse('Control must be disabled', control.isEnabled()); - assertEquals('Control must have disabled ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.DISABLED)); - } - - function testDecorateAriaStateDisabled() { - sandbox.innerHTML = - '<div id="foo" class="app goog-base-disabled"></div>'; - var foo = goog.dom.getElement('foo'); - - var element = testRenderer.decorate(control, foo); - - assertFalse('Control must be disabled', control.isEnabled()); - assertEquals('Control must have disabled ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.DISABLED)); - } - - function testUpdateAriaStateSelected() { - control.createDom(); - var element = control.getElement(); - - controlRenderer.updateAriaState(element, goog.ui.Component.State.SELECTED, - true); - assertEquals('Control must have selected ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.SELECTED)); - - controlRenderer.updateAriaState(element, goog.ui.Component.State.SELECTED, - false); - assertEquals('Control must no longer have selected ARIA state', - 'false', - goog.dom.a11y.getState(element, goog.dom.a11y.State.SELECTED)); - } - - function testCreateDomAriaStateSelected() { - control.setSupportedState(goog.ui.Component.State.SELECTED, true); - control.setSelected(true); - - control.createDom(); - var element = control.getElement(); - - assertTrue('Control must be selected', control.isSelected()); - assertEquals('Control must have selected ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.SELECTED)); - } - - function testDecorateAriaStateSelected() { - sandbox.innerHTML = - '<div id="foo" class="app goog-base-selected"></div>'; - var foo = goog.dom.getElement('foo'); - - var element = testRenderer.decorate(control, foo); - - assertTrue('Control must be selected', control.isSelected()); - assertEquals('Control must have selected ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.SELECTED)); - } - - function testUpdateAriaStateChecked() { - control.createDom(); - var element = control.getElement(); - - controlRenderer.updateAriaState(element, goog.ui.Component.State.CHECKED, - true); - assertEquals('Control must have checked ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.CHECKED)); - - controlRenderer.updateAriaState(element, goog.ui.Component.State.CHECKED, - false); - assertEquals('Control must no longer have checked ARIA state', - 'false', - goog.dom.a11y.getState(element, goog.dom.a11y.State.CHECKED)); - } - - function testCreateDomAriaStateChecked() { - control.setSupportedState(goog.ui.Component.State.CHECKED, true); - control.setChecked(true); - - control.createDom(); - var element = control.getElement(); - - assertTrue('Control must be checked', control.isChecked()); - assertEquals('Control must have checked ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.CHECKED)); - } - - function testDecorateAriaStateChecked() { - sandbox.innerHTML = - '<div id="foo" class="app goog-base-checked"></div>'; - var foo = goog.dom.getElement('foo'); - - control.setSupportedState(goog.ui.Component.State.CHECKED, true); - var element = testRenderer.decorate(control, foo); - - assertTrue('Control must be checked', control.isChecked()); - assertEquals('Control must have checked ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.CHECKED)); - } - - function testUpdateAriaStateOpened() { - control.createDom(); - var element = control.getElement(); - - controlRenderer.updateAriaState(element, goog.ui.Component.State.OPENED, - true); - assertEquals('Control must have expanded ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.EXPANDED)); - - controlRenderer.updateAriaState(element, goog.ui.Component.State.OPENED, - false); - assertEquals('Control must no longer have expanded ARIA state', - 'false', - goog.dom.a11y.getState(element, goog.dom.a11y.State.EXPANDED)); - } - - function testCreateDomAriaStateOpened() { - control.setSupportedState(goog.ui.Component.State.OPENED, true); - control.setOpen(true); - - control.createDom(); - var element = control.getElement(); - - assertTrue('Control must be opened', control.isOpen()); - assertEquals('Control must have expanded ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.EXPANDED)); - } - - function testDecorateAriaStateOpened() { - sandbox.innerHTML = - '<div id="foo" class="app goog-base-open"></div>'; - var foo = goog.dom.getElement('foo'); - - control.setSupportedState(goog.ui.Component.State.OPENED, true); - var element = testRenderer.decorate(control, foo); - - assertTrue('Control must be opened', control.isOpen()); - assertEquals('Control must have expanded ARIA state', 'true', - goog.dom.a11y.getState(element, goog.dom.a11y.State.EXPANDED)); - } - - function testSetContent() { - sandbox.innerHTML = 'Hello, world!'; - controlRenderer.setContent(sandbox, 'Not so fast!'); - assertEquals('Element must contain expected text value', 'Not so fast!', - goog.dom.getTextContent(sandbox)); - } - - function testSetContentNull() { - sandbox.innerHTML = 'Hello, world!'; - controlRenderer.setContent(sandbox, null); - assertEquals('Element must have no child nodes', 0, - sandbox.childNodes.length); - assertEquals('Element must contain expected text value', '', - goog.dom.getTextContent(sandbox)); - } - - function testSetContentEmpty() { - sandbox.innerHTML = 'Hello, world!'; - controlRenderer.setContent(sandbox, ''); - assertEquals('Element must not have children', 0, - sandbox.childNodes.length); - assertEquals('Element must contain expected text value', '', - goog.dom.getTextContent(sandbox)); - } - - function testSetContentWhitespace() { - sandbox.innerHTML = 'Hello, world!'; - controlRenderer.setContent(sandbox, ' '); - assertEquals('Element must have one child', 1, - sandbox.childNodes.length); - assertEquals('Child must be a text node', goog.dom.NodeType.TEXT, - sandbox.firstChild.nodeType); - assertEquals('Element must contain expected text value', ' ', - goog.dom.getTextContent(sandbox)); - } - - function testSetContentTextNode() { - sandbox.innerHTML = 'Hello, world!'; - controlRenderer.setContent(sandbox, document.createTextNode('Text')); - assertEquals('Element must have one child', 1, - sandbox.childNodes.length); - assertEquals('Child must be a text node', goog.dom.NodeType.TEXT, - sandbox.firstChild.nodeType); - assertEquals('Element must contain expected text value', 'Text', - goog.dom.getTextContent(sandbox)); - } - - function testSetContentElementNode() { - sandbox.innerHTML = 'Hello, world!'; - controlRenderer.setContent(sandbox, - goog.dom.createDom('div', {id: 'foo'}, 'Foo')); - assertEquals('Element must have one child', 1, - sandbox.childNodes.length); - assertEquals('Child must be an element node', goog.dom.NodeType.ELEMENT, - sandbox.firstChild.nodeType); - assertHTMLEquals('Element must contain expected HTML', - '<div id="foo">Foo</div>', sandbox.innerHTML); - } - - function testSetContentArray() { - sandbox.innerHTML = 'Hello, world!'; - controlRenderer.setContent(sandbox, - ['Hello, ', goog.dom.createDom('b', null, 'world'), '!']); - assertEquals('Element must have three children', 3, - sandbox.childNodes.length); - assertEquals('1st child must be a text node', goog.dom.NodeType.TEXT, - sandbox.childNodes[0].nodeType); - assertEquals('2nd child must be an element', goog.dom.NodeType.ELEMENT, - sandbox.childNodes[1].nodeType); - assertEquals('3rd child must be a text node', goog.dom.NodeType.TEXT, - sandbox.childNodes[2].nodeType); - assertHTMLEquals('Element must contain expected HTML', - 'Hello, <b>world</b>!', sandbox.innerHTML); - } - - function testSetContentNodeList() { - sandbox.innerHTML = 'Hello, world!'; - var div = goog.dom.createDom('div', null, 'Hello, ', - goog.dom.createDom('b', null, 'world'), '!'); - controlRenderer.setContent(sandbox, div.childNodes); - assertEquals('Element must have three children', 3, - sandbox.childNodes.length); - assertEquals('1st child must be a text node', goog.dom.NodeType.TEXT, - sandbox.childNodes[0].nodeType); - assertEquals('2nd child must be an element', goog.dom.NodeType.ELEMENT, - sandbox.childNodes[1].nodeType); - assertEquals('3rd child must be a text node', goog.dom.NodeType.TEXT, - sandbox.childNodes[2].nodeType); - assertHTMLEquals('Element must contain expected HTML', - 'Hello, <b>world</b>!', sandbox.innerHTML); - } - - function testGetKeyEventTarget() { - assertNull('Key event target for unrendered control must be null', - controlRenderer.getKeyEventTarget(control)); - control.createDom(); - assertEquals('Key event target for rendered control must be its element', - control.getElement(), controlRenderer.getKeyEventTarget(control)); - } - - function testGetCssClass() { - assertEquals('ControlRenderer\'s CSS class must have expected value', - goog.ui.ControlRenderer.CSS_CLASS, controlRenderer.getCssClass()); - assertEquals('TestRenderer\'s CSS class must have expected value', - TestRenderer.CSS_CLASS, testRenderer.getCssClass()); - } - - function testGetStructuralCssClass() { - assertEquals('ControlRenderer\'s structural class must be its CSS class', - controlRenderer.getCssClass(), - controlRenderer.getStructuralCssClass()); - assertEquals('TestRenderer\'s structural class must have expected value', - 'goog-base', testRenderer.getStructuralCssClass()); - } - - function testGetClassNames() { - // These tests use assertArrayEquals, because the order is significant. - assertArrayEquals('ControlRenderer must return expected class names ' + - 'in the expected order', - ['goog-control'], - controlRenderer.getClassNames(control)); - assertArrayEquals('TestRenderer must return expected class names ' + - 'in the expected order', - ['goog-button', 'goog-base'], - testRenderer.getClassNames(control)); - } - - function testGetClassNamesForControlWithState() { - control.setStateInternal(goog.ui.Component.State.HOVER | - goog.ui.Component.State.ACTIVE); - - // These tests use assertArrayEquals, because the order is significant. - assertArrayEquals('ControlRenderer must return expected class names ' + - 'in the expected order', - ['goog-control', 'goog-control-hover', 'goog-control-active'], - controlRenderer.getClassNames(control)); - assertArrayEquals('TestRenderer must return expected class names ' + - 'in the expected order', - ['goog-button', 'goog-base', 'goog-base-hover', 'goog-base-active'], - testRenderer.getClassNames(control)); - } - - function testGetClassNamesForControlWithExtraClassNames() { - control.addClassName('foo'); - control.addClassName('bar'); - - // These tests use assertArrayEquals, because the order is significant. - assertArrayEquals('ControlRenderer must return expected class names ' + - 'in the expected order', - ['goog-control', 'foo', 'bar'], - controlRenderer.getClassNames(control)); - assertArrayEquals('TestRenderer must return expected class names ' + - 'in the expected order', - ['goog-button', 'goog-base', 'foo', 'bar'], - testRenderer.getClassNames(control)); - } - - function testGetClassNamesForControlWithStateAndExtraClassNames() { - control.setStateInternal(goog.ui.Component.State.HOVER | - goog.ui.Component.State.ACTIVE); - control.addClassName('foo'); - control.addClassName('bar'); - - // These tests use assertArrayEquals, because the order is significant. - assertArrayEquals('ControlRenderer must return expected class names ' + - 'in the expected order', [ - 'goog-control', - 'goog-control-hover', - 'goog-control-active', - 'foo', - 'bar' - ], controlRenderer.getClassNames(control)); - assertArrayEquals('TestRenderer must return expected class names ' + - 'in the expected order', [ - 'goog-button', - 'goog-base', - 'goog-base-hover', - 'goog-base-active', - 'foo', - 'bar' - ], testRenderer.getClassNames(control)); - } - - function testGetClassNamesForState() { - // These tests use assertArrayEquals, because the order is significant. - assertArrayEquals('ControlRenderer must return expected class names ' + - 'in the expected order', - ['goog-control-hover', 'goog-control-checked'], - controlRenderer.getClassNamesForState(goog.ui.Component.State.HOVER | - goog.ui.Component.State.CHECKED)); - assertArrayEquals('TestRenderer must return expected class names ' + - 'in the expected order', - ['goog-base-hover', 'goog-base-checked'], - testRenderer.getClassNamesForState(goog.ui.Component.State.HOVER | - goog.ui.Component.State.CHECKED)); - } - - function testGetClassForState() { - var renderer = new goog.ui.ControlRenderer(); - assertUndefined('State-to-class map must not exist until first use', - renderer.classByState_); - assertEquals('Renderer must return expected class name for SELECTED', - 'goog-control-selected', - renderer.getClassForState(goog.ui.Component.State.SELECTED)); - assertUndefined('Renderer must return undefined for invalid state', - renderer.getClassForState('foo')); - } - - function testGetStateFromClass() { - var renderer = new goog.ui.ControlRenderer(); - assertUndefined('Class-to-state map must not exist until first use', - renderer.stateByClass_); - assertEquals('Renderer must return expected state', - goog.ui.Component.State.SELECTED, - renderer.getStateFromClass('goog-control-selected')); - assertEquals('Renderer must return 0x00 for unknown class', - 0x00, - renderer.getStateFromClass('goog-control-annoyed')); - } - - function testIe6ClassCombinationsCreateDom() { - control.setRenderer(testRenderer); - - control.enableClassName('combined', true); - - control.createDom(); - var element = control.getElement(); - - testRenderer.setState(control, goog.ui.Component.State.DISABLED, true); - var expectedClasses = [ - 'combined', - 'goog-base', - 'goog-base-disabled', - 'goog-button' - ]; - if (isIe6()) { - assertSameElements('IE6 and lower should have one combined class', - expectedClasses.concat(['combined_goog-base-disabled_goog-button']), - goog.dom.classes.get(element)); - } else { - assertSameElements('Non IE6 browsers should not have a combined class', - expectedClasses, goog.dom.classes.get(element)); - } - - testRenderer.setState(control, goog.ui.Component.State.DISABLED, false); - testRenderer.setState(control, goog.ui.Component.State.HOVER, true); - var expectedClasses = [ - 'combined', - 'goog-base', - 'goog-base-hover', - 'goog-button' - ]; - if (isIe6()) { - assertSameElements('IE6 and lower should have one combined class', - expectedClasses.concat(['combined_goog-base-hover_goog-button']), - goog.dom.classes.get(element)); - } else { - assertSameElements('Non IE6 browsers should not have a combined class', - expectedClasses, goog.dom.classes.get(element)); - } - - testRenderer.setRightToLeft(element, true); - testRenderer.enableExtraClassName(control, 'combined2', true); - var expectedClasses = [ - 'combined', - 'combined2', - 'goog-base', - 'goog-base-hover', - 'goog-base-rtl', - 'goog-button' - ]; - if (isIe6()) { - assertSameElements('IE6 and lower should have two combined class', - expectedClasses.concat([ - 'combined_goog-base-hover_goog-button', - 'combined_combined2_goog-base-hover_goog-base-rtl_goog-button' - ]), goog.dom.classes.get(element)); - } else { - assertSameElements('Non IE6 browsers should not have a combined class', - expectedClasses, goog.dom.classes.get(element)); - } - - } - - function testIe6ClassCombinationsDecorate() { - sandbox.innerHTML = - '<div id="foo" class="combined goog-base-hover"></div>'; - var foo = goog.dom.getElement('foo'); - - var element = testRenderer.decorate(control, foo); - - var expectedClasses = [ - 'combined', - 'goog-base', - 'goog-base-hover', - 'goog-button' - ]; - if (isIe6()) { - assertSameElements('IE6 and lower should have one combined class', - expectedClasses.concat(['combined_goog-base-hover_goog-button']), - goog.dom.classes.get(element)); - } else { - assertSameElements('Non IE6 browsers should not have a combined class', - expectedClasses, goog.dom.classes.get(element)); - } - - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/cookieeditor.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/cookieeditor.js.svn-base deleted file mode 100644 index eaf8e5d..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/cookieeditor.js.svn-base +++ /dev/null @@ -1,182 +0,0 @@ -// 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 Displays and edits the value of a cookie. - * Intended only for debugging. - */ -goog.provide('goog.ui.CookieEditor'); - -goog.require('goog.dom'); -goog.require('goog.dom.TagName'); -goog.require('goog.events.EventType'); -goog.require('goog.net.cookies'); -goog.require('goog.string'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); - - - -/** - * Displays and edits the value of a cookie. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Component} - */ -goog.ui.CookieEditor = function(opt_domHelper) { - goog.base(this, opt_domHelper); -}; -goog.inherits(goog.ui.CookieEditor, goog.ui.Component); - - -/** - * Cookie key. - * @type {?string} - * @private - */ -goog.ui.CookieEditor.prototype.cookieKey_; - - -/** - * Text area. - * @type {HTMLTextAreaElement} - * @private - */ -goog.ui.CookieEditor.prototype.textAreaElem_; - - -/** - * Clear button. - * @type {HTMLButtonElement} - * @private - */ -goog.ui.CookieEditor.prototype.clearButtonElem_; - - -/** - * Invalid value warning text. - * @type {HTMLSpanElement} - * @private - */ -goog.ui.CookieEditor.prototype.valueWarningElem_; - - -/** - * Update button. - * @type {HTMLButtonElement} - * @private - */ -goog.ui.CookieEditor.prototype.updateButtonElem_; - - -// TODO(user): add combobox for user to select different cookies -/** - * Sets the cookie which this component will edit. - * @param {string} cookieKey Cookie key. - */ -goog.ui.CookieEditor.prototype.selectCookie = function(cookieKey) { - goog.asserts.assert(goog.net.cookies.isValidName(cookieKey)); - this.cookieKey_ = cookieKey; - if (this.textAreaElem_) { - this.textAreaElem_.value = goog.net.cookies.get(cookieKey) || ''; - } -}; - - -/** @override */ -goog.ui.CookieEditor.prototype.canDecorate = function() { - return false; -}; - - -/** @override */ -goog.ui.CookieEditor.prototype.createDom = function() { - // Debug-only, so we don't need i18n. - this.clearButtonElem_ = /** @type {HTMLButtonElement} */ (goog.dom.createDom( - goog.dom.TagName.BUTTON, /* attributes */ null, 'Clear')); - this.updateButtonElem_ = /** @type {HTMLButtonElement} */ (goog.dom.createDom( - goog.dom.TagName.BUTTON, /* attributes */ null, 'Update')); - var value = this.cookieKey_ && goog.net.cookies.get(this.cookieKey_); - this.textAreaElem_ = /** @type {HTMLTextAreaElement} */ (goog.dom.createDom( - goog.dom.TagName.TEXTAREA, /* attibutes */ null, value || '')); - this.valueWarningElem_ = /** @type {HTMLSpanElement} */ (goog.dom.createDom( - goog.dom.TagName.SPAN, /* attibutes */ { - 'style': 'display:none;color:red' - }, 'Invalid cookie value.')); - this.setElementInternal(goog.dom.createDom(goog.dom.TagName.DIV, - /* attibutes */ null, - this.valueWarningElem_, - goog.dom.createDom(goog.dom.TagName.BR), - this.textAreaElem_, - goog.dom.createDom(goog.dom.TagName.BR), - this.clearButtonElem_, - this.updateButtonElem_)); -}; - - -/** @override */ -goog.ui.CookieEditor.prototype.enterDocument = function() { - goog.base(this, 'enterDocument'); - this.getHandler().listen(this.clearButtonElem_, - goog.events.EventType.CLICK, - this.handleClear_); - this.getHandler().listen(this.updateButtonElem_, - goog.events.EventType.CLICK, - this.handleUpdate_); -}; - - -/** - * Handles user clicking clear button. - * @param {!goog.events.Event} e The click event. - * @private - */ -goog.ui.CookieEditor.prototype.handleClear_ = function(e) { - if (this.cookieKey_) { - goog.net.cookies.remove(this.cookieKey_); - } - this.textAreaElem_.value = ''; -}; - - -/** - * Handles user clicking update button. - * @param {!goog.events.Event} e The click event. - * @private - */ -goog.ui.CookieEditor.prototype.handleUpdate_ = function(e) { - if (this.cookieKey_) { - var value = this.textAreaElem_.value; - if (value) { - // Strip line breaks. - value = goog.string.stripNewlines(value); - } - if (goog.net.cookies.isValidValue(value)) { - goog.net.cookies.set(this.cookieKey_, value); - goog.style.showElement(this.valueWarningElem_, false); - } else { - goog.style.showElement(this.valueWarningElem_, true); - } - } -}; - - -/** @override */ -goog.ui.CookieEditor.prototype.disposeInternal = function() { - this.clearButtonElem_ = null; - this.cookieKey_ = null; - this.textAreaElem_ = null; - this.updateButtonElem_ = null; - this.valueWarningElem_ = null; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/cookieeditor_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/cookieeditor_test.html.svn-base deleted file mode 100644 index f95e1ce..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/cookieeditor_test.html.svn-base +++ /dev/null @@ -1,107 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2010 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. - ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.CookieEditor</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.dom.TagName'); - goog.require('goog.events.Event'); - goog.require('goog.events.EventType'); - goog.require('goog.net.cookies'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.CookieEditor'); -</script> -</head><body> -<div id=test_container></div> -<script> - var COOKIE_KEY = 'my_fabulous_cookie'; - var COOKIE_VALUES; - - goog.net.cookies.get = function(key) { - return COOKIE_VALUES[key]; - }; - - goog.net.cookies.set = function(key, value) { - return COOKIE_VALUES[key] = value; - }; - - goog.net.cookies.remove = function(key, value) { - delete COOKIE_VALUES[key]; - }; - - function setUp() { - goog.dom.removeChildren(goog.dom.getElement('test_container')); - COOKIE_VALUES = {}; - } - - function newCookieEditor(opt_cookieValue) { - // Set cookie. - if (opt_cookieValue) { - goog.net.cookies.set(COOKIE_KEY, opt_cookieValue); - } - - // Render editor. - var editor = new goog.ui.CookieEditor(); - editor.selectCookie(COOKIE_KEY); - editor.render(goog.dom.getElement('test_container')); - assertEquals('wrong text area value', opt_cookieValue || '', - editor.textAreaElem_.value || ''); - - return editor; - } - - function testRender() { - // Render editor. - var editor = newCookieEditor(); - - // All expected elements created? - var elem = editor.getElement(); - assertNotNullNorUndefined('missing element', elem); - assertNotNullNorUndefined('missing clear button', editor.clearButtonElem_); - assertNotNullNorUndefined('missing update button', - editor.updateButtonElem_); - assertNotNullNorUndefined('missing text area', editor.textAreaElem_); - } - - function testEditCookie() { - // Render editor. - var editor = newCookieEditor(); - - // Invalid value. - var newValue = 'my bad value;'; - editor.textAreaElem_.value = newValue; - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.CLICK, editor.updateButtonElem_)); - assertTrue('unexpected cookie value', !goog.net.cookies.get(COOKIE_KEY)); - - // Valid value. - newValue = 'my fabulous value'; - editor.textAreaElem_.value = newValue; - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.CLICK, editor.updateButtonElem_)); - assertEquals('wrong cookie value', newValue, - goog.net.cookies.get(COOKIE_KEY)); - } - - function testClearCookie() { - // Render editor. - var value = 'I will be cleared'; - var editor = newCookieEditor(value); - - // Clear value. - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.CLICK, editor.clearButtonElem_)); - assertTrue('unexpected cookie value', !goog.net.cookies.get(COOKIE_KEY)); - } -</script> -</body></html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/css3buttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/css3buttonrenderer.js.svn-base deleted file mode 100644 index 9761585..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/css3buttonrenderer.js.svn-base +++ /dev/null @@ -1,150 +0,0 @@ -// 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 alternative imageless button renderer that uses CSS3 rather - * than voodoo to render custom buttons with 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 - * - * Tested and verified to work in Gecko 1.9.2+ and WebKit 528+. - * - * @author eae@google.com (Emil A Eklund) - * @author slightlyoff@google.com (Alex Russell) - * @see ../demos/css3button.html - */ - -goog.provide('goog.ui.Css3ButtonRenderer'); - -goog.require('goog.dom'); -goog.require('goog.dom.TagName'); -goog.require('goog.dom.classes'); -goog.require('goog.ui.Button'); -goog.require('goog.ui.ButtonRenderer'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.INLINE_BLOCK_CLASSNAME'); -goog.require('goog.ui.registry'); - - - -/** - * Custom renderer for {@link goog.ui.Button}s. Css3 buttons can contain - * almost arbitrary HTML content, will flow like inline elements, but can be - * styled like block-level elements. - * - * @constructor - * @extends {goog.ui.ButtonRenderer} - */ -goog.ui.Css3ButtonRenderer = function() { - goog.ui.ButtonRenderer.call(this); -}; -goog.inherits(goog.ui.Css3ButtonRenderer, goog.ui.ButtonRenderer); - - -/** - * The singleton instance of this renderer class. - * @type {goog.ui.Css3ButtonRenderer?} - * @private - */ -goog.ui.Css3ButtonRenderer.instance_ = null; -goog.addSingletonGetter(goog.ui.Css3ButtonRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.Css3ButtonRenderer.CSS_CLASS = goog.getCssName('goog-css3-button'); - - -/** @override */ -goog.ui.Css3ButtonRenderer.prototype.getContentElement = function(element) { - return /** @type {Element} */ (element); -}; - - -/** - * Returns the button's contents wrapped in the following DOM structure: - * <div class="goog-inline-block goog-css3-button"> - * Contents... - * </div> - * Overrides {@link goog.ui.ButtonRenderer#createDom}. - * @param {goog.ui.Button} button Button to render. - * @return {Element} Root element for the button. - */ -goog.ui.Css3ButtonRenderer.prototype.createDom = function(button) { - var classNames = this.getClassNames(button); - var attr = { - 'class': goog.ui.INLINE_BLOCK_CLASSNAME + ' ' + classNames.join(' '), - 'title': button.getTooltip() || '' - }; - return button.getDomHelper().createDom('div', attr, button.getContent()); -}; - - -/** - * Returns true if this renderer can decorate the element. Overrides - * {@link goog.ui.ButtonRenderer#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. - */ -goog.ui.Css3ButtonRenderer.prototype.canDecorate = function(element) { - return element.tagName == goog.dom.TagName.DIV; -}; - - -/** @override */ -goog.ui.Css3ButtonRenderer.prototype.decorate = function(button, element) { - goog.dom.classes.add(element, goog.ui.INLINE_BLOCK_CLASSNAME, - this.getCssClass()); - return goog.ui.Css3ButtonRenderer.superClass_.decorate.call(this, button, - 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.Css3ButtonRenderer.prototype.getCssClass = function() { - return goog.ui.Css3ButtonRenderer.CSS_CLASS; -}; - - -// Register a decorator factory function for goog.ui.Css3ButtonRenderer. -goog.ui.registry.setDecoratorByClassName( - goog.ui.Css3ButtonRenderer.CSS_CLASS, - function() { - return new goog.ui.Button(null, - goog.ui.Css3ButtonRenderer.getInstance()); - }); - - -// Register a decorator factory function for toggle buttons using the -// goog.ui.Css3ButtonRenderer. -goog.ui.registry.setDecoratorByClassName( - goog.getCssName('goog-css3-toggle-button'), - function() { - var button = new goog.ui.Button(null, - goog.ui.Css3ButtonRenderer.getInstance()); - button.setSupportedState(goog.ui.Component.State.CHECKED, true); - return button; - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/css3menubuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/css3menubuttonrenderer.js.svn-base deleted file mode 100644 index 71da4ea..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/css3menubuttonrenderer.js.svn-base +++ /dev/null @@ -1,147 +0,0 @@ -// 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 alternative imageless button renderer that uses CSS3 rather - * than voodoo to render custom buttons with 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 - * - * Tested and verified to work in Gecko 1.9.2+ and WebKit 528+. - * - * @author eae@google.com (Emil A Eklund) - * @author slightlyoff@google.com (Alex Russell) - * @author dalewis@google.com (Darren Lewis) - * @see ../demos/css3menubutton.html - */ - -goog.provide('goog.ui.Css3MenuButtonRenderer'); - -goog.require('goog.dom'); -goog.require('goog.dom.TagName'); -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. Css3 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.Css3MenuButtonRenderer = function() { - goog.ui.MenuButtonRenderer.call(this); -}; -goog.inherits(goog.ui.Css3MenuButtonRenderer, goog.ui.MenuButtonRenderer); - - -/** - * The singleton instance of this renderer class. - * @type {goog.ui.Css3MenuButtonRenderer?} - * @private - */ -goog.ui.Css3MenuButtonRenderer.instance_ = null; -goog.addSingletonGetter(goog.ui.Css3MenuButtonRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.Css3MenuButtonRenderer.CSS_CLASS = goog.getCssName('goog-css3-button'); - - -/** @override */ -goog.ui.Css3MenuButtonRenderer.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. - */ -goog.ui.Css3MenuButtonRenderer.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-css3-button goog-css3-menu-button"> - * <div class="goog-css3-button-caption">Contents...</div> - * <div class="goog-css3-button-dropdown"></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.Css3MenuButtonRenderer.prototype.createButton = function(content, dom) { - var baseClass = this.getCssClass(); - var inlineBlock = goog.ui.INLINE_BLOCK_CLASSNAME + ' '; - return dom.createDom('div', inlineBlock, - dom.createDom('div', [goog.getCssName(baseClass, 'caption'), - goog.getCssName('goog-inline-block')], - content), - dom.createDom('div', [goog.getCssName(baseClass, 'dropdown'), - goog.getCssName('goog-inline-block')])); -}; - - -/** - * 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.Css3MenuButtonRenderer.prototype.getCssClass = function() { - return goog.ui.Css3MenuButtonRenderer.CSS_CLASS; -}; - - -// Register a decorator factory function for goog.ui.Css3MenuButtonRenderer. -// Since we're using goog-css3-button as the base class in order to get the -// same styling as goog.ui.Css3ButtonRenderer, we need to be explicit about -// giving goog-css3-menu-button here. -goog.ui.registry.setDecoratorByClassName( - goog.getCssName('goog-css3-menu-button'), - function() { - return new goog.ui.MenuButton(null, null, - goog.ui.Css3MenuButtonRenderer.getInstance()); - }); - diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/cssnames.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/cssnames.js.svn-base deleted file mode 100644 index 4ad5419..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/cssnames.js.svn-base +++ /dev/null @@ -1,29 +0,0 @@ -// 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 Common CSS class name constants. - * - * @author mkretzschmar@google.com (Martin Kretzschmar) - */ - -goog.provide('goog.ui.INLINE_BLOCK_CLASSNAME'); - - -/** - * CSS class name for applying the "display: inline-block" property in a - * cross-browser way. - * @type {string} - */ -goog.ui.INLINE_BLOCK_CLASSNAME = goog.getCssName('goog-inline-block'); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/custombutton.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/custombutton.js.svn-base deleted file mode 100644 index 9491387..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/custombutton.js.svn-base +++ /dev/null @@ -1,59 +0,0 @@ -// 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 button rendered via {@link goog.ui.CustomButtonRenderer}. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.CustomButton'); - -goog.require('goog.ui.Button'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.CustomButtonRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * A custom button control. Identical to {@link goog.ui.Button}, except it - * defaults its renderer to {@link goog.ui.CustomButtonRenderer}. One could - * just as easily pass {@code goog.ui.CustomButtonRenderer.getInstance()} to - * the {@link goog.ui.Button} constructor and get the same result. Provided - * for convenience. - * - * @param {goog.ui.ControlContent} content Text caption or existing DOM - * structure to display as the button's caption. - * @param {goog.ui.ButtonRenderer=} opt_renderer Optional 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.CustomButton = function(content, opt_renderer, opt_domHelper) { - goog.ui.Button.call(this, content, opt_renderer || - goog.ui.CustomButtonRenderer.getInstance(), opt_domHelper); -}; -goog.inherits(goog.ui.CustomButton, goog.ui.Button); - - -// Register a decorator factory function for goog.ui.CustomButtons. -goog.ui.registry.setDecoratorByClassName(goog.ui.CustomButtonRenderer.CSS_CLASS, - function() { - // CustomButton defaults to using CustomButtonRenderer. - return new goog.ui.CustomButton(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/custombuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/custombuttonrenderer.js.svn-base deleted file mode 100644 index cb69a2d..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/custombuttonrenderer.js.svn-base +++ /dev/null @@ -1,287 +0,0 @@ -// 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 custom button renderer that uses CSS voodoo to render a - * button-like object with fake rounded corners. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.CustomButtonRenderer'); - -goog.require('goog.dom'); -goog.require('goog.dom.classes'); -goog.require('goog.string'); -goog.require('goog.ui.ButtonRenderer'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.INLINE_BLOCK_CLASSNAME'); - - - -/** - * Custom renderer for {@link goog.ui.Button}s. Custom buttons can contain - * almost arbitrary HTML content, will flow like inline elements, but can be - * styled like block-level elements. - * - * @constructor - * @extends {goog.ui.ButtonRenderer} - */ -goog.ui.CustomButtonRenderer = function() { - goog.ui.ButtonRenderer.call(this); -}; -goog.inherits(goog.ui.CustomButtonRenderer, goog.ui.ButtonRenderer); -goog.addSingletonGetter(goog.ui.CustomButtonRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.CustomButtonRenderer.CSS_CLASS = goog.getCssName('goog-custom-button'); - - -/** - * Returns the button's contents wrapped in the following DOM structure: - * <div class="goog-inline-block goog-custom-button"> - * <div class="goog-inline-block goog-custom-button-outer-box"> - * <div class="goog-inline-block goog-custom-button-inner-box"> - * Contents... - * </div> - * </div> - * </div> - * Overrides {@link goog.ui.ButtonRenderer#createDom}. - * @param {goog.ui.Button} button Button to render. - * @return {Element} Root element for the button. - */ -goog.ui.CustomButtonRenderer.prototype.createDom = function(button) { - var classNames = this.getClassNames(button); - var attributes = { - 'class': goog.ui.INLINE_BLOCK_CLASSNAME + ' ' + classNames.join(' '), - 'title': button.getTooltip() || '' - }; - var buttonElement = button.getDomHelper().createDom('div', attributes, - this.createButton(button.getContent(), button.getDomHelper())); - - this.setAriaStates(button, buttonElement); - - return buttonElement; -}; - - -/** - * Returns the ARIA role to be applied to custom buttons. - * @return {goog.dom.a11y.Role|undefined} ARIA role. - * @override - */ -goog.ui.CustomButtonRenderer.prototype.getAriaRole = function() { - return goog.dom.a11y.Role.BUTTON; -}; - - -/** - * Sets the button's ARIA states. - * @param {!goog.ui.Button} button Button whose ARIA state will be updated. - * @param {!Element} element Element whose ARIA state is to be updated. - */ -goog.ui.CustomButtonRenderer.prototype.setAriaStates = function(button, - element) { - goog.asserts.assert(button); - goog.asserts.assert(element); - if (!button.isEnabled()) { - this.updateAriaState(element, goog.ui.Component.State.DISABLED, - true); - } - if (button.isSelected()) { - this.updateAriaState(element, goog.ui.Component.State.SELECTED, - true); - } - if (button.isSupportedState(goog.ui.Component.State.CHECKED)) { - this.updateAriaState(element, goog.ui.Component.State.CHECKED, - true); - } - if (button.isOpen()) { - this.updateAriaState(element, goog.ui.Component.State.OPENED, - true); - } -}; - - -/** - * 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 custom 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 (if any). - */ -goog.ui.CustomButtonRenderer.prototype.getContentElement = function(element) { - return element && /** @type {Element} */ (element.firstChild.firstChild); -}; - - -/** - * 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-custom-button-outer-box"> - * <div class="goog-inline-block goog-custom-button-inner-box"> - * Contents... - * </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. - */ -goog.ui.CustomButtonRenderer.prototype.createButton = function(content, dom) { - return dom.createDom('div', - goog.ui.INLINE_BLOCK_CLASSNAME + ' ' + - goog.getCssName(this.getCssClass(), 'outer-box'), - dom.createDom('div', - goog.ui.INLINE_BLOCK_CLASSNAME + ' ' + - goog.getCssName(this.getCssClass(), 'inner-box'), content)); -}; - - -/** - * Returns true if this renderer can decorate the element. Overrides - * {@link goog.ui.ButtonRenderer#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. - */ -goog.ui.CustomButtonRenderer.prototype.canDecorate = function(element) { - return element.tagName == 'DIV'; -}; - - -/** - * 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 - */ -goog.ui.CustomButtonRenderer.prototype.hasBoxStructure = function( - button, element) { - var outer = button.getDomHelper().getFirstElementChild(element); - if (outer && outer.className.indexOf(goog.getCssName(this.getCssClass(), - 'outer-box')) != -1) { - var inner = button.getDomHelper().getFirstElementChild(outer); - if (inner && inner.className.indexOf(goog.getCssName(this.getCssClass(), - 'inner-box')) != -1) { - // We have a proper box structure. - return true; - } - } - return false; -}; - - -/** - * Takes an existing element and decorates it with the custom button control. - * Initializes the control's ID, content, tooltip, value, and state based - * on the ID of the element, its child nodes, and its CSS classes, respectively. - * Returns the element. Overrides {@link goog.ui.ButtonRenderer#decorate}. - * @param {goog.ui.Button} button Button instance to decorate the element. - * @param {Element} element Element to decorate. - * @return {Element} Decorated element. - */ -goog.ui.CustomButtonRenderer.prototype.decorate = function(button, element) { - // Trim text nodes in the element's child node list; otherwise madness - // ensues (i.e. on Gecko, buttons will flicker and shift when moused over). - goog.ui.CustomButtonRenderer.trimTextNodes_(element, true); - goog.ui.CustomButtonRenderer.trimTextNodes_(element, false); - - // Create the buttom dom if it has not been created. - if (!this.hasBoxStructure(button, element)) { - element.appendChild( - this.createButton(element.childNodes, button.getDomHelper())); - } - - goog.dom.classes.add(element, - goog.ui.INLINE_BLOCK_CLASSNAME, this.getCssClass()); - return goog.ui.CustomButtonRenderer.superClass_.decorate.call(this, button, - element); -}; - - -/** - * Returns the CSS class to be applied to the root element of components - * rendered using this renderer. - * @return {string} Renderer-specific CSS class. - */ -goog.ui.CustomButtonRenderer.prototype.getCssClass = function() { - return goog.ui.CustomButtonRenderer.CSS_CLASS; -}; - - -/** - * Takes an element and removes leading or trailing whitespace from the start - * or the end of its list of child nodes. The Boolean argument determines - * whether to trim from the start or the end of the node list. Empty text - * nodes are removed, and the first non-empty text node is trimmed from the - * left or the right as appropriate. For example, - * <div class="goog-inline-block"> - * #text "" - * #text "\n Hello " - * <span>...</span> - * #text " World! \n" - * #text "" - * </div> - * becomes - * <div class="goog-inline-block"> - * #text "Hello " - * <span>...</span> - * #text " World!" - * </div> - * This is essential for Gecko, where leading/trailing whitespace messes with - * the layout of elements with -moz-inline-box (used in goog-inline-block), and - * optional but harmless for non-Gecko. - * - * @param {Element} element Element whose child node list is to be trimmed. - * @param {boolean} fromStart Whether to trim from the start or from the end. - * @private - */ -goog.ui.CustomButtonRenderer.trimTextNodes_ = function(element, fromStart) { - if (element) { - var node = fromStart ? element.firstChild : element.lastChild, next; - // Tag soup HTML may result in a DOM where siblings have different parents. - while (node && node.parentNode == element) { - // Get the next/previous sibling here, since the node may be removed. - next = fromStart ? node.nextSibling : node.previousSibling; - if (node.nodeType == goog.dom.NodeType.TEXT) { - // Found a text node. - var text = node.nodeValue; - if (goog.string.trim(text) == '') { - // Found an empty text node; remove it. - element.removeChild(node); - } else { - // Found a non-empty text node; trim from the start/end, then exit. - node.nodeValue = fromStart ? - goog.string.trimLeft(text) : goog.string.trimRight(text); - break; - } - } else { - // Found a non-text node; done. - break; - } - node = next; - } - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/customcolorpalette.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/customcolorpalette.js.svn-base deleted file mode 100644 index f541356..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/customcolorpalette.js.svn-base +++ /dev/null @@ -1,137 +0,0 @@ -// 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 color palette with a button for adding additional colors - * manually. - * - */ - -goog.provide('goog.ui.CustomColorPalette'); - -goog.require('goog.color'); -goog.require('goog.dom'); -goog.require('goog.ui.ColorPalette'); - - - -/** - * A custom color palette is a grid of color swatches and a button that allows - * the user to add additional colors to the palette - * - * @param {Array.<string>} initColors Array of initial colors to populate the - * palette with. - * @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.ColorPalette} - */ -goog.ui.CustomColorPalette = function(initColors, opt_renderer, opt_domHelper) { - goog.ui.ColorPalette.call(this, initColors, opt_renderer, opt_domHelper); - this.setSupportedState(goog.ui.Component.State.OPENED, true); -}; -goog.inherits(goog.ui.CustomColorPalette, goog.ui.ColorPalette); - - -/** - * Returns an array of DOM nodes for each color, and an additional cell with a - * '+'. - * @return {Array.<Node>} Array of div elements. - * @private - */ -goog.ui.CustomColorPalette.prototype.createColorNodes_ = function() { - /** @desc Hover caption for the button that allows the user to add a color. */ - var MSG_CLOSURE_CUSTOM_COLOR_BUTTON = goog.getMsg('Add a color'); - - var nl = goog.ui.CustomColorPalette.superClass_.createColorNodes_.call(this); - nl.push(goog.dom.createDom('div', { - 'class': goog.getCssName('goog-palette-customcolor'), - 'title': MSG_CLOSURE_CUSTOM_COLOR_BUTTON - }, '+')); - return nl; -}; - - -/** - * @override - * @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. - */ -goog.ui.CustomColorPalette.prototype.performActionInternal = function(e) { - var item = /** @type {Element} */ (this.getHighlightedItem()); - if (item) { - if (goog.dom.classes.has( - item, goog.getCssName('goog-palette-customcolor'))) { - // User activated the special "add custom color" swatch. - this.promptForCustomColor(); - } else { - // User activated a normal color swatch. - this.setSelectedItem(item); - return this.dispatchEvent(goog.ui.Component.EventType.ACTION); - } - } - return false; -}; - - -/** - * Prompts the user to enter a custom color. Currently uses a window.prompt - * but could be updated to use a dialog box with a WheelColorPalette. - */ -goog.ui.CustomColorPalette.prototype.promptForCustomColor = function() { - /** @desc Default custom color dialog. */ - var MSG_CLOSURE_CUSTOM_COLOR_PROMPT = goog.getMsg( - 'Input custom color, i.e. pink, #F00, #D015FF or rgb(100, 50, 25)'); - - // A CustomColorPalette is considered "open" while the color selection prompt - // is open. Enabling state transition events for the OPENED state and - // listening for OPEN events allows clients to save the selection before - // it is destroyed (see e.g. bug 1064701). - var response = null; - this.setOpen(true); - if (this.isOpen()) { - // The OPEN event wasn't canceled; prompt for custom color. - response = window.prompt(MSG_CLOSURE_CUSTOM_COLOR_PROMPT, '#FFFFFF'); - this.setOpen(false); - } - - if (!response) { - // The user hit cancel - return; - } - - var color; - /** @preserveTry */ - try { - color = goog.color.parse(response).hex; - } catch (er) { - /** @desc Alert message sent when the input string is not a valid color. */ - var MSG_CLOSURE_CUSTOM_COLOR_INVALID_INPUT = goog.getMsg( - 'ERROR: "{$color}" is not a valid color.', {'color': response}); - alert(MSG_CLOSURE_CUSTOM_COLOR_INVALID_INPUT); - return; - } - - // TODO(user): This is relatively inefficient. Consider adding - // functionality to palette to add individual items after render time. - var colors = this.getColors(); - colors.push(color); - this.setColors(colors); - - // Set the selected color to the new color and notify listeners of the action. - this.setSelectedColor(color); - this.dispatchEvent(goog.ui.Component.EventType.ACTION); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/customcolorpalette_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/customcolorpalette_test.html.svn-base deleted file mode 100644 index 4fedfa0..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/customcolorpalette_test.html.svn-base +++ /dev/null @@ -1,60 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>CustomColorPalette Unit Tests</title> - <script src="../base.js"></script> - <script src="../deps.js"></script> - <script> - goog.require('goog.dom.TagName'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.CustomColorPalette'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var samplePalette; - - function setUp() { - samplePalette = new goog.ui.CustomColorPalette(); - } - - function tearDown() { - samplePalette.dispose(); - document.getElementById('sandbox').innerHTML = ''; - } - - function testRender() { - samplePalette.render(document.getElementById('sandbox')); - - assertTrue('Palette must have been rendered', - samplePalette.isInDocument()); - - var elem = samplePalette.getElement(); - assertNotNull('The palette element should not be null', elem); - assertEquals('The palette element should have the right tag name', - goog.dom.TagName.DIV, elem.tagName); - - assertTrue('The custom color palette should have the right class name', - goog.dom.classes.has(elem, 'goog-palette')); - } - - function testSetColors() { - var colorSet = ['#e06666', '#f6b26b', '#ffd966', '#93c47d', '#76a5af', - '#6fa8dc', '#8e7cc3']; - samplePalette.setColors(colorSet); - assertSameElements('The palette should have the correct set of colors', - colorSet, samplePalette.getColors()); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/datepicker.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/datepicker.js.svn-base deleted file mode 100644 index f2a17f9..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/datepicker.js.svn-base +++ /dev/null @@ -1,1333 +0,0 @@ -// 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 Date picker implementation. - * - * @author eae@google.com (Emil A Eklund) - * @see ../demos/datepicker.html - */ - -goog.provide('goog.ui.DatePicker'); -goog.provide('goog.ui.DatePicker.Events'); -goog.provide('goog.ui.DatePickerEvent'); - -goog.require('goog.date'); -goog.require('goog.date.Date'); -goog.require('goog.date.Interval'); -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.classes'); -goog.require('goog.events'); -goog.require('goog.events.Event'); -goog.require('goog.events.EventType'); -goog.require('goog.events.KeyHandler'); -goog.require('goog.events.KeyHandler.EventType'); -goog.require('goog.i18n.DateTimeFormat'); -goog.require('goog.i18n.DateTimeSymbols'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); - - - -/** - * DatePicker widget. Allows a single date to be selected from a calendar like - * view. - * - * @param {goog.date.Date|Date=} opt_date Date to initialize the date picker - * with, defaults to the current date. - * @param {Object=} opt_dateTimeSymbols Date and time symbols to use. - * Defaults to goog.i18n.DateTimeSymbols if not set. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Component} - */ -goog.ui.DatePicker = function(opt_date, opt_dateTimeSymbols, opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - - /** - * Date and time symbols to use. - * @type {Object} - * @private - */ - this.symbols_ = opt_dateTimeSymbols || goog.i18n.DateTimeSymbols; - - this.wdayNames_ = this.symbols_.SHORTWEEKDAYS; - - /** - * Selected date. - * @type {goog.date.Date} - * @private - */ - this.date_ = new goog.date.Date(opt_date); - this.date_.setFirstWeekCutOffDay(this.symbols_.FIRSTWEEKCUTOFFDAY); - this.date_.setFirstDayOfWeek(this.symbols_.FIRSTDAYOFWEEK); - - /** - * Active month. - * @type {goog.date.Date} - * @private - */ - this.activeMonth_ = this.date_.clone(); - this.activeMonth_.setDate(1); - - /** - * Class names to apply to the weekday columns. - * @type {Array.<string>} - * @private - */ - this.wdayStyles_ = ['', '', '', '', '', '', '']; - this.wdayStyles_[this.symbols_.WEEKENDRANGE[0]] = - goog.getCssName(this.getBaseCssClass(), 'wkend-start'); - this.wdayStyles_[this.symbols_.WEEKENDRANGE[1]] = - goog.getCssName(this.getBaseCssClass(), 'wkend-end'); - - /** - * Object that is being used to cache key handlers. - * @type {Object} - * @private - */ - this.keyHandlers_ = {}; -}; -goog.inherits(goog.ui.DatePicker, goog.ui.Component); - - -/** - * Flag indicating if the number of weeks shown should be fixed. - * @type {boolean} - * @private - */ -goog.ui.DatePicker.prototype.showFixedNumWeeks_ = true; - - -/** - * Flag indicating if days from other months should be shown. - * @type {boolean} - * @private - */ -goog.ui.DatePicker.prototype.showOtherMonths_ = true; - - -/** - * Flag indicating if extra week(s) always should be added at the end. If not - * set the extra week is added at the beginning if the number of days shown - * from the previous month is less then the number from the next month. - * @type {boolean} - * @private - */ -goog.ui.DatePicker.prototype.extraWeekAtEnd_ = true; - - -/** - * Flag indicating if week numbers should be shown. - * @type {boolean} - * @private - */ -goog.ui.DatePicker.prototype.showWeekNum_ = true; - - -/** - * Flag indicating if weekday names should be shown. - * @type {boolean} - * @private - */ -goog.ui.DatePicker.prototype.showWeekdays_ = true; - - -/** - * Flag indicating if none is a valid selection. Also controls if the none - * button should be shown or not. - * @type {boolean} - * @private - */ -goog.ui.DatePicker.prototype.allowNone_ = true; - - -/** - * Flag indicating if the today button should be shown. - * @type {boolean} - * @private - */ -goog.ui.DatePicker.prototype.showToday_ = true; - - -/** - * Flag indicating if the picker should use a simple navigation menu that only - * contains controls for navigating to the next and previous month. The default - * navigation menu contains controls for navigating to the next/previous month, - * next/previous year, and menus for jumping to specific months and years. - * @type {boolean} - * @private - */ -goog.ui.DatePicker.prototype.simpleNavigation_ = false; - - -/** - * Custom decorator function. Takes a goog.date.Date object, returns a String - * representing a CSS class or null if no special styling applies - * @type {Function} - * @private - */ -goog.ui.DatePicker.prototype.decoratorFunction_ = null; - - -/** - * Element for navigation row on a datepicker. - * @type {Element} - * @private - */ -goog.ui.DatePicker.prototype.elNavRow_ = null; - - -/** - * Element for footer row on a datepicker. - * @type {Element} - * @private - */ -goog.ui.DatePicker.prototype.elFootRow_ = null; - - -/** - * Next unique instance ID of a datepicker cell. - * @type {number} - * @private - */ -goog.ui.DatePicker.nextId_ = 0; - - -/** - * Name of base CSS clase of datepicker. - * @type {string} - * @private - */ -goog.ui.DatePicker.BASE_CSS_CLASS_ = goog.getCssName('goog-date-picker'); - - -/** - * Constants for event names - * - * @type {Object} - */ -goog.ui.DatePicker.Events = { - CHANGE: 'change', - SELECT: 'select' -}; - - -/** - * @deprecated Use isInDocument. - */ -goog.ui.DatePicker.prototype.isCreated = - goog.ui.DatePicker.prototype.isInDocument; - - -/** - * @return {number} The first day of week, 0 = Monday, 6 = Sunday. - */ -goog.ui.DatePicker.prototype.getFirstWeekday = function() { - return this.activeMonth_.getFirstDayOfWeek(); -}; - - -/** - * Returns the class name associated with specified weekday. - * @param {number} wday The week day number to get the class name for. - * @return {string} The class name associated with specified weekday. - */ -goog.ui.DatePicker.prototype.getWeekdayClass = function(wday) { - return this.wdayStyles_[wday]; -}; - - -/** - * @return {boolean} Whether a fixed number of weeks should be showed. If not - * only weeks for the current month will be shown. - */ -goog.ui.DatePicker.prototype.getShowFixedNumWeeks = function() { - return this.showFixedNumWeeks_; -}; - - -/** - * @return {boolean} Whether a days from the previous and/or next month should - * be shown. - */ -goog.ui.DatePicker.prototype.getShowOtherMonths = function() { - return this.showOtherMonths_; -}; - - -/** - * @return {boolean} Whether a the extra week(s) added always should be at the - * end. Only applicable if a fixed number of weeks are shown. - */ -goog.ui.DatePicker.prototype.getExtraWeekAtEnd = function() { - return this.extraWeekAtEnd_; -}; - - -/** - * @return {boolean} Whether week numbers should be shown. - */ -goog.ui.DatePicker.prototype.getShowWeekNum = function() { - return this.showWeekNum_; -}; - - -/** - * @return {boolean} Whether weekday names should be shown. - */ -goog.ui.DatePicker.prototype.getShowWeekdayNames = function() { - return this.showWeekdays_; -}; - - -/** - * @return {boolean} Whether none is a valid selection. - */ -goog.ui.DatePicker.prototype.getAllowNone = function() { - return this.allowNone_; -}; - - -/** - * @return {boolean} Whether the today button should be shown. - */ -goog.ui.DatePicker.prototype.getShowToday = function() { - return this.showToday_; -}; - - -/** - * Returns base CSS class. This getter is used to get base CSS class part. - * All CSS class names in component are created as: - * goog.getCssName(this.getBaseCssClass(), 'CLASS_NAME') - * @return {string} Base CSS class. - */ -goog.ui.DatePicker.prototype.getBaseCssClass = function() { - return goog.ui.DatePicker.BASE_CSS_CLASS_; -}; - - -/** - * Sets the first day of week - * - * @param {number} wday Week day, 0 = Monday, 6 = Sunday. - */ -goog.ui.DatePicker.prototype.setFirstWeekday = function(wday) { - this.activeMonth_.setFirstDayOfWeek(wday); - this.updateCalendarGrid_(); - this.redrawWeekdays_(); -}; - - -/** - * Sets class name associated with specified weekday. - * - * @param {number} wday Week day, 0 = Monday, 6 = Sunday. - * @param {string} className Class name. - */ -goog.ui.DatePicker.prototype.setWeekdayClass = function(wday, className) { - this.wdayStyles_[wday] = className; - this.redrawCalendarGrid_(); -}; - - -/** - * Sets whether a fixed number of weeks should be showed. If not only weeks - * for the current month will be showed. - * - * @param {boolean} b Whether a fixed number of weeks should be showed. - */ -goog.ui.DatePicker.prototype.setShowFixedNumWeeks = function(b) { - this.showFixedNumWeeks_ = b; - this.updateCalendarGrid_(); -}; - - -/** - * Sets whether a days from the previous and/or next month should be shown. - * - * @param {boolean} b Whether a days from the previous and/or next month should - * be shown. - */ -goog.ui.DatePicker.prototype.setShowOtherMonths = function(b) { - this.showOtherMonths_ = b; - this.redrawCalendarGrid_(); -}; - - -/** - * Sets whether the picker should use a simple navigation menu that only - * contains controls for navigating to the next and previous month. The default - * navigation menu contains controls for navigating to the next/previous month, - * next/previous year, and menus for jumping to specific months and years. - * - * @param {boolean} b Whether to use a simple navigation menu. - */ -goog.ui.DatePicker.prototype.setUseSimpleNavigationMenu = function(b) { - this.simpleNavigation_ = b; - this.updateNavigationRow_(); - this.updateCalendarGrid_(); -}; - - -/** - * Sets whether a the extra week(s) added always should be at the end. Only - * applicable if a fixed number of weeks are shown. - * - * @param {boolean} b Whether a the extra week(s) added always should be at the - * end. - */ -goog.ui.DatePicker.prototype.setExtraWeekAtEnd = function(b) { - this.extraWeekAtEnd_ = b; - this.updateCalendarGrid_(); -}; - - -/** - * Sets whether week numbers should be shown. - * - * @param {boolean} b Whether week numbers should be shown. - */ -goog.ui.DatePicker.prototype.setShowWeekNum = function(b) { - this.showWeekNum_ = b; - // The navigation row may rely on the number of visible columns, - // so we update it when adding/removing the weeknum column. - this.updateNavigationRow_(); - this.updateCalendarGrid_(); -}; - - -/** - * Sets whether weekday names should be shown. - * - * @param {boolean} b Whether weekday names should be shown. - */ -goog.ui.DatePicker.prototype.setShowWeekdayNames = function(b) { - this.showWeekdays_ = b; - this.redrawCalendarGrid_(); -}; - - -/** - * Sets whether the picker uses narrow weekday names ('M', 'T', 'W', ...). - * - * The default behavior is to use short names ('Mon', 'Tue', 'Wed', ...). - * - * @param {boolean} b Whether to use narrow weekday names. - */ -goog.ui.DatePicker.prototype.setUseNarrowWeekdayNames = function(b) { - this.wdayNames_ = b ? this.symbols_.NARROWWEEKDAYS : - this.symbols_.SHORTWEEKDAYS; - this.redrawWeekdays_(); -}; - - -/** - * Sets whether none is a valid selection. - * - * @param {boolean} b Whether none is a valid selection. - */ -goog.ui.DatePicker.prototype.setAllowNone = function(b) { - this.allowNone_ = b; - if (this.elNone_) { - this.updateTodayAndNone_(); - } -}; - - -/** - * Sets whether the today button should be shown. - * - * @param {boolean} b Whether the today button should be shown. - */ -goog.ui.DatePicker.prototype.setShowToday = function(b) { - this.showToday_ = b; - if (this.elToday_) { - this.updateTodayAndNone_(); - } -}; - - -/** - * Updates the display style of the None and Today buttons as well as hides the - * table foot if both are hidden. - * @private - */ -goog.ui.DatePicker.prototype.updateTodayAndNone_ = function() { - goog.style.showElement(this.elToday_, this.showToday_); - goog.style.showElement(this.elNone_, this.allowNone_); - goog.style.showElement(this.tableFoot_, this.showToday_ || this.allowNone_); -}; - - -/** - * Sets the decorator function. The function should have the interface of - * {string} f({goog.date.Date}); - * and return a String representing a CSS class to decorate the cell - * corresponding to the date specified. - * - * @param {Function} f The decorator function. - */ -goog.ui.DatePicker.prototype.setDecorator = function(f) { - this.decoratorFunction_ = f; -}; - - -/** - * Changes the active month to the previous one. - */ -goog.ui.DatePicker.prototype.previousMonth = function() { - this.activeMonth_.add(new goog.date.Interval(goog.date.Interval.MONTHS, -1)); - this.updateCalendarGrid_(); -}; - - -/** - * Changes the active month to the next one. - */ -goog.ui.DatePicker.prototype.nextMonth = function() { - this.activeMonth_.add(new goog.date.Interval(goog.date.Interval.MONTHS, 1)); - this.updateCalendarGrid_(); -}; - - -/** - * Changes the active year to the previous one. - */ -goog.ui.DatePicker.prototype.previousYear = function() { - this.activeMonth_.add(new goog.date.Interval(goog.date.Interval.YEARS, -1)); - this.updateCalendarGrid_(); -}; - - -/** - * Changes the active year to the next one. - */ -goog.ui.DatePicker.prototype.nextYear = function() { - this.activeMonth_.add(new goog.date.Interval(goog.date.Interval.YEARS, 1)); - this.updateCalendarGrid_(); -}; - - -/** - * Selects the current date. - */ -goog.ui.DatePicker.prototype.selectToday = function() { - this.setDate(new goog.date.Date()); -}; - - -/** - * Clears the selection. - */ -goog.ui.DatePicker.prototype.selectNone = function() { - if (this.allowNone_) { - this.setDate(null); - } -}; - - -/** - * @return {goog.date.Date} The selected date or null if nothing is selected. - */ -goog.ui.DatePicker.prototype.getDate = function() { - return this.date_ && this.date_.clone(); -}; - - -/** - * Sets the selected date. - * - * @param {goog.date.Date|Date} date Date to select or null to select nothing. - */ -goog.ui.DatePicker.prototype.setDate = function(date) { - // Check if date has been changed - var changed = date != this.date_ && - !(date && this.date_ && - date.getFullYear() == this.date_.getFullYear() && - date.getMonth() == this.date_.getMonth() && - date.getDate() == this.date_.getDate()); - - // Set current date to clone of supplied goog.date.Date or Date. - this.date_ = date && new goog.date.Date(date); - - // Set current month - if (date) { - this.activeMonth_.set(this.date_); - this.activeMonth_.setDate(1); - } - - // Update calendar grid even if the date has not changed as even if today is - // selected another month can be displayed. - this.updateCalendarGrid_(); - - // TODO(eae): Standardize selection and change events with other components. - // Fire select event. - var selectEvent = new goog.ui.DatePickerEvent( - goog.ui.DatePicker.Events.SELECT, this, this.date_); - this.dispatchEvent(selectEvent); - - // Fire change event. - if (changed) { - var changeEvent = new goog.ui.DatePickerEvent( - goog.ui.DatePicker.Events.CHANGE, this, this.date_); - this.dispatchEvent(changeEvent); - } -}; - - -/** - * Updates the navigation row (navigating months and maybe years) in the navRow_ - * element of a created picker. - * @private - */ -goog.ui.DatePicker.prototype.updateNavigationRow_ = function() { - if (!this.elNavRow_) { - return; - } - var row = this.elNavRow_; - - // Clear the navigation row. - while (row.firstChild) { - row.removeChild(row.firstChild); - } - // Populate the navigation row according to the configured navigation mode. - var cell, monthCell, yearCell; - - if (this.simpleNavigation_) { - cell = this.dom_.createElement('td'); - cell.colSpan = this.showWeekNum_ ? 1 : 2; - this.createButton_(cell, '\u00AB', this.previousMonth); // << - row.appendChild(cell); - - cell = this.dom_.createElement('td'); - cell.colSpan = this.showWeekNum_ ? 6 : 5; - cell.className = goog.getCssName(this.getBaseCssClass(), 'monthyear'); - row.appendChild(cell); - this.elMonthYear_ = cell; - - cell = this.dom_.createElement('td'); - this.createButton_(cell, '\u00BB', this.nextMonth); // >> - row.appendChild(cell); - - } else { - var fullDateFormat = this.symbols_.DATEFORMATS[ - goog.i18n.DateTimeFormat.Format.FULL_DATE].toLowerCase(); - - monthCell = this.dom_.createElement('td'); - monthCell.colSpan = 5; - this.createButton_(monthCell, '\u00AB', this.previousMonth); // << - this.elMonth_ = this.createButton_( - monthCell, '', this.showMonthMenu_, - goog.getCssName(this.getBaseCssClass(), 'month')); - this.createButton_(monthCell, '\u00BB', this.nextMonth); // >> - - yearCell = this.dom_.createElement('td'); - yearCell.colSpan = 3; - this.createButton_(yearCell, '\u00AB', this.previousYear); // << - this.elYear_ = this.createButton_(yearCell, '', this.showYearMenu_, - goog.getCssName(this.getBaseCssClass(), - 'year')); - this.createButton_(yearCell, '\u00BB', this.nextYear); // >> - - // If the date format has year ('y') appearing first before month ('m'), - // show the year on the left hand side of the datepicker popup. Otherwise, - // show the month on the left side. This check assumes the data to be - // valid, and that all date formats contain month and year. - if (fullDateFormat.indexOf('y') < fullDateFormat.indexOf('m')) { - row.appendChild(yearCell); - row.appendChild(monthCell); - } else { - row.appendChild(monthCell); - row.appendChild(yearCell); - } - } -}; - - -/** - * Updates the footer row (with select buttons) in the footRow_ element of a - * created picker. - * @private - */ -goog.ui.DatePicker.prototype.updateFooterRow_ = function() { - var row = this.elFootRow_; - - // Clear the footer row. - goog.dom.removeChildren(row); - - // Populate the footer row with buttons for Today and None. - var cell = this.dom_.createElement('td'); - cell.colSpan = 2; - cell.className = goog.getCssName(this.getBaseCssClass(), 'today-cont'); - - /** @desc Label for button that selects the current date. */ - var MSG_DATEPICKER_TODAY_BUTTON_LABEL = goog.getMsg('Today'); - this.elToday_ = this.createButton_(cell, MSG_DATEPICKER_TODAY_BUTTON_LABEL, - this.selectToday); - row.appendChild(cell); - - cell = this.dom_.createElement('td'); - cell.colSpan = 4; - row.appendChild(cell); - - cell = this.dom_.createElement('td'); - cell.colSpan = 2; - cell.className = goog.getCssName(this.getBaseCssClass(), 'none-cont'); - - /** @desc Label for button that clears the selection. */ - var MSG_DATEPICKER_NONE = goog.getMsg('None'); - this.elNone_ = this.createButton_(cell, MSG_DATEPICKER_NONE, this.selectNone); - row.appendChild(cell); - this.updateTodayAndNone_(); -}; - - -/** @override */ -goog.ui.DatePicker.prototype.decorateInternal = function(el) { - goog.ui.DatePicker.superClass_.decorateInternal.call(this, el); - - el.className = this.getBaseCssClass(); - - var table = this.dom_.createElement('table'); - var thead = this.dom_.createElement('thead'); - var tbody = this.dom_.createElement('tbody'); - var tfoot = this.dom_.createElement('tfoot'); - - goog.dom.a11y.setRole(tbody, 'grid'); - tbody.tabIndex = '0'; - - // As per comment in colorpicker: table.tBodies and table.tFoot should not be - // used because of a bug in Safari, hence using an instance variable - this.tableBody_ = tbody; - this.tableFoot_ = tfoot; - - var row = this.dom_.createElement('tr'); - row.className = goog.getCssName(this.getBaseCssClass(), 'head'); - this.elNavRow_ = row; - this.updateNavigationRow_(); - - thead.appendChild(row); - - var cell; - this.elTable_ = []; - for (var i = 0; i < 7; i++) { - row = this.dom_.createElement('tr'); - this.elTable_[i] = []; - for (var j = 0; j < 8; j++) { - cell = this.dom_.createElement(j == 0 || i == 0 ? 'th' : 'td'); - if ((j == 0 || i == 0) && j != i) { - cell.className = (j == 0) ? - goog.getCssName(this.getBaseCssClass(), 'week') : - goog.getCssName(this.getBaseCssClass(), 'wday'); - goog.dom.a11y.setRole(cell, j == 0 ? 'rowheader' : 'columnheader'); - } - row.appendChild(cell); - this.elTable_[i][j] = cell; - } - tbody.appendChild(row); - } - - row = this.dom_.createElement('tr'); - row.className = goog.getCssName(this.getBaseCssClass(), 'foot'); - this.elFootRow_ = row; - this.updateFooterRow_(); - tfoot.appendChild(row); - - - table.cellSpacing = '0'; - table.cellPadding = '0'; - table.appendChild(thead); - table.appendChild(tbody); - table.appendChild(tfoot); - el.appendChild(table); - - this.redrawWeekdays_(); - this.updateCalendarGrid_(); - - el.tabIndex = 0; -}; - - -/** @override */ -goog.ui.DatePicker.prototype.createDom = function() { - goog.ui.DatePicker.superClass_.createDom.call(this); - this.decorateInternal(this.getElement()); -}; - - -/** @override */ -goog.ui.DatePicker.prototype.enterDocument = function() { - goog.ui.DatePicker.superClass_.enterDocument.call(this); - - var eh = this.getHandler(); - eh.listen(this.tableBody_, goog.events.EventType.CLICK, - this.handleGridClick_); - eh.listen(this.getKeyHandlerForElement_(this.getElement()), - goog.events.KeyHandler.EventType.KEY, this.handleGridKeyPress_); -}; - - -/** @override */ -goog.ui.DatePicker.prototype.exitDocument = function() { - goog.ui.DatePicker.superClass_.exitDocument.call(this); - this.destroyMenu_(); - for (var uid in this.keyHandlers_) { - this.keyHandlers_[uid].dispose(); - } - this.keyHandlers_ = {}; -}; - - -/** - * @deprecated Use decorate instead. - */ -goog.ui.DatePicker.prototype.create = - goog.ui.DatePicker.prototype.decorate; - - -/** @override */ -goog.ui.DatePicker.prototype.disposeInternal = function() { - goog.ui.DatePicker.superClass_.disposeInternal.call(this); - - this.elTable_ = null; - this.tableBody_ = null; - this.tableFoot_ = null; - this.elNavRow_ = null; - this.elFootRow_ = null; - this.elMonth_ = null; - this.elMonthYear_ = null; - this.elYear_ = null; - this.elToday_ = null; - this.elNone_ = null; -}; - - -/** - * Click handler for date grid. - * - * @param {goog.events.BrowserEvent} event Click event. - * @private - */ -goog.ui.DatePicker.prototype.handleGridClick_ = function(event) { - if (event.target.tagName == 'TD') { - // colIndex/rowIndex is broken in Safari, find position by looping - var el, x = -2, y = -2; // first col/row is for weekday/weeknum - for (el = event.target; el; el = el.previousSibling, x++) {} - for (el = event.target.parentNode; el; el = el.previousSibling, y++) {} - var obj = this.grid_[y][x]; - this.setDate(obj.clone()); - } -}; - - -/** - * Keypress handler for date grid. - * - * @param {goog.events.BrowserEvent} event Keypress event. - * @private - */ -goog.ui.DatePicker.prototype.handleGridKeyPress_ = function(event) { - var months, days; - switch (event.keyCode) { - case 33: // Page up - event.preventDefault(); - months = -1; - break; - case 34: // Page down - event.preventDefault(); - months = 1; - break; - case 37: // Left - event.preventDefault(); - days = -1; - break; - case 39: // Right - event.preventDefault(); - days = 1; - break; - case 38: // Down - event.preventDefault(); - days = -7; - break; - case 40: // Up - event.preventDefault(); - days = 7; - break; - case 36: // Home - event.preventDefault(); - this.selectToday(); - case 46: // Delete - event.preventDefault(); - this.selectNone(); - default: - return; - } - var date; - if (this.date_) { - date = this.date_.clone(); - date.add(new goog.date.Interval(0, months, days)); - } else { - date = this.activeMonth_.clone(); - date.setDate(1); - } - this.setDate(date); -}; - - -/** - * Click handler for month button. Opens month selection menu. - * - * @param {goog.events.BrowserEvent} event Click event. - * @private - */ -goog.ui.DatePicker.prototype.showMonthMenu_ = function(event) { - event.stopPropagation(); - - var list = []; - for (var i = 0; i < 12; i++) { - list.push(this.symbols_.MONTHS[i]); - } - this.createMenu_(this.elMonth_, list, this.handleMonthMenuClick_, - this.symbols_.MONTHS[this.activeMonth_.getMonth()]); -}; - - -/** - * Click handler for year button. Opens year selection menu. - * - * @param {goog.events.BrowserEvent} event Click event. - * @private - */ -goog.ui.DatePicker.prototype.showYearMenu_ = function(event) { - event.stopPropagation(); - - var list = []; - var year = this.activeMonth_.getFullYear() - 5; - for (var i = 0; i < 11; i++) { - list.push(String(year + i)); - } - this.createMenu_(this.elYear_, list, this.handleYearMenuClick_, - String(this.activeMonth_.getFullYear())); -}; - - -/** - * Call back function for month menu. - * - * @param {Element} target Selected item. - * @private - */ -goog.ui.DatePicker.prototype.handleMonthMenuClick_ = function(target) { - var el = target; - for (var i = -1; el; el = goog.dom.getPreviousElementSibling(el), i++) {} - - this.activeMonth_.setMonth(i); - this.updateCalendarGrid_(); - - if (this.elMonth_.focus) { - this.elMonth_.focus(); - } -}; - - -/** - * Call back function for year menu. - * - * @param {Element} target Selected item. - * @private - */ -goog.ui.DatePicker.prototype.handleYearMenuClick_ = function(target) { - if (target.firstChild.nodeType == goog.dom.NodeType.TEXT) { - this.activeMonth_.setFullYear(Number(target.firstChild.nodeValue)); - this.updateCalendarGrid_(); - } - - this.elYear_.focus(); -}; - - -/** - * Support function for menu creation. - * - * @param {Element} srcEl Button to create menu for. - * @param {Array.<string>} items List of items to populate menu with. - * @param {Function} method Call back method. - * @param {string} selected Item to mark as selected in menu. - * @private - */ -goog.ui.DatePicker.prototype.createMenu_ = function(srcEl, items, method, - selected) { - this.destroyMenu_(); - - var el = this.dom_.createElement('div'); - el.className = goog.getCssName(this.getBaseCssClass(), 'menu'); - - this.menuSelected_ = null; - - var ul = this.dom_.createElement('ul'); - for (var i = 0; i < items.length; i++) { - var li = this.dom_.createDom('li', null, items[i]); - if (items[i] == selected) { - this.menuSelected_ = li; - } - ul.appendChild(li); - } - el.appendChild(ul); - el.style.left = srcEl.offsetLeft + srcEl.parentNode.offsetLeft + 'px'; - el.style.top = srcEl.offsetTop + 'px'; - el.style.width = srcEl.clientWidth + 'px'; - this.elMonth_.parentNode.appendChild(el); - - this.menu_ = el; - if (!this.menuSelected_) { - this.menuSelected_ = ul.firstChild; - } - this.menuSelected_.className = - goog.getCssName(this.getBaseCssClass(), 'menu-selected'); - this.menuCallback_ = method; - - var eh = this.getHandler(); - eh.listen(this.menu_, goog.events.EventType.CLICK, this.handleMenuClick_); - eh.listen(this.getKeyHandlerForElement_(this.menu_), - goog.events.KeyHandler.EventType.KEY, this.handleMenuKeyPress_); - eh.listen(this.dom_.getDocument(), goog.events.EventType.CLICK, - this.destroyMenu_); - el.tabIndex = 0; - el.focus(); -}; - - -/** - * Click handler for menu. - * - * @param {goog.events.BrowserEvent} event Click event. - * @private - */ -goog.ui.DatePicker.prototype.handleMenuClick_ = function(event) { - event.stopPropagation(); - - this.destroyMenu_(); - if (this.menuCallback_) { - this.menuCallback_(event.target); - } -}; - - -/** - * Keypress handler for menu. - * - * @param {goog.events.BrowserEvent} event Keypress event. - * @private - */ -goog.ui.DatePicker.prototype.handleMenuKeyPress_ = function(event) { - // Prevent the grid keypress handler from catching the keypress event. - event.stopPropagation(); - - var el; - var menuSelected = this.menuSelected_; - switch (event.keyCode) { - case 35: // End - event.preventDefault(); - el = menuSelected.parentNode.lastChild; - break; - case 36: // Home - event.preventDefault(); - el = menuSelected.parentNode.firstChild; - break; - case 38: // Up - event.preventDefault(); - el = menuSelected.previousSibling; - break; - case 40: // Down - event.preventDefault(); - el = menuSelected.nextSibling; - break; - case 13: // Enter - case 9: // Tab - case 0: // Space - event.preventDefault(); - this.destroyMenu_(); - this.menuCallback_(menuSelected); - break; - } - if (el && el != menuSelected) { - menuSelected.className = ''; - el.className = goog.getCssName(this.getBaseCssClass(), 'menu-selected'); - this.menuSelected_ = el; - } -}; - - -/** - * Support function for menu destruction. - * @private - */ -goog.ui.DatePicker.prototype.destroyMenu_ = function() { - if (this.menu_) { - var eh = this.getHandler(); - eh.unlisten(this.menu_, goog.events.EventType.CLICK, this.handleMenuClick_); - eh.unlisten(this.getKeyHandlerForElement_(this.menu_), - goog.events.KeyHandler.EventType.KEY, this.handleMenuKeyPress_); - eh.unlisten(this.dom_.getDocument(), goog.events.EventType.CLICK, - this.destroyMenu_); - goog.dom.removeNode(this.menu_); - delete this.menu_; - } -}; - - -/** - * Support function for button creation. - * - * @param {Element} parentNode Container the button should be added to. - * @param {string} label Button label. - * @param {Function} method Event handler. - * @param {string=} opt_className Class name for button, which will be used - * in addition to "goog-date-picker-btn". - * @private - * @return {Element} The created button element. - */ -goog.ui.DatePicker.prototype.createButton_ = function(parentNode, label, - method, opt_className) { - var classes = [goog.getCssName(this.getBaseCssClass(), 'btn')]; - if (opt_className) { - classes.push(opt_className); - } - var el = this.dom_.createElement('button'); - el.className = classes.join(' '); - el.appendChild(this.dom_.createTextNode(label)); - parentNode.appendChild(el); - this.getHandler().listen(el, goog.events.EventType.CLICK, function(e) { - // Since this is a button, the default action is to submit a form if the - // node is added inside a form. Prevent this. - e.preventDefault(); - method.call(this, e); - }); - - return el; -}; - - -/** - * Determines the dates/weekdays for the current month and builds an in memory - * representation of the calendar. - * - * @private - */ -goog.ui.DatePicker.prototype.updateCalendarGrid_ = function() { - if (!this.getElement()) { - return; - } - - var date = this.activeMonth_.clone(); - date.setDate(1); - - // Show year name of select month - if (this.elMonthYear_) { - goog.dom.setTextContent(this.elMonthYear_, - goog.date.formatMonthAndYear( - this.symbols_.MONTHS[date.getMonth()], - date.getFullYear())); - } - if (this.elMonth_) { - goog.dom.setTextContent(this.elMonth_, - this.symbols_.MONTHS[date.getMonth()]); - } - if (this.elYear_) { - goog.dom.setTextContent(this.elYear_, String(date.getFullYear())); - } - - var wday = date.getWeekday(); - var days = date.getNumberOfDaysInMonth(); - - // Determine how many days to show for previous month - date.add(new goog.date.Interval(goog.date.Interval.MONTHS, -1)); - date.setDate(date.getNumberOfDaysInMonth() - (wday - 1)); - - if (this.showFixedNumWeeks_ && !this.extraWeekAtEnd_ && days + wday < 33) { - date.add(new goog.date.Interval(goog.date.Interval.DAYS, -7)); - } - - // Create weekday/day grid - var dayInterval = new goog.date.Interval(goog.date.Interval.DAYS, 1); - this.grid_ = []; - for (var y = 0; y < 6; y++) { // Weeks - this.grid_[y] = []; - for (var x = 0; x < 7; x++) { // Weekdays - this.grid_[y][x] = date.clone(); - date.add(dayInterval); - } - } - - this.redrawCalendarGrid_(); -}; - - -/** - * Draws calendar view from in memory representation and applies class names - * depending on the selection, weekday and whatever the day belongs to the - * active month or not. - * @private - */ -goog.ui.DatePicker.prototype.redrawCalendarGrid_ = function() { - if (!this.getElement()) { - return; - } - - var month = this.activeMonth_.getMonth(); - var today = new goog.date.Date(); - var todayYear = today.getFullYear(); - var todayMonth = today.getMonth(); - var todayDate = today.getDate(); - - // Draw calendar week by week, a worst case month has six weeks. - for (var y = 0; y < 6; y++) { - - // Draw week number, if enabled - if (this.showWeekNum_) { - goog.dom.setTextContent(this.elTable_[y + 1][0], - this.grid_[y][0].getWeekNumber()); - goog.dom.classes.set(this.elTable_[y + 1][0], - goog.getCssName(this.getBaseCssClass(), 'week')); - } else { - goog.dom.setTextContent(this.elTable_[y + 1][0], ''); - goog.dom.classes.set(this.elTable_[y + 1][0], ''); - } - - for (var x = 0; x < 7; x++) { - var o = this.grid_[y][x]; - var el = this.elTable_[y + 1][x + 1]; - - // Assign a unique element id (required for setting the active descendant - // ARIA role) unless already set. - if (!el.id) { - el.id = 'goog-dp-' + goog.ui.DatePicker.nextId_++; - } - goog.dom.a11y.setRole(el, 'gridcell'); - var classes = [goog.getCssName(this.getBaseCssClass(), 'date')]; - if (this.showOtherMonths_ || o.getMonth() == month) { - // Date belongs to previous or next month - if (o.getMonth() != month) { - classes.push(goog.getCssName(this.getBaseCssClass(), 'other-month')); - } - - // Apply styles set by setWeekdayClass - var wday = (x + this.activeMonth_.getFirstDayOfWeek() + 7) % 7; - if (this.wdayStyles_[wday]) { - classes.push(this.wdayStyles_[wday]); - } - - // Current date - if (o.getDate() == todayDate && o.getMonth() == todayMonth && - o.getFullYear() == todayYear) { - classes.push(goog.getCssName(this.getBaseCssClass(), 'today')); - } - - // Selected date - if (this.date_ && o.getDate() == this.date_.getDate() && - o.getMonth() == this.date_.getMonth() && - o.getFullYear() == this.date_.getFullYear()) { - classes.push(goog.getCssName(this.getBaseCssClass(), 'selected')); - goog.dom.a11y.setState(this.tableBody_, 'activedescendant', el.id); - } - - // Custom decorator - if (this.decoratorFunction_) { - var customClass = this.decoratorFunction_(o); - if (customClass) { - classes.push(customClass); - } - } - - // Set cell text to the date and apply classes. - goog.dom.setTextContent(el, o.getDate()); - // Date belongs to previous or next month and showOtherMonths is false, - // clear text and classes. - } else { - goog.dom.setTextContent(el, ''); - } - goog.dom.classes.set(el, classes.join(' ')); - } - - // Hide the either the last one or last two weeks if they contain no days - // from the active month and the showFixedNumWeeks is false. The first four - // weeks are always shown as no month has less than 28 days). - if (y >= 4) { - goog.style.showElement(this.elTable_[y + 1][0].parentNode, - this.grid_[y][0].getMonth() == month || - this.showFixedNumWeeks_); - } - } -}; - - -/** - * Draw weekday names, if enabled. Start with whatever day has been set as the - * first day of week. - * @private - */ -goog.ui.DatePicker.prototype.redrawWeekdays_ = function() { - if (!this.getElement()) { - return; - } - if (this.showWeekdays_) { - for (var x = 0; x < 7; x++) { - var el = this.elTable_[0][x + 1]; - var wday = (x + this.activeMonth_.getFirstDayOfWeek() + 7) % 7; - goog.dom.setTextContent(el, this.wdayNames_[(wday + 1) % 7]); - } - } - goog.style.showElement(this.elTable_[0][0].parentNode, this.showWeekdays_); -}; - - -/** - * Returns the key handler for an element and caches it so that it can be - * retrieved at a later point. - * @param {Element} el The element to get the key handler for. - * @return {goog.events.KeyHandler} The key handler for the element. - * @private - */ -goog.ui.DatePicker.prototype.getKeyHandlerForElement_ = function(el) { - var uid = goog.getUid(el); - if (!(uid in this.keyHandlers_)) { - this.keyHandlers_[uid] = new goog.events.KeyHandler(el); - } - return this.keyHandlers_[uid]; -}; - - - -/** - * Object representing a date picker event. - * - * @param {string} type Event type. - * @param {goog.ui.DatePicker} target Date picker initiating event. - * @param {goog.date.Date} date Selected date. - * @constructor - * @extends {goog.events.Event} - */ -goog.ui.DatePickerEvent = function(type, target, date) { - goog.events.Event.call(this, type, target); - - /** - * The selected date - * @type {goog.date.Date} - */ - this.date = date; -}; -goog.inherits(goog.ui.DatePickerEvent, goog.events.Event); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/datepicker_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/datepicker_test.html.svn-base deleted file mode 100644 index 2e3b306..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/datepicker_test.html.svn-base +++ /dev/null @@ -1,203 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.DatePicker</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.i18n.DateTimeSymbols_en_US'); - goog.require('goog.i18n.DateTimeSymbols_zh_HK'); - goog.require('goog.style'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.DatePicker'); - </script> -</head> -<body> -<div id="sandbox"></div> -<script> - var picker; - var $$ = goog.dom.getElementsByTagNameAndClass; - var sandbox = goog.dom.getElement('sandbox'); - - function tearDown() { - picker.dispose(); - goog.dom.removeChildren(sandbox); - } - - function testIsMonthOnLeft() { - goog.i18n.DateTimeSymbols = goog.i18n.DateTimeSymbols_en_US; - picker = new goog.ui.DatePicker(); - picker.create(sandbox); - var head = $$('tr', 'goog-date-picker-head')[0]; - var month = $$('button', 'goog-date-picker-month', - head.firstChild)[0]; - assertSameElements( - 'Button element must have expected class names', - ['goog-date-picker-btn','goog-date-picker-month'], - goog.dom.classes.get(month) - ); - } - - function testIsYearOnLeft() { - goog.i18n.DateTimeSymbols = goog.i18n.DateTimeSymbols_zh_HK; - picker = new goog.ui.DatePicker(); - picker.create(sandbox); - var head = $$('tr', 'goog-date-picker-head')[0]; - var year = $$('button', 'goog-date-picker-year', - head.firstChild)[0]; - assertSameElements( - 'Button element must have expected class names', - ['goog-date-picker-btn','goog-date-picker-year'], - goog.dom.classes.get(year) - ); - } - - function testHidingOfTableFoot0() { - picker = new goog.ui.DatePicker(); - picker.setAllowNone(false); - picker.setShowToday(false); - picker.create(sandbox); - var tFoot = $$('tfoot')[0]; - assertFalse(goog.style.isElementShown(tFoot)) - } - - function testHidingOfTableFoot1() { - picker = new goog.ui.DatePicker(); - picker.setAllowNone(false); - picker.setShowToday(true); - picker.create(sandbox); - var tFoot = $$('tfoot')[0]; - assertTrue(goog.style.isElementShown(tFoot)) - } - - function testHidingOfTableFoot2() { - picker = new goog.ui.DatePicker(); - picker.setAllowNone(true); - picker.setShowToday(false); - picker.create(sandbox); - var tFoot = $$('tfoot')[0]; - assertTrue(goog.style.isElementShown(tFoot)) - } - - function testHidingOfTableFoot3() { - picker = new goog.ui.DatePicker(); - picker.setAllowNone(true); - picker.setShowToday(true); - picker.create(sandbox); - var tFoot = $$('tfoot')[0]; - assertTrue(goog.style.isElementShown(tFoot)) - } - - function testHidingOfTableFootAfterCreate0() { - picker = new goog.ui.DatePicker(); - picker.create(sandbox); - picker.setAllowNone(false); - picker.setShowToday(false); - var tFoot = $$('tfoot')[0]; - assertFalse(goog.style.isElementShown(tFoot)) - } - - function testHidingOfTableFootAfterCreate1() { - picker = new goog.ui.DatePicker(); - picker.create(sandbox); - picker.setAllowNone(false); - picker.setShowToday(true); - var tFoot = $$('tfoot')[0]; - assertTrue(goog.style.isElementShown(tFoot)) - } - - function testHidingOfTableFootAfterCreate2() { - picker = new goog.ui.DatePicker(); - picker.create(sandbox); - picker.setAllowNone(true); - picker.setShowToday(false); - var tFoot = $$('tfoot')[0]; - assertTrue(goog.style.isElementShown(tFoot)) - } - - function testHidingOfTableFootAfterCreate3() { - picker = new goog.ui.DatePicker(); - picker.create(sandbox); - picker.setAllowNone(true); - picker.setShowToday(true); - var tFoot = $$('tfoot')[0]; - assertTrue(goog.style.isElementShown(tFoot)) - } - - function testGetDate() { - picker = new goog.ui.DatePicker(new Date(2000, 0, 1)); - var date = picker.getDate(); - assertObjectEquals(new goog.date.Date(2000, 0, 1), date); - - date.setMonth(1); - assertObjectEquals('modifying the returned date is safe', - new goog.date.Date(2000, 0, 1), picker.getDate()); - - picker.setDate(null); - assertNull('no date is selected', picker.getDate()); - } - - function testSetDate() { - picker = new goog.ui.DatePicker(); - picker.createDom(); - picker.enterDocument(); - var selectEvents = 0; - var changeEvents = 0; - goog.events.listen(picker, goog.ui.DatePicker.Events.SELECT, - function() { - selectEvents++; - }); - goog.events.listen(picker, goog.ui.DatePicker.Events.CHANGE, - function() { - changeEvents++; - }); - - // Set date. - picker.setDate(new Date(2010, 1, 26)); - assertEquals('no select event dispatched', 1, selectEvents); - assertEquals('no change event dispatched', 1, changeEvents); - assertTrue('date is set', - new goog.date.Date(2010, 1, 26).equals(picker.getDate())); - - // Set date to same date. - picker.setDate(new Date(2010, 1, 26)); - assertEquals('1 select event dispatched', 2, selectEvents); - assertEquals('no change event dispatched', 1, changeEvents); - - // Set date to different date. - picker.setDate(new Date(2010, 1, 27)); - assertEquals('another select event dispatched', 3, selectEvents); - assertEquals('1 change event dispatched', 2, changeEvents); - - // Set date to none. - picker.setDate(null); - assertEquals('another select event dispatched', 4, selectEvents); - assertEquals('another change event dispatched', 3, changeEvents); - assertNull('date cleared', picker.getDate()); - } - - function testEventListenerLeaks() { - var listeners = goog.events.getTotalListenerCount(); - picker = new goog.ui.DatePicker(); - assertEquals('no listeners registered in constructor', listeners, - goog.events.getTotalListenerCount()); - picker.createDom(); - picker.enterDocument(); - picker.exitDocument(); - assertEquals('exitDocument cleans up all listeners', listeners, - goog.events.getTotalListenerCount()); - } - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/decorate.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/decorate.js.svn-base deleted file mode 100644 index 0cf9c2d..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/decorate.js.svn-base +++ /dev/null @@ -1,38 +0,0 @@ -// 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; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/decorate_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/decorate_test.html.svn-base deleted file mode 100644 index 4a3427a..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/decorate_test.html.svn-base +++ /dev/null @@ -1,114 +0,0 @@ -<!DOCTYPE html> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.registry</title> - <script src="../base.js"></script> - <script> - goog.require('goog.object'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.decorate'); - goog.require('goog.ui.registry'); - </script> -</head> -<body> - <div id="x" class="fake-component-x"></div> - <div id="y" class="fake-component-y fake-component-x"></div> - <div id="z" class="fake-component-z"></div> - <div id="u"></div> - <script> - // Fake component and renderer implementations, for testing only. - - // UnknownComponent has no default renderer or decorator registered. - function UnknownComponent() { - } - - // FakeComponentX's default renderer is FakeRenderer. It also has a - // decorator. - function FakeComponentX() { - this.element = null; - } - - FakeComponentX.prototype.decorate = function(element) { - this.element = element; - }; - - // FakeComponentY doesn't have an explicitly registered default - // renderer; it should inherit the default renderer from its superclass. - // It does have a decorator registered. - function FakeComponentY() { - FakeComponentX.call(this); - } - goog.inherits(FakeComponentY, FakeComponentX); - - // FakeComponentZ is just another component. Its default renderer is - // FakeSingletonRenderer, but it has no decorator registered. - function FakeComponentZ() { - } - - // FakeRenderer is a stateful renderer. - function FakeRenderer() { - } - - // FakeSingletonRenderer is a stateless renderer that can be used as a - // singleton. - function FakeSingletonRenderer() { - } - - FakeSingletonRenderer.instance_ = new FakeSingletonRenderer(); - - FakeSingletonRenderer.getInstance = function() { - return FakeSingletonRenderer.instance_; - }; - - function setUp() { - goog.ui.registry.setDefaultRenderer(FakeComponentX, FakeRenderer); - goog.ui.registry.setDefaultRenderer(FakeComponentZ, - FakeSingletonRenderer); - - goog.ui.registry.setDecoratorByClassName('fake-component-x', - function() { - return new FakeComponentX(); - }); - goog.ui.registry.setDecoratorByClassName('fake-component-y', - function() { - return new FakeComponentY(); - }); - } - - function tearDown() { - goog.ui.registry.reset(); - } - - function testDecorate() { - var dx = goog.ui.decorate(document.getElementById('x')); - assertTrue('Decorator for element with fake-component-x class must be ' + - 'a FakeComponentX', dx instanceof FakeComponentX); - assertEquals('Element x must have been decorated', - document.getElementById('x'), dx.element); - - var dy = goog.ui.decorate(document.getElementById('y')); - assertTrue('Decorator for element with fake-component-y class must be ' + - 'a FakeComponentY', dy instanceof FakeComponentY); - assertEquals('Element y must have been decorated', - document.getElementById('y'), dy.element); - - var dz = goog.ui.decorate(document.getElementById('z')); - assertNull('Decorator for element with unknown class must be null', dz); - - var du = goog.ui.decorate(document.getElementById('u')); - assertNull('Decorator for element without CSS class must be null', du); - } - - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/deprecatedbutton.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/deprecatedbutton.js.svn-base deleted file mode 100644 index b2cf8d0..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/deprecatedbutton.js.svn-base +++ /dev/null @@ -1,381 +0,0 @@ -// 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 Deprecated button class; use {@link goog.ui.Button} instead. - * - */ - -goog.provide('goog.ui.DeprecatedButton'); - -goog.require('goog.dom'); -goog.require('goog.events'); -goog.require('goog.events.Event'); -goog.require('goog.events.EventTarget'); -goog.require('goog.events.EventType'); - - - -/** - * Default implementation of a button. Uses the default browser-style button. - * - * @param {string=} opt_class Optional class for component. - * Default: 'goog-button'. - * @constructor - * @extends {goog.events.EventTarget} - * @deprecated Use {@link goog.ui.Button} instead. - */ -goog.ui.DeprecatedButton = function(opt_class) { - /** - * CSS class name for the button. - * @type {string} - * @private - */ - this.class_ = opt_class ? opt_class : goog.getCssName('goog-button'); - - /** - * Unique ID for the instance of this component. - * @type {string} - * @private - */ - this.id_ = this.getNextUniqueId_(); -}; -goog.inherits(goog.ui.DeprecatedButton, goog.events.EventTarget); - - -/** - * Prefix for all ID's of this component. - * @type {string} - * @private - */ -goog.ui.DeprecatedButton.BASE_ID_ = 'goog.ui.DeprecatedButton.'; - - -/** - * Next unique instance ID for this component. - * @type {number} - * @private - */ -goog.ui.DeprecatedButton.nextId_ = 0; - - -/** - * Gets the next unique ID for the component. - * @return {string} The next unique ID for the component. - */ -goog.ui.DeprecatedButton.getNextUniqueId = function() { - return goog.ui.DeprecatedButton.BASE_ID_ + goog.ui.DeprecatedButton.nextId_++; -}; - - -/** - * Gets the next unique ID for the component. This method is used in the - * constructor to generate the unique ID for the component. - * - * NOTE: This method is placed on the prototype so that classes that inherit - * this class can override this method and have the ID automatically set by - * calling the parent class's constructor. - * - * @return {string} The next unique ID for the component. - * @private - */ -goog.ui.DeprecatedButton.prototype.getNextUniqueId_ = function() { - return goog.ui.DeprecatedButton.getNextUniqueId(); -}; - - -/** -* Events fired by the Component. -* @enum {string} -*/ -goog.ui.DeprecatedButton.EventType = { - /** - * Fired by the Component when it is activated. - */ - ACTIVATE: 'activate', - - /** - * Fired by the Component when it is enabled/disabled. - */ - ENABLE: 'enable' -}; - - -/** - * Whether componet is enabled. - * @type {boolean} - * @private - */ -goog.ui.DeprecatedButton.prototype.enabled_ = true; - - -/** - * Whether componet is rendered. - * @type {boolean} - * @private - */ -goog.ui.DeprecatedButton.prototype.rendered_ = false; - - -/** - * HTML caption displayed in the component. - * @type {string} - * @private - */ -goog.ui.DeprecatedButton.prototype.caption_ = ''; - - -/** - * Tooltip for the component. - * @type {?string} - * @private - */ -goog.ui.DeprecatedButton.prototype.tooltip_ = null; - - -/** - * Value associated with the component. - * @type {Object} - * @private - */ -goog.ui.DeprecatedButton.prototype.value_ = null; - - -/** - * Main element for the component. - * @type {Element} - * @private - */ -goog.ui.DeprecatedButton.prototype.element_ = null; - - -/** - * Gets the caption for the component. - * @return {?string} The caption. - */ -goog.ui.DeprecatedButton.prototype.getCaption = function() { - return this.caption_; -}; - - -/** - * Sets the caption for the component. - * @param {string} caption The caption. - */ -goog.ui.DeprecatedButton.prototype.setCaption = function(caption) { - this.caption_ = caption; - if (this.isRendered()) { - var element = this.getElement(); - - element.value = caption; - goog.dom.setTextContent(element, caption); - } -}; - - -/** - * Gets the tooltip for the component. - * @return {?string} The tooltip. - */ -goog.ui.DeprecatedButton.prototype.getTooltip = function() { - return this.tooltip_; -}; - - -/** - * Sets the tooltip for the component. - * @param {string} tooltip The tooltip. - */ -goog.ui.DeprecatedButton.prototype.setTooltip = function(tooltip) { - this.tooltip_ = tooltip; - if (this.isRendered()) { - this.getElement().title = tooltip; - } -}; - - -/** - * Gets the value for the component. - * @return {Object} The value. - */ -goog.ui.DeprecatedButton.prototype.getValue = function() { - return this.value_; -}; - - -/** - * Sets the value for the component. - * @param {Object} value The value. - */ -goog.ui.DeprecatedButton.prototype.setValue = function(value) { - this.value_ = value; -}; - - -/** - * Gets the enabled status for the component. - * @return {boolean} The enabled status. - */ -goog.ui.DeprecatedButton.prototype.getEnabled = function() { - return this.enabled_; -}; - - -/** - * Sets the enabled status for the component. - * @param {boolean} enable The enabled status. - */ -goog.ui.DeprecatedButton.prototype.setEnabled = function(enable) { - // Fire event to see if can be enabled. - if (this.getEnabled() != enable && - this.dispatchEvent(goog.ui.DeprecatedButton.EventType.ENABLE)) { - if (this.isRendered()) { - this.element_.disabled = !enable; - } - this.enabled_ = enable; - } -}; - - -/** - * Gets the CSS className for the component. - * @return {string} The class name. - */ -goog.ui.DeprecatedButton.prototype.getClass = function() { - return this.class_; -}; - - -/** - * Gets the element representing the UI component. - * @return {Element} Element representing component if any. Otherwise, null. - */ -goog.ui.DeprecatedButton.prototype.getElement = function() { - return this.element_; -}; - - -/** - * Gets the unique ID for the instance of this component. - * @return {string} Unique element id. - */ -goog.ui.DeprecatedButton.prototype.getId = function() { - return this.id_; -}; - - -/** - * Determines whether the component has been rendered. - * @return {boolean} TRUE iff rendered. Otherwise, FALSE. - */ -goog.ui.DeprecatedButton.prototype.isRendered = function() { - return this.rendered_; -}; - - -/** - * Renders the component. Throws an Error if the component is already rendered. - * @param {Element=} opt_element Element to render the compponent into. - * If omitted, then the componenet is appended to - * the document. - */ -goog.ui.DeprecatedButton.prototype.render = function(opt_element) { - if (this.isRendered()) { - throw Error('Compenent already rendered'); - } - - // Get the DOM helper. - var domHelper = goog.dom.getDomHelper(opt_element); - - // Create element. - var element = domHelper.createDom('button', { - value: this.caption_, - title: this.tooltip_, - disabled: !this.enabled_, - className: this.class_ - }); - - // set the text shown in the button - goog.dom.setTextContent(element, this.caption_); - - // Append to parent. - var parentElement = opt_element || domHelper.getDocument().body; - domHelper.appendChild(parentElement, element); - - // Setup event handlers. - goog.events.listen(element, goog.events.EventType.CLICK, - this.onClick_, true, this); - - this.element_ = element; - this.rendered_ = true; -}; - - -/** - * Decorates the element for the UI component. - * @param {Element} element Element to decorate. - */ -goog.ui.DeprecatedButton.prototype.decorate = function(element) { - if (this.isRendered()) { - throw Error('Component already rendered'); - } else if (element && (element.tagName == 'BUTTON' || - (element.tagName == 'INPUT' && (element.type == 'BUTTON' || - element.type == 'SUBMIT' || element.type == 'RESET')))) { - // Setup properties. - this.element_ = element; - this.setCaption(element.value); - this.setTooltip(element.title); - this.class_ = element.className; - // Setup event handlers. - goog.events.listen(element, goog.events.EventType.CLICK, - this.onClick_, true, this); - this.rendered_ = true; - } else { - throw Error('Invalid element to decorate'); - } -}; - - -/** - * Handles the DOM click event. Dispatches the button ACTIVATE Event. - * @param {Object} e The event. - * @private - */ -goog.ui.DeprecatedButton.prototype.onClick_ = function(e) { - if (this.getEnabled()) { - this.dispatchEvent(goog.ui.DeprecatedButton.EventType.ACTIVATE); - } -}; - - -/** @override */ -goog.ui.DeprecatedButton.prototype.disposeInternal = function() { - goog.ui.DeprecatedButton.superClass_.disposeInternal.call(this); - - // Cleanup DOM. - var element = this.element_; - if (element) { - // Cleanup DOM events. - goog.events.unlisten(element, goog.events.EventType.CLICK, - this.onClick_, true, this); - - // Remove node. - var domHelper = goog.dom.getDomHelper(element); - domHelper.removeNode(element); - this.element_ = null; - } - - // Cleanup properties. - delete this.value_; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dialog.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dialog.js.svn-base deleted file mode 100644 index 8cfff71..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dialog.js.svn-base +++ /dev/null @@ -1,1522 +0,0 @@ -// 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 showing simple modal dialog boxes. - * - * TODO(user): - * * Standardize CSS class names with other components - * * Add functionality to "host" other components in content area - * * Abstract out ButtonSet and make it more general - * @see ../demos/dialog.html - */ - -goog.provide('goog.ui.Dialog'); -goog.provide('goog.ui.Dialog.ButtonSet'); -goog.provide('goog.ui.Dialog.ButtonSet.DefaultButtons'); -goog.provide('goog.ui.Dialog.DefaultButtonCaptions'); -goog.provide('goog.ui.Dialog.DefaultButtonKeys'); -goog.provide('goog.ui.Dialog.Event'); -goog.provide('goog.ui.Dialog.EventType'); - -goog.require('goog.asserts'); -goog.require('goog.dom'); -goog.require('goog.dom.NodeType'); -goog.require('goog.dom.TagName'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.classes'); -goog.require('goog.events.Event'); -goog.require('goog.events.EventType'); -goog.require('goog.events.KeyCodes'); -goog.require('goog.fx.Dragger'); -goog.require('goog.math.Rect'); -goog.require('goog.structs'); -goog.require('goog.structs.Map'); -goog.require('goog.style'); -goog.require('goog.ui.ModalPopup'); -goog.require('goog.userAgent'); - - - -/** - * Class for showing simple dialog boxes. - * The Html structure of the dialog box is: - * <pre> - * Element Function Class-name, modal-dialog = default - * ---------------------------------------------------------------------------- - * - iframe Iframe mask modal-dialog-bg - * - div Background mask modal-dialog-bg - * - div Dialog area modal-dialog - * - div Title bar modal-dialog-title - * - span modal-dialog-title-text - * - text Title text N/A - * - span modal-dialog-title-close - * - ?? Close box N/A - * - div Content area modal-dialog-content - * - ?? User specified content N/A - * - div Button area modal-dialog-buttons - * - button N/A - * - button - * - ... - * </pre> - * @constructor - * @param {string=} opt_class CSS class name for the dialog element, also used - * as a class name prefix for related elements; defaults to modal-dialog. - * @param {boolean=} opt_useIframeMask Work around windowed controls z-index - * issue by using an iframe instead of a div for bg element. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper; see {@link - * goog.ui.Component} for semantics. - * @extends {goog.ui.ModalPopup} - */ -goog.ui.Dialog = function(opt_class, opt_useIframeMask, opt_domHelper) { - goog.base(this, opt_useIframeMask, opt_domHelper); - - /** - * CSS class name for the dialog element, also used as a class name prefix for - * related elements. Defaults to goog.getCssName('modal-dialog'). - * @type {string} - * @private - */ - this.class_ = opt_class || goog.getCssName('modal-dialog'); - - this.buttons_ = goog.ui.Dialog.ButtonSet.createOkCancel(); -}; -goog.inherits(goog.ui.Dialog, goog.ui.ModalPopup); - - -/** - * Button set. Default to Ok/Cancel. - * @type {goog.ui.Dialog.ButtonSet} - * @private - */ -goog.ui.Dialog.prototype.buttons_; - - -/** - * Whether the escape key closes this dialog. - * @type {boolean} - * @private - */ -goog.ui.Dialog.prototype.escapeToCancel_ = true; - - -/** - * Whether this dialog should include a title close button. - * @type {boolean} - * @private - */ -goog.ui.Dialog.prototype.hasTitleCloseButton_ = true; - - -/** - * Whether the dialog is modal. Defaults to true. - * @type {boolean} - * @private - */ -goog.ui.Dialog.prototype.modal_ = true; - - -/** - * Whether the dialog is draggable. Defaults to true. - * @type {boolean} - * @private - */ -goog.ui.Dialog.prototype.draggable_ = true; - - -/** - * Opacity for background mask. Defaults to 50%. - * @type {number} - * @private - */ -goog.ui.Dialog.prototype.backgroundElementOpacity_ = 0.50; - - -/** - * Dialog's title. - * @type {string} - * @private - */ -goog.ui.Dialog.prototype.title_ = ''; - - -/** - * Dialog's content (HTML). - * @type {string} - * @private - */ -goog.ui.Dialog.prototype.content_ = ''; - - -/** - * Dragger. - * @type {goog.fx.Dragger} - * @private - */ -goog.ui.Dialog.prototype.dragger_ = null; - - -/** - * Whether the dialog should be disposed when it is hidden. - * @type {boolean} - * @private - */ -goog.ui.Dialog.prototype.disposeOnHide_ = false; - - -/** - * Element for the title bar. - * @type {Element} - * @private - */ -goog.ui.Dialog.prototype.titleEl_ = null; - - -/** - * Element for the text area of the title bar. - * @type {Element} - * @private - */ -goog.ui.Dialog.prototype.titleTextEl_ = null; - - -/** - * Id of element for the text area of the title bar. - * @type {?string} - * @private - */ -goog.ui.Dialog.prototype.titleId_ = null; - - -/** - * Element for the close box area of the title bar. - * @type {Element} - * @private - */ -goog.ui.Dialog.prototype.titleCloseEl_ = null; - - -/** - * Element for the content area. - * @type {Element} - * @private - */ -goog.ui.Dialog.prototype.contentEl_ = null; - - -/** - * Element for the button bar. - * @type {Element} - * @private - */ -goog.ui.Dialog.prototype.buttonEl_ = null; - - -/** @override */ -goog.ui.Dialog.prototype.getCssClass = function() { - return this.class_; -}; - - -/** - * Sets the title. - * @param {string} title The title text. - */ -goog.ui.Dialog.prototype.setTitle = function(title) { - this.title_ = title; - if (this.titleTextEl_) { - goog.dom.setTextContent(this.titleTextEl_, title); - } -}; - - -/** - * Gets the title. - * @return {string} The title. - */ -goog.ui.Dialog.prototype.getTitle = function() { - return this.title_; -}; - - -/** - * Allows arbitrary HTML to be set in the content element. - * @param {string} html Content HTML. - */ -goog.ui.Dialog.prototype.setContent = function(html) { - this.content_ = html; - if (this.contentEl_) { - this.contentEl_.innerHTML = html; - } -}; - - -/** - * Gets the content HTML of the content element. - * @return {string} Content HTML. - */ -goog.ui.Dialog.prototype.getContent = function() { - return this.content_; -}; - - -/** - * Renders if the DOM is not created. - * @private - */ -goog.ui.Dialog.prototype.renderIfNoDom_ = function() { - if (!this.getElement()) { - // TODO(gboyer): Ideally we'd only create the DOM, but many applications - // are requiring this behavior. Eventually, it would be best if the - // element getters could return null if the elements have not been - // created. - this.render(); - } -}; - - -/** - * Returns the content element so that more complicated things can be done with - * the content area. Renders if the DOM is not yet created. Overrides - * {@link goog.ui.Component#getContentElement}. - * @return {Element} The content element. - */ -goog.ui.Dialog.prototype.getContentElement = function() { - this.renderIfNoDom_(); - return this.contentEl_; -}; - - -/** - * Returns the title element so that more complicated things can be done with - * the title. Renders if the DOM is not yet created. - * @return {Element} The title element. - */ -goog.ui.Dialog.prototype.getTitleElement = function() { - this.renderIfNoDom_(); - return this.titleEl_; -}; - - -/** - * Returns the title text element so that more complicated things can be done - * with the text of the title. Renders if the DOM is not yet created. - * @return {Element} The title text element. - */ -goog.ui.Dialog.prototype.getTitleTextElement = function() { - this.renderIfNoDom_(); - return this.titleTextEl_; -}; - - -/** - * Returns the title close element so that more complicated things can be done - * with the close area of the title. Renders if the DOM is not yet created. - * @return {Element} The close box. - */ -goog.ui.Dialog.prototype.getTitleCloseElement = function() { - this.renderIfNoDom_(); - return this.titleCloseEl_; -}; - - -/** - * Returns the button element so that more complicated things can be done with - * the button area. Renders if the DOM is not yet created. - * @return {Element} The button container element. - */ -goog.ui.Dialog.prototype.getButtonElement = function() { - this.renderIfNoDom_(); - return this.buttonEl_; -}; - - -/** - * Returns the dialog element so that more complicated things can be done with - * the dialog box. Renders if the DOM is not yet created. - * @return {Element} The dialog element. - */ -goog.ui.Dialog.prototype.getDialogElement = function() { - this.renderIfNoDom_(); - return this.getElement(); -}; - - -/** - * Returns the background mask element so that more complicated things can be - * done with the background region. Renders if the DOM is not yet created. - * @return {Element} The background mask element. - */ -goog.ui.Dialog.prototype.getBackgroundElement = function() { - this.renderIfNoDom_(); - return goog.base(this, 'getBackgroundElement'); -}; - - -/** - * Gets the opacity of the background mask. - * @return {number} Background mask opacity. - */ -goog.ui.Dialog.prototype.getBackgroundElementOpacity = function() { - return this.backgroundElementOpacity_; -}; - - -/** - * Sets the opacity of the background mask. - * @param {number} opacity Background mask opacity. - */ -goog.ui.Dialog.prototype.setBackgroundElementOpacity = function(opacity) { - this.backgroundElementOpacity_ = opacity; - - if (this.getElement()) { - var bgEl = this.getBackgroundElement(); - if (bgEl) { - goog.style.setOpacity(bgEl, this.backgroundElementOpacity_); - } - } -}; - - -/** - * Sets the modal property of the dialog. In case the dialog is already - * inDocument, renders the modal background elements according to the specified - * modal parameter. - * - * Note that non-modal dialogs cannot use an iframe mask. - * - * @param {boolean} modal Whether the dialog is modal. - */ -goog.ui.Dialog.prototype.setModal = function(modal) { - if (modal != this.modal_) { - this.setModalInternal_(modal); - } -}; - - -/** - * Sets the modal property of the dialog. - * @param {boolean} modal Whether the dialog is modal. - * @private - */ -goog.ui.Dialog.prototype.setModalInternal_ = function(modal) { - this.modal_ = modal; - if (this.isInDocument()) { - var dom = this.getDomHelper(); - var bg = this.getBackgroundElement(); - var bgIframe = this.getBackgroundIframe(); - if (modal) { - if (bgIframe) { - dom.insertSiblingBefore(bgIframe, this.getElement()); - } - dom.insertSiblingBefore(bg, this.getElement()); - } else { - dom.removeNode(bgIframe); - dom.removeNode(bg); - } - } -}; - - -/** - * @return {boolean} modal Whether the dialog is modal. - */ -goog.ui.Dialog.prototype.getModal = function() { - return this.modal_; -}; - - -/** - * @return {string} The CSS class name for the dialog element. - */ -goog.ui.Dialog.prototype.getClass = function() { - return this.getCssClass(); -}; - - -/** - * Sets whether the dialog can be dragged. - * @param {boolean} draggable Whether the dialog can be dragged. - */ -goog.ui.Dialog.prototype.setDraggable = function(draggable) { - this.draggable_ = draggable; - this.setDraggingEnabled_(draggable && this.isInDocument()); -}; - - -/** - * Returns a dragger for moving the dialog and adds a class for the move cursor. - * Defaults to allow dragging of the title only, but can be overridden if - * different drag targets or dragging behavior is desired. - * @return {!goog.fx.Dragger} The created dragger instance. - * @protected - */ -goog.ui.Dialog.prototype.createDragger = function() { - return new goog.fx.Dragger(this.getElement(), this.titleEl_); -}; - - -/** - * @return {boolean} Whether the dialog is draggable. - */ -goog.ui.Dialog.prototype.getDraggable = function() { - return this.draggable_; -}; - - -/** - * Enables or disables dragging. - * @param {boolean} enabled Whether to enable it. - * @private. - */ -goog.ui.Dialog.prototype.setDraggingEnabled_ = function(enabled) { - if (this.getElement()) { - goog.dom.classes.enable(this.titleEl_, - goog.getCssName(this.class_, 'title-draggable'), enabled); - } - - if (enabled && !this.dragger_) { - this.dragger_ = this.createDragger(); - goog.dom.classes.add(this.titleEl_, - goog.getCssName(this.class_, 'title-draggable')); - goog.events.listen(this.dragger_, goog.fx.Dragger.EventType.START, - this.setDraggerLimits_, false, this); - } else if (!enabled && this.dragger_) { - this.dragger_.dispose(); - this.dragger_ = null; - } -}; - - -/** @override */ -goog.ui.Dialog.prototype.createDom = function() { - goog.base(this, 'createDom'); - var element = this.getElement(); - goog.asserts.assert(element, 'getElement() returns null'); - - var dom = this.getDomHelper(); - this.titleEl_ = dom.createDom('div', - {'className': goog.getCssName(this.class_, 'title'), 'id': this.getId()}, - this.titleTextEl_ = dom.createDom( - 'span', goog.getCssName(this.class_, 'title-text'), this.title_), - this.titleCloseEl_ = dom.createDom( - 'span', goog.getCssName(this.class_, 'title-close'))), - goog.dom.append(element, this.titleEl_, - this.contentEl_ = dom.createDom('div', - goog.getCssName(this.class_, 'content')), - this.buttonEl_ = dom.createDom('div', - goog.getCssName(this.class_, 'buttons'))); - - this.titleId_ = this.titleEl_.id; - goog.dom.a11y.setRole(element, 'dialog'); - goog.dom.a11y.setState(element, 'labelledby', this.titleId_ || ''); - // If setContent() was called before createDom(), make sure the inner HTML of - // the content element is initialized. - if (this.content_) { - this.contentEl_.innerHTML = this.content_; - } - goog.style.showElement(this.titleCloseEl_, this.hasTitleCloseButton_); - - // Render the buttons. - if (this.buttons_) { - this.buttons_.attachToElement(this.buttonEl_); - } - goog.style.showElement(this.buttonEl_, !!this.buttons_); - this.setBackgroundElementOpacity(this.backgroundElementOpacity_); -}; - - -/** @override */ -goog.ui.Dialog.prototype.decorateInternal = function(element) { - goog.base(this, 'decorateInternal', element); - - // Decorate or create the content element. - var contentClass = goog.getCssName(this.class_, 'content'); - this.contentEl_ = goog.dom.getElementsByTagNameAndClass( - null, contentClass, this.getElement())[0]; - if (this.contentEl_) { - this.content_ = this.contentEl_.innerHTML; - } else { - this.contentEl_ = this.getDomHelper().createDom('div', contentClass); - if (this.content_) { - this.contentEl_.innerHTML = this.content_; - } - this.getElement().appendChild(this.contentEl_); - } - - // Decorate or create the title bar element. - var titleClass = goog.getCssName(this.class_, 'title'); - var titleTextClass = goog.getCssName(this.class_, 'title-text'); - var titleCloseClass = goog.getCssName(this.class_, 'title-close'); - this.titleEl_ = goog.dom.getElementsByTagNameAndClass( - null, titleClass, this.getElement())[0]; - if (this.titleEl_) { - // Only look for title text & title close elements if a title bar element - // was found. Otherwise assume that the entire title bar has to be - // created from scratch. - this.titleTextEl_ = goog.dom.getElementsByTagNameAndClass( - null, titleTextClass, this.titleEl_)[0]; - this.titleCloseEl_ = goog.dom.getElementsByTagNameAndClass( - null, titleCloseClass, this.titleEl_)[0]; - } else { - // Create the title bar element and insert it before the content area. - // This is useful if the element to decorate only includes a content area. - this.titleEl_ = this.getDomHelper().createDom('div', titleClass); - this.getElement().insertBefore(this.titleEl_, this.contentEl_); - } - - // Decorate or create the title text element. - if (this.titleTextEl_) { - this.title_ = goog.dom.getTextContent(this.titleTextEl_); - } else { - this.titleTextEl_ = this.getDomHelper().createDom('span', titleTextClass, - this.title_); - this.titleEl_.appendChild(this.titleTextEl_); - } - goog.dom.a11y.setState(this.getElement(), 'labelledby', this.titleId_ || ''); - // Decorate or create the title close element. - if (!this.titleCloseEl_) { - this.titleCloseEl_ = this.getDomHelper().createDom('span', titleCloseClass); - this.titleEl_.appendChild(this.titleCloseEl_); - } - goog.style.showElement(this.titleCloseEl_, this.hasTitleCloseButton_); - - // Decorate or create the button container element. - var buttonsClass = goog.getCssName(this.class_, 'buttons'); - this.buttonEl_ = goog.dom.getElementsByTagNameAndClass( - null, buttonsClass, this.getElement())[0]; - if (this.buttonEl_) { - // Button container element found. Create empty button set and use it to - // decorate the button container. - this.buttons_ = new goog.ui.Dialog.ButtonSet(this.getDomHelper()); - this.buttons_.decorate(this.buttonEl_); - } else { - // Create new button container element, and render a button set into it. - this.buttonEl_ = this.getDomHelper().createDom('div', buttonsClass); - this.getElement().appendChild(this.buttonEl_); - if (this.buttons_) { - this.buttons_.attachToElement(this.buttonEl_); - } - goog.style.showElement(this.buttonEl_, !!this.buttons_); - } - this.setBackgroundElementOpacity(this.backgroundElementOpacity_); -}; - - -/** @override */ -goog.ui.Dialog.prototype.enterDocument = function() { - goog.base(this, 'enterDocument'); - - this.getHandler().listen(this, - [goog.ui.PopupBase.EventType.SHOW, goog.ui.PopupBase.EventType.HIDE], - this.setVisibleInternal_); - - // Add drag support. - this.setDraggingEnabled_(this.draggable_); - - // Add event listeners to the close box and the button container. - this.getHandler().listen( - this.titleCloseEl_, goog.events.EventType.CLICK, - this.onTitleCloseClick_); - - goog.dom.a11y.setRole(this.getElement(), 'dialog'); - if (this.titleTextEl_.id !== '') { - goog.dom.a11y.setState( - this.getElement(), 'labelledby', this.titleTextEl_.id); - } - - if (!this.modal_) { - this.setModalInternal_(false); - } -}; - - -/** @override */ -goog.ui.Dialog.prototype.exitDocument = function() { - if (this.isVisible()) { - this.setVisible(false); - } - - // Remove drag support. - this.setDraggingEnabled_(false); - - goog.base(this, 'exitDocument'); -}; - - -/** - * Sets the visibility of the dialog box and moves focus to the default button. - * Lazily renders the component if needed. - * @param {boolean} visible Whether the dialog should be visible. - */ -goog.ui.Dialog.prototype.setVisible = function(visible) { - if (visible == this.isVisible()) { - return; - } - - // If the dialog hasn't been rendered yet, render it now. - if (!this.isInDocument()) { - this.render(); - } - - goog.base(this, 'setVisible', visible); -}; - - -/** - * Sets visibility after super class setVisible is completed. - * @param {goog.events.Event} e The event object. - * @private - */ -goog.ui.Dialog.prototype.setVisibleInternal_ = function(e) { - if (e.target != this) { - return; - } - - var visible = this.isVisible(); - - if (visible) { - // Listen for keyboard and resize events while the dialog is visible. - this.getHandler(). - listen(this.getElement(), goog.events.EventType.KEYDOWN, this.onKey_). - listen(this.getElement(), goog.events.EventType.KEYPRESS, this.onKey_); - - this.dispatchEvent(goog.ui.Dialog.EventType.AFTER_SHOW); - // NOTE: see bug 1163154 for an example of an edge case where making the - // dialog visible in response to a KEYDOWN will result in a CLICK event - // firing on the default button (immediately closing the dialog) if the key - // that fired the KEYDOWN is also normally used to activate controls - // (i.e. SPACE/ENTER). - // - // This could be worked around by attaching the onButtonClick_ handler in a - // setTimeout, but that was deemed undesirable. - this.getHandler().listen(this.buttonEl_, goog.events.EventType.CLICK, - this.onButtonClick_); - } else { - // Stop listening for keyboard and resize events while the dialog is hidden. - this.getHandler(). - unlisten(this.getElement(), goog.events.EventType.KEYDOWN, this.onKey_). - unlisten(this.getElement(), goog.events.EventType.KEYPRESS, - this.onKey_). - unlisten(this.buttonEl_, goog.events.EventType.CLICK, - this.onButtonClick_); - - this.dispatchEvent(goog.ui.Dialog.EventType.AFTER_HIDE); - if (this.disposeOnHide_) { - this.dispose(); - } - } -}; - - -/** - * Focuses the dialog contents and the default dialog button if there is one. - */ -goog.ui.Dialog.prototype.focus = function() { - goog.base(this, 'focus'); - - // Move focus to the default button (if any). - if (this.getButtonSet()) { - var defaultButton = this.getButtonSet().getDefault(); - if (defaultButton) { - var doc = this.getDomHelper().getDocument(); - var buttons = this.buttonEl_.getElementsByTagName('button'); - for (var i = 0, button; button = buttons[i]; i++) { - if (button.name == defaultButton) { - try { - // Reopening a dialog can cause focusing the button to fail in - // WebKit and Opera. Shift the focus to a temporary <input> - // element to make refocusing the button possible. - if (goog.userAgent.WEBKIT || goog.userAgent.OPERA) { - var temp = doc.createElement('input'); - temp.style.cssText = - 'position:fixed;width:0;height:0;left:0;top:0;'; - this.getElement().appendChild(temp); - temp.focus(); - this.getElement().removeChild(temp); - } - button.focus(); - } catch (e) { - // Swallow this. Could be the button is disabled - // and IE6 wishes to throw an error. - } - break; - } - } - } - } -}; - - -/** - * Sets dragger limits when dragging is started. - * @param {!goog.events.Event} e goog.fx.Dragger.EventType.START event. - * @private - */ -goog.ui.Dialog.prototype.setDraggerLimits_ = function(e) { - var doc = this.getDomHelper().getDocument(); - var win = goog.dom.getWindow(doc) || window; - - // Take the max of scroll height and view height for cases in which document - // does not fill screen. - var viewSize = goog.dom.getViewportSize(win); - var w = Math.max(doc.body.scrollWidth, viewSize.width); - var h = Math.max(doc.body.scrollHeight, viewSize.height); - - var dialogSize = goog.style.getSize(this.getElement()); - if (goog.style.getComputedPosition(this.getElement()) == 'fixed') { - // Ensure position:fixed dialogs can't be dragged beyond the viewport. - this.dragger_.setLimits(new goog.math.Rect(0, 0, - Math.max(0, viewSize.width - dialogSize.width), - Math.max(0, viewSize.height - dialogSize.height))); - } else { - this.dragger_.setLimits(new goog.math.Rect(0, 0, - w - dialogSize.width, h - dialogSize.height)); - } -}; - - -/** - * Handles a click on the title close area. - * @param {goog.events.BrowserEvent} e Browser's event object. - * @private - */ -goog.ui.Dialog.prototype.onTitleCloseClick_ = function(e) { - if (!this.hasTitleCloseButton_) { - return; - } - - var bs = this.getButtonSet(); - var key = bs && bs.getCancel(); - // Only if there is a valid cancel button is an event dispatched. - if (key) { - var caption = /** @type {Element|string} */(bs.get(key)); - if (this.dispatchEvent(new goog.ui.Dialog.Event(key, caption))) { - this.setVisible(false); - } - } else { - this.setVisible(false); - } -}; - - -/** - * @return {boolean} Whether this dialog has a title close button. - */ -goog.ui.Dialog.prototype.getHasTitleCloseButton = function() { - return this.hasTitleCloseButton_; -}; - - -/** - * Sets whether the dialog should have a close button in the title bar. There - * will always be an element for the title close button, but setting this - * parameter to false will cause it to be hidden and have no active listener. - * @param {boolean} b Whether this dialog should have a title close button. - */ -goog.ui.Dialog.prototype.setHasTitleCloseButton = function(b) { - this.hasTitleCloseButton_ = b; - if (this.titleCloseEl_) { - goog.style.showElement(this.titleCloseEl_, this.hasTitleCloseButton_); - } -}; - - -/** - * @return {boolean} Whether the escape key should close this dialog. - */ -goog.ui.Dialog.prototype.isEscapeToCancel = function() { - return this.escapeToCancel_; -}; - - -/** - * @param {boolean} b Whether the escape key should close this dialog. - */ -goog.ui.Dialog.prototype.setEscapeToCancel = function(b) { - this.escapeToCancel_ = b; -}; - - -/** - * Sets whether the dialog should be disposed when it is hidden. By default - * dialogs are not disposed when they are hidden. - * @param {boolean} b Whether the dialog should get disposed when it gets - * hidden. - */ -goog.ui.Dialog.prototype.setDisposeOnHide = function(b) { - this.disposeOnHide_ = b; -}; - - -/** - * @return {boolean} Whether the dialog should be disposed when it is hidden. - */ -goog.ui.Dialog.prototype.getDisposeOnHide = function() { - return this.disposeOnHide_; -}; - - -/** @override */ -goog.ui.Dialog.prototype.disposeInternal = function() { - this.titleCloseEl_ = null; - this.buttonEl_ = null; - goog.base(this, 'disposeInternal'); -}; - - -/** - * Sets the button set to use. - * Note: Passing in null will cause no button set to be rendered. - * @param {goog.ui.Dialog.ButtonSet?} buttons The button set to use. - */ -goog.ui.Dialog.prototype.setButtonSet = function(buttons) { - this.buttons_ = buttons; - if (this.buttonEl_) { - if (this.buttons_) { - this.buttons_.attachToElement(this.buttonEl_); - } else { - this.buttonEl_.innerHTML = ''; - } - goog.style.showElement(this.buttonEl_, !!this.buttons_); - } -}; - - -/** - * Returns the button set being used. - * @return {goog.ui.Dialog.ButtonSet?} The button set being used. - */ -goog.ui.Dialog.prototype.getButtonSet = function() { - return this.buttons_; -}; - - -/** - * Handles a click on the button container. - * @param {goog.events.BrowserEvent} e Browser's event object. - * @private - */ -goog.ui.Dialog.prototype.onButtonClick_ = function(e) { - var button = this.findParentButton_(/** @type {Element} */ (e.target)); - if (button && !button.disabled) { - var key = button.name; - var caption = /** @type {Element|string} */( - this.getButtonSet().get(key)); - if (this.dispatchEvent(new goog.ui.Dialog.Event(key, caption))) { - this.setVisible(false); - } - } -}; - - -/** - * Finds the parent button of an element (or null if there was no button - * parent). - * @param {Element} element The element that was clicked on. - * @return {Element} Returns the parent button or null if not found. - * @private - */ -goog.ui.Dialog.prototype.findParentButton_ = function(element) { - var el = element; - while (el != null && el != this.buttonEl_) { - if (el.tagName == 'BUTTON') { - return /** @type {Element} */(el); - } - el = el.parentNode; - } - return null; -}; - - -/** - * Handles keydown and keypress events, and dismisses the popup if cancel is - * pressed. If there is a cancel action in the ButtonSet, than that will be - * fired. Also prevents tabbing out of the dialog. - * @param {goog.events.BrowserEvent} e Browser's event object. - * @private - */ -goog.ui.Dialog.prototype.onKey_ = function(e) { - var close = false; - var hasHandler = false; - var buttonSet = this.getButtonSet(); - var target = e.target; - - if (e.type == goog.events.EventType.KEYDOWN) { - // Escape and tab can only properly be handled in keydown handlers. - if (this.escapeToCancel_ && e.keyCode == goog.events.KeyCodes.ESC) { - // Only if there is a valid cancel button is an event dispatched. - var cancel = buttonSet && buttonSet.getCancel(); - - // Users may expect to hit escape on a SELECT element. - var isSpecialFormElement = - target.tagName == 'SELECT' && !target.disabled; - - if (cancel && !isSpecialFormElement) { - hasHandler = true; - - var caption = buttonSet.get(cancel); - close = this.dispatchEvent( - new goog.ui.Dialog.Event(cancel, - /** @type {Element|null|string} */(caption))); - } else if (!isSpecialFormElement) { - close = true; - } - } else if (e.keyCode == goog.events.KeyCodes.TAB && e.shiftKey && - target == this.getElement()) { - // Prevent the user from shift-tabbing backwards out of the dialog box. - // TODO(user): Instead, we should move the focus to the last tabbable - // element inside the dialog. - hasHandler = true; - } - } else if (e.keyCode == goog.events.KeyCodes.ENTER) { - // Only handle ENTER in keypress events, in case the action opens a - // popup window. - var key; - if (target.tagName == 'BUTTON') { - // If focus was on a button, it must have been enabled, so we can fire - // that button's handler. - key = target.name; - } else if (buttonSet) { - // Try to fire the default button's handler (if one exists), but only if - // the button is enabled. - var defaultKey = buttonSet.getDefault(); - var defaultButton = defaultKey && buttonSet.getButton(defaultKey); - - // Users may expect to hit enter on a TEXTAREA or a SELECT element. - var isSpecialFormElement = - (target.tagName == 'TEXTAREA' || target.tagName == 'SELECT') && - !target.disabled; - - if (defaultButton && !defaultButton.disabled && !isSpecialFormElement) { - key = defaultKey; - } - } - if (key && buttonSet) { - hasHandler = true; - close = this.dispatchEvent( - new goog.ui.Dialog.Event(key, String(buttonSet.get(key)))); - } - } - - if (close || hasHandler) { - e.stopPropagation(); - e.preventDefault(); - } - - if (close) { - this.setVisible(false); - } -}; - - - -/** - * Dialog event class. - * @param {string} key Key identifier for the button. - * @param {string|Element} caption Caption on the button (might be i18nlized). - * @constructor - * @extends {goog.events.Event} - */ -goog.ui.Dialog.Event = function(key, caption) { - this.type = goog.ui.Dialog.EventType.SELECT; - this.key = key; - this.caption = caption; -}; -goog.inherits(goog.ui.Dialog.Event, goog.events.Event); - - -/** - * Event type constant for dialog events. - * TODO(attila): Change this to goog.ui.Dialog.EventType.SELECT. - * @type {string} - * @deprecated Use goog.ui.Dialog.EventType.SELECT. - */ -goog.ui.Dialog.SELECT_EVENT = 'dialogselect'; - - -/** - * Events dispatched by dialogs. - * @enum {string} - */ -goog.ui.Dialog.EventType = { - /** - * Dispatched when the user closes the dialog. - * The dispatched event will always be of type {@link goog.ui.Dialog.Event}. - * Canceling the event will prevent the dialog from closing. - */ - SELECT: 'dialogselect', - - /** - * Dispatched after the dialog is closed. Not cancelable. - * @deprecated Use goog.ui.PopupBase.EventType.HIDE. - */ - AFTER_HIDE: 'afterhide', - - /** - * Dispatched after the dialog is shown. Not cancelable. - * @deprecated Use goog.ui.PopupBase.EventType.SHOW. - */ - AFTER_SHOW: 'aftershow' -}; - - - -/** - * A button set defines the behaviour of a set of buttons that the dialog can - * show. Uses the {@link goog.structs.Map} interface. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper; see {@link - * goog.ui.Component} for semantics. - * @constructor - * @extends {goog.structs.Map} - */ -goog.ui.Dialog.ButtonSet = function(opt_domHelper) { - // TODO(attila): Refactor ButtonSet to extend goog.ui.Component? - this.dom_ = opt_domHelper || goog.dom.getDomHelper(); - goog.structs.Map.call(this); -}; -goog.inherits(goog.ui.Dialog.ButtonSet, goog.structs.Map); - - -/** - * A CSS className for this component. - * @type {string} - * @private - */ -goog.ui.Dialog.ButtonSet.prototype.class_ = goog.getCssName('goog-buttonset'); - - -/** - * The button that has default focus (references key in buttons_ map). - * @type {?string} - * @private - */ -goog.ui.Dialog.ButtonSet.prototype.defaultButton_ = null; - - -/** - * Optional container the button set should be rendered into. - * @type {Element} - * @private - */ -goog.ui.Dialog.ButtonSet.prototype.element_ = null; - - -/** - * The button whose action is associated with the escape key and the X button - * on the dialog. - * @type {?string} - * @private - */ -goog.ui.Dialog.ButtonSet.prototype.cancelButton_ = null; - - -/** - * Adds a button to the button set. Buttons will be displayed in the order they - * are added. - * - * @param {string} key Key used to identify the button in events. - * @param {string|Element} caption A string caption or a DOM node that can be - * appended to a button element. - * @param {boolean=} opt_isDefault Whether this button is the default button, - * Dialog will dispatch for this button if enter is pressed. - * @param {boolean=} opt_isCancel Whether this button has the same behaviour as - * cancel. If escape is pressed this button will fire. - * @return {!goog.ui.Dialog.ButtonSet} The button set, to make it easy to chain - * "set" calls and build new ButtonSets. - */ -goog.ui.Dialog.ButtonSet.prototype.set = function(key, caption, - opt_isDefault, opt_isCancel) { - goog.structs.Map.prototype.set.call(this, key, caption); - - if (opt_isDefault) { - this.defaultButton_ = key; - } - if (opt_isCancel) { - this.cancelButton_ = key; - } - - return this; -}; - - -/** - * Adds a button (an object with a key and caption) to this button set. Buttons - * will be displayed in the order they are added. - * @see goog.ui.Dialog.DefaultButtons - * @param {!{key: string, caption: string}} button The button key and caption. - * @param {boolean=} opt_isDefault Whether this button is the default button. - * Dialog will dispatch for this button if enter is pressed. - * @param {boolean=} opt_isCancel Whether this button has the same behavior as - * cancel. If escape is pressed this button will fire. - * @return {!goog.ui.Dialog.ButtonSet} The button set, to make it easy to chain - * "addButton" calls and build new ButtonSets. - */ -goog.ui.Dialog.ButtonSet.prototype.addButton = function(button, opt_isDefault, - opt_isCancel) { - return this.set(button.key, button.caption, opt_isDefault, opt_isCancel); -}; - - -/** - * Attaches the button set to an element, rendering it inside. - * @param {Element} el Container. - */ -goog.ui.Dialog.ButtonSet.prototype.attachToElement = function(el) { - this.element_ = el; - this.render(); -}; - - -/** - * Renders the button set inside its container element. - */ -goog.ui.Dialog.ButtonSet.prototype.render = function() { - if (this.element_) { - this.element_.innerHTML = ''; - var domHelper = goog.dom.getDomHelper(this.element_); - goog.structs.forEach(this, function(caption, key) { - var button = domHelper.createDom('button', {'name': key}, caption); - if (key == this.defaultButton_) { - button.className = goog.getCssName(this.class_, 'default'); - } - this.element_.appendChild(button); - }, this); - } -}; - - -/** - * Decorates the given element by adding any {@code button} elements found - * among its descendants to the button set. The first button found is assumed - * to be the default and will receive focus when the button set is rendered. - * If a button with a name of {@link goog.ui.Dialog.DefaultButtonKeys.CANCEL} - * is found, it is assumed to have "Cancel" semantics. - * TODO(attila): ButtonSet should be a goog.ui.Component. Really. - * @param {Element} element The element to decorate; should contain buttons. - */ -goog.ui.Dialog.ButtonSet.prototype.decorate = function(element) { - if (!element || element.nodeType != goog.dom.NodeType.ELEMENT) { - return; - } - - this.element_ = element; - var buttons = this.element_.getElementsByTagName('button'); - for (var i = 0, button, key, caption; button = buttons[i]; i++) { - // Buttons should have a "name" attribute and have their caption defined by - // their innerHTML, but not everyone knows this, and we should play nice. - key = button.name || button.id; - caption = goog.dom.getTextContent(button) || button.value; - if (key) { - var isDefault = i == 0; - var isCancel = button.name == goog.ui.Dialog.DefaultButtonKeys.CANCEL; - this.set(key, caption, isDefault, isCancel); - if (isDefault) { - goog.dom.classes.add(button, goog.getCssName(this.class_, - 'default')); - } - } - } -}; - - -/** - * Gets the component's element. - * @return {Element} The element for the component. - * TODO(user): Remove after refactoring to goog.ui.Component. - */ -goog.ui.Dialog.ButtonSet.prototype.getElement = function() { - return this.element_; -}; - - -/** - * Returns the dom helper that is being used on this component. - * @return {!goog.dom.DomHelper} The dom helper used on this component. - * TODO(user): Remove after refactoring to goog.ui.Component. - */ -goog.ui.Dialog.ButtonSet.prototype.getDomHelper = function() { - return this.dom_; -}; - - -/** - * Sets the default button. - * @param {?string} key The default button. - */ -goog.ui.Dialog.ButtonSet.prototype.setDefault = function(key) { - this.defaultButton_ = key; -}; - - -/** - * Returns the default button. - * @return {?string} The default button. - */ -goog.ui.Dialog.ButtonSet.prototype.getDefault = function() { - return this.defaultButton_; -}; - - -/** - * Sets the cancel button. - * @param {?string} key The cancel button. - */ -goog.ui.Dialog.ButtonSet.prototype.setCancel = function(key) { - this.cancelButton_ = key; -}; - - -/** - * Returns the cancel button. - * @return {?string} The cancel button. - */ -goog.ui.Dialog.ButtonSet.prototype.getCancel = function() { - return this.cancelButton_; -}; - - -/** - * Returns the HTML Button element. - * @param {string} key The button to return. - * @return {Element} The button, if found else null. - */ -goog.ui.Dialog.ButtonSet.prototype.getButton = function(key) { - var buttons = this.getAllButtons(); - for (var i = 0, nextButton; nextButton = buttons[i]; i++) { - if (nextButton.name == key || nextButton.id == key) { - return nextButton; - } - } - return null; -}; - - -/** - * Returns all the HTML Button elements in the button set container. - * @return {NodeList} A live NodeList of the buttons. - */ -goog.ui.Dialog.ButtonSet.prototype.getAllButtons = function() { - return this.element_.getElementsByTagName(goog.dom.TagName.BUTTON); -}; - - -/** - * Enables or disables a button in this set by key. If the button is not found, - * does nothing. - * @param {string} key The button to enable or disable. - * @param {boolean} enabled True to enable; false to disable. - */ -goog.ui.Dialog.ButtonSet.prototype.setButtonEnabled = function(key, enabled) { - var button = this.getButton(key); - if (button) { - button.disabled = !enabled; - } -}; - - -/** - * Enables or disables all of the buttons in this set. - * @param {boolean} enabled True to enable; false to disable. - */ -goog.ui.Dialog.ButtonSet.prototype.setAllButtonsEnabled = function(enabled) { - var allButtons = this.getAllButtons(); - for (var i = 0, button; button = allButtons[i]; i++) { - button.disabled = !enabled; - } -}; - - -/** - * The keys used to identify standard buttons in events. - * @enum {string} - */ -goog.ui.Dialog.DefaultButtonKeys = { - OK: 'ok', - CANCEL: 'cancel', - YES: 'yes', - NO: 'no', - SAVE: 'save', - CONTINUE: 'continue' -}; - - -/** - * @desc Standard caption for the dialog 'OK' button. - * @private - */ -goog.ui.Dialog.MSG_DIALOG_OK_ = goog.getMsg('OK'); - - -/** - * @desc Standard caption for the dialog 'Cancel' button. - * @private - */ -goog.ui.Dialog.MSG_DIALOG_CANCEL_ = goog.getMsg('Cancel'); - - -/** - * @desc Standard caption for the dialog 'Yes' button. - * @private - */ -goog.ui.Dialog.MSG_DIALOG_YES_ = goog.getMsg('Yes'); - - -/** - * @desc Standard caption for the dialog 'No' button. - * @private - */ -goog.ui.Dialog.MSG_DIALOG_NO_ = goog.getMsg('No'); - - -/** - * @desc Standard caption for the dialog 'Save' button. - * @private - */ -goog.ui.Dialog.MSG_DIALOG_SAVE_ = goog.getMsg('Save'); - - -/** - * @desc Standard caption for the dialog 'Continue' button. - * @private - */ -goog.ui.Dialog.MSG_DIALOG_CONTINUE_ = goog.getMsg('Continue'); - - -/** - * The default captions for the default buttons. - * @enum {string} - */ -goog.ui.Dialog.DefaultButtonCaptions = { - OK: goog.ui.Dialog.MSG_DIALOG_OK_, - CANCEL: goog.ui.Dialog.MSG_DIALOG_CANCEL_, - YES: goog.ui.Dialog.MSG_DIALOG_YES_, - NO: goog.ui.Dialog.MSG_DIALOG_NO_, - SAVE: goog.ui.Dialog.MSG_DIALOG_SAVE_, - CONTINUE: goog.ui.Dialog.MSG_DIALOG_CONTINUE_ -}; - - -/** - * The standard buttons (keys associated with captions). - * @enum {!{key: string, caption: string}} - */ -goog.ui.Dialog.ButtonSet.DefaultButtons = { - OK: { - key: goog.ui.Dialog.DefaultButtonKeys.OK, - caption: goog.ui.Dialog.DefaultButtonCaptions.OK - }, - CANCEL: { - key: goog.ui.Dialog.DefaultButtonKeys.CANCEL, - caption: goog.ui.Dialog.DefaultButtonCaptions.CANCEL - }, - YES: { - key: goog.ui.Dialog.DefaultButtonKeys.YES, - caption: goog.ui.Dialog.DefaultButtonCaptions.YES - }, - NO: { - key: goog.ui.Dialog.DefaultButtonKeys.NO, - caption: goog.ui.Dialog.DefaultButtonCaptions.NO - }, - SAVE: { - key: goog.ui.Dialog.DefaultButtonKeys.SAVE, - caption: goog.ui.Dialog.DefaultButtonCaptions.SAVE - }, - CONTINUE: { - key: goog.ui.Dialog.DefaultButtonKeys.CONTINUE, - caption: goog.ui.Dialog.DefaultButtonCaptions.CONTINUE - } -}; - - -/** - * Creates a new ButtonSet with a single 'OK' button, which is also set with - * cancel button semantics so that pressing escape will close the dialog. - * @return {!goog.ui.Dialog.ButtonSet} The created ButtonSet. - */ -goog.ui.Dialog.ButtonSet.createOk = function() { - return new goog.ui.Dialog.ButtonSet(). - addButton(goog.ui.Dialog.ButtonSet.DefaultButtons.OK, true, true); -}; - - -/** - * Creates a new ButtonSet with 'OK' (default) and 'Cancel' buttons. - * @return {!goog.ui.Dialog.ButtonSet} The created ButtonSet. - */ -goog.ui.Dialog.ButtonSet.createOkCancel = function() { - return new goog.ui.Dialog.ButtonSet(). - addButton(goog.ui.Dialog.ButtonSet.DefaultButtons.OK, true). - addButton(goog.ui.Dialog.ButtonSet.DefaultButtons.CANCEL, false, true); -}; - - -/** - * Creates a new ButtonSet with 'Yes' (default) and 'No' buttons. - * @return {!goog.ui.Dialog.ButtonSet} The created ButtonSet. - */ -goog.ui.Dialog.ButtonSet.createYesNo = function() { - return new goog.ui.Dialog.ButtonSet(). - addButton(goog.ui.Dialog.ButtonSet.DefaultButtons.YES, true). - addButton(goog.ui.Dialog.ButtonSet.DefaultButtons.NO, false, true); -}; - - -/** - * Creates a new ButtonSet with 'Yes', 'No' (default), and 'Cancel' buttons. - * @return {!goog.ui.Dialog.ButtonSet} The created ButtonSet. - */ -goog.ui.Dialog.ButtonSet.createYesNoCancel = function() { - return new goog.ui.Dialog.ButtonSet(). - addButton(goog.ui.Dialog.ButtonSet.DefaultButtons.YES). - addButton(goog.ui.Dialog.ButtonSet.DefaultButtons.NO, true). - addButton(goog.ui.Dialog.ButtonSet.DefaultButtons.CANCEL, false, true); -}; - - -/** - * Creates a new ButtonSet with 'Continue', 'Save', and 'Cancel' (default) - * buttons. - * @return {!goog.ui.Dialog.ButtonSet} The created ButtonSet. - */ -goog.ui.Dialog.ButtonSet.createContinueSaveCancel = function() { - return new goog.ui.Dialog.ButtonSet(). - addButton(goog.ui.Dialog.ButtonSet.DefaultButtons.CONTINUE). - addButton(goog.ui.Dialog.ButtonSet.DefaultButtons.SAVE). - addButton(goog.ui.Dialog.ButtonSet.DefaultButtons.CANCEL, true, true); -}; - - -// TODO(user): These shared instances should be phased out. -(function() { - if (typeof document != 'undefined') { - /** @deprecated Use goog.ui.Dialog.ButtonSet#createOk. */ - goog.ui.Dialog.ButtonSet.OK = goog.ui.Dialog.ButtonSet.createOk(); - - /** @deprecated Use goog.ui.Dialog.ButtonSet#createOkCancel. */ - goog.ui.Dialog.ButtonSet.OK_CANCEL = - goog.ui.Dialog.ButtonSet.createOkCancel(); - - /** @deprecated Use goog.ui.Dialog.ButtonSet#createYesNo. */ - goog.ui.Dialog.ButtonSet.YES_NO = goog.ui.Dialog.ButtonSet.createYesNo(); - - /** @deprecated Use goog.ui.Dialog.ButtonSet#createYesNoCancel. */ - goog.ui.Dialog.ButtonSet.YES_NO_CANCEL = - goog.ui.Dialog.ButtonSet.createYesNoCancel(); - - /** @deprecated Use goog.ui.Dialog.ButtonSet#createContinueSaveCancel. */ - goog.ui.Dialog.ButtonSet.CONTINUE_SAVE_CANCEL = - goog.ui.Dialog.ButtonSet.createContinueSaveCancel(); - } -})(); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dialog_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dialog_test.html.svn-base deleted file mode 100644 index 440e343..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dialog_test.html.svn-base +++ /dev/null @@ -1,609 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2007 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.Dialog</title> -<script src="../base.js"></script> -<script> - goog.require('goog.ui.Dialog'); - goog.require('goog.ui.Dialog.ButtonSet'); - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.events.EventType'); - goog.require('goog.style'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.recordFunction'); -</script> -</head> -<body> -<iframe id="f" src="javascript:'<input>'"></iframe> -<script> - var decorateTarget; - var dialog; - - function setUp() { - dialog = new goog.ui.Dialog(); - var buttons = new goog.ui.Dialog.ButtonSet(); - buttons.set(goog.ui.Dialog.DefaultButtonKeys.CANCEL, - 'Foo!', - false, - true); - buttons.set(goog.ui.Dialog.DefaultButtonKeys.OK, - 'OK', - true); - dialog.setButtonSet(buttons); - dialog.setVisible(true); - - decorateTarget = goog.dom.createDom('div'); - document.body.appendChild(decorateTarget); - } - - function tearDown() { - dialog.dispose(); - goog.dom.removeNode(decorateTarget); - } - - function testCrossFrameFocus() { - // Firefox (3.6, maybe future versions) fails this test when there are too - // many other test files being run concurrently. - if (goog.userAgent.IE || goog.userAgent.GECKO) { - return; - } - dialog.setVisible(false); - var iframeWindow = goog.dom.getElement('f').contentWindow; - var iframeInput = iframeWindow.document.getElementsByTagName('input')[0]; - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.OK); - var buttonElement = dialog.getButtonSet().getButton(0); - var focusCounter = 0; - goog.events.listen(buttonElement, 'focus', function() { - focusCounter++; - }); - iframeInput.focus(); - dialog.setVisible(true); - dialog.setVisible(false); - iframeInput.focus(); - dialog.setVisible(true); - assertEquals(2, focusCounter); - } - - function testNoTitleClose() { - assertTrue(goog.style.isElementShown(dialog.getTitleCloseElement())); - dialog.setHasTitleCloseButton(false); - assertFalse(goog.style.isElementShown(dialog.getTitleCloseElement())); - } - - /** - * Helper that clicks the first button in the dialog and checks if that - * results in a goog.ui.Dialog.EventType.SELECT being dispatched. - * @param {boolean} disableButton Whether to disable the button being - * tested. - * @return {boolean} Whether a goog.ui.Dialog.EventType.SELECT was dispatched. - */ - function checkSelectDispatchedOnButtonClick(disableButton) { - var aButton = dialog.getButtonElement().getElementsByTagName('BUTTON')[0]; - assertNotEquals(aButton, null); - aButton.disabled = disableButton; - var wasCalled = false; - var callRecorder = function() { wasCalled = true; }; - goog.events.listen(dialog, goog.ui.Dialog.EventType.SELECT, callRecorder); - goog.testing.events.fireClickSequence(aButton); - return wasCalled; - } - - function testButtonClicksDispatchSelectEvents() { - assertTrue('Select event should be dispatched' + - ' when clicking on an enabled button', - checkSelectDispatchedOnButtonClick(false)); - } - - function testDisabledButtonClicksDontDispatchSelectEvents() { - assertFalse('Select event should not be dispatched' + - ' when clicking on a disabled button', - checkSelectDispatchedOnButtonClick(true)); - } - - function testEnterKeyDispatchesDefaultSelectEvents() { - var okButton = dialog.getButtonElement().getElementsByTagName('BUTTON')[1]; - assertNotEquals(okButton, null); - var wasCalled = false; - var callRecorder = function() { wasCalled = true; }; - goog.events.listen(dialog, goog.ui.Dialog.EventType.SELECT, callRecorder); - // Test that event is not dispatched when default button is disabled. - okButton.disabled = true; - goog.testing.events.fireKeySequence(dialog.getElement(), - goog.events.KeyCodes.ENTER); - assertFalse(wasCalled); - // Test that event is dispatched when default button is enabled. - okButton.disabled = false; - goog.testing.events.fireKeySequence(dialog.getElement(), - goog.events.KeyCodes.ENTER); - assertTrue(wasCalled); - } - - function testEnterKeyDoesNothingOnSpecialFormElements() { - dialog.setContent('<textarea>Hello dialog</textarea>'); - var textarea = dialog.getContentElement(). - getElementsByTagName('TEXTAREA')[0]; - var wasCalled = false; - var callRecorder = function() { - wasCalled = true; - }; - goog.events.listen(dialog, goog.ui.Dialog.EventType.SELECT, callRecorder); - - // Enter does not fire on the enabled textarea. - goog.testing.events.fireKeySequence(textarea, - goog.events.KeyCodes.ENTER); - assertFalse(wasCalled); - - // Enter fires on the disabled textarea. - textarea.disabled = true; - goog.testing.events.fireKeySequence(textarea, - goog.events.KeyCodes.ENTER); - assertTrue(wasCalled); - } - - function testEscapeKeyDoesNothingOnSpecialFormElements() { - dialog.setContent('<select><option>Hello</option>' + - '<option>dialog</option></select>'); - var select = dialog.getContentElement(). - getElementsByTagName('SELECT')[0]; - var wasCalled = false; - var callRecorder = function() { - wasCalled = true; - }; - goog.events.listen(dialog, goog.ui.Dialog.EventType.SELECT, callRecorder); - - // Escape does not fire on the enabled select box. - goog.testing.events.fireKeySequence(select, - goog.events.KeyCodes.ESC); - assertFalse(wasCalled); - - // Escape fires on the disabled select. - select.disabled = true; - goog.testing.events.fireKeySequence(select, - goog.events.KeyCodes.ESC); - assertTrue(wasCalled); - } - - function testEscapeCloses() { - // If escapeCloses is set to false, the dialog should ignore the escape key - assertTrue(dialog.isEscapeToCancel()); - dialog.setEscapeToCancel(false); - assertFalse(dialog.isEscapeToCancel()); - - var buttons = new goog.ui.Dialog.ButtonSet(); - buttons.set(goog.ui.Dialog.DefaultButtonKeys.OK, 'OK', true); - dialog.setButtonSet(buttons); - goog.testing.events.fireKeySequence(dialog.getContentElement(), - goog.events.KeyCodes.ESC); - assertTrue(dialog.isVisible()); - - // Having a cancel button should make no difference, escape should still not - // work. - buttons.set(goog.ui.Dialog.DefaultButtonKeys.CANCEL, 'Foo!', false, true); - dialog.setButtonSet(buttons); - goog.testing.events.fireKeySequence(dialog.getContentElement(), - goog.events.KeyCodes.ESC); - assertTrue(dialog.isVisible()); - } - - function testKeydownClosesWithoutButtonSet() { - // Clear button set - dialog.setButtonSet(null); - - // Create a custom button. - dialog.setContent('<button id="button" name="ok">OK</button>'); - var wasCalled = false; - function called() { - wasCalled = true; - } - var element = goog.dom.getElement('button'); - goog.events.listen(element, goog.events.EventType.KEYPRESS, called); - // Listen for 'Enter' on the button. - // This tests using a dialog with no ButtonSet that has been set. Uses - // a custom button. The callback should be called with no exception thrown. - goog.testing.events.fireKeySequence(element, goog.events.KeyCodes.ENTER); - assertTrue('Should have gotten event on the button.', wasCalled); - } - - function testEnterKeyWithoutDefaultDoesNotPreventPropagation() { - var buttons = new goog.ui.Dialog.ButtonSet(); - buttons.set(goog.ui.Dialog.DefaultButtonKeys.CANCEL, - 'Foo!', - false); - // Set a button set without a default selected button - dialog.setButtonSet(buttons); - dialog.setContent('<span id="linkel" tabindex="0">Link Span</span>'); - - var call = false; - function called() { - call = true; - } - var element = document.getElementById("linkel"); - goog.events.listen(element, goog.events.EventType.KEYDOWN, called); - goog.testing.events.fireKeySequence(element, goog.events.KeyCodes.ENTER); - - assertTrue('Should have gotten event on the link', call); - } - - function testPreventDefaultedSelectCausesStopPropagation() { - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.OK_CANCEL); - - var callCount = 0; - var keypressCount = 0; - var keydownCount = 0; - - var preventDefaulter = function(e) { - e.preventDefault(); - }; - - goog.events.listen( - dialog, goog.ui.Dialog.EventType.SELECT, preventDefaulter); - goog.events.listen( - document.body, goog.events.EventType.KEYPRESS, function() { - keypressCount++; - }); - goog.events.listen( - document.body, goog.events.EventType.KEYDOWN, function() { - keydownCount++; - }); - - // Ensure that if the SELECT event is prevented, all key events - // are still stopped from propagating. - goog.testing.events.fireKeySequence( - dialog.getElement(), goog.events.KeyCodes.ENTER); - assertEquals('The KEYPRESS should be stopped', 0, keypressCount); - assertEquals('The KEYDOWN should not be stopped', 1, keydownCount); - - keypressCount = 0; - keydownCount = 0; - goog.testing.events.fireKeySequence( - dialog.getElement(), goog.events.KeyCodes.ESC); - assertEquals('The KEYDOWN should be stopped', 0, keydownCount); - // Note: Some browsers don't yield keypresses on escape, so don't check. - - goog.events.unlisten( - dialog, goog.ui.Dialog.EventType.SELECT, preventDefaulter); - - keypressCount = 0; - keydownCount = 0; - goog.testing.events.fireKeySequence( - dialog.getElement(), goog.events.KeyCodes.ENTER); - assertEquals('The KEYPRESS should be stopped', 0, keypressCount); - assertEquals('The KEYDOWN should not be stopped', 1, keydownCount); - } - - function testEnterKeyHandledInKeypress() { - var inKeyPress = false; - goog.events.listen( - document.body, goog.events.EventType.KEYPRESS, - function() { - inKeyPress = true; - }, true /* capture */); - goog.events.listen( - document.body, goog.events.EventType.KEYPRESS, - function() { - inKeyPress = false; - }, false /* !capture */); - var selectCalled = false; - goog.events.listen( - dialog, goog.ui.Dialog.EventType.SELECT, function() { - selectCalled = true; - assertTrue( - 'Select must be dispatched during keypress to allow popups', - inKeyPress); - }); - - goog.testing.events.fireKeySequence( - dialog.getElement(), goog.events.KeyCodes.ENTER); - assertTrue(selectCalled); - } - - function testButtonsWithContentsDispatchSelectEvents() { - var aButton = dialog.getButtonElement().getElementsByTagName('BUTTON')[0]; - var aSpan = document.createElement('SPAN'); - aButton.appendChild(aSpan); - var wasCalled = false; - var callRecorder = function() { wasCalled = true; }; - goog.events.listen(dialog, goog.ui.Dialog.EventType.SELECT, callRecorder); - goog.testing.events.fireClickSequence(aSpan); - assertTrue(wasCalled); - } - - function testAfterHideEvent() { - var wasCalled = false; - var callRecorder = function() { wasCalled = true; }; - goog.events.listen(dialog, goog.ui.Dialog.EventType.AFTER_HIDE, - callRecorder); - dialog.setVisible(false); - assertTrue(wasCalled); - } - - function testAfterShowEvent() { - dialog.setVisible(false); - var wasCalled = false; - var callRecorder = function() { wasCalled = true; }; - goog.events.listen(dialog, goog.ui.Dialog.EventType.AFTER_SHOW, - callRecorder); - dialog.setVisible(true); - assertTrue(wasCalled); - } - - function testCannedButtonSets() { - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.OK); - assertButtons([goog.ui.Dialog.DefaultButtonKeys.OK]); - - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.OK_CANCEL); - assertButtons([goog.ui.Dialog.DefaultButtonKeys.OK, - goog.ui.Dialog.DefaultButtonKeys.CANCEL]); - - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.YES_NO); - assertButtons([goog.ui.Dialog.DefaultButtonKeys.YES, - goog.ui.Dialog.DefaultButtonKeys.NO]); - - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.YES_NO_CANCEL); - assertButtons([goog.ui.Dialog.DefaultButtonKeys.YES, - goog.ui.Dialog.DefaultButtonKeys.NO, - goog.ui.Dialog.DefaultButtonKeys.CANCEL]); - - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.CONTINUE_SAVE_CANCEL); - assertButtons([goog.ui.Dialog.DefaultButtonKeys.CONTINUE, - goog.ui.Dialog.DefaultButtonKeys.SAVE, - goog.ui.Dialog.DefaultButtonKeys.CANCEL]); - } - - function testFactoryButtonSets() { - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.createOk()); - assertButtons([goog.ui.Dialog.DefaultButtonKeys.OK]); - - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.createOkCancel()); - assertButtons([goog.ui.Dialog.DefaultButtonKeys.OK, - goog.ui.Dialog.DefaultButtonKeys.CANCEL]); - - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.createYesNo()); - assertButtons([goog.ui.Dialog.DefaultButtonKeys.YES, - goog.ui.Dialog.DefaultButtonKeys.NO]); - - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.createYesNoCancel()); - assertButtons([goog.ui.Dialog.DefaultButtonKeys.YES, - goog.ui.Dialog.DefaultButtonKeys.NO, - goog.ui.Dialog.DefaultButtonKeys.CANCEL]); - - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.createContinueSaveCancel()); - assertButtons([goog.ui.Dialog.DefaultButtonKeys.CONTINUE, - goog.ui.Dialog.DefaultButtonKeys.SAVE, - goog.ui.Dialog.DefaultButtonKeys.CANCEL]); - } - - function testDefaultButtonClassName() { - var key = 'someKey'; - var msg = 'someMessage'; - var isDefault = false; - var buttonSetOne = new goog.ui.Dialog.ButtonSet().set(key, msg, isDefault); - dialog.setButtonSet(buttonSetOne); - var defaultClassName = goog.getCssName(buttonSetOne.class_, 'default'); - var buttonOne = buttonSetOne.getButton(key); - assertNotEquals(defaultClassName, buttonOne.className); - var isDefault = true; - var buttonSetTwo = new goog.ui.Dialog.ButtonSet().set(key, msg, isDefault); - dialog.setButtonSet(buttonSetTwo); - var buttonTwo = buttonSetTwo.getButton(key); - assertEquals(defaultClassName, buttonTwo.className); - } - - function testGetButton() { - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.OK); - var buttons = document.getElementsByName( - goog.ui.Dialog.DefaultButtonKeys.OK); - assertEquals(buttons[0], dialog.getButtonSet().getButton( - goog.ui.Dialog.DefaultButtonKeys.OK)); - } - - function testGetAllButtons() { - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.YES_NO_CANCEL); - var buttons = dialog.getElement().getElementsByTagName( - goog.dom.TagName.BUTTON); - for (var i = 0; i < buttons.length; i++) { - assertEquals(buttons[i], dialog.getButtonSet().getAllButtons()[i]); - } - } - - function testSetButtonEnabled() { - var buttonSet = goog.ui.Dialog.ButtonSet.createYesNoCancel(); - dialog.setButtonSet(buttonSet); - assertFalse( - buttonSet.getButton(goog.ui.Dialog.DefaultButtonKeys.NO).disabled); - buttonSet.setButtonEnabled(goog.ui.Dialog.DefaultButtonKeys.NO, false); - assertTrue( - buttonSet.getButton(goog.ui.Dialog.DefaultButtonKeys.NO).disabled); - buttonSet.setButtonEnabled(goog.ui.Dialog.DefaultButtonKeys.NO, true); - assertFalse( - buttonSet.getButton(goog.ui.Dialog.DefaultButtonKeys.NO).disabled); - } - - function testSetAllButtonsEnabled() { - var buttonSet = goog.ui.Dialog.ButtonSet.createContinueSaveCancel(); - dialog.setButtonSet(buttonSet); - var buttons = buttonSet.getAllButtons(); - for (var i = 0; i < buttons.length; i++) { - assertFalse(buttons[i].disabled); - } - - buttonSet.setAllButtonsEnabled(false); - for (var i = 0; i < buttons.length; i++) { - assertTrue(buttons[i].disabled); - } - - buttonSet.setAllButtonsEnabled(true); - for (var i = 0; i < buttons.length; i++) { - assertFalse(buttons[i].disabled); - } - } - - function testIframeMask() { - // generate a new dialog - dialog.dispose(); - dialog = new goog.ui.Dialog(null, true /* iframe mask */); - dialog.setVisible(true); - - var iframes = - goog.dom.getElementsByTagNameAndClass(goog.dom.TagName.IFRAME); - // NOTE: one iframe already exists in the document, so we check for 1 extra - // iframe. - assertEquals('No iframe mask created', 2, iframes.length); - } - - function testNonModalDialog() { - // generate a new dialog - dialog.dispose(); - dialog = new goog.ui.Dialog(null, true /* iframe mask */); - dialog.setModal(false); - dialog.setVisible(true); - - var iframes = - goog.dom.getElementsByTagNameAndClass(goog.dom.TagName.IFRAME); - // NOTE: one iframe already exists in the document, so we check there are - // no extra iframes in the document. - assertEquals('Iframe mask created for modal dialog', 1, iframes.length); - } - - function testSwapModalForOpenDialog() { - dialog.dispose(); - dialog = new goog.ui.Dialog(null, true /* iframe mask */); - dialog.setVisible(true); - dialog.setModal(false); - assertFalse('IFrame bg element should not be in dom', - goog.dom.contains(document.body, dialog.getBackgroundIframe())); - assertFalse('bg element should not be in dom', - goog.dom.contains(document.body, dialog.getBackgroundElement())); - - dialog.setModal(true); - assertTrue('IFrame bg element should be in dom', - goog.dom.contains(document.body, dialog.getBackgroundIframe())); - assertTrue('bg element should be in dom', - goog.dom.contains(document.body, dialog.getBackgroundElement())); - - assertEquals('IFrame bg element is a child of body', - document.body, dialog.getBackgroundIframe().parentNode); - assertEquals('bg element is a child of body', - document.body, dialog.getBackgroundElement().parentNode); - - assertTrue('IFrame bg element should visible', - goog.style.isElementShown(dialog.getBackgroundIframe())); - assertTrue('bg element should be visible', - goog.style.isElementShown(dialog.getBackgroundElement())); - } - - /** - * Assert that the dialog has buttons with the given keys in the correct - * order. - * @param {Array.<string>} keys An array of button keys. - */ - function assertButtons(keys) { - var buttons = dialog.getElement().getElementsByTagName( - goog.dom.TagName.BUTTON); - var actualKeys = []; - for (var i = 0; i < buttons.length; i++) { - actualKeys[i] = buttons[i].name; - } - assertArrayEquals(keys, actualKeys); - } - - function testButtonSetOkFiresDialogEventOnEscape() { - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.OK); - var wasCalled = false; - var callRecorder = function() { wasCalled = true; }; - goog.events.listen(dialog, goog.ui.Dialog.EventType.SELECT, - callRecorder); - goog.testing.events.fireKeySequence( - dialog.getElement(), goog.events.KeyCodes.ESC); - assertTrue(wasCalled); - } - - function testHideButtons_afterRender() { - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.OK); - assertTrue(goog.style.isElementShown(dialog.buttonEl_)); - dialog.setButtonSet(null); - assertFalse(goog.style.isElementShown(dialog.buttonEl_)); - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.OK); - assertTrue(goog.style.isElementShown(dialog.buttonEl_)); - } - - function testHideButtons_beforeRender() { - dialog.dispose(); - - dialog = new goog.ui.Dialog(); - dialog.setButtonSet(null); - dialog.setVisible(true); - assertFalse(goog.style.isElementShown(dialog.buttonEl_)); - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.OK); - assertTrue(goog.style.isElementShown(dialog.buttonEl_)); - } - - function testHideButtons_beforeDecorate() { - dialog.dispose(); - - dialog = new goog.ui.Dialog(); - dialog.setButtonSet(null); - dialog.decorate(decorateTarget); - dialog.setVisible(true); - assertFalse(goog.style.isElementShown(dialog.buttonEl_)); - dialog.setButtonSet(goog.ui.Dialog.ButtonSet.OK); - assertTrue(goog.style.isElementShown(dialog.buttonEl_)); - } - - function testDefaultOpacityIsAppliedOnRender() { - dialog.dispose(); - - dialog = new goog.ui.Dialog(); - dialog.render(); - assertEquals(0.5, goog.style.getOpacity(dialog.getBackgroundElement())); - } - - function testDefaultOpacityIsAppliedOnDecorate() { - dialog.dispose(); - - dialog = new goog.ui.Dialog(); - dialog.decorate(decorateTarget); - assertEquals(0.5, goog.style.getOpacity(dialog.getBackgroundElement())); - } - - function testDraggableStyle() { - assertTrue('draggable CSS class is set', goog.dom.classes.has( - dialog.titleEl_, 'modal-dialog-title-draggable')); - dialog.setDraggable(false); - assertFalse('draggable CSS class is removed', goog.dom.classes.has( - dialog.titleEl_, 'modal-dialog-title-draggable')); - } - - function testDraggingLifecycle() { - dialog.dispose(); - - dialog = new goog.ui.Dialog(); - dialog.setDraggerLimits_ = goog.testing.recordFunction(); - dialog.createDom(); - assertNull('dragger is not created in createDom', dialog.dragger_); - - dialog.setVisible(true); - assertNotNull('dragger is created when the dialog is rendered', - dialog.dragger_); - - assertNull('dragging limits are not set just before dragging', - dialog.setDraggerLimits_.getLastCall()); - goog.testing.events.fireMouseDownEvent(dialog.titleEl_); - assertNotNull('dragging limits are set', - dialog.setDraggerLimits_.getLastCall()); - - dialog.exitDocument(); - assertNull('dragger is cleaned up in exitDocument', dialog.dragger_); - } -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dimensionpicker.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dimensionpicker.js.svn-base deleted file mode 100644 index 332aa8b..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dimensionpicker.js.svn-base +++ /dev/null @@ -1,293 +0,0 @@ -// 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 dimension picker control. A dimension picker allows the - * user to visually select a row and column count. - * - * @author robbyw@google.com (Robby Walker) - * @author abefettig@google.com (Abe Fettig) - * @see ../demos/dimensionpicker.html - * @see ../demos/dimensionpicker_rtl.html - */ - -goog.provide('goog.ui.DimensionPicker'); - -goog.require('goog.events.EventType'); -goog.require('goog.math.Size'); -goog.require('goog.ui.Control'); -goog.require('goog.ui.DimensionPickerRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * A dimension picker allows the user to visually select a row and column - * count using their mouse and keyboard. - * - * The currently selected dimension is controlled by an ACTION event. Event - * listeners may retrieve the selected item using the - * {@link #getValue} method. - * - * @param {goog.ui.DimensionPickerRenderer=} opt_renderer Renderer used to - * render or decorate the palette; defaults to - * {@link goog.ui.DimensionPickerRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for - * document interaction. - * @constructor - * @extends {goog.ui.Control} - */ -goog.ui.DimensionPicker = function(opt_renderer, opt_domHelper) { - goog.ui.Control.call(this, null, - opt_renderer || goog.ui.DimensionPickerRenderer.getInstance(), - opt_domHelper); - - this.size_ = new goog.math.Size(this.minColumns, this.minRows); -}; -goog.inherits(goog.ui.DimensionPicker, goog.ui.Control); - - -/** - * Minimum number of columns to show in the grid. - * @type {number} - */ -goog.ui.DimensionPicker.prototype.minColumns = 5; - - -/** - * Minimum number of rows to show in the grid. - * @type {number} - */ -goog.ui.DimensionPicker.prototype.minRows = 5; - - -/** - * Maximum number of columns to show in the grid. - * @type {number} - */ -goog.ui.DimensionPicker.prototype.maxColumns = 20; - - -/** - * Maximum number of rows to show in the grid. - * @type {number} - */ -goog.ui.DimensionPicker.prototype.maxRows = 20; - - -/** - * Palette dimensions (columns x rows). - * @type {goog.math.Size} - * @private - */ -goog.ui.DimensionPicker.prototype.size_; - - -/** - * Currently highlighted row count. - * @type {number} - * @private - */ -goog.ui.DimensionPicker.prototype.highlightedRows_ = 0; - - -/** - * Currently highlighted column count. - * @type {number} - * @private - */ -goog.ui.DimensionPicker.prototype.highlightedColumns_ = 0; - - -/** @override */ -goog.ui.DimensionPicker.prototype.enterDocument = function() { - goog.ui.DimensionPicker.superClass_.enterDocument.call(this); - - var handler = this.getHandler(); - handler. - listen(this.getRenderer().getMouseMoveElement(this), - goog.events.EventType.MOUSEMOVE, this.handleMouseMove). - listen(this.getDomHelper().getWindow(), goog.events.EventType.RESIZE, - this.handleWindowResize); - - var parent = this.getParent(); - if (parent) { - handler.listen(parent, goog.ui.Component.EventType.SHOW, this.handleShow_); - } -}; - - -/** @override */ -goog.ui.DimensionPicker.prototype.exitDocument = function() { - goog.ui.DimensionPicker.superClass_.exitDocument.call(this); - - var handler = this.getHandler(); - handler. - unlisten(this.getRenderer().getMouseMoveElement(this), - goog.events.EventType.MOUSEMOVE, this.handleMouseMove). - unlisten(this.getDomHelper().getWindow(), goog.events.EventType.RESIZE, - this.handleWindowResize); - - var parent = this.getParent(); - if (parent) { - handler.unlisten(parent, goog.ui.Component.EventType.SHOW, - this.handleShow_); - } -}; - - -/** - * Resets the highlighted size when the picker is shown. - * @private - */ -goog.ui.DimensionPicker.prototype.handleShow_ = function() { - if (this.isVisible()) { - this.setValue(0, 0); - } -}; - - -/** @override */ -goog.ui.DimensionPicker.prototype.disposeInternal = function() { - goog.ui.DimensionPicker.superClass_.disposeInternal.call(this); - delete this.size_; -}; - - -// Palette event handling. - - -/** - * Handles mousemove events. Determines which palette size was moused over and - * highlights it. - * @param {goog.events.BrowserEvent} e Mouse event to handle. - * @protected - */ -goog.ui.DimensionPicker.prototype.handleMouseMove = function(e) { - var highlightedSizeX = this.getRenderer().getGridOffsetX(this, - this.isRightToLeft() ? e.target.offsetWidth - e.offsetX : e.offsetX); - var highlightedSizeY = this.getRenderer().getGridOffsetY(this, e.offsetY); - - if (this.highlightedColumns_ != highlightedSizeX || - this.highlightedRows_ != highlightedSizeY) { - this.setValue(highlightedSizeX, highlightedSizeY); - } -}; - - -/** - * Handles window resize events. Ensures no scrollbars are introduced by the - * renderer's mouse catcher. - * @param {goog.events.Event} e Resize event to handle. - * @protected - */ -goog.ui.DimensionPicker.prototype.handleWindowResize = function(e) { - this.getRenderer().positionMouseCatcher(this); -}; - - -/** - * Handle key events if supported, so the user can use the keyboard to - * manipulate the highlighted rows and columns. - * @param {goog.events.KeyEvent} e The key event object. - * @return {boolean} Whether the key event was handled. - */ -goog.ui.DimensionPicker.prototype.handleKeyEvent = function(e) { - var rows = this.highlightedRows_; - var columns = this.highlightedColumns_; - switch (e.keyCode) { - case goog.events.KeyCodes.DOWN: - rows = Math.min(this.maxRows, rows + 1); - break; - case goog.events.KeyCodes.UP: - rows = Math.max(1, rows - 1); - break; - case goog.events.KeyCodes.LEFT: - if (columns == 1) { - // Delegate to parent. - return false; - } else { - columns = Math.max(1, columns - 1); - } - break; - case goog.events.KeyCodes.RIGHT: - columns = Math.min(this.maxColumns, columns + 1); - break; - default: - return goog.ui.DimensionPicker.superClass_.handleKeyEvent.call(this, e); - } - this.setValue(columns, rows); - return true; -}; - - -// Palette management. - - -/** - * @return {goog.math.Size} Current table size shown (columns x rows). - */ -goog.ui.DimensionPicker.prototype.getSize = function() { - return this.size_; -}; - - -/** - * @return {goog.math.Size} size The currently highlighted dimensions. - */ -goog.ui.DimensionPicker.prototype.getValue = function() { - return new goog.math.Size(this.highlightedColumns_, this.highlightedRows_); -}; - - -/** - * Sets the currently highlighted dimensions. - * @param {number} columns The number of columns to highlight, or a - * goog.math.Size object containing both. - * @param {number=} opt_rows The number of rows to highlight. Can be - * omitted when columns is a good.math.Size object. - */ -goog.ui.DimensionPicker.prototype.setValue = function(columns, - opt_rows) { - if (!goog.isDef(opt_rows)) { - opt_rows = columns.height; - columns = columns.width; - } - - if (this.highlightedColumns_ != columns || - this.highlightedRows_ != opt_rows) { - var renderer = this.getRenderer(); - // Show one more row/column than highlighted so the user understands the - // palette can grow. - this.size_.width = Math.max( - Math.min(columns + 1, this.maxColumns), this.minColumns); - this.size_.height = Math.max( - Math.min(opt_rows + 1, this.maxRows), this.minRows); - renderer.updateSize(this, this.getElement()); - - this.highlightedColumns_ = columns; - this.highlightedRows_ = opt_rows; - renderer.setHighlightedSize(this, columns, opt_rows); - } -}; - - -/** - * Register this control so it can be created from markup - */ -goog.ui.registry.setDecoratorByClassName( - goog.ui.DimensionPickerRenderer.CSS_CLASS, - function() { - return new goog.ui.DimensionPicker(); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dimensionpicker_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dimensionpicker_test.html.svn-base deleted file mode 100644 index 178822a..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dimensionpicker_test.html.svn-base +++ /dev/null @@ -1,156 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - Author: robbyw@google.com (Robby Walker) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.DimensionPicker</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.dom.TagName'); - goog.require('goog.math.Size'); - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.events'); - goog.require('goog.testing.ui.rendererasserts'); - goog.require('goog.ui.DimensionPicker'); - goog.require('goog.ui.DimensionPickerRenderer'); - </script> -</head> -<body> - <div id="render"></div> - <div id="decorate"></div> - <script> - var picker; - var render = goog.dom.getElement('render'); - var decorate = goog.dom.getElement('decorate'); - - function setUp() { - picker = new goog.ui.DimensionPicker(); - render.innerHTML = ''; - decorate.innerHTML = ''; - } - - function tearDown() { - picker.dispose(); - } - - function testConstructor() { - assertNotNull('Should have successful construction', picker); - assertNull('Should not be in document', picker.getElement()); - } - - function testRender() { - picker.render(render); - - assertEquals('Should create 1 child', 1, render.childNodes.length); - assertEquals('Should be a div', goog.dom.TagName.DIV, - render.firstChild.tagName); - } - - function testDecorate() { - picker.decorate(decorate); - - assertNotEquals('Should add several children', decorate.firstChild, - decorate.lastChild); - } - - function testHighlightedSize() { - picker.render(render); - - var size = picker.getValue(); - assertEquals('Should have 0 columns highlighted', 0, size.width); - assertEquals('Should have 0 rows highlighted', 0, size.height); - - picker.setValue(1, 2); - - size = picker.getValue(); - assertEquals('Should have 1 column highlighted', 1, size.width); - assertEquals('Should have 2 rows highlighted', 2, size.height); - - picker.setValue(new goog.math.Size(3, 4)); - size = picker.getValue(); - assertEquals('Should have 3 columns highlighted', 3, size.width); - assertEquals('Should have 4 rows highlighted', 4, size.height); - } - - function testSizeShown() { - picker.render(render); - - var size = picker.getSize(); - assertEquals('Should have 5 columns visible', 5, size.width); - assertEquals('Should have 5 rows visible', 5, size.height); - - picker.setValue(4, 4); - size = picker.getSize(); - assertEquals('Should have 5 columns visible', 5, size.width); - assertEquals('Should have 5 rows visible', 5, size.height); - - picker.setValue(12, 13); - size = picker.getSize(); - assertEquals('Should have 13 columns visible', 13, size.width); - assertEquals('Should have 14 rows visible', 14, size.height); - - picker.setValue(20, 20); - size = picker.getSize(); - assertEquals('Should have 20 columns visible', 20, size.width); - assertEquals('Should have 20 rows visible', 20, size.height); - - picker.setValue(2, 3); - size = picker.getSize(); - assertEquals('Should have 5 columns visible', 5, size.width); - assertEquals('Should have 5 rows visible', 5, size.height); - } - - function testHandleMove() { - picker.render(render); - var renderer = picker.getRenderer(); - var mouseMoveElem = renderer.getMouseMoveElement(picker); - - picker.rightToLeft_ = false; - var e = { - target: mouseMoveElem, - offsetX: 18, // Each grid square currently a magic 18px. - offsetY: 36 - }; - - picker.handleMouseMove(e); - var size = picker.getValue(); - assertEquals('Should have 1 column highlighted', 1, size.width); - assertEquals('Should have 2 rows highlighted', 2, size.height); - - picker.rightToLeft_ = true; - - picker.handleMouseMove(e); - var size = picker.getValue(); - // In RTL we pick from the right side of the picker, so an offsetX of 0 - // would actually mean select all columns. - assertEquals('Should have columns to the right of the mouse highlighted', - Math.ceil((mouseMoveElem.offsetWidth - e.offsetX) / 18), size.width); - assertEquals('Should have 2 rows highlighted', 2, size.height); - } - - function testDispose() { - var element = picker.getElement(); - picker.render(render); - picker.dispose(); - assertTrue('Picker should have been disposed of', picker.isDisposed()); - assertNull('Picker element reference should have been nulled out', - picker.getElement()); - } - - function testRendererDoesntCallGetCssClassInConstructor() { - goog.testing.ui.rendererasserts. - assertNoGetCssClassCallsInConstructor( - goog.ui.DimensionPickerRenderer); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dimensionpickerrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dimensionpickerrenderer.js.svn-base deleted file mode 100644 index ab779fd..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dimensionpickerrenderer.js.svn-base +++ /dev/null @@ -1,387 +0,0 @@ -// 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 The default renderer for a goog.dom.DimensionPicker. A - * dimension picker allows the user to visually select a row and column count. - * It looks like a palette but in order to minimize DOM load it is rendered. - * using CSS background tiling instead of as a grid of nodes. - * - * @author robbyw@google.com (Robby Walker) - * @author abefettig@google.com (Abe Fettig) - */ - -goog.provide('goog.ui.DimensionPickerRenderer'); - -goog.require('goog.dom'); -goog.require('goog.dom.TagName'); -goog.require('goog.i18n.bidi'); -goog.require('goog.style'); -goog.require('goog.ui.ControlRenderer'); -goog.require('goog.userAgent'); - - - -/** - * Default renderer for {@link goog.ui.DimensionPicker}s. Renders the - * palette as two divs, one with the un-highlighted background, and one with the - * highlighted background. - * - * @constructor - * @extends {goog.ui.ControlRenderer} - */ -goog.ui.DimensionPickerRenderer = function() { - goog.ui.ControlRenderer.call(this); -}; -goog.inherits(goog.ui.DimensionPickerRenderer, goog.ui.ControlRenderer); -goog.addSingletonGetter(goog.ui.DimensionPickerRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.DimensionPickerRenderer.CSS_CLASS = - goog.getCssName('goog-dimension-picker'); - - -/** - * Return the underlying div for the given outer element. - * @param {Element} element The root element. - * @return {Element} The underlying div. - * @private - */ -goog.ui.DimensionPickerRenderer.prototype.getUnderlyingDiv_ = function( - element) { - return element.firstChild.childNodes[1]; -}; - - -/** - * Return the highlight div for the given outer element. - * @param {Element} element The root element. - * @return {Element} The highlight div. - * @private - */ -goog.ui.DimensionPickerRenderer.prototype.getHighlightDiv_ = function( - element) { - return /** @type {Element} */ element.firstChild.lastChild; -}; - - -/** - * Return the status message div for the given outer element. - * @param {Element} element The root element. - * @return {Element} The status message div. - * @private - */ -goog.ui.DimensionPickerRenderer.prototype.getStatusDiv_ = function( - element) { - return /** @type {Element} */ (element.lastChild); -}; - - -/** - * Return the invisible mouse catching div for the given outer element. - * @param {Element} element The root element. - * @return {Element} The invisible mouse catching div. - * @private - */ -goog.ui.DimensionPickerRenderer.prototype.getMouseCatcher_ = function( - element) { - return /** @type {Element} */ element.firstChild.firstChild; -}; - - -/** - * Overrides {@link goog.ui.ControlRenderer#canDecorate} to allow decorating - * empty DIVs only. - * @param {Element} element The element to check. - * @return {boolean} Whether if the element is an empty div. - */ -goog.ui.DimensionPickerRenderer.prototype.canDecorate = function( - element) { - return element.tagName == goog.dom.TagName.DIV && !element.firstChild; -}; - - -/** - * Overrides {@link goog.ui.ControlRenderer#decorate} to decorate empty DIVs. - * @param {goog.ui.DimensionPicker} palette The palette object. - * @param {Element} element The element to decorate. - * @return {Element} The decorated element. - */ -goog.ui.DimensionPickerRenderer.prototype.decorate = function(palette, - element) { - goog.ui.DimensionPickerRenderer.superClass_.decorate.call(this, - palette, element); - - this.addElementContents_(palette, element); - this.updateSize(palette, element); - - return element; -}; - - -/** - * Scales various elements in order to update the palette's size. - * @param {goog.ui.DimensionPicker} palette The palette object. - * @param {Element} element The element to set the style of. - */ -goog.ui.DimensionPickerRenderer.prototype.updateSize = - function(palette, element) { - var size = palette.getSize(); - - element.style.width = size.width + 'em'; - - var underlyingDiv = this.getUnderlyingDiv_(element); - underlyingDiv.style.width = size.width + 'em'; - underlyingDiv.style.height = size.height + 'em'; - - if (palette.isRightToLeft()) { - this.adjustParentDirection_(palette, element); - } -}; - - -/** - * Adds the appropriate content elements to the given outer DIV. - * @param {goog.ui.DimensionPicker} palette The palette object. - * @param {Element} element The element to decorate. - * @private - */ -goog.ui.DimensionPickerRenderer.prototype.addElementContents_ = function( - palette, element) { - // First we create a single div containing three stacked divs. The bottom div - // catches mouse events. We can't use document level mouse move detection as - // we could lose events to iframes. This is especially important in Firefox 2 - // in which TrogEdit creates iframes. The middle div uses a css tiled - // background image to represent deselected tiles. The top div uses a - // different css tiled background image to represent selected tiles. - var mouseCatcherDiv = palette.getDomHelper().createDom(goog.dom.TagName.DIV, - goog.getCssName(this.getCssClass(), 'mousecatcher')); - var unhighlightedDiv = palette.getDomHelper().createDom(goog.dom.TagName.DIV, - { - 'class': goog.getCssName(this.getCssClass(), 'unhighlighted'), - 'style': 'width:100%;height:100%' - }); - var highlightedDiv = palette.getDomHelper().createDom(goog.dom.TagName.DIV, - goog.getCssName(this.getCssClass(), 'highlighted')); - element.appendChild( - palette.getDomHelper().createDom(goog.dom.TagName.DIV, - {'style': 'width:100%;height:100%'}, - mouseCatcherDiv, unhighlightedDiv, highlightedDiv)); - - // Lastly we add a div to store the text version of the current state. - element.appendChild(palette.getDomHelper().createDom(goog.dom.TagName.DIV, - goog.getCssName(this.getCssClass(), 'status'), - goog.i18n.bidi.enforceLtrInText('0 x 0'))); -}; - - -/** - * Creates a div and adds the appropriate contents to it. - * @param {goog.ui.DimensionPicker} palette Palette to render. - * @return {Element} Root element for the palette. - */ -goog.ui.DimensionPickerRenderer.prototype.createDom = function(palette) { - var classNames = this.getClassNames(palette); - var element = palette.getDomHelper().createDom(goog.dom.TagName.DIV, { - 'class' : classNames ? classNames.join(' ') : '' - }); - this.addElementContents_(palette, element); - this.updateSize(palette, element); - return element; -}; - - -/** - * Initializes the control's DOM when the control enters the document. Called - * from {@link goog.ui.Control#enterDocument}. - * @param {goog.ui.DimensionPicker} palette Palette whose DOM is to be - * initialized as it enters the document. - */ -goog.ui.DimensionPickerRenderer.prototype.initializeDom = function( - palette) { - goog.ui.DimensionPickerRenderer.superClass_.initializeDom.call(this, palette); - this.positionMouseCatcher(palette); -}; - - -/** - * Get the element to listen for mouse move events on. - * @param {goog.ui.DimensionPicker} palette The palette to listen on. - * @return {Element} The element to listen for mouse move events on. - */ -goog.ui.DimensionPickerRenderer.prototype.getMouseMoveElement = function( - palette) { - return /** @type {Element} */ (palette.getElement().firstChild); -}; - - -/** - * Returns the x offset in to the grid for the given mouse x position. - * @param {goog.ui.DimensionPicker} palette The table size palette. - * @param {number} x The mouse event x position. - * @return {number} The x offset in to the grid. - */ -goog.ui.DimensionPickerRenderer.prototype.getGridOffsetX = function( - palette, x) { - // TODO(robbyw): Don't rely on magic 18 - measure each palette's em size. - return Math.min(palette.maxColumns, Math.ceil(x / 18)); -}; - - -/** - * Returns the y offset in to the grid for the given mouse y position. - * @param {goog.ui.DimensionPicker} palette The table size palette. - * @param {number} y The mouse event y position. - * @return {number} The y offset in to the grid. - */ -goog.ui.DimensionPickerRenderer.prototype.getGridOffsetY = function( - palette, y) { - return Math.min(palette.maxRows, Math.ceil(y / 18)); -}; - - -/** - * Sets the highlighted size. - * @param {goog.ui.DimensionPicker} palette The table size palette. - * @param {number} columns The number of columns to highlight. - * @param {number} rows The number of rows to highlight. - */ -goog.ui.DimensionPickerRenderer.prototype.setHighlightedSize = function( - palette, columns, rows) { - var element = palette.getElement(); - - // Style the highlight div. - var style = this.getHighlightDiv_(element).style; - style.width = columns + 'em'; - style.height = rows + 'em'; - - // Explicitly set style.right so the element grows to the left when increase - // in width. - if (palette.isRightToLeft()) { - style.right = '0'; - } - - // Update the size text. - goog.dom.setTextContent(this.getStatusDiv_(element), - goog.i18n.bidi.enforceLtrInText(columns + ' x ' + rows)); -}; - - -/** - * Position the mouse catcher such that it receives mouse events past the - * selectedsize up to the maximum size. Takes care to not introduce scrollbars. - * Should be called on enter document and when the window changes size. - * @param {goog.ui.DimensionPicker} palette The table size palette. - */ -goog.ui.DimensionPickerRenderer.prototype.positionMouseCatcher = function( - palette) { - var mouseCatcher = this.getMouseCatcher_(palette.getElement()); - var doc = goog.dom.getOwnerDocument(mouseCatcher); - var body = doc.body; - - var position = goog.style.getRelativePosition(mouseCatcher, body); - - // Hide the mouse catcher so it doesn't affect the body's scroll size. - mouseCatcher.style.display = 'none'; - - // Compute the maximum size the catcher can be without introducing scrolling. - var xAvailableEm = (palette.isRightToLeft() && position.x > 0) ? - Math.floor(position.x / 18) : - Math.floor((body.scrollWidth - position.x) / 18); - - // Computing available height is more complicated - we need to check the - // window's inner height. - var height; - if (goog.userAgent.IE) { - // Offset 20px to make up for scrollbar size. - height = goog.style.getClientViewportElement(body).scrollHeight - 20; - } else { - var win = goog.dom.getWindow(doc); - // Offset 20px to make up for scrollbar size. - height = Math.max(win.innerHeight, body.scrollHeight) - 20; - } - var yAvailableEm = Math.floor((height - position.y) / 18); - - // Resize and display the mouse catcher. - mouseCatcher.style.width = Math.min(palette.maxColumns, xAvailableEm) + 'em'; - mouseCatcher.style.height = Math.min(palette.maxRows, yAvailableEm) + 'em'; - mouseCatcher.style.display = ''; - - // Explicitly set style.right so the mouse catcher is positioned on the left - // side instead of right. - if (palette.isRightToLeft()) { - mouseCatcher.style.right = '0'; - } -}; - - -/** - * Returns the CSS class to be applied to the root element of components - * rendered using this renderer. - * @return {string} Renderer-specific CSS class. - */ -goog.ui.DimensionPickerRenderer.prototype.getCssClass = function() { - return goog.ui.DimensionPickerRenderer.CSS_CLASS; -}; - - -/** - * This function adjusts the positioning from 'left' and 'top' to 'right' and - * 'top' as appropriate for RTL control. This is so when the dimensionpicker - * grow in width, the containing element grow to the left instead of right. - * This won't be necessary if goog.ui.SubMenu rendering code would position RTL - * control with 'right' and 'top'. - * @private - * - * @param {goog.ui.DimensionPicker} palette The palette object. - * @param {Element} element The palette's element. - */ -goog.ui.DimensionPickerRenderer.prototype.adjustParentDirection_ = - function(palette, element) { - var parent = palette.getParent(); - if (parent) { - var parentElement = parent.getElement(); - - // Anchors the containing element to the right so it grows to the left - // when it increase in width. - var right = goog.style.getStyle(parentElement, 'right'); - if (right == '') { - var parentPos = goog.style.getPosition(parentElement); - var parentSize = goog.style.getSize(parentElement); - if (parentSize.width != 0 && parentPos.x != 0) { - var visibleRect = goog.style.getBounds( - goog.style.getClientViewportElement()); - var visibleWidth = visibleRect.width; - right = visibleWidth - parentPos.x - parentSize.width; - goog.style.setStyle(parentElement, 'right', right + 'px'); - } - } - - // When a table is inserted, the containing elemet's position is - // recalculated the next time it shows, set left back to '' to prevent - // extra white space on the left. - var left = goog.style.getStyle(parentElement, 'left'); - if (left != '') { - goog.style.setStyle(parentElement, 'left', ''); - } - } else { - goog.style.setStyle(element, 'right', '0px'); - } -}; - diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dragdropdetector.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dragdropdetector.js.svn-base deleted file mode 100644 index 680bd6e..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/dragdropdetector.js.svn-base +++ /dev/null @@ -1,642 +0,0 @@ -// 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.showElement(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.showElement(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_; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/drilldownrow.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/drilldownrow.js.svn-base deleted file mode 100644 index 7144043..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/drilldownrow.js.svn-base +++ /dev/null @@ -1,490 +0,0 @@ -// 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 Tree-like drilldown components for HTML tables. - * - * This component supports expanding and collapsing groups of rows in - * HTML tables. The behavior is like typical Tree widgets, but tables - * need special support to enable the tree behaviors. - * - * Any row or rows in an HTML table can be DrilldownRows. The root - * DrilldownRow nodes are always visible in the table, but the rest show - * or hide as input events expand and collapse their ancestors. - * - * Programming them: Top-level DrilldownRows are made by decorating - * a TR element. Children are made with addChild or addChildAt, and - * are entered into the document by the render() method. - * - * A DrilldownRow can have any number of children. If it has no children - * it can be loaded, not loaded, or with a load in progress. - * Top-level DrilldownRows are always displayed (though setting - * style.display on a containing DOM node could make one be not - * visible to the user). A DrilldownRow can be expanded, or not. A - * DrilldownRow displays if all of its ancestors are expanded. - * - * Set up event handlers and style each row for the application in an - * enterDocument method. - * - * Children normally render into the document lazily, at the first - * moment when all ancestors are expanded. - * - * @see ../demos/drilldownrow.html - */ - -// TODO(user): Build support for dynamically loading DrilldownRows, -// probably using automplete as an example to follow. - -// TODO(user): Make DrilldownRows accessible through the keyboard. - -// The render method is redefined in this class because when addChildAt renders -// the new child it assumes that the child's DOM node will be a child -// of the parent component's DOM node, but all DOM nodes of DrilldownRows -// in the same tree of DrilldownRows are siblings to each other. -// -// Arguments (or lack of arguments) to the render methods in Component -// all determine the place of the new DOM node in the DOM tree, but -// the place of a new DrilldownRow in the DOM needs to be determined by -// its position in the tree of DrilldownRows. - -goog.provide('goog.ui.DrilldownRow'); - -goog.require('goog.dom'); -goog.require('goog.dom.classes'); -goog.require('goog.events'); -goog.require('goog.ui.Component'); - - - -/** - * Builds a DrilldownRow component, which can overlay a tree - * structure onto sections of an HTML table. - * - * @param {Object=} opt_properties This parameter can contain: - * contents: if present, user data identifying - * the information loaded into the row and its children. - * loaded: initializes the isLoaded property, defaults to true. - * expanded: DrilldownRow expanded or not, default is true. - * html: String of HTML, relevant and required for DrilldownRows to be - * added as children. Ignored when decorating an existing table row. - * decorator: Function that accepts one DrilldownRow argument, and - * should customize and style the row. The default is to call - * goog.ui.DrilldownRow.decorator. - * @constructor - * @extends {goog.ui.Component} - */ -goog.ui.DrilldownRow = function(opt_properties) { - goog.ui.Component.call(this); - var properties = opt_properties || {}; - - // Initialize instance variables. - - /** - * String of HTML to initialize the DOM structure for the table row. - * Should have the form '<tr attr="etc">Row contents here</tr>'. - * @type {string} - * @private - */ - this.html_ = properties.html; - - /** - * Controls whether this component's children will show when it shows. - * @type {boolean} - * @private - */ - this.expanded_ = typeof properties.expanded != 'undefined' ? - properties.expanded : true; - - /** - * Is this component loaded? States are true, false, and null for - * 'loading in progress'. For in-memory - * trees of components, this is always true. - * @type {boolean} - * @private - */ - this.loaded_ = typeof properties.loaded != 'undefined' ? - properties.loaded : true; - - /** - * If this component's DOM element is created from a string of - * HTML, this is the function to call when it is entered into the DOM tree. - * @type {Function} args are DrilldownRow and goog.events.EventHandler - * of the DrilldownRow. - * @private - */ - this.decoratorFn_ = properties.decorator || goog.ui.DrilldownRow.decorate; - - /** - * Is the DrilldownRow to be displayed? If it is rendered, this mirrors - * the style.display of the DrilldownRow's row. - * @type {boolean} - * @private - */ - this.displayed_ = true; -}; -goog.inherits(goog.ui.DrilldownRow, goog.ui.Component); - - -/** - * Example object with properties of the form accepted by the class - * constructor. These are educational and show the compiler that - * these properties can be set so it doesn't emit warnings. - */ -goog.ui.DrilldownRow.sampleProperties = { - 'html': '<tr><td>Sample</td><td>Sample</tr>', - 'loaded': true, - 'decorator': function(selfObj, handler) { - // When the mouse is hovering, add CSS class goog-drilldown-hover. - goog.ui.DrilldownRow.decorate(selfObj); - var row = selfObj.getElement(); - handler.listen(row, 'mouseover', function() { - goog.dom.classes.add(row, goog.getCssName('goog-drilldown-hover')); - }); - handler.listen(row, 'mouseout', function() { - goog.dom.classes.remove(row, goog.getCssName('goog-drilldown-hover')); - }); - } -}; - - -// -// Implementations of Component methods. -// - - -/** - * The base class method calls its superclass method and this - * drilldown's 'decorator' method as defined in the constructor. - */ -goog.ui.DrilldownRow.prototype.enterDocument = function() { - goog.ui.DrilldownRow.superClass_.enterDocument.call(this); - this.decoratorFn_(this, this.getHandler()); -}; - - -/** @override */ -goog.ui.DrilldownRow.prototype.createDom = function() { - this.setElementInternal(goog.ui.DrilldownRow.createRowNode_( - this.html_, this.getDomHelper().getDocument())); -}; - - -/** - * A top-level DrilldownRow decorates a TR element. - * - * @param {Element} node The element to test for decorability. - * @return {boolean} true iff the node is a TR. - */ -goog.ui.DrilldownRow.prototype.canDecorate = function(node) { - return node.tagName == 'TR'; -}; - - -/** - * Child drilldowns are rendered when needed. - * - * @param {goog.ui.DrilldownRow} child New child to be added. - * @param {number} index position to be occupied by the child. - * @param {boolean=} opt_render true to force immediate rendering. - */ -goog.ui.DrilldownRow.prototype.addChildAt = function(child, index, opt_render) { - goog.ui.DrilldownRow.superClass_.addChildAt.call(this, child, index, false); - child.setDisplayable_(this.isVisible_() && this.isExpanded()); - if (opt_render && !child.isInDocument()) { - child.render(); - } -}; - - -/** @override */ -goog.ui.DrilldownRow.prototype.removeChild = function(child) { - goog.dom.removeNode(child.getElement()); - return goog.ui.DrilldownRow.superClass_.removeChild.call(this, child); -}; - - -/** @override */ -goog.ui.DrilldownRow.prototype.disposeInternal = function() { - delete this.html_; - this.children_ = null; - goog.ui.DrilldownRow.superClass_.disposeInternal.call(this); -}; - - -/** - * Rendering of DrilldownRow's is on need, do not call this directly - * from application code. - * - * Rendering a DrilldownRow places it according to its position in its - * tree of DrilldownRows. DrilldownRows cannot be placed any other - * way so this method does not use any arguments. This does not call - * the base class method and does not modify any of this - * DrilldownRow's children. - */ -goog.ui.DrilldownRow.prototype.render = function() { - if (arguments.length) { - throw Error('A DrilldownRow cannot be placed under a specific parent.'); - } else { - var parent = this.getParent(); - if (!parent.isInDocument()) { - throw Error('Cannot render child of un-rendered parent'); - } - // The new child's TR node needs to go just after the last TR - // of the part of the parent's subtree that is to the left - // of this. The subtree includes the parent. - var previous = parent.previousRenderedChild_(this); - var row; - if (previous) { - row = previous.lastRenderedLeaf_().getElement(); - } else { - row = parent.getElement(); - } - row = /** @type {Element} */ (row.nextSibling); - // Render the child row component into the document. - if (row) { - this.renderBefore(row); - } else { - // Render at the end of the parent of this DrilldownRow's - // DOM element. - var tbody = /** @type {Element} */ (parent.getElement().parentNode); - goog.ui.DrilldownRow.superClass_.render.call(this, tbody); - } - } -}; - - -/** - * Finds the numeric index of this child within its parent Component. - * Throws an exception if it has no parent. - * - * @return {number} index of this within the children of the parent Component. - */ -goog.ui.DrilldownRow.prototype.findIndex = function() { - var parent = this.getParent(); - if (!parent) { - throw Error('Component has no parent'); - } - return parent.indexOfChild(this); -}; - - -// -// Type-specific operations -// - - -/** - * Returns the expanded state of the DrilldownRow. - * - * @return {boolean} true iff this is expanded. - */ -goog.ui.DrilldownRow.prototype.isExpanded = function() { - return this.expanded_; -}; - - -/** - * Sets the expanded state of this DrilldownRow: makes all children - * displayable or not displayable corresponding to the expanded state. - * - * @param {boolean} expanded whether this should be expanded or not. - */ -goog.ui.DrilldownRow.prototype.setExpanded = function(expanded) { - if (expanded != this.expanded_) { - this.expanded_ = expanded; - goog.dom.classes.toggle(this.getElement(), - goog.getCssName('goog-drilldown-expanded')); - goog.dom.classes.toggle(this.getElement(), - goog.getCssName('goog-drilldown-collapsed')); - if (this.isVisible_()) { - this.forEachChild(function(child) { - child.setDisplayable_(expanded); - }); - } - } -}; - - -/** - * Returns this DrilldownRow's level in the tree. Top level is 1. - * - * @return {number} depth of this DrilldownRow in its tree of drilldowns. - */ -goog.ui.DrilldownRow.prototype.getDepth = function() { - for (var component = this, depth = 0; - component instanceof goog.ui.DrilldownRow; - component = component.getParent(), depth++) {} - return depth; -}; - - -/** - * This static function is a default decorator that adds HTML at the - * beginning of the first cell to display indentation and an expander - * image; sets up a click handler on the toggler; initializes a class - * for the row: either goog-drilldown-expanded or - * goog-drilldown-collapsed, depending on the initial state of the - * DrilldownRow; and sets up a click event handler on the toggler - * element. - * - * This creates a DIV with class=toggle. Your application can set up - * CSS style rules something like this: - * - * tr.goog-drilldown-expanded .toggle { - * background-image: url('minus.png'); - * } - * - * tr.goog-drilldown-collapsed .toggle { - * background-image: url('plus.png'); - * } - * - * These background images show whether the DrilldownRow is expanded. - * - * @param {goog.ui.DrilldownRow} selfObj DrilldownRow to be decorated. - */ -goog.ui.DrilldownRow.decorate = function(selfObj) { - var depth = selfObj.getDepth(); - var row = selfObj.getElement(); - if (!row.cells) { - throw Error('No cells'); - } - var cell = row.cells[0]; - var html = '<div style="float: left; width: ' + depth + - 'em;"><div class=toggle style="width: 1em; float: right;">' + - ' </div></div>'; - var fragment = selfObj.getDomHelper().htmlToDocumentFragment(html); - cell.insertBefore(fragment, cell.firstChild); - goog.dom.classes.add(row, selfObj.isExpanded() ? - goog.getCssName('goog-drilldown-expanded') : - goog.getCssName('goog-drilldown-collapsed')); - // Default mouse event handling: - var toggler = fragment.getElementsByTagName('div')[0]; - var key = selfObj.getHandler().listen(toggler, 'click', function(event) { - selfObj.setExpanded(!selfObj.isExpanded()); - }); -}; - - -// -// Private methods -// - - -/** - * Turn display of a DrilldownRow on or off. If the DrilldownRow has not - * yet been rendered, this renders it. This propagates the effect - * of the change recursively as needed -- children displaying iff the - * parent is displayed and expanded. - * - * @param {boolean} display state, true iff display is desired. - * @private - */ -goog.ui.DrilldownRow.prototype.setDisplayable_ = function(display) { - if (display && !this.isInDocument()) { - this.render(); - } - if (this.displayed_ == display) { - return; - } - this.displayed_ = display; - if (this.isInDocument()) { - this.getElement().style.display = display ? '' : 'none'; - } - var selfObj = this; - this.forEachChild(function(child) { - child.setDisplayable_(display && selfObj.expanded_); - }); -}; - - -/** - * True iff this and all its DrilldownRow parents are displayable. The - * value is an approximation to actual visibility, since it does not - * look at whether DOM nodes containing the top-level component have - * display: none, visibility: hidden or are otherwise not displayable. - * So this visibility is relative to the top-level component. - * - * @return {boolean} visibility of this relative to its top-level drilldown. - * @private - */ -goog.ui.DrilldownRow.prototype.isVisible_ = function() { - for (var component = this; - component instanceof goog.ui.DrilldownRow; - component = component.getParent()) { - if (!component.displayed_) - return false; - } - return true; -}; - - -/** - * Create and return a TR element from HTML that looks like - * "<tr> ... </tr>". - * - * @param {string} html for one row. - * @param {Document} doc object to hold the Element. - * @return {Element} table row node created from the HTML. - * @private - */ -goog.ui.DrilldownRow.createRowNode_ = function(html, doc) { - // Note: this may be slow. - var tableHtml = '<table>' + html + '</table>'; - var div = doc.createElement('div'); - div.innerHTML = tableHtml; - return div.firstChild.rows[0]; -}; - - -/** - * Get the recursively rightmost child that is in the document. - * - * @return {goog.ui.DrilldownRow} rightmost child currently entered in - * the document, potentially this DrilldownRow. If this is in the - * document, result is non-null. - * @private - */ -goog.ui.DrilldownRow.prototype.lastRenderedLeaf_ = function() { - var leaf = null; - for (var node = this; - node && node.isInDocument(); - // Node will become undefined if parent has no children. - node = node.getChildAt(node.getChildCount() - 1)) { - leaf = node; - } - return /** @type {goog.ui.DrilldownRow} */ (leaf); -}; - - -/** - * Search this node's direct children for the last one that is in the - * document and is before the given child. - * @param {goog.ui.DrilldownRow} child The child to stop the search at. - * @return {goog.ui.Component?} The last child component before the given child - * that is in the document. - * @private - */ -goog.ui.DrilldownRow.prototype.previousRenderedChild_ = function(child) { - for (var i = this.getChildCount() - 1; i >= 0; i--) { - if (this.getChildAt(i) == child) { - for (var j = i - 1; j >= 0; j--) { - var prev = this.getChildAt(j); - if (prev.isInDocument()) { - return prev; - } - } - } - } - return null; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/drilldownrow_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/drilldownrow_test.html.svn-base deleted file mode 100644 index 0de92a1..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/drilldownrow_test.html.svn-base +++ /dev/null @@ -1,92 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2011 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. - -Author: nicksantos@google.com (Nick Santos) ---> -<head> -<title>DrilldownRow Tests</title> -<script type="text/javascript" src="../base.js"></script> -<script> -goog.require('goog.dom'); -goog.require('goog.ui.DrilldownRow'); -goog.require('goog.testing.jsunit'); -</script> - -<style type="text/css"> - -.toggle { - cursor: pointer; - cursor: hand; - background-repeat: none; - background-position: right; -} - -tr.goog-drilldown-expanded .toggle { - background-image: url('../images/minus.png'); -} - -tr.goog-drilldown-collapsed .toggle { - background-image: url('../images/plus.png'); -} - -tr.goog-drilldown-hover td { - background-color: #CCCCFF; -} - -td { - background-color: white; -} - -</style> -</head> - -<body> -<table id=table style="background-color: silver"> - <tr> - <th>Column Head</th> - <th>Second Head</th> - </tr> - <tr id=firstRow> - <td>First row</td> - <td>Second column</td> - </tr> -</table> -</body> - -<script type="text/javascript"> - -function testMakeRows() { - var ff = goog.dom.getElement('firstRow'); - var d = new goog.ui.DrilldownRow({}); - var d1 = new goog.ui.DrilldownRow( - {html: '<tr><td>Second row</td><td>Second column</td></tr>'} - ); - var d2 = new goog.ui.DrilldownRow( - {html: '<tr><td>Third row</td><td>Second column</td></tr>'} - ); - var d21 = new goog.ui.DrilldownRow( - {html: '<tr><td>Fourth row</td><td>Second column</td></tr>'} - ); - var d22 = new goog.ui.DrilldownRow(goog.ui.DrilldownRow.sampleProperties); - d.decorate(ff); - d.addChild(d1, true); - d.addChild(d2, true); - d2.addChild(d21, true); - d2.addChild(d22, true); - - assertThrows(function() { - d.findIndex(); - }); - - assertEquals(0, d1.findIndex()); - assertEquals(1, d2.findIndex()); -} - - -</script> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/filteredmenu.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/filteredmenu.js.svn-base deleted file mode 100644 index a904829..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/filteredmenu.js.svn-base +++ /dev/null @@ -1,569 +0,0 @@ -// 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 Menu where items can be filtered based on user keyboard input. - * If a filter is specified only the items matching it will be displayed. - * - * @author eae@google.com (Emil A Eklund) - * @see ../demos/filteredmenu.html - */ - - -goog.provide('goog.ui.FilteredMenu'); - -goog.require('goog.dom'); -goog.require('goog.events.EventType'); -goog.require('goog.events.InputHandler'); -goog.require('goog.events.KeyCodes'); -goog.require('goog.string'); -goog.require('goog.ui.FilterObservingMenuItem'); -goog.require('goog.ui.Menu'); - - - -/** - * Filtered menu class. - * @param {goog.ui.MenuRenderer=} opt_renderer Renderer used to render filtered - * menu; defaults to {@link goog.ui.MenuRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Menu} - */ -goog.ui.FilteredMenu = function(opt_renderer, opt_domHelper) { - goog.ui.Menu.call(this, opt_domHelper, opt_renderer); -}; -goog.inherits(goog.ui.FilteredMenu, goog.ui.Menu); - - -/** - * Events fired by component. - * @enum {string} - */ -goog.ui.FilteredMenu.EventType = { - /** Dispatched after the component filter criteria has been changed. */ - FILTER_CHANGED: 'filterchange' -}; - - -/** - * Filter input element. - * @type {Element|undefined} - * @private - */ -goog.ui.FilteredMenu.prototype.filterInput_; - - -/** - * The input handler that provides the input event. - * @type {goog.events.InputHandler|undefined} - * @private - */ -goog.ui.FilteredMenu.prototype.inputHandler_; - - -/** - * Maximum number of characters for filter input. - * @type {number} - * @private - */ -goog.ui.FilteredMenu.prototype.maxLength_ = 0; - - -/** - * Label displayed in the filter input when no text has been entered. - * @type {string} - * @private - */ -goog.ui.FilteredMenu.prototype.label_ = ''; - - -/** - * Label element. - * @type {Element|undefined} - * @private - */ -goog.ui.FilteredMenu.prototype.labelEl_; - - -/** - * Whether multiple items can be entered comma separated. - * @type {boolean} - * @private - */ -goog.ui.FilteredMenu.prototype.allowMultiple_ = false; - - -/** - * List of items entered in the search box if multiple entries are allowed. - * @type {Array.<string>|undefined} - * @private - */ -goog.ui.FilteredMenu.prototype.enteredItems_; - - -/** - * Index of first item that should be affected by the filter. Menu items with - * a lower index will not be affected by the filter. - * @type {number} - * @private - */ -goog.ui.FilteredMenu.prototype.filterFromIndex_ = 0; - - -/** - * Filter applied to the menu. - * @type {string|undefined|null} - * @private - */ -goog.ui.FilteredMenu.prototype.filterStr_; - - -/** - * Map of child nodes that shouldn't be affected by filtering. - * @type {Object|undefined} - * @private - */ -goog.ui.FilteredMenu.prototype.persistentChildren_; - - -/** @override */ -goog.ui.FilteredMenu.prototype.createDom = function() { - goog.ui.FilteredMenu.superClass_.createDom.call(this); - - var dom = this.getDomHelper(); - var el = dom.createDom('div', - goog.getCssName(this.getRenderer().getCssClass(), 'filter'), - this.labelEl_ = dom.createDom('div', null, this.label_), - this.filterInput_ = dom.createDom('input', {'type': 'text'})); - var element = this.getElement(); - dom.appendChild(element, el); - this.contentElement_ = dom.createDom('div', - goog.getCssName(this.getRenderer().getCssClass(), 'content')); - dom.appendChild(element, this.contentElement_); - - this.initFilterInput_(); -}; - - -/** - * Helper method that initializes the filter input element. - * @private - */ -goog.ui.FilteredMenu.prototype.initFilterInput_ = function() { - this.setFocusable(true); - this.setKeyEventTarget(this.filterInput_); - - // Workaround for mozilla bug #236791. - if (goog.userAgent.GECKO) { - this.filterInput_.setAttribute('autocomplete', 'off'); - } - - if (this.maxLength_) { - this.filterInput_.maxLength = this.maxLength_; - } -}; - - -/** - * Sets up listeners and prepares the filter functionality. - * @private - */ -goog.ui.FilteredMenu.prototype.setUpFilterListeners_ = function() { - if (!this.inputHandler_ && this.filterInput_) { - this.inputHandler_ = new goog.events.InputHandler( - /** @type {Element} */ (this.filterInput_)); - goog.style.setUnselectable(this.filterInput_, false); - goog.events.listen(this.inputHandler_, - goog.events.InputHandler.EventType.INPUT, - this.handleFilterEvent, false, this); - goog.events.listen(this.filterInput_.parentNode, - goog.events.EventType.CLICK, - this.onFilterLabelClick_, false, this); - if (this.allowMultiple_) { - this.enteredItems_ = []; - } - } -}; - - -/** - * Tears down listeners and resets the filter functionality. - * @private - */ -goog.ui.FilteredMenu.prototype.tearDownFilterListeners_ = function() { - if (this.inputHandler_) { - goog.events.unlisten(this.inputHandler_, - goog.events.InputHandler.EventType.INPUT, - this.handleFilterEvent, false, this); - goog.events.unlisten(this.filterInput_.parentNode, - goog.events.EventType.CLICK, - this.onFilterLabelClick_, false, this); - - this.inputHandler_.dispose(); - this.inputHandler_ = undefined; - this.enteredItems_ = undefined; - } -}; - - -/** @override */ -goog.ui.FilteredMenu.prototype.setVisible = function(show, opt_force, opt_e) { - var visibilityChanged = goog.ui.FilteredMenu.superClass_.setVisible.call(this, - show, opt_force, opt_e); - if (visibilityChanged && show && this.isInDocument()) { - this.setFilter(''); - this.setUpFilterListeners_(); - } else if (visibilityChanged && !show) { - this.tearDownFilterListeners_(); - } - - return visibilityChanged; -}; - - -/** @override */ -goog.ui.FilteredMenu.prototype.disposeInternal = function() { - this.tearDownFilterListeners_(); - this.filterInput_ = undefined; - this.labelEl_ = undefined; - goog.ui.FilteredMenu.superClass_.disposeInternal.call(this); -}; - - -/** - * Sets the filter label (the label displayed in the filter input element if no - * text has been entered). - * @param {?string} label Label text. - */ -goog.ui.FilteredMenu.prototype.setFilterLabel = function(label) { - this.label_ = label || ''; - if (this.labelEl_) { - goog.dom.setTextContent(this.labelEl_, this.label_); - } -}; - - -/** - * @return {string} The filter label. - */ -goog.ui.FilteredMenu.prototype.getFilterLabel = function() { - return this.label_; -}; - - -/** - * Sets the filter string. - * @param {?string} str Filter string. - */ -goog.ui.FilteredMenu.prototype.setFilter = function(str) { - if (this.filterInput_) { - this.filterInput_.value = str; - this.filterItems_(str); - } -}; - - -/** - * Returns the filter string. - * @return {string} Current filter or an an empty string. - */ -goog.ui.FilteredMenu.prototype.getFilter = function() { - return this.filterInput_ && goog.isString(this.filterInput_.value) ? - this.filterInput_.value : ''; -}; - - -/** - * Sets the index of first item that should be affected by the filter. Menu - * items with a lower index will not be affected by the filter. - * @param {number} index Index of first item that should be affected by filter. - */ -goog.ui.FilteredMenu.prototype.setFilterFromIndex = function(index) { - this.filterFromIndex_ = index; -}; - - -/** - * Returns the index of first item that is affected by the filter. - * @return {number} Index of first item that is affected by filter. - */ -goog.ui.FilteredMenu.prototype.getFilterFromIndex = function() { - return this.filterFromIndex_; -}; - - -/** - * Gets a list of items entered in the search box. - * @return {Array.<string>} The entered items. - */ -goog.ui.FilteredMenu.prototype.getEnteredItems = function() { - return this.enteredItems_ || []; -}; - - -/** - * Sets whether multiple items can be entered comma separated. - * @param {boolean} b Whether multiple items can be entered. - */ -goog.ui.FilteredMenu.prototype.setAllowMultiple = function(b) { - this.allowMultiple_ = b; -}; - - -/** - * @return {boolean} Whether multiple items can be entered comma separated. - */ -goog.ui.FilteredMenu.prototype.getAllowMultiple = function() { - return this.allowMultiple_; -}; - - -/** - * Sets whether the specified child should be affected (shown/hidden) by the - * filter criteria. - * @param {goog.ui.Component} child Child to change. - * @param {boolean} persistent Whether the child should be persistent. - */ -goog.ui.FilteredMenu.prototype.setPersistentVisibility = function(child, - persistent) { - if (!this.persistentChildren_) { - this.persistentChildren_ = {}; - } - this.persistentChildren_[child.getId()] = persistent; -}; - - -/** - * Returns whether the specified child should be affected (shown/hidden) by the - * filter criteria. - * @param {goog.ui.Component} child Menu item to check. - * @return {boolean} Whether the menu item is persistent. - */ -goog.ui.FilteredMenu.prototype.hasPersistentVisibility = function(child) { - return !!(this.persistentChildren_ && - this.persistentChildren_[child.getId()]); -}; - - -/** - * Handles filter input events. - * @param {goog.events.BrowserEvent} e The event object. - */ -goog.ui.FilteredMenu.prototype.handleFilterEvent = function(e) { - this.filterItems_(this.filterInput_.value); - - // Highlight the first visible item unless there's already a highlighted item. - var highlighted = this.getHighlighted(); - if (!highlighted || !highlighted.isVisible()) { - this.highlightFirst(); - } - this.dispatchEvent(goog.ui.FilteredMenu.EventType.FILTER_CHANGED); -}; - - -/** - * Shows/hides elements based on the supplied filter. - * @param {?string} str Filter string. - * @private - */ -goog.ui.FilteredMenu.prototype.filterItems_ = function(str) { - // Do nothing unless the filter string has changed. - if (this.filterStr_ == str) { - return; - } - - if (this.labelEl_) { - this.labelEl_.style.visibility = str == '' ? 'visible' : 'hidden'; - } - - if (this.allowMultiple_ && this.enteredItems_) { - // Matches all non space characters after the last comma. - var lastWordRegExp = /^(.+),[ ]*([^,]*)$/; - var matches = str.match(lastWordRegExp); - // matches[1] is the string up to, but not including, the last comma and - // matches[2] the part after the last comma. If there are no non-space - // characters after the last comma matches[2] is undefined. - var items = matches && matches[1] ? matches[1].split(',') : []; - - // If the number of comma separated items has changes recreate the - // entered items array and fire a change event. - if (str.substr(str.length - 1, 1) == ',' || - items.length != this.enteredItems_.length) { - var lastItem = items[items.length - 1] || ''; - - // Auto complete text in input box based on the highlighted item. - if (this.getHighlighted() && lastItem != '') { - var caption = this.getHighlighted().getCaption(); - if (caption.toLowerCase().indexOf(lastItem.toLowerCase()) == 0) { - items[items.length - 1] = caption; - this.filterInput_.value = items.join(',') + ','; - } - } - this.enteredItems_ = items; - this.dispatchEvent(goog.ui.Component.EventType.CHANGE); - this.setHighlightedIndex(-1); - } - - if (matches) { - str = matches.length > 2 ? goog.string.trim(matches[2]) : ''; - } - } - - var matcher = new RegExp('(^|[- ,_/.:])' + - goog.string.regExpEscape(str), 'i'); - for (var child, i = this.filterFromIndex_; child = this.getChildAt(i); i++) { - if (child instanceof goog.ui.FilterObservingMenuItem) { - child.callObserver(str); - } else if (!this.hasPersistentVisibility(child)) { - // Only show items matching the filter and highlight the part of the - // caption that matches. - var caption = child.getCaption(); - if (caption) { - var matchArray = caption.match(matcher); - if (str == '' || matchArray) { - child.setVisible(true); - var pos = caption.indexOf(matchArray[0]); - - // If position is non zero increase by one to skip the separator. - if (pos) { - pos++; - } - - if (str == '') { - child.setContent(caption); - } else { - child.setContent(this.getDomHelper().createDom('span', null, - caption.substr(0, pos), - this.getDomHelper().createDom( - 'b', null, caption.substr(pos, str.length)), - caption.substr(pos + str.length, - caption.length - str.length - pos))); - } - } else { - child.setVisible(false); - } - } else { - - // Hide separators and other items without a caption if a filter string - // has been entered. - child.setVisible(str == ''); - } - } - } - this.filterStr_ = str; -}; - - -/** - * Handles the menu's behavior for a key event. The highlighted menu item will - * be given the opportunity to handle the key behavior. - * @param {goog.events.KeyEvent} e A browser event. - * @return {boolean} Whether the event was handled. - */ -goog.ui.FilteredMenu.prototype.handleKeyEvent = function(e) { - // Home, end and the arrow keys are normally used to change the selected menu - // item. Return false here to prevent the menu from preventing the default - // behavior for HOME, END and any key press with a modifier. - if (e.shiftKey || e.ctrlKey || e.altKey || - e.keyCode == goog.events.KeyCodes.HOME || - e.keyCode == goog.events.KeyCodes.END) { - return false; - } - - if (e.keyCode == goog.events.KeyCodes.ESC) { - this.dispatchEvent(goog.ui.Component.EventType.BLUR); - return true; - } - - return goog.ui.FilteredMenu.superClass_.handleKeyEvent.call(this, e); -}; - - -/** - * Sets the highlighted index, unless the HIGHLIGHT event is intercepted and - * cancelled. -1 = no highlight. Also scrolls the menu item into view. - * @param {number} index Index of menu item to highlight. - */ -goog.ui.FilteredMenu.prototype.setHighlightedIndex = function(index) { - goog.ui.FilteredMenu.superClass_.setHighlightedIndex.call(this, index); - var contentEl = this.getContentElement(); - var el = this.getHighlighted() ? this.getHighlighted().getElement() : null; - - if (el && goog.dom.contains(contentEl, el)) { - var contentTop = goog.userAgent.IE && !goog.userAgent.isVersion(8) ? - 0 : contentEl.offsetTop; - - // IE (tested on IE8) sometime does not scroll enough by about - // 1px. So we add 1px to the scroll amount. This still looks ok in - // other browser except for the most degenerate case (menu height <= - // item height). - - // Scroll down if the highlighted item is below the bottom edge. - var diff = (el.offsetTop + el.offsetHeight - contentTop) - - (contentEl.clientHeight + contentEl.scrollTop) + 1; - contentEl.scrollTop += Math.max(diff, 0); - - // Scroll up if the highlighted item is above the top edge. - diff = contentEl.scrollTop - (el.offsetTop - contentTop) + 1; - contentEl.scrollTop -= Math.max(diff, 0); - } -}; - - -/** - * Handles clicks on the filter label. Focuses the input element. - * @param {goog.events.BrowserEvent} e A browser event. - * @private - */ -goog.ui.FilteredMenu.prototype.onFilterLabelClick_ = function(e) { - this.filterInput_.focus(); -}; - - -/** @override */ -goog.ui.FilteredMenu.prototype.getContentElement = function() { - return this.contentElement_ || this.getElement(); -}; - - -/** - * Returns the filter input element. - * @return {Element} Input element. - */ -goog.ui.FilteredMenu.prototype.getFilterInputElement = function() { - return this.filterInput_ || null; -}; - - -/** @override */ -goog.ui.FilteredMenu.prototype.decorateInternal = function(element) { - this.setElementInternal(element); - - // Decorate the menu content. - this.decorateContent(element); - - // Locate internally managed elements. - var el = this.getDomHelper().getElementsByTagNameAndClass('div', - goog.getCssName(this.getRenderer().getCssClass(), 'filter'), element)[0]; - this.labelEl_ = goog.dom.getFirstElementChild(el); - this.filterInput_ = goog.dom.getNextElementSibling(this.labelEl_); - this.contentElement_ = goog.dom.getNextElementSibling(el); - - // Decorate additional menu items (like 'apply'). - this.getRenderer().decorateChildren(this, el.parentNode, - this.contentElement_); - - this.initFilterInput_(); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/filteredmenu_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/filteredmenu_test.html.svn-base deleted file mode 100644 index 6243ba9..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/filteredmenu_test.html.svn-base +++ /dev/null @@ -1,301 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - - @author eae@google.com (Emil A Eklund) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.FilteredMenu</title> -<style> -.goog-menu { - position: absolute; - background: #eee; - border: 1px solid #aaa; - font: menu; -} -.goog-menu-content { - height: 2em; - overflow: auto; -} - -#testmenu { - right: 5px; - bottom: 5px; -} -</style> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.events.Event'); - goog.require('goog.math.Rect'); - goog.require('goog.style'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.FilteredMenu'); - goog.require('goog.ui.MenuItem'); -</script> -</head> -<body> -<div> - <div id="sandbox"></div> - - <div id="testmenu" class="goog-menu goog-menu-vertical"> - <div class="goog-menu-filter"> - <div></div> - <input tabindex="0" autocomplete="off" type="text"> - </div> - <div class="goog-menu-content"> - <div class="goog-menuitem">Apple</div> - <div class="goog-menuitem">Lemon</div> - <div class="goog-menuitem">Orange</div> - <div class="goog-menuitem">Strawberry</div> - </div> - </div> - -</div> -<script> - -var sandbox; - -function setUp() { - sandbox = goog.dom.getElement('sandbox'); -} - - -function tearDown() { - sandbox.innerHTML = ''; -} - - -function testRender() { - menu = new goog.ui.FilteredMenu(); - menu.addItem(new goog.ui.MenuItem('Menu Item 1')); - menu.addItem(new goog.ui.MenuItem('Menu Item 2')); - menu.render(sandbox); - - assertEquals('Menu should contain two items.', 2, menu.getChildCount()); - assertEquals('Caption of first menu item should match supplied value.', - 'Menu Item 1', - menu.getItemAt(0).getCaption()); - assertEquals('Caption of second menu item should match supplied value.', - 'Menu Item 2', - menu.getItemAt(1).getCaption()); - assertTrue('Caption of first item should be in document.', - sandbox.innerHTML.indexOf('Menu Item 1') != -1); - assertTrue('Caption of second item should be in document.', - sandbox.innerHTML.indexOf('Menu Item 2') != -1); - - menu.dispose(); -} - - -function testDecorate() { - menu = new goog.ui.FilteredMenu(); - menu.decorate(goog.dom.getElement('testmenu')); - - assertEquals('Menu should contain four items.', 4, menu.getChildCount()); - assertEquals('Caption of menu item should match decorated element', - 'Apple', - menu.getItemAt(0).getCaption()); - assertEquals('Caption of menu item should match decorated element', - 'Lemon', - menu.getItemAt(1).getCaption()); - assertEquals('Caption of menu item should match decorated element', - 'Orange', - menu.getItemAt(2).getCaption()); - assertEquals('Caption of menu item should match decorated element', - 'Strawberry', - menu.getItemAt(3).getCaption()); - - menu.dispose(); -} - - -function testDisposeClearsAllListeners() { - menu = new goog.ui.FilteredMenu(); - menu.addItem(new goog.ui.MenuItem('Menu Item 1')); - menu.addItem(new goog.ui.MenuItem('Menu Item 2')); - menu.render(sandbox); - menu.dispose(); - - assertEquals('Dispose should clear all listeners.', - 0, - goog.events.getTotalListenerCount()); -} - - -function testFilter() { - menu = new goog.ui.FilteredMenu(); - menu.addItem(new goog.ui.MenuItem('Family')); - menu.addItem(new goog.ui.MenuItem('Friends')); - menu.addItem(new goog.ui.MenuItem('Photos')); - menu.addItem(new goog.ui.MenuItem('Work')); - - menu.render(sandbox); - - // Check menu items. - assertEquals('Family should be the first label in the move to menu', - 'Family', menu.getChildAt(0).getCaption()); - assertEquals('Friends should be the second label in the move to menu', - 'Friends', menu.getChildAt(1).getCaption()); - assertEquals('Photos should be the third label in the move to menu', - 'Photos', menu.getChildAt(2).getCaption()); - assertEquals('Work should be the fourth label in the move to menu', - 'Work', menu.getChildAt(3).getCaption()); - - // Filter menu. - menu.setFilter('W'); - assertFalse('Family should not be visible when the menu is filtered', - menu.getChildAt(0).isVisible()); - assertFalse('Friends should not be visible when the menu is filtered', - menu.getChildAt(1).isVisible()); - assertFalse('Photos should not be visible when the menu is filtered', - menu.getChildAt(2).isVisible()); - assertTrue('Work should be visible when the menu is filtered', - menu.getChildAt(3).isVisible()); - - menu.setFilter('W,'); - for (var i = 0; i < menu.getChildCount(); i++) { - assertFalse('W, should not match anything with allowMultiple set to false', - menu.getChildAt(i).isVisible()); - } - - // Clear filter. - menu.setFilter(''); - for (var i = 0; i < menu.getChildCount(); i++) { - assertTrue('All items should be visible', menu.getChildAt(i).isVisible()); - } - - menu.dispose(); -} - - -function testFilterAllowMultiple() { - menu = new goog.ui.FilteredMenu(); - menu.setAllowMultiple(true); - menu.addItem(new goog.ui.MenuItem('Family')); - menu.addItem(new goog.ui.MenuItem('Friends')); - menu.addItem(new goog.ui.MenuItem('Photos')); - menu.addItem(new goog.ui.MenuItem('Work')); - - menu.render(sandbox); - - // Filter menu. - menu.setFilter('W,'); - for (var i = 0; i < menu.getChildCount(); i++) { - assertTrue('W, should show all items with allowMultiple set to true', - menu.getChildAt(i).isVisible()); - } - - // Filter second label. - menu.setFilter('Work,P'); - assertFalse('Family should not be visible when the menu is filtered', - menu.getChildAt(0).isVisible()); - assertFalse('Friends should not be visible when the menu is filtered', - menu.getChildAt(1).isVisible()); - assertTrue('Photos should be visible when the menu is filtered', - menu.getChildAt(2).isVisible()); - assertFalse('Work should not be visible when the menu is filtered', - menu.getChildAt(3).isVisible()); - - // Clear filter. - menu.setFilter(''); - for (var i = 0; i < menu.getChildCount(); i++) { - assertTrue('All items should be visible', menu.getChildAt(i).isVisible()); - } - - menu.dispose(); -} - - -function testFilterWordBoundary() { - menu = new goog.ui.FilteredMenu(); - menu.addItem(new goog.ui.MenuItem('Vacation Photos')); - menu.addItem(new goog.ui.MenuItem('Work')); - menu.addItem(new goog.ui.MenuItem('Receipts & Invoices')); - menu.addItem(new goog.ui.MenuItem('Invitations')); - menu.addItem(new goog.ui.MenuItem('3.Family')); - menu.addItem(new goog.ui.MenuItem('No:Farm')); - menu.addItem(new goog.ui.MenuItem('Syd/Family')); - - menu.render(sandbox); - - // Filter menu. - menu.setFilter('Photos'); - assertTrue('Vacation Photos should be visible when the menu is filtered', - menu.getChildAt(0).isVisible()); - assertFalse('Work should not be visible when the menu is filtered', - menu.getChildAt(1).isVisible()); - assertFalse('Receipts & Invoices should not be visible when the menu is ' + - 'filtered', - menu.getChildAt(2).isVisible()); - assertFalse('Invitations should not be visible when the menu is filtered', - menu.getChildAt(3).isVisible()); - - menu.setFilter('I'); - assertFalse('Vacation Photos should not be visible when the menu is filtered', - menu.getChildAt(0).isVisible()); - assertFalse('Work should not be visible when the menu is filtered', - menu.getChildAt(1).isVisible()); - assertTrue('Receipts & Invoices should be visible when the menu is filtered', - menu.getChildAt(2).isVisible()); - assertTrue('Invitations should be visible when the menu is filtered', - menu.getChildAt(3).isVisible()); - - menu.setFilter('Fa'); - assertTrue('3.Family should be visible when the menu is filtered', - menu.getChildAt(4).isVisible()); - assertTrue('No:Farm should be visible when the menu is filtered', - menu.getChildAt(5).isVisible()); - assertTrue('Syd/Family should be visible when the menu is filtered', - menu.getChildAt(6).isVisible()); - - menu.dispose(); -} - - -function testScrollIntoView() { - menu = new goog.ui.FilteredMenu(); - menu.addItem(new goog.ui.MenuItem('Family')); - menu.addItem(new goog.ui.MenuItem('Friends')); - menu.addItem(new goog.ui.MenuItem('Photos')); - menu.addItem(new goog.ui.MenuItem('Work')); - menu.render(sandbox); - - menu.setHighlightedIndex(0); - assertTrue('Highlighted item should be visible', isHighlightedVisible(menu)); - menu.setHighlightedIndex(1); - assertTrue('Highlighted item should be visible', isHighlightedVisible(menu)); - menu.setHighlightedIndex(2); - assertTrue('Highlighted item should be visible', isHighlightedVisible(menu)); - menu.setHighlightedIndex(3); - assertTrue('Highlighted item should be visible', isHighlightedVisible(menu)); - menu.setHighlightedIndex(0); - assertTrue('Highlighted item should be visible', isHighlightedVisible(menu)); - - menu.dispose(); -} - - -function isHighlightedVisible(menu) { - var contRect = goog.style.getBounds(menu.getContentElement()); - // Expands the containing rectangle by 1px on top and bottom. The test - // sometime fails with 1px out of bound on FF6/Linux. This is not - // consistently reproducible. - contRect = new goog.math.Rect( - contRect.left, contRect.top - 1, contRect.width, contRect.height + 2); - var itemRect = goog.style.getBounds(menu.getHighlighted().getElement()); - return contRect.contains(itemRect); -} - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/filterobservingmenuitem.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/filterobservingmenuitem.js.svn-base deleted file mode 100644 index f3bc6b7..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/filterobservingmenuitem.js.svn-base +++ /dev/null @@ -1,98 +0,0 @@ -// 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 Menu item observing the filter text in a - * {@link goog.ui.FilteredMenu}. The observer method is called when the filter - * text changes and allows the menu item to update its content and state based - * on the filter. - * - * @author eae@google.com (Emil A Eklund) - */ - -goog.provide('goog.ui.FilterObservingMenuItem'); - -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.FilterObservingMenuItemRenderer'); -goog.require('goog.ui.MenuItem'); -goog.require('goog.ui.registry'); - - - -/** - * Class representing a filter observing menu item. - * - * @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 {*=} opt_model Data/model associated with the menu item. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper used for - * document interactions. - * @param {goog.ui.MenuItemRenderer=} opt_renderer Optional renderer. - * @constructor - * @extends {goog.ui.MenuItem} - */ -goog.ui.FilterObservingMenuItem = function(content, opt_model, opt_domHelper, - opt_renderer) { - goog.ui.MenuItem.call(this, content, opt_model, opt_domHelper, - opt_renderer || new goog.ui.FilterObservingMenuItemRenderer()); -}; -goog.inherits(goog.ui.FilterObservingMenuItem, goog.ui.MenuItem); - - -/** - * Function called when the filter text changes. - * @type {Function} function(goog.ui.FilterObservingMenuItem, string) - * @private - */ -goog.ui.FilterObservingMenuItem.prototype.observer_ = null; - - -/** @override */ -goog.ui.FilterObservingMenuItem.prototype.enterDocument = function() { - goog.ui.FilterObservingMenuItem.superClass_.enterDocument.call(this); - this.callObserver(); -}; - - -/** - * Sets the observer functions. - * @param {Function} f function(goog.ui.FilterObservingMenuItem, string). - */ -goog.ui.FilterObservingMenuItem.prototype.setObserver = function(f) { - this.observer_ = f; - this.callObserver(); -}; - - -/** - * Calls the observer function if one has been specified. - * @param {?string=} opt_str Filter string. - */ -goog.ui.FilterObservingMenuItem.prototype.callObserver = function(opt_str) { - if (this.observer_) { - this.observer_(this, opt_str || ''); - } -}; - - -// Register a decorator factory function for -// goog.ui.FilterObservingMenuItemRenderer. -goog.ui.registry.setDecoratorByClassName( - goog.ui.FilterObservingMenuItemRenderer.CSS_CLASS, - function() { - // FilterObservingMenuItem defaults to using - // FilterObservingMenuItemRenderer. - return new goog.ui.FilterObservingMenuItem(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/filterobservingmenuitemrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/filterobservingmenuitemrenderer.js.svn-base deleted file mode 100644 index 842580c..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/filterobservingmenuitemrenderer.js.svn-base +++ /dev/null @@ -1,61 +0,0 @@ -// 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 Menu item observing the filter text in a - * {@link goog.ui.FilteredMenu}. The observer method is called when the filter - * text changes and allows the menu item to update its content and state based - * on the filter. - * - * @author eae@google.com (Emil A Eklund) - */ - -goog.provide('goog.ui.FilterObservingMenuItemRenderer'); - -goog.require('goog.ui.MenuItemRenderer'); - - - -/** - * Default renderer for {@link goog.ui.FilterObservingMenuItem}s. Each item has - * the following structure: - * <div class="goog-filterobsmenuitem"><div>...(content)...</div></div> - * - * @constructor - * @extends {goog.ui.MenuItemRenderer} - */ -goog.ui.FilterObservingMenuItemRenderer = function() { - goog.ui.MenuItemRenderer.call(this); -}; -goog.inherits(goog.ui.FilterObservingMenuItemRenderer, - goog.ui.MenuItemRenderer); -goog.addSingletonGetter(goog.ui.FilterObservingMenuItemRenderer); - - -/** - * CSS class name the renderer applies to menu item elements. - * @type {string} - */ -goog.ui.FilterObservingMenuItemRenderer.CSS_CLASS = - goog.getCssName('goog-filterobsmenuitem'); - - -/** - * Returns the CSS class to be applied to menu items rendered using this - * renderer. - * @return {string} Renderer-specific CSS class. - */ -goog.ui.FilterObservingMenuItemRenderer.prototype.getCssClass = function() { - return goog.ui.FilterObservingMenuItemRenderer.CSS_CLASS; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/flatbuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/flatbuttonrenderer.js.svn-base deleted file mode 100644 index 73349f4..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/flatbuttonrenderer.js.svn-base +++ /dev/null @@ -1,138 +0,0 @@ -// 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 Similiar functionality of {@link goog.ui.ButtonRenderer}, - * but uses a <div> element instead of a <button> or <input> element. - * - */ - -goog.provide('goog.ui.FlatButtonRenderer'); - -goog.require('goog.dom.classes'); -goog.require('goog.ui.Button'); -goog.require('goog.ui.ButtonRenderer'); -goog.require('goog.ui.INLINE_BLOCK_CLASSNAME'); -goog.require('goog.ui.registry'); - - - -/** - * Flat renderer for {@link goog.ui.Button}s. Flat buttons can contain - * almost arbitrary HTML content, will flow like inline elements, but can be - * styled like block-level elements. - * @constructor - * @extends {goog.ui.ButtonRenderer} - */ -goog.ui.FlatButtonRenderer = function() { - goog.ui.ButtonRenderer.call(this); -}; -goog.inherits(goog.ui.FlatButtonRenderer, goog.ui.ButtonRenderer); -goog.addSingletonGetter(goog.ui.FlatButtonRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.FlatButtonRenderer.CSS_CLASS = goog.getCssName('goog-flat-button'); - - -/** - * Returns the control's contents wrapped in a div element, with - * the renderer's own CSS class and additional state-specific classes applied - * to it, and the button's disabled attribute set or cleared as needed. - * Overrides {@link goog.ui.ButtonRenderer#createDom}. - * @param {goog.ui.Button} button Button to render. - * @return {Element} Root element for the button. - */ -goog.ui.FlatButtonRenderer.prototype.createDom = function(button) { - var classNames = this.getClassNames(button); - var attributes = { - 'class': goog.ui.INLINE_BLOCK_CLASSNAME + ' ' + classNames.join(' '), - 'title': button.getTooltip() || '' - }; - return button.getDomHelper().createDom( - 'div', attributes, button.getContent()); -}; - - -/** - * Returns the ARIA role to be applied to flat buttons. - * @return {goog.dom.a11y.Role|undefined} ARIA role. - * @override - */ -goog.ui.FlatButtonRenderer.prototype.getAriaRole = function() { - return goog.dom.a11y.Role.BUTTON; -}; - - -/** - * Returns true if this renderer can decorate the element. Overrides - * {@link goog.ui.ButtonRenderer#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. - */ -goog.ui.FlatButtonRenderer.prototype.canDecorate = function(element) { - return element.tagName == 'DIV'; -}; - - -/** - * Takes an existing element and decorates it with the flat button control. - * Initializes the control's ID, content, tooltip, value, and state based - * on the ID of the element, its child nodes, and its CSS classes, respectively. - * Returns the element. Overrides {@link goog.ui.ButtonRenderer#decorate}. - * @param {goog.ui.Button} button Button instance to decorate the element. - * @param {Element} element Element to decorate. - * @return {Element} Decorated element. - */ -goog.ui.FlatButtonRenderer.prototype.decorate = function(button, element) { - goog.dom.classes.add(element, goog.ui.INLINE_BLOCK_CLASSNAME); - return goog.ui.FlatButtonRenderer.superClass_.decorate.call(this, button, - element); -}; - - -/** - * Flat buttons can't use the value attribute since they are div elements. - * Overrides {@link goog.ui.ButtonRenderer#getValue} to prevent trying to - * access the element's value. - * @param {Element} element The button control's root element. - * @return {null} Value not valid for flat buttons. - */ -goog.ui.FlatButtonRenderer.prototype.getValue = function(element) { - // Flat buttons don't store their value in the DOM. - return null; -}; - - -/** - * Returns the CSS class to be applied to the root element of components - * rendered using this renderer. - * @return {string} Renderer-specific CSS class. - */ -goog.ui.FlatButtonRenderer.prototype.getCssClass = function() { - return goog.ui.FlatButtonRenderer.CSS_CLASS; -}; - - -// Register a decorator factory function for Flat Buttons. -goog.ui.registry.setDecoratorByClassName(goog.ui.FlatButtonRenderer.CSS_CLASS, - function() { - // Uses goog.ui.Button, but with FlatButtonRenderer. - return new goog.ui.Button(null, goog.ui.FlatButtonRenderer.getInstance()); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/flatmenubuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/flatmenubuttonrenderer.js.svn-base deleted file mode 100644 index f622fa7..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/flatmenubuttonrenderer.js.svn-base +++ /dev/null @@ -1,199 +0,0 @@ -// 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 Similiar functionality of {@link goog.ui.MenuButtonRenderer}, - * but inherits from {@link goog.ui.FlatButtonRenderer} instead of - * {@link goog.ui.CustomButtonRenderer}. This creates a simpler menu button - * that will look more like a traditional <select> menu. - * - */ - -goog.provide('goog.ui.FlatMenuButtonRenderer'); - -goog.require('goog.style'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.FlatButtonRenderer'); -goog.require('goog.ui.INLINE_BLOCK_CLASSNAME'); -goog.require('goog.ui.Menu'); -goog.require('goog.ui.MenuButton'); -goog.require('goog.ui.MenuRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * Flat Menu Button renderer. Creates a simpler version of - * {@link goog.ui.MenuButton} that doesn't look like a button and - * doesn't have rounded corners. Uses just a <div> and looks more like - * a traditional <select> element. - * @constructor - * @extends {goog.ui.FlatButtonRenderer} - */ -goog.ui.FlatMenuButtonRenderer = function() { - goog.ui.FlatButtonRenderer.call(this); -}; -goog.inherits(goog.ui.FlatMenuButtonRenderer, goog.ui.FlatButtonRenderer); -goog.addSingletonGetter(goog.ui.FlatMenuButtonRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.FlatMenuButtonRenderer.CSS_CLASS = - goog.getCssName('goog-flat-menu-button'); - - -/** - * Returns the button's contents wrapped in the following DOM structure: - * <div class="goog-inline-block goog-flat-menu-button"> - * <div class="goog-inline-block goog-flat-menu-button-caption"> - * Contents... - * </div> - * <div class="goog-inline-block goog-flat-menu-button-dropdown"> - * - * </div> - * </div> - * Overrides {@link goog.ui.FlatButtonRenderer#createDom}. - * @param {goog.ui.Button} button Button to render. - * @return {Element} Root element for the button. - */ -goog.ui.FlatMenuButtonRenderer.prototype.createDom = function(button) { - var classNames = this.getClassNames(button); - var attributes = { - 'class': goog.ui.INLINE_BLOCK_CLASSNAME + ' ' + classNames.join(' '), - 'title': button.getTooltip() || '' - }; - return button.getDomHelper().createDom('div', attributes, - [this.createCaption(button.getContent(), button.getDomHelper()), - this.createDropdown(button.getDomHelper())]); -}; - - -/** - * Takes the button's root element and returns the parent element of the - * button's contents. - * @param {Element} element Root element of the button whose content - * element is to be returned. - * @return {Element} The button's content element (if any). - */ -goog.ui.FlatMenuButtonRenderer.prototype.getContentElement = function(element) { - return element && /** @type {Element} */ (element.firstChild); -}; - - -/** - * 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.MenuButton} button Menu button to decorate the element. - * @param {Element} element Element to decorate. - * @return {Element} Decorated element. - */ -goog.ui.FlatMenuButtonRenderer.prototype.decorate = function(button, element) { - // TODO(user): MenuButtonRenderer uses the exact same code. - // Refactor this block to its own module where both can use it. - 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; see - // bug 1089244. - goog.style.showElement(menuElem, false); - button.getDomHelper().getDocument().body.appendChild(menuElem); - - // Decorate the menu and attach it to the button. - var menu = new goog.ui.Menu(); - menu.decorate(menuElem); - button.setMenu(menu); - } - - // Add the caption if it's not already there. - var captionElem = goog.dom.getElementsByTagNameAndClass( - '*', goog.getCssName(this.getCssClass(), 'caption'), element)[0]; - if (!captionElem) { - element.appendChild( - this.createCaption(element.childNodes, button.getDomHelper())); - } - - // Add the dropdown icon if it's not already there. - var dropdownElem = goog.dom.getElementsByTagNameAndClass( - '*', goog.getCssName(this.getCssClass(), 'dropdown'), element)[0]; - if (!dropdownElem) { - element.appendChild(this.createDropdown(button.getDomHelper())); - } - - // Let the superclass do the rest. - return goog.ui.FlatMenuButtonRenderer.superClass_.decorate.call(this, button, - element); -}; - - -/** - * 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-flat-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.FlatMenuButtonRenderer.prototype.createCaption = function(content, - dom) { - return dom.createDom('div', - goog.ui.INLINE_BLOCK_CLASSNAME + ' ' + - goog.getCssName(this.getCssClass(), 'caption'), content); -}; - - -/** - * Returns an appropriately-styled DIV containing a dropdown arrow element. - * Creates the following DOM structure: - * <div class="goog-inline-block goog-flat-menu-button-dropdown"> - * - * </div> - * @param {goog.dom.DomHelper} dom DOM helper, used for document interaction. - * @return {Element} Dropdown element. - */ -goog.ui.FlatMenuButtonRenderer.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. - */ -goog.ui.FlatMenuButtonRenderer.prototype.getCssClass = function() { - return goog.ui.FlatMenuButtonRenderer.CSS_CLASS; -}; - - -// Register a decorator factory function for Flat Menu Buttons. -goog.ui.registry.setDecoratorByClassName( - goog.ui.FlatMenuButtonRenderer.CSS_CLASS, - function() { - // Uses goog.ui.MenuButton, but with FlatMenuButtonRenderer. - return new goog.ui.MenuButton(null, null, - goog.ui.FlatMenuButtonRenderer.getInstance()); - }); - diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/formpost.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/formpost.js.svn-base deleted file mode 100644 index 4787c7b..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/formpost.js.svn-base +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2008 The Closure Library Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Utility for making the browser submit a hidden form, which can - * be used to effect a POST from JavaScript. - * - */ - -goog.provide('goog.ui.FormPost'); - -goog.require('goog.array'); -goog.require('goog.dom.TagName'); -goog.require('goog.string'); -goog.require('goog.string.StringBuffer'); -goog.require('goog.ui.Component'); - - - -/** - * Creates a formpost object. - * @constructor - * @extends {goog.ui.Component} - * @param {goog.dom.DomHelper=} opt_dom The DOM helper. - */ -goog.ui.FormPost = function(opt_dom) { - goog.ui.Component.call(this, opt_dom); -}; -goog.inherits(goog.ui.FormPost, goog.ui.Component); - - -/** @override */ -goog.ui.FormPost.prototype.createDom = function() { - this.setElementInternal(this.getDomHelper().createDom(goog.dom.TagName.FORM, - {'method': 'POST', 'style': 'display:none'})); -}; - - -/** - * Constructs a POST request and directs the browser as if a form were - * submitted. - * @param {Object} parameters Object with parameter values. Values can be - * strings, numbers, or arrays of strings or numbers. - * @param {string=} opt_url The destination URL. If not specified, uses the - * current URL for window for the DOM specified in the constructor. - * @param {string=} opt_target An optional name of a window in which to open the - * URL. If not specified, uses the window for the DOM specified in the - * constructor. - */ -goog.ui.FormPost.prototype.post = function(parameters, opt_url, opt_target) { - var form = this.getElement(); - if (!form) { - this.render(); - form = this.getElement(); - } - form.action = opt_url || ''; - form.target = opt_target || ''; - this.setParameters_(form, parameters); - form.submit(); -}; - - -/** - * Creates hidden inputs in a form to match parameters. - * @param {Element} form The form element. - * @param {Object} parameters Object with parameter values. Values can be - * strings, numbers, or arrays of strings or numbers. - * @private - */ -goog.ui.FormPost.prototype.setParameters_ = function(form, parameters) { - var name, value, sb = new goog.string.StringBuffer(); - for (name in parameters) { - value = parameters[name]; - if (goog.isArrayLike(value)) { - goog.array.forEach(value, goog.bind(this.appendInput_, this, sb, name)); - } else { - this.appendInput_(sb, name, value); - } - } - form.innerHTML = sb.toString(); -}; - - -/** - * Appends a hidden <INPUT> tag to a string buffer. - * @param {goog.string.StringBuffer} out A string buffer. - * @param {string} name The name of the input. - * @param {string} value The value of the input. - * @private - */ -goog.ui.FormPost.prototype.appendInput_ = function(out, name, value) { - out.append( - '<input type="hidden" name="', - goog.string.htmlEscape(name), - '" value="', - goog.string.htmlEscape(value), - '">'); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/formpost_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/formpost_test.html.svn-base deleted file mode 100644 index 5a08867..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/formpost_test.html.svn-base +++ /dev/null @@ -1,105 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2009 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> - <meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.FormPost</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.dom.TagName'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.FormPost'); - goog.require('goog.userAgent'); - goog.require('goog.userAgent.product'); - goog.require('goog.userAgent.product.isVersion'); - </script> -</head> -<body> - <script> - var TARGET = 'target'; - var ACTION_URL = 'http://url/'; - var formPost; - var parameters; - var submits; - var originalCreateDom = goog.ui.FormPost.prototype.createDom; - - function isChrome7or8() { - // Temporarily disabled in Chrome 7 & 8. See b/3176768 - if (goog.userAgent.product.CHROME && - goog.userAgent.product.isVersion('7.0') && - !goog.userAgent.product.isVersion('8.0')) { - return false; - } - - return true; - } - - function setUp() { - formPost = new goog.ui.FormPost(); - submits = 0; - - // Replace the form's submit method with a fake. - goog.ui.FormPost.prototype.createDom = function() { - originalCreateDom.apply(this, arguments); - - this.getElement().submit = function() { submits++ }; - } - parameters = {'foo': 'bar', 'baz': 'blah', 'array': ['no', 'yes']}; - } - - function tearDown() { - formPost.dispose(); - goog.ui.FormPost.prototype.createDom = originalCreateDom; - } - - function testPost() { - formPost.post(parameters, ACTION_URL, TARGET); - expectUrlAndParameters_(ACTION_URL, TARGET, parameters); - } - - function testPostWithDefaults() { - // Temporarily disabled in Chrome 7. See See b/3176768 - if (isChrome7or8) { - return; - } - formPost = new goog.ui.FormPost(); - formPost.post(parameters); - expectUrlAndParameters_('', '', parameters); - } - - function expectUrlAndParameters_(url, target, parameters) { - var form = formPost.getElement(); - assertEquals('element must be a form', - goog.dom.TagName.FORM, form.tagName); - assertEquals('form must be hidden', 'none', form.style.display); - assertEquals('form method must be POST', - 'POST', form.method.toUpperCase()); - assertEquals('submits', 1, submits); - assertEquals('action attribute', url, form.action); - assertEquals('target attribute', target, form.target); - var inputs = goog.dom.getElementsByTagNameAndClass( - goog.dom.TagName.INPUT, null, form); - var formValues = {}; - for (var i = 0, input = inputs[i]; input = inputs[i]; i++) { - if (goog.isArray(formValues[input.name])) { - formValues[input.name].push(input.value); - } else if (input.name in formValues) { - formValues[input.name] = [formValues[input.name], input.value]; - } else { - formValues[input.name] = input.value; - } - } - assertObjectEquals('form values must match', parameters, formValues); - } - - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/gauge.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/gauge.js.svn-base deleted file mode 100644 index f3dfdc3..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/gauge.js.svn-base +++ /dev/null @@ -1,1002 +0,0 @@ -// 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 Gauge UI component, using browser vector graphics. - * @see ../demos/gauge.html - */ - - -goog.provide('goog.ui.Gauge'); -goog.provide('goog.ui.GaugeColoredRange'); - - -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -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.graphics'); -goog.require('goog.graphics.Font'); -goog.require('goog.graphics.Path'); -goog.require('goog.graphics.SolidFill'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.GaugeTheme'); - - - -/** - * Information on how to decorate a range in the gauge. - * This is an internal-only class. - * @param {number} fromValue The range start (minimal) value. - * @param {number} toValue The range end (maximal) value. - * @param {string} backgroundColor Color to fill the range background with. - * @constructor - */ -goog.ui.GaugeColoredRange = function(fromValue, toValue, backgroundColor) { - - /** - * The range start (minimal) value. - * @type {number} - */ - this.fromValue = fromValue; - - - /** - * The range end (maximal) value. - * @type {number} - */ - this.toValue = toValue; - - - /** - * Color to fill the range background with. - * @type {string} - */ - this.backgroundColor = backgroundColor; -}; - - - -/** - * A UI component that displays a gauge. - * A gauge displayes a current value within a round axis that represents a - * given range. - * The gauge is built from an external border, and internal border inside it, - * ticks and labels inside the internal border, and a needle that points to - * the current value. - * @param {number} width The width in pixels. - * @param {number} height The height in pixels. - * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the - * document we want to render in. - * @constructor - * @extends {goog.ui.Component} - */ -goog.ui.Gauge = function(width, height, opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - - /** - * The width in pixels of this component. - * @type {number} - * @private - */ - this.width_ = width; - - - /** - * The height in pixels of this component. - * @type {number} - * @private - */ - this.height_ = height; - - - /** - * The underlying graphics. - * @type {goog.graphics.AbstractGraphics} - * @private - */ - this.graphics_ = goog.graphics.createGraphics(width, height, - null, null, opt_domHelper); - - - /** - * Colors to paint the background of certain ranges (optional). - * @type {Array.<goog.ui.GaugeColoredRange>} - * @private - */ - this.rangeColors_ = []; -}; -goog.inherits(goog.ui.Gauge, goog.ui.Component); - - -/** - * Constant for a background color for a gauge area. - */ -goog.ui.Gauge.RED = '#ffc0c0'; - - -/** - * Constant for a background color for a gauge area. - */ -goog.ui.Gauge.GREEN = '#c0ffc0'; - - -/** - * Constant for a background color for a gauge area. - */ -goog.ui.Gauge.YELLOW = '#ffffa0'; - - -/** - * The radius of the entire gauge from the canvas size. - * @type {number} - */ -goog.ui.Gauge.FACTOR_RADIUS_FROM_SIZE = 0.45; - - -/** - * The ratio of internal gauge radius from entire radius. - * The remaining area is the border around the gauge. - * @type {number} - */ -goog.ui.Gauge.FACTOR_MAIN_AREA = 0.9; - - -/** - * The ratio of the colored background area for value ranges. - * The colored area width is computed as - * InternalRadius * (1 - FACTOR_COLOR_RADIUS) - * @type {number} - */ -goog.ui.Gauge.FACTOR_COLOR_RADIUS = 0.75; - - -/** - * The ratio of the major ticks length start position, from the radius. - * The major ticks length width is computed as - * InternalRadius * (1 - FACTOR_MAJOR_TICKS) - * @type {number} - */ -goog.ui.Gauge.FACTOR_MAJOR_TICKS = 0.8; - - -/** - * The ratio of the minor ticks length start position, from the radius. - * The minor ticks length width is computed as - * InternalRadius * (1 - FACTOR_MINOR_TICKS) - * @type {number} - */ -goog.ui.Gauge.FACTOR_MINOR_TICKS = 0.9; - - -/** - * The length of the needle front (value facing) from the internal radius. - * The needle front is the part of the needle that points to the value. - * @type {number} - */ -goog.ui.Gauge.FACTOR_NEEDLE_FRONT = 0.95; - - -/** - * The length of the needle back relative to the internal radius. - * The needle back is the part of the needle that points away from the value. - * @type {number} - */ -goog.ui.Gauge.FACTOR_NEEDLE_BACK = 0.3; - - -/** - * The width of the needle front at the hinge. - * This is the width of the curve control point, the actual width is - * computed by the curve itself. - * @type {number} - */ -goog.ui.Gauge.FACTOR_NEEDLE_WIDTH = 0.07; - - -/** - * The width (radius) of the needle hinge from the gauge radius. - * @type {number} - */ -goog.ui.Gauge.FACTOR_NEEDLE_HINGE = 0.15; - - -/** - * The title font size (height) for titles relative to the internal radius. - * @type {number} - */ -goog.ui.Gauge.FACTOR_TITLE_FONT_SIZE = 0.16; - - -/** - * The offset of the title from the center, relative to the internal radius. - * @type {number} - */ -goog.ui.Gauge.FACTOR_TITLE_OFFSET = 0.35; - - -/** - * The formatted value font size (height) relative to the internal radius. - * @type {number} - */ -goog.ui.Gauge.FACTOR_VALUE_FONT_SIZE = 0.18; - - -/** - * The title font size (height) for tick labels relative to the internal radius. - * @type {number} - */ -goog.ui.Gauge.FACTOR_TICK_LABEL_FONT_SIZE = 0.14; - - -/** - * The offset of the formatted value down from the center, relative to the - * internal radius. - * @type {number} - */ -goog.ui.Gauge.FACTOR_VALUE_OFFSET = 0.75; - - -/** - * The font name for title text. - * @type {string} - */ -goog.ui.Gauge.TITLE_FONT_NAME = 'arial'; - - -/** - * The maximal size of a step the needle can move (percent from size of range). - * If the needle needs to move more, it will be moved in animated steps, to - * show a smooth transition between values. - * @type {number} - */ -goog.ui.Gauge.NEEDLE_MOVE_MAX_STEP = 0.02; - - -/** - * Time in miliseconds for animating a move of the value pointer. - * @type {number} - */ -goog.ui.Gauge.NEEDLE_MOVE_TIME = 400; - - -/** - * Tolerance factor for how much values can exceed the range (being too - * low or too high). The value is presented as a position (percentage). - * @type {number} - */ -goog.ui.Gauge.MAX_EXCEED_POSITION_POSITION = 0.02; - - -/** - * The minimal value that can be displayed. - * @private - * @type {number} - */ -goog.ui.Gauge.prototype.minValue_ = 0; - - -/** - * The maximal value that can be displayed. - * @private - * @type {number} - */ -goog.ui.Gauge.prototype.maxValue_ = 100; - - -/** - * The number of major tick sections. - * @private - * @type {number} - */ -goog.ui.Gauge.prototype.majorTicks_ = 5; - - -/** - * The number of minor tick sections in each major tick section. - * @private - * @type {number} - */ -goog.ui.Gauge.prototype.minorTicks_ = 2; - - -/** - * The current value that needs to be displayed in the gauge. - * @private - * @type {number} - */ -goog.ui.Gauge.prototype.value_ = 0; - - -/** - * The current value formatted into a String. - * @private - * @type {?string} - */ -goog.ui.Gauge.prototype.formattedValue_ = null; - - -/** - * The current colors theme. - * @private - * @type {goog.ui.GaugeTheme?} - */ -goog.ui.Gauge.prototype.theme_ = null; - - -/** - * Title to display above the gauge center. - * @private - * @type {?string} - */ -goog.ui.Gauge.prototype.titleTop_ = null; - - -/** - * Title to display below the gauge center. - * @private - * @type {?string} - */ -goog.ui.Gauge.prototype.titleBottom_ = null; - - -/** - * Font to use for drawing titles. - * If null (default), computed dynamically with a size relative to the - * gauge radius. - * @private - * @type {goog.graphics.Font?} - */ -goog.ui.Gauge.prototype.titleFont_ = null; - - -/** - * Font to use for drawing the formatted value. - * If null (default), computed dynamically with a size relative to the - * gauge radius. - * @private - * @type {goog.graphics.Font?} - */ -goog.ui.Gauge.prototype.valueFont_ = null; - - -/** - * Font to use for drawing tick labels. - * If null (default), computed dynamically with a size relative to the - * gauge radius. - * @private - * @type {goog.graphics.Font?} - */ -goog.ui.Gauge.prototype.tickLabelFont_ = null; - - -/** - * The size in angles of the gauge axis area. - * @private - * @type {number} - */ -goog.ui.Gauge.prototype.angleSpan_ = 270; - - -/** - * The radius for drawing the needle. - * Computed on full redraw, and used on every animation step of moving - * the needle. - * @type {number} - * @private - */ -goog.ui.Gauge.prototype.needleRadius_ = 0; - - -/** - * The group elemnt of the needle. Contains all elements that change when the - * gauge value changes. - * @type {goog.graphics.GroupElement?} - * @private - */ -goog.ui.Gauge.prototype.needleGroup_ = null; - - -/** - * The current position (0-1) of the visible needle. - * Initially set to null to prevent animation on first opening of the gauge. - * @type {?number} - * @private - */ -goog.ui.Gauge.prototype.needleValuePosition_ = null; - - -/** - * Text labels to display by major tick marks. - * @type {Array.<string>?} - * @private - */ -goog.ui.Gauge.prototype.majorTickLabels_ = null; - - -/** - * Animation object while needle is being moved (animated). - * @type {goog.fx.Animation?} - * @private - */ -goog.ui.Gauge.prototype.animation_ = null; - - -/** - * @return {number} The minimum value of the range. - */ -goog.ui.Gauge.prototype.getMinimum = function() { - return this.minValue_; -}; - - -/** - * Sets the minimum value of the range - * @param {number} min The minimum value of the range. - */ -goog.ui.Gauge.prototype.setMinimum = function(min) { - this.minValue_ = min; - - if (this.getElement()) { - goog.dom.a11y.setState(this.getElement(), 'valuemin', min); - } -}; - - -/** - * @return {number} The maximum value of the range. - */ -goog.ui.Gauge.prototype.getMaximum = function() { - return this.maxValue_; -}; - - -/** - * Sets the maximum number of the range - * @param {number} max The maximum value of the range. - */ -goog.ui.Gauge.prototype.setMaximum = function(max) { - this.maxValue_ = max; - - if (this.getElement()) { - goog.dom.a11y.setState(this.getElement(), 'valuemax', max); - } -}; - - -/** - * Sets the current value range displayed by the gauge. - * @param {number} value The current value for the gauge. This value - * determines the position of the needle of the gauge. - * @param {string=} opt_formattedValue The string value to show in the gauge. - * If not specified, no string value will be displayed. - */ -goog.ui.Gauge.prototype.setValue = function(value, opt_formattedValue) { - this.value_ = value; - this.formattedValue_ = opt_formattedValue || null; - - this.stopAnimation_(); // Stop the active animation if exists - - // Compute desired value position (normalize value to range 0-1) - var valuePosition = this.valueToRangePosition_(value); - if (this.needleValuePosition_ == null) { - // No animation on initial display - this.needleValuePosition_ = valuePosition; - this.drawValue_(); - } else { - // Animate move - this.animation_ = new goog.fx.Animation([this.needleValuePosition_], - [valuePosition], - goog.ui.Gauge.NEEDLE_MOVE_TIME, - goog.fx.easing.inAndOut); - - var events = [goog.fx.Transition.EventType.BEGIN, - goog.fx.Animation.EventType.ANIMATE, - goog.fx.Transition.EventType.END]; - goog.events.listen(this.animation_, events, this.onAnimate_, false, this); - goog.events.listen(this.animation_, goog.fx.Transition.EventType.END, - this.onAnimateEnd_, false, this); - - // Start animation - this.animation_.play(false); - } - - if (this.getElement()) { - goog.dom.a11y.setState(this.getElement(), 'valuenow', this.value_); - } -}; - - -/** - * Sets the number of major tick sections and minor tick sections. - * @param {number} majorUnits The number of major tick sections. - * @param {number} minorUnits The number of minor tick sections for each major - * tick section. - */ -goog.ui.Gauge.prototype.setTicks = function(majorUnits, minorUnits) { - this.majorTicks_ = Math.max(1, majorUnits); - this.minorTicks_ = Math.max(1, minorUnits); - this.draw_(); -}; - - -/** - * Sets the labels of the major ticks. - * @param {Array.<string>} tickLabels A text label for each major tick value. - */ -goog.ui.Gauge.prototype.setMajorTickLabels = function(tickLabels) { - this.majorTickLabels_ = tickLabels; - this.draw_(); -}; - - -/** - * Sets the top title of the gauge. - * The top title is displayed above the center. - * @param {string} text The top title text. - */ -goog.ui.Gauge.prototype.setTitleTop = function(text) { - this.titleTop_ = text; - this.draw_(); -}; - - -/** - * Sets the bottom title of the gauge. - * The top title is displayed below the center. - * @param {string} text The bottom title text. - */ -goog.ui.Gauge.prototype.setTitleBottom = function(text) { - this.titleBottom_ = text; - this.draw_(); -}; - - -/** - * Sets the font for displaying top and bottom titles. - * @param {goog.graphics.Font} font The font for titles. - */ -goog.ui.Gauge.prototype.setTitleFont = function(font) { - this.titleFont_ = font; - this.draw_(); -}; - - -/** - * Sets the font for displaying the formatted value. - * @param {goog.graphics.Font} font The font for displaying the value. - */ -goog.ui.Gauge.prototype.setValueFont = function(font) { - this.valueFont_ = font; - this.drawValue_(); -}; - - -/** - * Sets the color theme for drawing the gauge. - * @param {goog.ui.GaugeTheme} theme The color theme to use. - */ -goog.ui.Gauge.prototype.setTheme = function(theme) { - this.theme_ = theme; - this.draw_(); -}; - - -/** - * Set the background color for a range of values on the gauge. - * @param {number} fromValue The lower (start) value of the colored range. - * @param {number} toValue The higher (end) value of the colored range. - * @param {string} color The color name to paint the range with. For example - * 'red', '#ffcc00' or constants like goog.ui.Gauge.RED. - */ -goog.ui.Gauge.prototype.addBackgroundColor = function(fromValue, toValue, - color) { - this.rangeColors_.push( - new goog.ui.GaugeColoredRange(fromValue, toValue, color)); - this.draw_(); -}; - - -/** - * Creates the DOM representation of the graphics area. - */ -goog.ui.Gauge.prototype.createDom = function() { - this.setElementInternal(this.getDomHelper().createDom( - 'div', goog.getCssName('goog-gauge'), this.graphics_.getElement())); -}; - - -/** - * Clears the entire graphics area. - * @private - */ -goog.ui.Gauge.prototype.clear_ = function() { - this.graphics_.clear(); - this.needleGroup_ = null; -}; - - -/** - * Redraw the entire gauge. - * @private - */ -goog.ui.Gauge.prototype.draw_ = function() { - if (!this.isInDocument()) { - return; - } - - this.clear_(); - - var x, y; - var size = Math.min(this.width_, this.height_); - var r = Math.round(goog.ui.Gauge.FACTOR_RADIUS_FROM_SIZE * size); - var cx = this.width_ / 2; - var cy = this.height_ / 2; - - var theme = this.theme_; - if (!theme) { - // Lazy allocation of default theme, common to all instances - theme = goog.ui.Gauge.prototype.theme_ = new goog.ui.GaugeTheme(); - } - - // Draw main circle frame around gauge - var graphics = this.graphics_; - var stroke = this.theme_.getExternalBorderStroke(); - var fill = theme.getExternalBorderFill(cx, cy, r); - graphics.drawCircle(cx, cy, r, stroke, fill); - - r -= stroke.getWidth(); - r = Math.round(r * goog.ui.Gauge.FACTOR_MAIN_AREA); - stroke = theme.getInternalBorderStroke(); - fill = theme.getInternalBorderFill(cx, cy, r); - graphics.drawCircle(cx, cy, r, stroke, fill); - r -= stroke.getWidth() * 2; - - // Draw Background with external and internal borders - var rBackgroundInternal = r * goog.ui.Gauge.FACTOR_COLOR_RADIUS; - for (var i = 0; i < this.rangeColors_.length; i++) { - var rangeColor = this.rangeColors_[i]; - var fromValue = rangeColor.fromValue; - var toValue = rangeColor.toValue; - var path = new goog.graphics.Path(); - var fromAngle = this.valueToAngle_(fromValue); - var toAngle = this.valueToAngle_(toValue); - path.arc(cx, cy, r, r, fromAngle, toAngle - fromAngle, false); - path.arc(cx, cy, rBackgroundInternal, rBackgroundInternal, - toAngle, fromAngle - toAngle, true); - path.close(); - fill = new goog.graphics.SolidFill(rangeColor.backgroundColor); - graphics.drawPath(path, null, fill); - } - - // Draw titles - if (this.titleTop_ || this.titleBottom_) { - var font = this.titleFont_; - if (!font) { - // Lazy creation of font - var fontSize = - Math.round(r * goog.ui.Gauge.FACTOR_TITLE_FONT_SIZE); - font = new goog.graphics.Font( - fontSize, goog.ui.Gauge.TITLE_FONT_NAME); - this.titleFont_ = font; - } - fill = new goog.graphics.SolidFill(theme.getTitleColor()); - if (this.titleTop_) { - y = cy - Math.round(r * goog.ui.Gauge.FACTOR_TITLE_OFFSET); - graphics.drawTextOnLine(this.titleTop_, 0, y, this.width_, y, - 'center', font, null, fill); - } - if (this.titleBottom_) { - y = cy + Math.round(r * goog.ui.Gauge.FACTOR_TITLE_OFFSET); - graphics.drawTextOnLine(this.titleBottom_, 0, y, this.width_, y, - 'center', font, null, fill); - } - } - - // Draw tick marks - var majorTicks = this.majorTicks_; - var minorTicks = this.minorTicks_; - var rMajorTickInternal = r * goog.ui.Gauge.FACTOR_MAJOR_TICKS; - var rMinorTickInternal = r * goog.ui.Gauge.FACTOR_MINOR_TICKS; - var ticks = majorTicks * minorTicks; - var valueRange = this.maxValue_ - this.minValue_; - var tickValueSpan = valueRange / ticks; - var majorTicksPath = new goog.graphics.Path(); - var minorTicksPath = new goog.graphics.Path(); - - var tickLabelFill = new goog.graphics.SolidFill(theme.getTickLabelColor()); - var tickLabelFont = this.tickLabelFont_; - if (!tickLabelFont) { - tickLabelFont = new goog.graphics.Font( - Math.round(r * goog.ui.Gauge.FACTOR_TICK_LABEL_FONT_SIZE), - goog.ui.Gauge.TITLE_FONT_NAME); - } - var tickLabelFontSize = tickLabelFont.size; - - for (var i = 0; i <= ticks; i++) { - var angle = this.valueToAngle_(i * tickValueSpan + this.minValue_); - var isMajorTick = i % minorTicks == 0; - var rInternal = isMajorTick ? rMajorTickInternal : rMinorTickInternal; - var path = isMajorTick ? majorTicksPath : minorTicksPath; - x = cx + goog.math.angleDx(angle, rInternal); - y = cy + goog.math.angleDy(angle, rInternal); - path.moveTo(x, y); - x = cx + goog.math.angleDx(angle, r); - y = cy + goog.math.angleDy(angle, r); - path.lineTo(x, y); - - // Draw the tick's label for major ticks - if (isMajorTick && this.majorTickLabels_) { - var tickIndex = Math.floor(i / minorTicks); - var label = this.majorTickLabels_[tickIndex]; - if (label) { - x = cx + goog.math.angleDx(angle, rInternal - tickLabelFontSize / 2); - y = cy + goog.math.angleDy(angle, rInternal - tickLabelFontSize / 2); - var x1, x2; - var align = 'center'; - if (angle > 280 || angle < 90) { - align = 'right'; - x1 = 0; - x2 = x; - } else if (angle >= 90 && angle < 260) { - align = 'left'; - x1 = x; - x2 = this.width_; - } else { - // Values around top (angle 260-280) are centered around point - var dw = Math.min(x, this.width_ - x); // Nearest side border - x1 = x - dw; - x2 = x + dw; - y += Math.round(tickLabelFontSize / 4); // Movea bit down - } - graphics.drawTextOnLine(label, x1, y, x2, y, - align, tickLabelFont, null, tickLabelFill); - } - } - } - stroke = theme.getMinorTickStroke(); - graphics.drawPath(minorTicksPath, stroke, null); - stroke = theme.getMajorTickStroke(); - graphics.drawPath(majorTicksPath, stroke, null); - - // Draw the needle and the value label. Stop animation when doing - // full redraw and jump to the final value position. - this.stopAnimation_(); - this.valuePosition_ = this.valueToRangePosition_(this.value); - this.needleRadius_ = r; - this.drawValue_(); -}; - - -/** - * Handle animation events while the hand is moving. - * @param {goog.fx.AnimationEvent} e The event. - * @private - */ -goog.ui.Gauge.prototype.onAnimate_ = function(e) { - this.needleValuePosition_ = e.x; - this.drawValue_(); -}; - - -/** - * Handle animation events when hand move is complete. - * @private - */ -goog.ui.Gauge.prototype.onAnimateEnd_ = function() { - this.stopAnimation_(); -}; - - -/** - * Stop the current animation, if it is active. - * @private - */ -goog.ui.Gauge.prototype.stopAnimation_ = function() { - if (this.animation_) { - goog.events.removeAll(this.animation_); - this.animation_.stop(false); - this.animation_ = null; - } -}; - - -/** - * Convert a value to the position in the range. The returned position - * is a value between 0 and 1, where 0 indicates the lowest range value, - * 1 is the highest range, and any value in between is proportional - * to mapping the range to (0-1). - * If the value is not within the range, the returned value may be a bit - * lower than 0, or a bit higher than 1. This is done so that values out - * of range will be displayed just a bit outside of the gauge axis. - * @param {number} value The value to convert. - * @private - * @return {number} The range position. - */ -goog.ui.Gauge.prototype.valueToRangePosition_ = function(value) { - var valueRange = this.maxValue_ - this.minValue_; - var valuePct = (value - this.minValue_) / valueRange; // 0 to 1 - - // If value is out of range, trim it not to be too much out of range - valuePct = Math.max(valuePct, - -goog.ui.Gauge.MAX_EXCEED_POSITION_POSITION); - valuePct = Math.min(valuePct, - 1 + goog.ui.Gauge.MAX_EXCEED_POSITION_POSITION); - - return valuePct; -}; - - -/** - * Convert a value to an angle based on the value range and angle span - * @param {number} value The value. - * @return {number} The angle where this value is located on the round - * axis, based on the range and angle span. - * @private - */ -goog.ui.Gauge.prototype.valueToAngle_ = function(value) { - var valuePct = this.valueToRangePosition_(value); - return this.valuePositionToAngle_(valuePct); -}; - - -/** - * Convert a value-position (percent in the range) to an angle based on - * the angle span. A value-position is a value that has been proportinally - * adjusted to a value betwwen 0-1, proportionaly to the range. - * @param {number} valuePct The value. - * @return {number} The angle where this value is located on the round - * axis, based on the range and angle span. - * @private - */ -goog.ui.Gauge.prototype.valuePositionToAngle_ = function(valuePct) { - var startAngle = goog.math.standardAngle((360 - this.angleSpan_) / 2 + 90); - return this.angleSpan_ * valuePct + startAngle; -}; - - -/** - * Draw the elements that depend on the current value (the needle and - * the formatted value). This function is called whenever a value is changed - * or when the entire gauge is redrawn. - * @private - */ -goog.ui.Gauge.prototype.drawValue_ = function() { - if (!this.isInDocument()) { - return; - } - - var r = this.needleRadius_; - var graphics = this.graphics_; - var theme = this.theme_; - var cx = this.width_ / 2; - var cy = this.height_ / 2; - var angle = this.valuePositionToAngle_( - /** @type {number} */(this.needleValuePosition_)); - - // Compute the needle path - var frontRadius = - Math.round(r * goog.ui.Gauge.FACTOR_NEEDLE_FRONT); - var backRadius = - Math.round(r * goog.ui.Gauge.FACTOR_NEEDLE_BACK); - var frontDx = goog.math.angleDx(angle, frontRadius); - var frontDy = goog.math.angleDy(angle, frontRadius); - var backDx = goog.math.angleDx(angle, backRadius); - var backDy = goog.math.angleDy(angle, backRadius); - var angleRight = goog.math.standardAngle(angle + 90); - var distanceControlPointBase = r * goog.ui.Gauge.FACTOR_NEEDLE_WIDTH; - var controlPointMidDx = goog.math.angleDx(angleRight, - distanceControlPointBase); - var controlPointMidDy = goog.math.angleDy(angleRight, - distanceControlPointBase); - - var path = new goog.graphics.Path(); - path.moveTo(cx + frontDx, cy + frontDy); - path.curveTo(cx + controlPointMidDx, cy + controlPointMidDy, - cx - backDx + (controlPointMidDx / 2), - cy - backDy + (controlPointMidDy / 2), - cx - backDx, cy - backDy); - path.curveTo(cx - backDx - (controlPointMidDx / 2), - cy - backDy - (controlPointMidDy / 2), - cx - controlPointMidDx, cy - controlPointMidDy, - cx + frontDx, cy + frontDy); - - // Draw the needle hinge - var rh = Math.round(r * goog.ui.Gauge.FACTOR_NEEDLE_HINGE); - - // Clean previous needle - var needleGroup = this.needleGroup_; - if (needleGroup) { - needleGroup.clear(); - } else { - needleGroup = this.needleGroup_ = graphics.createGroup(); - } - - // Draw current formatted value if provided. - if (this.formattedValue_) { - var font = this.valueFont_; - if (!font) { - var fontSize = - Math.round(r * goog.ui.Gauge.FACTOR_VALUE_FONT_SIZE); - font = new goog.graphics.Font(fontSize, - goog.ui.Gauge.TITLE_FONT_NAME); - font.bold = true; - this.valueFont_ = font; - } - var fill = new goog.graphics.SolidFill(theme.getValueColor()); - var y = cy + Math.round(r * goog.ui.Gauge.FACTOR_VALUE_OFFSET); - graphics.drawTextOnLine(this.formattedValue_, 0, y, this.width_, y, - 'center', font, null, fill, needleGroup); - } - - // Draw the needle - var stroke = theme.getNeedleStroke(); - var fill = theme.getNeedleFill(cx, cy, rh); - graphics.drawPath(path, stroke, fill, needleGroup); - stroke = theme.getHingeStroke(); - fill = theme.getHingeFill(cx, cy, rh); - graphics.drawCircle(cx, cy, rh, stroke, fill, needleGroup); -}; - - -/** - * Redraws the entire gauge. - * Should be called after theme colors have been changed. - */ -goog.ui.Gauge.prototype.redraw = function() { - this.draw_(); -}; - - -/** - * Called when the component is added to the DOM. - * Overrides {@link goog.ui.Component#enterDocument}. - */ -goog.ui.Gauge.prototype.enterDocument = function() { - goog.ui.Gauge.superClass_.enterDocument.call(this); - - // set roles and states - var el = this.getElement(); - goog.dom.a11y.setRole(el, 'progressbar'); - goog.dom.a11y.setState(el, 'live', 'polite'); - goog.dom.a11y.setState(el, 'valuemin', this.minValue_); - goog.dom.a11y.setState(el, 'valuemax', this.maxValue_); - goog.dom.a11y.setState(el, 'valuenow', this.value_); - this.draw_(); -}; - - -/** - * Called when the component is removed from the DOM. - * Overrides {@link goog.ui.Component#exitDocument}. - */ -goog.ui.Gauge.prototype.exitDocument = function() { - goog.ui.Gauge.superClass_.exitDocument.call(this); - this.stopAnimation_(); -}; - - -/** @override */ -goog.ui.Gauge.prototype.disposeInternal = function() { - this.stopAnimation_(); - this.graphics_.dispose(); - delete this.graphics_; - delete this.needleGroup_; - delete this.theme_; - delete this.rangeColors_; - goog.ui.Gauge.superClass_.disposeInternal.call(this); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/gaugetheme.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/gaugetheme.js.svn-base deleted file mode 100644 index cc04f43..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/gaugetheme.js.svn-base +++ /dev/null @@ -1,169 +0,0 @@ -// 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 color theme used by a gauge (goog.ui.Guage). - */ - - -goog.provide('goog.ui.GaugeTheme'); - - -goog.require('goog.graphics.LinearGradient'); -goog.require('goog.graphics.SolidFill'); -goog.require('goog.graphics.Stroke'); - - - -/** - * A class for the default color theme for a Gauge. - * Users can extend this class to provide a custom color theme, and apply the - * custom color theme by calling {@link goog.ui.Gauge#setTheme}. - * @constructor - */ -goog.ui.GaugeTheme = function() { -}; - - -/** - * Returns the stroke for the external border of the gauge. - * @return {goog.graphics.Stroke} The stroke to use. - */ -goog.ui.GaugeTheme.prototype.getExternalBorderStroke = function() { - return new goog.graphics.Stroke(1, '#333333'); -}; - - -/** - * Returns the fill for the external border of the gauge. - * @param {number} cx X coordinate of the center of the gauge. - * @param {number} cy Y coordinate of the center of the gauge. - * @param {number} r Radius of the gauge. - * @return {goog.graphics.Fill} The fill to use. - */ -goog.ui.GaugeTheme.prototype.getExternalBorderFill = function(cx, cy, r) { - return new goog.graphics.LinearGradient(cx + r, cy - r, cx - r, cy + r, - '#f7f7f7', '#cccccc'); -}; - - -/** - * Returns the stroke for the internal border of the gauge. - * @return {goog.graphics.Stroke} The stroke to use. - */ -goog.ui.GaugeTheme.prototype.getInternalBorderStroke = function() { - return new goog.graphics.Stroke(2, '#e0e0e0'); -}; - - -/** - * Returns the fill for the internal border of the gauge. - * @param {number} cx X coordinate of the center of the gauge. - * @param {number} cy Y coordinate of the center of the gauge. - * @param {number} r Radius of the gauge. - * @return {goog.graphics.Fill} The fill to use. - */ -goog.ui.GaugeTheme.prototype.getInternalBorderFill = function(cx, cy, r) { - return new goog.graphics.SolidFill('#f7f7f7'); -}; - - -/** - * Returns the stroke for the major ticks of the gauge. - * @return {goog.graphics.Stroke} The stroke to use. - */ -goog.ui.GaugeTheme.prototype.getMajorTickStroke = function() { - return new goog.graphics.Stroke(2, '#333333'); -}; - - -/** - * Returns the stroke for the minor ticks of the gauge. - * @return {goog.graphics.Stroke} The stroke to use. - */ -goog.ui.GaugeTheme.prototype.getMinorTickStroke = function() { - return new goog.graphics.Stroke(1, '#666666'); -}; - - -/** - * Returns the stroke for the hinge at the center of the gauge. - * @return {goog.graphics.Stroke} The stroke to use. - */ -goog.ui.GaugeTheme.prototype.getHingeStroke = function() { - return new goog.graphics.Stroke(1, '#666666'); -}; - - -/** - * Returns the fill for the hinge at the center of the gauge. - * @param {number} cx X coordinate of the center of the gauge. - * @param {number} cy Y coordinate of the center of the gauge. - * @param {number} r Radius of the hinge. - * @return {goog.graphics.Fill} The fill to use. - */ -goog.ui.GaugeTheme.prototype.getHingeFill = function(cx, cy, r) { - return new goog.graphics.LinearGradient(cx + r, cy - r, cx - r, cy + r, - '#4684ee', '#3776d6'); -}; - - -/** - * Returns the stroke for the gauge needle. - * @return {goog.graphics.Stroke} The stroke to use. - */ -goog.ui.GaugeTheme.prototype.getNeedleStroke = function() { - return new goog.graphics.Stroke(1, '#c63310'); -}; - - -/** - * Returns the fill for the hinge at the center of the gauge. - * @param {number} cx X coordinate of the center of the gauge. - * @param {number} cy Y coordinate of the center of the gauge. - * @param {number} r Radius of the gauge. - * @return {goog.graphics.Fill} The fill to use. - */ -goog.ui.GaugeTheme.prototype.getNeedleFill = function(cx, cy, r) { - // Make needle a bit transparent so that text underneeth is still visible. - return new goog.graphics.SolidFill('#dc3912', 0.7); -}; - - -/** - * Returns the color for the gauge title. - * @return {string} The color to use. - */ -goog.ui.GaugeTheme.prototype.getTitleColor = function() { - return '#333333'; -}; - - -/** - * Returns the color for the gauge value. - * @return {string} The color to use. - */ -goog.ui.GaugeTheme.prototype.getValueColor = function() { - return 'black'; -}; - - -/** - * Returns the color for the labels (formatted values) of tick marks. - * @return {string} The color to use. - */ -goog.ui.GaugeTheme.prototype.getTickLabelColor = function() { - return '#333333'; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hovercard.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hovercard.js.svn-base deleted file mode 100644 index 04fcd85..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hovercard.js.svn-base +++ /dev/null @@ -1,450 +0,0 @@ -// 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 Show hovercards with a delay after the mouse moves over an - * element of a specified type and with a specific attribute. - * - * @see ../demos/hovercard.html - */ - -goog.provide('goog.ui.HoverCard'); -goog.provide('goog.ui.HoverCard.EventType'); -goog.provide('goog.ui.HoverCard.TriggerEvent'); - -goog.require('goog.dom'); -goog.require('goog.events'); -goog.require('goog.events.EventType'); -goog.require('goog.ui.AdvancedTooltip'); - - - -/** - * Create a hover card object. Hover cards extend tooltips in that they don't - * have to be manually attached to each element that can cause them to display. - * Instead, you can create a function that gets called when the mouse goes over - * any element on your page, and returns whether or not the hovercard should be - * shown for that element. - * - * Alternatively, you can define a map of tag names to the attribute name each - * tag should have for that tag to trigger the hover card. See example below. - * - * Hovercards can also be triggered manually by calling - * {@code triggerForElement}, shown without a delay by calling - * {@code showForElement}, or triggered over other elements by calling - * {@code attach}. For the latter two cases, the application is responsible - * for calling {@code detach} when finished. - * - * HoverCard objects fire a TRIGGER event when the mouse moves over an element - * that can trigger a hovercard, and BEFORE_SHOW when the hovercard is - * about to be shown. Clients can respond to these events and can prevent the - * hovercard from being triggered or shown. - * - * @param {Function|Object} isAnchor Function that returns true if a given - * element should trigger the hovercard. Alternatively, it can be a map of - * tag names to the attribute that the tag should have in order to trigger - * the hovercard, e.g., {A: 'href'} for all links. Tag names must be all - * upper case; attribute names are case insensitive. - * @param {boolean=} opt_checkDescendants Use false for a performance gain if - * you are sure that none of your triggering elements have child elements. - * Default is true. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper to use for - * creating and rendering the hovercard element. - * @param {Document=} opt_triggeringDocument Optional document to use in place - * of the one included in the DomHelper for finding triggering elements. - * Defaults to the document included in the DomHelper. - * @constructor - * @extends {goog.ui.AdvancedTooltip} - */ -goog.ui.HoverCard = function(isAnchor, opt_checkDescendants, opt_domHelper, - opt_triggeringDocument) { - goog.ui.AdvancedTooltip.call(this, null, null, opt_domHelper); - - if (goog.isFunction(isAnchor)) { - // Override default implementation of {@code isAnchor_}. - this.isAnchor_ = isAnchor; - } else { - - /** - * Map of tag names to attribute names that will trigger a hovercard. - * @type {Object} - * @private - */ - this.anchors_ = isAnchor; - } - - /** - * Whether anchors may have child elements. If true, then we need to check - * the parent chain of any mouse over event to see if any of those elements - * could be anchors. Default is true. - * @type {boolean} - * @private - */ - this.checkDescendants_ = opt_checkDescendants != false; - - /** - * Array of anchor elements that should be detached when we are no longer - * associated with them. - * @type {!Array.<Element>} - * @private - */ - this.tempAttachedAnchors_ = []; - - /** - * Document containing the triggering elements, to which we listen for - * mouseover events. - * @type {Document} - * @private - */ - this.document_ = opt_triggeringDocument || (opt_domHelper ? - opt_domHelper.getDocument() : goog.dom.getDocument()); - - goog.events.listen(this.document_, goog.events.EventType.MOUSEOVER, - this.handleTriggerMouseOver_, false, this); -}; -goog.inherits(goog.ui.HoverCard, goog.ui.AdvancedTooltip); - - -/** - * Enum for event type fired by HoverCard. - * @enum {string} - */ -goog.ui.HoverCard.EventType = { - TRIGGER: 'trigger', - CANCEL_TRIGGER: 'canceltrigger', - BEFORE_SHOW: goog.ui.PopupBase.EventType.BEFORE_SHOW, - SHOW: goog.ui.PopupBase.EventType.SHOW, - BEFORE_HIDE: goog.ui.PopupBase.EventType.BEFORE_HIDE, - HIDE: goog.ui.PopupBase.EventType.HIDE -}; - - -/** @override */ -goog.ui.HoverCard.prototype.disposeInternal = function() { - goog.ui.HoverCard.superClass_.disposeInternal.call(this); - - goog.events.unlisten(this.document_, goog.events.EventType.MOUSEOVER, - this.handleTriggerMouseOver_, false, this); -}; - - -/** - * Anchor of hovercard currently being shown. This may be different from - * {@code anchor} property if a second hovercard is triggered, when - * {@code anchor} becomes the second hovercard while {@code currentAnchor_} - * is still the old (but currently displayed) anchor. - * @type {Element} - * @private - */ -goog.ui.HoverCard.prototype.currentAnchor_; - - -/** - * Maximum number of levels to search up the dom when checking descendants. - * @type {number} - * @private - */ -goog.ui.HoverCard.prototype.maxSearchSteps_; - - -/** - * This function can be overridden by passing a function as the first parameter - * to the constructor. - * @param {Element} element Element to test. - * @return {boolean} Whether or not hovercard should be shown. - * @private - */ -goog.ui.HoverCard.prototype.isAnchor_ = function(element) { - return element.tagName in this.anchors_ && - !!element.getAttribute(this.anchors_[element.tagName]); -}; - - -/** - * If the user mouses over an element with the correct tag and attribute, then - * trigger the hovercard for that element. If anchors could have children, then - * we also need to check the parent chain of the given element. - * @param {goog.events.Event} e Mouse over event. - * @private - */ -goog.ui.HoverCard.prototype.handleTriggerMouseOver_ = function(e) { - var target = /** @type {Element} */ (e.target); - // Target might be null when hovering over disabled input textboxes in IE. - if (!target) { - return; - } - if (this.isAnchor_(target)) { - this.setPosition(null); - this.triggerForElement(target); - } else if (this.checkDescendants_) { - var trigger = goog.dom.getAncestor(target, - goog.bind(this.isAnchor_, this), - false, - this.maxSearchSteps_); - if (trigger) { - this.triggerForElement(/** @type {Element} */ (trigger)); - } - } -}; - - -/** - * Triggers the hovercard to show after a delay. - * @param {Element} anchorElement Element that is triggering the hovercard. - * @param {goog.positioning.AbstractPosition=} opt_pos Position to display - * hovercard. - * @param {Object=} opt_data Data to pass to the onTrigger event. - */ -goog.ui.HoverCard.prototype.triggerForElement = function(anchorElement, - opt_pos, opt_data) { - if (anchorElement == this.currentAnchor_) { - // Element is already showing, just make sure it doesn't hide. - this.clearHideTimer(); - return; - } - if (anchorElement == this.anchor) { - // Hovercard is pending, no need to retrigger. - return; - } - - // If a previous hovercard was being triggered, cancel it. - this.maybeCancelTrigger_(); - - // Create a new event for this trigger - var triggerEvent = new goog.ui.HoverCard.TriggerEvent( - goog.ui.HoverCard.EventType.TRIGGER, this, anchorElement, opt_data); - - if (!this.getElements().contains(anchorElement)) { - this.attach(anchorElement); - this.tempAttachedAnchors_.push(anchorElement); - } - this.anchor = anchorElement; - if (!this.onTrigger(triggerEvent)) { - this.onCancelTrigger(); - return; - } - var pos = opt_pos || this.position_; - this.startShowTimer(anchorElement, - /** @type {goog.positioning.AbstractPosition} */ (pos)); -}; - - -/** - * Sets the current anchor element at the time that the hovercard is shown. - * @param {Element} anchor New current anchor element, or null if there is - * no current anchor. - * @private - */ -goog.ui.HoverCard.prototype.setCurrentAnchor_ = function(anchor) { - if (anchor != this.currentAnchor_) { - this.detachTempAnchor_(this.currentAnchor_); - } - this.currentAnchor_ = anchor; -}; - - -/** - * If given anchor is in the list of temporarily attached anchors, then - * detach and remove from the list. - * @param {Element|undefined} anchor Anchor element that we may want to detach - * from. - * @private - */ -goog.ui.HoverCard.prototype.detachTempAnchor_ = function(anchor) { - var pos = goog.array.indexOf(this.tempAttachedAnchors_, anchor); - if (pos != -1) { - this.detach(anchor); - this.tempAttachedAnchors_.splice(pos, 1); - } -}; - - -/** - * Called when an element triggers the hovercard. This will return false - * if an event handler sets preventDefault to true, which will prevent - * the hovercard from being shown. - * @param {!goog.ui.HoverCard.TriggerEvent} triggerEvent Event object to use - * for trigger event. - * @return {boolean} Whether hovercard should be shown or cancelled. - * @protected - */ -goog.ui.HoverCard.prototype.onTrigger = function(triggerEvent) { - return this.dispatchEvent(triggerEvent); -}; - - -/** - * Abort pending hovercard showing, if any. - */ -goog.ui.HoverCard.prototype.cancelTrigger = function() { - this.clearShowTimer(); - this.onCancelTrigger(); -}; - - -/** - * If hovercard is in the process of being triggered, then cancel it. - * @private - */ -goog.ui.HoverCard.prototype.maybeCancelTrigger_ = function() { - if (this.getState() == goog.ui.Tooltip.State.WAITING_TO_SHOW || - this.getState() == goog.ui.Tooltip.State.UPDATING) { - this.cancelTrigger(); - } -}; - - -/** - * This method gets called when we detect that a trigger event will not lead - * to the hovercard being shown. - * @protected - */ -goog.ui.HoverCard.prototype.onCancelTrigger = function() { - var event = new goog.ui.HoverCard.TriggerEvent( - goog.ui.HoverCard.EventType.CANCEL_TRIGGER, this, this.anchor || null); - this.dispatchEvent(event); - this.detachTempAnchor_(this.anchor); - delete this.anchor; -}; - - -/** - * Gets the DOM element that triggered the current hovercard. Note that in - * the TRIGGER or CANCEL_TRIGGER events, the current hovercard's anchor may not - * be the one that caused the event, so use the event's anchor property instead. - * @return {Element} Object that caused the currently displayed hovercard (or - * pending hovercard if none is displayed) to be triggered. - */ -goog.ui.HoverCard.prototype.getAnchorElement = function() { - // this.currentAnchor_ is only set if the hovercard is showing. If it isn't - // showing yet, then use this.anchor as the pending anchor. - return /** @type {Element} */ (this.currentAnchor_ || this.anchor); -}; - - -/** - * Make sure we detach from temp anchor when we are done displaying hovercard. - * @protected - * @suppress {underscore} - * @override - */ -goog.ui.HoverCard.prototype.onHide_ = function() { - goog.ui.HoverCard.superClass_.onHide_.call(this); - this.setCurrentAnchor_(null); -}; - - -/** - * This mouse over event is only received if the anchor is already attached. - * If it was attached manually, then it may need to be triggered. - * @param {goog.events.BrowserEvent} event Mouse over event. - * @protected - */ -goog.ui.HoverCard.prototype.handleMouseOver = function(event) { - // If this is a child of a triggering element, find the triggering element. - var trigger = this.getAnchorFromElement( - /** @type {Element} */ (event.target)); - - // If we moused over an element different from the one currently being - // triggered (if any), then trigger this new element. - if (trigger && trigger != this.anchor) { - this.triggerForElement(trigger); - return; - } - - goog.ui.HoverCard.superClass_.handleMouseOver.call(this, event); -}; - - -/** - * If the mouse moves out of the trigger while we're being triggered, then - * cancel it. - * @param {goog.events.BrowserEvent} event Mouse out or blur event. - * @protected - */ -goog.ui.HoverCard.prototype.handleMouseOutAndBlur = function(event) { - // Get ready to see if a trigger should be cancelled. - var anchor = this.anchor; - var state = this.getState(); - goog.ui.HoverCard.superClass_.handleMouseOutAndBlur.call(this, event); - if (state != this.getState() && - (state == goog.ui.Tooltip.State.WAITING_TO_SHOW || - state == goog.ui.Tooltip.State.UPDATING)) { - // Tooltip's handleMouseOutAndBlur method sets anchor to null. Reset - // so that the cancel trigger event will have the right data, and so that - // it will be properly detached. - this.anchor = anchor; - this.onCancelTrigger(); // This will remove and detach the anchor. - } -}; - - -/** - * Called by timer from mouse over handler. If this is called and the hovercard - * is not shown for whatever reason, then send a cancel trigger event. - * @param {Element} el Element to show tooltip for. - * @param {goog.positioning.AbstractPosition=} opt_pos Position to display popup - * at. - */ -goog.ui.HoverCard.prototype.maybeShow = function(el, opt_pos) { - goog.ui.HoverCard.superClass_.maybeShow.call(this, el, opt_pos); - - if (!this.isVisible()) { - this.cancelTrigger(); - } else { - this.setCurrentAnchor_(el); - } -}; - - -/** - * Sets the max number of levels to search up the dom if checking descendants. - * @param {number} maxSearchSteps Maximum number of levels to search up the - * dom if checking descendants. - */ -goog.ui.HoverCard.prototype.setMaxSearchSteps = function(maxSearchSteps) { - if (!maxSearchSteps) { - this.checkDescendants_ = false; - } else if (this.checkDescendants_) { - this.maxSearchSteps_ = maxSearchSteps; - } -}; - - - -/** - * Create a trigger event for specified anchor and optional data. - * @param {goog.ui.HoverCard.EventType} type Event type. - * @param {goog.ui.HoverCard} target Hovercard that is triggering the event. - * @param {Element} anchor Element that triggered event. - * @param {Object=} opt_data Optional data to be available in the TRIGGER event. - * @constructor - * @extends {goog.events.Event} - */ -goog.ui.HoverCard.TriggerEvent = function(type, target, anchor, opt_data) { - goog.events.Event.call(this, type, target); - - /** - * Element that triggered the hovercard event. - * @type {Element} - */ - this.anchor = anchor; - - /** - * Optional data to be passed to the listener. - * @type {Object|undefined} - */ - this.data = opt_data; -}; -goog.inherits(goog.ui.HoverCard.TriggerEvent, goog.events.Event); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hovercard_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hovercard_test.html.svn-base deleted file mode 100644 index 27edee5..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hovercard_test.html.svn-base +++ /dev/null @@ -1,343 +0,0 @@ -<html> -<!-- -Copyright 2010 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> - -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.HoverCard</title> - - <style type="text/css"> - .goog-tooltip { - background: infobackground; - color: infotext; - border: 1px solid infotext; - padding: 1px; - font:menu; - } - </style> - - <script type="text/javascript" src="../base.js"></script> - <script type="text/javascript"> - goog.require('goog.ui.HoverCard'); - goog.require('goog.dom'); - goog.require('goog.testing.MockClock'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - </script> - - </head> - <body> - <p id="notpopup">Content</p> - <span id="john" email="john@gmail.com">Span for John that can trigger a - hovercard.</span><br> - <span id="jane">Span for Jane that doesn't trigger a hovercard (no email - attribute)</span><br> - <span id="james" email="james@gmail.com">Span for James that can trigger a - hovercard<span id="child">Child of james</span></span><br> - <div id="bill" email="bill@gmail.com">Doesn't trigger for Bill because - it's a div</div> - <script type="text/javascript"> - - var timer = new goog.testing.MockClock(); - var card; - - // Variables for mocks - var triggeredElement; - var cancelledElement; - var showDelay; - var shownCard; - var hideDelay; - - // spans - var john = goog.dom.getElement('john'); - var jane = goog.dom.getElement('jane'); - var james = goog.dom.getElement('james'); - var bill = goog.dom.getElement('bill'); - var child = goog.dom.getElement('child'); - - // Inactive - var elsewhere; - var offAnchor; - - function setUp() { - timer.install(); - triggeredElement = null; - cancelledElement = null; - showDelay = null; - shownCard = null; - hideDelay = null; - elsewhere = goog.dom.getElement('notpopup'); - offAnchor = new goog.math.Coordinate(1, 1); - } - - function initCard(opt_isAnchor, opt_checkChildren, opt_maxSearchSteps) { - var isAnchor = opt_isAnchor || {SPAN: 'email'}; - card = new goog.ui.HoverCard(isAnchor, opt_checkChildren); - card.setText('Test hovercard'); - - if (opt_maxSearchSteps != null) { - card.setMaxSearchSteps(opt_maxSearchSteps); - } - - goog.events.listen(card, goog.ui.HoverCard.EventType.TRIGGER, onTrigger); - goog.events.listen(card, goog.ui.HoverCard.EventType.CANCEL_TRIGGER, - onCancel); - goog.events.listen(card, goog.ui.HoverCard.EventType.BEFORE_SHOW, - onBeforeShow); - - // This gets around the problem where AdvancedToolTip thinks it's - // receiving a ghost event because cursor position hasn't moved off of - // (0, 0). - card.cursorPosition = new goog.math.Coordinate(1, 1); - } - - // Event handlers - function onTrigger(event) { - triggeredElement = event.anchor; - if (showDelay) { - card.setShowDelayMs(showDelay); - } - return true; - } - - function onCancel(event) { - cancelledElement = event.anchor; - } - - function onBeforeShow() { - shownCard = card.getAnchorElement(); - if (hideDelay) { - card.setHideDelayMs(hideDelay); - } - return true; - } - - function tearDown() { - card.dispose(); - timer.uninstall(); - } - - /** - * Verify that hovercard displays and goes away under normal circumstances. - */ - function testTrigger() { - initCard(); - - // Mouse over correct element fires trigger - showDelay = 500; - goog.testing.events.fireMouseOverEvent(john, elsewhere); - assertEquals('Hovercard should have triggered', john, - triggeredElement); - - // Show card after delay - timer.tick(showDelay - 1); - assertNull('Card should not have shown', shownCard); - assertFalse(card.isVisible()); - hideDelay = 5000; - timer.tick(1); - assertEquals('Card should have shown', john, shownCard); - assertTrue(card.isVisible()); - - // Mouse out leads to hide delay - goog.testing.events.fireMouseOutEvent(john, elsewhere); - goog.testing.events.fireMouseMoveEvent(document, offAnchor); - timer.tick(hideDelay - 1); - assertTrue('Card should still be visible', card.isVisible()); - timer.tick(10); - assertFalse('Card should be hidden', card.isVisible()); - } - - /** - * Verify that CANCEL_TRIGGER event occurs when mouse goes out of - * triggering element before hovercard is shown. - */ - function testOnCancel() { - initCard(); - - showDelay = 500; - goog.testing.events.fireMouseOverEvent(john, elsewhere); - timer.tick(showDelay - 1); - goog.testing.events.fireMouseOutEvent(john, elsewhere); - goog.testing.events.fireMouseMoveEvent(document, offAnchor); - timer.tick(10); - assertFalse('Card should be hidden', card.isVisible()); - assertEquals('Should have cancelled trigger', john, cancelledElement); - } - - /** - * Verify that mousing over non-triggering elements don't interfere. - */ - function testMouseOverNonTrigger() { - initCard(); - - // Mouse over correct element fires trigger - showDelay = 500; - goog.testing.events.fireMouseOverEvent(john, elsewhere); - timer.tick(showDelay); - - // Mouse over and out other element does nothing - triggeredElement = null; - goog.testing.events.fireMouseOverEvent(jane, elsewhere); - timer.tick(showDelay + 1); - assertNull(triggeredElement); - } - - /** - * Verify that a mouse over event with no target will not break - * hover card. - */ - function testMouseOverNoTarget() { - initCard(); - card.handleTriggerMouseOver_(new goog.testing.events.Event()); - } - - /** - * Verify that mousing over a second trigger before the first one shows - * will correctly cancel the first and show the second. - */ - function testMultipleTriggers() { - initCard(); - - // Test second trigger when first one still pending - showDelay = 500; - hideDelay = 1000; - goog.testing.events.fireMouseOverEvent(john, elsewhere); - timer.tick(250); - goog.testing.events.fireMouseOutEvent(john, james); - goog.testing.events.fireMouseOverEvent(james, john); - // First trigger should cancel because it isn't showing yet - assertEquals('Should cancel first trigger', john, cancelledElement); - timer.tick(300); - assertFalse(card.isVisible()); - timer.tick(250); - assertEquals('Should show second card', james, shownCard); - assertTrue(card.isVisible()); - - goog.testing.events.fireMouseOutEvent(james, john); - goog.testing.events.fireMouseOverEvent(john, james); - assertEquals('Should still show second card', james, - card.getAnchorElement()); - assertTrue(card.isVisible()); - - shownCard = null; - timer.tick(501); - assertEquals('Should show first card again', john, shownCard); - assertTrue(card.isVisible()); - - // Test that cancelling while another is showing gives correct cancel - // information - cancelledElement = null; - goog.testing.events.fireMouseOutEvent(john, james); - goog.testing.events.fireMouseOverEvent(james, john); - goog.testing.events.fireMouseOutEvent(james, elsewhere); - assertEquals('Should cancel second card', james, cancelledElement); - } - - /** - * Verify manual triggering. - */ - function testManualTrigger() { - initCard(); - - // Doesn't normally trigger for div tag - showDelay = 500; - goog.testing.events.fireMouseOverEvent(bill, elsewhere); - timer.tick(showDelay); - assertFalse(card.isVisible()); - - // Manually trigger element - card.triggerForElement(bill); - hideDelay = 600; - timer.tick(showDelay); - assertTrue(card.isVisible()); - goog.testing.events.fireMouseOutEvent(bill, elsewhere); - goog.testing.events.fireMouseMoveEvent(document, offAnchor); - timer.tick(hideDelay); - assertFalse(card.isVisible()); - } - - /** - * Verify creating with isAnchor function. - */ - function testIsAnchor() { - // Initialize card so only bill triggers it. - initCard(function(element) { - return element == bill; - }); - - showDelay = 500; - goog.testing.events.fireMouseOverEvent(bill, elsewhere); - timer.tick(showDelay); - assertTrue('Should trigger card', card.isVisible()); - - hideDelay = 300; - goog.testing.events.fireMouseOutEvent(bill, elsewhere); - goog.testing.events.fireMouseMoveEvent(document, offAnchor); - timer.tick(hideDelay); - assertFalse(card.isVisible()); - - goog.testing.events.fireMouseOverEvent(john, elsewhere); - timer.tick(showDelay); - assertFalse('Should not trigger card', card.isVisible()); - } - - /** - * Verify mouse over child of anchor triggers hovercard. - */ - function testAnchorWithChildren() { - initCard(); - - showDelay = 500; - goog.testing.events.fireMouseOverEvent(james, elsewhere); - timer.tick(250); - - // Moving from an anchor to a child of that anchor shouldn't cancel - // or retrigger. - var childBounds = goog.style.getBounds(child); - var inChild = new goog.math.Coordinate(childBounds.left + 1, - childBounds.top + 1); - goog.testing.events.fireMouseOutEvent(james, child); - goog.testing.events.fireMouseMoveEvent(child, inChild); - assertNull("Shouldn't cancel trigger", cancelledElement); - triggeredElement = null; - goog.testing.events.fireMouseOverEvent(child, james); - assertNull("Shouldn't retrigger card", triggeredElement); - timer.tick(250); - assertTrue('Card should show with original delay', card.isVisible()); - - hideDelay = 300; - goog.testing.events.fireMouseOutEvent(child, elsewhere); - goog.testing.events.fireMouseMoveEvent(child, offAnchor); - timer.tick(hideDelay); - assertFalse(card.isVisible()); - - goog.testing.events.fireMouseOverEvent(child, elsewhere); - timer.tick(showDelay); - assertTrue('Mouse over child should trigger card', card.isVisible()); - } - - function testNoTriggerWithMaxSearchSteps() { - initCard(undefined, true, 0); - - showDelay = 500; - goog.testing.events.fireMouseOverEvent(child, elsewhere); - timer.tick(showDelay); - assertFalse('Should not trigger card', card.isVisible()); - } - - function testTriggerWithMaxSearchSteps() { - initCard(undefined, true, 2); - - showDelay = 500; - goog.testing.events.fireMouseOverEvent(child, elsewhere); - timer.tick(showDelay); - assertTrue('Should trigger card', card.isVisible()); - } - - </script> - </body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hsvapalette.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hsvapalette.js.svn-base deleted file mode 100644 index 86dd70b..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hsvapalette.js.svn-base +++ /dev/null @@ -1,308 +0,0 @@ -// 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 HSVA (hue/saturation/value/alpha) color palette/picker - * implementation. - * Without the styles from the demo css file, only a hex color label and input - * field show up. - * - * @see ../demos/hsvapalette.html - */ - -goog.provide('goog.ui.HsvaPalette'); - -goog.require('goog.array'); -goog.require('goog.color'); -goog.require('goog.color.alpha'); -goog.require('goog.events.EventType'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.HsvPalette'); - - - -/** - * Creates an HSVA palette. Allows a user to select the hue, saturation, - * value/brightness and alpha/opacity. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @param {string=} opt_color Optional initial color, without alpha (default is - * red). - * @param {number=} opt_alpha Optional initial alpha (default is 1). - * @param {string=} opt_class Optional base for creating classnames (default is - * 'goog-hsva-palette'). - * @extends {goog.ui.HsvPalette} - * @constructor - */ -goog.ui.HsvaPalette = function(opt_domHelper, opt_color, opt_alpha, opt_class) { - goog.ui.HsvPalette.call(this, opt_domHelper, opt_color, opt_class); - - /** - * Alpha transparency of the currently selected color, in [0, 1]. When - * undefined, the palette will behave as a non-transparent HSV palette, - * assuming full opacity. - * @type {number} - * @private - */ - this.alpha_ = goog.isDef(opt_alpha) ? opt_alpha : 1; - - /** - * The base class name for the component. - * @type {string} - * @private - */ - this.class_ = opt_class || goog.getCssName('goog-hsva-palette'); - - /** - * The document which is being listened to. - * type {HTMLDocument} - * @private - */ - this.document_ = opt_domHelper ? opt_domHelper.getDocument() : - goog.dom.getDomHelper().getDocument(); -}; -goog.inherits(goog.ui.HsvaPalette, goog.ui.HsvPalette); - - -/** - * DOM element representing the alpha background image. - * @type {Element} - * @private - */ -goog.ui.HsvaPalette.prototype.aImageEl_; - - -/** - * DOM element representing the alpha handle. - * @type {Element} - * @private - */ -goog.ui.HsvaPalette.prototype.aHandleEl_; - - -/** - * DOM element representing the swatch backdrop image. - * @type {Element} - * @private - */ -goog.ui.HsvaPalette.prototype.swatchBackdropEl_; - - -/** @override */ -goog.ui.HsvaPalette.prototype.getAlpha = function() { - return this.alpha_; -}; - - -/** - * Sets which color is selected and update the UI. The passed color should be - * in #rrggbb format. The alpha value will be set to 1. - * @param {number} alpha The selected alpha value, in [0, 1]. - */ -goog.ui.HsvaPalette.prototype.setAlpha = function(alpha) { - this.setColorAlphaHelper_(this.color_, alpha); -}; - - -/** - * Sets which color is selected and update the UI. The passed color should be - * in #rrggbb format. The alpha value will be set to 1. - * @param {string} color The selected color. - */ -goog.ui.HsvaPalette.prototype.setColor = function(color) { - this.setColorAlphaHelper_(color, 1); -}; - - -/** - * Gets the color that is currently selected in this color picker, in #rrggbbaa - * format. - * @return {string} The string of the selected color with alpha. - */ -goog.ui.HsvaPalette.prototype.getColorRgbaHex = function() { - var alphaHex = Math.floor(this.alpha_ * 255).toString(16); - return this.color_ + (alphaHex.length == 1 ? '0' + alphaHex : alphaHex); -}; - - -/** - * Sets which color is selected and update the UI. The passed color should be - * in #rrggbbaa format. The alpha value will be set to 1. - * @param {string} color The selected color with alpha. - */ -goog.ui.HsvaPalette.prototype.setColorRgbaHex = function(color) { - var parsed = goog.ui.HsvaPalette.parseColorRgbaHex_(color); - this.setColorAlphaHelper_(parsed[0], parsed[1]); -}; - - -/** - * Sets which color and alpha value are selected and update the UI. The passed - * color should be in #rrggbb format. - * @param {string} color The selected color in #rrggbb format. - * @param {number} alpha The selected alpha value, in [0, 1]. - * @private - */ -goog.ui.HsvaPalette.prototype.setColorAlphaHelper_ = function(color, alpha) { - var colorChange = this.color_ != color; - var alphaChange = this.alpha_ != alpha; - this.alpha_ = alpha; - this.color_ = color; - if (colorChange) { - // This is to prevent multiple event dispatches. - goog.ui.HsvaPalette.superClass_.setColor_.call(this, color); - } - if (colorChange || alphaChange) { - this.updateUi_(); - this.dispatchEvent(goog.ui.Component.EventType.ACTION); - } -}; - - -/** @override */ -goog.ui.HsvaPalette.prototype.createDom = function() { - goog.ui.HsvaPalette.superClass_.createDom.call(this); - - var dom = this.getDomHelper(); - this.aImageEl_ = dom.createDom( - goog.dom.TagName.DIV, goog.getCssName(this.class_, 'a-image')); - this.aHandleEl_ = dom.createDom( - goog.dom.TagName.DIV, goog.getCssName(this.class_, 'a-handle')); - this.swatchBackdropEl_ = dom.createDom( - goog.dom.TagName.DIV, goog.getCssName(this.class_, 'swatch-backdrop')); - dom.appendChild(this.element_, this.aImageEl_); - dom.appendChild(this.element_, this.aHandleEl_); - dom.appendChild(this.element_, this.swatchBackdropEl_); -}; - - -/** @override */ -goog.ui.HsvaPalette.prototype.disposeInternal = function() { - goog.ui.HsvaPalette.superClass_.disposeInternal.call(this); - - delete this.aImageEl_; - delete this.aHandleEl_; - delete this.swatchBackdropEl_; -}; - - -/** - * Updates the position, opacity, and styles for the UI representation of the - * palette. - * @private - */ -goog.ui.HsvaPalette.prototype.updateUi_ = function() { - goog.ui.HsvaPalette.superClass_.updateUi_.call(this); - if (this.isInDocument()) { - var a = this.alpha_ * 255; - var top = this.aImageEl_.offsetTop - - Math.floor(this.aHandleEl_.offsetHeight / 2) + - this.aImageEl_.offsetHeight * ((255 - a) / 255); - this.aHandleEl_.style.top = top + 'px'; - this.aImageEl_.style.backgroundColor = this.color_; - goog.style.setOpacity(this.swatchEl_, a / 255); - } -}; - - -/** @override */ -goog.ui.HsvaPalette.prototype.updateInput = function() { - if (!goog.array.equals([this.color_, this.alpha_], - goog.ui.HsvaPalette.parseUserInput_(this.inputEl_.value))) { - this.inputEl_.value = this.getColorRgbaHex(); - } -}; - - -/** - * Handles mousedown events on palette UI elements. - * @param {goog.events.BrowserEvent} e Event object. - * @private - */ -goog.ui.HsvaPalette.prototype.handleMouseDown_ = function(e) { - goog.ui.HsvaPalette.superClass_.handleMouseDown_.call(this, e); - if (e.target == this.aImageEl_ || e.target == this.aHandleEl_) { - // Setup value change listeners - var b = goog.style.getBounds(this.vImageEl_); - this.handleMouseMoveA_(b, e); - this.mouseMoveListener_ = goog.events.listen(this.document_, - goog.events.EventType.MOUSEMOVE, - goog.bind(this.handleMouseMoveA_, this, b)); - this.mouseUpListener_ = goog.events.listen(this.document_, - goog.events.EventType.MOUSEUP, this.handleMouseUp_, false, this); - } -}; - - -/** - * Handles mousemove events on the document once a drag operation on the alpha - * slider has started. - * @param {goog.math.Rect} b Boundaries of the value slider object at the start - * of the drag operation. - * @param {goog.events.Event} e Event object. - * @private - */ -goog.ui.HsvaPalette.prototype.handleMouseMoveA_ = function(b, e) { - e.preventDefault(); - var vportPos = this.getDomHelper().getDocumentScroll(); - var newA = (b.top + b.height - Math.min( - Math.max(vportPos.y + e.clientY, b.top), - b.top + b.height)) / b.height; - this.setAlpha(newA); -}; - - -/** - * Handles input events on the hex value input field. - * @param {goog.events.Event} e Event object. - * @private - */ -goog.ui.HsvaPalette.prototype.handleInput_ = function(e) { - var parsed = goog.ui.HsvaPalette.parseUserInput_(this.inputEl_.value); - if (parsed) { - this.setColorAlphaHelper_(parsed[0], parsed[1]); - } -}; - - -/** - * Parses an #rrggbb or #rrggbbaa color string. - * @param {string} value User-entered color value. - * @return {Array} A two element array [color, alpha], where color is #rrggbb - * and alpha is in [0, 1]. Null if the argument was invalid. - * @private - */ -goog.ui.HsvaPalette.parseUserInput_ = function(value) { - if (/^#[0-9a-f]{8}$/i.test(value)) { - return goog.ui.HsvaPalette.parseColorRgbaHex_(value); - } else if (/^#[0-9a-f]{6}$/i.test(value)) { - return [value, 1]; - } - return null; -}; - - -/** - * Parses a #rrggbbaa color string. - * @param {string} color The color and alpha in #rrggbbaa format. - * @return {Array} A two element array [color, alpha], where color is #rrggbb - * and alpha is in [0, 1]. - * @private - */ -goog.ui.HsvaPalette.parseColorRgbaHex_ = function(color) { - var hex = goog.color.alpha.parse(color).hex; - return [ - goog.color.alpha.extractHexColor(hex), - parseInt(goog.color.alpha.extractAlpha(hex), 16) / 255 - ]; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hsvapalette_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hsvapalette_test.html.svn-base deleted file mode 100644 index 8a7eb9f..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hsvapalette_test.html.svn-base +++ /dev/null @@ -1,152 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>HsvaPalette Unit Tests</title> - <script src="../base.js"></script> - <script src="../deps.js"></script> - <script> - goog.require('goog.color.alpha'); - goog.require('goog.events'); - goog.require('goog.math.Rect'); - goog.require('goog.style'); - goog.require('goog.testing.PropertyReplacer'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.HsvaPalette'); - goog.require('goog.userAgent'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var samplePalette; - var eventWasFired = false; - var stubs = new goog.testing.PropertyReplacer(); - - function setUp() { - samplePalette = new goog.ui.HsvaPalette(); - } - - function tearDown() { - samplePalette.dispose(); - stubs.reset(); - } - - function testZeroAlpha() { - var palette = new goog.ui.HsvaPalette(null, undefined, 0); - assertEquals(0, palette.getAlpha()); - } - - function testOptionalInitialColor() { - var alpha = 0.5; - var color = '#0000ff'; - var palette = new goog.ui.HsvaPalette(null, color, alpha); - assertEquals(color, palette.getColor()); - assertEquals(alpha, palette.getAlpha()); - } - - function testCustomClassName() { - var customClassName = 'custom-plouf'; - var customClassPalette = - new goog.ui.HsvaPalette(null, null, null, customClassName); - customClassPalette.createDom(); - assertTrue(goog.dom.classes.has(customClassPalette.getElement(), - customClassName)); - } - - function testSetColor() { - var color = '#abcdef01'; - samplePalette.setColorRgbaHex(color); - assertEquals(color, - goog.color.alpha.parse(samplePalette.getColorRgbaHex()).hex); - } - - function testRender() { - samplePalette.render(document.getElementById('sandbox')); - - assertTrue(samplePalette.isInDocument()); - - var elem = samplePalette.getElement(); - assertNotNull(elem); - assertEquals(goog.dom.TagName.DIV, elem.tagName); - - if (goog.userAgent.IE && !goog.userAgent.isVersion('7')) { - assertSameElements('On IE6, the noalpha class must be present', - ['goog-hsva-palette', 'goog-hsva-palette-noalpha'], - goog.dom.classes.get(elem)); - } else { - assertEquals('The noalpha class must not be present', - 'goog-hsva-palette', elem.className); - } - } - - function testNoLeftOverListenersAfterDispose() { - var initialListenerCount = goog.events.getTotalListenerCount(); - samplePalette.render(document.getElementById('sandbox')); - samplePalette.dispose(); - assertEquals(initialListenerCount, goog.events.getTotalListenerCount()); - } - - function testInputColor() { - samplePalette.render(document.getElementById('sandbox')); - var color = '#00112233'; - samplePalette.inputEl_.value = color; - samplePalette.handleInput_(null); - assertEquals(color, - goog.color.alpha.parse(samplePalette.getColorRgbaHex()).hex); - } - - function testHandleMouseMoveAlpha() { - samplePalette.render(document.getElementById('sandbox')); - stubs.set(goog.dom, 'getPageScroll', function() { - return new goog.math.Coordinate(0, 0); - }); - - // Lowering the opacity of a dark, opaque red should yield a - // more transparent red. - samplePalette.setColorRgbaHex('#630c0000'); - goog.style.setPageOffset(samplePalette.aImageEl_, 0, 0); - goog.style.setSize(samplePalette.aImageEl_, 10, 100); - var boundaries = goog.style.getBounds(samplePalette.aImageEl_); - - var event = new goog.events.Event(); - event.clientY = boundaries.top; - samplePalette.handleMouseMoveA_(boundaries, event); - - assertEquals('#630c00ff', samplePalette.getColorRgbaHex()); - } - - function testSwatchOpacity() { - samplePalette.render(document.getElementById('sandbox')); - - samplePalette.setAlpha(1); - assertEquals(1, goog.style.getOpacity(samplePalette.swatchEl_)); - - samplePalette.setAlpha(0x99 / 0xff); - assertEquals(0.6, goog.style.getOpacity(samplePalette.swatchEl_)); - - samplePalette.setAlpha(0); - assertEquals(0, goog.style.getOpacity(samplePalette.swatchEl_)); - } - - function testNoTransparencyBehavior() { - samplePalette.render(document.getElementById('sandbox')); - - samplePalette.inputEl_.value = '#abcdef22'; - samplePalette.handleInput_(null); - samplePalette.inputEl_.value = '#abcdef'; - samplePalette.handleInput_(null); - assertEquals(1, goog.style.getOpacity(samplePalette.swatchEl_)); - } - - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hsvpalette.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hsvpalette.js.svn-base deleted file mode 100644 index 6afb85a..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hsvpalette.js.svn-base +++ /dev/null @@ -1,472 +0,0 @@ -// 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 HSV (hue/saturation/value) color palette/picker - * implementation. Inspired by examples like - * http://johndyer.name/lab/colorpicker/ and the author's initial work. This - * control allows for more control in picking colors than a simple swatch-based - * palette. Without the styles from the demo css file, only a hex color label - * and input field show up. - * - * @author arv@google.com (Erik Arvidsson) - * @author smcbride@google.com (Sean McBride) - * @author manucornet@google.com (Manu Cornet) - * @see ../demos/hsvpalette.html - */ - -goog.provide('goog.ui.HsvPalette'); - -goog.require('goog.color'); -goog.require('goog.dom'); -goog.require('goog.dom.DomHelper'); -goog.require('goog.events'); -goog.require('goog.events.Event'); -goog.require('goog.events.EventType'); -goog.require('goog.events.InputHandler'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.userAgent'); - - - -/** - * Creates an HSV palette. Allows a user to select the hue, saturation and - * value/brightness. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @param {string=} opt_color Optional initial color (default is red). - * @param {string=} opt_class Optional base for creating classnames (default is - * goog.getCssName('goog-hsv-palette')). - * @extends {goog.ui.Component} - * @constructor - */ -goog.ui.HsvPalette = function(opt_domHelper, opt_color, opt_class) { - goog.ui.Component.call(this, opt_domHelper); - - this.setColor_(opt_color || '#f00'); - - /** - * The base class name for the component. - * @type {string} - * @private - */ - this.class_ = opt_class || goog.getCssName('goog-hsv-palette'); - - /** - * The document which is being listened to. - * type {HTMLDocument} - * @private - */ - this.document_ = this.getDomHelper().getDocument(); -}; -goog.inherits(goog.ui.HsvPalette, goog.ui.Component); -// TODO(user): Make this inherit from goog.ui.Control and split this into -// a control and a renderer. - - -/** - * DOM element representing the hue/saturation background image. - * @type {Element} - * @private - */ -goog.ui.HsvPalette.prototype.hsImageEl_; - - -/** - * DOM element representing the hue/saturation handle. - * @type {Element} - * @private - */ -goog.ui.HsvPalette.prototype.hsHandleEl_; - - -/** - * DOM element representing the value background image. - * @type {Element} - * @private - */ -goog.ui.HsvPalette.prototype.vImageEl_; - - -/** - * DOM element representing the value handle. - * @type {Element} - * @private - */ -goog.ui.HsvPalette.prototype.vHandleEl_; - - -/** - * DOM element representing the current color swatch. - * @type {Element} - * @private - */ -goog.ui.HsvPalette.prototype.swatchEl_; - - -/** - * DOM element representing the hex color input text field. - * @type {Element} - * @private - */ -goog.ui.HsvPalette.prototype.inputEl_; - - -/** - * Input handler object for the hex value input field. - * @type {goog.events.InputHandler} - * @private - */ -goog.ui.HsvPalette.prototype.inputHandler_; - - -/** - * Listener key for the mousemove event (during a drag operation). - * @type {?number} - * @private - */ -goog.ui.HsvPalette.prototype.mouseMoveListener_; - - -/** - * Listener key for the mouseup event (during a drag operation). - * @type {?number} - * @private - */ -goog.ui.HsvPalette.prototype.mouseUpListener_; - - -/** - * Gets the color that is currently selected in this color picker. - * @return {string} The string of the selected color. - */ -goog.ui.HsvPalette.prototype.getColor = function() { - return this.color_; -}; - - -/** - * Alpha transparency of the currently selected color, in [0, 1]. - * For the HSV palette this always returns 1. The HSVA palette overrides - * this method. - * @return {number} The current alpha value. - */ -goog.ui.HsvPalette.prototype.getAlpha = function() { - return 1; -}; - - -/** - * Updates the text entry field. - * @protected - */ -goog.ui.HsvPalette.prototype.updateInput = function() { - var parsed; - try { - parsed = goog.color.parse(this.inputEl_.value).hex; - } catch (e) { - // ignore - } - if (this.color_ != parsed) { - this.inputEl_.value = this.color_; - } -}; - - -/** - * Sets which color is selected and update the UI. - * @param {string} color The selected color. - */ -goog.ui.HsvPalette.prototype.setColor = function(color) { - if (color != this.color_) { - this.setColor_(color); - this.updateUi_(); - this.dispatchEvent(goog.ui.Component.EventType.ACTION); - } -}; - - -/** - * Sets which color is selected. - * @param {string} color The selected color. - * @private - */ -goog.ui.HsvPalette.prototype.setColor_ = function(color) { - var rgbHex = goog.color.parse(color).hex; - var rgbArray = goog.color.hexToRgb(rgbHex); - this.hsv_ = goog.color.rgbArrayToHsv(rgbArray); - // Hue is divided by 360 because the documentation for goog.color is currently - // incorrect. - // TODO(user): Fix this, see http://1324469 . - this.hsv_[0] = this.hsv_[0] / 360; - this.color_ = rgbHex; -}; - - -/** - * Alters the hue, saturation, and/or value of the currently selected color and - * updates the UI. - * @param {?number=} opt_hue (optional) hue in [0, 1]. - * @param {?number=} opt_saturation (optional) saturation in [0, 1]. - * @param {?number=} opt_value (optional) value in [0, 255]. - */ -goog.ui.HsvPalette.prototype.setHsv = function(opt_hue, - opt_saturation, - opt_value) { - if (opt_hue != null || opt_saturation != null || opt_value != null) { - this.setHsv_(opt_hue, opt_saturation, opt_value); - this.updateUi_(); - this.dispatchEvent(goog.ui.Component.EventType.ACTION); - } -}; - - -/** - * Alters the hue, saturation, and/or value of the currently selected color. - * @param {?number=} opt_hue (optional) hue in [0, 1]. - * @param {?number=} opt_saturation (optional) saturation in [0, 1]. - * @param {?number=} opt_value (optional) value in [0, 255]. - * @private - */ -goog.ui.HsvPalette.prototype.setHsv_ = function(opt_hue, - opt_saturation, - opt_value) { - this.hsv_[0] = (opt_hue != null) ? opt_hue : this.hsv_[0]; - this.hsv_[1] = (opt_saturation != null) ? opt_saturation : this.hsv_[1]; - this.hsv_[2] = (opt_value != null) ? opt_value : this.hsv_[2]; - // Hue is multiplied by 360 because the documentation for goog.color is - // currently incorrect. - // TODO(user): Fix this, see http://1324469 . - this.color_ = goog.color.hsvArrayToHex([ - this.hsv_[0] * 360, - this.hsv_[1], - this.hsv_[2] - ]); -}; - - -/** - * HsvPalettes cannot be used to decorate pre-existing html, since the - * structure they build is fairly complicated. - * @param {Element} element Element to decorate. - * @return {boolean} Returns always false. - */ -goog.ui.HsvPalette.prototype.canDecorate = function(element) { - return false; -}; - - -/** @override */ -goog.ui.HsvPalette.prototype.createDom = function() { - var dom = this.getDomHelper(); - var noalpha = (goog.userAgent.IE && !goog.userAgent.isVersion('7')) ? - ' ' + goog.getCssName(this.class_, 'noalpha') : ''; - var element = dom.createDom(goog.dom.TagName.DIV, - this.class_ + noalpha, - dom.createDom(goog.dom.TagName.DIV, - goog.getCssName(this.class_, 'hs-backdrop')), - this.hsImageEl_ = dom.createDom(goog.dom.TagName.DIV, - goog.getCssName(this.class_, 'hs-image')), - this.hsHandleEl_ = dom.createDom(goog.dom.TagName.DIV, - goog.getCssName(this.class_, 'hs-handle')), - this.vImageEl_ = dom.createDom(goog.dom.TagName.DIV, - goog.getCssName(this.class_, 'v-image')), - this.vHandleEl_ = dom.createDom(goog.dom.TagName.DIV, - goog.getCssName(this.class_, 'v-handle')), - this.swatchEl_ = dom.createDom(goog.dom.TagName.DIV, - goog.getCssName(this.class_, 'swatch')), - dom.createDom('label', null, - //dom.createDom('span', null, 'Hex color '), - this.inputEl_ = dom.createDom('input', - {'class': goog.getCssName(this.class_, 'input'), 'type': 'text'}) - ) - ); - this.setElementInternal(element); - - // TODO(arv): Set tabIndex -}; - - -/** - * Renders the color picker inside the provided element. This will override the - * current content of the element. - */ -goog.ui.HsvPalette.prototype.enterDocument = function() { - goog.ui.HsvPalette.superClass_.enterDocument.call(this); - - // TODO(user): Accessibility. - - this.updateUi_(); - - var handler = this.getHandler(); - handler.listen(this.getElement(), goog.events.EventType.MOUSEDOWN, - this.handleMouseDown_, false, this); - - // Cannot create InputHandler in createDom because IE throws an exception - // on document.activeElement - if (!this.inputHandler_) { - this.inputHandler_ = new goog.events.InputHandler(this.inputEl_); - } - - handler.listen(this.inputHandler_, - goog.events.InputHandler.EventType.INPUT, this.handleInput_, false, this); -}; - - -/** @override */ -goog.ui.HsvPalette.prototype.disposeInternal = function() { - goog.ui.HsvPalette.superClass_.disposeInternal.call(this); - - delete this.hsImageEl_; - delete this.hsHandleEl_; - delete this.vImageEl_; - delete this.vHandleEl_; - delete this.swatchEl_; - delete this.inputEl_; - if (this.inputHandler_) { - this.inputHandler_.dispose(); - delete this.inputHandler_; - } - goog.events.unlistenByKey(this.mouseMoveListener_); - goog.events.unlistenByKey(this.mouseUpListener_); -}; - - -/** - * Updates the position, opacity, and styles for the UI representation of the - * palette. - * @private - */ -goog.ui.HsvPalette.prototype.updateUi_ = function() { - if (this.isInDocument()) { - var h = this.hsv_[0]; - var s = this.hsv_[1]; - var v = this.hsv_[2]; - - var left = this.hsImageEl_.offsetLeft - - Math.floor(this.hsHandleEl_.offsetWidth / 2) + - this.hsImageEl_.offsetWidth * h; - this.hsHandleEl_.style.left = left + 'px'; - var top = this.hsImageEl_.offsetTop - - Math.floor(this.hsHandleEl_.offsetHeight / 2) + - this.hsImageEl_.offsetHeight * (1 - s); - this.hsHandleEl_.style.top = top + 'px'; - - top = this.vImageEl_.offsetTop - - Math.floor(this.vHandleEl_.offsetHeight / 2) + - this.vImageEl_.offsetHeight * ((255 - v) / 255); - this.vHandleEl_.style.top = top + 'px'; - goog.style.setOpacity(this.hsImageEl_, (v / 255)); - - goog.style.setStyle(this.vImageEl_, 'background-color', - goog.color.hsvToHex(this.hsv_[0] * 360, this.hsv_[1], 255)); - - goog.style.setStyle(this.swatchEl_, 'background-color', this.color_); - goog.style.setStyle(this.swatchEl_, 'color', - (this.hsv_[2] > 255 / 2) ? '#000' : '#fff'); - this.updateInput(); - } -}; - - -/** - * Handles mousedown events on palette UI elements. - * @param {goog.events.BrowserEvent} e Event object. - * @private - */ -goog.ui.HsvPalette.prototype.handleMouseDown_ = function(e) { - if (e.target == this.vImageEl_ || e.target == this.vHandleEl_) { - // Setup value change listeners - var b = goog.style.getBounds(this.vImageEl_); - this.handleMouseMoveV_(b, e); - this.mouseMoveListener_ = goog.events.listen(this.document_, - goog.events.EventType.MOUSEMOVE, - goog.bind(this.handleMouseMoveV_, this, b)); - this.mouseUpListener_ = goog.events.listen(this.document_, - goog.events.EventType.MOUSEUP, this.handleMouseUp_, false, this); - } else if (e.target == this.hsImageEl_ || e.target == this.hsHandleEl_) { - // Setup hue/saturation change listeners - var b = goog.style.getBounds(this.hsImageEl_); - this.handleMouseMoveHs_(b, e); - this.mouseMoveListener_ = goog.events.listen(this.document_, - goog.events.EventType.MOUSEMOVE, - goog.bind(this.handleMouseMoveHs_, this, b)); - this.mouseUpListener_ = goog.events.listen(this.document_, - goog.events.EventType.MOUSEUP, this.handleMouseUp_, false, this); - } -}; - - -/** - * Handles mousemove events on the document once a drag operation on the value - * slider has started. - * @param {goog.math.Rect} b Boundaries of the value slider object at the start - * of the drag operation. - * @param {goog.events.BrowserEvent} e Event object. - * @private - */ -goog.ui.HsvPalette.prototype.handleMouseMoveV_ = function(b, e) { - e.preventDefault(); - var vportPos = this.getDomHelper().getDocumentScroll(); - var newV = Math.round( - 255 * (b.top + b.height - Math.min( - Math.max(vportPos.y + e.clientY, b.top), - b.top + b.height) - ) / b.height - ); - this.setHsv(null, null, newV); -}; - - -/** - * Handles mousemove events on the document once a drag operation on the - * hue/saturation slider has started. - * @param {goog.math.Rect} b Boundaries of the value slider object at the start - * of the drag operation. - * @param {goog.events.BrowserEvent} e Event object. - * @private - */ -goog.ui.HsvPalette.prototype.handleMouseMoveHs_ = function(b, e) { - e.preventDefault(); - var vportPos = this.getDomHelper().getDocumentScroll(); - var newH = (Math.min(Math.max(vportPos.x + e.clientX, b.left), - b.left + b.width) - b.left) / b.width; - var newS = (-Math.min(Math.max(vportPos.y + e.clientY, b.top), - b.top + b.height) + b.top + b.height) / b.height; - this.setHsv(newH, newS, null); -}; - - -/** - * Handles mouseup events on the document, which ends a drag operation. - * @param {goog.events.Event} e Event object. - * @private - */ -goog.ui.HsvPalette.prototype.handleMouseUp_ = function(e) { - goog.events.unlistenByKey(this.mouseMoveListener_); - goog.events.unlistenByKey(this.mouseUpListener_); -}; - - -/** - * Handles input events on the hex value input field. - * @param {goog.events.Event} e Event object. - * @private - */ -goog.ui.HsvPalette.prototype.handleInput_ = function(e) { - if (/^#[0-9a-f]{6}$/i.test(this.inputEl_.value)) { - this.setColor(this.inputEl_.value); - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hsvpalette_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hsvpalette_test.html.svn-base deleted file mode 100644 index 5dc8bd3..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/hsvpalette_test.html.svn-base +++ /dev/null @@ -1,202 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<!-- -This test has not yet been updated to run on IE8. See http://b/hotlist?id=36311 ---> -<!--meta http-equiv="X-UA-Compatible" content="IE=edge"--> -<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"> - <title>HsvPalette Unit Tests</title> - <script src="../base.js"></script> - <script src="../deps.js"></script> - <script> - goog.require('goog.color'); - goog.require('goog.events'); - goog.require('goog.math.Rect'); - goog.require('goog.style'); - goog.require('goog.testing.PropertyReplacer'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.HsvPalette'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var samplePalette; - var eventWasFired = false; - var stubs = new goog.testing.PropertyReplacer(); - - function setUp() { - samplePalette = new goog.ui.HsvPalette(); - } - - function tearDown() { - samplePalette.dispose(); - stubs.reset(); - } - - function testOptionalInitialColor() { - var initialColor = '#0000ff'; - var customInitialPalette = new goog.ui.HsvPalette(null, initialColor); - assertEquals(initialColor, - goog.color.parse(customInitialPalette.getColor()).hex); - } - - function testCustomClassName() { - var customClassName = 'custom-plouf'; - var customClassPalette = - new goog.ui.HsvPalette(null, null, customClassName); - customClassPalette.createDom(); - assertTrue(goog.dom.classes.has(customClassPalette.getElement(), - customClassName)); - } - - function testCannotDecorate() { - assertFalse(samplePalette.canDecorate()); - } - - function testSetColor() { - var color = '#abcdef'; - samplePalette.setColor(color); - assertEquals(color, goog.color.parse(samplePalette.getColor()).hex); - } - - function testChangeEvent() { - // TODO(user): Add functionality to goog.testing.events to assert - // an event was fired. - goog.events.listen(samplePalette, goog.ui.Component.EventType.ACTION, - function() {eventWasFired = true;}); - samplePalette.setColor('#123456'); - assertTrue(eventWasFired); - } - - function testSetHsv() { - // Start from red. - samplePalette.setColor('#ff0000'); - - // Setting hue to 0.5 should yield cyan. - samplePalette.setHsv(0.5, null, null); - assertEquals('#00ffff', goog.color.parse(samplePalette.getColor()).hex); - - // Setting saturation to 0 should yield white. - samplePalette.setHsv(null, 0, null); - assertEquals('#ffffff', - goog.color.parse(samplePalette.getColor()).hex); - - // Setting value/brightness to 0 should yield black. - samplePalette.setHsv(null, null, 0); - assertEquals('#000000', goog.color.parse(samplePalette.getColor()).hex); - } - - function testRender() { - samplePalette.render(document.getElementById('sandbox')); - - assertTrue(samplePalette.isInDocument()); - - var elem = samplePalette.getElement(); - assertNotNull(elem); - assertEquals(goog.dom.TagName.DIV, elem.tagName); - - if (goog.userAgent.IE && !goog.userAgent.isVersion('7')) { - assertSameElements('On IE6, the noalpha class must be present', - ['goog-hsv-palette', 'goog-hsv-palette-noalpha'], - goog.dom.classes.get(elem)); - } else { - assertEquals('The noalpha class must not be present', - 'goog-hsv-palette', elem.className); - } - } - - function testNoLeftOverListenersAfterDispose() { - var initialListenerCount = goog.events.getTotalListenerCount(); - samplePalette.render(document.getElementById('sandbox')); - samplePalette.dispose(); - assertEquals(initialListenerCount, goog.events.getTotalListenerCount()); - } - - function testSwatchTextIsReadable() { - samplePalette.render(document.getElementById('sandbox')); - - // Text should be black when background is light. - samplePalette.setColor('#ccffff'); - assertEquals('#000000', - goog.color.parse(goog.style.getStyle(samplePalette.swatchEl_, - 'color')).hex); - - // Text should be white when background is dark. - samplePalette.setColor('#410800'); - assertEquals('#ffffff', - goog.color.parse(goog.style.getStyle(samplePalette.swatchEl_, - 'color')).hex); - } - - function testInputColor() { - samplePalette.render(document.getElementById('sandbox')); - var color = '#001122'; - samplePalette.inputEl_.value = color; - samplePalette.handleInput_(null); - assertEquals(color, goog.color.parse(samplePalette.getColor()).hex); - } - - function testHandleMouseMoveValue() { - samplePalette.render(document.getElementById('sandbox')); - stubs.set(goog.dom, 'getPageScroll', function() { - return new goog.math.Coordinate(0, 0); - }); - - // Raising the value/brightness of a dark red should yield a lighter red. - samplePalette.setColor('#630c00'); - goog.style.setPageOffset(samplePalette.vImageEl_, 0, 0); - goog.style.setSize(samplePalette.vImageEl_, 10, 100); - var boundaries = goog.style.getBounds(samplePalette.vImageEl_); - - var event = new goog.events.Event(); - event.clientY = -50; - // TODO(user): Use - // goog.testing.events.fireMouseDownEvent(samplePalette.vImageEl_); - // when google.testing.events support specifying properties of the event - // or find out how tod o it if it already supports it. - samplePalette.handleMouseMoveV_(boundaries, event); - assertEquals('#ff1e00', goog.color.parse(samplePalette.getColor()).hex); - } - - function testHandleMouseMoveHueSaturation() { - samplePalette.render(document.getElementById('sandbox')); - stubs.set(goog.dom, 'getPageScroll', function() { - return new goog.math.Coordinate(0, 0); - }); - - // The following hue/saturation selection should yield a light yellow. - goog.style.setPageOffset(samplePalette.hsImageEl_, 0, 0); - goog.style.setSize(samplePalette.hsImageEl_, 100, 100); - var boundaries = goog.style.getBounds(samplePalette.hsImageEl_); - - var event = new goog.events.Event(); - event.clientX = 20; - event.clientY = 85; - // TODO(user): Use goog.testing.events when appropriate (see above). - samplePalette.handleMouseMoveHs_(boundaries, event); - // TODO(user): Fix the main code for this, see bug #1324469. - // NOTE(gboyer): It's a little better than before due to the - // goog.style getBoundingClientRect fix, but still not the same. :-( - if (goog.userAgent.IE) { - var expectedColor = '#ffe0b2'; - } else { - var expectedColor = '#ffeec4'; - } - - assertEquals(expectedColor, - goog.color.parse(samplePalette.getColor()).hex); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/idgenerator.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/idgenerator.js.svn-base deleted file mode 100644 index f626d2f..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/idgenerator.js.svn-base +++ /dev/null @@ -1,57 +0,0 @@ -// 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(); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/idletimer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/idletimer.js.svn-base deleted file mode 100644 index 19000e0..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/idletimer.js.svn-base +++ /dev/null @@ -1,299 +0,0 @@ -// 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 Idle Timer. - * - * Keeps track of transitions between active and idle. This class is built on - * top of ActivityMonitor. Whenever an active user becomes idle, this class - * dispatches a BECOME_IDLE event. Whenever an idle user becomes active, this - * class dispatches a BECOME_ACTIVE event. The amount of inactive time it - * takes for a user to be considered idle is specified by the client, and - * different instances of this class can all use different thresholds. - * - */ - -goog.provide('goog.ui.IdleTimer'); -goog.require('goog.Timer'); -goog.require('goog.events'); -goog.require('goog.events.EventTarget'); -goog.require('goog.structs.Set'); -goog.require('goog.ui.ActivityMonitor'); - - - -/** - * Event target that will give notification of state changes between active and - * idle. This class is designed to require few resources while the user is - * active. - * @param {number} idleThreshold Amount of time in ms at which we consider the - * user has gone idle. - * @param {goog.ui.ActivityMonitor=} opt_activityMonitor The activity monitor - * keeping track of user interaction. Defaults to a default-constructed - * activity monitor. If a default activity monitor is used then this class - * will dispose of it. If an activity monitor is passed in then the caller - * remains responsible for disposing of it. - * @constructor - * @extends {goog.events.EventTarget} - */ -goog.ui.IdleTimer = function(idleThreshold, opt_activityMonitor) { - goog.events.EventTarget.call(this); - - var activityMonitor = opt_activityMonitor || - this.getDefaultActivityMonitor_(); - - /** - * The amount of time in ms at which we consider the user has gone idle - * @type {number} - * @private - */ - this.idleThreshold_ = idleThreshold; - - /** - * The activity monitor keeping track of user interaction - * @type {goog.ui.ActivityMonitor} - * @private - */ - this.activityMonitor_ = activityMonitor; - - /** - * Cached onActivityTick_ bound to the object for later use - * @type {Function} - * @private - */ - this.boundOnActivityTick_ = goog.bind(this.onActivityTick_, this); - - // Decide whether the user is currently active or idle. This method will - // check whether it is correct to start with the user in the active state. - this.maybeStillActive_(); -}; -goog.inherits(goog.ui.IdleTimer, goog.events.EventTarget); - - -/** - * Whether a listener is currently registered for an idle timer event. On - * initialization, the user is assumed to be active. - * @type {boolean} - * @private - */ -goog.ui.IdleTimer.prototype.hasActivityListener_ = false; - - -/** - * Handle to the timer ID used for checking ongoing activity, or null - * @type {?number} - * @private - */ -goog.ui.IdleTimer.prototype.onActivityTimerId_ = null; - - -/** - * Whether the user is currently idle - * @type {boolean} - * @private - */ -goog.ui.IdleTimer.prototype.isIdle_ = false; - - -/** - * The default activity monitor created by this class, if any - * @type {goog.ui.ActivityMonitor?} - * @private - */ -goog.ui.IdleTimer.defaultActivityMonitor_ = null; - - -/** - * The idle timers that currently reference the default activity monitor - * @type {goog.structs.Set} - * @private - */ -goog.ui.IdleTimer.defaultActivityMonitorReferences_ = new goog.structs.Set(); - - -/** - * Event constants for the idle timer event target - * @enum {string} - */ -goog.ui.IdleTimer.Event = { - /** Event fired when an idle user transitions into the active state */ - BECOME_ACTIVE: 'active', - /** Event fired when an active user transitions into the idle state */ - BECOME_IDLE: 'idle' -}; - - -/** - * Gets the default activity monitor used by this class. If a default has not - * been created yet, then a new one will be created. - * @return {goog.ui.ActivityMonitor} The default activity monitor. - * @private - */ -goog.ui.IdleTimer.prototype.getDefaultActivityMonitor_ = function() { - goog.ui.IdleTimer.defaultActivityMonitorReferences_.add(this); - if (goog.ui.IdleTimer.defaultActivityMonitor_ == null) { - goog.ui.IdleTimer.defaultActivityMonitor_ = new goog.ui.ActivityMonitor(); - } - return goog.ui.IdleTimer.defaultActivityMonitor_; -}; - - -/** - * Removes the reference to the default activity monitor. If there are no more - * references then the default activity monitor gets disposed. - * @private - */ -goog.ui.IdleTimer.prototype.maybeDisposeDefaultActivityMonitor_ = function() { - goog.ui.IdleTimer.defaultActivityMonitorReferences_.remove(this); - if (goog.ui.IdleTimer.defaultActivityMonitor_ != null && - goog.ui.IdleTimer.defaultActivityMonitorReferences_.isEmpty()) { - goog.ui.IdleTimer.defaultActivityMonitor_.dispose(); - goog.ui.IdleTimer.defaultActivityMonitor_ = null; - } -}; - - -/** - * Checks whether the user is active. If the user is still active, then a timer - * is started to check again later. - * @private - */ -goog.ui.IdleTimer.prototype.maybeStillActive_ = function() { - // See how long before the user would go idle. The user is considered idle - // after the idle time has passed, not exactly when the idle time arrives. - var remainingIdleThreshold = this.idleThreshold_ + 1 - - (goog.now() - this.activityMonitor_.getLastEventTime()); - if (remainingIdleThreshold > 0) { - // The user is still active. Check again later. - this.onActivityTimerId_ = goog.Timer.callOnce( - this.boundOnActivityTick_, remainingIdleThreshold); - } else { - // The user has not been active recently. - this.becomeIdle_(); - } -}; - - -/** - * Handler for the timeout used for checking ongoing activity - * @private - */ -goog.ui.IdleTimer.prototype.onActivityTick_ = function() { - // The timer has fired. - this.onActivityTimerId_ = null; - - // The maybeStillActive method will restart the timer, if appropriate. - this.maybeStillActive_(); -}; - - -/** - * Transitions from the active state to the idle state - * @private - */ -goog.ui.IdleTimer.prototype.becomeIdle_ = function() { - this.isIdle_ = true; - - // The idle timer will send notification when the user does something - // interactive. - goog.events.listen(this.activityMonitor_, - goog.ui.ActivityMonitor.Event.ACTIVITY, - this.onActivity_, false, this); - this.hasActivityListener_ = true; - - // Notify clients of the state change. - this.dispatchEvent(goog.ui.IdleTimer.Event.BECOME_IDLE); -}; - - -/** - * Handler for idle timer events when the user does something interactive - * @param {goog.events.Event} e The event object. - * @private - */ -goog.ui.IdleTimer.prototype.onActivity_ = function(e) { - this.becomeActive_(); -}; - - -/** - * Transitions from the idle state to the active state - * @private - */ -goog.ui.IdleTimer.prototype.becomeActive_ = function() { - this.isIdle_ = false; - - // Stop listening to every interactive event. - this.removeActivityListener_(); - - // Notify clients of the state change. - this.dispatchEvent(goog.ui.IdleTimer.Event.BECOME_ACTIVE); - - // Periodically check whether the user has gone inactive. - this.maybeStillActive_(); -}; - - -/** - * Removes the activity listener, if necessary - * @private - */ -goog.ui.IdleTimer.prototype.removeActivityListener_ = function() { - if (this.hasActivityListener_) { - goog.events.unlisten(this.activityMonitor_, - goog.ui.ActivityMonitor.Event.ACTIVITY, - this.onActivity_, false, this); - this.hasActivityListener_ = false; - } -}; - - -/** @override */ -goog.ui.IdleTimer.prototype.disposeInternal = function() { - this.removeActivityListener_(); - if (this.onActivityTimerId_ != null) { - goog.global.clearTimeout(this.onActivityTimerId_); - this.onActivityTimerId_ = null; - } - this.maybeDisposeDefaultActivityMonitor_(); - goog.ui.IdleTimer.superClass_.disposeInternal.call(this); -}; - - -/** - * @return {number} the amount of time at which we consider the user has gone - * idle in ms. - */ -goog.ui.IdleTimer.prototype.getIdleThreshold = function() { - return this.idleThreshold_; -}; - - -/** - * @return {goog.ui.ActivityMonitor} the activity monitor keeping track of user - * interaction. - */ -goog.ui.IdleTimer.prototype.getActivityMonitor = function() { - return this.activityMonitor_; -}; - - -/** - * Returns true if there has been no user action for at least the specified - * interval, and false otherwise - * @return {boolean} true if the user is idle, false otherwise. - */ -goog.ui.IdleTimer.prototype.isIdle = function() { - return this.isIdle_; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/idletimer_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/idletimer_test.html.svn-base deleted file mode 100644 index 3975118..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/idletimer_test.html.svn-base +++ /dev/null @@ -1,100 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2007 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.IdleTimer</title> -<script src="../base.js"></script> -<script> - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.MockClock'); - goog.require('goog.ui.IdleTimer'); - goog.require('goog.ui.MockActivityMonitor'); -</script> -</head> -<body> -<script> - - var clock; - - function setUp() { - clock = new goog.testing.MockClock(true); - goog.now = goog.bind(clock.getCurrentTime, clock); - } - - function tearDown() { - clock.dispose(); - } - - - /** - * Tests whether an event is fired when the user becomes idle - */ - function testBecomeIdle() { - var idleThreshold = 1000; - var mockActivityMonitor = new goog.ui.MockActivityMonitor(); - var idleTimer = new goog.ui.IdleTimer(idleThreshold, mockActivityMonitor); - - mockActivityMonitor.simulateEvent(); - assertFalse('Precondition: user should be active', idleTimer.isIdle()); - - var onBecomeIdleCount = 0; - var onBecomeIdle = function() { - onBecomeIdleCount += 1; - }; - goog.events.listen(idleTimer, - goog.ui.IdleTimer.Event.BECOME_IDLE, - onBecomeIdle); - - clock.tick(idleThreshold); - mockActivityMonitor.simulateEvent(); - clock.tick(idleThreshold); - assert('The BECOME_IDLE event fired too early', onBecomeIdleCount == 0); - assertFalse('The user should still be active', idleTimer.isIdle()); - - clock.tick(1); - assert('The BECOME_IDLE event fired too late', onBecomeIdleCount == 1); - assert('The user should be idle', idleTimer.isIdle()); - - idleTimer.dispose(); - } - - - /** - * Tests whether an event is fired when the user becomes active - */ - function testBecomeActive() { - var idleThreshold = 1000; - var mockActivityMonitor = new goog.ui.MockActivityMonitor(); - var idleTimer = new goog.ui.IdleTimer(idleThreshold, mockActivityMonitor); - - clock.tick(idleThreshold + 1); - assert('Precondition: user should be idle', idleTimer.isIdle()); - - var onBecomeActiveCount = 0; - var onBecomeActive = function() { - onBecomeActiveCount += 1; - }; - goog.events.listen(idleTimer, - goog.ui.IdleTimer.Event.BECOME_ACTIVE, - onBecomeActive); - - clock.tick(idleThreshold); - assert('The BECOME_ACTIVE event fired too early', onBecomeActiveCount == 0); - assert('The user should still be idle', idleTimer.isIdle()); - - mockActivityMonitor.simulateEvent(); - assert('The BECOME_ACTIVE event fired too late', onBecomeActiveCount == 1); - assertFalse('The user should be active', idleTimer.isIdle()); - - idleTimer.dispose(); - } - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/iframemask.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/iframemask.js.svn-base deleted file mode 100644 index b84ca64..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/iframemask.js.svn-base +++ /dev/null @@ -1,259 +0,0 @@ -// 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 Iframe shims, to protect controls on the underlying page - * from bleeding through popups. - * - * @author gboyer@google.com (Garrett Boyer) - * @author nicksantos@google.com (Nick Santos) (Ported to Closure) - */ - - -goog.provide('goog.ui.IframeMask'); - -goog.require('goog.Disposable'); -goog.require('goog.Timer'); -goog.require('goog.dom'); -goog.require('goog.dom.DomHelper'); -goog.require('goog.dom.iframe'); -goog.require('goog.events.EventHandler'); -goog.require('goog.events.EventTarget'); -goog.require('goog.style'); - - - -/** - * Controller for an iframe mask. The mask is only valid in the current - * document, or else the document of the given DOM helper. - * - * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper for the relevant - * document. - * @param {goog.structs.Pool=} opt_iframePool An optional source of iframes. - * Iframes will be grabbed from the pool when they're needed and returned - * to the pool (but still attached to the DOM) when they're done. - * @constructor - * @extends {goog.Disposable} - */ -goog.ui.IframeMask = function(opt_domHelper, opt_iframePool) { - goog.Disposable.call(this); - - /** - * The DOM helper for this document. - * @type {goog.dom.DomHelper} - * @private - */ - this.dom_ = opt_domHelper || goog.dom.getDomHelper(); - - /** - * An Element to snap the mask to. If none is given, defaults to - * a full-screen iframe mask. - * @type {Element} - * @private - */ - this.snapElement_ = this.dom_.getDocument().documentElement; - - /** - * An event handler for listening to popups and the like. - * @type {goog.events.EventHandler|undefined} - * @private - */ - this.handler_ = new goog.events.EventHandler(this); - - /** - * An iframe pool. - * @type {goog.structs.Pool|undefined} - * @private - */ - this.iframePool_ = opt_iframePool; -}; -goog.inherits(goog.ui.IframeMask, goog.Disposable); - - -/** - * An iframe. - * @type {HTMLIFrameElement} - * @private - */ -goog.ui.IframeMask.prototype.iframe_; - - -/** - * The z-index of the iframe mask. - * @type {number} - * @private - */ -goog.ui.IframeMask.prototype.zIndex_ = 1; - - -/** - * The opacity of the iframe mask, expressed as a value between 0 and 1, with - * 1 being totally opaque. - * @type {number} - * @private - */ -goog.ui.IframeMask.prototype.opacity_ = 0; - - -/** - * Removes the iframe from the DOM. - * @override - * @protected - */ -goog.ui.IframeMask.prototype.disposeInternal = function() { - if (this.iframePool_) { - this.iframePool_.releaseObject( - /** @type {HTMLIFrameElement} */ (this.iframe_)); - } else { - goog.dom.removeNode(this.iframe_); - } - this.iframe_ = null; - - this.handler_.dispose(); - this.handler_ = null; - - goog.ui.IframeMask.superClass_.disposeInternal.call(this); -}; - - -/** - * CSS for a hidden iframe. - * @type {string} - * @private - */ -goog.ui.IframeMask.HIDDEN_CSS_TEXT_ = - 'position:absolute;display:none;z-index:1'; - - -/** - * Removes the mask from the screen. - */ -goog.ui.IframeMask.prototype.hideMask = function() { - if (this.iframe_) { - this.iframe_.style.cssText = goog.ui.IframeMask.HIDDEN_CSS_TEXT_; - if (this.iframePool_) { - this.iframePool_.releaseObject(this.iframe_); - this.iframe_ = null; - } - } -}; - - -/** - * Gets the iframe to use as a mask. Creates a new one if one has not been - * created yet. - * @return {HTMLIFrameElement} The iframe. - * @private - */ -goog.ui.IframeMask.prototype.getIframe_ = function() { - if (!this.iframe_) { - this.iframe_ = this.iframePool_ ? - /** @type {HTMLIFrameElement} */ (this.iframePool_.getObject()) : - goog.dom.iframe.createBlank(this.dom_); - this.iframe_.style.cssText = goog.ui.IframeMask.HIDDEN_CSS_TEXT_; - this.dom_.getDocument().body.appendChild(this.iframe_); - } - return this.iframe_; -}; - - -/** - * Applies the iframe mask to the screen. - */ -goog.ui.IframeMask.prototype.applyMask = function() { - var iframe = this.getIframe_(); - var bounds = goog.style.getBounds(this.snapElement_); - iframe.style.cssText = - 'position:absolute;' + - 'left:' + bounds.left + 'px;' + - 'top:' + bounds.top + 'px;' + - 'width:' + bounds.width + 'px;' + - 'height:' + bounds.height + 'px;' + - 'z-index:' + this.zIndex_; - goog.style.setOpacity(iframe, this.opacity_); - iframe.style.display = 'block'; -}; - - -/** - * Sets the opacity of the mask. Will take effect the next time the mask - * is applied. - * @param {number} opacity A value between 0 and 1, with 1 being - * totally opaque. - */ -goog.ui.IframeMask.prototype.setOpacity = function(opacity) { - this.opacity_ = opacity; -}; - - -/** - * Sets the z-index of the mask. Will take effect the next time the mask - * is applied. - * @param {number} zIndex A z-index value. - */ -goog.ui.IframeMask.prototype.setZIndex = function(zIndex) { - this.zIndex_ = zIndex; -}; - - -/** - * Sets the element to use as the bounds of the mask. Takes effect immediately. - * @param {Element} snapElement The snap element, which the iframe will be - * "snapped" around. - */ -goog.ui.IframeMask.prototype.setSnapElement = function(snapElement) { - this.snapElement_ = snapElement; - if (this.iframe_ && goog.style.isElementShown(this.iframe_)) { - this.applyMask(); - } -}; - - -/** - * Listens on the specified target, hiding and showing the iframe mask - * when the given event types are dispatched. - * @param {goog.events.EventTarget} target The event target to listen on. - * @param {string} showEvent When this event fires, the mask will be applied. - * @param {string} hideEvent When this event fires, the mask will be hidden. - * @param {Element=} opt_snapElement When the mask is applied, it will - * automatically snap to this element. If no element is specified, it will - * use the default snap element. - */ -goog.ui.IframeMask.prototype.listenOnTarget = function(target, showEvent, - hideEvent, opt_snapElement) { - var timerKey; - this.handler_.listen(target, showEvent, function() { - if (opt_snapElement) { - this.setSnapElement(opt_snapElement); - } - // Check out the iframe asynchronously, so we don't block the SHOW - // event and cause a bounce. - timerKey = goog.Timer.callOnce(this.applyMask, 0, this); - }); - this.handler_.listen(target, hideEvent, function() { - if (timerKey) { - goog.Timer.clear(timerKey); - timerKey = null; - } - this.hideMask(); - }); -}; - - -/** - * Removes all handlers attached by listenOnTarget. - */ -goog.ui.IframeMask.prototype.removeHandlers = function() { - this.handler_.removeAll(); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/iframemask_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/iframemask_test.html.svn-base deleted file mode 100644 index eeea52b..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/iframemask_test.html.svn-base +++ /dev/null @@ -1,230 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - - @author gboyer@google.com (Garrett Boyer) - @author nicksantos@google.com (Nick Santos) (Ported to Closure) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>goog.ui.IframeMask Unit Test</title> -<script src="../base.js"></script> -<script> - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.MockClock'); - goog.require('goog.testing.StrictMock'); - goog.require('goog.ui.IframeMask'); - goog.require('goog.ui.Popup'); - goog.require('goog.structs.Pool'); -</script> -<style type="text/css"> -#popup { - position: absolute; - left: 100px; - top: 900px; /* so that you can see unit test failures */ - width: 300px; - height: 400px; -} -</style> -</head> -<body> - -<div id="sandbox"></div> - -<script> - -var iframeMask; -var mockClock; - -function setUp() { - goog.dom.getElement('sandbox').innerHTML = '<div id="popup"></div>'; - mockClock = new goog.testing.MockClock(true); - - iframeMask = new goog.ui.IframeMask(); -} - -function tearDown() { - iframeMask.dispose(); - mockClock.dispose(); - - assertNoIframes(); -} - -function findOneAndOnlyIframe() { - var iframes = document.getElementsByTagName(goog.dom.TagName.IFRAME); - assertEquals('There should be exactly 1 iframe in the document', - 1, iframes.length); - return iframes[0]; -} - -function assertNoIframes() { - assertEquals('Expected no iframes in the document', 0, - goog.dom.getElementsByTagNameAndClass(goog.dom.TagName.IFRAME).length); -} - -function testApplyFullScreenMask() { - iframeMask.applyMask(); - - var iframe = findOneAndOnlyIframe(); - assertEquals('block', iframe.style.display); - assertEquals('absolute', iframe.style.position); - - // coerce zindex to a string - assertEquals('1', iframe.style.zIndex + ''); - - iframeMask.hideMask(); - assertEquals('none', iframe.style.display); -} - -function testApplyOpacity() { - iframeMask.setOpacity(0.3); - iframeMask.applyMask(); - - if (goog.userAgent.IE) { - assertContains('Expected opactity to be set in the CSS style', - '30', findOneAndOnlyIframe().style.cssText); - } else { - assertContains('Expected opactity to be set in the CSS style', - '0.3', findOneAndOnlyIframe().style.cssText); - } -} - -function testApplyZIndex() { - iframeMask.setZIndex(5); - iframeMask.applyMask(); - - // coerce zindex to a string - assertEquals('5', findOneAndOnlyIframe().style.zIndex + ''); -} - -function testSnapElement() { - iframeMask.setSnapElement(goog.dom.getElement('popup')); - iframeMask.applyMask(); - - var iframe = findOneAndOnlyIframe(); - var bounds = goog.style.getBounds(iframe); - assertEquals(100, bounds.left); - assertEquals(900, bounds.top); - assertEquals(300, bounds.width); - assertEquals(400, bounds.height); - - iframeMask.setSnapElement(document.documentElement); - - // Make sure that snapping to a different element changes the bounds. - assertNotEquals('Snap element not updated', - 400, goog.style.getBounds(iframe).height); -} - -function testAttachToPopup() { - var popup = new goog.ui.Popup(goog.dom.getElement('popup')); - iframeMask.listenOnTarget(popup, goog.ui.PopupBase.EventType.SHOW, - goog.ui.PopupBase.EventType.HIDE, goog.dom.getElement('popup')); - - assertNoIframes(); - popup.setVisible(true); - assertNoIframes(); - - // Tick because the showing of the iframe mask happens asynchronously. - // (Otherwise the handling of the mousedown can take so long that a bounce - // occurs). - mockClock.tick(1); - - var iframe = findOneAndOnlyIframe(); - var bounds = goog.style.getBounds(iframe); - assertEquals(300, bounds.width); - assertEquals(400, bounds.height); - assertEquals('block', iframe.style.display); - - popup.setVisible(false); - assertEquals('none', iframe.style.display); -} - -function testQuickHidingPopup() { - var popup = new goog.ui.Popup(goog.dom.getElement('popup')); - iframeMask.listenOnTarget(popup, goog.ui.PopupBase.EventType.SHOW, - goog.ui.PopupBase.EventType.HIDE); - - assertNoIframes(); - popup.setVisible(true); - assertNoIframes(); - popup.setVisible(false); - assertNoIframes(); - - // Tick because the showing of the iframe mask happens asynchronously. - // (Otherwise the handling of the mousedown can take so long that a bounce - // occurs). - mockClock.tick(1); - assertNoIframes(); -} - -function testRemoveHandlers() { - var popup = new goog.ui.Popup(goog.dom.getElement('popup')); - iframeMask.listenOnTarget(popup, goog.ui.PopupBase.EventType.SHOW, - goog.ui.PopupBase.EventType.HIDE); - iframeMask.removeHandlers(); - popup.setVisible(true); - - // Tick because the showing of the iframe mask happens asynchronously. - // (Otherwise the handling of the mousedown can take so long that a bounce - // occurs). - mockClock.tick(1); - assertNoIframes(); -} - -function testIframePool() { - var iframe = goog.dom.iframe.createBlank(goog.dom.getDomHelper()); - var mockPool = new goog.testing.StrictMock(goog.structs.Pool); - mockPool.getObject(); - mockPool.$returns(iframe); - - mockPool.$replay(); - - iframeMask.dispose(); - - // Create a new iframe mask with a pool, and verify that it checks - // its iframe out of the pool instead of creating one. - iframeMask = new goog.ui.IframeMask(null, mockPool); - iframeMask.applyMask(); - mockPool.$verify(); - findOneAndOnlyIframe(); - - mockPool.$reset(); - - mockPool.releaseObject(iframe); - mockPool.$replay(); - - // When the iframe mask has a pool, the pool is responsible for - // removing the iframe from the DOM. - iframeMask.hideMask(); - mockPool.$verify(); - findOneAndOnlyIframe() - - // And showing the iframe again should check it out of the pool again. - mockPool.$reset(); - mockPool.getObject(); - mockPool.$returns(iframe); - mockPool.$replay(); - - iframeMask.applyMask(); - mockPool.$verify(); - - // When the test is over, the iframe mask should be disposed. Make sure - // that the pool removes the iframe from the page. - mockPool.$reset(); - mockPool.releaseObject(iframe); - mockPool.$does(function() { - goog.dom.removeNode(iframe); - }); - mockPool.$replay(); -} - -</script> - -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/imagelessbuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/imagelessbuttonrenderer.js.svn-base deleted file mode 100644 index 6aa5f76..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/imagelessbuttonrenderer.js.svn-base +++ /dev/null @@ -1,205 +0,0 @@ -// 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) - * @see ../demos/imagelessbutton.html - */ - -goog.provide('goog.ui.ImagelessButtonRenderer'); - -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.ImagelessButtonRenderer = function() { - goog.ui.CustomButtonRenderer.call(this); -}; -goog.inherits(goog.ui.ImagelessButtonRenderer, goog.ui.CustomButtonRenderer); - - -/** - * The singleton instance of this renderer class. - * @type {goog.ui.ImagelessButtonRenderer?} - * @private - */ -goog.ui.ImagelessButtonRenderer.instance_ = null; -goog.addSingletonGetter(goog.ui.ImagelessButtonRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.ImagelessButtonRenderer.CSS_CLASS = - goog.getCssName('goog-imageless-button'); - - -/** - * Returns the button's contents wrapped in 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">Contents...</div> - * </div> - * </div> - * </div> - * </div> - * Overrides {@link goog.ui.ButtonRenderer#createDom}. - * @param {goog.ui.Button} button Button to render. - * @return {Element} Root element for the button. - * @override - */ -goog.ui.ImagelessButtonRenderer.prototype.createDom = - goog.ui.ImagelessButtonRenderer.superClass_.createDom; - - -/** @override */ -goog.ui.ImagelessButtonRenderer.prototype.getContentElement = function( - element) { - return (/** @type {Element} */ element && element.firstChild && - element.firstChild.firstChild && - 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-imageless-button-outer-box"> - * <div class="goog-inline-block goog-imageless-button-inner-box"> - * <div class="goog-imageless-button-pos"> - * <div class="goog-imageless-button-top-shadow"> </div> - * <div class="goog-imageless-button-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.ImagelessButtonRenderer.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'), - 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.ImagelessButtonRenderer.prototype.hasBoxStructure = function( - button, element) { - var outer = button.getDomHelper().getFirstElementChild(element); - if (outer && - outer.className.indexOf( - goog.getCssName(this.getCssClass(), 'outer-box')) != -1) { - var inner = button.getDomHelper().getFirstElementChild(outer); - if (inner && - inner.className.indexOf( - goog.getCssName(this.getCssClass(), 'inner-box')) != -1) { - var pos = button.getDomHelper().getFirstElementChild(inner); - if (pos && - pos.className.indexOf( - goog.getCssName(this.getCssClass(), 'pos')) != -1) { - var shadow = button.getDomHelper().getFirstElementChild(pos); - if (shadow && shadow.className.indexOf( - goog.getCssName(this.getCssClass(), 'top-shadow')) != -1) { - var content = button.getDomHelper().getNextElementSibling(shadow); - if (content && - content.className.indexOf( - goog.getCssName(this.getCssClass(), 'content')) != -1) { - // 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.ImagelessButtonRenderer.prototype.getCssClass = function() { - return goog.ui.ImagelessButtonRenderer.CSS_CLASS; -}; - - -// Register a decorator factory function for goog.ui.ImagelessButtonRenderer. -goog.ui.registry.setDecoratorByClassName( - goog.ui.ImagelessButtonRenderer.CSS_CLASS, - function() { - return new goog.ui.Button(null, - goog.ui.ImagelessButtonRenderer.getInstance()); - }); - - -// Register a decorator factory function for toggle buttons using the -// goog.ui.ImagelessButtonRenderer. -goog.ui.registry.setDecoratorByClassName( - goog.getCssName('goog-imageless-toggle-button'), - function() { - var button = new goog.ui.Button(null, - goog.ui.ImagelessButtonRenderer.getInstance()); - button.setSupportedState(goog.ui.Component.State.CHECKED, true); - return button; - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/imagelessmenubuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/imagelessmenubuttonrenderer.js.svn-base deleted file mode 100644 index fc8fea5..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/imagelessmenubuttonrenderer.js.svn-base +++ /dev/null @@ -1,204 +0,0 @@ -// 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.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. - */ -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); - if (outer && - outer.className.indexOf( - goog.getCssName(this.getCssClass(), 'outer-box')) != -1) { - var inner = button.getDomHelper().getFirstElementChild(outer); - if (inner && - inner.className.indexOf( - goog.getCssName(this.getCssClass(), 'inner-box')) != -1) { - var pos = button.getDomHelper().getFirstElementChild(inner); - if (pos && - pos.className.indexOf( - goog.getCssName(this.getCssClass(), 'pos')) != -1) { - var shadow = button.getDomHelper().getFirstElementChild(pos); - if (shadow && shadow.className.indexOf( - goog.getCssName(this.getCssClass(), 'top-shadow')) != -1) { - var content = button.getDomHelper().getNextElementSibling(shadow); - if (content && - content.className.indexOf( - goog.getCssName(this.getCssClass(), 'content')) != -1) { - // 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()); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/imagelessroundedcorner.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/imagelessroundedcorner.js.svn-base deleted file mode 100644 index a3634c6..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/imagelessroundedcorner.js.svn-base +++ /dev/null @@ -1,972 +0,0 @@ -// 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 definitions for imageless rounded corners. - * - * NOTE: This technique uses one Canvas or VML element per corner, and is quite - * slow. The border-radius CSS property is preferable, but not available in all - * browsers. ImagelessRoundedCorner should be avoided where performance is - * critical. - * - * @supported IE 6.0+, Safari 2.0+, Firefox 1.5+, Opera 9.2+. - * @see ../demos/imagelessroundedcorner.html - */ - -goog.provide('goog.ui.AbstractImagelessRoundedCorner'); -goog.provide('goog.ui.CanvasRoundedCorner'); -goog.provide('goog.ui.ImagelessRoundedCorner'); -goog.provide('goog.ui.VmlRoundedCorner'); - -goog.require('goog.dom.DomHelper'); -goog.require('goog.graphics.SolidFill'); -goog.require('goog.graphics.Stroke'); -goog.require('goog.graphics.Path'); -goog.require('goog.graphics.VmlGraphics'); -goog.require('goog.userAgent'); - - -/** - * Returns an instance of goog.ui.ImagelessRoundedCorner that can render a - * rounded corner, with the implementation varying depending on the current - * platform. The rounded corner contains 3 components: horizontal filler, arc, - * and vertical filler. Horizontal and/or vertical fillers are added if the - * radius of the rounded corner is less than the width and/or height of the - * containing element. This is a factory method for image-less rounded corner - * classes. - * @param {!Element} element The container element for the rounded corner. - * @param {number} width The width of the element excluding the border, in - * pixels. - * @param {number} height The height of the element excluding the border, in - * pixels. - * @param {number} borderWidth The thickness of the rounded corner, in pixels. - * @param {number} radius The radius of the rounded corner, in pixels. The - * radius must be less than or equal to the width or height (whichever - * is greater). - * @param {goog.ui.ImagelessRoundedCorner.Corner} location Location of the - * rounded corner. - * @param {string} borderColor The color of the rounded corner. - * @param {string=} opt_backgroundColor The background color of the rounded - * corner. - * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the - * document we want to render in. - * @return {goog.ui.AbstractImagelessRoundedCorner|undefined} Imageless rounded - * corner instance. - */ -goog.ui.ImagelessRoundedCorner.create = function(element, - width, - height, - borderWidth, - radius, - location, - borderColor, - opt_backgroundColor, - opt_domHelper) { - // Check for invalid values. - if (width <= 0 || - height <= 0 || - borderWidth <= 0 || - radius < 0) { - return; - } - - // Instantiate the proper rounded corner, based on user-agent. - var roundedCorner; - var version = parseFloat(goog.userAgent.VERSION); - if (goog.userAgent.IE) { - roundedCorner = new goog.ui.VmlRoundedCorner(element, - width, - height, - borderWidth, - radius, - location, - borderColor, - opt_backgroundColor, - opt_domHelper); - } else { - roundedCorner = new goog.ui.CanvasRoundedCorner(element, - width, - height, - borderWidth, - radius, - location, - borderColor, - opt_backgroundColor, - opt_domHelper); - } - - return roundedCorner; -}; - - -/** - * Enum for specifying which corners to render. - * @enum {number} - */ -goog.ui.ImagelessRoundedCorner.Corner = { - TOP_LEFT: 1, - TOP_RIGHT: 2, - BOTTOM_LEFT: 4, - BOTTOM_RIGHT: 8 -}; - - -/** - * Specifies the top-left and bottom-left corners. - * @type {number} - * @private - */ -goog.ui.ImagelessRoundedCorner.LEFT_ = - goog.ui.ImagelessRoundedCorner.Corner.TOP_LEFT | - goog.ui.ImagelessRoundedCorner.Corner.BOTTOM_LEFT; - - -/** - * Specifies the top-left and top-right corners. - * @type {number} - * @private - */ -goog.ui.ImagelessRoundedCorner.TOP_ = - goog.ui.ImagelessRoundedCorner.Corner.TOP_LEFT | - goog.ui.ImagelessRoundedCorner.Corner.TOP_RIGHT; - - - -/** - * Base class for various image-less rounded corner classes. Do not create - * instances of this class. Instead, utilize - * goog.ui.ImagelessRoundedCorner.create(). - * @param {!Element} element The container element for the rounded corner. - * @param {number} width The width of the element excluding the border, in - * pixels. - * @param {number} height The height of the element excluding the border, in - * pixels. - * @param {number} borderWidth The thickness of the rounded corner, in pixels. - * @param {number} radius The radius of the rounded corner, in pixels. The - * radius must be less than or equal to the width or height (whichever - * is greater). - * @param {goog.ui.ImagelessRoundedCorner.Corner} location Location of the - * rounded corner. - * @param {string} borderColor The color of the rounded corner. - * @param {string=} opt_backgroundColor The background color of the - * rounded corner. - * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the - * document we want to render in. - * @constructor - */ -goog.ui.AbstractImagelessRoundedCorner = function(element, - width, - height, - borderWidth, - radius, - location, - borderColor, - opt_backgroundColor, - opt_domHelper) { - /** - * The container element for the rounded corner. - * @type {!Element} - * @private - */ - this.element_ = element; - - /** - * The width of the container element for the rounded corner, in pixels. - * @type {number} - * @private - */ - this.width_ = width; - - /** - * The height of the container element for the rounded corner, in pixels. - * @type {number} - * @private - */ - this.height_ = height; - - /** - * The color of the rounded corner. - * @type {string} - * @private - */ - this.borderColor_ = borderColor; - - /** - * The background color of the rounded corner. - * @type {string|undefined} - * @private - */ - this.backgroundColor_ = opt_backgroundColor; - - /** - * The thickness of the rounded corner, in pixels. - * @type {number} - * @private - */ - this.borderWidth_ = borderWidth; - - /** - * The radius of the rounded corner, in pixels. - * @type {number} - * @private - */ - this.radius_ = radius; - - /** - * Indicates if this is a left rounded corner (ex. top left or bottom left). - * @type {boolean} - * @private - */ - this.isLeft_ = !!(location & goog.ui.ImagelessRoundedCorner.LEFT_); - - /** - * Indicates if this is a top rounded corner (ex. top left or top right). - * @type {boolean} - * @private - */ - this.isTop_ = !!(location & goog.ui.ImagelessRoundedCorner.TOP_); - - /** - * The DOM helper object for the document we want to render in. - * @type {!goog.dom.DomHelper} - * @private - */ - this.domHelper_ = opt_domHelper || goog.dom.getDomHelper(this.element_); - - /** - * The start angle of the rounded corner arc - * @type {number} - * @private - */ - this.startAngle_ = this.getStartAngle(); - - /** - * The end angle of the rounded corner arc - * @type {number} - * @private - */ - this.endAngle_ = this.getEndAngle(); - - /** - * The x and y coordinates indicating where to begin drawing. - * @type {!Array.<number>} - * @private - */ - this.start_ = []; - - /** - * The x and y coordinates indicating where to stop drawing. - * @type {!Array.<number>} - * @private - */ - this.end_ = []; - - - // Define the circle center of the arc, and the start/end points. The - // start/end points, and the circle center for the arc are moved inward, - // depending on the borderWidth of the stroke. - var borderWidthOffset = this.getBorderWidthOffset(); - if (this.isLeft_) { - this.start_[0] = this.width_; - this.xCenter_ = this.radius_ + borderWidthOffset; - this.end_[0] = borderWidthOffset; - } else { - this.start_[0] = 0; - this.xCenter_ = this.width_ - this.radius_ - borderWidthOffset; - this.end_[0] = this.width_ - borderWidthOffset; - } - if (this.isTop_) { - this.start_[1] = borderWidthOffset; - this.yCenter_ = this.radius_ + borderWidthOffset; - this.end_[1] = this.height_; - } else { - this.start_[1] = this.height_ - borderWidthOffset; - this.yCenter_ = this.height_ - this.radius_ - borderWidthOffset; - this.end_[1] = 0; - } -}; - - -/** - * X-axis coordinate of the circle center that the rounded corner arc is - * based on. - * @type {number} - * @private - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.xCenter_; - - -/** - * Y-axis coordinate of the circle center that the rounded corner arc is - * based on. - * @type {number} - * @private - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.yCenter_; - - -/** - * Thickness constant used as an offset to help determine where to start - * rendering. - * @type {number} - */ -goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR = 1 / 2; - - -/** - * Returns the end angle of the arc for the rounded corner. - * @return {number} The end angle, in degrees or radians. - * @protected - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.getEndAngle = - goog.abstractMethod; - - -/** - * Returns the start angle of the arc for the rounded corner. - * @return {number} The start angle, in degrees or radians. - * @protected - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.getStartAngle = - goog.abstractMethod; - - -/** - * Returns the thickness offset used for accurately rendering the corner - * within its container. - * @return {number} The thickness offset, in pixels. - * @protected - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.getBorderWidthOffset = - function() { - return this.borderWidth_ * - goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR; -}; - - -/** - * Returns the underlying DOM element containing the rounded corner. - * @return {!Element} The underlying DOM element. - * @protected - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.getElement = - goog.abstractMethod; - - -/** - * Renders the rounded corner. - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.draw = goog.abstractMethod; - - -/** - * Returns the height of the element containing the rounded corner. - * @return {number} The height of the element, in pixels. - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.getHeight = function() { - return this.height_; -}; - - -/** - * Sets the height of the element containing the rounded corner. - * @param {number} height The height of the element, in pixels. - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.setHeight = function(height) { - this.height_ = height; -}; - - -/** - * Returns the width of the element containing the rounded corner. - * @return {number} The width of the element, in pixels. - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.getWidth = function() { - return this.width_; -}; - - -/** - * Sets the width of the element containing the rounded corner. - * @param {number} width The width of the element, in pixels. - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.setWidth = function(width) { - this.width_ = width; -}; - - -/** - * Returns the thickness of the rounded corner. - * @return {number} The thickness of the rounded corner, in pixels. - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.getLineWidth = - function() { - return this.borderWidth_; -}; - - -/** - * Sets the thickness of the rounded corner. - * @param {number} thickness The thickness of the rounded corner, in pixels. - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.setLineWidth = - function(thickness) { - this.borderWidth_ = thickness; -}; - - -/** - * Returns the radius of the rounded corner. - * @return {number} The radius of the rounded corner, in pixels. - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.getRadius = function() { - return this.radius_; -}; - - -/** - * Sets the radius of the rounded corner. - * @param {number} radius The radius of the rounded corner, in pixels. - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.setRadius = function(radius) { - this.radius_ = radius; -}; - - -/** - * Returns the color of the rounded corner. - * @return {string} The color of the rounded corner. - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.getBorderColor = function() { - return this.borderColor_; -}; - - -/** - * Sets the color of the rounded corner. - * @param {string} borderColor The color of the rounded corner. - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.setBorderColor = - function(borderColor) { - this.borderColor_ = borderColor; -}; - - -/** - * Returns the background color of the rounded corner. - * @return {string|undefined} The background color of the rounded corner. - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.getBackgroundColor = - function() { - return this.backgroundColor_; -}; - - -/** - * Sets the background color of the rounded corner. - * @param {string} backgroundColor The background color of the rounded corner. - */ -goog.ui.AbstractImagelessRoundedCorner.prototype.setBackgroundColor = - function(backgroundColor) { - this.backgroundColor_ = backgroundColor; -}; - - - -/** - * Class for rendering a Canvas-based rounded corner (Gecko and Safari3+). - * Horizontal and/or vertical fillers are added if the radius of the rounded - * corner is less than the width and/or height of the containing element. - * The line is drawn as a single, continuous line, starting with the horizontal - * filler, then the arc, then finishing with the vertical filler. - * Do not instantiate this class directly. Instead, use - * goog.ui.ImagelessRoundedCorner.create(). - * @param {!Element} element The element to be turned into a rounded corner. - * @param {number} width The width of the element excluding the border, in - * pixels. - * @param {number} height The height of the element excluding the border, in - * pixels. - * @param {number} borderWidth The thickness of the rounded corner, in pixels. - * @param {number} radius The radius of the rounded corner, in pixels. The - * radius must be less than or equal to the width or height (whichever - * is greater). - * @param {goog.ui.ImagelessRoundedCorner.Corner} location Location of the - * rounded corner. - * @param {string} borderColor The color of the rounded corner. - * @param {string=} opt_backgroundColor The background color of the rounded - * corner. - * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the - * document we want to render in. - * @constructor - * @extends {goog.ui.AbstractImagelessRoundedCorner} - */ -goog.ui.CanvasRoundedCorner = function(element, - width, - height, - borderWidth, - radius, - location, - borderColor, - opt_backgroundColor, - opt_domHelper) { - goog.ui.AbstractImagelessRoundedCorner.call(this, - element, - width, - height, - borderWidth, - radius, - location, - borderColor, - opt_backgroundColor, - opt_domHelper); - - /** - * The canvas containing the rounded corner. - * @type {!Element} - * @private - */ - this.canvas_ = this.domHelper_.createDom('canvas', { - 'height' : height, - 'width' : width - }); - - // If background color is defined, adjust the current end point, define the - // opposite corner, and end at the start offset. Account for thickness - // offsets in these calculations. The enclosed area will be filled by - // backgroundColor - if (this.backgroundColor_) { - var borderWidthOffset = this.getBorderWidthOffset(); - this.oppositeCorner_ = []; - - // Move one pixel more in the direction the line is being drawn. Then draw - // a line to the opposite corner + the diagonal offset. Then draw a line - // to the start, offset by 1px. - if (this.isLeft_) { - this.oppositeCorner_[0] = this.width_ + borderWidthOffset; - this.xStartOffset_ = this.start_[0] + borderWidthOffset; - } else { - this.oppositeCorner_[0] = -borderWidthOffset; - this.xStartOffset_ = -borderWidthOffset; - } - if (this.isTop_) { - this.end_[1] += borderWidthOffset; - this.oppositeCorner_[1] = this.height_ + borderWidthOffset; - } else { - this.end_[1] -= borderWidthOffset; - this.oppositeCorner_[1] = -borderWidthOffset; - } - } - - // Safari requires the canvas to be added to the DOM before defining the - // graphics context. Otherwise, rendering will fail. - this.domHelper_.appendChild(this.element_, this.canvas_); -}; -goog.inherits(goog.ui.CanvasRoundedCorner, - goog.ui.AbstractImagelessRoundedCorner); - - -/** - * The x and y coordinates of the corner opposite the rounded corner arc, - * with the stroke thickness offset added. This is defined if - * backgroundColor_ is defined. - * @type {Array.<number>} - * @private - */ -goog.ui.CanvasRoundedCorner.prototype.oppositeCorner_; - - -/** - * The x coordinate of the path's end, when enclosing the path. This is - * defined if backgroundColor_ is defined. - * @type {number} - * @private - */ -goog.ui.CanvasRoundedCorner.prototype.xStartOffset_; - - -/** - * Half a radian. - * @type {number} - * @private - */ -goog.ui.CanvasRoundedCorner.RADIANS_HALF_ = Math.PI / 2; - - -/** - * One radian. - * @type {number} - * @private - */ -goog.ui.CanvasRoundedCorner.RADIANS_ONE_ = Math.PI; - - -/** - * Three halves of a radian. - * @type {number} - * @private - */ -goog.ui.CanvasRoundedCorner.RADIANS_THREE_HALVES_ = 1.5 * Math.PI; - - -/** - * Two radians. - * @type {number} - * @private - */ -goog.ui.CanvasRoundedCorner.RADIANS_TWO_ = 2 * Math.PI; - - -/** @override */ -goog.ui.CanvasRoundedCorner.prototype.getEndAngle = function() { - return this.isLeft_ ? - goog.ui.CanvasRoundedCorner.RADIANS_ONE_ : - goog.ui.CanvasRoundedCorner.RADIANS_TWO_; -}; - - -/** @override */ -goog.ui.CanvasRoundedCorner.prototype.getStartAngle = function() { - return this.isTop_ ? - goog.ui.CanvasRoundedCorner.RADIANS_THREE_HALVES_ : - goog.ui.CanvasRoundedCorner.RADIANS_HALF_; -}; - - -/** @override */ -goog.ui.CanvasRoundedCorner.prototype.getElement = function() { - return this.canvas_; -}; - - -/** @override */ -goog.ui.CanvasRoundedCorner.prototype.draw = function() { - // Determine which direction to draw, and obtain the context. - var counterClockwise = this.isLeft_ && this.isTop_ || - !this.isLeft_ && !this.isTop_; - var context = this.canvas_.getContext('2d'); - - var version = parseFloat(goog.userAgent.VERSION); - if (goog.userAgent.WEBKIT && - goog.userAgent.isVersion('500') && - this.oppositeCorner_ && - this.xStartOffset_) { - // For Safari2, we must render the rounded corner differently when - // backgroundColor_ is specified. Safari2 cannot render the stroke using - // one color, while filling the enclosed path with another color. - this.drawSafari2WithBackground_(context, counterClockwise); - } else { - // Specify the stroke style and line width. - context.strokeStyle = this.borderColor_; - context.lineWidth = this.borderWidth_; - - // Draw the defined path. - context.beginPath(); - context.moveTo(this.start_[0], this.start_[1]); - context.arc(this.xCenter_, - this.yCenter_, - this.radius_, - this.startAngle_, - this.endAngle_, - counterClockwise); - context.lineTo(this.end_[0], this.end_[1]); - - // If backgroundColor_ is defined, render and enclose the rest of the path, - // and fill the background. - if (this.oppositeCorner_ && this.xStartOffset_) { - context.lineTo(this.oppositeCorner_[0], - this.oppositeCorner_[1]); - context.lineTo(this.xStartOffset_, - this.start_[1]); - context.closePath(); - context.fillStyle = this.backgroundColor_; - context.fill(); - } - - // Render the defined path. - context.stroke(); - } -}; - - -/** - * Safari2-specific implementation for rendering a rounded corner with - * a background color. The background is filled, followed by the rounded - * corner path. - * @param {Object} context Graphics context used for drawing. - * @param {boolean} counterClockwise Specify true to draw in a - * counter-clockwise direction, and false to draw clockwise. - * @private - */ -goog.ui.CanvasRoundedCorner.prototype.drawSafari2WithBackground_ = - function(context, counterClockwise) { - // If backgroundColor_ is defined, outline the path, - // and fill the enclosed area. - if (this.oppositeCorner_ && this.xStartOffset_) { - // Draw the defined path. - context.strokeStyle = this.backgroundColor_; - context.lineWidth = 1; - context.beginPath(); - context.moveTo(this.start_[0], this.start_[1]); - context.arc(this.xCenter_, - this.yCenter_, - this.radius_, - this.startAngle_, - this.endAngle_, - counterClockwise); - context.lineTo(this.end_[0], this.end_[1]); - context.lineTo(this.oppositeCorner_[0], - this.oppositeCorner_[1]); - context.lineTo(this.xStartOffset_, - this.start_[1]); - context.closePath(); - context.fillStyle = this.backgroundColor_; - context.fill(); - } - - // Draw the rounded corner arc and filler(s). - context.strokeStyle = this.borderColor_; - context.borderWidth = this.borderWidth_; - context.beginPath(); - context.moveTo(this.start_[0], this.start_[1]); - context.arc(this.xCenter_, - this.yCenter_, - this.radius_, - this.startAngle_, - this.endAngle_, - counterClockwise); - context.lineTo(this.end_[0], this.end_[1]); - context.stroke(); -}; - - - -/** - * Class for rendering an imageless, VML-based rounded corner. Horizontal - * and/or vertical fillers are added if the radius of the rounded corner is less - * than the width and/or height of the containing element. The line is drawn as - * a single, continuous line, starting with the horizontal filler, then the arc, - * then finishing with the vertical filler. Do not instantiate this class - * directly. Instead, use goog.ui.ImagelessRoundedCorner.create(). - * @param {!Element} element The element to be turned into a rounded corner. - * @param {number} width The width of the element excluding the border, in - * pixels. - * @param {number} height The height of the element excluding the border, in - * pixels. - * @param {number} borderWidth The thickness of the rounded corner, in pixels. - * @param {number} radius The radius of the rounded corner, in pixels. The - * radius must be less than or equal to the width or height (whichever - * is greater). - * @param {goog.ui.ImagelessRoundedCorner.Corner} location Location of the - * rounded corner. - * @param {string} borderColor The color of the rounded corner. - * @param {string=} opt_backgroundColor The background color of the rounded - * corner. - * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the - * document we want to render in. - * @constructor - * @extends {goog.ui.AbstractImagelessRoundedCorner} - */ -goog.ui.VmlRoundedCorner = function(element, - width, - height, - borderWidth, - radius, - location, - borderColor, - opt_backgroundColor, - opt_domHelper) { - goog.ui.AbstractImagelessRoundedCorner.call(this, - element, - width, - height, - borderWidth, - radius, - location, - borderColor, - opt_backgroundColor, - opt_domHelper); - - // An offset is subtracted to accommodate the subpixel rendering calculations - // specific to VmlGraphics. - this.start_[0] -= goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR; - this.end_[0] -= goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR; - this.xCenter_ -= goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR; - this.start_[1] -= goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR; - this.end_[1] -= goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR; - this.yCenter_ -= goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR; - - /** - * VML wrapper API object. - * @type {!goog.graphics.VmlGraphics} - * @private - */ - this.graphics_ = new goog.graphics.VmlGraphics(this.width_, - this.height_, - this.width_, - this.height_, - this.domHelper_); - /** - * Container element that will contain the actual rounded corner. - * @type {!Element} - * @private - */ - this.container_ = this.domHelper_.createDom('div', { - 'style' : 'overflow:hidden;position:relative;' + - 'width:' + this.width_ + 'px;' + - 'height:' + this.height_ + 'px;' - }); -}; -goog.inherits(goog.ui.VmlRoundedCorner, goog.ui.AbstractImagelessRoundedCorner); - - -/** @override */ -goog.ui.VmlRoundedCorner.prototype.getEndAngle = function() { - return this.isLeft_ ? 180 : 360; -}; - - -/** @override */ -goog.ui.VmlRoundedCorner.prototype.getStartAngle = function() { - return this.isTop_ ? 270 : 90; -}; - - -/** @override */ -goog.ui.VmlRoundedCorner.prototype.getElement = function() { - return this.container_; -}; - - -/** @override */ -goog.ui.VmlRoundedCorner.prototype.draw = function() { - // Determine which direction to draw, and enable VML. - var clockwise = this.isLeft_ && !this.isTop_ || - !this.isLeft_ && this.isTop_; - this.graphics_.createDom(); - - // If needed, fill the background color. - if (this.backgroundColor_) { - this.drawBackground_(clockwise); - } - - // Draw the defined path. - var path = new goog.graphics.Path(); - path.moveTo(this.start_[0], this.start_[1]); - path.arc(this.xCenter_, - this.yCenter_, - this.radius_, - this.radius_, - this.startAngle_, - clockwise ? 90 : -90, - true); - path.lineTo(this.end_[0], this.end_[1]); - var stroke = new goog.graphics.Stroke(this.borderWidth_, - this.borderColor_); - this.graphics_.drawPath(path, stroke, null); - - // Extract the shape node, append it to the container, and set the - // container styles. Then append the container to the DOM. - var shapeNode = this.extractShapeNode_(); - this.domHelper_.appendChild(this.container_, shapeNode); - this.domHelper_.appendChild(this.element_, this.container_); -}; - - -/** - * Renders a 1-coordinate wide path, following the same path as the rounded - * corner, then going along the adjacent horizontal edge, then along the - * adjacent vertical edge, and back to the start of the rounded corner path. - * @param {boolean} clockwise Use true to render the arc in a clockwise - * direction, and false in the counter-clockwise direction. - * @private - */ -goog.ui.VmlRoundedCorner.prototype.drawBackground_ = - function(clockwise) { - // Calculate key points in the path: the end of the arc, the corner opposite - // the arc, and the end of the path. - var arcEnd = []; - arcEnd[0] = this.isLeft_ ? - goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR : - this.width_ - goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR; - arcEnd[1] = this.isTop_ ? - this.height_ - - goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR : - goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR; - var oppositeCorner = []; - oppositeCorner[0] = this.isLeft_ ? - this.width_ - goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR : - goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR; - oppositeCorner[1] = arcEnd[1]; - var endX = this.isLeft_ ? - this.start_[0] - - goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR : - goog.ui.AbstractImagelessRoundedCorner.BORDER_WIDTH_FACTOR; - var path = new goog.graphics.Path(); - - // Draw out the path according to the points just defined. - path.moveTo(this.start_[0], this.start_[1]); - path.arc(this.xCenter_, - this.yCenter_, - this.radius_, - this.radius_, - this.startAngle_, - clockwise ? 90 : -90, - true); - path.lineTo(arcEnd[0], arcEnd[1]); - path.lineTo(oppositeCorner[0], - oppositeCorner[1]); - path.lineTo(endX, - this.start_[1]); - - // Render the path and fill, then append the generated path to the DOM. - var stroke = new goog.graphics.Stroke(1, - /** @type {string} */ (this.backgroundColor_)); - var fill = new goog.graphics.SolidFill( - /** @type {string} */ (this.backgroundColor_), 1); - this.graphics_.drawPath(path, stroke, fill); - var shapeNode = this.extractShapeNode_(); - this.domHelper_.appendChild(this.container_, shapeNode); -}; - - -/** - * Helper method that extracts the 'shape' node from the private - * goog.graphics.VmlGraphics instance, sets the size to this.width_ and - * this.height_, and sets the position to (0, 0). - * @return {Element} The VML shape element. - * @private - */ -goog.ui.VmlRoundedCorner.prototype.extractShapeNode_ = function() { - var shapeNode = /** @type {Element} */ ( - goog.dom.findNode(this.graphics_.getElement(), - goog.ui.VmlRoundedCorner.isShapeNode_)); - goog.style.setSize(shapeNode, - this.width_, - this.height_); - goog.style.setPosition(shapeNode, 0, 0); - return shapeNode; -}; - - -/** - * Indicates if the specified node is a 'shape' node. - * @param {Node} node The DOM node to inspect. - * @return {boolean} true if the node is an element node with the name 'shape', - * and false otherwise. - * @private - */ -goog.ui.VmlRoundedCorner.isShapeNode_ = function(node) { - return node.nodeType == goog.dom.NodeType.ELEMENT && - node.nodeName == 'shape'; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/inputdatepicker.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/inputdatepicker.js.svn-base deleted file mode 100644 index 1976d20..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/inputdatepicker.js.svn-base +++ /dev/null @@ -1,306 +0,0 @@ -// 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 Input Date Picker implementation. Pairs a - * goog.ui.PopupDatePicker with an input element and handles the input from - * either. - * - * @see ../demos/inputdatepicker.html - */ - -goog.provide('goog.ui.InputDatePicker'); - -goog.require('goog.date.DateTime'); -goog.require('goog.dom'); -goog.require('goog.i18n.DateTimeParse'); -goog.require('goog.string'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.PopupDatePicker'); - - - -/** - * Input date picker widget. - * - * @param {goog.i18n.DateTimeFormat} dateTimeFormatter A formatter instance - * used to format the date picker's date for display in the input element. - * @param {goog.i18n.DateTimeParse} dateTimeParser A parser instance used to - * parse the input element's string as a date to set the picker. - * @param {goog.ui.DatePicker=} opt_datePicker Optional DatePicker. This - * enables the use of a custom date-picker instance. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @extends {goog.ui.Component} - * @constructor - */ -goog.ui.InputDatePicker = function( - dateTimeFormatter, dateTimeParser, opt_datePicker, opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - - this.dateTimeFormatter_ = dateTimeFormatter; - this.dateTimeParser_ = dateTimeParser; - - this.popupDatePicker_ = new goog.ui.PopupDatePicker( - opt_datePicker, opt_domHelper); - this.addChild(this.popupDatePicker_); - this.popupDatePicker_.setAllowAutoFocus(false); -}; -goog.inherits(goog.ui.InputDatePicker, goog.ui.Component); - - -/** - * Used to format the date picker's date for display in the input element. - * @type {goog.i18n.DateTimeFormat} - * @private - */ -goog.ui.InputDatePicker.prototype.dateTimeFormatter_ = null; - - -/** - * Used to parse the input element's string as a date to set the picker. - * @type {goog.i18n.DateTimeParse} - * @private - */ -goog.ui.InputDatePicker.prototype.dateTimeParser_ = null; - - -/** - * The instance of goog.ui.PopupDatePicker used to pop up and select the date. - * @type {goog.ui.PopupDatePicker} - * @private - */ -goog.ui.InputDatePicker.prototype.popupDatePicker_ = null; - - -/** - * The element that the PopupDatePicker should be parented to. Defaults to the - * body element of the page. - * @type {Element} - * @private - */ -goog.ui.InputDatePicker.prototype.popupParentElement_ = null; - - -/** - * Returns the PopupDatePicker's internal DatePicker instance. This can be - * used to customize the date picker's styling. - * - * @return {goog.ui.DatePicker} The internal DatePicker instance. - */ -goog.ui.InputDatePicker.prototype.getDatePicker = function() { - return this.popupDatePicker_.getDatePicker(); -}; - - -/** - * Returns the selected date, if any. Compares the dates from the date picker - * and the input field, causing them to be synced if different. - * @return {goog.date.Date?} The selected date, if any. - */ -goog.ui.InputDatePicker.prototype.getDate = function() { - - // The user expectation is that the date be whatever the input shows. - // This method biases towards the input value to conform to that expectation. - - var inputDate = this.getInputValueAsDate_(); - var pickerDate = this.popupDatePicker_.getDate(); - - if (inputDate && pickerDate) { - if (!inputDate.equals(pickerDate)) { - this.popupDatePicker_.setDate(inputDate); - } - } else { - this.popupDatePicker_.setDate(null); - } - - return inputDate; -}; - - -/** - * Sets the selected date. See goog.ui.PopupDatePicker.setDate(). - * @param {goog.date.Date?} date The date to set. - */ -goog.ui.InputDatePicker.prototype.setDate = function(date) { - this.popupDatePicker_.setDate(date); -}; - - -/** - * Sets the value of the input element. This can be overridden to support - * alternative types of input setting. - * - * @param {string} value The value to set. - */ -goog.ui.InputDatePicker.prototype.setInputValue = function(value) { - var el = this.getElement(); - if (el.labelInput_) { - el.labelInput_.setValue(value); - } else { - el.value = value; - } -}; - - -/** - * Returns the value of the input element. This can be overridden to support - * alternative types of input getting. - * - * @return {string} The input value. - */ -goog.ui.InputDatePicker.prototype.getInputValue = function() { - var el = this.getElement(); - if (el.labelInput_) { - return el.labelInput_.getValue(); - } else { - return el.value; - } -}; - - -/** - * Gets the input element value and attempts to parse it as a date. - * - * @return {goog.date.Date?} The date object is returned if the parse - * is successful, null is returned on failure. - * @private - */ -goog.ui.InputDatePicker.prototype.getInputValueAsDate_ = function() { - var value = goog.string.trim(this.getInputValue()); - if (value) { - var date = new goog.date.DateTime(); - // DateTime needed as parse assumes it can call getHours(), getMinutes(), - // etc, on the date if hours and minutes aren't defined. - if (this.dateTimeParser_.strictParse(value, date) > 0) { - return date; - } - } - - return null; -}; - - -/** - * Creates an input element for use with the popup date picker. - */ -goog.ui.InputDatePicker.prototype.createDom = function() { - this.setElementInternal( - this.getDomHelper().createDom('input', {'type': 'text'})); - this.popupDatePicker_.createDom(); -}; - - -/** - * Sets the element that the PopupDatePicker should be parented to. If not set, - * defaults to the body element of the page. - * @param {Element} el The element that the PopupDatePicker should be parented - * to. - */ -goog.ui.InputDatePicker.prototype.setPopupParentElement = function(el) { - this.popupParentElement_ = el; -}; - - -/** - * Called when the DOM for the component is for sure in the document. - */ -goog.ui.InputDatePicker.prototype.enterDocument = function() { - goog.ui.InputDatePicker.superClass_.enterDocument.call(this); - var el = this.getElement(); - - (this.popupParentElement_ || this.getDomHelper().getDocument().body). - appendChild(this.popupDatePicker_.getElement()); - this.popupDatePicker_.enterDocument(); - this.popupDatePicker_.attach(el); - - // Set the date picker to have the input's initial value, if any. - this.popupDatePicker_.setDate(this.getInputValueAsDate_()); - - var handler = this.getHandler(); - handler.listen(this.popupDatePicker_, goog.ui.DatePicker.Events.CHANGE, - this.onDateChanged_); - handler.listen(this.popupDatePicker_, goog.ui.PopupBase.EventType.SHOW, - this.onPopup_); -}; - - -/** - * Called when the DOM for the component is removed from the document or - * when the component no longer is managing the DOM. - */ -goog.ui.InputDatePicker.prototype.exitDocument = function() { - goog.ui.InputDatePicker.superClass_.exitDocument.call(this); - var el = this.getElement(); - - this.popupDatePicker_.detach(el); - this.popupDatePicker_.exitDocument(); - goog.dom.removeNode(this.popupDatePicker_.getElement()); -}; - - -/** @override */ -goog.ui.InputDatePicker.prototype.decorateInternal = function(element) { - goog.ui.InputDatePicker.superClass_.decorateInternal.call(this, element); - - this.popupDatePicker_.createDom(); -}; - - -/** @override */ -goog.ui.InputDatePicker.prototype.disposeInternal = function() { - goog.ui.InputDatePicker.superClass_.disposeInternal.call(this); - this.popupDatePicker_.dispose(); - this.popupDatePicker_ = null; - this.popupParentElement_ = null; -}; - - -/** - * See goog.ui.PopupDatePicker.showPopup(). - * @param {Element} element Reference element for displaying the popup -- popup - * will appear at the bottom-left corner of this element. - */ -goog.ui.InputDatePicker.prototype.showForElement = function(element) { - this.popupDatePicker_.showPopup(element); -}; - - -/** - * See goog.ui.PopupDatePicker.hidePopup(). - */ -goog.ui.InputDatePicker.prototype.hidePopup = function() { - this.popupDatePicker_.hidePopup(); -}; - - -/** - * Event handler for popup date picker popup events. - * - * @param {goog.events.Event} e popup event. - * @private - */ -goog.ui.InputDatePicker.prototype.onPopup_ = function(e) { - this.setDate(this.getInputValueAsDate_()); -}; - - -/** - * Event handler for date change events. Called when the date changes. - * - * @param {goog.ui.DatePickerEvent} e Date change event. - * @private - */ -goog.ui.InputDatePicker.prototype.onDateChanged_ = function(e) { - this.setInputValue(e.date ? this.dateTimeFormatter_.format(e.date) : ''); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/inputdatepicker_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/inputdatepicker_test.html.svn-base deleted file mode 100644 index d765b53..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/inputdatepicker_test.html.svn-base +++ /dev/null @@ -1,109 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: bolinfest@google.com (Michael Bolin) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.InputDatePicker</title> - <script src="../base.js"></script> - <script> - goog.require('goog.ui.InputDatePicker'); - goog.require('goog.testing.jsunit'); - </script> -</head> -<body> - -<div id="renderElement"></div> -<div id="popupParent"></div> - -<script> - var dateTimeFormatter = new goog.i18n.DateTimeFormat('MM/dd/yyyy'); - var dateTimeParser = new goog.i18n.DateTimeParse('MM/dd/yyyy'); - - var inputDatePicker; - var popupDatePicker; - - function setUp() { - } - - function tearDown() { - if (inputDatePicker) { - inputDatePicker.dispose(); - } - if (popupDatePicker) { - popupDatePicker.dispose(); - } - goog.dom.getElement('renderElement').innerHTML = ''; - goog.dom.getElement('popupParent').innerHTML = ''; - } - - /** - * Ensure that if setPopupParentElement is not called, that the - * PopupDatePicker is parented to the body element. - */ - function test_setPopupParentElementDefault() { - setPopupParentElement_(null); - assertEquals('PopupDatePicker should be parented to the body element', - document.body, - popupDatePicker.getElement().parentNode); - } - - /** - * Ensure that if setPopupParentElement is called, that the - * PopupDatePicker is parented to the specified element. - */ - function test_setPopupParentElement() { - var popupParentElement = goog.dom.getElement('popupParent'); - setPopupParentElement_(popupParentElement); - assertEquals('PopupDatePicker should be parented to the popupParent DIV', - popupParentElement, - popupDatePicker.getElement().parentNode); - } - - /** - * Creates a new InputDatePicker and calls setPopupParentElement with the - * specified element, if provided. If el is null, then setPopupParentElement - * is not called. - * @param {Element} el If non-null, the argument to pass to - * inputDatePicker.setPopupParentElement(). - * @private - */ - function setPopupParentElement_(el) { - inputDatePicker = new goog.ui.InputDatePicker( - dateTimeFormatter, - dateTimeParser); - - if (el) { - inputDatePicker.setPopupParentElement(el); - } - - inputDatePicker.render(goog.dom.getElement('renderElement')); - popupDatePicker = inputDatePicker.popupDatePicker_; - } - - - function test_ItParsesDataCorrectly() { - inputDatePicker = new goog.ui.InputDatePicker( - dateTimeFormatter, - dateTimeParser); - inputDatePicker.render(goog.dom.getElement('renderElement')); - - inputDatePicker.createDom(); - inputDatePicker.setInputValue('8/9/2009'); - - var parsedDate = inputDatePicker.getInputValueAsDate_(); - assertEquals(2009, parsedDate.getYear()); - assertEquals(7, parsedDate.getMonth()); // Months start from 0 - assertEquals(9, parsedDate.getDate()); - } -</script> - -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/itemevent.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/itemevent.js.svn-base deleted file mode 100644 index d297b0c..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/itemevent.js.svn-base +++ /dev/null @@ -1,50 +0,0 @@ -// 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 goog.ui.ItemEvent class. - * - */ - -goog.provide('goog.ui.ItemEvent'); - - -goog.require('goog.events.Event'); - - - -/** - * Generic ui event class for events that take a single item like a menu click - * event. - * - * @constructor - * @extends {goog.events.Event} - * @param {string} type Event Type. - * @param {Object} target Reference to the object that is the target - * of this event. - * @param {Object} item The item that was clicked. - */ -goog.ui.ItemEvent = function(type, target, item) { - goog.events.Event.call(this, type, target); - - /** - * Item for the event. The type of this object is specific to the type - * of event. For a menu, it would be the menu item that was clicked. For a - * listbox selection, it would be the listitem that was selected. - * - * @type {Object} - */ - this.item = item; -}; -goog.inherits(goog.ui.ItemEvent, goog.events.Event); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/keyboardshortcuthandler.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/keyboardshortcuthandler.js.svn-base deleted file mode 100644 index adfdff0..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/keyboardshortcuthandler.js.svn-base +++ /dev/null @@ -1,979 +0,0 @@ -// 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. - * - * @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_); - - /** - * 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 -]; - - -/** - * 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.<number>} 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 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_(event.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' && (el.type == 'text' || el.type == 'password')) { - 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); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/keyboardshortcuthandler_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/keyboardshortcuthandler_test.html.svn-base deleted file mode 100644 index bd679dc..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/keyboardshortcuthandler_test.html.svn-base +++ /dev/null @@ -1,672 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <!-- Author: gboyer@google.com (Garrett Boyer) --> - <title>Closure Unit Tests - goog.ui.KeyboardShortcutHandler</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.testing.MockClock'); - goog.require('goog.testing.PropertyReplacer'); - goog.require('goog.testing.StrictMock'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.KeyboardShortcutHandler'); - </script> -</head> -<body> - <div id="rootDiv"> - <div id="targetDiv">The test presses keys on me!</div> - <input type="text" id="targetTextBox" value="text box"> - <input type="password" id="targetPassword" value="password"> - <input type="checkbox" id="targetCheckBox"> - <textarea id="targetTextArea">text area</textarea> - <select id="targetSelect"><option>select</option></select> - <button id="targetButton">A Button</button> - </div> - <script> - var Modifiers = goog.ui.KeyboardShortcutHandler.Modifiers; - var KeyCodes = goog.events.KeyCodes; - - var handler; - var targetDiv; - var listener; - var mockClock; - var stubs = new goog.testing.PropertyReplacer(); - - /** - * Fires a keypress on the target div. - * @return {boolean} The returnValue of the sequence: false if - * preventDefault() was called on any of the events, true otherwise. - */ - function fire(keycode, opt_extraProperties, opt_element) { - return goog.testing.events.fireKeySequence( - opt_element || targetDiv, keycode, opt_extraProperties); - } - - function fireAltGraphKey(keycode, keyPressKeyCode, opt_extraProperties, - opt_element) { - return goog.testing.events.fireNonAsciiKeySequence( - opt_element || targetDiv, keycode, keyPressKeyCode, - opt_extraProperties); - } - - function setUp() { - targetDiv = goog.dom.getElement('targetDiv'); - handler = new goog.ui.KeyboardShortcutHandler( - goog.dom.getElement('rootDiv')); - - // Create a mock event listener in order to set expectations on what - // events are fired. We create a fake class whose only method is - // shortcutFired(shortcut identifier). - listener = new goog.testing.StrictMock( - {shortcutFired: goog.nullFunction}); - goog.events.listen( - handler, - goog.ui.KeyboardShortcutHandler.EventType.SHORTCUT_TRIGGERED, - function (event) { listener.shortcutFired(event.identifier); }); - - // Set up a fake clock, because keyboard shortcuts *are* time - // sensitive. - mockClock = new goog.testing.MockClock(true); - } - - function tearDown() { - mockClock.uninstall(); - handler.dispose(); - stubs.reset(); - } - - function testAllowsSingleLetterKeyBindingsSpecifiedAsString() { - listener.shortcutFired('lettergee'); - listener.$replay(); - - handler.registerShortcut('lettergee', 'g'); - fire(KeyCodes.G); - - listener.$verify() - } - - function testAllowsSingleLetterKeyBindingsSpecifiedAsKeyCode() { - listener.shortcutFired('lettergee'); - listener.$replay(); - - handler.registerShortcut('lettergee', KeyCodes.G); - fire(KeyCodes.G); - - listener.$verify() - } - - function testDoesntFireWhenWrongKeyIsPressed() { - listener.$replay(); // no events expected - - handler.registerShortcut('letterjay', 'j'); - fire(KeyCodes.G); - - listener.$verify() - } - - function testAllowsControlAndLetterSpecifiedAsAString() { - listener.shortcutFired('lettergee'); - listener.$replay(); - - handler.registerShortcut('lettergee', 'ctrl+g'); - fire(KeyCodes.G, {ctrlKey: true}); - - listener.$verify() - } - - function testAllowsControlAndLetterSpecifiedAsArgSequence() { - listener.shortcutFired('lettergeectrl'); - listener.$replay(); - - handler.registerShortcut('lettergeectrl', - KeyCodes.G, Modifiers.CTRL); - fire(KeyCodes.G, {ctrlKey: true}); - - listener.$verify() - } - - function testAllowsControlAndLetterSpecifiedAsArray() { - listener.shortcutFired('lettergeectrl'); - listener.$replay(); - - handler.registerShortcut('lettergeectrl', - [KeyCodes.G, Modifiers.CTRL]); - fire(KeyCodes.G, {ctrlKey: true}); - - listener.$verify() - } - - function testAllowsShift() { - listener.shortcutFired('lettergeeshift'); - listener.$replay(); - - handler.registerShortcut('lettergeeshift', - [KeyCodes.G, Modifiers.SHIFT]); - fire(KeyCodes.G, {shiftKey: true}); - - listener.$verify() - } - - function testAllowsAlt() { - listener.shortcutFired('lettergeealt'); - listener.$replay(); - - handler.registerShortcut('lettergeealt', - [KeyCodes.G, Modifiers.ALT]); - fire(KeyCodes.G, {altKey: true}); - - listener.$verify() - } - - function testAllowsMeta() { - listener.shortcutFired('lettergeemeta'); - listener.$replay(); - - handler.registerShortcut('lettergeemeta', - [KeyCodes.G, Modifiers.META]); - fire(KeyCodes.G, {metaKey: true}); - - listener.$verify() - } - - function testAllowsMultipleModifiers() { - listener.shortcutFired('lettergeectrlaltshift'); - listener.$replay(); - - handler.registerShortcut('lettergeectrlaltshift', - KeyCodes.G, Modifiers.CTRL | Modifiers.ALT | Modifiers.SHIFT); - fire(KeyCodes.G, {ctrlKey: true, altKey: true, shiftKey: true}); - - listener.$verify() - } - - function testAllowsMultipleModifiersSpecifiedAsString() { - listener.shortcutFired('lettergeectrlaltshiftmeta'); - listener.$replay(); - - handler.registerShortcut('lettergeectrlaltshiftmeta', - 'ctrl+shift+alt+meta+g'); - fire(KeyCodes.G, - {ctrlKey: true, altKey: true, shiftKey: true, metaKey: true}); - - listener.$verify() - } - - function testPreventsDefaultOnReturnFalse() { - listener.shortcutFired('x'); - listener.$replay(); - - handler.registerShortcut('x', 'x'); - var key = goog.events.listen(handler, - goog.ui.KeyboardShortcutHandler.EventType.SHORTCUT_TRIGGERED, - function (event) { return false }); - - assertFalse('return false in listener must prevent default', - fire(KeyCodes.X)); - - listener.$verify(); - - goog.events.unlistenByKey(key); - } - - function testPreventsDefaultWhenExceptionThrown() { - handler.registerShortcut('x', 'x'); - handler.setAlwaysPreventDefault(true); - goog.events.listenOnce(handler, - goog.ui.KeyboardShortcutHandler.EventType.SHORTCUT_TRIGGERED, - function (event) { throw new Error('x'); }); - - // We can't use the standard infrastructure to detect that - // the event was preventDefaulted, because of the exception. - var callCount = 0; - stubs.set(goog.events.BrowserEvent.prototype, 'preventDefault', - function() { - callCount++; - }); - - var e = assertThrows(goog.partial(fire, KeyCodes.X)); - assertEquals('x', e.message); - - assertEquals(1, callCount); - } - - function testDoesntFireWhenUserForgetsRequiredModifier() { - listener.$replay(); // no events expected - - handler.registerShortcut('lettergeectrl', - KeyCodes.G, Modifiers.CTRL); - fire(KeyCodes.G); - - listener.$verify() - } - - function testDoesntFireIfTooManyModifiersPressed() { - listener.$replay(); // no events expected - - handler.registerShortcut('lettergeectrl', - KeyCodes.G, Modifiers.CTRL); - fire(KeyCodes.G, {ctrlKey: true, metaKey: true}); - - listener.$verify() - } - - function testDoesntFireIfAnyRequiredModifierForgotten() { - listener.$replay(); // no events expected - - handler.registerShortcut('lettergeectrlaltshift', - KeyCodes.G, Modifiers.CTRL | Modifiers.ALT | Modifiers.SHIFT); - fire(KeyCodes.G, {altKey: true, shiftKey: true}); - - listener.$verify() - } - - function testAllowsMultiKeySequenceSpecifiedAsArray() { - listener.shortcutFired('quitemacs'); - listener.$replay(); - - handler.registerShortcut('quitemacs', - [KeyCodes.X, Modifiers.CTRL, - KeyCodes.C]); - fire(KeyCodes.X, {ctrlKey: true}); - fire(KeyCodes.C); - - listener.$verify() - } - - function testAllowsMultiKeySequenceSpecifiedAsArray() { - listener.shortcutFired('quitemacs'); - listener.$replay(); - - handler.registerShortcut('quitemacs', - [KeyCodes.X, Modifiers.CTRL, - KeyCodes.C]); - fire(KeyCodes.X, {ctrlKey: true}); - fire(KeyCodes.C); - - listener.$verify() - } - - function testAllowsMultiKeySequenceSpecifiedAsArguments() { - listener.shortcutFired('quitvi'); - listener.$replay(); - - handler.registerShortcut('quitvi', - KeyCodes.COLON, Modifiers.NONE, - KeyCodes.Q, Modifiers.NONE, - KeyCodes.EXCLAMATION, Modifiers.NONE); - fire(KeyCodes.COLON); - fire(KeyCodes.Q); - fire(KeyCodes.EXCLAMATION); - - listener.$verify() - } - - function testMultiKeyEventIsNotFiredIfUserIsTooSlow() { - listener.$replay(); // no events expected - - handler.registerShortcut('quitemacs', - [KeyCodes.X, Modifiers.CTRL, - KeyCodes.C]); - - fire(KeyCodes.X, {ctrlKey: true}); - - // Wait 3 seconds before hitting C. Although the actual limit is 1500 - // at time of writing, it's best not to over-specify functionality. - mockClock.tick(3000); - - fire(KeyCodes.C); - - listener.$verify() - } - - function testAllowsMultipleAHandlers() { - listener.shortcutFired('quitvi'); - listener.shortcutFired('letterex'); - listener.shortcutFired('quitemacs'); - listener.$replay(); - - // register 3 handlers in 3 diferent ways - handler.registerShortcut('quitvi', - KeyCodes.COLON, Modifiers.NONE, - KeyCodes.Q, Modifiers.NONE, - KeyCodes.EXCLAMATION, Modifiers.NONE); - handler.registerShortcut('quitemacs', - [KeyCodes.X, Modifiers.CTRL, - KeyCodes.C]); - handler.registerShortcut('letterex', 'x'); - - - // quit vi - fire(KeyCodes.COLON); - fire(KeyCodes.Q); - fire(KeyCodes.EXCLAMATION); - - // then press the letter x - fire(KeyCodes.X); - - // then quit emacs - fire(KeyCodes.X, {ctrlKey: true}); - fire(KeyCodes.C); - - listener.$verify() - } - - function testCanRemoveOneHandler() { - listener.shortcutFired('letterex'); - listener.$replay(); - - // register 2 handlers, then remove quitvi - handler.registerShortcut('quitvi', - KeyCodes.COLON, Modifiers.NONE, - KeyCodes.Q, Modifiers.NONE, - KeyCodes.EXCLAMATION, Modifiers.NONE); - handler.registerShortcut('letterex', 'x'); - handler.unregisterShortcut( - KeyCodes.COLON, Modifiers.NONE, - KeyCodes.Q, Modifiers.NONE, - KeyCodes.EXCLAMATION, Modifiers.NONE); - - // call the "quit VI" keycodes, even though it is removed - fire(KeyCodes.COLON); - fire(KeyCodes.Q); - fire(KeyCodes.EXCLAMATION); - - // press the letter x - fire(KeyCodes.X); - - listener.$verify() - } - - function testCanRemoveTwoHandlers() { - listener.$replay(); // no events expected - - handler.registerShortcut('quitemacs', - [KeyCodes.X, Modifiers.CTRL, - KeyCodes.C]); - handler.registerShortcut('letterex', 'x'); - handler.unregisterShortcut( - [KeyCodes.X, Modifiers.CTRL, - KeyCodes.C]); - handler.unregisterShortcut('x'); - - fire(KeyCodes.X, {ctrlKey: true}); - fire(KeyCodes.C); - fire(KeyCodes.X); - - listener.$verify() - } - - function testCheckRegisteredShortcuts() { - assertFalse(handler.isShortcutRegistered('x')); - handler.registerShortcut('letterex', 'x'); - assertTrue(handler.isShortcutRegistered('x')); - - handler.registerShortcut('qe', [KeyCodes.X, Modifiers.CTRL, KeyCodes.C]); - assertTrue(handler.isShortcutRegistered('x')); - assertTrue(handler.isShortcutRegistered([KeyCodes.X, - Modifiers.CTRL, KeyCodes.C])); - handler.unregisterShortcut('x'); - assertFalse(handler.isShortcutRegistered('x')); - assertTrue(handler.isShortcutRegistered([KeyCodes.X, - Modifiers.CTRL, KeyCodes.C])); - handler.unregisterShortcut([KeyCodes.X, Modifiers.CTRL, KeyCodes.C]); - assertFalse(handler.isShortcutRegistered([KeyCodes.X, - Modifiers.CTRL, KeyCodes.C])); - } - - /** - * Registers a slew of keyboard shortcuts to test each primary category - * of shortcuts. - */ - function registerEnterSpaceXF1AltY() { - // Enter and space are specially handled keys. - handler.registerShortcut('enter', KeyCodes.ENTER); - handler.registerShortcut('space', KeyCodes.SPACE) - // 'x' should be treated as text in many contexts - handler.registerShortcut('x', 'x'); - // F1 is a global shortcut. - handler.registerShortcut('global', KeyCodes.F1); - // Alt-Y has modifiers, which pass through most form elements. - handler.registerShortcut('withAlt', 'alt+y'); - } - - /** - * Fires enter, space, X, F1, and Alt-Y keys on a widget. - * @param {Element} target The element on which to fire the events. - */ - function fireEnterSpaceXF1AltY(target) { - fire(KeyCodes.ENTER, undefined, target); - fire(KeyCodes.SPACE, undefined, target); - fire(KeyCodes.X, undefined, target); - fire(KeyCodes.F1, undefined, target); - fire(KeyCodes.Y, {altKey: true}, target); - } - - function testIgnoreNonGlobalShortcutsInSelect() { - var targetSelect = goog.dom.getElement('targetSelect'); - - listener.shortcutFired('global'); - listener.shortcutFired('withAlt'); - listener.$replay(); - - registerEnterSpaceXF1AltY(); - fireEnterSpaceXF1AltY(goog.dom.getElement('targetSelect')); - - listener.$verify(); - } - - function testIgnoreNonGlobalShortcutsInTextArea() { - listener.shortcutFired('global'); - listener.shortcutFired('withAlt'); - listener.$replay(); - - registerEnterSpaceXF1AltY(); - fireEnterSpaceXF1AltY(goog.dom.getElement('targetTextArea')); - - listener.$verify(); - } - - function testIgnoreShortcutsExceptEnterInTextBoxAndPassword() { - // Events for the text box. - listener.shortcutFired('enter'); - listener.shortcutFired('global'); - listener.shortcutFired('withAlt'); - // Events for the password field. - listener.shortcutFired('enter'); - listener.shortcutFired('global'); - listener.shortcutFired('withAlt'); - listener.$replay(); - - registerEnterSpaceXF1AltY(); - fireEnterSpaceXF1AltY(goog.dom.getElement('targetTextBox')); - fireEnterSpaceXF1AltY(goog.dom.getElement('targetPassword')); - - listener.$verify(); - } - - function testIgnoreSpaceInCheckBoxAndButton() { - // Events for the check box. - listener.shortcutFired('enter'); - listener.shortcutFired('x'); - listener.shortcutFired('global'); - listener.shortcutFired('withAlt'); - // Events for the button. - listener.shortcutFired('enter'); - listener.shortcutFired('x'); - listener.shortcutFired('global'); - listener.shortcutFired('withAlt'); - listener.$replay(); - - registerEnterSpaceXF1AltY(); - fireEnterSpaceXF1AltY(goog.dom.getElement('targetCheckBox')); - fireEnterSpaceXF1AltY(goog.dom.getElement('targetButton')); - - listener.$verify(); - } - - function testIgnoreNonGlobalShortcutsInContentEditable() { - try { - document.designMode = 'on'; - targetDiv.contentEditable = 'true'; - - // Expect only global shortcuts. - listener.shortcutFired('global'); - listener.$replay(); - - registerEnterSpaceXF1AltY(); - fireEnterSpaceXF1AltY(targetDiv); - - listener.$verify(); - } finally { - document.designMode = 'off'; - targetDiv.contentEditable = 'false'; - } - } - - function testSetAllShortcutsAreGlobal() { - listener.shortcutFired('enter'); - listener.shortcutFired('space'); - listener.shortcutFired('x'); - listener.shortcutFired('global'); - listener.shortcutFired('withAlt'); - listener.$replay(); - - registerEnterSpaceXF1AltY(); - handler.setAllShortcutsAreGlobal(true); - fireEnterSpaceXF1AltY(goog.dom.getElement('targetTextArea')); - - listener.$verify(); - } - - function testSetModifierShortcutsAreGlobalFalse() { - listener.shortcutFired('global'); - listener.$replay(); - - registerEnterSpaceXF1AltY(); - handler.setModifierShortcutsAreGlobal(false); - fireEnterSpaceXF1AltY(goog.dom.getElement('targetTextArea')); - - listener.$verify(); - } - - function testAltGraphKeyOnUSLayout() { - // Windows does not assign printable characters to any ctrl+alt keys of - // the US layout. This test verifies we fire shortcut events when typing - // ctrl+alt keys on the US layout. - listener.shortcutFired('letterOne'); - listener.shortcutFired('letterTwo'); - listener.shortcutFired('letterThree'); - listener.shortcutFired('letterFour'); - listener.shortcutFired('letterFive'); - if (goog.userAgent.WINDOWS && !goog.userAgent.GECKO) { - listener.$replay(); - - handler.registerShortcut('letterOne', 'ctrl+alt+1'); - handler.registerShortcut('letterTwo', 'ctrl+alt+2'); - handler.registerShortcut('letterThree', 'ctrl+alt+3'); - handler.registerShortcut('letterFour', 'ctrl+alt+4'); - handler.registerShortcut('letterFive', 'ctrl+alt+5'); - - // Send key events on the English (United States) layout. - fireAltGraphKey(KeyCodes.ONE, 0, {ctrlKey: true, altKey: true}); - fireAltGraphKey(KeyCodes.TWO, 0, {ctrlKey: true, altKey: true}); - fireAltGraphKey(KeyCodes.THREE, 0, {ctrlKey: true, altKey: true}); - fireAltGraphKey(KeyCodes.FOUR, 0, {ctrlKey: true, altKey: true}); - fireAltGraphKey(KeyCodes.FIVE, 0, {ctrlKey: true, altKey: true}); - - listener.$verify() - } - } - - function testAltGraphKeyOnFrenchLayout() { - // Windows assigns printable characters to ctrl+alt+[2-5] keys of the - // French layout. This test verifies we fire shortcut events only when - // we type ctrl+alt+1 keys on the French layout. - listener.shortcutFired('letterOne'); - if (goog.userAgent.WINDOWS && !goog.userAgent.GECKO) { - listener.$replay(); - - handler.registerShortcut('letterOne', 'ctrl+alt+1'); - handler.registerShortcut('letterTwo', 'ctrl+alt+2'); - handler.registerShortcut('letterThree', 'ctrl+alt+3'); - handler.registerShortcut('letterFour', 'ctrl+alt+4'); - handler.registerShortcut('letterFive', 'ctrl+alt+5'); - - // Send key events on the French (France) layout. - fireAltGraphKey(KeyCodes.ONE, 0, {ctrlKey: true, altKey: true}); - fireAltGraphKey(KeyCodes.TWO, 0x0303, {ctrlKey: true, altKey: true}); - fireAltGraphKey(KeyCodes.THREE, 0x0023, {ctrlKey: true, altKey: true}); - fireAltGraphKey(KeyCodes.FOUR, 0x007b, {ctrlKey: true, altKey: true}); - fireAltGraphKey(KeyCodes.FIVE, 0x205b, {ctrlKey: true, altKey: true}); - - listener.$verify() - } - } - - function testAltGraphKeyOnSpanishLayout() { - // Windows assigns printable characters to ctrl+alt+[1-5] keys of the - // Spanish layout. This test verifies we do not fire shortcut events at - // all when typing ctrl+alt+[1-5] keys on the Spanish layout. - if (goog.userAgent.WINDOWS && !goog.userAgent.GECKO) { - listener.$replay(); - - handler.registerShortcut('letterOne', 'ctrl+alt+1'); - handler.registerShortcut('letterTwo', 'ctrl+alt+2'); - handler.registerShortcut('letterThree', 'ctrl+alt+3'); - handler.registerShortcut('letterFour', 'ctrl+alt+4'); - handler.registerShortcut('letterFive', 'ctrl+alt+5'); - - // Send key events on the Spanish (Spain) layout. - fireAltGraphKey(KeyCodes.ONE, 0x007c, {ctrlKey: true, altKey: true}); - fireAltGraphKey(KeyCodes.TWO, 0x0040, {ctrlKey: true, altKey: true}); - fireAltGraphKey(KeyCodes.THREE, 0x0023, {ctrlKey: true, altKey: true}); - fireAltGraphKey(KeyCodes.FOUR, 0x0303, {ctrlKey: true, altKey: true}); - fireAltGraphKey(KeyCodes.FIVE, 0x20ac, {ctrlKey: true, altKey: true}); - - listener.$verify() - } - } - - function testNumpadKeyShortcuts() { - var testCases = [ - ['letterNumpad0', 'num-0', KeyCodes.NUM_ZERO], - ['letterNumpad1', 'num-1', KeyCodes.NUM_ONE], - ['letterNumpad2', 'num-2', KeyCodes.NUM_TWO], - ['letterNumpad3', 'num-3', KeyCodes.NUM_THREE], - ['letterNumpad4', 'num-4', KeyCodes.NUM_FOUR], - ['letterNumpad5', 'num-5', KeyCodes.NUM_FIVE], - ['letterNumpad6', 'num-6', KeyCodes.NUM_SIX], - ['letterNumpad7', 'num-7', KeyCodes.NUM_SEVEN], - ['letterNumpad8', 'num-8', KeyCodes.NUM_EIGHT], - ['letterNumpad9', 'num-9', KeyCodes.NUM_NINE], - ['letterNumpadMultiply', 'num-multiply', KeyCodes.NUM_MULTIPLY], - ['letterNumpadPlus', 'num-plus', KeyCodes.NUM_PLUS], - ['letterNumpadMinus', 'num-minus', KeyCodes.NUM_MINUS], - ['letterNumpadPERIOD', 'num-period', KeyCodes.NUM_PERIOD], - ['letterNumpadDIVISION', 'num-division', KeyCodes.NUM_DIVISION] - ]; - for (var i = 0; i < testCases.length; ++i) { - listener.shortcutFired(testCases[i][0]); - } - listener.$replay(); - - // Register shortcuts for numpad keys and send numpad-key events. - for (var i = 0; i < testCases.length; ++i) { - handler.registerShortcut(testCases[i][0], testCases[i][1]); - fire(testCases[i][2]); - } - listener.$verify() - } - - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/labelinput.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/labelinput.js.svn-base deleted file mode 100644 index 6b8dbd6..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/labelinput.js.svn-base +++ /dev/null @@ -1,565 +0,0 @@ -// Copyright 2006 The Closure Library Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview This behavior is applied to a text input and it shows a text - * message inside the element if the user hasn't entered any text. - * - * This uses the HTML5 placeholder attribute where it is supported. - * - * This is ported from http://go/labelinput.js - * - * Known issue: Safari does not allow you get to the window object from a - * document. We need that to listen to the onload event. For now we hard code - * the window to the current window. - * - * Known issue: We need to listen to the form submit event but we attach the - * event only once (when created or when it is changed) so if you move the DOM - * node to another form it will not be cleared correctly before submitting. - * - * Known issue: Where the placeholder attribute isn't supported, screen reader - * users encounter trouble because the label is deleted upon focus. For now we - * set the "aria-label" attribute. - * - * @author arv@google.com (Erik Arvidsson) - * @see ../demos/labelinput.html - */ - -goog.provide('goog.ui.LabelInput'); - -goog.require('goog.Timer'); -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.a11y.State'); -goog.require('goog.dom.classes'); -goog.require('goog.events.EventHandler'); -goog.require('goog.events.EventType'); -goog.require('goog.ui.Component'); -goog.require('goog.userAgent'); - - - -/** - * This creates the label input object. - * @param {string=} opt_label The text to show as the label. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @extends {goog.ui.Component} - * @constructor - */ -goog.ui.LabelInput = function(opt_label, opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - - /** - * The text to show as the label. - * @type {string} - * @private - */ - this.label_ = opt_label || ''; -}; -goog.inherits(goog.ui.LabelInput, goog.ui.Component); - - -/** - * Variable used to store the element value on keydown and restore it on - * keypress. See {@link #handleEscapeKeys_} - * @type {?string} - * @private - */ -goog.ui.LabelInput.prototype.ffKeyRestoreValue_ = null; - - -/** - * Indicates whether the browser supports the placeholder attribute, new in - * HTML5. - * @type {boolean} - * @private - */ -goog.ui.LabelInput.SUPPORTS_PLACEHOLDER_ = ( - 'placeholder' in document.createElement('input')); - - -/** - * @type {goog.events.EventHandler} - * @private - */ -goog.ui.LabelInput.prototype.eventHandler_; - - -/** - * @type {boolean} - * @private - */ -goog.ui.LabelInput.prototype.hasFocus_ = false; - - -/** - * Creates the DOM nodes needed for the label input. - */ -goog.ui.LabelInput.prototype.createDom = function() { - this.setElementInternal( - this.getDomHelper().createDom('input', {'type': 'text'})); -}; - - -/** - * Decorates an existing HTML input element as a label input. If the element - * has a "label" attribute then that will be used as the label property for the - * label input object. - * @param {HTMLInputElement} element The HTML input element to decorate. - */ -goog.ui.LabelInput.prototype.decorateInternal = function(element) { - goog.ui.LabelInput.superClass_.decorateInternal.call(this, element); - if (!this.label_) { - this.label_ = element.getAttribute('label') || ''; - } - - // Check if we're attaching to an element that already has focus. - if (goog.dom.getActiveElement(goog.dom.getOwnerDocument(element)) == - element) { - this.hasFocus_ = true; - goog.dom.classes.remove(this.getElement(), this.LABEL_CLASS_NAME); - } - - if (goog.ui.LabelInput.SUPPORTS_PLACEHOLDER_) { - this.getElement().placeholder = this.label_; - return; - } - goog.dom.a11y.setState(this.getElement(), - goog.dom.a11y.State.LABEL, - this.label_); -}; - - -/** - * Called when the DOM for the component is for sure in the document. - */ -goog.ui.LabelInput.prototype.enterDocument = function() { - goog.ui.LabelInput.superClass_.enterDocument.call(this); - this.attachEvents_(); - this.check_(); - - // Make it easy for other closure widgets to play nicely with inputs using - // LabelInput: - this.getElement().labelInput_ = this; -}; - - -/** - * Called when the DOM for the component is removed from the document or - * when the component no longer is managing the DOM. - */ -goog.ui.LabelInput.prototype.exitDocument = function() { - goog.ui.LabelInput.superClass_.exitDocument.call(this); - this.detachEvents_(); - - this.getElement().labelInput_ = null; -}; - - -/** - * Attaches the events we need to listen to. - * @private - */ -goog.ui.LabelInput.prototype.attachEvents_ = function() { - var eh = new goog.events.EventHandler(this); - eh.listen(this.getElement(), goog.events.EventType.FOCUS, this.handleFocus_); - eh.listen(this.getElement(), goog.events.EventType.BLUR, this.handleBlur_); - - if (goog.ui.LabelInput.SUPPORTS_PLACEHOLDER_) { - this.eventHandler_ = eh; - return; - } - - if (goog.userAgent.GECKO) { - eh.listen(this.getElement(), [ - goog.events.EventType.KEYPRESS, - goog.events.EventType.KEYDOWN, - goog.events.EventType.KEYUP - ], this.handleEscapeKeys_); - } - - // IE sets defaultValue upon load so we need to test that as well. - var d = goog.dom.getOwnerDocument(this.getElement()); - var w = goog.dom.getWindow(d); - eh.listen(w, goog.events.EventType.LOAD, this.handleWindowLoad_); - - this.eventHandler_ = eh; - this.attachEventsToForm_(); -}; - - -/** - * Adds a listener to the form so that we can clear the input before it is - * submitted. - * @private - */ -goog.ui.LabelInput.prototype.attachEventsToForm_ = function() { - // in case we have are in a form we need to make sure the label is not - // submitted - if (!this.formAttached_ && this.eventHandler_ && this.getElement().form) { - this.eventHandler_.listen(this.getElement().form, - goog.events.EventType.SUBMIT, - this.handleFormSubmit_); - this.formAttached_ = true; - } -}; - - -/** - * Stops listening to the events. - * @private - */ -goog.ui.LabelInput.prototype.detachEvents_ = function() { - if (this.eventHandler_) { - this.eventHandler_.dispose(); - this.eventHandler_ = null; - } -}; - - -/** @override */ -goog.ui.LabelInput.prototype.disposeInternal = function() { - goog.ui.LabelInput.superClass_.disposeInternal.call(this); - this.detachEvents_(); -}; - - -/** - * The CSS class name to add to the input when the user has not entered a - * value. - */ -goog.ui.LabelInput.prototype.LABEL_CLASS_NAME = - goog.getCssName('label-input-label'); - - -/** - * Handler for the focus event. - * @param {goog.events.Event} e The event object passed in to the event handler. - * @private - */ -goog.ui.LabelInput.prototype.handleFocus_ = function(e) { - this.hasFocus_ = true; - goog.dom.classes.remove(this.getElement(), this.LABEL_CLASS_NAME); - if (goog.ui.LabelInput.SUPPORTS_PLACEHOLDER_) { - return; - } - if (!this.hasChanged() && !this.inFocusAndSelect_) { - var me = this; - var clearValue = function() { - me.getElement().value = ''; - }; - if (goog.userAgent.IE) { - goog.Timer.callOnce(clearValue, 10); - } else { - clearValue(); - } - } -}; - - -/** - * Handler for the blur event. - * @param {goog.events.Event} e The event object passed in to the event handler. - * @private - */ -goog.ui.LabelInput.prototype.handleBlur_ = function(e) { - // We listen to the click event when we enter focusAndSelect mode so we can - // fake an artificial focus when the user clicks on the input box. However, - // if the user clicks on something else (and we lose focus), there is no - // need for an artificial focus event. - if (!goog.ui.LabelInput.SUPPORTS_PLACEHOLDER_) { - this.eventHandler_.unlisten( - this.getElement(), goog.events.EventType.CLICK, this.handleFocus_); - this.ffKeyRestoreValue_ = null; - } - this.hasFocus_ = false; - this.check_(); -}; - - -/** - * Handler for key events in Firefox. - * - * If the escape key is pressed when a text input has not been changed manually - * since being focused, the text input will revert to its previous value. - * Firefox does not honor preventDefault for the escape key. The revert happens - * after the keydown event and before every keypress. We therefore store the - * element's value on keydown and restore it on keypress. The restore value is - * nullified on keyup so that {@link #getValue} returns the correct value. - * - * IE and Chrome don't have this problem, Opera blurs in the input box - * completely in a way that preventDefault on the escape key has no effect. - * - * @param {goog.events.BrowserEvent} e The event object passed in to - * the event handler. - * @private - */ -goog.ui.LabelInput.prototype.handleEscapeKeys_ = function(e) { - if (e.keyCode == 27) { - if (e.type == goog.events.EventType.KEYDOWN) { - this.ffKeyRestoreValue_ = this.getElement().value; - } else if (e.type == goog.events.EventType.KEYPRESS) { - this.getElement().value = /** @type {string} */ (this.ffKeyRestoreValue_); - } else if (e.type == goog.events.EventType.KEYUP) { - this.ffKeyRestoreValue_ = null; - } - e.preventDefault(); - } -}; - - -/** - * Handler for the submit event of the form element. - * @param {goog.events.Event} e The event object passed in to the event handler. - * @private - */ -goog.ui.LabelInput.prototype.handleFormSubmit_ = function(e) { - if (!this.hasChanged()) { - this.getElement().value = ''; - // allow form to be sent before restoring value - goog.Timer.callOnce(this.handleAfterSubmit_, 10, this); - } -}; - - -/** - * Restore value after submit - * @param {Event} e The event object passed in to the event handler. - * @private - */ -goog.ui.LabelInput.prototype.handleAfterSubmit_ = function(e) { - if (!this.hasChanged()) { - this.getElement().value = this.label_; - } -}; - - -/** - * Handler for the load event the window. This is needed because - * IE sets defaultValue upon load. - * @param {Event} e The event object passed in to the event handler. - * @private - */ -goog.ui.LabelInput.prototype.handleWindowLoad_ = function(e) { - this.check_(); -}; - - -/** - * @return {boolean} Whether the control is currently focused on. - */ -goog.ui.LabelInput.prototype.hasFocus = function() { - return this.hasFocus_; -}; - - -/** - * @return {boolean} Whether the value has changed been changed by the user. - */ -goog.ui.LabelInput.prototype.hasChanged = function() { - return !!this.getElement() && this.getElement().value != '' && - this.getElement().value != this.label_; -}; - - -/** - * Clears the value of the input element without resetting the default text. - */ -goog.ui.LabelInput.prototype.clear = function() { - this.getElement().value = ''; - - // Reset ffKeyRestoreValue_ when non-null - if (this.ffKeyRestoreValue_ != null) { - this.ffKeyRestoreValue_ = ''; - } -}; - - -/** - * Clears the value of the input element and resets the default text. - */ -goog.ui.LabelInput.prototype.reset = function() { - if (this.hasChanged()) { - this.clear(); - this.check_(); - } -}; - - -/** - * Use this to set the value through script to ensure that the label state is - * up to date - * @param {string} s The new value for the input. - */ -goog.ui.LabelInput.prototype.setValue = function(s) { - if (this.ffKeyRestoreValue_ != null) { - this.ffKeyRestoreValue_ = s; - } - this.getElement().value = s; - this.check_(); -}; - - -/** - * Returns the current value of the text box, returning an empty string if the - * search box is the default value - * @return {string} The value of the input box. - */ -goog.ui.LabelInput.prototype.getValue = function() { - if (this.ffKeyRestoreValue_ != null) { - // Fix the Firefox from incorrectly reporting the value to calling code - // that attached the listener to keypress before the labelinput - return this.ffKeyRestoreValue_; - } - return this.hasChanged() ? /** @type {string} */ (this.getElement().value) : - ''; -}; - - -/** - * Sets the label text. - * @param {string} label The text to show as the label. - */ -goog.ui.LabelInput.prototype.setLabel = function(label) { - if (goog.ui.LabelInput.SUPPORTS_PLACEHOLDER_) { - this.label_ = label; - if (this.getElement()) { - this.getElement().placeholder = this.label_; - } - return; - } - if (this.getElement() && !this.hasChanged()) { - this.getElement().value = ''; - } - this.label_ = label; - this.restoreLabel_(); - // Check if this has been called before DOM structure building - if (this.getElement()) { - goog.dom.a11y.setState(this.getElement(), - goog.dom.a11y.State.LABEL, - this.label_); - } -}; - - -/** - * @return {string} The text to show as the label. - */ -goog.ui.LabelInput.prototype.getLabel = function() { - return this.label_; -}; - - -/** - * Checks the state of the input element - * @private - */ -goog.ui.LabelInput.prototype.check_ = function() { - if (!goog.ui.LabelInput.SUPPORTS_PLACEHOLDER_) { - // if we haven't got a form yet try now - this.attachEventsToForm_(); - goog.dom.a11y.setState(this.getElement(), - goog.dom.a11y.State.LABEL, - this.label_); - } else if (this.getElement().placeholder != this.label_) { - this.getElement().placeholder = this.label_; - } - - if (!this.hasChanged()) { - if (!this.inFocusAndSelect_ && !this.hasFocus_) { - goog.dom.classes.add(this.getElement(), this.LABEL_CLASS_NAME); - } - - // Allow browser to catchup with CSS changes before restoring the label. - if (!goog.ui.LabelInput.SUPPORTS_PLACEHOLDER_) { - goog.Timer.callOnce(this.restoreLabel_, 10, this); - } - } else { - goog.dom.classes.remove(this.getElement(), this.LABEL_CLASS_NAME); - } -}; - - -/** - * This method focuses the input and if selects all the text. If the value - * hasn't changed it will set the value to the label so that the label text is - * selected. - */ -goog.ui.LabelInput.prototype.focusAndSelect = function() { - // We need to check whether the input has changed before focusing - var hc = this.hasChanged(); - this.inFocusAndSelect_ = true; - this.getElement().focus(); - if (!hc && !goog.ui.LabelInput.SUPPORTS_PLACEHOLDER_) { - this.getElement().value = this.label_; - } - this.getElement().select(); - - // Since the object now has focus, we won't get a focus event when they - // click in the input element. The expected behavior when you click on - // the default text is that it goes away and allows you to type...so we - // have to fire an artificial focus event when we're in focusAndSelect mode. - if (goog.ui.LabelInput.SUPPORTS_PLACEHOLDER_) { - return; - } - if (this.eventHandler_) { - this.eventHandler_.listenOnce( - this.getElement(), goog.events.EventType.CLICK, this.handleFocus_); - } - - // set to false in timer to let IE trigger the focus event - goog.Timer.callOnce(this.focusAndSelect_, 10, this); -}; - - -/** - * Enables/Disables the label input. - * @param {boolean} enabled Whether to enable (true) or disable (false) the - * label input. - */ -goog.ui.LabelInput.prototype.setEnabled = function(enabled) { - this.getElement().disabled = !enabled; - goog.dom.classes.enable(this.getElement(), - goog.getCssName(this.LABEL_CLASS_NAME, 'disabled'), !enabled); -}; - - -/** - * @return {boolean} True if the label input is enabled, false otherwise. - */ -goog.ui.LabelInput.prototype.isEnabled = function() { - return !this.getElement().disabled; -}; - - -/** - * @private - */ -goog.ui.LabelInput.prototype.focusAndSelect_ = function() { - this.inFocusAndSelect_ = false; -}; - - -/** - * Sets the value of the input element to label. - * @private - */ -goog.ui.LabelInput.prototype.restoreLabel_ = function() { - // Check again in case something changed since this was scheduled. - // We check that the element is still there since this is called by a timer - // and the dispose method may have been called prior to this. - if (this.getElement() && !this.hasChanged() && !this.hasFocus_) { - this.getElement().value = this.label_; - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/labelinput_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/labelinput_test.html.svn-base deleted file mode 100644 index 876f734..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/labelinput_test.html.svn-base +++ /dev/null @@ -1,213 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2011 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.LabelInput</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.dom.a11y'); - goog.require('goog.dom.a11y.State'); - goog.require('goog.dom.classes'); - goog.require('goog.events.EventType'); - goog.require('goog.testing.MockClock'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.LabelInput'); - goog.require('goog.userAgent'); -</script> -</head> -<body> -<input id="i" type="text"></input> -<input id="p" type="text" placeholder="browser-ignorant placeholder"></input> -<script> - -var labelInput; -var mockClock; - -function setUp() { - mockClock = new goog.testing.MockClock(true); -} - -function tearDown() { - mockClock.dispose(); - labelInput.dispose(); -} - -function testGetLabel() { - labelInput = new goog.ui.LabelInput(); - assertEquals('no label', '', labelInput.getLabel()); - - labelInput = new goog.ui.LabelInput('search'); - assertEquals('label is given in the ctor', 'search', labelInput.getLabel()); -} - -function testSetLabel() { - labelInput = new goog.ui.LabelInput(); - labelInput.setLabel('search'); - assertEquals('label is set', 'search', labelInput.getLabel()); - - // When browsers support the placeholder attribute, we use that instead of - // the value property - and this test will fail. - if (isPlaceholderSupported()) { - return; - } - - labelInput.createDom(); - labelInput.enterDocument(); - mockClock.tick(10); - assertEquals('label is rendered', 'search', labelInput.getElement().value); - assertEquals('label should have aria-label attribute \'search\'', 'search', - goog.dom.a11y.getState(labelInput.getElement(), - goog.dom.a11y.State.LABEL)); - - labelInput.setLabel('new label'); - assertEquals('label is updated', 'new label', labelInput.getElement().value); - assertEquals('label should have aria-label attribute \'new label\'', - 'new label', goog.dom.a11y.getState(labelInput.getElement(), - goog.dom.a11y.State.LABEL)); -} - -function testPlaceholderAttribute() { - labelInput = new goog.ui.LabelInput(); - labelInput.setLabel('search'); - - // Some browsers don't support the placeholder attribute, in which case we - // this test will fail. - if (! isPlaceholderSupported()) { - return; - } - - labelInput.createDom(); - labelInput.enterDocument(); - mockClock.tick(10); - assertEquals('label should have placeholder attribute \'search\'', 'search', - labelInput.getElement().placeholder); - - labelInput.setLabel('new label'); - assertEquals('label should have aria-label attribute \'new label\'', - 'new label', labelInput.getElement().placeholder); -} - -function testDecorateElementWithExistingPlaceholderAttribute() { - labelInput = new goog.ui.LabelInput(); - labelInput.setLabel('search'); - - labelInput.decorate(goog.dom.getElement('p')); - labelInput.enterDocument(); - mockClock.tick(10); - - // The presence of an existing placeholder doesn't necessarily mean the - // browser supports placeholders. Make sure labels are used for browsers - // without placeholder support: - if (isPlaceholderSupported()) { - assertEquals('label should have placeholder attribute \'search\'', 'search', - labelInput.getElement().placeholder); - } else { - assertEquals('label is rendered', 'search', labelInput.getElement().value); - assertEquals('label should have aria-label attribute \'search\'', 'search', - goog.dom.a11y.getState(labelInput.getElement(), - goog.dom.a11y.State.LABEL)); - } -} - -function testDecorateElementWithFocus() { - labelInput = new goog.ui.LabelInput(); - labelInput.setLabel('search'); - - var decoratedElement = goog.dom.getElement('i'); - - decoratedElement.value = ''; - decoratedElement.focus(); - - labelInput.decorate(decoratedElement); - labelInput.enterDocument(); - mockClock.tick(10); - - assertEquals('label for pre-focused input should not have LABEL_CLASS_NAME', - -1, - labelInput.getElement().className.indexOf(labelInput.LABEL_CLASS_NAME)); - - if (!isPlaceholderSupported()) { - assertEquals('label rendered for pre-focused element', - '', labelInput.getElement().value); - // NOTE(user): element.blur() doesn't seem to trigger the BLUR event in - // IE in the test environment. This could be related to the IE issues with - // testClassName() below. - goog.testing.events.fireBrowserEvent( - new goog.testing.events.Event( - goog.events.EventType.BLUR, decoratedElement)); - mockClock.tick(10); - assertEquals('label not rendered for blurred element', - 'search', labelInput.getElement().value); - } -} - -function testClassName() { - labelInput = new goog.ui.LabelInput(); - - // IE always fails this test, suspect it is a focus issue. - if (goog.userAgent.IE) { - return; - } - // FF does not perform focus if the window is not active in the first place. - if (goog.userAgent.GECKO && document.hasFocus && !document.hasFocus()) { - return; - } - - labelInput.decorate(goog.dom.getElement('i')); - labelInput.setLabel('search'); - - var el = labelInput.getElement(); - assertTrue('label before focus should have LABEL_CLASS_NAME', - goog.dom.classes.has(el, labelInput.LABEL_CLASS_NAME)); - - labelInput.getElement().focus(); - - assertFalse('label after focus should not have LABEL_CLASS_NAME', - goog.dom.classes.has(el, labelInput.LABEL_CLASS_NAME)); - - labelInput.getElement().blur(); - - assertTrue('label after blur should have LABEL_CLASS_NAME', - goog.dom.classes.has(el, labelInput.LABEL_CLASS_NAME)); -} - -function isPlaceholderSupported() { - if (goog.dom.getElement('i').placeholder != null) { - return true; - } -} - -function testEnable() { - labelInput = new goog.ui.LabelInput(); - labelInput.createDom(); - labelInput.enterDocument(); - - var labelElement = labelInput.getElement(); - var disabledClass = goog.getCssName(labelInput.LABEL_CLASS_NAME, 'disabled'); - - assertTrue('label should be enabled', labelInput.isEnabled()); - assertFalse('label should not have the disabled class', - goog.dom.classes.has(labelElement, disabledClass)); - - labelInput.setEnabled(false); - assertFalse('label should be disabled', labelInput.isEnabled()); - assertTrue('label should have the disabled class', - goog.dom.classes.has(labelElement, disabledClass)); - - labelInput.setEnabled(true); - assertTrue('label should be enabled', labelInput.isEnabled()); - assertFalse('label should not have the disabled class', - goog.dom.classes.has(labelElement, disabledClass)); -} - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/linkbuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/linkbuttonrenderer.js.svn-base deleted file mode 100644 index 4f720ad..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/linkbuttonrenderer.js.svn-base +++ /dev/null @@ -1,67 +0,0 @@ -// 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()); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menu.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menu.js.svn-base deleted file mode 100644 index 80fda28..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menu.js.svn-base +++ /dev/null @@ -1,463 +0,0 @@ -// 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 base menu class that supports key and mouse events. The menu - * can be bound to an existing HTML structure or can generate its own DOM. - * - * To decorate, the menu should be bound to an element containing children - * with the classname 'goog-menuitem'. HRs will be classed as separators. - * - * Decorate Example: - * <div id="menu" class="goog-menu" tabIndex="0"> - * <div class="goog-menuitem">Google</div> - * <div class="goog-menuitem">Yahoo</div> - * <div class="goog-menuitem">MSN</div> - * <hr> - * <div class="goog-menuitem">New...</div> - * </div> - * <script> - * - * var menu = new goog.ui.Menu(); - * menu.decorate(goog.dom.getElement('menu')); - * - * TESTED=FireFox 2.0, IE6, Opera 9, Chrome. - * TODO(user): Key handling is flaky in Opera and Chrome - * TODO(user): Rename all references of "item" to child since menu is - * essentially very generic and could, in theory, host a date or color picker. - * - * @see ../demos/menu.html - * @see ../demos/menus.html - */ - -goog.provide('goog.ui.Menu'); -goog.provide('goog.ui.Menu.EventType'); - -goog.require('goog.math.Coordinate'); -goog.require('goog.string'); -goog.require('goog.style'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.Component.State'); -goog.require('goog.ui.Container'); -goog.require('goog.ui.Container.Orientation'); -goog.require('goog.ui.MenuHeader'); -goog.require('goog.ui.MenuItem'); -goog.require('goog.ui.MenuRenderer'); -goog.require('goog.ui.MenuSeparator'); - -// The dependencies MenuHeader, MenuItem, and MenuSeparator are implicit. -// There are no references in the code, but we need to load these -// classes before goog.ui.Menu. - - - -// TODO(robbyw): Reverse constructor argument order for consistency. -/** - * A basic menu class. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @param {goog.ui.MenuRenderer=} opt_renderer Renderer used to render or - * decorate the container; defaults to {@link goog.ui.MenuRenderer}. - * @constructor - * @extends {goog.ui.Container} - */ -goog.ui.Menu = function(opt_domHelper, opt_renderer) { - goog.ui.Container.call(this, goog.ui.Container.Orientation.VERTICAL, - opt_renderer || goog.ui.MenuRenderer.getInstance(), opt_domHelper); - - // Unlike Containers, Menus aren't keyboard-accessible by default. This line - // preserves backwards compatibility with code that depends on menus not - // receiving focus - e.g. {@code goog.ui.MenuButton}. - this.setFocusable(false); -}; -goog.inherits(goog.ui.Menu, goog.ui.Container); - - -// TODO(robbyw): Remove this and all references to it. -// Please ensure that BEFORE_SHOW behavior is not disrupted as a result. -/** - * Event types dispatched by the menu. - * @enum {string} - * @deprecated Use goog.ui.Component.EventType. - */ -goog.ui.Menu.EventType = { - /** Dispatched before the menu becomes visible */ - BEFORE_SHOW: goog.ui.Component.EventType.BEFORE_SHOW, - - /** Dispatched when the menu is shown */ - SHOW: goog.ui.Component.EventType.SHOW, - - /** Dispatched before the menu becomes hidden */ - BEFORE_HIDE: goog.ui.Component.EventType.HIDE, - - /** Dispatched when the menu is hidden */ - HIDE: goog.ui.Component.EventType.HIDE -}; - - -// TODO(robbyw): Remove this and all references to it. -/** - * CSS class for menus. - * @type {string} - * @deprecated Use goog.ui.MenuRenderer.CSS_CLASS. - */ -goog.ui.Menu.CSS_CLASS = goog.ui.MenuRenderer.CSS_CLASS; - - -/** - * Coordinates of the mousedown event that caused this menu to be made visible. - * Used to prevent the consequent mouseup event due to a simple click from - * activating a menu item immediately. Considered protected; should only be used - * within this package or by subclasses. - * @type {goog.math.Coordinate|undefined} - */ -goog.ui.Menu.prototype.openingCoords; - - -/** - * Whether the menu can move the focus to it's key event target when it is - * shown. Default = true - * @type {boolean} - * @private - */ -goog.ui.Menu.prototype.allowAutoFocus_ = true; - - -/** - * Whether the menu should use windows syle behavior and allow disabled menu - * items to be highlighted (though not selectable). Defaults to false - * @type {boolean} - * @private - */ -goog.ui.Menu.prototype.allowHighlightDisabled_ = false; - - -/** - * Returns the CSS class applied to menu elements, also used as the prefix for - * derived styles, if any. Subclasses should override this method as needed. - * Considered protected. - * @return {string} The CSS class applied to menu elements. - * @protected - * @deprecated Use getRenderer().getCssClass(). - */ -goog.ui.Menu.prototype.getCssClass = function() { - return this.getRenderer().getCssClass(); -}; - - -/** - * Returns whether the provided element is to be considered inside the menu for - * purposes such as dismissing the menu on an event. This is so submenus can - * make use of elements outside their own DOM. - * @param {Element} element The element to test for. - * @return {boolean} Whether the provided element is to be considered inside - * the menu. - */ -goog.ui.Menu.prototype.containsElement = function(element) { - if (this.getRenderer().containsElement(this, element)) { - return true; - } - - for (var i = 0, count = this.getChildCount(); i < count; i++) { - var child = this.getChildAt(i); - if (typeof child.containsElement == 'function' && - child.containsElement(element)) { - return true; - } - } - - return false; -}; - - -/** - * Adds a new menu item at the end of the menu. - * @param {goog.ui.MenuHeader|goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu - * item to add to the menu. - * @deprecated Use {@link #addChild} instead, with true for the second argument. - */ -goog.ui.Menu.prototype.addItem = function(item) { - this.addChild(item, true); -}; - - -/** - * Adds a new menu item at a specific index in the menu. - * @param {goog.ui.MenuHeader|goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu - * item to add to the menu. - * @param {number} n Index at which to insert the menu item. - * @deprecated Use {@link #addChildAt} instead, with true for the third - * argument. - */ -goog.ui.Menu.prototype.addItemAt = function(item, n) { - this.addChildAt(item, n, true); -}; - - -/** - * Removes an item from the menu and disposes of it. - * @param {goog.ui.MenuHeader|goog.ui.MenuItem|goog.ui.MenuSeparator} item The - * menu item to remove. - * @deprecated Use {@link #removeChild} instead. - */ -goog.ui.Menu.prototype.removeItem = function(item) { - var removedChild = this.removeChild(item, true); - if (removedChild) { - removedChild.dispose(); - } -}; - - -/** - * Removes a menu item at a given index in the menu and disposes of it. - * @param {number} n Index of item. - * @deprecated Use {@link #removeChildAt} instead. - */ -goog.ui.Menu.prototype.removeItemAt = function(n) { - var removedChild = this.removeChildAt(n, true); - if (removedChild) { - removedChild.dispose(); - } -}; - - -/** - * Returns a reference to the menu item at a given index. - * @param {number} n Index of menu item. - * @return {goog.ui.MenuHeader|goog.ui.MenuItem|goog.ui.MenuSeparator|null} - * Reference to the menu item. - * @deprecated Use {@link #getChildAt} instead. - */ -goog.ui.Menu.prototype.getItemAt = function(n) { - return /** @type {goog.ui.MenuItem?} */(this.getChildAt(n)); -}; - - -/** - * Returns the number of items in the menu (including separators). - * @return {number} The number of items in the menu. - * @deprecated Use {@link #getChildCount} instead. - */ -goog.ui.Menu.prototype.getItemCount = function() { - return this.getChildCount(); -}; - - -/** - * Returns an array containing the menu items contained in the menu. - * @return {Array.<goog.ui.MenuItem>} An array of menu items. - * @deprecated Use getChildAt, forEachChild, and getChildCount. - */ -goog.ui.Menu.prototype.getItems = function() { - // TODO(user): Remove reference to getItems and instead use getChildAt, - // forEachChild, and getChildCount - var children = []; - this.forEachChild(function(child) { - children.push(child); - }); - return children; -}; - - -/** - * Sets the position of the menu relative to the view port. - * @param {number|goog.math.Coordinate} x Left position or coordinate obj. - * @param {number=} opt_y Top position. - */ -goog.ui.Menu.prototype.setPosition = function(x, opt_y) { - // NOTE(user): It is necessary to temporarily set the display from none, so - // that the position gets set correctly. - var visible = this.isVisible(); - if (!visible) { - goog.style.showElement(this.getElement(), true); - } - goog.style.setPageOffset(this.getElement(), x, opt_y); - if (!visible) { - goog.style.showElement(this.getElement(), false); - } -}; - - -/** - * Gets the page offset of the menu, or null if the menu isn't visible - * @return {goog.math.Coordinate?} Object holding the x-y coordinates of the - * menu or null if the menu is not visible. - */ -goog.ui.Menu.prototype.getPosition = function() { - return this.isVisible() ? goog.style.getPageOffset(this.getElement()) : null; -}; - - -/** - * Sets whether the menu can automatically move focus to its key event target - * when it is set to visible. - * @param {boolean} allow Whether the menu can automatically move focus to its - * key event target when it is set to visible. - */ -goog.ui.Menu.prototype.setAllowAutoFocus = function(allow) { - this.allowAutoFocus_ = allow; - if (allow) { - this.setFocusable(true); - } -}; - - -/** - * @return {boolean} Whether the menu can automatically move focus to its key - * event target when it is set to visible. - */ -goog.ui.Menu.prototype.getAllowAutoFocus = function() { - return this.allowAutoFocus_; -}; - - -/** - * Sets whether the menu will highlight disabled menu items or skip to the next - * active item. - * @param {boolean} allow Whether the menu will highlight disabled menu items or - * skip to the next active item. - */ -goog.ui.Menu.prototype.setAllowHighlightDisabled = function(allow) { - this.allowHighlightDisabled_ = allow; -}; - - -/** - * @return {boolean} Whether the menu will highlight disabled menu items or skip - * to the next active item. - */ -goog.ui.Menu.prototype.getAllowHighlightDisabled = function() { - return this.allowHighlightDisabled_; -}; - - -/** - * @override - * @param {goog.events.Event=} opt_e Mousedown event that caused this menu to - * be made visible (ignored if show is false). - */ -goog.ui.Menu.prototype.setVisible = function(show, opt_force, opt_e) { - var visibilityChanged = goog.ui.Menu.superClass_.setVisible.call(this, show, - opt_force); - if (visibilityChanged && show && this.isInDocument() && - this.allowAutoFocus_) { - this.getKeyEventTarget().focus(); - } - if (show && opt_e && goog.isNumber(opt_e.clientX)) { - this.openingCoords = new goog.math.Coordinate(opt_e.clientX, opt_e.clientY); - } else { - this.openingCoords = null; - } - return visibilityChanged; -}; - - -/** @override */ -goog.ui.Menu.prototype.handleEnterItem = function(e) { - if (this.allowAutoFocus_) { - this.getKeyEventTarget().focus(); - } - - return goog.ui.Menu.superClass_.handleEnterItem.call(this, e); -}; - - -/** - * Highlights the next item that begins with the specified string. If no - * (other) item begins with the given string, the selection is unchanged. - * @param {string} charStr The prefix to match. - * @return {boolean} Whether a matching prefix was found. - */ -goog.ui.Menu.prototype.highlightNextPrefix = function(charStr) { - var re = new RegExp('^' + goog.string.regExpEscape(charStr), 'i'); - return this.highlightHelper(function(index, max) { - // Index is >= -1 because it is set to -1 when nothing is selected. - var start = index < 0 ? 0 : index; - var wrapped = false; - - // We always start looking from one after the current, because we - // keep the current selection only as a last resort. This makes the - // loop a little awkward in the case where there is no current - // selection, as we need to stop somewhere but can't just stop - // when index == start, which is why we need the 'wrapped' flag. - do { - ++index; - if (index == max) { - index = 0; - wrapped = true; - } - var name = this.getChildAt(index).getCaption(); - if (name && name.match(re)) { - return index; - } - } while (!wrapped || index != start); - return this.getHighlightedIndex(); - }, this.getHighlightedIndex()); -}; - - -/** @override */ -goog.ui.Menu.prototype.canHighlightItem = function(item) { - return (this.allowHighlightDisabled_ || item.isEnabled()) && - item.isVisible() && item.isSupportedState(goog.ui.Component.State.HOVER); -}; - - -/** @override */ -goog.ui.Menu.prototype.decorateInternal = function(element) { - this.decorateContent(element); - goog.ui.Menu.superClass_.decorateInternal.call(this, element); -}; - - -/** @override */ -goog.ui.Menu.prototype.handleKeyEventInternal = function(e) { - var handled = goog.base(this, 'handleKeyEventInternal', e); - if (!handled) { - // Loop through all child components, and for each menu item call its - // key event handler so that keyboard mnemonics can be handled. - this.forEachChild(function(menuItem) { - if (!handled && menuItem.getMnemonic && - menuItem.getMnemonic() == e.keyCode) { - if (this.isEnabled()) { - this.setHighlighted(menuItem); - } - // We still delegate to handleKeyEvent, so that it can handle - // enabled/disabled state. - handled = menuItem.handleKeyEvent(e); - } - }, this); - } - return handled; -}; - - -/** - * Decorate menu items located in any descendent node which as been explicitly - * marked as a 'content' node. - * @param {Element} element Element to decorate. - * @protected - */ -goog.ui.Menu.prototype.decorateContent = function(element) { - var renderer = this.getRenderer(); - var contentElements = this.getDomHelper().getElementsByTagNameAndClass('div', - goog.getCssName(renderer.getCssClass(), 'content'), element); - - // Some versions of IE do not like it when you access this nodeList - // with invalid indices. See - // http://code.google.com/p/closure-library/issues/detail?id=373 - var length = contentElements.length; - for (var i = 0; i < length; i++) { - renderer.decorateChildren(this, contentElements[i]); - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menu_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menu_test.html.svn-base deleted file mode 100644 index 33abb73..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menu_test.html.svn-base +++ /dev/null @@ -1,129 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - - @author nicksantos@google.com (Nick Santos) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.Menu</title> -<style type='text/css'> -.goog-menu { - position: absolute; - color: #aaa; -} -</style> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.events.Event'); - goog.require('goog.math'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Component.EventType'); - goog.require('goog.ui.Menu'); -</script> -</head> -<body> -<script> - -var menu; -var clonedMenuDom; - -function setUp() { - clonedMenuDom = goog.dom.getElement('demoMenu').cloneNode(true); - - menu = new goog.ui.Menu(); -} - -function tearDown() { - menu.dispose(); - - var element = goog.dom.getElement('demoMenu'); - element.parentNode.replaceChild(clonedMenuDom, element); -} - -/** @bug 1463524 */ -function testMouseupDoesntActivateMenuItemImmediately() { - menu.decorate(goog.dom.getElement('demoMenu')); - - var fakeEvent = {clientX: 42, clientY: 42}; - var itemElem = goog.dom.getElement('menuItem2'); - var coords = new goog.math.Coordinate(42, 42); - - var menuItem = menu.getChildAt(1); - var actionDispatched = false; - goog.events.listen(menuItem, goog.ui.Component.EventType.ACTION, - function(e) { - actionDispatched = true; - }); - - menu.setVisible(true, false, fakeEvent); - // Makes the menu item active so it can be selected on mouseup. - menuItem.setActive(true); - - goog.testing.events.fireMouseUpEvent(itemElem, undefined, coords); - assertFalse('ACTION should not be dispatched after the initial mouseup', - actionDispatched); - - goog.testing.events.fireMouseUpEvent(itemElem, undefined, coords); - assertTrue('ACTION should be dispatched after the second mouseup', - actionDispatched); - -} - -function testHoverBehavior() { - menu.decorate(goog.dom.getElement('demoMenu')); - - goog.testing.events.fireMouseOverEvent(goog.dom.getElement('menuItem2'), - document.body); - assertEquals(1, menu.getHighlightedIndex()); - - menu.exitDocument(); - assertEquals(-1, menu.getHighlightedIndex()); -} - -function testIndirectionDecoration() { - menu.decorate(goog.dom.getElement('complexMenu')); - - goog.testing.events.fireMouseOverEvent(goog.dom.getElement('complexItem3'), - document.body); - assertEquals(2, menu.getHighlightedIndex()); - - menu.exitDocument(); - assertEquals(-1, menu.getHighlightedIndex()); -} - -</script> - -<p> - Here's a menu defined in markup: -</p> -<div id="demoMenu" class="goog-menu"> - <div id='menuItem1' class="goog-menuitem">Annual Report.pdf</div> - <div id='menuItem2' class="goog-menuitem">Quarterly Update.pdf</div> - <div id='menuItem3' class="goog-menuitem">Enemies List.txt</div> -</div> - -<p> - Here's a menu which has been rendered with an explicit content node: -</p> -<div id="complexMenu" class="goog-menu"> - <div style="border:1px solid black;"> - <div class="goog-menu-content"> - <div id='complexItem1' class="goog-menuitem">Drizzle</div> - <div id='complexItem2' class="goog-menuitem">Rain</div> - <div id='complexItem3' class="goog-menuitem">Deluge</div> - </div> - </div> -</div> - -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubase.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubase.js.svn-base deleted file mode 100644 index 95e8d86..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubase.js.svn-base +++ /dev/null @@ -1,191 +0,0 @@ -// 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 MenuBase class. - * - */ - -goog.provide('goog.ui.MenuBase'); - -goog.require('goog.events.EventHandler'); -goog.require('goog.events.EventType'); -goog.require('goog.events.KeyHandler'); -goog.require('goog.events.KeyHandler.EventType'); -goog.require('goog.ui.Popup'); - - - -/** - * The MenuBase class provides an abstract base class for different - * implementations of menu controls. - * - * @param {Element=} opt_element A DOM element for the popup. - * @deprecated Use goog.ui.Menu. - * @constructor - * @extends {goog.ui.Popup} - */ -goog.ui.MenuBase = function(opt_element) { - goog.ui.Popup.call(this, opt_element); - - /** - * Event handler for simplifiying adding/removing listeners. - * @type {goog.events.EventHandler} - * @private - */ - this.eventHandler_ = new goog.events.EventHandler(this); - - /** - * KeyHandler to cope with the vagaries of cross-browser key events. - * @type {goog.events.KeyHandler} - * @private - */ - this.keyHandler_ = new goog.events.KeyHandler(this.getElement()); -}; -goog.inherits(goog.ui.MenuBase, goog.ui.Popup); - - -/** - * Events fired by the Menu - */ -goog.ui.MenuBase.Events = {}; - - -/** - * Event fired by the Menu when an item is "clicked". - */ -goog.ui.MenuBase.Events.ITEM_ACTION = 'itemaction'; - - -/** @override */ -goog.ui.MenuBase.prototype.disposeInternal = function() { - goog.ui.MenuBase.superClass_.disposeInternal.call(this); - this.eventHandler_.dispose(); - this.keyHandler_.dispose(); -}; - - -/** - * Called after the menu is shown. Derived classes can override to hook this - * event but should make sure to call the parent class method. - * - * @protected - * @suppress {underscore} - * @override - */ -goog.ui.MenuBase.prototype.onShow_ = function() { - goog.ui.MenuBase.superClass_.onShow_.call(this); - - // register common event handlers for derived classes - var el = this.getElement(); - this.eventHandler_.listen( - el, goog.events.EventType.MOUSEOVER, this.onMouseOver); - this.eventHandler_.listen( - el, goog.events.EventType.MOUSEOUT, this.onMouseOut); - this.eventHandler_.listen( - el, goog.events.EventType.MOUSEDOWN, this.onMouseDown); - this.eventHandler_.listen( - el, goog.events.EventType.MOUSEUP, this.onMouseUp); - - this.eventHandler_.listen( - this.keyHandler_, - goog.events.KeyHandler.EventType.KEY, - this.onKeyDown); -}; - - -/** - * Called after the menu 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} - * @override - */ -goog.ui.MenuBase.prototype.onHide_ = function(opt_target) { - goog.ui.MenuBase.superClass_.onHide_.call(this, opt_target); - - // remove listeners when hidden - this.eventHandler_.removeAll(); -}; - - -/** - * Returns the selected item - * - * @return {Object} The item selected or null if no item is selected. - */ -goog.ui.MenuBase.prototype.getSelectedItem = function() { - return null; -}; - - -/** - * Sets the selected item - * - * @param {Object} item The item to select. The type of this item is specific - * to the menu class. - */ -goog.ui.MenuBase.prototype.setSelectedItem = function(item) { -}; - - -/** - * Mouse over handler for the menu. Derived classes should override. - * - * @param {goog.events.Event} e The event object. - * @protected - */ -goog.ui.MenuBase.prototype.onMouseOver = function(e) { -}; - - -/** - * Mouse out handler for the menu. Derived classes should override. - * - * @param {goog.events.Event} e The event object. - * @protected - */ -goog.ui.MenuBase.prototype.onMouseOut = function(e) { -}; - - -/** - * Mouse down handler for the menu. Derived classes should override. - * - * @param {goog.events.Event} e The event object. - * @protected - */ -goog.ui.MenuBase.prototype.onMouseDown = function(e) { -}; - - -/** - * Mouse up handler for the menu. Derived classes should override. - * - * @param {goog.events.Event} e The event object. - * @protected - */ -goog.ui.MenuBase.prototype.onMouseUp = function(e) { -}; - - -/** - * Key down handler for the menu. Derived classes should override. - * - * @param {goog.events.KeyEvent} e The event object. - * @protected - */ -goog.ui.MenuBase.prototype.onKeyDown = function(e) { -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubutton.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubutton.js.svn-base deleted file mode 100644 index ccb80c3..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubutton.js.svn-base +++ /dev/null @@ -1,875 +0,0 @@ -// 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 menu button control. - * - * @author attila@google.com (Attila Bodis) - * @see ../demos/menubutton.html - */ - -goog.provide('goog.ui.MenuButton'); - -goog.require('goog.Timer'); -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.a11y.State'); -goog.require('goog.events.EventType'); -goog.require('goog.events.KeyCodes'); -goog.require('goog.events.KeyHandler.EventType'); -goog.require('goog.math.Box'); -goog.require('goog.math.Rect'); -goog.require('goog.positioning'); -goog.require('goog.positioning.Corner'); -goog.require('goog.positioning.MenuAnchoredPosition'); -goog.require('goog.style'); -goog.require('goog.ui.Button'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.Component.State'); -goog.require('goog.ui.Menu'); -goog.require('goog.ui.MenuButtonRenderer'); -goog.require('goog.ui.registry'); -goog.require('goog.userAgent'); -goog.require('goog.userAgent.product'); - - - -/** - * A menu button control. Extends {@link goog.ui.Button} by composing a button - * with a dropdown arrow and a popup menu. - * - * @param {goog.ui.ControlContent} content Text caption or existing DOM - * structure to display as the button's caption (if any). - * @param {goog.ui.Menu=} opt_menu Menu to render under the button when clicked. - * @param {goog.ui.ButtonRenderer=} opt_renderer Renderer used to render or - * decorate the menu button; defaults to {@link goog.ui.MenuButtonRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for - * document interaction. - * @constructor - * @extends {goog.ui.Button} - */ -goog.ui.MenuButton = function(content, opt_menu, opt_renderer, opt_domHelper) { - goog.ui.Button.call(this, content, opt_renderer || - goog.ui.MenuButtonRenderer.getInstance(), opt_domHelper); - - // Menu buttons support the OPENED state. - this.setSupportedState(goog.ui.Component.State.OPENED, true); - - if (opt_menu) { - this.setMenu(opt_menu); - } - this.menuMargin_ = null; - this.timer_ = new goog.Timer(500); // 0.5 sec - - // Phones running iOS prior to version 4.2. - if ((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')) { - // @bug 4322060 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. - this.setFocusablePopupMenu(true); - } -}; -goog.inherits(goog.ui.MenuButton, goog.ui.Button); - - -/** - * The menu. - * @type {goog.ui.Menu|undefined} - * @private - */ -goog.ui.MenuButton.prototype.menu_; - - -/** - * The menu position on this button, when set explicitly. - * @type {goog.positioning.AnchoredPosition|undefined} - * @private - */ -goog.ui.MenuButton.prototype.menuPosition_; - - -/** - * The position element. If set, use positionElement_ to position the - * popup menu instead of the default which is to use the menu button element. - * @type {Element|undefined} - * @private - */ -goog.ui.MenuButton.prototype.positionElement_; - - -/** - * The margin to apply to the menu's position when it is shown. If null, no - * margin will be applied. - * @type {goog.math.Box} - * @private - */ -goog.ui.MenuButton.prototype.menuMargin_; - - -/** - * Whether the popup menu should be aligned to the start or the end of the - * button; defaults to true (align to start). - * @type {boolean} - * @private - */ -goog.ui.MenuButton.prototype.alignToStart_ = true; - - -/** - * Whether the popup menu should scroll when it's to big to fit vertically - * on the screen. Defaults to false, use the adjust logic to reposition the - * menu on overflow rather then scroll. - * @type {boolean} - * @private - */ -goog.ui.MenuButton.prototype.scrollOnOverflow_ = false; - - -/** - * Whether the attached popup menu is focusable or not (defaults to false). - * Popup menus attached to menu buttons usually don't need to be focusable, - * i.e. the button retains keyboard focus, and forwards key events to the - * menu for processing. However, menus like {@link goog.ui.FilteredMenu} - * need to be focusable. - * @type {boolean} - * @private - */ -goog.ui.MenuButton.prototype.isFocusablePopupMenu_ = false; - - -/** - * A Timer to correct menu position. - * @type {goog.Timer} - * @private - */ -goog.ui.MenuButton.prototype.timer_; - - -/** - * The bounding rectangle of the button element. - * @type {goog.math.Rect} - * @private - */ -goog.ui.MenuButton.prototype.buttonRect_; - - -/** - * The viewport rectangle. - * @type {goog.math.Box} - * @private - */ -goog.ui.MenuButton.prototype.viewportBox_; - - -/** - * The original size. - * @type {goog.math.Size|undefined} - * @private - */ -goog.ui.MenuButton.prototype.originalSize_; - - -/** - * Do we render the drop down menu as a sibling to the label, or at the end - * of the current dom? - * @type {boolean} - * @private - */ -goog.ui.MenuButton.prototype.renderMenuAsSibling_ = false; - - -/** - * Sets up event handlers specific to menu buttons. - * @override - */ -goog.ui.MenuButton.prototype.enterDocument = function() { - goog.ui.MenuButton.superClass_.enterDocument.call(this); - if (this.menu_) { - this.attachMenuEventListeners_(this.menu_, true); - } - goog.dom.a11y.setState(this.getElement(), - goog.dom.a11y.State.HASPOPUP, 'true'); -}; - - -/** - * Removes event handlers specific to menu buttons, and ensures that the - * attached menu also exits the document. - * @override - */ -goog.ui.MenuButton.prototype.exitDocument = function() { - goog.ui.MenuButton.superClass_.exitDocument.call(this); - if (this.menu_) { - this.setOpen(false); - this.menu_.exitDocument(); - this.attachMenuEventListeners_(this.menu_, false); - - var menuElement = this.menu_.getElement(); - if (menuElement) { - goog.dom.removeNode(menuElement); - } - } -}; - - -/** @override */ -goog.ui.MenuButton.prototype.disposeInternal = function() { - goog.ui.MenuButton.superClass_.disposeInternal.call(this); - if (this.menu_) { - this.menu_.dispose(); - delete this.menu_; - } - delete this.positionElement_; - this.timer_.dispose(); -}; - - -/** - * Handles mousedown events. Invokes the superclass implementation to dispatch - * an ACTIVATE event and activate the button. Also toggles the visibility of - * the attached menu. - * @param {goog.events.Event} e Mouse event to handle. - * @override - * @protected - */ -goog.ui.MenuButton.prototype.handleMouseDown = function(e) { - goog.ui.MenuButton.superClass_.handleMouseDown.call(this, e); - if (this.isActive()) { - // The component was allowed to activate; toggle menu visibility. - this.setOpen(!this.isOpen(), e); - if (this.menu_) { - this.menu_.setMouseButtonPressed(this.isOpen()); - } - } -}; - - -/** - * Handles mouseup events. Invokes the superclass implementation to dispatch - * an ACTION event and deactivate the button. - * @param {goog.events.Event} e Mouse event to handle. - * @override - * @protected - */ -goog.ui.MenuButton.prototype.handleMouseUp = function(e) { - goog.ui.MenuButton.superClass_.handleMouseUp.call(this, e); - if (this.menu_ && !this.isActive()) { - this.menu_.setMouseButtonPressed(false); - } -}; - - -/** - * Performs the appropriate action when the menu button is activated by the - * user. Overrides the superclass implementation by not dispatching an {@code - * ACTION} event, because menu buttons exist only to reveal menus, not to - * perform actions themselves. Calls {@link #setActive} to deactivate the - * button. - * @param {goog.events.Event} e Mouse or key event that triggered the action. - * @return {boolean} Whether the action was allowed to proceed. - * @override - * @protected - */ -goog.ui.MenuButton.prototype.performActionInternal = function(e) { - this.setActive(false); - return true; -}; - - -/** - * Handles mousedown events over the document. If the mousedown happens over - * an element unrelated to the component, hides the menu. - * TODO(attila): Reconcile this with goog.ui.Popup (and handle frames/windows). - * @param {goog.events.BrowserEvent} e Mouse event to handle. - * @protected - */ -goog.ui.MenuButton.prototype.handleDocumentMouseDown = function(e) { - if (this.menu_ && - this.menu_.isVisible() && - !this.containsElement(/** @type {Element} */ (e.target))) { - // User clicked somewhere else in the document while the menu was visible; - // dismiss menu. - this.setOpen(false); - } -}; - - -/** - * Returns true if the given element is to be considered part of the component, - * even if it isn't a DOM descendant of the component's root element. - * @param {Element} element Element to test (if any). - * @return {boolean} Whether the element is considered part of the component. - * @protected - */ -goog.ui.MenuButton.prototype.containsElement = function(element) { - return element && goog.dom.contains(this.getElement(), element) || - this.menu_ && this.menu_.containsElement(element) || false; -}; - - -/** @override */ -goog.ui.MenuButton.prototype.handleKeyEventInternal = function(e) { - // Handle SPACE on keyup and all other keys on keypress. - if (e.keyCode == goog.events.KeyCodes.SPACE) { - // Prevent page scrolling in Chrome. - e.preventDefault(); - if (e.type != goog.events.EventType.KEYUP) { - return false; - } - } else if (e.type != goog.events.KeyHandler.EventType.KEY) { - return false; - } - - if (this.menu_ && this.menu_.isVisible()) { - // Menu is open. - var handledByMenu = this.menu_.handleKeyEvent(e); - if (e.keyCode == goog.events.KeyCodes.ESC) { - // Dismiss the menu. - this.setOpen(false); - return true; - } - return handledByMenu; - } - - if (e.keyCode == goog.events.KeyCodes.DOWN || - e.keyCode == goog.events.KeyCodes.UP || - e.keyCode == goog.events.KeyCodes.SPACE) { - // Menu is closed, and the user hit the down/up/space key; open menu. - this.setOpen(true); - return true; - } - - // Key event wasn't handled by the component. - return false; -}; - - -/** - * Handles {@code ACTION} events dispatched by an activated menu item. - * @param {goog.events.Event} e Action event to handle. - * @protected - */ -goog.ui.MenuButton.prototype.handleMenuAction = function(e) { - // Close the menu on click. - this.setOpen(false); -}; - - -/** - * Handles {@code BLUR} events dispatched by the popup menu by closing it. - * Only registered if the menu is focusable. - * @param {goog.events.Event} e Blur event dispatched by a focusable menu. - */ -goog.ui.MenuButton.prototype.handleMenuBlur = function(e) { - // Close the menu when it reports that it lost focus, unless the button is - // pressed (active). - if (!this.isActive()) { - this.setOpen(false); - } -}; - - -/** - * Handles blur events dispatched by the button's key event target when it - * loses keyboard focus by closing the popup menu (unless it is focusable). - * Only registered if the button is focusable. - * @param {goog.events.Event} e Blur event dispatched by the menu button. - * @override - * @protected - */ -goog.ui.MenuButton.prototype.handleBlur = function(e) { - if (!this.isFocusablePopupMenu()) { - this.setOpen(false); - } - goog.ui.MenuButton.superClass_.handleBlur.call(this, e); -}; - - -/** - * Returns the menu attached to the button. If no menu is attached, creates a - * new empty menu. - * @return {goog.ui.Menu} Popup menu attached to the menu button. - */ -goog.ui.MenuButton.prototype.getMenu = function() { - if (!this.menu_) { - this.setMenu(new goog.ui.Menu(this.getDomHelper())); - } - return this.menu_ || null; -}; - - -/** - * Replaces the menu attached to the button with the argument, and returns the - * previous menu (if any). - * @param {goog.ui.Menu?} menu New menu to be attached to the menu button (null - * to remove the menu). - * @return {goog.ui.Menu|undefined} Previous menu (undefined if none). - */ -goog.ui.MenuButton.prototype.setMenu = function(menu) { - var oldMenu = this.menu_; - - // Do nothing unless the new menu is different from the current one. - if (menu != oldMenu) { - if (oldMenu) { - this.setOpen(false); - if (this.isInDocument()) { - this.attachMenuEventListeners_(oldMenu, false); - } - delete this.menu_; - } - if (menu) { - this.menu_ = menu; - menu.setParent(this); - menu.setVisible(false); - menu.setAllowAutoFocus(this.isFocusablePopupMenu()); - if (this.isInDocument()) { - this.attachMenuEventListeners_(menu, true); - } - } - } - - return oldMenu; -}; - - -/** - * Specify explicitly which corner of the button to use, which will override - * the value from setAlignMenuToStart() and setScrollOnOverflow(). - * @param {goog.positioning.AnchoredPosition} position The position of the - * Menu the button. - */ -goog.ui.MenuButton.prototype.setMenuPosition = function(position) { - this.menuPosition_ = position; -}; - - -/** - * Sets an element for anchoring the menu. - * @param {Element} positionElement New element to use for - * positioning the dropdown menu. Null to use the default behavior - * of positioning to this menu button. - */ -goog.ui.MenuButton.prototype.setPositionElement = function( - positionElement) { - this.positionElement_ = positionElement; - this.positionMenu(); -}; - - -/** - * Sets a margin that will be applied to the menu's position when it is shown. - * If null, no margin will be applied. - * @param {goog.math.Box} margin Margin to apply. - */ -goog.ui.MenuButton.prototype.setMenuMargin = function(margin) { - this.menuMargin_ = margin; -}; - - -/** - * Adds a new menu item at the end of the menu. - * @param {goog.ui.MenuItem|goog.ui.MenuSeparator|goog.ui.Control} item Menu - * item to add to the menu. - */ -goog.ui.MenuButton.prototype.addItem = function(item) { - this.getMenu().addChild(item, true); -}; - - -/** - * Adds a new menu item at the specific index in the menu. - * @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu item to add to the - * menu. - * @param {number} index Index at which to insert the menu item. - */ -goog.ui.MenuButton.prototype.addItemAt = function(item, index) { - this.getMenu().addChildAt(item, index, true); -}; - - -/** - * Removes the item from the menu and disposes of it. - * @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item The menu item to remove. - */ -goog.ui.MenuButton.prototype.removeItem = function(item) { - var child = this.getMenu().removeChild(item, true); - if (child) { - child.dispose(); - } -}; - - -/** - * Removes the menu item at a given index in the menu and disposes of it. - * @param {number} index Index of item. - */ -goog.ui.MenuButton.prototype.removeItemAt = function(index) { - var child = this.getMenu().removeChildAt(index, true); - if (child) { - child.dispose(); - } -}; - - -/** - * Returns the menu item at a given index. - * @param {number} index Index of menu item. - * @return {goog.ui.MenuItem?} Menu item (null if not found). - */ -goog.ui.MenuButton.prototype.getItemAt = function(index) { - return this.menu_ ? - /** @type {goog.ui.MenuItem} */ (this.menu_.getChildAt(index)) : null; -}; - - -/** - * Returns the number of items in the menu (including separators). - * @return {number} The number of items in the menu. - */ -goog.ui.MenuButton.prototype.getItemCount = function() { - return this.menu_ ? this.menu_.getChildCount() : 0; -}; - - -/** - * Shows/hides the menu button based on the value of the argument. Also hides - * the popup menu if the button is being hidden. - * @param {boolean} visible Whether to show or hide the button. - * @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.MenuButton.prototype.setVisible = function(visible, opt_force) { - var visibilityChanged = goog.ui.MenuButton.superClass_.setVisible.call(this, - visible, opt_force); - if (visibilityChanged && !this.isVisible()) { - this.setOpen(false); - } - return visibilityChanged; -}; - - -/** - * Enables/disables the menu button based on the value of the argument, and - * updates its CSS styling. Also hides the popup menu if the button is being - * disabled. - * @param {boolean} enable Whether to enable or disable the button. - * @override - */ -goog.ui.MenuButton.prototype.setEnabled = function(enable) { - goog.ui.MenuButton.superClass_.setEnabled.call(this, enable); - if (!this.isEnabled()) { - this.setOpen(false); - } -}; - - -/** - * @return {boolean} Whether the menu is aligned to the start of the button - * (left if the render direction is left-to-right, right if the render - * direction is right-to-left). - */ -goog.ui.MenuButton.prototype.isAlignMenuToStart = function() { - return this.alignToStart_; -}; - - -/** - * Sets whether the menu is aligned to the start or the end of the button. - * @param {boolean} alignToStart Whether the menu is to be aligned to the start - * of the button (left if the render direction is left-to-right, right if - * the render direction is right-to-left). - */ -goog.ui.MenuButton.prototype.setAlignMenuToStart = function(alignToStart) { - this.alignToStart_ = alignToStart; -}; - - -/** - * Sets whether the menu should scroll when it's too big to fix vertically on - * the screen. The css of the menu element should have overflow set to auto. - * Note: Adding or removing items while the menu is open will not work correctly - * if scrollOnOverflow is on. - * @param {boolean} scrollOnOverflow Whether the menu should scroll when too big - * to fit on the screen. If false, adjust logic will be used to try and - * reposition the menu to fit. - */ -goog.ui.MenuButton.prototype.setScrollOnOverflow = function(scrollOnOverflow) { - this.scrollOnOverflow_ = scrollOnOverflow; -}; - - -/** - * @return {boolean} Wether the menu will scroll when it's to big to fit - * vertically on the screen. - */ -goog.ui.MenuButton.prototype.isScrollOnOverflow = function() { - return this.scrollOnOverflow_; -}; - - -/** - * @return {boolean} Whether the attached menu is focusable. - */ -goog.ui.MenuButton.prototype.isFocusablePopupMenu = function() { - return this.isFocusablePopupMenu_; -}; - - -/** - * Sets whether the attached popup menu is focusable. If the popup menu is - * focusable, it may steal keyboard focus from the menu button, so the button - * will not hide the menu on blur. - * @param {boolean} focusable Whether the attached menu is focusable. - */ -goog.ui.MenuButton.prototype.setFocusablePopupMenu = function(focusable) { - // TODO(attila): The menu itself should advertise whether it is focusable. - this.isFocusablePopupMenu_ = focusable; -}; - - -/** - * Sets whether to render the menu as a sibling element of the button. - * Normally, the menu is a child of document.body. This option is useful if - * you need the menu to inherit styles from a common parent element, or if you - * otherwise need it to share a parent element for desired event handling. One - * example of the latter is if the parent is in a goog.ui.Popup, to ensure that - * clicks on the menu are considered being within the popup. - * @param {boolean} renderMenuAsSibling Whether we render the menu at the end - * of the dom or as a sibling to the button/label that renders the drop - * down. - */ -goog.ui.MenuButton.prototype.setRenderMenuAsSibling = function( - renderMenuAsSibling) { - this.renderMenuAsSibling_ = renderMenuAsSibling; -}; - - -/** - * Reveals the menu and hooks up menu-specific event handling. - * @deprecated Use {@link #setOpen} instead. - */ -goog.ui.MenuButton.prototype.showMenu = function() { - this.setOpen(true); -}; - - -/** - * Hides the menu and cleans up menu-specific event handling. - * @deprecated Use {@link #setOpen} instead. - */ -goog.ui.MenuButton.prototype.hideMenu = function() { - this.setOpen(false); -}; - - -/** - * Opens or closes the attached popup menu. - * @param {boolean} open Whether to open or close the menu. - * @param {goog.events.Event=} opt_e Mousedown event that caused the menu to - * be opened. - * @override - */ -goog.ui.MenuButton.prototype.setOpen = function(open, opt_e) { - goog.ui.MenuButton.superClass_.setOpen.call(this, open); - if (this.menu_ && this.hasState(goog.ui.Component.State.OPENED) == open) { - if (open) { - if (!this.menu_.isInDocument()) { - if (this.renderMenuAsSibling_) { - this.menu_.render(/** @type {Element} */ ( - this.getElement().parentNode)); - } else { - this.menu_.render(); - } - } - this.viewportBox_ = - goog.style.getVisibleRectForElement(this.getElement()); - this.buttonRect_ = goog.style.getBounds(this.getElement()); - this.positionMenu(); - this.menu_.setHighlightedIndex(-1); - } else { - this.setActive(false); - this.menu_.setMouseButtonPressed(false); - - // Clear any remaining a11y state. - if (this.getElement()) { - goog.dom.a11y.setState(this.getElement(), - goog.dom.a11y.State.ACTIVEDESCENDANT, ''); - } - - // Clear any sizes that might have been stored. - if (goog.isDefAndNotNull(this.originalSize_)) { - this.originalSize_ = undefined; - var elem = this.menu_.getElement(); - if (elem) { - goog.style.setSize(elem, '', ''); - } - } - } - this.menu_.setVisible(open, false, opt_e); - // In Pivot Tables the menu button somehow gets disposed of during the - // setVisible call, causing attachPopupListeners_ to fail. - // TODO(user): Debug what happens. - if (!this.isDisposed()) { - this.attachPopupListeners_(open); - } - } -}; - - -/** - * Positions the menu under the button. May be called directly in cases when - * the menu size is known to change. - */ -goog.ui.MenuButton.prototype.positionMenu = function() { - if (!this.menu_.isInDocument()) { - return; - } - - var positionElement = this.positionElement_ || this.getElement(); - - var position = this.menuPosition_; - if (!position) { - var anchorCorner = this.isAlignMenuToStart() ? - goog.positioning.Corner.BOTTOM_START : - goog.positioning.Corner.BOTTOM_END; - position = new goog.positioning.MenuAnchoredPosition(positionElement, - anchorCorner, /* opt_adjust */ !this.scrollOnOverflow_, - /* opt_resize */ this.scrollOnOverflow_); - } - - var elem = this.menu_.getElement(); - if (!this.menu_.isVisible()) { - elem.style.visibility = 'hidden'; - goog.style.showElement(elem, true); - } - - if (!this.originalSize_ && this.scrollOnOverflow_) { - this.originalSize_ = goog.style.getSize(elem); - } - var popupCorner = goog.positioning.flipCornerVertical(position.corner); - position.reposition(elem, popupCorner, this.menuMargin_, this.originalSize_); - - if (!this.menu_.isVisible()) { - goog.style.showElement(elem, false); - elem.style.visibility = 'visible'; - } -}; - - -/** - * Periodically repositions the menu while it is visible. - * - * @param {goog.events.Event} e An event object. - * @private - */ -goog.ui.MenuButton.prototype.onTick_ = function(e) { - // Call positionMenu() only if the button position or size was - // changed, or if the window's viewport was changed. - var currentButtonRect = goog.style.getBounds(this.getElement()); - var currentViewport = goog.style.getVisibleRectForElement(this.getElement()); - if (!goog.math.Rect.equals(this.buttonRect_, currentButtonRect) || - !goog.math.Box.equals(this.viewportBox_, currentViewport)) { - this.buttonRect_ = currentButtonRect; - this.viewportBox_ = currentViewport; - this.positionMenu(); - } -}; - - -/** - * Attaches or detaches menu event listeners to/from the given menu. - * Called each time a menu is attached to or detached from the button. - * @param {goog.ui.Menu} menu Menu on which to listen for events. - * @param {boolean} attach Whether to attach or detach event listeners. - * @private - */ -goog.ui.MenuButton.prototype.attachMenuEventListeners_ = function(menu, - attach) { - var handler = this.getHandler(); - var method = attach ? handler.listen : handler.unlisten; - - // Handle events dispatched by menu items. - method.call(handler, menu, goog.ui.Component.EventType.ACTION, - this.handleMenuAction); - method.call(handler, menu, goog.ui.Component.EventType.HIGHLIGHT, - this.handleHighlightItem); - method.call(handler, menu, goog.ui.Component.EventType.UNHIGHLIGHT, - this.handleUnHighlightItem); -}; - - -/** - * Handles {@code HIGHLIGHT} events dispatched by the attached menu. - * @param {goog.events.Event} e Highlight event to handle. - */ -goog.ui.MenuButton.prototype.handleHighlightItem = function(e) { - goog.dom.a11y.setState(this.getElement(), - goog.dom.a11y.State.ACTIVEDESCENDANT, e.target.getElement().id); -}; - - -/** - * Handles UNHIGHLIGHT events dispatched by the associated menu. - * @param {goog.events.Event} e Unhighlight event to handle. - */ -goog.ui.MenuButton.prototype.handleUnHighlightItem = function(e) { - if (!this.menu_.getHighlighted()) { - goog.dom.a11y.setState(this.getElement(), - goog.dom.a11y.State.ACTIVEDESCENDANT, ''); - } -}; - - -/** - * Attaches or detaches event listeners depending on whether the popup menu - * is being shown or hidden. Starts listening for document mousedown events - * and for menu blur events when the menu is shown, and stops listening for - * these events when it is hidden. Called from {@link #setOpen}. - * @param {boolean} attach Whether to attach or detach event listeners. - * @private - */ -goog.ui.MenuButton.prototype.attachPopupListeners_ = function(attach) { - var handler = this.getHandler(); - var method = attach ? handler.listen : handler.unlisten; - - // Listen for document mousedown events in the capture phase, because - // the target may stop propagation of the event in the bubble phase. - method.call(handler, this.getDomHelper().getDocument(), - goog.events.EventType.MOUSEDOWN, this.handleDocumentMouseDown, true); - - // Only listen for blur events dispatched by the menu if it is focusable. - if (this.isFocusablePopupMenu()) { - method.call(handler, /** @type {goog.events.EventTarget} */ (this.menu_), - goog.ui.Component.EventType.BLUR, this.handleMenuBlur); - } - - method.call(handler, this.timer_, goog.Timer.TICK, this.onTick_); - if (attach) { - this.timer_.start(); - } else { - this.timer_.stop(); - } -}; - - -// Register a decorator factory function for goog.ui.MenuButtons. -goog.ui.registry.setDecoratorByClassName(goog.ui.MenuButtonRenderer.CSS_CLASS, - function() { - // MenuButton defaults to using MenuButtonRenderer. - return new goog.ui.MenuButton(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubutton_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubutton_test.html.svn-base deleted file mode 100644 index c6d6294..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubutton_test.html.svn-base +++ /dev/null @@ -1,520 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - - @author nicksantos@google.com (Nick Santos) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.MenuButton</title> -<style type='text/css'> -.goog-menu { - position: absolute; - color: #aaa; -} -</style> -<script src="../base.js"></script> -<script> - goog.require('goog.Timer'); - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.events.Event'); - goog.require('goog.events.EventType'); - goog.require('goog.events.KeyCodes'); - goog.require('goog.positioning'); - goog.require('goog.positioning.MenuAnchoredPosition'); - goog.require('goog.positioning.Overflow'); - goog.require('goog.style'); - goog.require('goog.testing.ExpectedFailures'); - goog.require('goog.testing.PropertyReplacer'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.recordFunction'); - goog.require('goog.ui.Menu'); - goog.require('goog.ui.MenuButton'); - goog.require('goog.ui.MenuItem'); - goog.require('goog.userAgent'); - goog.require('goog.userAgent.product'); -</script> -</head> -<body> -<iframe id="iframe1" src="menubutton_test_frame.html" width="400" height="400"> -</iframe> -<div id="positionElement" style="position: absolute; left: 205px"></div> -<script> - -var menuButton; -var clonedMenuButtonDom; -var expectedFailures = new goog.testing.ExpectedFailures(); - -// Mock out goog.positioning.positionAtCoordinate to always ignore failure when -// the window is too small, since we don't care about the viewport size on -// the selenium farm. -// TODO(nicksantos): Move this into a common location if we ever have enough -// code for a general goog.testing.ui library. -var originalPositionAtCoordinate = goog.positioning.positionAtCoordinate; -goog.positioning.positionAtCoordinate = function(absolutePos, movableElement, - movableElementCorner, opt_margin, opt_viewport, opt_overflow, - opt_preferredSize) { - return originalPositionAtCoordinate.call(this, absolutePos, movableElement, - movableElementCorner, opt_margin, opt_viewport, - goog.positioning.Overflow.IGNORE, opt_preferredSize); -}; - -function MyFakeEvent(keyCode) { - this.type = goog.events.KeyHandler.EventType.KEY; - this.keyCode = keyCode; - this.preventDefault = goog.nullFunction; - this.stopPropagation = goog.nullFunction; -} - -function setUp() { - clonedMenuButtonDom = goog.dom.getElement('demoMenuButton').cloneNode(true); - - menuButton = new goog.ui.MenuButton(); -} - -function tearDown() { - expectedFailures.handleTearDown(); - menuButton.dispose(); - - var element = goog.dom.getElement('demoMenuButton'); - element.parentNode.replaceChild(clonedMenuButtonDom, element); -} - -/** - * Open the menu and click on the menu item inside. - */ -function testBasicButtonBehavior() { - var node = goog.dom.getElement('demoMenuButton'); - menuButton.decorate(node); - goog.testing.events.fireClickSequence(node); - - assertTrue('Menu must open after click', menuButton.isOpen()); - - var menuItemClicked = 0; - var lastMenuItemClicked = null; - goog.events.listen(menuButton.getMenu(), - goog.ui.Component.EventType.ACTION, - function(e) { - menuItemClicked++; - lastMenuItemClicked = e.target - }); - - var menuItem2 = goog.dom.getElement('menuItem2'); - goog.testing.events.fireClickSequence(menuItem2); - assertFalse('Menu must close on clicking when open', menuButton.isOpen()); - assertEquals('Number of menu items clicked should be 1', 1, menuItemClicked); - assertEquals('menuItem2 should be the last menuitem clicked', menuItem2, - lastMenuItemClicked.getElement()); -} - -/** - * Open the menu, highlight first menuitem and then the second. - * Check if the aria-activedescendant property is set correctly. - */ -function testHighlightItemBehavior() { - var node = goog.dom.getElement('demoMenuButton'); - menuButton.decorate(node); - goog.testing.events.fireClickSequence(node); - - assertTrue('Menu must open after click', menuButton.isOpen()); - - menuButton.handleKeyEvent(new MyFakeEvent(goog.events.KeyCodes.DOWN)); - assertEquals('First menuitem must be the aria-activedescendant', - 'menuItem1', goog.dom.a11y.getState(menuButton.getElement(), - goog.dom.a11y.State.ACTIVEDESCENDANT)); - - menuButton.handleKeyEvent(new MyFakeEvent(goog.events.KeyCodes.DOWN)); - assertEquals('Second menuitem must be the aria-activedescendant', - 'menuItem2', goog.dom.a11y.getState(menuButton.getElement(), - goog.dom.a11y.State.ACTIVEDESCENDANT)); -} - -/** - * Open the menu and click on the menu item inside after exiting and entering - * the document once, to test proper setup/teardown behavior of MenuButton. - */ -function testButtonAfterEnterDocument() { - var node = goog.dom.getElement('demoMenuButton'); - menuButton.decorate(node); - - menuButton.exitDocument(); - menuButton.enterDocument(); - - goog.testing.events.fireClickSequence(node); - assertTrue('Menu must open after click', menuButton.isOpen()); - - var menuItem2 = goog.dom.getElement('menuItem2'); - goog.testing.events.fireClickSequence(menuItem2); - assertFalse('Menu must close on clicking when open', menuButton.isOpen()); -} - -/** - * Renders the menu button, moves its menu and then repositions to make sure the - * position is more or less ok. - */ -function testPositionMenu() { - var node = goog.dom.getElement('demoMenuButton'); - menuButton.decorate(node); - var menu = menuButton.getMenu(); - menu.setVisible(true, true); - - // Move to 500, 500 - menu.setPosition(500, 500); - - // Now reposition and make sure position is more or less ok. - menuButton.positionMenu(); - var menuNode = goog.dom.getElement('demoMenu'); - assertRoughlyEquals(menuNode.offsetTop, node.offsetTop + node.offsetHeight, - 20); - assertRoughlyEquals(menuNode.offsetLeft, node.offsetLeft, 20); -} - -/** - * Tests that calling positionMenu when the menu is not in the document does not - * throw an exception. - */ -function testPositionMenuNotInDocument() { - var menu = new goog.ui.Menu(); - menu.createDom(); - menuButton.setMenu(menu); - menuButton.positionMenu(); -} - -/** - * Shows the menu and moves the menu button, a timer correct the menu position. - */ -function testOpenedMenuPositionCorrection() { - var iframe = goog.dom.getElement('iframe1'); - var iframeDoc = goog.dom.getFrameContentDocument(iframe); - var iframeDom = goog.dom.getDomHelper(iframeDoc); - var iframeWindow = goog.dom.getWindow(iframeDoc); - - var button = new goog.ui.MenuButton(); - iframeWindow.scrollTo(0, 0); - var node = iframeDom.getElement('demoMenuButton'); - button.decorate(node); - var mockTimer = new goog.Timer(); - // Don't start the timer. We manually dispatch the Tick event. - mockTimer.start = goog.nullFunction; - button.timer_ = mockTimer; - - var replacer = new goog.testing.PropertyReplacer(); - var positionMenuCalled; - var origPositionMenu = goog.bind(button.positionMenu, button); - replacer.set(button, 'positionMenu', function() { - positionMenuCalled = true; - origPositionMenu(); - }); - - // Show the menu. - button.setOpen(true); - - // Confirm the menu position - var menuNode = iframeDom.getElement('demoMenu'); - assertRoughlyEquals(menuNode.offsetTop, node.offsetTop + node.offsetHeight, - 20); - assertRoughlyEquals(menuNode.offsetLeft, node.offsetLeft, 20); - - positionMenuCalled = false; - // A Tick event is dispatched. - mockTimer.dispatchEvent(goog.Timer.TICK); - assertFalse('positionMenu() shouldn\'t be called.', positionMenuCalled); - - // Move the menu button by DOM structure change - var p1 = iframeDom.createDom('p', null, iframeDom.createTextNode('foo')); - var p2 = iframeDom.createDom('p', null, iframeDom.createTextNode('foo')); - var p3 = iframeDom.createDom('p', null, iframeDom.createTextNode('foo')); - iframeDom.insertSiblingBefore(p1, node); - iframeDom.insertSiblingBefore(p2, node); - iframeDom.insertSiblingBefore(p3, node); - - // Confirm the menu is detached from the button. - assertTrue(Math.abs(node.offsetTop + node.offsetHeight - - menuNode.offsetTop) > 20); - - positionMenuCalled = false; - // A Tick event is dispatched. - mockTimer.dispatchEvent(goog.Timer.TICK); - assertTrue('positionMenu() should be called.', positionMenuCalled); - - // The menu is moved to appropriate position again. - assertRoughlyEquals(menuNode.offsetTop, node.offsetTop + node.offsetHeight, - 20); - - // Make the frame page scrollable. - var viewportHeight = iframeDom.getViewportSize().height; - var footer = iframeDom.getElement('footer'); - goog.style.setSize(footer, 1, viewportHeight * 2); - // Change the viewport offset. - iframeWindow.scrollTo(0, viewportHeight); - // A Tick event is dispatched and positionMenu() should be called. - positionMenuCalled = false; - mockTimer.dispatchEvent(goog.Timer.TICK); - assertTrue('positionMenu() should be called.', positionMenuCalled); - goog.style.setSize(footer, 1, 1); - - // Tear down. - iframeDom.removeNode(p1); - iframeDom.removeNode(p2); - iframeDom.removeNode(p3); - replacer.reset(); - button.dispose(); -} - -/** - * Use a different button to position the menu and make sure it does so - * correctly. - */ -function testAlternatePositioningElement() { - var node = goog.dom.getElement('demoMenuButton'); - menuButton.decorate(node); - - var posElement = goog.dom.getElement('positionElement'); - menuButton.setPositionElement(posElement); - - // Show the menu. - menuButton.setOpen(true); - - // Confirm the menu position - var menuNode = menuButton.getMenu().getElement(); - assertRoughlyEquals(menuNode.offsetTop, posElement.offsetTop - + posElement.offsetHeight, 20); - assertRoughlyEquals(menuNode.offsetLeft, posElement.offsetLeft, 20); -} - -/** - * Test forced positioning above the button. - */ -function testPositioningAboveAnchor() { - var node = goog.dom.getElement('demoMenuButton'); - menuButton.decorate(node); - - // Show the menu. - var position = new goog.positioning.MenuAnchoredPosition( - menuButton.getElement(), - goog.positioning.Corner.TOP_START, - /* opt_adjust */ false, /* opt_resize */ false); - menuButton.setMenuPosition(position); - menuButton.setAlignMenuToStart(true); // Should have no effect - menuButton.setScrollOnOverflow(true); // Should have no effect - menuButton.setOpen(true); - - // Confirm the menu position - var buttonBounds = goog.style.getBounds(node); - var menuNode = menuButton.getMenu().getElement(); - var menuBounds = goog.style.getBounds(menuNode); - - expectedFailures.expectFailureFor(isWinSafariBefore5()); - try { - assertRoughlyEquals(menuBounds.top + menuBounds.height, - buttonBounds.top, 3); - assertRoughlyEquals(menuBounds.left, buttonBounds.left, 3); - } catch (e) { - expectedFailures.handleException(e); - } - // For this test to be valid, the node must have non-trival height. - assertRoughlyEquals(node.offsetHeight, 19, 3); -} - -/** - * Test forced positioning below the button. - */ -function testPositioningBelowAnchor() { - var node = goog.dom.getElement('demoMenuButton'); - menuButton.decorate(node); - - // Show the menu. - // Show the menu. - var position = new goog.positioning.MenuAnchoredPosition( - menuButton.getElement(), - goog.positioning.Corner.BOTTOM_START, - /* opt_adjust */ false, /* opt_resize */ false); - menuButton.setMenuPosition(position); - menuButton.setAlignMenuToStart(true); // Should have no effect - menuButton.setScrollOnOverflow(true); // Should have no effect - menuButton.setOpen(true); - - // Confirm the menu position - var buttonBounds = goog.style.getBounds(node); - var menuNode = menuButton.getMenu().getElement(); - var menuBounds = goog.style.getBounds(menuNode); - - expectedFailures.expectFailureFor(isWinSafariBefore5()); - try { - assertRoughlyEquals(menuBounds.top, - buttonBounds.top + buttonBounds.height, 3); - assertRoughlyEquals(menuBounds.left, buttonBounds.left, 3); - } catch (e) { - expectedFailures.handleException(e); - } - // For this test to be valid, the node must have non-trival height. - assertRoughlyEquals(node.offsetHeight, 19, 3); -} - -function isWinSafariBefore5() { - return goog.userAgent.WINDOWS && goog.userAgent.product.SAFARI && - !goog.userAgent.isVersion(533); -} - -/** - * Tests that space, and only space, fire on key up. - */ -function testSpaceFireOnKeyUp() { - var node = goog.dom.getElement('demoMenuButton'); - menuButton.decorate(node); - - e = new goog.events.Event(goog.events.KeyHandler.EventType.KEY, menuButton); - e.preventDefault = goog.testing.recordFunction(); - e.keyCode = goog.events.KeyCodes.SPACE; - menuButton.handleKeyEvent(e); - assertFalse('Menu must not have been triggered by Space keypress', - menuButton.isOpen()); - assertNotNull('Page scrolling is prevented', e.preventDefault.getLastCall()); - - e = new goog.events.Event(goog.events.EventType.KEYUP, menuButton); - e.keyCode = goog.events.KeyCodes.SPACE; - menuButton.handleKeyEvent(e); - assertTrue('Menu must have been triggered by Space keyup', - menuButton.isOpen()); - menuButton.getMenu().setHighlightedIndex(0); - e = new goog.events.Event(goog.events.KeyHandler.EventType.KEY, menuButton); - e.keyCode = goog.events.KeyCodes.DOWN; - menuButton.handleKeyEvent(e); - assertEquals('Highlighted menu item must have hanged by Down keypress', - 1, - menuButton.getMenu().getHighlightedIndex()); - - menuButton.getMenu().setHighlightedIndex(0); - e = new goog.events.Event(goog.events.EventType.KEYUP, menuButton); - e.keyCode = goog.events.KeyCodes.DOWN; - menuButton.handleKeyEvent(e); - assertEquals('Highlighted menu item must not have changed by Down keyup', - 0, - menuButton.getMenu().getHighlightedIndex()); -} - - -/** - * Tests that preventing the button from closing also prevents the menu from - * being hidden. - */ -function testPreventHide() { - var node = goog.dom.getElement('demoMenuButton'); - menuButton.decorate(node); - menuButton.setDispatchTransitionEvents(goog.ui.Component.State.OPENED, true); - - // Show the menu. - menuButton.setOpen(true); - assertTrue('Menu button should be open.', menuButton.isOpen()); - assertTrue('Menu should be visible.', menuButton.getMenu().isVisible()); - - var key = goog.events.listen(menuButton, - goog.ui.Component.EventType.CLOSE, - function(event) { event.preventDefault(); }); - - // Try to hide the menu. - menuButton.setOpen(false); - assertTrue('Menu button should still be open.', menuButton.isOpen()); - assertTrue('Menu should still be visible.', menuButton.getMenu().isVisible()); - - // Remove listener and try again. - goog.events.unlistenByKey(key); - menuButton.setOpen(false); - assertFalse('Menu button should not be open.', menuButton.isOpen()); - assertFalse('Menu should not be visible.', menuButton.getMenu().isVisible()); -} - - -/** - * Tests that opening and closing the menu does not affect how adding or - * removing menu items changes the size of the menu. - */ -function testResizeOnItemAddOrRemove() { - var node = goog.dom.getElement('demoMenuButton'); - menuButton.decorate(node); - var menu = menuButton.getMenu(); - - // Show the menu. - menuButton.setOpen(true); - var originalSize = goog.style.getSize(menu.getElement()); - - // Check that removing an item while the menu is left open correctly changes - // the size of the menu. - // Remove an item using a method on Menu. - var item = menu.removeChildAt(0, true); - // Confirm size of menu changed. - var afterRemoveSize = goog.style.getSize(menu.getElement()); - assertTrue('Height of menu must decrease after removing a menu item.', - afterRemoveSize.height < originalSize.height); - - // Check that removing an item while the menu is closed, then opened - // (so that reposition is called) correctly changes the size of the menu. - // Hide menu. - menuButton.setOpen(false); - var item2 = menu.removeChildAt(0, true); - menuButton.setOpen(true); - // Confirm size of menu changed. - var afterRemoveAgainSize = goog.style.getSize(menu.getElement()); - assertTrue('Height of menu must decrease after removing a second menu item.', - afterRemoveAgainSize.height < afterRemoveSize.height); - - // Check that adding an item while the menu is opened, then closed, then - // opened, correctly changes the size of the menu. - // Add an item, this time using a MenuButton method. - menuButton.setOpen(true); - menuButton.addItem(item2); - menuButton.setOpen(false); - menuButton.setOpen(true); - // Confirm size of menu changed. - var afterAddSize = goog.style.getSize(menu.getElement()); - assertTrue('Height of menu must increase after adding a menu item.', - afterRemoveAgainSize.height < afterAddSize.height); - assertEquals( - 'Removing and adding back items must not change the height of a menu.', - afterRemoveSize.height, afterAddSize.height); - - // Add back the last item to keep state consistent. - menuButton.addItem(item); -} - -/** - * Try rendering the menu as a sibling rather than as a child of the dom. - */ -function testRenderMenuAsSibling() { - menuButton.setRenderMenuAsSibling(true); - menuButton.addItem(new goog.ui.MenuItem('Menu item 1')); - menuButton.addItem(new goog.ui.MenuItem('Menu item 2')); - // By default the menu is rendered into the top level dom and the button - // is rendered into whatever parent we provide. If we don't provide a - // parent then we aren't really testing anything, since both would be, by - // default, rendered into the top level dom, and therefore siblings. - menuButton.render(goog.dom.getElement('siblingTest')); - menuButton.setOpen(true); - assertEquals( - menuButton.getElement().parentNode, - menuButton.getMenu().getElement().parentNode); -} -</script> -<p> - Here's a menubutton defined in markup: -</p> -<div id="siblingTest"></div> -<div id="demoMenuButton" class="goog-menu-button"> - <div id="demoMenu" class="goog-menu"> - <div id='menuItem1' class="goog-menuitem">Annual Report.pdf</div> - <div id='menuItem2' class="goog-menuitem">Quarterly Update.pdf</div> - <div id='menuItem3' class="goog-menuitem">Enemies List.txt</div> - </div> -</div> - -<div id="footer"></div> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubutton_test_frame.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubutton_test_frame.html.svn-base deleted file mode 100644 index b918890..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubutton_test_frame.html.svn-base +++ /dev/null @@ -1,41 +0,0 @@ -<!DOCTYPE html> -<!-- - - @author tkent@google.com (TAMURA Kent) ---> -<html> -<!-- -Copyright 2009 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<style type='text/css'> -#demoMenuButton { - /* - * Set a fixed width because the button size can be changed by a scroll bar - * without it. - */ - width: 64px; -} -.goog-menu { - position: absolute; - color: #aaa; -} -</style> -</head> -<body> -<div id="demoMenuButton" class="goog-menu-button"> - Button - <div id="demoMenu" class="goog-menu"> - <div id='menuItem1' class="goog-menuitem">Annual Report.pdf</div> - <div id='menuItem2' class="goog-menuitem">Quarterly Update.pdf</div> - <div id='menuItem3' class="goog-menuitem">Enemies List.txt</div> - </div> -</div> - -<div id="footer"></div> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubuttonrenderer.js.svn-base deleted file mode 100644 index f51dc9b..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubuttonrenderer.js.svn-base +++ /dev/null @@ -1,227 +0,0 @@ -// 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. - */ -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.MenuButton} button Menu button to decorate the element. - * @param {Element} element Element to decorate. - * @return {Element} Decorated element. - */ -goog.ui.MenuButtonRenderer.prototype.decorate = function(button, element) { - // 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.showElement(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. - */ -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. - */ -goog.ui.MenuButtonRenderer.prototype.getCssClass = function() { - return goog.ui.MenuButtonRenderer.CSS_CLASS; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubuttonrenderer_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubuttonrenderer_test.html.svn-base deleted file mode 100644 index 97293b0..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menubuttonrenderer_test.html.svn-base +++ /dev/null @@ -1,161 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - - @author nicksantos@google.com (Nick Santos) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests for MenuButtonRenderer</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.dom.classes'); - goog.require('goog.events'); - goog.require('goog.events.Event'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.MenuButton'); - goog.require('goog.testing.ui.rendererasserts'); -</script> -</head> -<body> - -<div id='root'> - <!-- A parent to attach rendered buttons to --> - <div id='parent'></div> - - <!-- A button to decorate --> - <div id='decoratedButton'>Foo</div> -</div> - -<script> - -var decoratedButton; -var renderedButton; -var savedRootTree; - -function setUp() { - savedRootTree = goog.dom.getElement('root').cloneNode(true); - decoratedButton = null; - renderedButton = null; -} - -function tearDown() { - if (decoratedButton) { - decoratedButton.dispose(); - } - - if (renderedButton) { - renderedButton.dispose(); - } - - var root = goog.dom.getElement('root'); - root.parentNode.replaceChild(savedRootTree, root); -} - -function testRendererWithTextContent() { - renderedButton = new goog.ui.MenuButton('Foo'); - renderOnParent(renderedButton); - checkButtonCaption(renderedButton); - - decoratedButton = new goog.ui.MenuButton(); - decorateDemoButton(decoratedButton); - checkButtonCaption(decoratedButton); - - assertButtonsEqual(); -} - -function testRendererWithNodeContent() { - renderedButton = new goog.ui.MenuButton( - goog.dom.createDom('div', null, 'Foo')); - renderOnParent(renderedButton); - - var contentEl = renderedButton.getContentElement(); - if (goog.userAgent.IE || goog.userAgent.OPERA) { - assertHTMLEquals('<div unselectable="on">Foo</div>', contentEl.innerHTML); - } else { - assertHTMLEquals('<div>Foo</div>', contentEl.innerHTML); - } - assertTrue(hasInlineBlock(contentEl)); -} - -function testSetContent() { - renderedButton = new goog.ui.MenuButton(); - renderOnParent(renderedButton); - - var contentEl = renderedButton.getContentElement(); - assertHTMLEquals('', contentEl.innerHTML); - - renderedButton.setContent('Foo'); - contentEl = renderedButton.getContentElement(); - assertHTMLEquals('Foo', contentEl.innerHTML); - assertTrue(hasInlineBlock(contentEl)); - - renderedButton.setContent(goog.dom.createDom('div', null, 'Bar')); - contentEl = renderedButton.getContentElement(); - assertHTMLEquals('<div>Bar</div>', contentEl.innerHTML); - - renderedButton.setContent('Foo'); - contentEl = renderedButton.getContentElement(); - assertHTMLEquals('Foo', contentEl.innerHTML); -} - -function assertButtonsEqual() { - assertHTMLEquals( - "Rendered button and decorated button produced different HTML!", - renderedButton.getElement().innerHTML, - decoratedButton.getElement().innerHTML); -} - -/** - * Render the given button as a child of 'parent'. - * @param {goog.ui.Button} button A button with content 'Foo'. - */ -function renderOnParent(button) { - button.render(goog.dom.getElement('parent')); -} - -/** - * Decaorate the button with id 'button'. - * @param {goog.ui.Button} button A button with no content. - */ -function decorateDemoButton(button) { - button.decorate(goog.dom.getElement('decoratedButton')); -} - -/** - * Verify that the button's caption is never the direct - * child of an inline-block element. - * @param {goog.ui.Button} button A button. - */ -function checkButtonCaption(button) { - var contentElement = button.getContentElement(); - assertEquals('Foo', contentElement.innerHTML); - assertTrue(hasInlineBlock(contentElement)); - assert(hasInlineBlock(contentElement.parentNode)); - - button.setContent('Bar'); - contentElement = button.getContentElement(); - assertEquals('Bar', contentElement.innerHTML); - assertTrue(hasInlineBlock(contentElement)); - assert(hasInlineBlock(contentElement.parentNode)); -} - -function hasInlineBlock(el) { - return goog.dom.classes.has(el, 'goog-inline-block'); -} - -function testDoesntCallGetCssClassInConstructor() { - goog.testing.ui.rendererasserts. - assertNoGetCssClassCallsInConstructor(goog.ui.MenuButtonRenderer); -} -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuheader.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuheader.js.svn-base deleted file mode 100644 index 36b2852..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuheader.js.svn-base +++ /dev/null @@ -1,62 +0,0 @@ -// 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); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuheaderrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuheaderrenderer.js.svn-base deleted file mode 100644 index e71514f..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuheaderrenderer.js.svn-base +++ /dev/null @@ -1,55 +0,0 @@ -// 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.MenuHeader}s. - * - */ - -goog.provide('goog.ui.MenuHeaderRenderer'); - -goog.require('goog.dom'); -goog.require('goog.dom.classes'); -goog.require('goog.ui.ControlRenderer'); - - - -/** - * Renderer for menu headers. - * @constructor - * @extends {goog.ui.ControlRenderer} - */ -goog.ui.MenuHeaderRenderer = function() { - goog.ui.ControlRenderer.call(this); -}; -goog.inherits(goog.ui.MenuHeaderRenderer, goog.ui.ControlRenderer); -goog.addSingletonGetter(goog.ui.MenuHeaderRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.MenuHeaderRenderer.CSS_CLASS = goog.getCssName('goog-menuheader'); - - -/** - * Returns the CSS class to be applied to the root element of components - * rendered using this renderer. - * @return {string} Renderer-specific CSS class. - */ -goog.ui.MenuHeaderRenderer.prototype.getCssClass = function() { - return goog.ui.MenuHeaderRenderer.CSS_CLASS; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuitem.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuitem.js.svn-base deleted file mode 100644 index a172e03..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuitem.js.svn-base +++ /dev/null @@ -1,235 +0,0 @@ -// 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 items in menus. - * @see goog.ui.Menu - * - * @see ../demos/menuitem.html - */ - -goog.provide('goog.ui.MenuItem'); - -goog.require('goog.array'); -goog.require('goog.dom'); -goog.require('goog.dom.classes'); -goog.require('goog.events.KeyCodes'); -goog.require('goog.math.Coordinate'); -goog.require('goog.string'); -goog.require('goog.ui.Component.State'); -goog.require('goog.ui.Control'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.MenuItemRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * Class representing an item in a menu. - * - * @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 {*=} opt_model Data/model associated with the menu item. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper used for - * document interactions. - * @param {goog.ui.MenuItemRenderer=} opt_renderer Optional renderer. - * @constructor - * @extends {goog.ui.Control} - */ -goog.ui.MenuItem = function(content, opt_model, opt_domHelper, opt_renderer) { - goog.ui.Control.call(this, content, opt_renderer || - goog.ui.MenuItemRenderer.getInstance(), opt_domHelper); - this.setValue(opt_model); -}; -goog.inherits(goog.ui.MenuItem, goog.ui.Control); - - -/** - * The access key for this menu item. This key allows the user to quickly - * trigger this item's action with they keyboard. For example, setting the - * mnenomic key to 70 (F), when the user opens the menu and hits "F," the - * menu item is triggered. - * - * @type {goog.events.KeyCodes} - * @private - */ -goog.ui.MenuItem.mnemonicKey_; - - -/** - * The class set on an element that contains a parenthetical mnemonic key hint. - * Parenthetical hints are added to items in which the mnemonic key is not found - * within the menu item's caption itself. For example, if you have a menu item - * with the caption "Record," but its mnemonic key is "I", the caption displayed - * in the menu will appear as "Record (I)". - * - * @type {string} - * @private - */ -goog.ui.MenuItem.MNEMONIC_WRAPPER_CLASS_ = - goog.getCssName('goog-menuitem-mnemonic-separator'); - - -/** - * The class set on an element that contains a keyboard accelerator hint. - * @type {string} - * @private - */ -goog.ui.MenuItem.ACCELERATOR_CLASS_ = goog.getCssName('goog-menuitem-accel'); - - -// goog.ui.Component and goog.ui.Control implementation. - - -/** - * Returns the value associated with the menu item. The default implementation - * returns the model object associated with the item (if any), or its caption. - * @return {*} Value associated with the menu item, if any, or its caption. - */ -goog.ui.MenuItem.prototype.getValue = function() { - var model = this.getModel(); - return model != null ? model : this.getCaption(); -}; - - -/** - * Sets the value associated with the menu item. The default implementation - * stores the value as the model of the menu item. - * @param {*} value Value to be associated with the menu item. - */ -goog.ui.MenuItem.prototype.setValue = function(value) { - this.setModel(value); -}; - - -/** - * Sets the menu item to be selectable or not. Set to true for menu items - * that represent selectable options. - * @param {boolean} selectable Whether the menu item is selectable. - */ -goog.ui.MenuItem.prototype.setSelectable = function(selectable) { - this.setSupportedState(goog.ui.Component.State.SELECTED, selectable); - if (this.isChecked() && !selectable) { - this.setChecked(false); - } - - var element = this.getElement(); - if (element) { - this.getRenderer().setSelectable(this, element, selectable); - } -}; - - -/** - * Sets the menu item to be checkable or not. Set to true for menu items - * that represent checkable options. - * @param {boolean} checkable Whether the menu item is checkable. - */ -goog.ui.MenuItem.prototype.setCheckable = function(checkable) { - this.setSupportedState(goog.ui.Component.State.CHECKED, checkable); - - var element = this.getElement(); - if (element) { - this.getRenderer().setCheckable(this, element, checkable); - } -}; - - -/** - * Returns the text caption of the component while ignoring accelerators. - * @override - */ -goog.ui.MenuItem.prototype.getCaption = function() { - var content = this.getContent(); - if (goog.isArray(content)) { - var acceleratorClass = goog.ui.MenuItem.ACCELERATOR_CLASS_; - var mnemonicWrapClass = goog.ui.MenuItem.MNEMONIC_WRAPPER_CLASS_; - var caption = goog.array.map(content, function(node) { - var classes = goog.dom.classes.get(node); - if (goog.array.contains(classes, acceleratorClass) || - goog.array.contains(classes, mnemonicWrapClass)) { - return ''; - } else { - return goog.dom.getRawTextContent(node); - } - }).join(''); - return goog.string.collapseBreakingSpaces(caption); - } - return goog.ui.MenuItem.superClass_.getCaption.call(this); -}; - - -/** @override */ -goog.ui.MenuItem.prototype.handleMouseUp = function(e) { - var parentMenu = /** @type {goog.ui.Menu} */ (this.getParent()); - - if (parentMenu) { - var oldCoords = parentMenu.openingCoords; - // Clear out the saved opening coords immediately so they're not used twice. - parentMenu.openingCoords = null; - - if (oldCoords && goog.isNumber(e.clientX)) { - var newCoords = new goog.math.Coordinate(e.clientX, e.clientY); - if (goog.math.Coordinate.equals(oldCoords, newCoords)) { - // This menu was opened by a mousedown and we're handling the consequent - // mouseup. The coords haven't changed, meaning this was a simple click, - // not a click and drag. Don't do the usual behavior because the menu - // just popped up under the mouse and the user didn't mean to activate - // this item. - return; - } - } - } - - goog.base(this, 'handleMouseUp', e); -}; - - -/** @override */ -goog.ui.MenuItem.prototype.handleKeyEventInternal = function(e) { - if (e.keyCode == this.getMnemonic() && this.performActionInternal(e)) { - return true; - } else { - return goog.base(this, 'handleKeyEventInternal', e); - } -}; - - -/** - * Sets the mnemonic key code. The mnemonic is the key associated with this - * action. - * @param {goog.events.KeyCodes} key The key code. - */ -goog.ui.MenuItem.prototype.setMnemonic = function(key) { - this.mnemonicKey_ = key; -}; - - -/** - * Gets the mnemonic key code. The mnemonic is the key associated with this - * action. - * @return {goog.events.KeyCodes} The key code of the mnemonic key. - */ -goog.ui.MenuItem.prototype.getMnemonic = function() { - return this.mnemonicKey_; -}; - - -// Register a decorator factory function for goog.ui.MenuItems. -goog.ui.registry.setDecoratorByClassName(goog.ui.MenuItemRenderer.CSS_CLASS, - function() { - // MenuItem defaults to using MenuItemRenderer. - return new goog.ui.MenuItem(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuitem_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuitem_test.html.svn-base deleted file mode 100644 index fb8103a..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuitem_test.html.svn-base +++ /dev/null @@ -1,559 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.MenuItem</title> - <script src="../base.js"></script> - <script> - goog.require('goog.array'); - goog.require('goog.dom'); - goog.require('goog.dom.NodeType'); - goog.require('goog.dom.classes'); - goog.require('goog.events.KeyCodes'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.recordFunction'); - goog.require('goog.ui.Component.State'); - goog.require('goog.ui.MenuItem'); - goog.require('goog.ui.MenuItemRenderer'); - </script> -</head> -<body> - <div id="sandbox"></div> - <div id="parentComponent"></div> - <script> - var sandbox = goog.dom.getElement('sandbox'); - var item; - - function setUp() { - item = new goog.ui.MenuItem('Item'); - } - - function tearDown() { - item.dispose(); - goog.dom.removeChildren(sandbox); - } - - function testMenuItem() { - assertNotNull('Instance must not be null', item); - assertEquals('Renderer must default to MenuItemRenderer singleton', - goog.ui.MenuItemRenderer.getInstance(), item.getRenderer()); - assertEquals('Content must have expected value', 'Item', - item.getContent()); - assertEquals('Caption must default to the content', item.getContent(), - item.getCaption()); - assertEquals('Value must default to the caption', item.getCaption(), - item.getValue()); - } - - function testMenuItemConstructor() { - var model = 'Hello'; - var fakeDom = {}; - var fakeRenderer = {}; - - var menuItem = new goog.ui.MenuItem('Item', model, fakeDom, fakeRenderer); - assertEquals('Content must have expected value', 'Item', - menuItem.getContent()); - assertEquals('Caption must default to the content', menuItem.getContent(), - menuItem.getCaption()); - assertEquals('Model must be set', model, menuItem.getModel()); - assertNotEquals('Value must not equal the caption', menuItem.getCaption(), - menuItem.getValue()); - assertEquals('Value must equal the model', model, menuItem.getValue()); - assertEquals('DomHelper must be set', fakeDom, menuItem.getDomHelper()); - assertEquals('Renderer must be set', fakeRenderer, - menuItem.getRenderer()); - } - - function testGetValue() { - assertUndefined('Model must be undefined by default', item.getModel()); - assertEquals('Without a model, value must default to the caption', - item.getCaption(), item.getValue()); - item.setModel('Foo'); - assertEquals('With a model, value must default to the model', - item.getModel(), item.getValue()); - } - - function testSetValue() { - assertUndefined('Model must be undefined by default', item.getModel()); - assertEquals('Without a model, value must default to the caption', - item.getCaption(), item.getValue()); - item.setValue(17); - assertEquals('Value must be set', 17, item.getValue()); - assertEquals('Value and model must be the same', item.getValue(), - item.getModel()); - } - - function testGetSetContent() { - assertEquals('Content must have expected value', 'Item', - item.getContent()); - item.setContent(goog.dom.createDom('div', 'foo', 'Foo')); - assertEquals('Content must be an element', goog.dom.NodeType.ELEMENT, - item.getContent().nodeType); - assertHTMLEquals('Content must be the expected element', - '<div class="foo">Foo</div>', - goog.dom.getOuterHtml(item.getContent())); - } - - function testGetSetCaption() { - assertEquals('Caption must have expected value', 'Item', - item.getCaption()); - item.setCaption('Hello, world!'); - assertTrue('Caption must be a string', goog.isString(item.getCaption())); - assertEquals('Caption must have expected value', 'Hello, world!', - item.getCaption()); - item.setContent(goog.dom.createDom('div', 'foo', 'Foo')); - assertTrue('Caption must be a string', goog.isString(item.getCaption())); - assertEquals('Caption must have expected value', 'Foo', - item.getCaption()); - } - - function testGetSetContentAfterCreateDom() { - item.createDom(); - assertEquals('Content must have expected value', 'Item', - item.getContent()); - item.setContent(goog.dom.createDom('div', 'foo', 'Foo')); - assertEquals('Content must be an element', goog.dom.NodeType.ELEMENT, - item.getContent().nodeType); - assertHTMLEquals('Content must be the expected element', - '<div class="foo">Foo</div>', - goog.dom.getOuterHtml(item.getContent())); - } - - function testGetSetCaptionAfterCreateDom() { - item.createDom(); - assertEquals('Caption must have expected value', 'Item', - item.getCaption()); - item.setCaption('Hello, world!'); - assertTrue('Caption must be a string', goog.isString(item.getCaption())); - assertEquals('Caption must have expected value', 'Hello, world!', - item.getCaption()); - item.setContent(goog.dom.createDom('div', 'foo', 'Foo')); - assertTrue('Caption must be a string', goog.isString(item.getCaption())); - assertEquals('Caption must have expected value', 'Foo', - item.getCaption()); - - var arrayContent = goog.array.clone(goog.dom.htmlToDocumentFragment( - ' <b> \xa0foo</b><i> bar</i> ').childNodes); - item.setContent(arrayContent); - assertEquals('whitespaces must be normalized in the caption', - '\xa0foo bar', item.getCaption()); - } - - function testSetSelectable() { - assertFalse('Item must not be selectable by default', - item.isSupportedState(goog.ui.Component.State.SELECTED)); - item.setSelectable(true); - assertTrue('Item must be selectable', - item.isSupportedState(goog.ui.Component.State.SELECTED)); - item.setSelected(true); - assertTrue('Item must be selected', item.isSelected()); - assertFalse('Item must not be checked', item.isChecked()); - item.setSelectable(false); - assertFalse('Item must not no longer be selectable', - item.isSupportedState(goog.ui.Component.State.SELECTED)); - assertFalse('Item must no longer be selected', item.isSelected()); - assertFalse('Item must not be checked', item.isChecked()); - } - - function testSetCheckable() { - assertFalse('Item must not be checkable by default', - item.isSupportedState(goog.ui.Component.State.CHECKED)); - item.setCheckable(true); - assertTrue('Item must be checkable', - item.isSupportedState(goog.ui.Component.State.CHECKED)); - item.setChecked(true); - assertTrue('Item must be checked', item.isChecked()); - assertFalse('Item must not be selected', item.isSelected()); - item.setCheckable(false); - assertFalse('Item must not no longer be checkable', - item.isSupportedState(goog.ui.Component.State.CHECKED)); - assertFalse('Item must no longer be checked', item.isChecked()); - assertFalse('Item must not be selected', item.isSelected()); - } - - function testSetSelectableBeforeCreateDom() { - item.setSelectable(true); - item.createDom(); - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - item.setSelectable(false); - assertFalse('Item must no longer have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - } - - function testSetCheckableBeforeCreateDom() { - item.setCheckable(true); - item.createDom(); - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - item.setCheckable(false); - assertFalse('Item must no longer have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - } - - function testSetSelectableAfterCreateDom() { - item.createDom(); - item.setSelectable(true); - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - item.setSelectable(false); - assertFalse('Item must no longer have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - } - - function testSetCheckableAfterCreateDom() { - item.createDom(); - item.setCheckable(true); - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - item.setCheckable(false); - assertFalse('Item must no longer have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - } - - function testSelectableBehavior() { - item.setSelectable(true); - item.render(sandbox); - assertFalse('Item must not be selected by default', item.isSelected()); - item.performActionInternal(); - assertTrue('Item must be selected', item.isSelected()); - item.performActionInternal(); - assertTrue('Item must still be selected', item.isSelected()); - } - - function testCheckableBehavior() { - item.setCheckable(true); - item.render(sandbox); - assertFalse('Item must not be checked by default', item.isChecked()); - item.performActionInternal(); - assertTrue('Item must be checked', item.isChecked()); - item.performActionInternal(); - assertFalse('Item must no longer be checked', item.isChecked()); - } - - function testGetSetContentForItemWithCheckBox() { - item.setSelectable(true); - item.createDom(); - - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - assertEquals('getContent() must not return the checkbox structure', - 'Item', item.getContent()); - - item.setContent('Hello'); - assertEquals('getContent() must not return the checkbox structure', - 'Hello', item.getContent()); - assertTrue('Item must still have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - - item.setContent(goog.dom.createDom('span', 'foo', 'Foo')); - assertEquals('getContent() must return element', - goog.dom.NodeType.ELEMENT, item.getContent().nodeType); - assertTrue('Item must still have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - - item.setContent(null); - assertNull('getContent() must return null', item.getContent()); - assertTrue('Item must still have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - } - - function testGetSetCaptionForItemWithCheckBox() { - item.setCheckable(true); - item.createDom(); - - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - assertEquals('getCaption() must not return the checkbox structure', - 'Item', item.getCaption()); - - item.setCaption('Hello'); - assertEquals('getCaption() must not return the checkbox structure', - 'Hello', item.getCaption()); - assertTrue('Item must still have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - - item.setContent(goog.dom.createDom('span', 'foo', 'Foo')); - assertEquals('getCaption() must return text content', 'Foo', - item.getCaption()); - assertTrue('Item must still have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - - item.setCaption(''); - assertEquals('getCaption() must return empty string', '', - item.getCaption()); - assertTrue('Item must still have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - } - - function testGetSetCaptionForItemWithAccelerators() { - var contentArr = []; - contentArr.push(goog.dom.createDom('span', - goog.getCssName('goog-menuitem-accel'), 'Ctrl+1')); - contentArr.push(goog.dom.createTextNode('Hello')); - item.setCaption(contentArr); - assertEquals('getCaption() must not return the accelerator', 'Hello', - item.getCaption()); - - item.setCaption(''); - assertEquals('getCaption() must return empty string', '', - item.getCaption()); - } - - function testGetSetCaptionForItemWithMnemonics() { - var contentArr = []; - contentArr.push(goog.dom.createDom('span', - goog.getCssName('goog-menuitem-mnemonic-hint'), 'H')); - contentArr.push(goog.dom.createTextNode('ello')); - item.setCaption(contentArr); - assertEquals('getCaption() must not return hint markup', 'Hello', - item.getCaption()); - - contentArr = []; - contentArr.push(goog.dom.createTextNode('Hello')); - contentArr.push(goog.dom.createDom('span', - goog.getCssName('goog-menuitem-mnemonic-separator'), '(', - goog.dom.createDom('span', - goog.getCssName('goog-menuitem-mnemonic-hint'), 'J'), ')')); - item.setCaption(contentArr); - assertEquals('getCaption() must not return the paranethetical mnemonic', - 'Hello', item.getCaption()); - - item.setCaption(''); - assertEquals('getCaption() must return the empty string', '', - item.getCaption()); - } - - function testHandleKeyEventInternalWithMnemonic() { - item.performActionInternal = - goog.testing.recordFunction(item.performActionInternal); - item.setMnemonic(goog.events.KeyCodes.F); - item.handleKeyEventInternal({'keyCode': goog.events.KeyCodes.F}); - assertEquals('performActionInternal must be called', 1, - item.performActionInternal.getCallCount()); - } - - function testHandleKeyEventInternalWithoutMnemonic() { - item.performActionInternal = goog.testing.recordFunction( - item.performActionInternal); - item.handleKeyEventInternal({'keyCode': goog.events.KeyCodes.F}); - assertEquals('performActionInternal must not be called without a' + - ' mnemonic', 0, item.performActionInternal.getCallCount()); - } - - function testRender() { - item.render(sandbox); - var contentElement = item.getContentElement(); - assertNotNull('Content element must exist', contentElement); - assertTrue('Content element must have expected class name', - goog.dom.classes.has(contentElement, - item.getRenderer().getStructuralCssClass() + '-content')); - assertHTMLEquals('Content element must have expected structure', - 'Item', contentElement.innerHTML); - } - - function testRenderSelectableItem() { - item.setSelectable(true); - item.render(sandbox); - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - assertEquals('getCaption() return expected value', 'Item', - item.getCaption()); - } - - function testRenderSelectedItem() { - item.setSelectable(true); - item.setSelected(true); - item.render(sandbox); - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - assertTrue('Item must have selected style', - goog.dom.classes.has(item.getElement(), - item.getRenderer().getClassForState( - goog.ui.Component.State.SELECTED))); - } - - function testRenderCheckableItem() { - item.setCheckable(true); - item.render(sandbox); - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - assertEquals('getCaption() return expected value', 'Item', - item.getCaption()); - } - - function testRenderCheckedItem() { - item.setCheckable(true); - item.setChecked(true); - item.render(sandbox); - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - assertTrue('Item must have checked style', - goog.dom.classes.has(item.getElement(), - item.getRenderer().getClassForState( - goog.ui.Component.State.CHECKED))); - } - - function testDecorate() { - sandbox.innerHTML = '<div id="foo">Foo</div>'; - var foo = goog.dom.getElement('foo'); - item.decorate(foo); - assertEquals('Decorated element must be as expected', foo, - item.getElement()); - assertTrue('Decorated element must have expected class name', - goog.dom.classes.has(item.getElement(), - item.getRenderer().getCssClass())); - assertEquals('Content element must be the decorated element\'s child', - item.getContentElement(), item.getElement().firstChild); - assertHTMLEquals('Content must have expected structure', 'Foo', - item.getContentElement().innerHTML); - } - - function testDecorateCheckableItem() { - sandbox.innerHTML = '<div id="foo" class="goog-option">Foo</div>'; - var foo = goog.dom.getElement('foo'); - item.decorate(foo); - assertEquals('Decorated element must be as expected', foo, - item.getElement()); - assertTrue('Decorated element must have expected class name', - goog.dom.classes.has(item.getElement(), - item.getRenderer().getCssClass())); - assertEquals('Content element must be the decorated element\'s child', - item.getContentElement(), item.getElement().firstChild); - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - assertFalse('Item must not be checked', item.isChecked()); - } - - function testDecorateCheckedItem() { - sandbox.innerHTML = - '<div id="foo" class="goog-option goog-option-selected">Foo</div>'; - var foo = goog.dom.getElement('foo'); - item.decorate(foo); - assertEquals('Decorated element must be as expected', foo, - item.getElement()); - assertSameElements('Decorated element must have expected class names', - ['goog-menuitem', 'goog-option', 'goog-option-selected'], - goog.dom.classes.get(item.getElement())); - assertEquals('Content element must be the decorated element\'s child', - item.getContentElement(), item.getElement().firstChild); - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - assertTrue('Item must be checked', item.isChecked()); - } - - function testDecorateTemplate() { - sandbox.innerHTML = '<div id="foo" class="goog-menuitem">' + - '<div class="goog-menuitem-content">Foo</div></div>'; - var foo = goog.dom.getElement('foo'); - item.decorate(foo); - assertEquals('Decorated element must be as expected', foo, - item.getElement()); - assertTrue('Decorated element must have expected class name', - goog.dom.classes.has(item.getElement(), - item.getRenderer().getCssClass())); - assertEquals('Content element must be the decorated element\'s child', - item.getContentElement(), item.getElement().firstChild); - assertHTMLEquals('Content must have expected structure', 'Foo', - item.getContentElement().innerHTML); - } - - function testDecorateCheckableItemTemplate() { - sandbox.innerHTML = '<div id="foo" class="goog-menuitem goog-option">' + - '<div class="goog-menuitem-content">' + - '<div class="goog-menuitem-checkbox"></div>' + - 'Foo</div></div>'; - var foo = goog.dom.getElement('foo'); - item.decorate(foo); - assertEquals('Decorated element must be as expected', foo, - item.getElement()); - assertTrue('Decorated element must have expected class name', - goog.dom.classes.has(item.getElement(), - item.getRenderer().getCssClass())); - assertEquals('Content element must be the decorated element\'s child', - item.getContentElement(), item.getElement().firstChild); - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - assertEquals('Item must have exactly one checkbox structure', 1, - goog.dom.getElementsByTagNameAndClass('div', 'goog-menuitem-checkbox', - item.getElement()).length); - assertFalse('Item must not be checked', item.isChecked()); - } - - function testDecorateCheckedItemTemplate() { - sandbox.innerHTML = '<div id="foo" ' + - 'class="goog-menuitem goog-option goog-option-selected">' + - '<div class="goog-menuitem-content">' + - '<div class="goog-menuitem-checkbox"></div>' + - 'Foo</div></div>'; - var foo = goog.dom.getElement('foo'); - item.decorate(foo); - assertEquals('Decorated element must be as expected', foo, - item.getElement()); - assertSameElements('Decorated element must have expected class names', - ['goog-menuitem', 'goog-option', 'goog-option-selected'], - goog.dom.classes.get(item.getElement())); - assertEquals('Content element must be the decorated element\'s child', - item.getContentElement(), item.getElement().firstChild); - assertTrue('Item must have checkbox structure', - item.getRenderer().hasCheckBoxStructure(item.getElement())); - assertEquals('Item must have exactly one checkbox structure', 1, - goog.dom.getElementsByTagNameAndClass('div', 'goog-menuitem-checkbox', - item.getElement()).length); - assertTrue('Item must be checked', item.isChecked()); - } - - /** @bug 1463524 */ - function testHandleMouseUp() { - var COORDS_1 = new goog.math.Coordinate(1, 1); - var COORDS_2 = new goog.math.Coordinate(2, 2); - item.setActive(true); - // Override performActionInternal() for testing purposes. - var actionPerformed; - item.performActionInternal = function() { - actionPerformed = true; - return true; - }; - item.render(sandbox); - - // Scenario 1: item has no parent. - actionPerformed = false; - item.setActive(true); - goog.testing.events.fireMouseUpEvent(item.getElement()); - assertTrue('Action should be performed on mouseup', actionPerformed); - - // Scenario 2: item has a parent. - actionPerformed = false; - item.setActive(true); - var parent = new goog.ui.Component(); - var parentElem = goog.dom.getElement('parentComponent'); - parent.render(parentElem); - parent.addChild(item); - parent.openingCoords = COORDS_1; - goog.testing.events.fireMouseUpEvent( - item.getElement(), undefined, COORDS_2); - assertTrue('Action should be performed on mouseup', actionPerformed); - - // Scenario 3: item has a parent which was opened during mousedown, and - // item, and now the mouseup fires at the same coords. - actionPerformed = false; - item.setActive(true); - parent.openingCoords = COORDS_2; - goog.testing.events.fireMouseUpEvent( - item.getElement(), undefined, COORDS_2); - assertFalse('Action should not be performed on mouseup', actionPerformed); - } - - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuitemrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuitemrenderer.js.svn-base deleted file mode 100644 index 76077be..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuitemrenderer.js.svn-base +++ /dev/null @@ -1,354 +0,0 @@ -// 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.MenuItem}s. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.MenuItemRenderer'); - -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.a11y.Role'); -goog.require('goog.dom.classes'); -goog.require('goog.ui.Component.State'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.ControlRenderer'); - - - -/** - * Default renderer for {@link goog.ui.MenuItem}s. Each item has the following - * structure: - * <pre> - * <div class="goog-menuitem"> - * <div class="goog-menuitem-content"> - * ...(menu item contents)... - * </div> - * </div> - * </pre> - * @constructor - * @extends {goog.ui.ControlRenderer} - */ -goog.ui.MenuItemRenderer = function() { - goog.ui.ControlRenderer.call(this); - - /** - * Commonly used CSS class names, cached here for convenience (and to avoid - * unnecessary string concatenation). - * @type {!Array.<string>} - * @private - */ - this.classNameCache_ = []; -}; -goog.inherits(goog.ui.MenuItemRenderer, goog.ui.ControlRenderer); -goog.addSingletonGetter(goog.ui.MenuItemRenderer); - - -/** - * CSS class name the renderer applies to menu item elements. - * @type {string} - */ -goog.ui.MenuItemRenderer.CSS_CLASS = goog.getCssName('goog-menuitem'); - - -/** - * Constants for referencing composite CSS classes. - * @enum {number} - * @private - */ -goog.ui.MenuItemRenderer.CompositeCssClassIndex_ = { - HOVER: 0, - CHECKBOX: 1, - CONTENT: 2 -}; - - -/** - * Returns the composite CSS class by using the cached value or by constructing - * the value from the base CSS class and the passed index. - * @param {goog.ui.MenuItemRenderer.CompositeCssClassIndex_} index Index for the - * CSS class - could be highlight, checkbox or content in usual cases. - * @return {string} The composite CSS class. - * @private - */ -goog.ui.MenuItemRenderer.prototype.getCompositeCssClass_ = function(index) { - var result = this.classNameCache_[index]; - if (!result) { - switch (index) { - case goog.ui.MenuItemRenderer.CompositeCssClassIndex_.HOVER: - result = goog.getCssName(this.getStructuralCssClass(), 'highlight'); - break; - case goog.ui.MenuItemRenderer.CompositeCssClassIndex_.CHECKBOX: - result = goog.getCssName(this.getStructuralCssClass(), 'checkbox'); - break; - case goog.ui.MenuItemRenderer.CompositeCssClassIndex_.CONTENT: - result = goog.getCssName(this.getStructuralCssClass(), 'content'); - break; - } - this.classNameCache_[index] = result; - } - - return result; -}; - - -/** @return {goog.dom.a11y.Role} The ARIA role. */ -goog.ui.MenuItemRenderer.prototype.getAriaRole = function() { - return goog.dom.a11y.Role.MENU_ITEM; -}; - - -/** - * Overrides {@link goog.ui.ControlRenderer#createDom} by adding extra markup - * and stying to the menu item's element if it is selectable or checkable. - * @param {goog.ui.Control} item Menu item to render. - * @return {Element} Root element for the item. - * @override - */ -goog.ui.MenuItemRenderer.prototype.createDom = function(item) { - var element = item.getDomHelper().createDom( - 'div', this.getClassNames(item).join(' '), - this.createContent(item.getContent(), item.getDomHelper())); - this.setEnableCheckBoxStructure(item, element, - item.isSupportedState(goog.ui.Component.State.SELECTED) || - item.isSupportedState(goog.ui.Component.State.CHECKED)); - return element; -}; - - -/** @override */ -goog.ui.MenuItemRenderer.prototype.getContentElement = function(element) { - return /** @type {Element} */ (element && element.firstChild); -}; - - -/** - * Overrides {@link goog.ui.ControlRenderer#decorate} by initializing the - * menu item to checkable based on whether the element to be decorated has - * extra stying indicating that it should be. - * @param {goog.ui.Control} item Menu item instance to decorate the element. - * @param {Element} element Element to decorate. - * @return {Element} Decorated element. - * @override - */ -goog.ui.MenuItemRenderer.prototype.decorate = function(item, element) { - if (!this.hasContentStructure(element)) { - element.appendChild( - this.createContent(element.childNodes, item.getDomHelper())); - } - if (goog.dom.classes.has(element, goog.getCssName('goog-option'))) { - item.setCheckable(true); - this.setCheckable(item, element, true); - } - return goog.ui.MenuItemRenderer.superClass_.decorate.call(this, item, - element); -}; - - -/** - * Takes a menu item's root element, and sets its content to the given text - * caption or DOM structure. Overrides the superclass immplementation by - * making sure that the checkbox structure (for selectable/checkable menu - * items) is preserved. - * @param {Element} element The item's root element. - * @param {goog.ui.ControlContent} content Text caption or DOM structure to be - * set as the item's content. - * @override - */ -goog.ui.MenuItemRenderer.prototype.setContent = function(element, content) { - // Save the checkbox element, if present. - var contentElement = this.getContentElement(element); - var checkBoxElement = this.hasCheckBoxStructure(element) ? - contentElement.firstChild : null; - goog.ui.MenuItemRenderer.superClass_.setContent.call(this, element, content); - if (checkBoxElement && !this.hasCheckBoxStructure(element)) { - // The call to setContent() blew away the checkbox element; reattach it. - contentElement.insertBefore(checkBoxElement, - contentElement.firstChild || null); - } -}; - - -/** - * Returns true if the element appears to have a proper menu item structure by - * checking whether its first child has the appropriate structural class name. - * @param {Element} element Element to check. - * @return {boolean} Whether the element appears to have a proper menu item DOM. - * @protected - */ -goog.ui.MenuItemRenderer.prototype.hasContentStructure = function(element) { - var child = goog.dom.getFirstElementChild(element); - var contentClassName = this.getCompositeCssClass_( - goog.ui.MenuItemRenderer.CompositeCssClassIndex_.CONTENT); - return !!child && child.className.indexOf(contentClassName) != -1; -}; - - -/** - * Wraps the given text caption or existing DOM node(s) in a structural element - * containing the menu item's contents. - * @param {goog.ui.ControlContent} content Menu item contents. - * @param {goog.dom.DomHelper} dom DOM helper for document interaction. - * @return {Element} Menu item content element. - * @protected - */ -goog.ui.MenuItemRenderer.prototype.createContent = function(content, dom) { - var contentClassName = this.getCompositeCssClass_( - goog.ui.MenuItemRenderer.CompositeCssClassIndex_.CONTENT); - return dom.createDom('div', contentClassName, content); -}; - - -/** - * Enables/disables radio button semantics on the menu item. - * @param {goog.ui.Control} item Menu item to update. - * @param {Element} element Menu item element to update (may be null if the - * item hasn't been rendered yet). - * @param {boolean} selectable Whether the item should be selectable. - */ -goog.ui.MenuItemRenderer.prototype.setSelectable = function(item, element, - selectable) { - if (element) { - goog.dom.a11y.setRole(element, selectable ? - goog.dom.a11y.Role.MENU_ITEM_RADIO : this.getAriaRole()); - this.setEnableCheckBoxStructure(item, element, selectable); - } -}; - - -/** - * Enables/disables checkbox semantics on the menu item. - * @param {goog.ui.Control} item Menu item to update. - * @param {Element} element Menu item element to update (may be null if the - * item hasn't been rendered yet). - * @param {boolean} checkable Whether the item should be checkable. - */ -goog.ui.MenuItemRenderer.prototype.setCheckable = function(item, element, - checkable) { - if (element) { - goog.dom.a11y.setRole(element, checkable ? - goog.dom.a11y.Role.MENU_ITEM_CHECKBOX : this.getAriaRole()); - this.setEnableCheckBoxStructure(item, element, checkable); - } -}; - - -/** - * Determines whether the item contains a checkbox element. - * @param {Element} element Menu item root element. - * @return {boolean} Whether the element contains a checkbox element. - * @protected - */ -goog.ui.MenuItemRenderer.prototype.hasCheckBoxStructure = function(element) { - var contentElement = this.getContentElement(element); - if (contentElement) { - var child = contentElement.firstChild; - var checkboxClassName = this.getCompositeCssClass_( - goog.ui.MenuItemRenderer.CompositeCssClassIndex_.CHECKBOX); - return !!child && !!child.className && - child.className.indexOf(checkboxClassName) != -1; - } - return false; -}; - - -/** - * Adds or removes extra markup and CSS styling to the menu item to make it - * selectable or non-selectable, depending on the value of the - * {@code selectable} argument. - * @param {goog.ui.Control} item Menu item to update. - * @param {Element} element Menu item element to update. - * @param {boolean} enable Whether to add or remove the checkbox structure. - * @protected - */ -goog.ui.MenuItemRenderer.prototype.setEnableCheckBoxStructure = function(item, - element, enable) { - if (enable != this.hasCheckBoxStructure(element)) { - goog.dom.classes.enable(element, goog.getCssName('goog-option'), enable); - var contentElement = this.getContentElement(element); - if (enable) { - // Insert checkbox structure. - var checkboxClassName = this.getCompositeCssClass_( - goog.ui.MenuItemRenderer.CompositeCssClassIndex_.CHECKBOX); - contentElement.insertBefore( - item.getDomHelper().createDom('div', checkboxClassName), - contentElement.firstChild || null); - } else { - // Remove checkbox structure. - contentElement.removeChild(contentElement.firstChild); - } - } -}; - - -/** - * Takes a single {@link goog.ui.Component.State}, and returns the - * corresponding CSS class name (null if none). Overrides the superclass - * implementation by using 'highlight' as opposed to 'hover' as the CSS - * class name suffix for the HOVER state, for backwards compatibility. - * @param {goog.ui.Component.State} state Component state. - * @return {string|undefined} CSS class representing the given state - * (undefined if none). - * @override - */ -goog.ui.MenuItemRenderer.prototype.getClassForState = function(state) { - switch (state) { - case goog.ui.Component.State.HOVER: - // We use 'highlight' as the suffix, for backwards compatibility. - return this.getCompositeCssClass_( - goog.ui.MenuItemRenderer.CompositeCssClassIndex_.HOVER); - case goog.ui.Component.State.CHECKED: - case goog.ui.Component.State.SELECTED: - // We use 'goog-option-selected' as the class, for backwards compatibility. - return goog.getCssName('goog-option-selected'); - default: - return goog.ui.MenuItemRenderer.superClass_.getClassForState.call(this, - state); - } -}; - - -/** - * Takes a single CSS class name which may represent a component state, and - * returns the corresponding component state (0x00 if none). Overrides the - * superclass implementation by treating 'goog-option-selected' as special, - * for backwards compatibility. - * @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). - * @override - */ -goog.ui.MenuItemRenderer.prototype.getStateFromClass = function(className) { - var hoverClassName = this.getCompositeCssClass_( - goog.ui.MenuItemRenderer.CompositeCssClassIndex_.HOVER); - switch (className) { - case goog.getCssName('goog-option-selected'): - return goog.ui.Component.State.CHECKED; - case hoverClassName: - return goog.ui.Component.State.HOVER; - default: - return goog.ui.MenuItemRenderer.superClass_.getStateFromClass.call(this, - className); - } -}; - - -/** @override */ -goog.ui.MenuItemRenderer.prototype.getCssClass = function() { - return goog.ui.MenuItemRenderer.CSS_CLASS; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuitemrenderer_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuitemrenderer_test.html.svn-base deleted file mode 100644 index 0529e1a..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuitemrenderer_test.html.svn-base +++ /dev/null @@ -1,191 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.MenuItemRenderer</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.dom.classes'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.MenuItem'); - goog.require('goog.ui.MenuItemRenderer'); - goog.require('goog.testing.ui.rendererasserts'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var sandbox = goog.dom.getElement('sandbox'); - var item, renderer; - - function setUp() { - item = new goog.ui.MenuItem('Hello'); - renderer = goog.ui.MenuItemRenderer.getInstance(); - } - - function tearDown() { - item.dispose(); - goog.dom.removeChildren(sandbox); - } - - function testMenuItemRenderer() { - assertNotNull('Instance must not be null', renderer); - assertEquals('Singleton getter must always return same instance', - renderer, goog.ui.MenuItemRenderer.getInstance()); - } - - function testCreateDom() { - var element = renderer.createDom(item); - assertNotNull('Element must not be null', element); - assertSameElements('Element must have the expected class names', - ['goog-menuitem'], goog.dom.classes.get(element)); - assertEquals('Element must have exactly one child element', 1, - element.childNodes.length); - assertHTMLEquals('Child element must have the expected structure', - '<div class="goog-menuitem-content">Hello</div>', - element.innerHTML); - } - - function testCreateDomWithHoverState() { - item.setHighlighted(true); - var element = renderer.createDom(item); - assertSameElements('Element must have the expected class names', - ['goog-menuitem', 'goog-menuitem-highlight'], - goog.dom.classes.get(element)); - } - - function testCreateDomForCheckableItem() { - item.setSupportedState(goog.ui.Component.State.CHECKED, true); - var element = renderer.createDom(item); - assertSameElements('Element must have the expected class names', - ['goog-menuitem', 'goog-option'], - goog.dom.classes.get(element)); - assertHTMLEquals('Child element must have the expected structure', - '<div class="goog-menuitem-content">' + - '<div class="goog-menuitem-checkbox"></div>Hello</div>', - element.innerHTML); - - item.setChecked(true); - element = renderer.createDom(item); - assertSameElements('Checked item must have the expected class names', - ['goog-menuitem', 'goog-option', 'goog-option-selected'], - goog.dom.classes.get(element)); - } - - function testCreateDomForSelectableItem() { - item.setSupportedState(goog.ui.Component.State.SELECTED, true); - var element = renderer.createDom(item); - assertSameElements('Element must have the expected class names', - ['goog-menuitem', 'goog-option'], - goog.dom.classes.get(element)); - assertHTMLEquals('Child element must have the expected structure', - '<div class="goog-menuitem-content">' + - '<div class="goog-menuitem-checkbox"></div>Hello</div>', - element.innerHTML); - - item.setSelected(true); - element = renderer.createDom(item); - assertSameElements('Selected item must have the expected class names', - ['goog-menuitem', 'goog-option', 'goog-option-selected'], - goog.dom.classes.get(element)); - } - - function testGetContentElement() { - assertNull('Content element must be the null initially', - item.getContentElement()); - item.createDom(); - assertEquals('Content element must be the element\'s first child', - item.getElement().firstChild, item.getContentElement()); - } - - function testDecorate() { - sandbox.innerHTML = '<div id="foo">Hello</div>'; - var foo = goog.dom.getElement('foo'); - - var element = renderer.decorate(item, foo); - assertSameElements('Element must have the expected class names', - ['goog-menuitem'], goog.dom.classes.get(element)); - assertEquals('Element must have exactly one child element', 1, - element.childNodes.length); - assertHTMLEquals('Child element must have the expected structure', - '<div class="goog-menuitem-content">Hello</div>', - element.innerHTML); - } - - function testDecorateWithContentStructure() { - sandbox.innerHTML = - '<div id="foo"><div class="goog-menuitem-content">Hello</div></div>'; - var foo = goog.dom.getElement('foo'); - - var element = renderer.decorate(item, foo); - assertSameElements('Element must have the expected class names', - ['goog-menuitem'], goog.dom.classes.get(element)); - assertEquals('Element must have exactly one child element', 1, - element.childNodes.length); - assertHTMLEquals('Child element must have the expected structure', - '<div class="goog-menuitem-content">Hello</div>', - element.innerHTML); - } - - function testDecorateWithHoverState() { - sandbox.innerHTML = - '<div id="foo" class="goog-menuitem-highlight">Hello</div>'; - var foo = goog.dom.getElement('foo'); - - assertFalse('Item must not be highlighted', item.isHighlighted()); - var element = renderer.decorate(item, foo); - assertSameElements('Element must have the expected class names', - ['goog-menuitem', 'goog-menuitem-highlight'], - goog.dom.classes.get(element)); - assertTrue('Item must be highlighted', item.isHighlighted()); - } - - function testDecorateCheckableItem() { - sandbox.innerHTML = '<div id="foo" class="goog-option">Hello</div>'; - var foo = goog.dom.getElement('foo'); - - assertFalse('Item must not be checkable', - item.isSupportedState(goog.ui.Component.State.CHECKED)); - var element = renderer.decorate(item, foo); - assertSameElements('Element must have the expected class names', - ['goog-menuitem', 'goog-option'], goog.dom.classes.get(element)); - assertTrue('Item must be checkable', - item.isSupportedState(goog.ui.Component.State.CHECKED)); - assertHTMLEquals('Child element must have the expected structure', - '<div class="goog-menuitem-content">' + - '<div class="goog-menuitem-checkbox"></div>Hello</div>', - element.innerHTML); - } - - function testSetContent() { - item.setSupportedState(goog.ui.Component.State.CHECKED, true); - var element = renderer.createDom(item); - assertHTMLEquals('Child element must have the expected structure', - '<div class="goog-menuitem-content">' + - '<div class="goog-menuitem-checkbox"></div>Hello</div>', - element.innerHTML); - - renderer.setContent(element, 'Goodbye'); - assertHTMLEquals('Child element must have the expected structure', - '<div class="goog-menuitem-content">' + - '<div class="goog-menuitem-checkbox"></div>Goodbye</div>', - element.innerHTML); - } - - function testDoesntCallGetCssClassInConstructor() { - goog.testing.ui.rendererasserts. - assertNoGetCssClassCallsInConstructor(goog.ui.MenuItemRenderer); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menurenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menurenderer.js.svn-base deleted file mode 100644 index db0d2d4..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menurenderer.js.svn-base +++ /dev/null @@ -1,118 +0,0 @@ -// 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.Menu}s. - * - * @author robbyw@google.com (Robby Walker) - * @author pupius@google.com (Daniel Pupius) - */ - -goog.provide('goog.ui.MenuRenderer'); - -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.a11y.Role'); -goog.require('goog.dom.a11y.State'); -goog.require('goog.ui.ContainerRenderer'); -goog.require('goog.ui.Separator'); - - - -/** - * Default renderer for {@link goog.ui.Menu}s, based on {@link - * goog.ui.ContainerRenderer}. - * @constructor - * @extends {goog.ui.ContainerRenderer} - */ -goog.ui.MenuRenderer = function() { - goog.ui.ContainerRenderer.call(this); -}; -goog.inherits(goog.ui.MenuRenderer, goog.ui.ContainerRenderer); -goog.addSingletonGetter(goog.ui.MenuRenderer); - - -/** - * Default CSS class to be applied to the root element of toolbars rendered - * by this renderer. - * @type {string} - */ -goog.ui.MenuRenderer.CSS_CLASS = goog.getCssName('goog-menu'); - - -/** - * Returns the ARIA role to be applied to menus. - * @return {string} ARIA role. - * @override - */ -goog.ui.MenuRenderer.prototype.getAriaRole = function() { - return goog.dom.a11y.Role.MENU; -}; - - -/** - * Returns whether the element is a UL or acceptable to our superclass. - * @param {Element} element Element to decorate. - * @return {boolean} Whether the renderer can decorate the element. - */ -goog.ui.MenuRenderer.prototype.canDecorate = function(element) { - return element.tagName == 'UL' || - goog.ui.MenuRenderer.superClass_.canDecorate.call(this, element); -}; - - -/** - * Inspects the element, and creates an instance of {@link goog.ui.Control} or - * an appropriate subclass best suited to decorate it. Overrides the superclass - * implementation by recognizing HR elements as separators. - * @param {Element} element Element to decorate. - * @return {goog.ui.Control?} A new control suitable to decorate the element - * (null if none). - */ -goog.ui.MenuRenderer.prototype.getDecoratorForChild = function(element) { - return element.tagName == 'HR' ? - new goog.ui.Separator() : - goog.ui.MenuRenderer.superClass_.getDecoratorForChild.call(this, - element); -}; - - -/** - * Returns whether the given element is contained in the menu's DOM. - * @param {goog.ui.Menu} menu The menu to test. - * @param {Element} element The element to test. - * @return {boolean} Whether the given element is contained in the menu. - */ -goog.ui.MenuRenderer.prototype.containsElement = function(menu, element) { - return goog.dom.contains(menu.getElement(), element); -}; - - -/** - * Returns the CSS class to be applied to the root element of containers - * rendered using this renderer. - * @return {string} Renderer-specific CSS class. - */ -goog.ui.MenuRenderer.prototype.getCssClass = function() { - return goog.ui.MenuRenderer.CSS_CLASS; -}; - - -/** @override */ -goog.ui.MenuRenderer.prototype.initializeDom = function(container) { - goog.ui.MenuRenderer.superClass_.initializeDom.call(this, container); - - var element = container.getElement(); - goog.dom.a11y.setState(element, goog.dom.a11y.State.HASPOPUP, 'true'); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuseparator.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuseparator.js.svn-base deleted file mode 100644 index 3d9850f..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuseparator.js.svn-base +++ /dev/null @@ -1,51 +0,0 @@ -// 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(); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuseparatorrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuseparatorrenderer.js.svn-base deleted file mode 100644 index 5efe16c..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuseparatorrenderer.js.svn-base +++ /dev/null @@ -1,108 +0,0 @@ -// 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.MenuSeparator}s. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.MenuSeparatorRenderer'); - -goog.require('goog.dom'); -goog.require('goog.dom.classes'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.ControlRenderer'); - - - -/** - * Renderer for menu separators. - * @constructor - * @extends {goog.ui.ControlRenderer} - */ -goog.ui.MenuSeparatorRenderer = function() { - goog.ui.ControlRenderer.call(this); -}; -goog.inherits(goog.ui.MenuSeparatorRenderer, goog.ui.ControlRenderer); -goog.addSingletonGetter(goog.ui.MenuSeparatorRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.MenuSeparatorRenderer.CSS_CLASS = goog.getCssName('goog-menuseparator'); - - -/** - * Returns an empty, styled menu separator DIV. Overrides {@link - * goog.ui.ControlRenderer#createDom}. - * @param {goog.ui.Separator} separator Separator to render. - * @return {Element} Root element for the separator. - */ -goog.ui.MenuSeparatorRenderer.prototype.createDom = function(separator) { - return separator.getDomHelper().createDom('div', this.getCssClass()); -}; - - -/** - * Takes an existing element, and decorates it with the separator. Overrides - * {@link goog.ui.ControlRenderer#decorate}. - * @param {goog.ui.Separator} separator Separator to decorate the element. - * @param {Element} element Element to decorate. - * @return {Element} Decorated element. - */ -goog.ui.MenuSeparatorRenderer.prototype.decorate = function(separator, - element) { - // Normally handled in the superclass. But we don't call the superclass. - if (element.id) { - separator.setId(element.id); - } - - if (element.tagName == 'HR') { - // Replace HR with separator. - var hr = element; - element = this.createDom(separator); - goog.dom.insertSiblingBefore(element, hr); - goog.dom.removeNode(hr); - } else { - goog.dom.classes.add(element, this.getCssClass()); - } - return element; -}; - - -/** - * Overrides {@link goog.ui.ControlRenderer#setContent} to do nothing, since - * separators are empty. - * @param {Element} separator The separator's root element. - * @param {goog.ui.ControlContent} content Text caption or DOM structure to be - * set as the separators's content (ignored). - */ -goog.ui.MenuSeparatorRenderer.prototype.setContent = function(separator, - content) { - // Do nothing. Separators are empty. -}; - - -/** - * Returns the CSS class to be applied to the root element of components - * rendered using this renderer. - * @return {string} Renderer-specific CSS class. - */ -goog.ui.MenuSeparatorRenderer.prototype.getCssClass = function() { - return goog.ui.MenuSeparatorRenderer.CSS_CLASS; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuseparatorrenderer_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuseparatorrenderer_test.html.svn-base deleted file mode 100644 index a28b82a..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/menuseparatorrenderer_test.html.svn-base +++ /dev/null @@ -1,61 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2011 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - - @author mfrederick@google.com (Michael Frederick) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests for MenuSeparatorRenderer</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.dom.classes'); - goog.require('goog.events'); - goog.require('goog.events.Event'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.MenuButton'); - goog.require('goog.testing.ui.rendererasserts'); -</script> -</head> -<body> - -<div id="sandbox"> - <!-- A menu separator to decorate --> - <div id="separator" class="goog-menuseparator"></div> -</div> - -<script> - -var sandbox; -var originalSandbox; - -function setUp() { - sandbox = goog.dom.getElement('sandbox'); - originalSandbox = sandbox.cloneNode(true); -} - -function tearDown() { - sandbox.parentNode.replaceChild(originalSandbox, sandbox); -} - -function testDecorate() { - var separator = new goog.ui.MenuSeparator(); - var dummyId = 'foo'; - separator.setId(dummyId); - assertEquals(dummyId, separator.getId()); - var renderer = new goog.ui.MenuSeparatorRenderer(); - renderer.decorate(separator, goog.dom.getElement('separator')) - assertEquals('separator', separator.getId()); -} - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/mockactivitymonitor.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/mockactivitymonitor.js.svn-base deleted file mode 100644 index 0a0ce68..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/mockactivitymonitor.js.svn-base +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2007 The Closure Library Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview Definition of goog.ui.MockActivityMonitor. - */ - -goog.provide('goog.ui.MockActivityMonitor'); - -goog.require('goog.events.EventType'); -goog.require('goog.ui.ActivityMonitor'); - - - -/** - * A mock implementation of goog.ui.ActivityMonitor for unit testing. Clients - * of this class should override goog.now to return a synthetic time from - * the unit test. - * @constructor - * @extends {goog.ui.ActivityMonitor} - */ -goog.ui.MockActivityMonitor = function() { - goog.ui.ActivityMonitor.call(this); -}; -goog.inherits(goog.ui.MockActivityMonitor, goog.ui.ActivityMonitor); - - -/** - * Simulates an event that updates the user to being non-idle. - * @param {goog.events.EventType=} opt_type The type of event that made the user - * not idle. If not specified, defaults to MOUSEMOVE. - */ -goog.ui.MockActivityMonitor.prototype.simulateEvent = function(opt_type) { - var type = opt_type || goog.events.EventType.MOUSEMOVE; - var eventTime = goog.now(); - - // update internal state noting whether the user was idle - this.lastEventTime_ = eventTime; - this.lastEventType_ = type; - - // dispatch event - this.dispatchEvent(goog.ui.ActivityMonitor.Event.ACTIVITY); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/modalpopup.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/modalpopup.js.svn-base deleted file mode 100644 index 3648dce..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/modalpopup.js.svn-base +++ /dev/null @@ -1,467 +0,0 @@ -// 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 Class for showing simple modal popup. - */ - -goog.provide('goog.ui.ModalPopup'); - -goog.require('goog.Timer'); -goog.require('goog.asserts'); -goog.require('goog.dom'); -goog.require('goog.dom.TagName'); -goog.require('goog.dom.classes'); -goog.require('goog.dom.iframe'); -goog.require('goog.events'); -goog.require('goog.events.EventType'); -goog.require('goog.events.FocusHandler'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.PopupBase.EventType'); -goog.require('goog.userAgent'); - - - -/** - * Base class for modal popup UI components. This can also be used as - * a standalone component to render a modal popup with an empty div. - * - * WARNING: goog.ui.ModalPopup is only guaranteed to work when it is rendered - * directly in the 'body' element. - * - * The Html structure of the modal popup is: - * <pre> - * Element Function Class-name, goog-modalpopup = default - * ---------------------------------------------------------------------------- - * - iframe Iframe mask goog-modalpopup-bg - * - div Background mask goog-modalpopup-bg - * - div Modal popup area goog-modalpopup - * - span Tab catcher - * </pre> - * @constructor - * @param {boolean=} opt_useIframeMask Work around windowed controls z-index - * issue by using an iframe instead of a div for bg element. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper; see {@link - * goog.ui.Component} for semantics. - * @extends {goog.ui.Component} - */ -goog.ui.ModalPopup = function(opt_useIframeMask, opt_domHelper) { - goog.base(this, opt_domHelper); - - /** - * Whether the modal popup should use an iframe as the background - * element to work around z-order issues. - * @type {boolean} - * @private - */ - this.useIframeMask_ = !!opt_useIframeMask; -}; -goog.inherits(goog.ui.ModalPopup, goog.ui.Component); - - -/** - * Focus handler. It will be initialized in enterDocument. - * @type {goog.events.FocusHandler} - * @private - */ -goog.ui.ModalPopup.prototype.focusHandler_ = null; - - -/** - * Whether the modal popup is visible. - * @type {boolean} - * @private - */ -goog.ui.ModalPopup.prototype.visible_ = false; - - -/** - * Element for the background which obscures the UI and blocks events. - * @type {Element} - * @private - */ -goog.ui.ModalPopup.prototype.bgEl_ = null; - - -/** - * Iframe element that is only used for IE as a workaround to keep select-type - * elements from burning through background. - * @type {Element} - * @private - */ -goog.ui.ModalPopup.prototype.bgIframeEl_ = null; - - -/** - * Element used to catch focus and prevent the user from tabbing out - * of the popup. - * @type {Element} - * @private - */ -goog.ui.ModalPopup.prototype.tabCatcherElement_ = null; - - -/** - * @return {string} Base CSS class for this component. - * @protected - */ -goog.ui.ModalPopup.prototype.getCssClass = function() { - return goog.getCssName('goog-modalpopup'); -}; - - -/** - * Returns the background iframe mask element, if any. - * @return {Element} The background iframe mask element. - * @protected - */ -goog.ui.ModalPopup.prototype.getBackgroundIframe = function() { - return this.bgIframeEl_; -}; - - -/** - * Returns the background mask element. - * @return {Element} The background mask element. - */ -goog.ui.ModalPopup.prototype.getBackgroundElement = function() { - return this.bgEl_; -}; - - -/** - * Creates the initial DOM representation for the modal popup. - * Overrides {@link goog.ui.Component#createDom}. - */ -goog.ui.ModalPopup.prototype.createDom = function() { - // Create the modal popup element, and make sure it's hidden. - goog.base(this, 'createDom'); - - var element = this.getElement(); - goog.dom.classes.add(element, this.getCssClass()); - goog.dom.setFocusableTabIndex(element, true); - goog.style.showElement(element, false); - - // Manages the DOM for background mask elements. - this.manageBackgroundDom_(); - this.createTabCatcher_(); -}; - - -/** - * Creates and disposes of the DOM for background mask elements. - * @private - */ -goog.ui.ModalPopup.prototype.manageBackgroundDom_ = function() { - if (this.useIframeMask_ && !this.bgIframeEl_) { - // IE renders the iframe on top of the select elements while still - // respecting the z-index of the other elements on the page. See - // http://support.microsoft.com/kb/177378 for more information. - // Flash and other controls behave in similar ways for other browsers - this.bgIframeEl_ = goog.dom.iframe.createBlank(this.getDomHelper()); - this.bgIframeEl_.className = goog.getCssName(this.getCssClass(), 'bg'); - goog.style.showElement(this.bgIframeEl_, false); - goog.style.setOpacity(this.bgIframeEl_, 0); - } - - // Create the backgound mask, initialize its opacity, and make sure it's - // hidden. - if (!this.bgEl_) { - this.bgEl_ = this.getDomHelper().createDom( - 'div', goog.getCssName(this.getCssClass(), 'bg')); - goog.style.showElement(this.bgEl_, false); - } -}; - - -/** - * Creates the tab catcher element. - * @private - */ -goog.ui.ModalPopup.prototype.createTabCatcher_ = function() { - // Creates tab catcher element. - if (!this.tabCatcherElement_) { - this.tabCatcherElement_ = this.getDomHelper().createElement('span'); - goog.style.showElement(this.tabCatcherElement_, false); - goog.dom.setFocusableTabIndex(this.tabCatcherElement_, true); - this.tabCatcherElement_.style.position = 'absolute'; - } -}; - - -/** - * Renders the background mask. - * @private - */ -goog.ui.ModalPopup.prototype.renderBackground_ = function() { - goog.asserts.assert(!!this.bgEl_, 'Background element must not be null.'); - if (this.bgIframeEl_) { - goog.dom.insertSiblingBefore(this.bgIframeEl_, this.getElement()); - } - goog.dom.insertSiblingBefore(this.bgEl_, this.getElement()); -}; - - -/** @override */ -goog.ui.ModalPopup.prototype.canDecorate = function(element) { - // Assume we can decorate any DIV. - return !!element && element.tagName == goog.dom.TagName.DIV; -}; - - -/** @override */ -goog.ui.ModalPopup.prototype.decorateInternal = function(element) { - // Decorate the modal popup area element. - goog.base(this, 'decorateInternal', element); - goog.dom.classes.add(this.getElement(), this.getCssClass()); - - // Create the background mask... - this.manageBackgroundDom_(); - this.createTabCatcher_(); - - // Make sure the decorated modal popup is hidden. - goog.style.showElement(this.getElement(), false); -}; - - -/** @override */ -goog.ui.ModalPopup.prototype.enterDocument = function() { - this.renderBackground_(); - goog.base(this, 'enterDocument'); - - goog.dom.insertSiblingAfter(this.tabCatcherElement_, this.getElement()); - - this.focusHandler_ = new goog.events.FocusHandler( - this.getDomHelper().getDocument()); - - // We need to watch the entire document so that we can detect when the - // focus is moved out of this modal popup. - this.getHandler().listen( - this.focusHandler_, goog.events.FocusHandler.EventType.FOCUSIN, - this.onFocus_); -}; - - -/** @override */ -goog.ui.ModalPopup.prototype.exitDocument = function() { - if (this.isVisible()) { - this.setVisible(false); - } - - goog.dispose(this.focusHandler_); - - goog.base(this, 'exitDocument'); - goog.dom.removeNode(this.bgIframeEl_); - goog.dom.removeNode(this.bgEl_); - goog.dom.removeNode(this.tabCatcherElement_); -}; - - -/** - * Sets the visibility of the modal popup box and focus to the popup. - * Lazily renders the component if needed. - * @param {boolean} visible Whether the modal popup should be visible. - */ -goog.ui.ModalPopup.prototype.setVisible = function(visible) { - goog.asserts.assert( - this.isInDocument(), 'ModalPopup must be rendered first.'); - if (visible == this.visible_) { - return; - } - - if (visible) { - this.show_(); - } else { - this.hide_(); - } -}; - - -/** - * Shows the popup. - * @private - */ -goog.ui.ModalPopup.prototype.show_ = function() { - if (!this.dispatchEvent(goog.ui.PopupBase.EventType.BEFORE_SHOW)) { - return; - } - - this.resizeBackground_(); - this.reposition(); - - // Listen for keyboard and resize events while the modal popup is visible. - this.getHandler().listen( - this.getDomHelper().getWindow(), goog.events.EventType.RESIZE, - this.resizeBackground_); - - this.showPopupElement_(true); - this.focus(); - this.visible_ = true; - this.dispatchEvent(goog.ui.PopupBase.EventType.SHOW); -}; - - -/** - * Hides the popup. - * @private - */ -goog.ui.ModalPopup.prototype.hide_ = function() { - if (!this.dispatchEvent(goog.ui.PopupBase.EventType.BEFORE_HIDE)) { - return; - } - - // Stop listening for keyboard and resize events while the modal - // popup is hidden. - this.getHandler().unlisten( - this.getDomHelper().getWindow(), goog.events.EventType.RESIZE, - this.resizeBackground_); - - this.showPopupElement_(false); - this.visible_ = false; - this.dispatchEvent(goog.ui.PopupBase.EventType.HIDE); -}; - - -/** - * Shows or hides the popup element. - * @param {boolean} visible Shows the popup element if true, hides if false. - * @private - */ -goog.ui.ModalPopup.prototype.showPopupElement_ = function(visible) { - if (this.bgIframeEl_) { - goog.style.showElement(this.bgIframeEl_, visible); - } - if (this.bgEl_) { - goog.style.showElement(this.bgEl_, visible); - } - goog.style.showElement(this.getElement(), visible); - goog.style.showElement(this.tabCatcherElement_, visible); -}; - - -/** - * @return {boolean} Whether the modal popup is visible. - */ -goog.ui.ModalPopup.prototype.isVisible = function() { - return this.visible_; -}; - - -/** - * Focuses on the modal popup. - */ -goog.ui.ModalPopup.prototype.focus = function() { - this.focusElement_(); -}; - - -/** - * Make the background element the size of the document. - * - * NOTE(user): We must hide the background element before measuring the - * document, otherwise the size of the background will stop the document from - * shrinking to fit a smaller window. This does cause a slight flicker in Linux - * browsers, but should not be a common scenario. - * @private - */ -goog.ui.ModalPopup.prototype.resizeBackground_ = function() { - if (this.bgIframeEl_) { - goog.style.showElement(this.bgIframeEl_, false); - } - if (this.bgEl_) { - goog.style.showElement(this.bgEl_, false); - } - - var doc = this.getDomHelper().getDocument(); - var win = goog.dom.getWindow(doc) || window; - - // Take the max of scroll height and view height for cases in which document - // does not fill screen. - var viewSize = goog.dom.getViewportSize(win); - var w = Math.max(doc.body.scrollWidth, viewSize.width); - var h = Math.max(doc.body.scrollHeight, viewSize.height); - - if (this.bgIframeEl_) { - goog.style.showElement(this.bgIframeEl_, true); - goog.style.setSize(this.bgIframeEl_, w, h); - } - if (this.bgEl_) { - goog.style.showElement(this.bgEl_, true); - goog.style.setSize(this.bgEl_, w, h); - } -}; - - -/** - * Centers the modal popup in the viewport, taking scrolling into account. - */ -goog.ui.ModalPopup.prototype.reposition = function() { - // TODO(user): Make this use goog.positioning as in goog.ui.PopupBase? - - // Get the current viewport to obtain the scroll offset. - var doc = this.getDomHelper().getDocument(); - var win = goog.dom.getWindow(doc) || window; - if (goog.style.getComputedPosition(this.getElement()) == 'fixed') { - var x = 0; - var y = 0; - } else { - var scroll = this.getDomHelper().getDocumentScroll(); - var x = scroll.x; - var y = scroll.y; - } - - var popupSize = goog.style.getSize(this.getElement()); - var viewSize = goog.dom.getViewportSize(win); - - // Make sure left and top are non-negatives. - var left = Math.max(x + viewSize.width / 2 - popupSize.width / 2, 0); - var top = Math.max(y + viewSize.height / 2 - popupSize.height / 2, 0); - goog.style.setPosition(this.getElement(), left, top); - - // We place the tab catcher at the same position as the dialog to - // prevent IE from scrolling when users try to tab out of the dialog. - goog.style.setPosition(this.tabCatcherElement_, left, top); -}; - - -/** - * Handles focus events. Makes sure that if the user tabs past the - * elements in the modal popup, the focus wraps back to the beginning. - * @param {goog.events.BrowserEvent} e Browser's event object. - * @private - */ -goog.ui.ModalPopup.prototype.onFocus_ = function(e) { - if (e.target == this.tabCatcherElement_) { - goog.Timer.callOnce(this.focusElement_, 0, this); - } -}; - - -/** - * Moves the focus to the modal popup. - * @private - */ -goog.ui.ModalPopup.prototype.focusElement_ = function() { - try { - if (goog.userAgent.IE) { - // In IE, we must first focus on the body or else focussing on a - // sub-element will not work. - this.getDomHelper().getDocument().body.focus(); - } - this.getElement().focus(); - } catch (e) { - // Swallow this. IE can throw an error if the element can not be focused. - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/modalpopup_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/modalpopup_test.html.svn-base deleted file mode 100644 index 70fbe49..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/modalpopup_test.html.svn-base +++ /dev/null @@ -1,172 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2011 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.ModalPopup</title> -<script src="../base.js"></script> -<script> - goog.require('goog.ui.ModalPopup'); - goog.require('goog.dispose'); - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.style'); - goog.require('goog.ui.PopupBase.EventType'); - goog.require('goog.testing.jsunit'); -</script> -</head> -<body> -<script> - - -var popup; - - -function setUp() { -} - - -function tearDown() { - goog.dispose(popup); -} - - -function testDispose() { - popup = new goog.ui.ModalPopup(); - popup.render(); - - goog.dispose(popup); - assertNull(goog.dom.getElementByClass('goog-modalpopup-bg')); - assertNull(goog.dom.getElementByClass('goog-modalpopup')); - assertEquals(0, goog.dom.getElementsByTagNameAndClass('span').length); -} - - -function testRenderWithoutIframeMask() { - popup = new goog.ui.ModalPopup(); - popup.render(); - - assertEquals(0, goog.dom.getElementsByTagNameAndClass( - 'iframe', 'goog-modalpopup-bg').length); - - var bg = goog.dom.getElementsByTagNameAndClass('div', 'goog-modalpopup-bg'); - assertEquals(1, bg.length); - var content = goog.dom.getElementByClass('goog-modalpopup'); - assertNotNull(content); - var tabCatcher = goog.dom.getElementsByTagNameAndClass('span'); - assertEquals(1, tabCatcher.length); - - assertTrue(goog.dom.compareNodeOrder(bg[0], content) < 0); - assertTrue(goog.dom.compareNodeOrder(content, tabCatcher[0]) < 0); -} - - -function testRenderWithIframeMask() { - popup = new goog.ui.ModalPopup(true); - popup.render(); - - var iframe = goog.dom.getElementsByTagNameAndClass( - 'iframe', 'goog-modalpopup-bg'); - assertEquals(1, iframe.length); - var bg = goog.dom.getElementsByTagNameAndClass('div', 'goog-modalpopup-bg'); - assertEquals(1, bg.length); - var content = goog.dom.getElementByClass('goog-modalpopup'); - assertNotNull(content); - var tabCatcher = goog.dom.getElementsByTagNameAndClass('span'); - assertEquals(1, tabCatcher.length); - - assertTrue(goog.dom.compareNodeOrder(iframe[0], bg[0]) < 0); - assertTrue(goog.dom.compareNodeOrder(bg[0], content) < 0); - assertTrue(goog.dom.compareNodeOrder(content, tabCatcher[0]) < 0); -} - - -function testRenderDoesNotShowAnyElement() { - popup = new goog.ui.ModalPopup(true); - popup.render(); - - var iframe = goog.dom.getElementsByTagNameAndClass( - 'iframe', 'goog-modalpopup-bg'); - assertFalse(goog.style.isElementShown(iframe[0])); - var bg = goog.dom.getElementsByTagNameAndClass('div', 'goog-modalpopup-bg'); - assertFalse(goog.style.isElementShown(bg[0])); - assertFalse(goog.style.isElementShown( - goog.dom.getElementByClass('goog-modalpopup'))); - var tabCatcher = goog.dom.getElementsByTagNameAndClass('span'); - assertFalse(goog.style.isElementShown(tabCatcher[0])); -} - - -function testIframeOpacityIsSetToZero() { - popup = new goog.ui.ModalPopup(true); - popup.render(); - - var iframe = goog.dom.getElementsByTagNameAndClass( - 'iframe', 'goog-modalpopup-bg')[0]; - assertEquals(0, goog.style.getOpacity(iframe)); -} - - -function testEventFiredOnShow() { - popup = new goog.ui.ModalPopup(true); - popup.render(); - - var beforeShowCallCount = 0; - var beforeShowHandler = function() { - beforeShowCallCount++; - }; - var showCallCount = false; - var showHandler = function() { - assertEquals('BEFORE_SHOW is not dispatched before SHOW', - 1, beforeShowCallCount); - showCallCount++; - }; - - goog.events.listen( - popup, goog.ui.PopupBase.EventType.BEFORE_SHOW, beforeShowHandler); - goog.events.listen(popup, goog.ui.PopupBase.EventType.SHOW, showHandler); - - popup.setVisible(true); - - assertEquals(1, beforeShowCallCount); - assertEquals(1, showCallCount); -} - - -function testEventFiredOnHide() { - popup = new goog.ui.ModalPopup(true); - popup.render(); - popup.setVisible(true); - - var beforeHideCallCount = 0; - var beforeHideHandler = function() { - beforeHideCallCount++; - }; - var hideCallCount = false; - var hideHandler = function() { - assertEquals('BEFORE_HIDE is not dispatched before HIDE', - 1, beforeHideCallCount); - hideCallCount++; - }; - - goog.events.listen( - popup, goog.ui.PopupBase.EventType.BEFORE_HIDE, beforeHideHandler); - goog.events.listen(popup, goog.ui.PopupBase.EventType.HIDE, hideHandler); - - popup.setVisible(false); - - assertEquals(1, beforeHideCallCount); - assertEquals(1, hideCallCount); -} - - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/nativebuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/nativebuttonrenderer.js.svn-base deleted file mode 100644 index e9793b4..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/nativebuttonrenderer.js.svn-base +++ /dev/null @@ -1,207 +0,0 @@ -// 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); -}; - - -/** - * @override - * Native buttons natively support BiDi and keyboard focus. - * @suppress {visibility} getHandler and performActionInternal - */ -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); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/nativebuttonrenderer_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/nativebuttonrenderer_test.html.svn-base deleted file mode 100644 index 38852a9..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/nativebuttonrenderer_test.html.svn-base +++ /dev/null @@ -1,214 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.NativeButtonRenderer</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.testing.ExpectedFailures'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Button'); - goog.require('goog.ui.Component.State'); - goog.require('goog.ui.NativeButtonRenderer'); - goog.require('goog.testing.ui.rendererasserts'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var sandbox = goog.dom.getElement('sandbox'); - var renderer = goog.ui.NativeButtonRenderer.getInstance(); - var expectedFailures = new goog.testing.ExpectedFailures(); - var button; - - function setUp() { - button = new goog.ui.Button('Hello', renderer); - } - - function tearDown() { - button.dispose(); - goog.dom.removeChildren(sandbox); - expectedFailures.handleTearDown(); - } - - function testConstructor() { - assertNotNull('Renderer must not be null', renderer); - } - - function testGetAriaRole() { - assertUndefined('ARIA role must be undefined', renderer.getAriaRole()); - } - - function testCreateDom() { - button.setTooltip('Hello, world!'); - button.setValue('foo'); - var element = renderer.createDom(button); - assertNotNull('Element must not be null', element); - assertEquals('Element must be a button', 'BUTTON', element.tagName); - assertSameElements('Button element must have expected class name', - ['goog-button'], goog.dom.classes.get(element)); - assertFalse('Button element must be enabled', element.disabled); - assertEquals('Button element must have expected title', 'Hello, world!', - element.title); - // Expected to fail on IE. - expectedFailures.expectFailureFor(goog.userAgent.IE); - try { - // See http://www.fourmilab.ch/fourmilog/archives/2007-03/000824.html - // for a description of the problem. - assertEquals('Button element must have expected value', 'foo', - element.value); - assertEquals('Button element must have expected contents', 'Hello', - element.innerHTML); - } catch (e) { - expectedFailures.handleException(e); - } - assertFalse('Button must not handle its own mouse events', - button.isHandleMouseEvents()); - assertFalse('Button must not support the custom FOCUSED state', - button.isSupportedState(goog.ui.Component.State.FOCUSED)); - } - - function testCanDecorate() { - sandbox.innerHTML = - '<button id="buttonElement">Button</button>\n' + - '<input id="inputButton" type="button" value="Input Button">\n' + - '<input id="inputSubmit" type="submit" value="Input Submit">\n' + - '<input id="inputReset" type="reset" value="Input Reset">\n' + - '<input id="inputText" type="text" size="10">\n' + - '<div id="divButton" class="goog-button">Hello</div>'; - - assertTrue('Must be able to decorate <button>', - renderer.canDecorate(goog.dom.getElement('buttonElement'))); - assertTrue('Must be able to decorate <input type="button">', - renderer.canDecorate(goog.dom.getElement('inputButton'))); - assertTrue('Must be able to decorate <input type="submit">', - renderer.canDecorate(goog.dom.getElement('inputSubmit'))); - assertTrue('Must be able to decorate <input type="reset">', - renderer.canDecorate(goog.dom.getElement('inputReset'))); - assertFalse('Must not be able to decorate <input type="text">', - renderer.canDecorate(goog.dom.getElement('inputText'))); - assertFalse('Must not be able to decorate <div class="goog-button">', - renderer.canDecorate(goog.dom.getElement('divButton'))); - } - - function testDecorate() { - sandbox.innerHTML = - '<button id="foo" title="Hello!" value="bar">Foo Button</button>\n' + - '<button id="disabledButton" value="bah" disabled>Disabled</button>'; - - var element = renderer.decorate(button, goog.dom.getElement('foo')); - assertEquals('Decorated element must be as expected', - goog.dom.getElement('foo'), element); - assertEquals('Decorated button title must have expected value', 'Hello!', - button.getTooltip()); - // Expected to fail on IE. - expectedFailures.expectFailureFor(goog.userAgent.IE); - try { - // See http://www.fourmilab.ch/fourmilog/archives/2007-03/000824.html - // for a description of the problem. - assertEquals('Decorated button value must have expected value', 'bar', - button.getValue()); - } catch (e) { - expectedFailures.handleException(e); - } - assertFalse('Button must not handle its own mouse events', - button.isHandleMouseEvents()); - assertFalse('Button must not support the custom FOCUSED state', - button.isSupportedState(goog.ui.Component.State.FOCUSED)); - - element = renderer.decorate(button, - goog.dom.getElement('disabledButton')); - assertFalse('Decorated button must be disabled', button.isEnabled()); - assertSameElements('Decorated button must have expected class names', - ['goog-button', 'goog-button-disabled'], - goog.dom.classes.get(element)); - // Expected to fail on IE. - expectedFailures.expectFailureFor(goog.userAgent.IE); - try { - // See http://www.fourmilab.ch/fourmilog/archives/2007-03/000824.html - // for a description of the problem. - assertEquals('Decorated button value must have expected value', 'bah', - button.getValue()); - } catch (e) { - expectedFailures.handleException(e); - } - assertFalse('Button must not handle its own mouse events', - button.isHandleMouseEvents()); - assertFalse('Button must not support the custom FOCUSED state', - button.isSupportedState(goog.ui.Component.State.FOCUSED)); - } - - function testInitializeDom() { - var dispatchedActionCount = 0; - var handleAction = function() { - dispatchedActionCount++; - }; - goog.events.listen(button, goog.ui.Component.EventType.ACTION, - handleAction); - - button.render(sandbox); - goog.testing.events.fireClickSequence(button.getElement()); - assertEquals('Button must have dispatched ACTION on click', 1, - dispatchedActionCount); - - goog.events.unlisten(button, goog.ui.Component.EventType.ACTION, - handleAction); - } - - function testIsFocusable() { - assertTrue('Enabled button must be focusable', - renderer.isFocusable(button)); - button.setEnabled(false); - assertFalse('Disabled button must not be focusable', - renderer.isFocusable(button)); - } - - function testSetState() { - button.render(sandbox); - assertFalse('Button element must not be disabled', - button.getElement().disabled); - renderer.setState(button, goog.ui.Component.State.DISABLED, true); - assertTrue('Button element must be disabled', - button.getElement().disabled); - } - - function testGetValue() { - sandbox.innerHTML = '<button id="foo" value="blah">Hello</button>'; - // Expected to fail on IE. - expectedFailures.expectFailureFor(goog.userAgent.IE); - try { - // See http://www.fourmilab.ch/fourmilog/archives/2007-03/000824.html - // for a description of the problem. - assertEquals('Value must be as expected', 'blah', - renderer.getValue(goog.dom.getElement('foo'))); - } catch (e) { - expectedFailures.handleException(e); - } - } - - function testSetValue() { - button.render(sandbox); - renderer.setValue(button.getElement(), 'What?'); - assertEquals('Button must have expected value', 'What?', - renderer.getValue(button.getElement())); - } - - function testDoesntCallGetCssClassInConstructor() { - goog.testing.ui.rendererasserts. - assertNoGetCssClassCallsInConstructor(goog.ui.NativeButtonRenderer); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/offlineinstalldialog.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/offlineinstalldialog.js.svn-base deleted file mode 100644 index 876f560..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/offlineinstalldialog.js.svn-base +++ /dev/null @@ -1,1086 +0,0 @@ -// 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 dialog for presenting the offline (Gears) install flow. It - * show information on how to install Gears if Gears is not already installed, - * or will offer the option to enable the application for Gears support. - * - * @see ../demos/offline.html - */ - -goog.provide('goog.ui.OfflineInstallDialog'); -goog.provide('goog.ui.OfflineInstallDialog.ButtonKeyType'); -goog.provide('goog.ui.OfflineInstallDialog.EnableScreen'); -goog.provide('goog.ui.OfflineInstallDialog.InstallScreen'); -goog.provide('goog.ui.OfflineInstallDialog.InstallingGearsScreen'); -goog.provide('goog.ui.OfflineInstallDialog.ScreenType'); -goog.provide('goog.ui.OfflineInstallDialog.UpgradeScreen'); -goog.provide('goog.ui.OfflineInstallDialogScreen'); - -goog.require('goog.Disposable'); -goog.require('goog.dom.classes'); -goog.require('goog.gears'); -goog.require('goog.string'); -goog.require('goog.string.StringBuffer'); -goog.require('goog.ui.Dialog'); -goog.require('goog.ui.Dialog.ButtonSet'); -goog.require('goog.ui.Dialog.EventType'); -goog.require('goog.window'); - - - -/** - * An offline install dialog. - * @param {string=} opt_class CSS class name for the dialog element, also used - * as a class name prefix for related elements; defaults to modal-dialog. - * @param {boolean=} opt_useIframeMask Work around windowed controls z-index - * issue by using an iframe instead of a div for bg element. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Dialog} - */ -goog.ui.OfflineInstallDialog = function( - opt_class, opt_useIframeMask, opt_domHelper) { - goog.ui.Dialog.call(this, opt_class, opt_useIframeMask, opt_domHelper); - - /** - * This is used to allow more screens to be added programatically. It is a - * map from screen type to a constructor that extends - * goog.ui.OfflineInstallDialogScreen. - * @type {Object} - * @private - */ - this.screenConstructors_ = {}; - - /** - * This is a map of constructed screens. It uses the constructors in the - * screenConstructors_ map. - * @type {Object} - * @private - */ - this.screens_ = {}; - - this.currentScreenType_ = goog.gears.hasFactory() ? - goog.ui.OfflineInstallDialog.ScreenType.ENABLE : - goog.ui.OfflineInstallDialog.ScreenType.INSTALL; - - this.registerScreenType(goog.ui.OfflineInstallDialog.EnableScreen.TYPE, - goog.ui.OfflineInstallDialog.EnableScreen); - this.registerScreenType(goog.ui.OfflineInstallDialog.InstallScreen.TYPE, - goog.ui.OfflineInstallDialog.InstallScreen); - this.registerScreenType(goog.ui.OfflineInstallDialog.UpgradeScreen.TYPE, - goog.ui.OfflineInstallDialog.UpgradeScreen); - this.registerScreenType( - goog.ui.OfflineInstallDialog.InstallingGearsScreen.TYPE, - goog.ui.OfflineInstallDialog.InstallingGearsScreen); -}; -goog.inherits(goog.ui.OfflineInstallDialog, goog.ui.Dialog); - - -/** - * Buttons keys of the dialog. - * @enum {string} - */ -goog.ui.OfflineInstallDialog.ButtonKeyType = { - INSTALL: 'io', - UPGRADE: 'u', - ENABLE: 'eo', - CANCEL: 'ca', - CLOSE: 'cl', - OK: 'ok' -}; - - -/** - * The various types of screens the dialog can display. - * @enum {string} - */ -goog.ui.OfflineInstallDialog.ScreenType = { - INSTALL: 'i', - INSTALLING_GEARS: 'ig', - ENABLE: 'e', - UPGRADE: 'u' -}; - - -/** - * Whether the dialog is dirty and requires an upate to its display. - * @type {boolean} - * @private - */ -goog.ui.OfflineInstallDialog.prototype.dirty_ = false; - - -/** - * The type of the current screen of the dialog. - * @type {string} - * @private - */ -goog.ui.OfflineInstallDialog.prototype.currentScreenType_; - - -/** - * The url of the application. - * @type {string} - * @private - */ -goog.ui.OfflineInstallDialog.prototype.appUrl_ = ''; - - -/** - * The url of the page to download Gears from. - * @type {string} - * @private - */ -goog.ui.OfflineInstallDialog.prototype.gearsDownloadPageUrl_ = ''; - - -/** - * Marks as dirty and calls update if needed. - * @private - */ -goog.ui.OfflineInstallDialog.prototype.invalidateAndUpdate_ = function() { - this.dirty_ = true; - if (this.getElement() && this.isVisible()) { - this.update(); - } -}; - - -/** - * Sets the URL of the appliction to show in the dialog. - * @param {string} url The application URL. - */ -goog.ui.OfflineInstallDialog.prototype.setAppUrl = function(url) { - this.appUrl_ = url; - this.invalidateAndUpdate_(); -}; - - -/** - * @return {string} The application URL. - */ -goog.ui.OfflineInstallDialog.prototype.getAppUrl = function() { - return this.appUrl_; -}; - - -/** - * Sets the Gears download page URL. - * @param {string} url The Gears download page URL. - */ -goog.ui.OfflineInstallDialog.prototype.setGearsDownloadPageUrl = function(url) { - this.gearsDownloadPageUrl_ = url; - this.invalidateAndUpdate_(); -}; - - -/** - * @return {string} The Gears download page URL. - */ -goog.ui.OfflineInstallDialog.prototype.getGearsDownloadPageUrl = function() { - return this.gearsDownloadPageUrl_; -}; - - -/** - * This allows you to provide a shorter and more user friendly URL to the Gears - * download page since the Gears download URL can get quite ugly with all its - * params. - * @return {string} The Gears download page friendly URL. - */ -goog.ui.OfflineInstallDialog.prototype.getGearsDownloadPageFriendlyUrl = - function() { - return this.gearsDownloadPageFriendlyUrl_ || this.gearsDownloadPageUrl_; -}; - - -/** - * Sets the Gears download page friendly URL. - * @see #getGearsDownloadPageFriendlyUrl - * @param {string} url The Gears download page friendly URL. - */ -goog.ui.OfflineInstallDialog.prototype.setGearsDownloadPageFriendlyUrl = - function(url) { - this.gearsDownloadPageFriendlyUrl_ = url; - this.invalidateAndUpdate_(); -}; - - -/** - * Sets the screen type. - * @param {string} screenType The screen type. - */ -goog.ui.OfflineInstallDialog.prototype.setCurrentScreenType = function( - screenType) { - if (screenType != this.currentScreenType_) { - // If we have a current screen object then call deactivate on it - var currentScreen = this.getCurrentScreen(); - if (currentScreen && this.isInDocument()) { - currentScreen.deactivate(); - } - this.currentScreenType_ = screenType; - this.invalidateAndUpdate_(); - } -}; - - -/** - * @return {string} The screen type. - */ -goog.ui.OfflineInstallDialog.prototype.getCurrentScreenType = function() { - return this.currentScreenType_; -}; - - -/** - * @return {goog.ui.OfflineInstallDialogScreen?} The current screen object. - */ -goog.ui.OfflineInstallDialog.prototype.getCurrentScreen = function() { - return this.getScreen(this.currentScreenType_); -}; - - -/** - * Returns the screen object for a given registered type or null if no such type - * exists. This will create a screen object for a registered type as needed. - * @param {string} type The type of screen to get. - * @return {goog.ui.OfflineInstallDialogScreen?} The screen object. - */ -goog.ui.OfflineInstallDialog.prototype.getScreen = function(type) { - if (this.screens_[type]) { - return this.screens_[type]; - } - // Construct lazily as needed - if (this.screenConstructors_[type]) { - return this.screens_[type] = new this.screenConstructors_[type](this); - } - return null; -}; - - -/** - * Registers a screen constructor to be usable with the dialog. - * @param {string} type The type of this screen. - * @param {Function} constr A function that represents a constructor that - * extends goog.ui.OfflineInstallDialogScreen. - */ -goog.ui.OfflineInstallDialog.prototype.registerScreenType = function(type, - constr) { - this.screenConstructors_[type] = constr; - // Remove screen in case it already exists. - if (this.screens_[type]) { - var isCurrenScreenType = this.currentScreenType_ == type; - this.screens_[type].dispose(); - delete this.screens_[type]; - if (isCurrenScreenType) { - this.invalidateAndUpdate_(); - } - } -}; - - -/** - * Registers an instance of a screen to be usable with the dialog. - * @param {goog.ui.OfflineInstallDialogScreen} screen The screen to register. - */ -goog.ui.OfflineInstallDialog.prototype.registerScreen = function(screen) { - this.screens_[screen.getType()] = screen; -}; - - -/** @override */ -goog.ui.OfflineInstallDialog.prototype.setVisible = function(visible) { - if (this.isInDocument() && visible) { - if (this.dirty_) { - this.update(); - } - } - - goog.ui.OfflineInstallDialog.superClass_.setVisible.call(this, visible); -}; - - -/** @override */ -goog.ui.OfflineInstallDialog.prototype.createDom = function() { - goog.ui.OfflineInstallDialog.superClass_.createDom.call(this); - this.update(); -}; - - -/** @override */ -goog.ui.OfflineInstallDialog.prototype.enterDocument = function() { - goog.ui.OfflineInstallDialog.superClass_.enterDocument.call(this); - - this.getHandler().listen( - this, goog.ui.Dialog.EventType.SELECT, this.handleSelect_); - - if (this.dirty_) { - this.update(); - } -}; - - -/** - * Updates the dialog. This will ensure the correct screen is shown. - */ -goog.ui.OfflineInstallDialog.prototype.update = function() { - if (this.getElement()) { - var screen = this.getCurrentScreen(); - if (screen) { - screen.activate(); - } - - // Clear the dirty state. - this.dirty_ = false; - } -}; - - -/** - * Handles the SELECT_EVENT for the current dialog. Forward the event to the - * correct screen object and let the screen decide where to go next. - * @param {goog.ui.Dialog.Event} e The event. - * @private - */ -goog.ui.OfflineInstallDialog.prototype.handleSelect_ = function(e) { - var screen = this.getCurrentScreen(); - if (screen) { - screen.handleSelect(e); - } -}; - - -/** - * Opens a new browser window with the Gears download page and changes - * the screen to the installing gears page. - */ -goog.ui.OfflineInstallDialog.prototype.goToGearsDownloadPage = function() { - goog.window.open(this.gearsDownloadPageUrl_); -}; - - -/** @override */ -goog.ui.OfflineInstallDialog.prototype.disposeInternal = function() { - goog.ui.OfflineInstallDialog.superClass_.disposeInternal.call(this); - - delete this.screenConstructors_; - for (var type in this.screens_) { - this.screens_[type].dispose(); - } - delete this.screens_; -}; - - - -/** - * Represents a screen on the dialog. You can create new screens and add them - * to the offline install dialog by calling registerScreenType and - * setCurrentScreenType. - * @param {goog.ui.OfflineInstallDialog} dialog The dialog this screen should - * work with. - * @param {string} type The screen type name. - * @constructor - * @extends {goog.Disposable} - */ -goog.ui.OfflineInstallDialogScreen = function(dialog, type) { - goog.Disposable.call(this); - - /** - * @type {goog.ui.OfflineInstallDialog} - * @protected - * @suppress {underscore} - */ - this.dialog_ = dialog; - - /** - * @type {string} - * @private - */ - this.type_ = type; - - /** - * @type {goog.dom.DomHelper} - * @private - */ - this.dom_ = dialog.getDomHelper(); -}; -goog.inherits(goog.ui.OfflineInstallDialogScreen, goog.Disposable); - - -/** - * The HTML content to show on the screen. - * @type {string} - * @private - */ -goog.ui.OfflineInstallDialogScreen.prototype.content_ = ''; - - -/** - * The title to show on the dialog. - * @type {string} - * @private - */ -goog.ui.OfflineInstallDialogScreen.prototype.title_ = ''; - - -/** - * The button set to use with this screen. - * @type {goog.ui.Dialog.ButtonSet} - * @private - */ -goog.ui.OfflineInstallDialogScreen.prototype.buttonSet_; - - -/** - * @return {goog.ui.OfflineInstallDialog} The dialog the screen will be - * displayed in. - */ -goog.ui.OfflineInstallDialogScreen.prototype.getDialog = function() { - return this.dialog_; -}; - - -/** - * Returns the type of the screen. This is used to identify the screen type this - * reflects. - * @return {string} The type of the screen. - */ -goog.ui.OfflineInstallDialogScreen.prototype.getType = function() { - return this.type_; -}; - - -/** - * @return {goog.ui.Dialog.ButtonSet} The button set to use with this screen. - */ -goog.ui.OfflineInstallDialogScreen.prototype.getButtonSet = function() { - return this.buttonSet_; -}; - - -/** - * Sets the button set to use with this screen. - * @param {goog.ui.Dialog.ButtonSet} bs The button set to use. - */ -goog.ui.OfflineInstallDialogScreen.prototype.setButtonSet = function(bs) { - this.buttonSet_ = bs; -}; - - -/** - * @return {string} The HTML content to used for this screen. - */ -goog.ui.OfflineInstallDialogScreen.prototype.getContent = function() { - return this.content_; -}; - - -/** - * Sets the HTML content to use for this screen. - * @param {string} html The HTML text to use as content for the screen. - */ -goog.ui.OfflineInstallDialogScreen.prototype.setContent = function(html) { - this.content_ = html; -}; - - -/** - * @return {string} The text title to used for the dialog when this screen is - * shown. - */ -goog.ui.OfflineInstallDialogScreen.prototype.getTitle = function() { - return this.title_ || this.dialog_.getTitle(); -}; - - -/** - * Sets the plain text title to use for this screen. - * @param {string} title The plain text to use as a title on the dialog. - */ -goog.ui.OfflineInstallDialogScreen.prototype.setTitle = function(title) { - this.title_ = title; -}; - - -/** - * @return {string} A custom class name that should be added to the dialog when - * this screen is active. - */ -goog.ui.OfflineInstallDialogScreen.prototype.getCustomClassName = function() { - return this.customClassName_; -}; - - -/** - * Sets the custom class name that should be added to the dialog when this - * screen is active. - * @param {string} customClassName The custom class name. - */ -goog.ui.OfflineInstallDialogScreen.prototype.setCustomClassName = function( - customClassName) { - this.customClassName_ = customClassName; -}; - - -/** - * Called when the screen is shown. At this point the dialog is in the document. - */ -goog.ui.OfflineInstallDialogScreen.prototype.activate = function() { - var d = this.dialog_; - // Add custom class. - var customClassName = this.getCustomClassName(); - if (customClassName) { - goog.dom.classes.add(d.getElement(), customClassName); - } - - d.setTitle(this.getTitle()); - d.setContent(this.getContent()); - d.setButtonSet(this.getButtonSet()); -}; - - -/** - * Called when the screen is hidden. At this point the dialog is in the - * document. - */ -goog.ui.OfflineInstallDialogScreen.prototype.deactivate = function() { - // Remove custom class name - var customClassName = this.getCustomClassName(); - if (customClassName) { - goog.dom.classes.remove(this.dialog_.getElement(), customClassName); - } -}; - - -/** - * Called when the user clicks any of the buttons for this dialog screen. - * @param {goog.ui.Dialog.Event} e The dialog event. - */ -goog.ui.OfflineInstallDialogScreen.prototype.handleSelect = function(e) { - -}; - - - -// Classes for some of the standard screens - - - -/** - * This screen is shown to users that do have Gears installed but have - * not enabled the current application for offline access. - * @param {goog.ui.OfflineInstallDialog} dialog The dialog this is a screen - * for. - * @constructor - * @extends {goog.ui.OfflineInstallDialogScreen} - */ -goog.ui.OfflineInstallDialog.EnableScreen = function(dialog) { - goog.ui.OfflineInstallDialogScreen.call(this, dialog, - goog.ui.OfflineInstallDialog.EnableScreen.TYPE); - - /** - * @desc Text of button that enables offline functionality for the app. - * @hidden - */ - var MSG_OFFLINE_DIALOG_ENABLE_GEARS = goog.getMsg('Enable offline access'); - - /** - * @type {string} - * @protected - * @suppress {underscore} - */ - this.enableMsg_ = MSG_OFFLINE_DIALOG_ENABLE_GEARS; -}; -goog.inherits(goog.ui.OfflineInstallDialog.EnableScreen, - goog.ui.OfflineInstallDialogScreen); - - -/** - * The type of this screen. - * @type {string} - */ -goog.ui.OfflineInstallDialog.EnableScreen.TYPE = - goog.ui.OfflineInstallDialog.ScreenType.ENABLE; - - -/** - * Should enable button action be performed immediately when the user presses - * the enter key anywhere on the dialog. This should be set to false if there - * are other action handlers on the dialog that may stop propagation. - * @type {boolean} - * @protected - */ -goog.ui.OfflineInstallDialog.EnableScreen.prototype.enableOnEnter = true; - - -/** - * @return {goog.ui.Dialog.ButtonSet} The button set for the enable screen. - */ -goog.ui.OfflineInstallDialog.EnableScreen.prototype.getButtonSet = function() { - if (!this.buttonSet_) { - - /** - * @desc Text of button that cancels setting up Offline. - * @hidden - */ - var MSG_OFFLINE_DIALOG_CANCEL = goog.getMsg('Cancel'); - var buttonSet = this.buttonSet_ = new goog.ui.Dialog.ButtonSet(this.dom_); - buttonSet.set(goog.ui.OfflineInstallDialog.ButtonKeyType.ENABLE, - this.enableMsg_, this.enableOnEnter, false); - buttonSet.set(goog.ui.OfflineInstallDialog.ButtonKeyType.CANCEL, - MSG_OFFLINE_DIALOG_CANCEL, false, true); - } - - return this.buttonSet_; -}; - - - -/** - * This screen is shown to users that do have Gears installed but have - * not enabled the current application for offline access. - * @param {goog.ui.OfflineInstallDialog} dialog The dialog this is a screen - * for. - * @param {string=} opt_type An optional type, for specifying a more specific - * type of dialog. Only for use by subclasses. - * @constructor - * @extends {goog.ui.OfflineInstallDialogScreen} - */ -goog.ui.OfflineInstallDialog.InstallScreen = function(dialog, opt_type) { - goog.ui.OfflineInstallDialogScreen.call(this, dialog, - opt_type || goog.ui.OfflineInstallDialog.InstallScreen.TYPE); - - /** - * @desc The description of the the install step to perform in order to - * enable offline access. - * @hidden - */ - var MSG_OFFLINE_DIALOG_INSTALL_GEARS = goog.getMsg('Install Gears'); - - /** - * @type {string} - * @protected - * @suppress {underscore} - */ - this.installMsg_ = MSG_OFFLINE_DIALOG_INSTALL_GEARS; - - /** - * @desc Text of button that opens the download page for Gears. - * @hidden - */ - var MSG_INSTALL_GEARS = goog.getMsg('Get Gears now'); - - /** - * @type {string} - * @protected - * @suppress {underscore} - */ - this.enableMsg_ = MSG_INSTALL_GEARS; - - /** - * @desc Text of button that cancels setting up Offline. - * @hidden - */ - var MSG_OFFLINE_DIALOG_CANCEL_2 = goog.getMsg('Cancel'); - - /** - * @type {string} - * @private - */ - this.cancelMsg_ = MSG_OFFLINE_DIALOG_CANCEL_2; -}; -goog.inherits(goog.ui.OfflineInstallDialog.InstallScreen, - goog.ui.OfflineInstallDialogScreen); - - -/** - * The type of this screen. - * @type {string} - */ -goog.ui.OfflineInstallDialog.InstallScreen.TYPE = - goog.ui.OfflineInstallDialog.ScreenType.INSTALL; - - -/** - * The text to show before the installation steps. - * @type {string} - * @private - */ -goog.ui.OfflineInstallDialog.InstallScreen.prototype.installDescription_ = ''; - - -/** - * The CSS className to use when showing the app url. - * @type {string} - * @private - */ -goog.ui.OfflineInstallDialog.InstallScreen.prototype.appUrlClassName_ = - goog.getCssName('goog-offlinedialog-url'); - - -/** - * The CSS className for the element that contains the install steps. - * @type {string} - * @private - */ -goog.ui.OfflineInstallDialog.InstallScreen.prototype.stepsClassName_ = - goog.getCssName('goog-offlinedialog-steps'); - - -/** - * The CSS className for each step element. - * @type {string} - * @private - */ -goog.ui.OfflineInstallDialog.InstallScreen.prototype.stepClassName_ = - goog.getCssName('goog-offlinedialog-step'); - - -/** - * The CSS className for the element that shows the step number. - * @type {string} - * @private - */ -goog.ui.OfflineInstallDialog.InstallScreen.prototype.stepNumberClassName_ = - goog.getCssName('goog-offlinedialog-step-number'); - - -/** - * The CSS className for the element that shows the step desccription. - * @type {string} - * @private - */ -goog.ui.OfflineInstallDialog.InstallScreen.prototype.stepDescriptionClassName_ = - goog.getCssName('goog-offlinedialog-step-description'); - - -/** - * Should install button action be performed immediately when the user presses - * the enter key anywhere on the dialog. This should be set to false if there - * are other action handlers on the dialog that may stop propagation. - * @type {boolean} - * @protected - */ -goog.ui.OfflineInstallDialog.InstallScreen.prototype.isInstallButtonDefault = - true; - - -/** - * @return {goog.ui.Dialog.ButtonSet} The button set for the install screen. - */ -goog.ui.OfflineInstallDialog.InstallScreen.prototype.getButtonSet = function() { - if (!this.buttonSet_) { - var buttonSet = this.buttonSet_ = new goog.ui.Dialog.ButtonSet(this.dom_); - buttonSet.set(goog.ui.OfflineInstallDialog.ButtonKeyType.INSTALL, - this.enableMsg_, this.isInstallButtonDefault, false); - buttonSet.set(goog.ui.OfflineInstallDialog.ButtonKeyType.CANCEL, - this.cancelMsg_, false, true); - } - - return this.buttonSet_; -}; - - -/** - * Sets the install description. This is the text before the installation steps. - * @param {string} description The install description. - */ -goog.ui.OfflineInstallDialog.InstallScreen.prototype.setInstallDescription = - function(description) { - this.installDescription_ = description; -}; - - -/** @override */ -goog.ui.OfflineInstallDialog.InstallScreen.prototype.getContent = function() { - if (!this.content_) { - var sb = new goog.string.StringBuffer(this.installDescription_); - - /** - * @desc Header for the section that states the steps for the user to - * perform in order to enable offline access. - * @hidden - */ - var MSG_OFFLINE_DIALOG_NEED_TO = goog.getMsg('You\'ll need to:'); - sb.append('<div class="', this.stepsClassName_, '">', - MSG_OFFLINE_DIALOG_NEED_TO); - - // Create and append the html for step #1. - - sb.append(this.getStepHtml_(1, this.installMsg_)); - - // Create and append the html for step #2. - /** - * @desc One of the steps to perform in order to enable offline access. - * @hidden - */ - var MSG_OFFLINE_DIALOG_RESTART_BROWSER = goog.getMsg( - 'Restart your browser'); - sb.append(this.getStepHtml_(2, MSG_OFFLINE_DIALOG_RESTART_BROWSER)); - - // Create and append the html for step #3. - /** - * @desc One of the steps to perform in order to enable offline access. - * @hidden - */ - var MSG_OFFLINE_DIALOG_COME_BACK = goog.getMsg('Come back to {$appUrl}!', { - 'appUrl': '<span class="' + this.appUrlClassName_ + '">' + - this.dialog_.getAppUrl() + '</span>' - }); - sb.append(this.getStepHtml_(3, MSG_OFFLINE_DIALOG_COME_BACK)); - - // Close the enclosing element. - sb.append('</div>'); - - this.content_ = String(sb); - } - return this.content_; -}; - - -/** - * Creats the html for a step. - * @param {number} stepNumber The number of the step. - * @param {string} description The description of the step. - * @private - * @return {string} The step HTML in string form. - */ -goog.ui.OfflineInstallDialog.InstallScreen.prototype.getStepHtml_ = function( - stepNumber, description) { - return goog.string.buildString('<div class="', this.stepClassName_, - '"><span class="', this.stepNumberClassName_, '">', stepNumber, - '</span><span class="', this.stepDescriptionClassName_, '">', - description, '</span></div>'); -}; - - -/** - * Overrides to go to Gears page. - * @override - */ -goog.ui.OfflineInstallDialog.InstallScreen.prototype.handleSelect = - function(e) { - switch (e.key) { - case goog.ui.OfflineInstallDialog.ButtonKeyType.INSTALL: - case goog.ui.OfflineInstallDialog.ButtonKeyType.UPGRADE: - e.preventDefault(); - this.dialog_.goToGearsDownloadPage(); - this.dialog_.setCurrentScreenType( - goog.ui.OfflineInstallDialog.ScreenType.INSTALLING_GEARS); - break; - } -}; - - - -/** - * This screen is shown to users that needs to update their version of Gears - * before they can enabled the current application for offline access. - * @param {goog.ui.OfflineInstallDialog} dialog The dialog this is a screen - * for. - * @constructor - * @extends {goog.ui.OfflineInstallDialog.InstallScreen} - */ -goog.ui.OfflineInstallDialog.UpgradeScreen = function(dialog) { - goog.ui.OfflineInstallDialog.InstallScreen.call(this, dialog, - goog.ui.OfflineInstallDialog.UpgradeScreen.TYPE); - - /** - * @desc The description of the the upgrade step to perform in order to enable - * offline access. - * @hidden - */ - var MSG_OFFLINE_DIALOG_INSTALL_NEW_GEARS = goog.getMsg( - 'Install a new version of Gears'); - - /** - * Override to say upgrade instead of install. - * @type {string} - * @protected - * @suppress {underscore} - */ - this.installMsg_ = MSG_OFFLINE_DIALOG_INSTALL_NEW_GEARS; - - /** - * @desc Text of button that opens the download page for Gears for an - * upgrade. - * @hidden - */ - var MSG_OFFLINE_DIALOG_UPGRADE_GEARS = - goog.getMsg('Upgrade Gears now'); - - /** - * Override the text on the button to show upgrade instead of install. - * @type {string} - * @protected - * @suppress {underscore} - */ - this.enableMsg_ = MSG_OFFLINE_DIALOG_UPGRADE_GEARS; -}; -goog.inherits(goog.ui.OfflineInstallDialog.UpgradeScreen, - goog.ui.OfflineInstallDialog.InstallScreen); - - -/** - * The type of this screen. - * @type {string} - */ -goog.ui.OfflineInstallDialog.UpgradeScreen.TYPE = - goog.ui.OfflineInstallDialog.ScreenType.UPGRADE; - - -/** - * Should upgrade button action be performed immediately when the user presses - * the enter key anywhere on the dialog. This should be set to false if there - * are other action handlers on the dialog that may stop propagation. - * @type {boolean} - * @protected - */ -goog.ui.OfflineInstallDialog.UpgradeScreen.prototype.isUpgradeButtonDefault = - true; - - -/** - * @return {goog.ui.Dialog.ButtonSet} The button set for the upgrade screen. - */ -goog.ui.OfflineInstallDialog.UpgradeScreen.prototype.getButtonSet = function() { - if (!this.buttonSet_) { - /** - * @desc Text of button that cancels setting up Offline. - * @hidden - */ - var MSG_OFFLINE_DIALOG_CANCEL_3 = goog.getMsg('Cancel'); - - var buttonSet = this.buttonSet_ = new goog.ui.Dialog.ButtonSet(this.dom_); - buttonSet.set(goog.ui.OfflineInstallDialog.ButtonKeyType.UPGRADE, - this.enableMsg_, this.isUpgradeButtonDefault, false); - buttonSet.set(goog.ui.OfflineInstallDialog.ButtonKeyType.CANCEL, - MSG_OFFLINE_DIALOG_CANCEL_3, false, true); - } - - return this.buttonSet_; -}; - - -/** - * Sets the upgrade description. This is the text before the upgrade steps. - * @param {string} description The upgrade description. - */ -goog.ui.OfflineInstallDialog.UpgradeScreen.prototype.setUpgradeDescription = - function(description) { - this.setInstallDescription(description); -}; - - - -/** - * This screen is shown to users after the window to the Gears download page has - * been opened. - * @param {goog.ui.OfflineInstallDialog} dialog The dialog this is a screen - * for. - * @constructor - * @extends {goog.ui.OfflineInstallDialogScreen} - */ -goog.ui.OfflineInstallDialog.InstallingGearsScreen = function(dialog) { - goog.ui.OfflineInstallDialogScreen.call(this, dialog, - goog.ui.OfflineInstallDialog.InstallingGearsScreen.TYPE); -}; -goog.inherits(goog.ui.OfflineInstallDialog.InstallingGearsScreen, - goog.ui.OfflineInstallDialogScreen); - - -/** - * The type of this screen. - * @type {string} - */ -goog.ui.OfflineInstallDialog.InstallingGearsScreen.TYPE = - goog.ui.OfflineInstallDialog.ScreenType.INSTALLING_GEARS; - - -/** - * The CSS className to use for bold text. - * @type {string} - * @private - */ -goog.ui.OfflineInstallDialog.InstallingGearsScreen.prototype.boldClassName_ = - goog.getCssName('goog-offlinedialog-bold'); - - -/** - * Gets the button set for the dialog when the user is suposed to be installing - * Gears. - * @return {goog.ui.Dialog.ButtonSet} The button set. - */ -goog.ui.OfflineInstallDialog.InstallingGearsScreen.prototype.getButtonSet = - function() { - if (!this.buttonSet_) { - /** - * @desc Text of button that closes the dialog. - * @hidden - */ - var MSG_OFFLINE_DIALOG_CLOSE = goog.getMsg('Close'); - - var buttonSet = this.buttonSet_ = - new goog.ui.Dialog.ButtonSet(this.dom_); - buttonSet.set(goog.ui.OfflineInstallDialog.ButtonKeyType.CLOSE, - MSG_OFFLINE_DIALOG_CLOSE, false, true); - } - return this.buttonSet_; -}; - - -/** - * Gets the content for the dialog when the user is suposed to be installing - * Gears. - * @return {string} The content of the dialog as html. - */ -goog.ui.OfflineInstallDialog.InstallingGearsScreen.prototype.getContent = - function() { - if (!this.content_) { - /** - * @desc Congratulate the user for trying to download Google gears, - * and give them a push in the right direction. - */ - var MSG_OFFLINE_DIALOG_GEARS_DOWNLOAD_OPEN = goog.getMsg( - 'Great! The Gears download page has been opened in a new ' + - 'window. If you accidentally closed it, you can {$aBegin}open the ' + - 'Gears download page again{$aEnd}.', - { - 'aBegin': '<a ' + 'target="_blank" href="' + - this.getDialog().getGearsDownloadPageUrl() + '">', - 'aEnd': '</a>' - }); - - /** - * @desc Informs the user to come back to the the given site after - * installing Gears. - * @hidden - */ - var MSG_OFFLINE_DIALOG_GEARS_AFTER_INSTALL = goog.getMsg('After you\'ve ' + - 'downloaded and installed Gears, {$beginTag}restart your ' + - 'browser, and then come back to {$appUrl}!{$endTag}', - { - 'beginTag': '<div class="' + this.boldClassName_ + '">', - 'endTag': '</div>', 'appUrl': this.getDialog().getAppUrl() - }); - - // Set the content. - this.content_ = goog.string.buildString('<div>', - MSG_OFFLINE_DIALOG_GEARS_DOWNLOAD_OPEN, '</div><br/><div>', - MSG_OFFLINE_DIALOG_GEARS_AFTER_INSTALL, '</div>'); - } - return this.content_; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/offlinestatuscard.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/offlinestatuscard.js.svn-base deleted file mode 100644 index a4ae68b..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/offlinestatuscard.js.svn-base +++ /dev/null @@ -1,580 +0,0 @@ -// 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 card that displays the offline status of an app. It contains - * detailed information such as a progress bar the indicates the status of - * syncing and allows you to perform actions (such as manually go offline). - * - * @see ../demos/offline.html - */ - -goog.provide('goog.ui.OfflineStatusCard'); -goog.provide('goog.ui.OfflineStatusCard.EventType'); - -goog.require('goog.dom'); -goog.require('goog.events.EventType'); -goog.require('goog.gears.StatusType'); -goog.require('goog.structs.Map'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.ProgressBar'); - - - -/** - * A offline status card. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Component} - */ -goog.ui.OfflineStatusCard = function(opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - - /** - * The progress bar for showing the status of syncing. - * @type {goog.ui.ProgressBar} - * @private - */ - this.progressBar_ = new goog.ui.ProgressBar(opt_domHelper); - this.addChild(this.progressBar_); - - /** - * A map of action element uid/action event type pairs. - * @type {goog.structs.Map} - * @private - */ - this.actionMap_ = new goog.structs.Map(); -}; -goog.inherits(goog.ui.OfflineStatusCard, goog.ui.Component); - - -/** - * Event types dispatched by the component. - * @enum {string} - */ -goog.ui.OfflineStatusCard.EventType = { - /** Dispatched when the user wants the card to be dismissed. */ - DISMISS: 'dismiss' -}; - - -/** - * Whether the component is dirty and requires an upate to its display. - * @type {boolean} - * @protected - */ -goog.ui.OfflineStatusCard.prototype.dirty = false; - - -/** - * The status of the component. - * @type {goog.gears.StatusType} - * @private - */ -goog.ui.OfflineStatusCard.prototype.status_ = - goog.gears.StatusType.NOT_INSTALLED; - - -/** - * The element that holds the status message. - * @type {Element} - * @private - */ -goog.ui.OfflineStatusCard.prototype.statusEl_ = null; - - -/** - * The element that, when clicked, performs the appropriate action (such as - * pausing synchronization). - * @type {Element} - * @private - */ -goog.ui.OfflineStatusCard.prototype.actionEl_ = null; - - -/** - * The element that displays additional messaging. - * @type {Element} - * @private - */ -goog.ui.OfflineStatusCard.prototype.messageEl_ = null; - - -/** - * The element that holds the progress bar and progress status. - * @type {Element} - * @private - */ -goog.ui.OfflineStatusCard.prototype.progressEl_ = null; - - -/** - * The element that holds the progress status. - * @type {Element} - * @private - */ -goog.ui.OfflineStatusCard.prototype.progressStatusEl_ = null; - - -/** - * The element that holds the close button. - * @type {Element} - * @private - */ -goog.ui.OfflineStatusCard.prototype.closeEl_ = null; - - -/** - * CSS class name for the element. - * @type {string} - * @private - */ -goog.ui.OfflineStatusCard.prototype.className_ = - goog.getCssName('goog-offlinestatuscard'); - - -/** - * CSS class name for the shadow element. - * @type {string} - * @private - */ -goog.ui.OfflineStatusCard.prototype.shadowClassName_ = - goog.getCssName('goog-offlinestatuscard-shadow'); - - -/** - * CSS class name for the content element. - * @type {string} - * @private - */ -goog.ui.OfflineStatusCard.prototype.contentClassName_ = - goog.getCssName('goog-offlinestatuscard-content'); - - -/** - * CSS class name for the status element. - * @type {string} - * @private - */ -goog.ui.OfflineStatusCard.prototype.statusClassName_ = - goog.getCssName('goog-offlinestatuscard-status'); - - -/** - * CSS class name for the action element. - * @type {string} - * @private - */ -goog.ui.OfflineStatusCard.prototype.actionClassName_ = - goog.getCssName('goog-offlinestatuscard-action'); - - -/** - * CSS class name for each action item contained in the action element. - * @type {string} - * @private - */ -goog.ui.OfflineStatusCard.prototype.actionItemClassName_ = - goog.getCssName('goog-offlinestatuscard-action-item'); - - -/** - * CSS class name for the last action item contained in the action element. - * @type {string} - * @private - */ -goog.ui.OfflineStatusCard.prototype.lastActionItemClassName_ = - goog.getCssName('goog-offlinestatuscard-action-item-last'); - - -/** - * CSS class name for the message element. - * @type {string} - * @private - */ -goog.ui.OfflineStatusCard.prototype.messageClassName_ = - goog.getCssName('goog-offlinestatuscard-message'); - - -/** - * CSS class name for the progress bar status element. - * @type {string} - * @private - */ -goog.ui.OfflineStatusCard.prototype.progressBarStatusClassName_ = - goog.getCssName('goog-offlinestatuscard-progressbarstatus'); - - -/** - * CSS class name for the close card element. - * @type {string} - * @private - */ -goog.ui.OfflineStatusCard.prototype.closeCardClassName_ = - goog.getCssName('goog-offlinestatuscard-closecard'); - - -/** - * Gets the progress bar. - * @return {goog.ui.ProgressBar} The progress bar. - */ -goog.ui.OfflineStatusCard.prototype.getProgressBar = function() { - return this.progressBar_; -}; - - -/** - * Gets the status of the offline component of the app. - * @return {goog.gears.StatusType} The offline status. - */ -goog.ui.OfflineStatusCard.prototype.getStatus = function() { - return this.status_; -}; - - -/** - * Sets the status of the offline component of the app. - * @param {goog.gears.StatusType} status The offline status. - */ -goog.ui.OfflineStatusCard.prototype.setStatus = function(status) { - if (this.status_ != status) { - this.dirty = true; - } - this.status_ = status; - if (this.isInDocument()) { - this.update(); - } -}; - - -/** - * Creates the initial DOM representation for the component. - */ -goog.ui.OfflineStatusCard.prototype.createDom = function() { - var dom = this.getDomHelper(); - this.setElementInternal(dom.createDom('div', this.className_, - dom.createDom('div', this.shadowClassName_, - dom.createDom('div', this.contentClassName_, - this.closeEl_ = dom.createDom('div', this.closeCardClassName_), - this.statusEl_ = dom.createDom('div', this.statusClassName_), - this.progressEl_ = dom.createDom('div', null, - this.progressBarStatusEl_ = - dom.createDom('div', this.progressBarStatusClassName_)), - this.actionEl_ = dom.createDom('div', this.actionClassName_), - this.messageEl_ = dom.createDom('div', - this.messageClassName_))))); - - // Create and append the DOM of the progress bar. - this.progressBar_.createDom(); - dom.insertSiblingBefore( - this.progressBar_.getElement(), this.progressBarStatusEl_); - - this.createAdditionalDom(); - - this.update(); -}; - - -/** @override */ -goog.ui.OfflineStatusCard.prototype.enterDocument = function() { - goog.ui.OfflineStatusCard.superClass_.enterDocument.call(this); - - // Listen for changes to the progress bar. - var handler = this.getHandler(); - handler.listen(this.progressBar_, goog.ui.Component.EventType.CHANGE, - this.handleProgressChange_); - - // Listen for a click on the action element. - handler.listen( - this.actionEl_, goog.events.EventType.CLICK, this.handleActionClick_); - - // Listen for the click on the close element. - handler.listen(this.closeEl_, goog.events.EventType.CLICK, this.closePopup_); - - // Update the component if it is dirty. - if (this.dirty) { - this.update(); - } -}; - - -/** - * Allows subclasses to initialize additional DOM structures during createDom. - * @protected - */ -goog.ui.OfflineStatusCard.prototype.createAdditionalDom = function() { -}; - - -/** - * Sends an event to OfflineStatusComponent to dismiss the popup. - * @private - */ -goog.ui.OfflineStatusCard.prototype.closePopup_ = function() { - this.dispatchEvent(goog.ui.OfflineStatusCard.EventType.DISMISS); -}; - - -/** - * Updates the display of the component. - */ -goog.ui.OfflineStatusCard.prototype.update = function() { - if (this.getElement()) { - var status = this.getStatus(); - var dom = this.getDomHelper(); - - this.configureStatusElement(status); - this.configureActionLinks(status); - this.configureProgressElement(status); - - // Configure the message element. - var message = this.getAdditionalMessage(status); - var messageEl = this.messageEl_; - goog.style.showElement(messageEl, message); - if (message) { - dom.setTextContent(messageEl, message); - } - - // Clear the dirty state. - this.dirty = false; - } -}; - - -/** - * Set the message to display in the status portion of the card. - * @param {goog.gears.StatusType} status The offline status. - */ -goog.ui.OfflineStatusCard.prototype.configureStatusElement = function(status) { - /** - * @desc Tell the user whether they are online, offline, or syncing to - * Gears. - */ - var MSG_OFFLINE_STATUS = goog.getMsg( - 'Status: {$msg}', {'msg': this.getStatusMessage(status)}); - this.getDomHelper().setTextContent(this.statusEl_, MSG_OFFLINE_STATUS); -}; - - -/** - * Set the action element to show correct action(s) for a particular status. - * @param {goog.gears.StatusType} status The offline status. - */ -goog.ui.OfflineStatusCard.prototype.configureActionLinks = function(status) { - // Configure the action element. - var actions = this.getActions(status); - goog.dom.removeChildren(this.actionEl_); - this.actionMap_.clear(); - - if (actions) { - var lastIdx = actions.length - 1; - for (var i = 0; i <= lastIdx; i++) { - // Ensure there is no padding to the right of the last action link. - this.createLinkNode_(actions[i], i == lastIdx ? - this.lastActionItemClassName_ : this.actionItemClassName_); - } - } -}; - - -/** - * Creates an action link element and styles it. - * @param {Object} action An action object with message and event type. - * @param {string} className The css class name to style the link with. - * @private - */ -goog.ui.OfflineStatusCard.prototype.createLinkNode_ = function( - action, className) { - var actionEl = this.actionEl_; - var dom = this.getDomHelper(); - var a = dom.createDom('span', className); - dom.appendChild(actionEl, a); - // A text node is needed here in order for links to wrap. - dom.appendChild(actionEl, dom.createTextNode(' ')); - this.actionMap_.set(goog.getUid(a), action.eventType); - goog.style.showElement(a, true); - dom.setTextContent(a, action.message); -}; - - -/** - * Configure the progress bar element. - * @param {goog.gears.StatusType} status The offline status. - */ -goog.ui.OfflineStatusCard.prototype.configureProgressElement = - function(status) { - var showProgress = this.shouldShowProgressBar(status); - goog.style.showElement(this.progressEl_, showProgress); - if (showProgress) { - this.updateProgressStatus(); - } -}; - - -/** - * Returns true if we want to display a progress bar. - * @param {goog.gears.StatusType} status The offline status. - * @return {boolean} Whether we want to display a progress bar. - */ -goog.ui.OfflineStatusCard.prototype.shouldShowProgressBar = function(status) { - return status == goog.gears.StatusType.SYNCING || - status == goog.gears.StatusType.CAPTURING; -}; - - -/** - * Handles a CHANGE event of the progress bar. Updates the status. - * @param {goog.events.Event} e The event. - * @private - */ -goog.ui.OfflineStatusCard.prototype.handleProgressChange_ = function(e) { - this.updateProgressStatus(); -}; - - -/** - * Handles a CLICK event on the action element. Dispatches the appropriate - * action event type. - * @param {goog.events.BrowserEvent} e The event. - * @private - */ -goog.ui.OfflineStatusCard.prototype.handleActionClick_ = function(e) { - var actionEventType = /** @type {string} */ (this.actionMap_.get( - goog.getUid(e.target))); - if (actionEventType) { - this.dispatchEvent(actionEventType); - } -}; - - -/** - * Updates the status of the progress bar. - * @protected - */ -goog.ui.OfflineStatusCard.prototype.updateProgressStatus = function() { - this.getDomHelper().setTextContent( - this.progressBarStatusEl_, this.getProgressStatusMessage()); -}; - - -/** - * Gets the status message for the progress bar. - * @return {string} The status message for the progress bar. - */ -goog.ui.OfflineStatusCard.prototype.getProgressStatusMessage = function() { - var pb = this.progressBar_; - var percentValue = Math.round((pb.getValue() - pb.getMinimum()) / - (pb.getMaximum() - pb.getMinimum()) * 100); - /** @desc The percent complete status of the syncing. */ - var MSG_OFFLINE_PERCENT_COMPLETE = goog.getMsg( - '{$num}% complete.', {'num': percentValue}); - return MSG_OFFLINE_PERCENT_COMPLETE; -}; - - -/** - * Gets the status message for the given status. - * @param {goog.gears.StatusType} status The offline status. - * @return {string} The status message. - */ -goog.ui.OfflineStatusCard.prototype.getStatusMessage = function(status) { - var message = ''; - - switch (status) { - case goog.gears.StatusType.OFFLINE: - /** @desc Status shown when the app is offline. */ - var MSG_OFFLINE_STATUS_OFFLINE_MESSAGE = goog.getMsg( - 'Offline. No connection available.'); - message = MSG_OFFLINE_STATUS_OFFLINE_MESSAGE; - break; - case goog.gears.StatusType.ONLINE: - /** @desc Status shown when the app is online. */ - var MSG_OFFLINE_STATUS_ONLINE_MESSAGE = goog.getMsg('Online'); - message = MSG_OFFLINE_STATUS_ONLINE_MESSAGE; - break; - case goog.gears.StatusType.SYNCING: - /** @desc Status shown when the app is synchronizing. */ - var MSG_OFFLINE_STATUS_SYNCING_MESSAGE = goog.getMsg('Synchronizing...'); - message = MSG_OFFLINE_STATUS_SYNCING_MESSAGE; - break; - case goog.gears.StatusType.CAPTURING: - /** @desc Status shown when the app is capturing resources. */ - var MSG_OFFLINE_STATUS_CAPTURING_MESSAGE = goog.getMsg( - 'Updating software...'); - message = MSG_OFFLINE_STATUS_CAPTURING_MESSAGE; - break; - case goog.gears.StatusType.ERROR: - /** @desc Status shown when an error has occured. */ - var MSG_OFFLINE_STATUS_ERROR_MESSAGE = goog.getMsg( - 'Errors have been found.'); - message = MSG_OFFLINE_STATUS_ERROR_MESSAGE; - break; - default: - break; - } - return message; -}; - - -/** - * Gets the action to display for the given status. - * @param {goog.gears.StatusType} status The offline status. - * @return {Array.<Object>?} An array of action objects to display. - */ -goog.ui.OfflineStatusCard.prototype.getActions = function(status) { - return null; -}; - - -/** - * Creates an action object containing a message for the action and event - * type to dispatch if the action occurs. - * @param {string} actionMessage The action message. - * @param {string} actionEventType The action event type. - * @return {Object} An object containing message and eventType properties. - */ -goog.ui.OfflineStatusCard.prototype.createActionObject = function( - actionMessage, actionEventType) { - return {message: actionMessage, eventType: actionEventType}; -}; - - -/** - * Gets the additional message to display for the given status. - * @param {goog.gears.StatusType} status The offline status. - * @return {string} The additional message. - */ -goog.ui.OfflineStatusCard.prototype.getAdditionalMessage = function(status) { - return ''; -}; - - -/** @override */ -goog.ui.OfflineStatusCard.prototype.disposeInternal = function() { - goog.ui.OfflineStatusCard.superClass_.disposeInternal.call(this); - - this.progressBar_.dispose(); - this.progressBar_ = null; - - this.actionMap_.clear(); - this.actionMap_ = null; - - this.statusEl_ = null; - this.actionEl_ = null; - this.messageEl_ = null; - this.progressEl_ = null; - this.progressStatusEl_ = null; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/offlinestatuscomponent.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/offlinestatuscomponent.js.svn-base deleted file mode 100644 index 13c8eef..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/offlinestatuscomponent.js.svn-base +++ /dev/null @@ -1,546 +0,0 @@ -// 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 component that displays the offline status of an app. - * Currently, it is used to show an icon with a tootip for the status. - * - * @see ../demos/offline.html - */ - -goog.provide('goog.ui.OfflineStatusComponent'); -goog.provide('goog.ui.OfflineStatusComponent.StatusClassNames'); - -goog.require('goog.dom.classes'); -goog.require('goog.events.EventType'); -goog.require('goog.gears.StatusType'); -goog.require('goog.positioning'); -goog.require('goog.positioning.AnchoredPosition'); -goog.require('goog.positioning.Corner'); -goog.require('goog.positioning.Overflow'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.OfflineStatusCard.EventType'); -goog.require('goog.ui.Popup'); - - - -/** - * An offline status component. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Component} - */ -goog.ui.OfflineStatusComponent = function(opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); -}; -goog.inherits(goog.ui.OfflineStatusComponent, goog.ui.Component); - - -/** - * The className's to use for the element of the component for each status type. - * @enum {string} - */ -goog.ui.OfflineStatusComponent.StatusClassNames = { - NOT_INSTALLED: goog.getCssName('goog-offlinestatus-notinstalled'), - INSTALLED: goog.getCssName('goog-offlinestatus-installed'), - PAUSED: goog.getCssName('goog-offlinestatus-paused'), - OFFLINE: goog.getCssName('goog-offlinestatus-offline'), - ONLINE: goog.getCssName('goog-offlinestatus-online'), - SYNCING: goog.getCssName('goog-offlinestatus-syncing'), - ERROR: goog.getCssName('goog-offlinestatus-error') -}; - - -/** - * Whether the component is dirty and requires an upate to its display. - * @type {boolean} - * @private - */ -goog.ui.OfflineStatusComponent.prototype.dirty_ = false; - - -/** - * The status of the component. - * @type {goog.gears.StatusType} - * @private - */ -goog.ui.OfflineStatusComponent.prototype.status_ = - goog.gears.StatusType.NOT_INSTALLED; - - -/** - * The status of the component that is displayed. - * @type {goog.gears.StatusType?} - * @private - */ -goog.ui.OfflineStatusComponent.prototype.displayedStatus_ = null; - - -/** - * The dialog that manages the install flow. - * @type {goog.ui.OfflineInstallDialog?} - * @private - */ -goog.ui.OfflineStatusComponent.prototype.dialog_ = null; - - -/** - * The card for displaying the detailed status. - * @type {goog.ui.OfflineStatusCard?} - * @private - */ -goog.ui.OfflineStatusComponent.prototype.card_ = null; - - -/** - * The popup for the OfflineStatusCard. - * @type {goog.ui.Popup?} - * @private - */ -goog.ui.OfflineStatusComponent.prototype.popup_ = null; - - -/** - * CSS class name for the element. - * @type {string} - * @private - */ -goog.ui.OfflineStatusComponent.prototype.className_ = - goog.getCssName('goog-offlinestatus'); - - -/** - * @desc New feature text for the offline acces feature. - * @type {string} - * @private - */ -goog.ui.OfflineStatusComponent.prototype.MSG_OFFLINE_NEW_FEATURE_ = - goog.getMsg('New! Offline Access'); - - -/** - * @desc Connectivity status of the app indicating the app is paused (user - * initiated offline). - * @type {string} - * @private - */ -goog.ui.OfflineStatusComponent.prototype.MSG_OFFLINE_STATUS_PAUSED_TITLE_ = - goog.getMsg('Paused (offline). Click to connect.'); - - -/** - * @desc Connectivity status of the app indicating the app is offline. - * @type {string} - * @private - */ -goog.ui.OfflineStatusComponent.prototype.MSG_OFFLINE_STATUS_OFFLINE_TITLE_ = - goog.getMsg('Offline. No connection available.'); - - -/** - * @desc Connectivity status of the app indicating the app is online. - * @type {string} - * @private - */ -goog.ui.OfflineStatusComponent.prototype.MSG_OFFLINE_STATUS_ONLINE_TITLE_ = - goog.getMsg('Online. Click for details.'); - - -/** - * @desc Connectivity status of the app indicating the app is synchronizing with - * the server. - * @type {string} - * @private - */ -goog.ui.OfflineStatusComponent.prototype.MSG_OFFLINE_STATUS_SYNCING_TITLE_ = - goog.getMsg('Synchronizing. Click for details.'); - - -/** - * @desc Connectivity status of the app indicating errors have been found. - * @type {string} - * @private - */ -goog.ui.OfflineStatusComponent.prototype.MSG_OFFLINE_STATUS_ERROR_TITLE_ = - goog.getMsg('Errors found. Click for details.'); - - -/** - * Gets the status of the offline component of the app. - * @return {goog.gears.StatusType} The offline status. - */ -goog.ui.OfflineStatusComponent.prototype.getStatus = function() { - return this.status_; -}; - - -/** - * Sets the status of the offline component of the app. - * @param {goog.gears.StatusType} status The offline - * status. - */ -goog.ui.OfflineStatusComponent.prototype.setStatus = function(status) { - if (this.isStatusDifferent(status)) { - this.dirty_ = true; - } - - this.status_ = status; - if (this.isInDocument()) { - this.update(); - } - - // Set the status of the card, if necessary. - if (this.card_) { - this.card_.setStatus(status); - } -}; - - -/** - * Returns whether the given status is different from the currently - * recorded status. - * @param {goog.gears.StatusType} status The offline status. - * @return {boolean} Whether the status is different. - */ -goog.ui.OfflineStatusComponent.prototype.isStatusDifferent = function(status) { - return this.status_ != status; -}; - - -/** - * Sets the install dialog. - * @param {goog.ui.OfflineInstallDialog} dialog The dialog. - */ -goog.ui.OfflineStatusComponent.prototype.setInstallDialog = function(dialog) { - // If there is a current dialog, remove it. - if (this.dialog_ && this.indexOfChild(this.dialog_) >= 0) { - this.removeChild(this.dialog_); - } - this.dialog_ = dialog; -}; - - -/** - * Gets the install dialog. - * @return {goog.ui.OfflineInstallDialog} dialog The dialog. - */ -goog.ui.OfflineStatusComponent.prototype.getInstallDialog = function() { - return this.dialog_; -}; - - -/** - * Sets the status card. - * @param {goog.ui.OfflineStatusCard} card The card. - */ -goog.ui.OfflineStatusComponent.prototype.setStatusCard = function(card) { - // If there is a current card, remove it. - if (this.card_) { - this.getHandler().unlisten(this.card_, - goog.ui.OfflineStatusCard.EventType.DISMISS, - this.performStatusAction, false, this); - this.popup_.dispose(); - if (this.indexOfChild(this.card_) >= 0) { - this.removeChild(this.card_); - } - this.popup_ = null; - this.card_ = null; - } - this.card_ = card; - this.getHandler().listen(this.card_, - goog.ui.OfflineStatusCard.EventType.DISMISS, - this.performStatusAction, false, this); - card.setStatus(this.status_); -}; - - -/** - * Gets the status card. - * @return {goog.ui.OfflineStatusCard} The card. - */ -goog.ui.OfflineStatusComponent.prototype.getStatusCard = function() { - return this.card_; -}; - - -/** - * Creates the initial DOM representation for the component. - */ -goog.ui.OfflineStatusComponent.prototype.createDom = function() { - var anchorProps = { - 'class': this.className_, - 'href': '#' - }; - this.setElementInternal( - this.getDomHelper().createDom('a', anchorProps)); - this.update(); -}; - - -/** @override */ -goog.ui.OfflineStatusComponent.prototype.enterDocument = function() { - goog.ui.OfflineStatusComponent.superClass_.enterDocument.call(this); - - this.getHandler().listen( - this.getElement(), goog.events.EventType.CLICK, this.handleClick_); - - if (this.dirty_) { - this.update(); - } -}; - - -/** - * Updates the display of the component. - */ -goog.ui.OfflineStatusComponent.prototype.update = function() { - if (this.getElement()) { - var status = this.getStatus(); - var messageInfo = this.getMessageInfo(status); - - // Set the title. - var element = this.getElement(); - element.title = messageInfo.title; - - // Set the appropriate class. - var previousStatus = this.displayStatus_; - var previousStatusClassName = this.getStatusClassName_(previousStatus); - var currentStatusClassName = this.getStatusClassName_(status); - if (previousStatus && - goog.dom.classes.has(element, previousStatusClassName)) { - goog.dom.classes.swap( - element, previousStatusClassName, currentStatusClassName); - } else { - goog.dom.classes.add(element, currentStatusClassName); - } - - // Set the current display status - this.displayStatus_ = status; - - // Set the text. - if (messageInfo.textIsHtml) { - element.innerHTML = messageInfo.text; - } else { - this.getDomHelper().setTextContent(element, messageInfo.text); - } - - // Clear the dirty state. - this.dirty_ = false; - } -}; - - -/** - * Gets the messaging info for the given status. - * @param {goog.gears.StatusType} status Status to get the message info for. - * @return {Object} Object that has three properties - text (string), - * textIsHtml (boolean), and title (string). - */ -goog.ui.OfflineStatusComponent.prototype.getMessageInfo = function(status) { - var title = ''; - var text = ' '; - var textIsHtml = true; - - switch (status) { - case goog.gears.StatusType.NOT_INSTALLED: - case goog.gears.StatusType.INSTALLED: - text = this.MSG_OFFLINE_NEW_FEATURE_; - textIsHtml = false; - break; - case goog.gears.StatusType.PAUSED: - title = this.MSG_OFFLINE_STATUS_PAUSED_TITLE_; - break; - case goog.gears.StatusType.OFFLINE: - title = this.MSG_OFFLINE_STATUS_OFFLINE_TITLE_; - break; - case goog.gears.StatusType.ONLINE: - title = this.MSG_OFFLINE_STATUS_ONLINE_TITLE_; - break; - case goog.gears.StatusType.SYNCING: - title = this.MSG_OFFLINE_STATUS_SYNCING_TITLE_; - break; - case goog.gears.StatusType.ERROR: - title = this.MSG_OFFLINE_STATUS_ERROR_TITLE_; - break; - default: - break; - } - - return {text: text, textIsHtml: textIsHtml, title: title}; -}; - - -/** - * Gets the CSS className for the given status. - * @param {goog.gears.StatusType} status Status to get the className for. - * @return {string} The className. - * @private - */ -goog.ui.OfflineStatusComponent.prototype.getStatusClassName_ = function( - status) { - var className = ''; - switch (status) { - case goog.gears.StatusType.NOT_INSTALLED: - className = - goog.ui.OfflineStatusComponent.StatusClassNames.NOT_INSTALLED; - break; - case goog.gears.StatusType.INSTALLED: - className = goog.ui.OfflineStatusComponent.StatusClassNames.INSTALLED; - break; - case goog.gears.StatusType.PAUSED: - className = goog.ui.OfflineStatusComponent.StatusClassNames.PAUSED; - break; - case goog.gears.StatusType.OFFLINE: - className = goog.ui.OfflineStatusComponent.StatusClassNames.OFFLINE; - break; - case goog.gears.StatusType.ONLINE: - className = goog.ui.OfflineStatusComponent.StatusClassNames.ONLINE; - break; - case goog.gears.StatusType.SYNCING: - case goog.gears.StatusType.CAPTURING: - className = goog.ui.OfflineStatusComponent.StatusClassNames.SYNCING; - break; - case goog.gears.StatusType.ERROR: - className = goog.ui.OfflineStatusComponent.StatusClassNames.ERROR; - break; - default: - break; - } - return className; -}; - - -/** - * Handles a click on the component. Opens the applicable install dialog or - * status card. - * @param {goog.events.BrowserEvent} e The event. - * @private - * @return {boolean|undefined} Always false to prevent the anchor navigation. - */ -goog.ui.OfflineStatusComponent.prototype.handleClick_ = function(e) { - this.performAction(); - return false; -}; - - -/** - * Performs the action as if the component was clicked. - */ -goog.ui.OfflineStatusComponent.prototype.performAction = function() { - var status = this.getStatus(); - - if (status == goog.gears.StatusType.NOT_INSTALLED || - status == goog.gears.StatusType.INSTALLED) { - this.performEnableAction(); - } else { - this.performStatusAction(); - } -}; - - -/** - * Performs the action to start the flow of enabling the offline feature of - * the application. - */ -goog.ui.OfflineStatusComponent.prototype.performEnableAction = function() { - // If Gears is not installed or if it is installed but not enabled, then - // show the install dialog. - var dialog = this.dialog_; - if (dialog) { - if (!dialog.isInDocument()) { - this.addChild(dialog); - dialog.render(this.getDomHelper().getDocument().body); - } - dialog.setVisible(true); - } -}; - - -/** - * Performs the action to show the offline status. - * @param {goog.events.Event=} opt_evt Event. - * @param {Element=} opt_element Optional element to anchor the card against. - */ -goog.ui.OfflineStatusComponent.prototype.performStatusAction = function(opt_evt, - opt_element) { - // Shows the offline status card. - var card = this.card_; - if (card) { - if (!this.popup_) { - if (!card.getElement()) { - card.createDom(); - } - this.insertCardElement(card); - this.addChild(card); - var popup = this.getPopupInternal(); - var anchorEl = opt_element || this.getElement(); - var pos = new goog.positioning.AnchoredPosition( - anchorEl, goog.positioning.Corner.BOTTOM_START); - - // Override to pass in overflow - pos.reposition = function(element, popupCorner, opt_margin) { - goog.positioning.positionAtAnchor(this.element, this.corner, element, - popupCorner, null, opt_margin, goog.positioning.Overflow.ADJUST_X); - }; - - popup.setPosition(pos); - popup.setElement(card.getElement()); - } - this.popup_.setVisible(!this.popup_.isOrWasRecentlyVisible()); - } -}; - - -/** - * Inserts the card into the document body. - * @param {goog.ui.OfflineStatusCard} card The offline status card. - * @protected - */ -goog.ui.OfflineStatusComponent.prototype.insertCardElement = function(card) { - this.getDomHelper().getDocument().body.appendChild(card.getElement()); -}; - - -/** - * @return {goog.ui.Popup} A popup object, if none exists a new one is created. - * @protected - */ -goog.ui.OfflineStatusComponent.prototype.getPopupInternal = function() { - if (!this.popup_) { - this.popup_ = new goog.ui.Popup(); - this.popup_.setMargin(3, 0, 0, 0); - } - return this.popup_; -}; - - -/** @override */ -goog.ui.OfflineStatusComponent.prototype.disposeInternal = function() { - goog.ui.OfflineStatusComponent.superClass_.disposeInternal.call(this); - - if (this.dialog_) { - this.dialog_.dispose(); - this.dialog_ = null; - } - - if (this.card_) { - this.card_.dispose(); - this.card_ = null; - } - - if (this.popup_) { - this.popup_.dispose(); - this.popup_ = null; - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/option.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/option.js.svn-base deleted file mode 100644 index 7922cd8..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/option.js.svn-base +++ /dev/null @@ -1,68 +0,0 @@ -// 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 menu item class that supports selection state. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.Option'); - -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.MenuItem'); -goog.require('goog.ui.registry'); - - - -/** - * Class representing a menu option. This is just a convenience class that - * extends {@link goog.ui.MenuItem} by making it selectable. - * - * @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 {*=} opt_model Data/model associated with the menu item. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper used for - * document interactions. - * @constructor - * @extends {goog.ui.MenuItem} - */ -goog.ui.Option = function(content, opt_model, opt_domHelper) { - goog.ui.MenuItem.call(this, content, opt_model, opt_domHelper); - this.setSelectable(true); -}; -goog.inherits(goog.ui.Option, goog.ui.MenuItem); - - -/** - * Performs the appropriate action when the option is activated by the user. - * Overrides the superclass implementation by not changing the selection state - * of the option and not dispatching any SELECTED events, for backwards - * compatibility with existing uses of this class. - * @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. - */ -goog.ui.Option.prototype.performActionInternal = function(e) { - return this.dispatchEvent(goog.ui.Component.EventType.ACTION); -}; - - -// Register a decorator factory function for goog.ui.Options. -goog.ui.registry.setDecoratorByClassName( - goog.getCssName('goog-option'), function() { - // Option defaults to using MenuItemRenderer. - return new goog.ui.Option(null); -}); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/palette.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/palette.js.svn-base deleted file mode 100644 index 0cef647..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/palette.js.svn-base +++ /dev/null @@ -1,529 +0,0 @@ -// 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.EventType'); -goog.require('goog.events.KeyCodes'); -goog.require('goog.math.Size'); -goog.require('goog.ui.Component.Error'); -goog.require('goog.ui.Component.EventType'); -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.ui.Control.call(this, items, - opt_renderer || goog.ui.PaletteRenderer.getInstance(), opt_domHelper); -}; -goog.inherits(goog.ui.Palette, goog.ui.Control); - - -/** - * 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; -}; - - -/** - * Overrides {@link goog.ui.Control#setContentInternal} by also updating the - * grid size and the selection model. Considered protected. - * @param {Array.<Node>} items Array of DOM nodes to be displayed as items - * in the palette grid (one item per cell). - * @protected - */ -goog.ui.Palette.prototype.setContentInternal = function(items) { - 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 null, since palettes - * don't have text captions. - * @return {null} Always null. - */ -goog.ui.Palette.prototype.getCaption = function() { - return null; -}; - - -/** - * Overrides {@link goog.ui.Control#setCaption} to be a no-op, since palettes - * don't have text captions. - * @param {string} caption Ignored. - */ -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. - */ -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. - */ -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.getRenderer().highlightCell(this, item, false); - } -}; - - -/** - * 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. - */ -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. - */ -goog.ui.Palette.prototype.performActionInternal = function(e) { - var item = this.getHighlightedItem(); - if (item) { - this.setSelectedItem(item); - return this.dispatchEvent(goog.ui.Component.EventType.ACTION); - } - 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. - */ -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 (null if none). - */ -goog.ui.Palette.prototype.getHighlightedItem = function() { - var items = this.getContent(); - return items && items[this.highlightedIndex_]; -}; - - -/** - * 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); - } -}; - - -/** - * 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} 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) { - 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); - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/paletterenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/paletterenderer.js.svn-base deleted file mode 100644 index 6a8f029..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/paletterenderer.js.svn-base +++ /dev/null @@ -1,319 +0,0 @@ -// 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.Palette}s. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.PaletteRenderer'); - -goog.require('goog.array'); -goog.require('goog.dom'); -goog.require('goog.dom.NodeType'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.classes'); -goog.require('goog.style'); -goog.require('goog.ui.ControlRenderer'); -goog.require('goog.userAgent'); - - - -/** - * Default renderer for {@link goog.ui.Palette}s. Renders the palette as an - * HTML table wrapped in a DIV, with one palette item per cell: - * - * <div class="goog-palette"> - * <table class="goog-palette-table"> - * <tbody class="goog-palette-body"> - * <tr class="goog-palette-row"> - * <td class="goog-palette-cell">...Item 0...</td> - * <td class="goog-palette-cell">...Item 1...</td> - * ... - * </tr> - * <tr class="goog-palette-row"> - * ... - * </tr> - * </tbody> - * </table> - * </div> - * - * @constructor - * @extends {goog.ui.ControlRenderer} - */ -goog.ui.PaletteRenderer = function() { - goog.ui.ControlRenderer.call(this); -}; -goog.inherits(goog.ui.PaletteRenderer, goog.ui.ControlRenderer); -goog.addSingletonGetter(goog.ui.PaletteRenderer); - - -/** - * Globally unique ID sequence for cells rendered by this renderer class. - * @type {number} - * @private - */ -goog.ui.PaletteRenderer.cellId_ = 0; - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.PaletteRenderer.CSS_CLASS = goog.getCssName('goog-palette'); - - -/** - * Returns the palette items arranged in a table wrapped in a DIV, with the - * renderer's own CSS class and additional state-specific classes applied to - * it. - * @param {goog.ui.Palette} palette Palette to render. - * @return {Element} Root element for the palette. - */ -goog.ui.PaletteRenderer.prototype.createDom = function(palette) { - var classNames = this.getClassNames(palette); - return palette.getDomHelper().createDom( - 'div', classNames ? classNames.join(' ') : null, - this.createGrid(/** @type {Array.<Node>} */(palette.getContent()), - palette.getSize(), palette.getDomHelper())); -}; - - -/** - * Returns the given items in a table with {@code size.width} columns and - * {@code size.height} rows. If the table is too big, empty cells will be - * created as needed. If the table is too small, the items that don't fit - * will not be rendered. - * @param {Array.<Node>} items Palette items. - * @param {goog.math.Size} size Palette size (columns x rows); both dimensions - * must be specified as numbers. - * @param {goog.dom.DomHelper} dom DOM helper for document interaction. - * @return {Element} Palette table element. - */ -goog.ui.PaletteRenderer.prototype.createGrid = function(items, size, dom) { - var rows = []; - for (var row = 0, index = 0; row < size.height; row++) { - var cells = []; - for (var column = 0; column < size.width; column++) { - var item = items && items[index++]; - cells.push(this.createCell(item, dom)); - } - rows.push(this.createRow(cells, dom)); - } - - return this.createTable(rows, dom); -}; - - -/** - * Returns a table element (or equivalent) that wraps the given rows. - * @param {Array.<Element>} rows Array of row elements. - * @param {goog.dom.DomHelper} dom DOM helper for document interaction. - * @return {Element} Palette table element. - */ -goog.ui.PaletteRenderer.prototype.createTable = function(rows, dom) { - var table = dom.createDom('table', - goog.getCssName(this.getCssClass(), 'table'), - dom.createDom('tbody', goog.getCssName(this.getCssClass(), 'body'), - rows)); - table.cellSpacing = 0; - table.cellPadding = 0; - goog.dom.a11y.setRole(table, 'grid'); - return table; -}; - - -/** - * Returns a table row element (or equivalent) that wraps the given cells. - * @param {Array.<Element>} cells Array of cell elements. - * @param {goog.dom.DomHelper} dom DOM helper for document interaction. - * @return {Element} Row element. - */ -goog.ui.PaletteRenderer.prototype.createRow = function(cells, dom) { - return dom.createDom('tr', goog.getCssName(this.getCssClass(), 'row'), cells); -}; - - -/** - * Returns a table cell element (or equivalent) that wraps the given palette - * item (which must be a DOM node). - * @param {Node|string} node Palette item. - * @param {goog.dom.DomHelper} dom DOM helper for document interaction. - * @return {Element} Cell element. - */ -goog.ui.PaletteRenderer.prototype.createCell = function(node, dom) { - var cell = dom.createDom('td', { - 'class': goog.getCssName(this.getCssClass(), 'cell'), - // Cells must have an ID, for accessibility, so we generate one here. - 'id': goog.getCssName(this.getCssClass(), 'cell-') + - goog.ui.PaletteRenderer.cellId_++ - }, node); - goog.dom.a11y.setRole(cell, 'gridcell'); - return cell; -}; - - -/** - * Overrides {@link goog.ui.ControlRenderer#canDecorate} to always return false. - * @param {Element} element Ignored. - * @return {boolean} False, since palettes don't support the decorate flow (for - * now). - */ -goog.ui.PaletteRenderer.prototype.canDecorate = function(element) { - return false; -}; - - -/** - * Overrides {@link goog.ui.ControlRenderer#decorate} to be a no-op, since - * palettes don't support the decorate flow (for now). - * @param {goog.ui.Palette} palette Ignored. - * @param {Element} element Ignored. - * @return {null} Always null. - */ -goog.ui.PaletteRenderer.prototype.decorate = function(palette, element) { - return null; -}; - - -/** - * Overrides {@link goog.ui.ControlRenderer#setContent} for palettes. Locates - * the HTML table representing the palette grid, and replaces the contents of - * each cell with a new element from the array of nodes passed as the second - * argument. If the new content has too many items the table will have more - * rows added to fit, if there are less items than the table has cells, then the - * left over cells will be empty. - * @param {Element} element Root element of the palette control. - * @param {Array.<Node>} items Array of items to replace existing palette items. - */ -goog.ui.PaletteRenderer.prototype.setContent = function(element, items) { - if (element) { - var tbody = goog.dom.getElementsByTagNameAndClass( - 'tbody', goog.getCssName(this.getCssClass(), 'body'), element)[0]; - if (tbody) { - var index = 0; - goog.array.forEach(tbody.rows, function(row) { - goog.array.forEach(row.cells, function(cell) { - goog.dom.removeChildren(cell); - if (items) { - var item = items[index++]; - if (item) { - goog.dom.appendChild(cell, item); - } - } - }); - }); - - // Make space for any additional items. - if (index < items.length) { - var cells = []; - var dom = goog.dom.getDomHelper(element); - var width = tbody.rows[0].cells.length; - while (index < items.length) { - var item = items[index++]; - cells.push(this.createCell(item, dom)); - if (cells.length == width) { - var row = this.createRow(cells, dom); - goog.dom.appendChild(tbody, row); - cells.length = 0; - } - } - if (cells.length > 0) { - while (cells.length < width) { - cells.push(this.createCell('', dom)); - } - var row = this.createRow(cells, dom); - goog.dom.appendChild(tbody, row); - } - } - } - // Make sure the new contents are still unselectable. - goog.style.setUnselectable(element, true, goog.userAgent.GECKO); - } -}; - - -/** - * Returns the item corresponding to the given node, or null if the node is - * neither a palette cell nor part of a palette item. - * @param {goog.ui.Palette} palette Palette in which to look for the item. - * @param {Node} node Node to look for. - * @return {Node} The corresponding palette item (null if not found). - */ -goog.ui.PaletteRenderer.prototype.getContainingItem = function(palette, node) { - var root = palette.getElement(); - while (node && node.nodeType == goog.dom.NodeType.ELEMENT && node != root) { - if (node.tagName == 'TD' && goog.dom.classes.has( - /** @type {Element} */ (node), - goog.getCssName(this.getCssClass(), 'cell'))) { - return node.firstChild; - } - node = node.parentNode; - } - - return null; -}; - - -/** - * Updates the highlight styling of the palette cell containing the given node - * based on the value of the Boolean argument. - * @param {goog.ui.Palette} palette Palette containing the item. - * @param {Node} node Item whose cell is to be highlighted or un-highlighted. - * @param {boolean} highlight If true, the cell is highlighted; otherwise it is - * un-highlighted. - */ -goog.ui.PaletteRenderer.prototype.highlightCell = function(palette, - node, - highlight) { - if (node) { - var cell = /** @type {Element} */ (node.parentNode); - goog.dom.classes.enable(cell, - goog.getCssName(this.getCssClass(), 'cell-hover'), highlight); - // See http://www.w3.org/TR/2006/WD-aria-state-20061220/#activedescendent - // for an explanation of the activedescendent. - var table = /** @type {Element} */ (palette.getElement().firstChild); - goog.dom.a11y.setState(table, 'activedescendent', cell.id); - } -}; - - -/** - * Updates the selection styling of the palette cell containing the given node - * based on the value of the Boolean argument. - * @param {goog.ui.Palette} palette Palette containing the item. - * @param {Node} node Item whose cell is to be selected or deselected. - * @param {boolean} select If true, the cell is selected; otherwise it is - * deselected. - */ -goog.ui.PaletteRenderer.prototype.selectCell = function(palette, node, select) { - if (node) { - var cell = /** @type {Element} */ (node.parentNode); - goog.dom.classes.enable(cell, - goog.getCssName(this.getCssClass(), 'cell-selected'), - select); - } -}; - - -/** - * Returns the CSS class to be applied to the root element of components - * rendered using this renderer. - * @return {string} Renderer-specific CSS class. - */ -goog.ui.PaletteRenderer.prototype.getCssClass = function() { - return goog.ui.PaletteRenderer.CSS_CLASS; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/plaintextspellchecker.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/plaintextspellchecker.js.svn-base deleted file mode 100644 index dc73f4e..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/plaintextspellchecker.js.svn-base +++ /dev/null @@ -1,670 +0,0 @@ -// 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 Plain text spell checker implementation. - * - * @author eae@google.com (Emil A Eklund) - * @author sergeys@google.com (Sergey Solyanik) - * @see ../demos/plaintextspellchecker.html - */ - -goog.provide('goog.ui.PlainTextSpellChecker'); - -goog.require('goog.Timer'); -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -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.style'); -goog.require('goog.ui.AbstractSpellChecker'); -goog.require('goog.ui.AbstractSpellChecker.AsyncResult'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.userAgent'); - - - -/** - * Plain text spell checker implementation. - * - * @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.AbstractSpellChecker} - */ -goog.ui.PlainTextSpellChecker = function(handler, opt_domHelper) { - goog.ui.AbstractSpellChecker.call(this, handler, opt_domHelper); - - /** - * Correction UI container. - * @type {HTMLDivElement} - * @private - */ - this.overlay_ = /** @type {HTMLDivElement} */ - (this.getDomHelper().createDom('div')); - goog.style.setPreWrap(this.overlay_); - - /** - * Bound async function (to avoid rebinding it on every call). - * @type {Function} - * @private - */ - this.boundContinueAsyncFn_ = goog.bind(this.continueAsync_, this); - - /** - * Regular expression for matching line breaks. - * @type {RegExp} - * @private - */ - this.endOfLineMatcher_ = new RegExp('(.*)(\n|\r\n){0,1}', 'g'); -}; -goog.inherits(goog.ui.PlainTextSpellChecker, goog.ui.AbstractSpellChecker); - - -/** - * Class name for invalid words. - * @type {string} - */ -goog.ui.PlainTextSpellChecker.prototype.invalidWordClassName = - goog.getCssName('goog-spellcheck-invalidword'); - - -/** - * Class name for corrected words. - * @type {string} - */ -goog.ui.PlainTextSpellChecker.prototype.correctedWordClassName = - goog.getCssName('goog-spellcheck-correctedword'); - - -/** - * Class name for correction pane. - * @type {string} - */ -goog.ui.PlainTextSpellChecker.prototype.correctionPaneClassName = - goog.getCssName('goog-spellcheck-correctionpane'); - - -/** - * Number of words to scan to precharge the dictionary. - * @type {number} - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.dictionaryPreScanSize_ = 1000; - - -/** - * Size of window. Used to check if a resize operation actually changed the size - * of the window. - * @type {goog.math.Size|undefined} - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.winSize_; - - -/** - * Numeric Id of the element that has focus. 0 when not set. - * - * @type {number} - * @private - */ -goog.ui.AbstractSpellChecker.prototype.focusedElementId_ = 0; - - -/** - * Event handler for listening to events without leaking. - * @type {goog.events.EventHandler|undefined} - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.eventHandler_; - - -/** - * The object handling keyboard events. - * @type {goog.events.KeyHandler|undefined} - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.keyHandler_; - - -/** - * Creates the initial DOM representation for the component. - */ -goog.ui.PlainTextSpellChecker.prototype.createDom = function() { - this.setElementInternal(this.getDomHelper().createElement('textarea')); -}; - - -/** - * Called when the component's element is known to be in the document. - */ -goog.ui.PlainTextSpellChecker.prototype.enterDocument = function() { - goog.ui.PlainTextSpellChecker.superClass_.enterDocument.call(this); - - this.eventHandler_ = new goog.events.EventHandler(this); - this.keyHandler_ = new goog.events.KeyHandler(this.overlay_); - - this.initSuggestionsMenu(); - this.initAccessibility_(); -}; - - -/** @override */ -goog.ui.PlainTextSpellChecker.prototype.exitDocument = function() { - goog.ui.PlainTextSpellChecker.superClass_.exitDocument.call(this); - - if (this.eventHandler_) { - this.eventHandler_.dispose(); - this.eventHandler_ = undefined; - } - if (this.keyHandler_) { - this.keyHandler_.dispose(); - this.keyHandler_ = undefined; - } -}; - - -/** - * Initializes suggestions menu. Populates menu with separator and ignore option - * that are always valid. Suggestions are later added above the separator. - * - * @protected - */ -goog.ui.PlainTextSpellChecker.prototype.initSuggestionsMenu = function() { - goog.ui.PlainTextSpellChecker.superClass_.initSuggestionsMenu.call(this); - this.eventHandler_.listen(/** @type {goog.ui.PopupMenu} */ (this.menu_), - goog.ui.Component.EventType.BLUR, this.onCorrectionBlur_); -}; - - -/** - * Checks spelling for all text and displays correction UI. - */ -goog.ui.PlainTextSpellChecker.prototype.check = function() { - var text = this.getElement().value; - this.getElement().readOnly = true; - - // Prepare and position correction UI. - this.overlay_.innerHTML = ''; - this.overlay_.className = this.correctionPaneClassName; - if (this.getElement().parentNode != this.overlay_.parentNode) { - this.getElement().parentNode.appendChild(this.overlay_); - } - goog.style.showElement(this.overlay_, false); - - this.preChargeDictionary_(text); -}; - - -/** - * Final stage of spell checking - displays the correction UI. - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.finishCheck_ = function() { - // Show correction UI. - this.positionOverlay_(); - goog.style.showElement(this.getElement(), false); - goog.style.showElement(this.overlay_, true); - - var eh = this.eventHandler_; - eh.listen(this.overlay_, goog.events.EventType.CLICK, this.onWordClick_); - eh.listen(/** @type {goog.events.KeyHandler} */ (this.keyHandler_), - goog.events.KeyHandler.EventType.KEY, this.handleOverlayKeyEvent); - - // The position and size of the overlay element needs to be recalculated if - // the browser window is resized. - var win = goog.dom.getWindow(this.getDomHelper().getDocument()) || window; - this.winSize_ = goog.dom.getViewportSize(win); - eh.listen(win, goog.events.EventType.RESIZE, this.onWindowResize_); - - goog.ui.PlainTextSpellChecker.superClass_.check.call(this); -}; - - -/** - * Start the scan after the dictionary was loaded. - * - * @param {string} text text to process. - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.preChargeDictionary_ = function(text) { - this.eventHandler_.listen(this.handler_, - goog.spell.SpellCheck.EventType.READY, this.onDictionaryCharged_, true); - - this.populateDictionary(text, this.dictionaryPreScanSize_); -}; - - -/** - * Loads few initial dictionary words into the cache. - * - * @param {goog.events.Event} e goog.spell.SpellCheck.EventType.READY event. - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.onDictionaryCharged_ = function(e) { - e.stopPropagation(); - this.eventHandler_.unlisten(this.handler_, - goog.spell.SpellCheck.EventType.READY, this.onDictionaryCharged_, true); - this.checkAsync_(this.getElement().value); -}; - - -/** - * Processes the included and skips the excluded text ranges. - * @return {goog.ui.AbstractSpellChecker.AsyncResult} Whether the spell - * checking is pending or done. - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.spellCheckLoop_ = function() { - for (var i = this.textArrayIndex_; i < this.textArray_.length; ++i) { - var text = this.textArray_[i]; - if (this.textArrayProcess_[i]) { - var result = this.processTextAsync(this.overlay_, text); - if (result == goog.ui.AbstractSpellChecker.AsyncResult.PENDING) { - this.textArrayIndex_ = i + 1; - goog.Timer.callOnce(this.boundContinueAsyncFn_); - return result; - } - } else { - this.processRange(this.overlay_, text); - } - } - - this.textArray_ = []; - this.textArrayProcess_ = []; - - return goog.ui.AbstractSpellChecker.AsyncResult.DONE; -}; - - -/** - * Breaks text into included and excluded ranges using the marker RegExp - * supplied by the caller. - * - * @param {string} text text to process. - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.initTextArray_ = function(text) { - if (!this.excludeMarker) { - this.textArray_ = [text]; - this.textArrayProcess_ = [true]; - return; - } - - this.textArray_ = []; - this.textArrayProcess_ = []; - this.excludeMarker.lastIndex = 0; - var stringSegmentStart = 0; - var result; - while (result = this.excludeMarker.exec(text)) { - if (result[0].length == 0) { - break; - } - var excludedRange = result[0]; - var includedRange = text.substr(stringSegmentStart, result.index - - stringSegmentStart); - if (includedRange) { - this.textArray_.push(includedRange); - this.textArrayProcess_.push(true); - } - this.textArray_.push(excludedRange); - this.textArrayProcess_.push(false); - stringSegmentStart = this.excludeMarker.lastIndex; - } - - var leftoverText = text.substr(stringSegmentStart); - if (leftoverText) { - this.textArray_.push(leftoverText); - this.textArrayProcess_.push(true); - } -}; - - -/** - * Starts asynchrnonous spell checking. - * - * @param {string} text text to process. - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.checkAsync_ = function(text) { - this.initializeAsyncMode(); - this.initTextArray_(text); - this.textArrayIndex_ = 0; - if (this.spellCheckLoop_() == - goog.ui.AbstractSpellChecker.AsyncResult.PENDING) { - return; - } - this.finishAsyncProcessing(); - this.finishCheck_(); -}; - - -/** - * Continues asynchrnonous spell checking. - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.continueAsync_ = function() { - // First finish with the current segment. - var result = this.continueAsyncProcessing(); - if (result == goog.ui.AbstractSpellChecker.AsyncResult.PENDING) { - goog.Timer.callOnce(this.boundContinueAsyncFn_); - return; - } - if (this.spellCheckLoop_() == - goog.ui.AbstractSpellChecker.AsyncResult.PENDING) { - return; - } - this.finishAsyncProcessing(); - this.finishCheck_(); -}; - - -/** - * Processes word. - * - * @param {Node} node Node containing word. - * @param {string} word Word to process. - * @param {goog.spell.SpellCheck.WordStatus} status Status of word. - * @protected - */ -goog.ui.PlainTextSpellChecker.prototype.processWord = function(node, word, - status) { - node.appendChild(this.createWordElement_(word, status)); -}; - - -/** - * Processes range of text - recognized words and separators. - * - * @param {Node} node Node containing separator. - * @param {string} text text to process. - * @protected - */ -goog.ui.PlainTextSpellChecker.prototype.processRange = function(node, text) { - this.endOfLineMatcher_.lastIndex = 0; - var result; - while (result = this.endOfLineMatcher_.exec(text)) { - if (result[0].length == 0) { - break; - } - node.appendChild(this.getDomHelper().createTextNode(result[1])); - if (result[2]) { - node.appendChild(this.getDomHelper().createElement('br')); - } - } -}; - - -/** - * Hides correction UI. - */ -goog.ui.PlainTextSpellChecker.prototype.resume = function() { - var wasVisible = this.isVisible_; - - goog.ui.PlainTextSpellChecker.superClass_.resume.call(this); - - goog.style.showElement(this.overlay_, false); - goog.style.showElement(this.getElement(), true); - this.getElement().readOnly = false; - - if (wasVisible) { - this.getElement().value = goog.dom.getRawTextContent(this.overlay_); - this.overlay_.innerHTML = ''; - - var eh = this.eventHandler_; - eh.unlisten(this.overlay_, goog.events.EventType.CLICK, this.onWordClick_); - eh.unlisten(/** @type {goog.events.KeyHandler} */ (this.keyHandler_), - goog.events.KeyHandler.EventType.KEY, this.handleOverlayKeyEvent); - - var win = goog.dom.getWindow(this.getDomHelper().getDocument()) || window; - eh.unlisten(win, goog.events.EventType.RESIZE, this.onWindowResize_); - } -}; - - -/** - * Returns desired element properties for the specified status. - * - * @param {goog.spell.SpellCheck.WordStatus} status Status of word. - * @return {Object} Properties to apply to word element. - * @protected - */ -goog.ui.PlainTextSpellChecker.prototype.getElementProperties = - function(status) { - if (status == goog.spell.SpellCheck.WordStatus.INVALID) { - return {'class': this.invalidWordClassName}; - } else if (status == goog.spell.SpellCheck.WordStatus.CORRECTED) { - return {'class': this.correctedWordClassName}; - } - return {'class': ''}; -}; - - -/** - * Handles the click events. - * - * @param {goog.events.BrowserEvent} event Event object. - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.onWordClick_ = function(event) { - if (event.target.className == this.invalidWordClassName || - event.target.className == this.correctedWordClassName) { - this.showSuggestionsMenu(/** @type {Element} */ (event.target), event); - - // Prevent document click handler from closing the menu. - event.stopPropagation(); - } -}; - - -/** - * Handles window resize events. - * - * @param {goog.events.BrowserEvent} event Event object. - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.onWindowResize_ = function(event) { - var win = goog.dom.getWindow(this.getDomHelper().getDocument()) || window; - var size = goog.dom.getViewportSize(win); - - if (size.width != this.winSize_.width || - size.height != this.winSize_.height) { - goog.style.showElement(this.overlay_, false); - goog.style.showElement(this.getElement(), true); - - // IE requires a slight delay, allowing the resize operation to take effect. - if (goog.userAgent.IE) { - goog.Timer.callOnce(this.resizeOverlay_, 100, this); - } else { - this.resizeOverlay_(); - } - this.winSize_ = size; - } -}; - - -/** - * Resizes overlay to match the size of the bound element then displays the - * overlay. Helper for {@link #onWindowResize_}. - * - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.resizeOverlay_ = function() { - this.positionOverlay_(); - goog.style.showElement(this.getElement(), false); - goog.style.showElement(this.overlay_, true); -}; - - -/** - * Updates the position and size of the overlay to match the original element. - * - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.positionOverlay_ = function() { - goog.style.setPosition( - this.overlay_, goog.style.getPosition(this.getElement())); - goog.style.setSize(this.overlay_, goog.style.getSize(this.getElement())); -}; - - -/** @override */ -goog.ui.PlainTextSpellChecker.prototype.disposeInternal = function() { - this.getDomHelper().removeNode(this.overlay_); - delete this.overlay_; - delete this.boundContinueAsyncFn_; - delete this.endOfLineMatcher_; - goog.ui.PlainTextSpellChecker.superClass_.disposeInternal.call(this); -}; - - -/** - * Specify ARIA roles and states as appropriate. - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.initAccessibility_ = function() { - goog.dom.a11y.setRole(this.overlay_, 'region'); - goog.dom.a11y.setState(this.overlay_, 'live', 'assertive'); - this.overlay_.tabIndex = 0; - - /** @desc Title for Spell Checker's overlay.*/ - var MSG_SPELLCHECKER_OVERLAY_TITLE = goog.getMsg('Spell Checker'); - this.overlay_.title = MSG_SPELLCHECKER_OVERLAY_TITLE; -}; - - -/** - * Handles key down for overlay. - * @param {goog.events.BrowserEvent} e The browser event. - * @return {boolean|undefined} The handled value. - */ -goog.ui.PlainTextSpellChecker.prototype.handleOverlayKeyEvent = function(e) { - var handled = false; - switch (e.keyCode) { - case goog.events.KeyCodes.RIGHT: - if (e.ctrlKey) { - handled = this.navigate_(goog.ui.AbstractSpellChecker.Direction.NEXT); - } - break; - - case goog.events.KeyCodes.LEFT: - if (e.ctrlKey) { - handled = this.navigate_( - goog.ui.AbstractSpellChecker.Direction.PREVIOUS); - } - break; - - case goog.events.KeyCodes.DOWN: - if (this.focusedElementId_) { - var el = this.getDomHelper().getElement(this.makeElementId( - this.focusedElementId_)); - if (el) { - var position = goog.style.getPosition(el); - var size = goog.style.getSize(el); - position.x += size.width / 2; - position.y += size.height / 2; - this.showSuggestionsMenu(el, position); - handled = undefined; - } - } - break; - } - - if (handled) { - e.preventDefault(); - } - - return handled; -}; - - -/** - * Navigate keyboard focus in the given direction. - * - * @param {goog.ui.AbstractSpellChecker.Direction} direction The direction to - * navigate in. - * @return {boolean} Whether the action is handled here. If not handled - * here, the initiating event may be propagated. - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.navigate_ = function(direction) { - var handled = false; - var previous = direction == goog.ui.AbstractSpellChecker.Direction.PREVIOUS; - var lastId = goog.ui.AbstractSpellChecker.nextId_; - var focusedId = this.focusedElementId_; - - var el; - do { - focusedId += previous ? -1 : 1; - if (focusedId < 1 || focusedId > lastId) { - focusedId = 0; - break; - } - } while (!(el = this.getElementById(focusedId))); - - if (el) { - el.focus(); - this.focusedElementId_ = focusedId; - handled = true; - } - - return handled; -}; - - -/** - * Handles correction menu actions. - * - * @param {goog.events.Event} event Action event. - * @protected - */ -goog.ui.PlainTextSpellChecker.prototype.onCorrectionAction = function(event) { - goog.ui.PlainTextSpellChecker.superClass_.onCorrectionAction.call(this, - event); - - // In case of editWord base class has already set the focus (on the input), - // otherwise set the focus back on the word. - if (event.target != this.menuEdit_) { - this.reFocus_(); - } -}; - - -/** - * Handles blur on the menu. - * @param {goog.events.BrowserEvent} event Blur event. - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.onCorrectionBlur_ = function(event) { - this.reFocus_(); -}; - - -/** - * Sets the focus back on the previously focused word element. - * @private - */ -goog.ui.PlainTextSpellChecker.prototype.reFocus_ = function() { - var el = this.getElementById(this.focusedElementId_); - if (el) { - el.focus(); - } else { - this.overlay_.focus(); - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/plaintextspellchecker_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/plaintextspellchecker_test.html.svn-base deleted file mode 100644 index 8272816..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/plaintextspellchecker_test.html.svn-base +++ /dev/null @@ -1,240 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2007 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<!-- -This test has not yet been updated to run on IE8. See http://b/hotlist?id=36311 ---> -<!--meta http-equiv="X-UA-Compatible" content="IE=edge"--> -<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"> -<title>Closure Unit Tests - goog.ui.PlainTextSpellChecker</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.string.StringBuffer'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.PlainTextSpellChecker'); -</script> -</head> -<body> - -<textarea id="test1" style="width: 50ex; height: 15em;"></textarea> -<textarea id="test2" style="width: 50ex; height: 15em;"></textarea> -<textarea id="test3" style="width: 50ex; height: 15em;"></textarea> - -<script> - -var missspelling = 'missspelling'; -var iggnore = 'iggnore'; -var vocabulary = ['test', 'words', 'a', 'few', missspelling, iggnore]; - -// We don't use Math.random() to make test predictable. Math.random is not -// repeatable, so a success on the dev machine != success in the lab (or on -// other dev machines). This is the same pseudorandom logic that CRT rand() -// uses. -var rseed = 1; -function random(range) { - rseed = (rseed * 1103515245 + 12345) & 0xffffffff; - return ((rseed >> 16) & 0x7fff) % range; -}; - -function localSpellCheckingFunction(words, spellChecker, callback) { - var len = words.length; - var results = []; - for (var i = 0; i < len; i++) { - var word = words[i]; - var found = false; - // Last two words are considered misspellings - for (var j = 0 ; j < vocabulary.length - 2 ; ++j) { - if (vocabulary[j] == word) { - found = true; - break; - } - } - if (found) { - results.push([word, goog.spell.SpellCheck.WordStatus.VALID]); - } else { - results.push([word, goog.spell.SpellCheck.WordStatus.INVALID, - ['foo','bar']]); - } - } - callback.call(spellChecker, results); -}; - -function generateRandomSpace() { - var string = ''; - var nSpace = 1 + random(4); - for (var i = 0; i < nSpace ; ++i) { - string += ' '; - } - return string; -}; - -function generateRandomString(maxWords, doQuotes) { - var x = random(10); - var string = ''; - if (doQuotes) { - if (x == 0) { - string = 'On xxxxx yyyy wrote:\n> '; - } else if (x < 3) { - string = '> '; - } - } - - var nWords = 1 + random(maxWords); - for (var i = 0; i < nWords ; ++i) { - string += vocabulary[random(vocabulary.length)]; - string += generateRandomSpace(); - } - return string; -}; - -var timerQueue = []; -function processTimerQueue() { - while (timerQueue.length > 0) { - var fn = timerQueue.shift(); - fn(); - } -}; - -function localTimer(fn, delay, obj) { - if (obj) { - fn = goog.bind(fn, obj); - } - timerQueue.push(fn); - return timerQueue.length; -}; - -function testPlainTextSpellCheckerNoQuotes() { - var handler = new goog.spell.SpellCheck(localSpellCheckingFunction); - var s = new goog.ui.PlainTextSpellChecker(handler); - s.asyncWordsPerBatch_ = 100; - var el = document.getElementById('test1'); - s.decorate(el); - var text = ''; - for (var i = 0 ; i < 10 ; ++i) { - text += generateRandomString(10, false) + '\n'; - } - el.value = text; - // Yes this looks bizzare. This is for '\n' processing. - // They get converted to CRLF as part of the above statement. - text = el.value; - - var timerSav = goog.Timer.callOnce; - goog.Timer.callOnce = localTimer; - - s.check(); - processTimerQueue(); - s.ignoreWord(iggnore); - processTimerQueue(); - s.check(); - processTimerQueue(); - s.resume(); - processTimerQueue(); - - goog.Timer.callOnce = timerSav; - - assertEquals('Spell checker run should not change the underlying element.', - text, el.value); - s.dispose(); -}; - -function testPlainTextSpellCheckerWithQuotes() { - var handler = new goog.spell.SpellCheck(localSpellCheckingFunction); - var s = new goog.ui.PlainTextSpellChecker(handler); - s.asyncWordsPerBatch_ = 100; - var el = document.getElementById('test2'); - s.decorate(el); - var text = ''; - for (var i = 0 ; i < 10; ++i) { - text += generateRandomString(10, true) + '\n'; - } - el.value = text; - // Yes this looks bizzare. This is for '\n' processing. - // They get converted to CRLF as part of the above statement. - text = el.value; - - var timerSav = goog.Timer.callOnce; - goog.Timer.callOnce = localTimer; - - s.setExcludeMarker(new RegExp('\nOn .* wrote:\n(> .*\n)+|\n(> .*\n)', 'g')); - s.check(); - processTimerQueue(); - s.ignoreWord(iggnore); - processTimerQueue(); - s.check(); - processTimerQueue(); - s.resume(); - processTimerQueue(); - - goog.Timer.callOnce = timerSav; - - assertEquals('Spell checker run should not change the underlying element.', - text, el.value); - s.dispose(); -}; - -function testPlainTextSpellCheckerWordReplacement() { - var handler = new goog.spell.SpellCheck(localSpellCheckingFunction); - var s = new goog.ui.PlainTextSpellChecker(handler); - s.asyncWordsPerBatch_ = 100; - var el = document.getElementById('test3'); - s.decorate(el); - var text = ''; - for (var i = 0 ; i < 10 ; ++i) { - text += generateRandomString(10, false) + '\n'; - } - el.value = text; - - var timerSav = goog.Timer.callOnce; - goog.Timer.callOnce = localTimer; - - s.check(); - processTimerQueue(); - - var container = s.overlay_; - var wordEl = container.firstChild; - while (wordEl) { - if (goog.dom.getTextContent(wordEl) == missspelling) { - break; - } - wordEl = wordEl.nextSibling; - } - - if (!wordEl) { - assertTrue('Cannot find the world that should have been here.' - + 'Please revise the test', false); - return; - } - - s.activeWord_ = missspelling; - s.activeElement_ = wordEl; - var suggestions = s.getSuggestions_(); - s.replaceWord(wordEl, missspelling, 'foo'); - assertEquals('Should have set the original word attribute!', - wordEl.getAttribute(goog.ui.AbstractSpellChecker.ORIGINAL_), - missspelling); - - s.activeWord_ = goog.dom.getTextContent(wordEl); - s.activeElement_ = wordEl; - var newSuggestions = s.getSuggestions_(); - assertEquals('Suggestion list should still be present even if the word ' - + 'is now correct!', suggestions, newSuggestions); - - s.resume(); - processTimerQueue(); - - goog.Timer.callOnce = timerSav; - s.dispose(); -}; - - - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popup.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popup.js.svn-base deleted file mode 100644 index addd66a..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popup.js.svn-base +++ /dev/null @@ -1,410 +0,0 @@ -// 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 Popup class. - * - * @see ../demos/popup.html - */ - -goog.provide('goog.ui.Popup'); -goog.provide('goog.ui.Popup.AbsolutePosition'); -goog.provide('goog.ui.Popup.AnchoredPosition'); -goog.provide('goog.ui.Popup.AnchoredViewPortPosition'); -goog.provide('goog.ui.Popup.ClientPosition'); -goog.provide('goog.ui.Popup.Corner'); -goog.provide('goog.ui.Popup.Overflow'); -goog.provide('goog.ui.Popup.ViewPortClientPosition'); -goog.provide('goog.ui.Popup.ViewPortPosition'); - -goog.require('goog.math.Box'); -goog.require('goog.positioning'); -goog.require('goog.positioning.AbsolutePosition'); -goog.require('goog.positioning.AnchoredPosition'); -goog.require('goog.positioning.AnchoredViewportPosition'); -goog.require('goog.positioning.ClientPosition'); -goog.require('goog.positioning.Corner'); -goog.require('goog.positioning.Overflow'); -goog.require('goog.positioning.OverflowStatus'); -goog.require('goog.positioning.ViewportClientPosition'); -goog.require('goog.positioning.ViewportPosition'); -goog.require('goog.style'); -goog.require('goog.ui.PopupBase'); - - - -/** - * The Popup class provides functionality for displaying an absolutely - * positioned element at a particular location in the window. It's designed to - * be used as the foundation for building controls like a menu or tooltip. The - * Popup class includes functionality for displaying a Popup near adjacent to - * an anchor element. - * - * This works cross browser and thus does not use IE's createPopup feature - * which supports extending outside the edge of the brower window. - * - * @param {Element=} opt_element A DOM element for the popup. - * @param {goog.positioning.AbstractPosition=} opt_position A positioning helper - * object. - * @constructor - * @extends {goog.ui.PopupBase} - */ -goog.ui.Popup = function(opt_element, opt_position) { - /** - * Corner of the popup to used in the positioning algorithm. - * - * @type {goog.positioning.Corner} - * @private - */ - this.popupCorner_ = goog.positioning.Corner.TOP_START; - - /** - * Positioning helper object. - * - * @type {goog.positioning.AbstractPosition|undefined} - * @protected - * @suppress {underscore} - */ - this.position_ = opt_position || undefined; - goog.ui.PopupBase.call(this, opt_element); -}; -goog.inherits(goog.ui.Popup, goog.ui.PopupBase); - - -/** - * Enum for representing an element corner for positioning the popup. - * - * @enum {number} - * - * @deprecated Use {@link goog.positioning.Corner} instead, this alias will be - * removed at the end of Q1 2009. - */ -goog.ui.Popup.Corner = goog.positioning.Corner; - - -/** - * Enum for representing position handling in cases where the element would be - * positioned outside the viewport. - * - * @enum {number} - * - * @deprecated Use {@link goog.positioning.Overflow} instead, this alias will be - * removed at the end of Q1 2009. - */ -goog.ui.Popup.Overflow = goog.positioning.Overflow; - - -/** - * Margin for the popup used in positioning algorithms. - * - * @type {goog.math.Box|undefined} - * @private - */ -goog.ui.Popup.prototype.margin_; - - -/** - * Returns the corner of the popup to used in the positioning algorithm. - * - * @return {goog.positioning.Corner} The popup corner used for positioning. - */ -goog.ui.Popup.prototype.getPinnedCorner = function() { - return this.popupCorner_; -}; - - -/** - * Sets the corner of the popup to used in the positioning algorithm. - * - * @param {goog.positioning.Corner} corner The popup corner used for - * positioning. - */ -goog.ui.Popup.prototype.setPinnedCorner = function(corner) { - this.popupCorner_ = corner; - if (this.isVisible()) { - this.reposition(); - } -}; - - -/** - * @return {goog.positioning.AbstractPosition} The position helper object - * associated with the popup. - */ -goog.ui.Popup.prototype.getPosition = function() { - return this.position_ || null; -}; - - -/** - * Sets the position helper object associated with the popup. - * - * @param {goog.positioning.AbstractPosition} position A position helper object. - */ -goog.ui.Popup.prototype.setPosition = function(position) { - this.position_ = position || undefined; - if (this.isVisible()) { - this.reposition(); - } -}; - - -/** - * Returns the margin to place around the popup. - * - * @return {goog.math.Box?} The margin. - */ -goog.ui.Popup.prototype.getMargin = function() { - return this.margin_ || null; -}; - - -/** - * Sets the margin to place around the popup. - * - * @param {goog.math.Box|number|null} arg1 Top value or Box. - * @param {number=} opt_arg2 Right value. - * @param {number=} opt_arg3 Bottom value. - * @param {number=} opt_arg4 Left value. - */ -goog.ui.Popup.prototype.setMargin = function(arg1, opt_arg2, opt_arg3, - opt_arg4) { - if (arg1 == null || arg1 instanceof goog.math.Box) { - this.margin_ = arg1; - } else { - this.margin_ = new goog.math.Box(arg1, - /** @type {number} */ (opt_arg2), - /** @type {number} */ (opt_arg3), - /** @type {number} */ (opt_arg4)); - } - if (this.isVisible()) { - this.reposition(); - } -}; - - -/** - * Repositions the popup according to the current state. - */ -goog.ui.Popup.prototype.reposition = function() { - if (!this.position_) { - return; - } - - var hideForPositioning = !this.isVisible() && - this.getType() != goog.ui.PopupBase.Type.MOVE_OFFSCREEN; - var el = this.getElement(); - if (hideForPositioning) { - el.style.visibility = 'hidden'; - goog.style.showElement(el, true); - } - - this.position_.reposition(el, this.popupCorner_, this.margin_); - - if (hideForPositioning) { - // NOTE(eae): The visibility property is reset to 'visible' by the show_ - // method in PopupBase. Resetting it here causes flickering in some - // situations, even if set to visible after the display property has been - // set to none by the call below. - goog.style.showElement(el, false); - } -}; - - -/** - * Positions a movable element relative to an anchorElement. The caller - * specifies the corners that should touch. This functions then moves the - * movable element accordingly. - * - * @param {Element} anchorElement The DOM element that is the anchor for where - * the movable element should position itself. - * @param {goog.positioning.Corner} anchorElementCorner The corner of the - * anchorElement for positioning the movable element. - * @param {Element} movableElement The DOM element to move. - * @param {goog.positioning.Corner} movableElementCorner The corner of the - * movableElement that that should be positioned adjacent to the - * anchorElement. - * @param {goog.math.Coordinate?=} opt_offset An offset specified in pixels. - * After the normal positioning algorithm is applied, the offset is then - * applied. Positive coordinates move the popup closer to the center of the - * anchor element. Negative coordinates move the popup away from the center - * of the anchor element. - * @param {goog.math.Box?=} opt_margin A margin specified in pixels. - * After the normal positioning algorithm is applied and any offset, the - * margin is then applied. Positive coordinates move the popup away from the - * spot it was positioned towards its center. Negative coordiates move it - * towards the spot it was positioned away from its center. - * @param {number=} opt_overflow Overflow handling mode. Defaults - * to goog.ui.Popup.Overflow.IGNORE if not specified. Bitmap. - * @return {boolean} Returns true if the element was positioned or false if - * opt_overflow was set to FAIL and the element wouldn't fit inside the - * viewport. - * - * @deprecated Use {@link goog.positioning.positionAtAnchor} instead, this alias - * will be removed at the end of Q1 2009. - */ -goog.ui.Popup.positionPopup = function(anchorElement, anchorElementCorner, - movableElement, movableElementCorner, - opt_offset, opt_margin, opt_overflow) { - return (goog.positioning.positionAtAnchor(anchorElement, anchorElementCorner, - movableElement, movableElementCorner, opt_offset, opt_margin, - opt_overflow) & goog.positioning.OverflowStatus.FAILED) == 0; -}; - - -/** - * Positions the specified corner of the movable element at the - * specified coordinate. - * - * @param {goog.math.Coordinate} absolutePos The coordinate to position the - * element at. - * @param {Element} movableElement The element to be positioned. - * @param {goog.positioning.Corner} movableElementCorner The corner of the - * movableElement that that should be positioned. - * @param {goog.math.Box=} opt_margin A margin specified in pixels. - * @return {boolean} Always returns true. - * - * @deprecated Use {@link goog.positioning.positionAtCoordinate} instead, this - * alias will be removed at the end of Q1 2009. - */ -goog.ui.Popup.positionAtCoordinate = function(absolutePos, movableElement, - movableElementCorner, - opt_margin) { - goog.positioning.positionAtCoordinate(absolutePos, movableElement, - movableElementCorner, opt_margin); - return true; -}; - - - -/** - * Encapsulates a popup position where the popup is anchored at a corner of - * an element. - * - * When using AnchoredPosition, it is recommended that the popup element - * specified in the Popup constructor or Popup.setElement be absolutely - * positioned. - * - * @param {Element} element The element to anchor the popup at. - * @param {goog.positioning.Corner} corner The corner of the element to anchor - * the popup at. - * @constructor - * @extends {goog.positioning.AbstractPosition} - * - * @deprecated Use {@link goog.positioning.AnchoredPosition} instead, this - * alias will be removed at the end of Q1 2009. - */ -goog.ui.Popup.AnchoredPosition = goog.positioning.AnchoredPosition; - - - -/** - * Encapsulates a popup position where the popup is anchored at a corner of - * an element. The corners are swapped if dictated by the viewport. For instance - * if a popup is anchored with its top left corner to the bottom left corner of - * the anchor the popup is either displayed below the anchor (as specified) or - * above it if there's not enough room to display it below. - * - * When using AnchoredPosition, it is recommended that the popup element - * specified in the Popup constructor or Popup.setElement be absolutely - * positioned. - * - * @param {Element} element The element to anchor the popup at. - * @param {goog.positioning.Corner} corner The corner of the element to anchor - * the popup at. - * @param {boolean=} opt_adjust Whether the positioning should be adjusted until - * the element fits inside the viewport even if that means that the anchored - * corners are ignored. - * @constructor - * @extends {goog.ui.Popup.AnchoredPosition} - * - * @deprecated Use {@link goog.positioning.AnchoredViewportPosition} instead, - * this alias will be removed at the end of Q1 2009. - */ -goog.ui.Popup.AnchoredViewPortPosition = - goog.positioning.AnchoredViewportPosition; - - - -/** - * Encapsulates a popup position where the popup absolutely positioned by - * setting the left/top style elements directly to the specified values. - * The position is generally relative to the element's offsetParent. Normally, - * this is the document body, but can be another element if the popup element - * is scoped by an element with relative position. - * - * @param {number|!goog.math.Coordinate} arg1 Left position or coordinate. - * @param {number=} opt_arg2 Top position. - * @constructor - * @extends {goog.positioning.AbstractPosition} - * - * @deprecated Use {@link goog.positioning.AbsolutePosition} instead, this alias - * will be removed at the end of Q1 2009. - */ -goog.ui.Popup.AbsolutePosition = goog.positioning.AbsolutePosition; - - - -/** - * Encapsulates a popup position where the popup is positioned according to - * coordinates relative to the element's view port (page). This calculates the - * correct position to use even if the element is relatively positioned to some - * other element. - * - * @param {number|!goog.math.Coordinate} arg1 Left position or coordinate. - * @param {number=} opt_arg2 Top position. - * @constructor - * @extends {goog.ui.Popup.AbsolutePosition} - * - * @deprecated Use {@link goog.positioning.ViewPortPosition} instead, this alias - * will be removed at the end of Q1 2009. - */ -goog.ui.Popup.ViewPortPosition = goog.positioning.ViewportPosition; - - - -/** - * Encapsulates a popup position where the popup is positioned relative to the - * window (client) coordinates. This calculates the correct position to - * use even if the element is relatively positioned to some other element. This - * is for trying to position an element at the spot of the mouse cursor in - * a MOUSEMOVE event. Just use the event.clientX and event.clientY as the - * parameters. - * - * @param {number|!goog.math.Coordinate} arg1 Left position or coordinate. - * @param {number=} opt_arg2 Top position. - * @constructor - * @extends {goog.ui.Popup.AbsolutePosition} - * - * @deprecated Use {@link goog.positioning.ClientPosition} instead, this alias - * will be removed at the end of Q1 2009. - */ -goog.ui.Popup.ClientPosition = goog.positioning.ClientPosition; - - - -/** - * Encapsulates a popup position where the popup is positioned relative to the - * window (client) coordinates, and made to stay within the viewport. - * - * @param {number|!goog.math.Coordinate} arg1 Left position or coordinate. - * @param {number=} opt_arg2 Top position if arg1 is a number representing the - * left position, ignored otherwise. - * @constructor - * @extends {goog.ui.Popup.ClientPosition} - * - * @deprecated Use {@link goog.positioning.ViewPortClientPosition} instead, this - * alias will be removed at the end of Q1 2009. - */ -goog.ui.Popup.ViewPortClientPosition = goog.positioning.ViewportClientPosition; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popup_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popup_test.html.svn-base deleted file mode 100644 index 83c2d83..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popup_test.html.svn-base +++ /dev/null @@ -1,137 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.Popup</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.math.Box'); - goog.require('goog.math.Coordinate'); - goog.require('goog.positioning'); - goog.require('goog.positioning.Corner'); - goog.require('goog.positioning.AnchoredPosition'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Popup'); -</script> -<style> -#popup { - position: absolute; -} -#anchor { - margin-left: 100px; -} -</style> -</head> -<body> - <span id="anchor">anchor</span> - <div id="popup"> - Popup. - </div> -<script> - -/** - * This is used to round pixel values on FF3 Mac. - */ -function assertRoundedEquals(a, b, c) { - function round(x) { - return goog.userAgent.GECKO && (goog.userAgent.MAC || goog.userAgent.X11) && - goog.userAgent.isVersion('1.9') ? Math.round(x) : x; - } - if (arguments.length == 3) { - assertEquals(a, round(b), round(c)); - } else { - assertEquals(round(a), round(b)); - } -} - -function testCreateAndReposition() { - var anchorEl = document.getElementById('anchor'); - var popupEl = document.getElementById('popup'); - var corner = goog.positioning.Corner; - - var pos = new goog.positioning.AnchoredPosition(anchorEl, - corner.BOTTOM_START); - var popup = new goog.ui.Popup(popupEl, pos); - popup.setVisible(true); - - var anchorRect = goog.style.getBounds(anchorEl); - var popupRect = goog.style.getBounds(popupEl); - assertRoundedEquals('Left edge of popup should line up with left edge ' + - 'of anchor.', - anchorRect.left, - popupRect.left); - assertRoundedEquals('Popup should be positioned just below the anchor.', - anchorRect.top + anchorRect.height, - popupRect.top); - - // Reposition. - anchorEl.style.marginTop = '7px'; - popup.reposition(); - - anchorRect = goog.style.getBounds(anchorEl); - popupRect = goog.style.getBounds(popupEl); - assertRoundedEquals('Popup should be positioned just below the anchor.', - anchorRect.top + anchorRect.height, - popupRect.top); -} - - -function testSetPinnedCorner() { - var anchorEl = document.getElementById('anchor'); - var popupEl = document.getElementById('popup'); - var corner = goog.positioning.Corner; - - var pos = new goog.positioning.AnchoredPosition(anchorEl, - corner.BOTTOM_START); - var popup = new goog.ui.Popup(popupEl, pos); - popup.setVisible(true); - - var anchorRect = goog.style.getBounds(anchorEl); - var popupRect = goog.style.getBounds(popupEl); - assertRoundedEquals('Left edge of popup should line up with left edge ' + - 'of anchor.', - anchorRect.left, - popupRect.left); - assertRoundedEquals('Popup should be positioned just below the anchor.', - anchorRect.top + anchorRect.height, - popupRect.top); - - // Change pinned corner. - popup.setPinnedCorner(corner.BOTTOM_END); - - anchorRect = goog.style.getBounds(anchorEl); - popupRect = goog.style.getBounds(popupEl); - assertRoundedEquals('Right edge of popup should line up with left edge ' + - 'of anchor.', - anchorRect.left, - popupRect.left + popupRect.width); - assertRoundedEquals('Bottom edge of popup should line up with bottom ' + - 'of anchor.', - anchorRect.top + anchorRect.height, - popupRect.top + popupRect.height); - - // Position outside the viewport. - anchorEl.style.marginLeft = '0'; - popup.reposition(); - - anchorRect = goog.style.getBounds(anchorEl); - popupRect = goog.style.getBounds(popupEl); - - assertRoundedEquals('Right edge of popup should line up with left edge ' + - 'of anchor.', - anchorRect.left, - popupRect.left + popupRect.width); - - anchorEl.style.marginLeft = ''; -} - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupbase.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupbase.js.svn-base deleted file mode 100644 index 7187f7b..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupbase.js.svn-base +++ /dev/null @@ -1,801 +0,0 @@ -// 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. - * - * @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(); - } - - // 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_(); - } - this.isVisible_ = false; - - // 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.showElement(this.element_, true); -}; - - -/** - * Hides the popup element. - * @private - */ -goog.ui.PopupBase.prototype.hidePopupElement_ = function() { - this.element_.style.visibility = 'hidden'; - goog.style.showElement(this.element_, false); -}; - - -/** - * Hides the popup by moving it offscreen. - * - * @private - */ -goog.ui.PopupBase.prototype.moveOffscreen_ = function() { - this.element_.style.left = '-200px'; - this.element_.style.top = '-200px'; -}; - - -/** - * 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. - * @private - */ -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.lastHideTime_ = goog.now(); - 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_; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupbase_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupbase_test.html.svn-base deleted file mode 100644 index 8d19668..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupbase_test.html.svn-base +++ /dev/null @@ -1,269 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - Author: gboyer@google.com (Garrett Boyer) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.PopupBase</title> -<script src="../base.js"></script> -<script> - goog.require('goog.events.EventTarget'); - goog.require('goog.events.EventType'); - goog.require('goog.fx.Transition'); - goog.require('goog.fx.Transition.EventType'); - goog.require('goog.ui.Popup'); - goog.require('goog.testing.MockClock'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); -</script> -</head> -<body> - -<div id="commonAncestor"> - <div id="targetDiv"> - Mouse and key target - </div> - - <div id="popupDiv" style="visibility:hidden"> - Popup Contents Here. - </div> -</div> - -<script> - -var targetDiv = goog.dom.getElement('targetDiv'); -var popupDiv = goog.dom.getElement('popupDiv'); -var clock; -var popup; - -function setUp() { - popup = new goog.ui.PopupBase(popupDiv); - clock = new goog.testing.MockClock(true); -} - -function tearDown() { - popup.dispose(); - clock.uninstall(); -} - -function testSetVisible() { - popup.setVisible(true); - assertEquals('visible', popupDiv.style.visibility); - assertEquals('', popupDiv.style.display); - popup.setVisible(false); - assertEquals('hidden', popupDiv.style.visibility); - assertEquals('none', popupDiv.style.display); -} - -function testEscapeDismissal() { - popup.setHideOnEscape(true); - assertTrue('Sanity check that getHideOnEscape is true when set to true.', - popup.getHideOnEscape()); - popup.setVisible(true); - assertFalse('Escape key should be cancelled', - goog.testing.events.fireKeySequence( - targetDiv, goog.events.KeyCodes.ESC)); - assertFalse(popup.isVisible()); -} - -function testEscapeDismissalCanBeDisabled() { - popup.setHideOnEscape(false); - popup.setVisible(true); - assertTrue('Escape key should be cancelled', - goog.testing.events.fireKeySequence( - targetDiv, goog.events.KeyCodes.ESC)); - assertTrue(popup.isVisible()); -} - -function testEscapeDismissalIsDisabledByDefault() { - assertFalse(popup.getHideOnEscape()); -} - -function testEscapeDismissalDoesNotRecognizeOtherKeys() { - popup.setHideOnEscape(true); - popup.setVisible(true); - var eventsPropagated = 0; - goog.events.listenOnce(goog.dom.getElement('commonAncestor'), - [goog.events.EventType.KEYDOWN, - goog.events.EventType.KEYUP, - goog.events.EventType.KEYPRESS], - function() { - ++eventsPropagated; - }); - assertTrue('Popup should remain visible', popup.isVisible()); - assertTrue('The key event default action should not be prevented', - goog.testing.events.fireKeySequence( - targetDiv, goog.events.KeyCodes.A)); - assertEquals('Keydown, keyup, and keypress should have all propagated', - 3, eventsPropagated); -} - -function testEscapeDismissalCanBeCancelledByBeforeHideEvent() { - popup.setHideOnEscape(true); - popup.setVisible(true); - var eventsPropagated = 0; - goog.events.listenOnce(goog.dom.getElement('commonAncestor'), - goog.events.EventType.KEYDOWN, - function() { - ++eventsPropagated; - }); - // Make a listener so that we stop hiding with an event handler. - goog.events.listenOnce(popup, goog.ui.PopupBase.EventType.BEFORE_HIDE, - function(e) { - e.preventDefault(); - }); - assertEquals('The hide should have been cancelled', - true, popup.isVisible()); - assertTrue('The key event default action should not be prevented', - goog.testing.events.fireKeySequence( - targetDiv, goog.events.KeyCodes.ESC)); - assertEquals('Keydown should have all propagated', - 1, eventsPropagated); -} - -function testEscapeDismissalProvidesKeyTargetAsTargetForHideEvents() { - popup.setHideOnEscape(true); - popup.setVisible(true); - var calls = 0; - goog.events.listenOnce(popup, - [goog.ui.PopupBase.EventType.BEFORE_HIDE, - goog.ui.PopupBase.EventType.HIDE], - function(e) { - calls++; - assertEquals('The key target should be the hide event target', - 'targetDiv', e.target.id); - }); - goog.testing.events.fireKeySequence( - targetDiv, goog.events.KeyCodes.ESC); -} - -function testAutoHide() { - popup.setAutoHide(true); - popup.setVisible(true); - clock.tick(1000); // avoid bouncing - goog.testing.events.fireClickSequence(targetDiv); - assertFalse(popup.isVisible()); -} - -function testAutoHideCanBeDisabled() { - popup.setAutoHide(false); - popup.setVisible(true); - clock.tick(1000); // avoid bouncing - goog.testing.events.fireClickSequence(targetDiv); - assertTrue('Should not be hidden if auto hide is disabled', popup.isVisible()); -} - -function testAutoHideEnabledByDefault() { - assertTrue(popup.getAutoHide()); -} - -function testCanAddElementDuringBeforeShow() { - popup.setElement(null); - goog.events.listenOnce(popup, goog.ui.PopupBase.EventType.BEFORE_SHOW, - function() { - popup.setElement(popupDiv); - }); - popup.setVisible(true); - assertTrue('Popup should be shown', popup.isVisible()); -} - -function testShowWithNoElementThrowsException() { - popup.setElement(null); - var e = assertThrows(function() { - popup.setVisible(true); - }); - assertEquals('Caller must call setElement before trying to show the popup', - e.message); -} - -function testShowEventFiredWithNoTransition() { - var showHandlerCalled = false; - goog.events.listen(popup, goog.ui.PopupBase.EventType.SHOW, function() { - showHandlerCalled = true; - }); - - popup.setVisible(true); - assertTrue(showHandlerCalled); -} - -function testHideEventFiredWithNoTransition() { - var hideHandlerCalled = false; - goog.events.listen(popup, goog.ui.PopupBase.EventType.HIDE, function() { - hideHandlerCalled = true; - }); - - popup.setVisible(true); - popup.setVisible(false); - assertTrue(hideHandlerCalled); -} - -function testOnShowTransition() { - var mockTransition = new MockTransition(); - - var showHandlerCalled = false; - goog.events.listen(popup, goog.ui.PopupBase.EventType.SHOW, function() { - showHandlerCalled = true; - }); - - popup.setTransition(mockTransition); - popup.setVisible(true); - assertTrue(mockTransition.wasPlayed); - - assertFalse(showHandlerCalled); - mockTransition.dispatchEvent(goog.fx.Transition.EventType.END); - assertTrue(showHandlerCalled); -} - -function testOnHideTransition() { - var mockTransition = new MockTransition(); - - var hideHandlerCalled = false; - goog.events.listen(popup, goog.ui.PopupBase.EventType.HIDE, function() { - hideHandlerCalled = true; - }); - - popup.setTransition(undefined, mockTransition); - popup.setVisible(true); - assertFalse(mockTransition.wasPlayed); - - popup.setVisible(false); - assertTrue(mockTransition.wasPlayed); - - assertFalse(hideHandlerCalled); - mockTransition.dispatchEvent(goog.fx.Transition.EventType.END); - assertTrue(hideHandlerCalled); -} - - - -/** - * @implements {goog.fx.Transition} - * @extends {goog.events.EventTarget} - */ -var MockTransition = function() { - goog.base(this); - this.wasPlayed = false; -}; -goog.inherits(MockTransition, goog.events.EventTarget); - - -MockTransition.prototype.play = function() { - this.wasPlayed = true; -} - - -MockTransition.prototype.stop = goog.nullFunction; - - -// TODO(gboyer): Write better unit tests for click and cross-iframe dismissal. - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupcolorpicker.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupcolorpicker.js.svn-base deleted file mode 100644 index 79bd5d2..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupcolorpicker.js.svn-base +++ /dev/null @@ -1,441 +0,0 @@ -// 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 Popup Color Picker implementation. This is intended to be - * less general than goog.ui.ColorPicker and presents a default set of colors - * that CCC apps currently use in their color pickers. - * - * @see ../demos/popupcolorpicker.html - */ - -goog.provide('goog.ui.PopupColorPicker'); - -goog.require('goog.dom.classes'); -goog.require('goog.events.EventType'); -goog.require('goog.positioning.AnchoredPosition'); -goog.require('goog.positioning.Corner'); -goog.require('goog.ui.ColorPicker'); -goog.require('goog.ui.ColorPicker.EventType'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.Popup'); - - - -/** - * Popup color picker widget. - * - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @param {goog.ui.ColorPicker=} opt_colorPicker Optional color picker to use - * for this popup. - * @extends {goog.ui.Component} - * @constructor - */ -goog.ui.PopupColorPicker = function(opt_domHelper, opt_colorPicker) { - goog.ui.Component.call(this, opt_domHelper); - - if (opt_colorPicker) { - this.colorPicker_ = opt_colorPicker; - } -}; -goog.inherits(goog.ui.PopupColorPicker, goog.ui.Component); - - -/** - * Whether the color picker is initialized. - * @type {boolean} - * @private - */ -goog.ui.PopupColorPicker.prototype.initialized_ = false; - - -/** - * Instance of a color picker control. - * @type {goog.ui.ColorPicker} - * @private - */ -goog.ui.PopupColorPicker.prototype.colorPicker_ = null; - - -/** - * Instance of goog.ui.Popup used to manage the behavior of the color picker. - * @type {goog.ui.Popup} - * @private - */ -goog.ui.PopupColorPicker.prototype.popup_ = null; - - -/** - * Corner of the popup which is pinned to the attaching element. - * @type {goog.positioning.Corner} - * @private - */ -goog.ui.PopupColorPicker.prototype.pinnedCorner_ = - goog.positioning.Corner.TOP_START; - - -/** - * Corner of the attaching element where the popup shows. - * @type {goog.positioning.Corner} - * @private - */ -goog.ui.PopupColorPicker.prototype.popupCorner_ = - goog.positioning.Corner.BOTTOM_START; - - -/** - * Reference to the element that triggered the last popup. - * @type {Element} - * @private - */ -goog.ui.PopupColorPicker.prototype.lastTarget_ = null; - - -/** - * Whether the color picker can move the focus to its key event target when it - * is shown. The default is true. Setting to false can break keyboard - * navigation, but this is needed for certain scenarios, for example the - * toolbar menu in trogedit which can't have the selection changed. - * @type {boolean} - * @private - */ -goog.ui.PopupColorPicker.prototype.allowAutoFocus_ = true; - - -/** - * Whether the color picker can accept focus. - * @type {boolean} - * @private - */ -goog.ui.PopupColorPicker.prototype.focusable_ = true; - - -/** - * If true, then the colorpicker will toggle off if it is already visible. - * - * @type {boolean} - * @private - */ -goog.ui.PopupColorPicker.prototype.toggleMode_ = true; - - -/** @override */ -goog.ui.PopupColorPicker.prototype.createDom = function() { - goog.ui.PopupColorPicker.superClass_.createDom.call(this); - this.popup_ = new goog.ui.Popup(this.getElement()); - this.popup_.setPinnedCorner(this.pinnedCorner_); - goog.dom.classes.set(this.getElement(), - goog.getCssName('goog-popupcolorpicker')); - this.getElement().unselectable = 'on'; -}; - - -/** @override */ -goog.ui.PopupColorPicker.prototype.disposeInternal = function() { - goog.ui.PopupColorPicker.superClass_.disposeInternal.call(this); - this.colorPicker_ = null; - this.lastTarget_ = null; - this.initialized_ = false; - if (this.popup_) { - this.popup_.dispose(); - this.popup_ = null; - } -}; - - -/** - * ColorPickers cannot be used to decorate pre-existing html, since the - * structure they build is fairly complicated. - * @param {Element} element Element to decorate. - * @return {boolean} Returns always false. - */ -goog.ui.PopupColorPicker.prototype.canDecorate = function(element) { - return false; -}; - - -/** - * @return {goog.ui.ColorPicker} The color picker instance. - */ -goog.ui.PopupColorPicker.prototype.getColorPicker = function() { - return this.colorPicker_; -}; - - -/** - * 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.PopupColorPicker.prototype.getAutoHide = function() { - return !!this.popup_ && this.popup_.getAutoHide(); -}; - - -/** - * Sets whether the Popup dismisses itself when the user clicks outside of it - - * must be called after the Popup has been created (in createDom()), - * otherwise it does nothing. - * - * @param {boolean} autoHide Whether to autohide on an external click. - */ -goog.ui.PopupColorPicker.prototype.setAutoHide = function(autoHide) { - if (this.popup_) { - this.popup_.setAutoHide(autoHide); - } -}; - - -/** - * Returns the region inside which the Popup dismisses itself when the user - * clicks, or null if it was not set. Null indicates the entire document is - * the autohide region. - * @return {Element} The DOM element for autohide, or null if it hasn't been - * set. - */ -goog.ui.PopupColorPicker.prototype.getAutoHideRegion = function() { - return this.popup_ && this.popup_.getAutoHideRegion(); -}; - - -/** - * Sets the region inside which the Popup dismisses itself when the user - * clicks - must be called after the Popup has been created (in createDom()), - * otherwise it does nothing. - * - * @param {Element} element The DOM element for autohide. - */ -goog.ui.PopupColorPicker.prototype.setAutoHideRegion = function(element) { - if (this.popup_) { - this.popup_.setAutoHideRegion(element); - } -}; - - -/** - * Returns the {@link goog.ui.PopupBase} from this picker. Returns null if the - * popup has not yet been created. - * - * NOTE: This should *ONLY* be called from tests. If called before createDom(), - * this should return null. - * - * @return {goog.ui.PopupBase?} The popup or null if it hasn't been created. - */ -goog.ui.PopupColorPicker.prototype.getPopup = function() { - return this.popup_; -}; - - -/** - * @return {Element} The last element that triggered the popup. - */ -goog.ui.PopupColorPicker.prototype.getLastTarget = function() { - return this.lastTarget_; -}; - - -/** - * Attaches the popup color picker to an element. - * @param {Element} element The element to attach to. - */ -goog.ui.PopupColorPicker.prototype.attach = function(element) { - this.getHandler().listen(element, goog.events.EventType.MOUSEDOWN, - this.show_); -}; - - -/** - * Detatches the popup color picker from an element. - * @param {Element} element The element to detach from. - */ -goog.ui.PopupColorPicker.prototype.detach = function(element) { - this.getHandler().unlisten(element, goog.events.EventType.MOUSEDOWN, - this.show_); -}; - - -/** - * Gets the color that is currently selected in this color picker. - * @return {?string} The hex string of the color selected, or null if no - * color is selected. - */ -goog.ui.PopupColorPicker.prototype.getSelectedColor = function() { - return this.colorPicker_.getSelectedColor(); -}; - - -/** - * Sets whether the color picker can accept focus. - * @param {boolean} focusable True iff the color picker can accept focus. - */ -goog.ui.PopupColorPicker.prototype.setFocusable = function(focusable) { - this.focusable_ = focusable; - if (this.colorPicker_) { - // TODO(user): In next revision sort the behavior of passing state to - // children correctly - this.colorPicker_.setFocusable(focusable); - } -}; - - -/** - * Sets whether the color picker can automatically move focus to its key event - * target when it is set to visible. - * @param {boolean} allow Whether to allow auto focus. - */ -goog.ui.PopupColorPicker.prototype.setAllowAutoFocus = function(allow) { - this.allowAutoFocus_ = allow; -}; - - -/** - * @return {boolean} Whether the color picker can automatically move focus to - * its key event target when it is set to visible. - */ -goog.ui.PopupColorPicker.prototype.getAllowAutoFocus = function() { - return this.allowAutoFocus_; -}; - - -/** - * Sets whether the color picker should toggle off if it is already open. - * @param {boolean} toggle The new toggle mode. - */ -goog.ui.PopupColorPicker.prototype.setToggleMode = function(toggle) { - this.toggleMode_ = toggle; -}; - - -/** - * Gets whether the colorpicker is in toggle mode - * @return {boolean} toggle. - */ -goog.ui.PopupColorPicker.prototype.getToggleMode = function() { - return this.toggleMode_; -}; - - -/** - * Sets whether the picker remembers the last selected color between popups. - * - * @param {boolean} remember Whether to remember the selection. - */ -goog.ui.PopupColorPicker.prototype.setRememberSelection = function(remember) { - this.rememberSelection_ = remember; -}; - - -/** - * @return {boolean} Whether the picker remembers the last selected color - * between popups. - */ -goog.ui.PopupColorPicker.prototype.getRememberSelection = function() { - return this.rememberSelection_; -}; - - -/** - * Add an array of colors to the colors displayed by the color picker. - * Does not add duplicated colors. - * @param {Array.<string>} colors The array of colors to be added. - */ -goog.ui.PopupColorPicker.prototype.addColors = function(colors) { - -}; - - -/** - * Clear the colors displayed by the color picker. - */ -goog.ui.PopupColorPicker.prototype.clearColors = function() { - -}; - - -/** - * Set the pinned corner of the popup. - * @param {goog.positioning.Corner} corner The corner of the popup which is - * pinned to the attaching element. - */ -goog.ui.PopupColorPicker.prototype.setPinnedCorner = function(corner) { - this.pinnedCorner_ = corner; - if (this.popup_) { - this.popup_.setPinnedCorner(this.pinnedCorner_); - } -}; - - -/** - * Sets which corner of the attaching element this popup shows up. - * @param {goog.positioning.Corner} corner The corner of the attaching element - * where to show the popup. - */ -goog.ui.PopupColorPicker.prototype.setPopupCorner = function(corner) { - this.popupCorner_ = corner; -}; - - -/** - * Handles click events on the targets and shows the color picker. - * @param {goog.events.BrowserEvent} e The browser event. - * @private - */ -goog.ui.PopupColorPicker.prototype.show_ = function(e) { - if (!this.initialized_) { - this.colorPicker_ = this.colorPicker_ || - goog.ui.ColorPicker.createSimpleColorGrid(this.getDomHelper()); - this.colorPicker_.setFocusable(this.focusable_); - this.addChild(this.colorPicker_, true); - this.getHandler().listen(this.colorPicker_, - goog.ui.ColorPicker.EventType.CHANGE, this.onColorPicked_); - this.initialized_ = true; - } - - if (this.popup_.isOrWasRecentlyVisible() && this.toggleMode_ && - this.lastTarget_ == e.currentTarget) { - this.popup_.setVisible(false); - return; - } - - this.lastTarget_ = /** @type {Element} */ (e.currentTarget); - this.popup_.setPosition(new goog.positioning.AnchoredPosition( - this.lastTarget_, this.popupCorner_)); - if (!this.rememberSelection_) { - this.colorPicker_.setSelectedIndex(-1); - } - this.popup_.setVisible(true); - if (this.allowAutoFocus_) { - this.colorPicker_.focus(); - } -}; - - -/** - * Handles the color change event. - * @param {goog.events.Event} e The event. - * @private - */ -goog.ui.PopupColorPicker.prototype.onColorPicked_ = function(e) { - // When we show the color picker we reset the color, which triggers an event. - // Here we block that event so that it doesn't dismiss the popup - // TODO(user): Update the colorpicker to allow selection to be cleared - if (this.colorPicker_.getSelectedIndex() == -1) { - e.stopPropagation(); - return; - } - this.popup_.setVisible(false); - if (this.allowAutoFocus_) { - this.lastTarget_.focus(); - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupcolorpicker_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupcolorpicker_test.html.svn-base deleted file mode 100644 index d9563ae..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupcolorpicker_test.html.svn-base +++ /dev/null @@ -1,71 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2007 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.Popup</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.PopupColorPicker'); -</script> -</head> -<body> -<div id="containingDiv"> -<a href="javascript:void(0)" id="button1">color picker</a> -<script> - -// Unittest to ensure that the popup gets created in createDom(). -function testPopupCreation() { - var picker = new goog.ui.PopupColorPicker(); - picker.createDom(); - assertNotNull(picker.getPopup()); -} - -function testAutoHideIsSetProperly() { - var picker = new goog.ui.PopupColorPicker(); - picker.createDom(); - picker.setAutoHide(true); - var containingDiv = goog.dom.getElement('containingDiv'); - picker.setAutoHideRegion(containingDiv); - assertTrue(picker.getAutoHide()); - assertEquals(containingDiv, picker.getAutoHideRegion()); -} - -// Unittest to ensure the popup opens with a custom color picker. -function testCustomColorPicker() { - var button1 = document.getElementById('button1'); - var domHelper = goog.dom.getDomHelper(); - var colorPicker = new goog.ui.ColorPicker(); - colorPicker.setColors(["#ffffff", "#000000"]); - var picker = new goog.ui.PopupColorPicker(domHelper, colorPicker); - picker.render(); - picker.attach(button1); - assertNotNull(picker.getColorPicker()); - assertNotNull(picker.getPopup().getElement()); - assertNull(picker.getSelectedColor()); - - var changeEvents = 0; - goog.events.listen(picker, goog.ui.ColorPicker.EventType.CHANGE, function(e) { - changeEvents++; - }); - - // Select the first color. - goog.testing.events.fireClickSequence(button1); - goog.testing.events.fireClickSequence( - document.getElementById('goog-palette-cell-0').firstChild); - assertEquals("#ffffff", picker.getSelectedColor()); - assertEquals(1, changeEvents); -} - -</script> -</div> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupdatepicker.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupdatepicker.js.svn-base deleted file mode 100644 index e200b70..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupdatepicker.js.svn-base +++ /dev/null @@ -1,273 +0,0 @@ -// 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 Popup Date Picker implementation. Pairs a goog.ui.DatePicker - * with a goog.ui.Popup allowing the DatePicker to be attached to elements. - * - * @see ../demos/popupdatepicker.html - */ - -goog.provide('goog.ui.PopupDatePicker'); - -goog.require('goog.events.EventType'); -goog.require('goog.positioning.AnchoredPosition'); -goog.require('goog.positioning.Corner'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.DatePicker'); -goog.require('goog.ui.DatePicker.Events'); -goog.require('goog.ui.Popup'); -goog.require('goog.ui.PopupBase.EventType'); - - - -/** - * Popup date picker widget. - * - * @param {goog.ui.DatePicker=} opt_datePicker Optional DatePicker. This - * enables the use of a custom date-picker instance. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @extends {goog.ui.Component} - * @constructor - */ -goog.ui.PopupDatePicker = function(opt_datePicker, opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - - this.datePicker_ = opt_datePicker || new goog.ui.DatePicker(); -}; -goog.inherits(goog.ui.PopupDatePicker, goog.ui.Component); - - -/** - * Instance of a date picker control. - * @type {goog.ui.DatePicker?} - * @private - */ -goog.ui.PopupDatePicker.prototype.datePicker_ = null; - - -/** - * Instance of goog.ui.Popup used to manage the behavior of the date picker. - * @type {goog.ui.Popup?} - * @private - */ -goog.ui.PopupDatePicker.prototype.popup_ = null; - - -/** - * Reference to the element that triggered the last popup. - * @type {Element} - * @private - */ -goog.ui.PopupDatePicker.prototype.lastTarget_ = null; - - -/** - * Whether the date picker can move the focus to its key event target when it - * is shown. The default is true. Setting to false can break keyboard - * navigation, but this is needed for certain scenarios, for example the - * toolbar menu in trogedit which can't have the selection changed. - * @type {boolean} - * @private - */ -goog.ui.PopupDatePicker.prototype.allowAutoFocus_ = true; - - -/** @override */ -goog.ui.PopupDatePicker.prototype.createDom = function() { - goog.ui.PopupDatePicker.superClass_.createDom.call(this); - this.getElement().className = goog.getCssName('goog-popupdatepicker'); - this.popup_ = new goog.ui.Popup(this.getElement()); -}; - - -/** @override */ -goog.ui.PopupDatePicker.prototype.enterDocument = function() { - goog.ui.PopupDatePicker.superClass_.enterDocument.call(this); - // Create the DatePicker, if it isn't already. - // Done here as DatePicker assumes that the element passed to it is attached - // to a document. - if (!this.datePicker_.isInDocument()) { - var el = this.getElement(); - // Make it initially invisible - el.style.visibility = 'hidden'; - goog.style.showElement(el, false); - this.datePicker_.decorate(el); - } - this.getHandler().listen(this.datePicker_, goog.ui.DatePicker.Events.CHANGE, - this.onDateChanged_); -}; - - -/** @override */ -goog.ui.PopupDatePicker.prototype.disposeInternal = function() { - goog.ui.PopupDatePicker.superClass_.disposeInternal.call(this); - if (this.popup_) { - this.popup_.dispose(); - this.popup_ = null; - } - this.datePicker_.dispose(); - this.datePicker_ = null; - this.lastTarget_ = null; -}; - - -/** - * DatePicker cannot be used to decorate pre-existing html, since they're - * not based on Components. - * @param {Element} element Element to decorate. - * @return {boolean} Returns always false. - */ -goog.ui.PopupDatePicker.prototype.canDecorate = function(element) { - return false; -}; - - -/** - * @return {goog.ui.DatePicker} The date picker instance. - */ -goog.ui.PopupDatePicker.prototype.getDatePicker = function() { - return this.datePicker_; -}; - - -/** - * @return {goog.date.Date?} The selected date, if any. See - * goog.ui.DatePicker.getDate(). - */ -goog.ui.PopupDatePicker.prototype.getDate = function() { - return this.datePicker_.getDate(); -}; - - -/** - * Sets the selected date. See goog.ui.DatePicker.setDate(). - * @param {goog.date.Date?} date The date to select. - */ -goog.ui.PopupDatePicker.prototype.setDate = function(date) { - this.datePicker_.setDate(date); -}; - - -/** - * @return {Element} The last element that triggered the popup. - */ -goog.ui.PopupDatePicker.prototype.getLastTarget = function() { - return this.lastTarget_; -}; - - -/** - * Attaches the popup date picker to an element. - * @param {Element} element The element to attach to. - */ -goog.ui.PopupDatePicker.prototype.attach = function(element) { - this.getHandler().listen(element, goog.events.EventType.MOUSEDOWN, - this.showPopup_); -}; - - -/** - * Detatches the popup date picker from an element. - * @param {Element} element The element to detach from. - */ -goog.ui.PopupDatePicker.prototype.detach = function(element) { - this.getHandler().unlisten(element, goog.events.EventType.MOUSEDOWN, - this.showPopup_); -}; - - -/** - * Sets whether the date picker can automatically move focus to its key event - * target when it is set to visible. - * @param {boolean} allow Whether to allow auto focus. - */ -goog.ui.PopupDatePicker.prototype.setAllowAutoFocus = function(allow) { - this.allowAutoFocus_ = allow; -}; - - -/** - * @return {boolean} Whether the date picker can automatically move focus to - * its key event target when it is set to visible. - */ -goog.ui.PopupDatePicker.prototype.getAllowAutoFocus = function() { - return this.allowAutoFocus_; -}; - - -/** - * Show the popup at the bottom-left corner of the specified element. - * @param {Element} element Reference element for displaying the popup -- popup - * will appear at the bottom-left corner of this element. - */ -goog.ui.PopupDatePicker.prototype.showPopup = function(element) { - this.lastTarget_ = element; - this.popup_.setPosition(new goog.positioning.AnchoredPosition( - element, goog.positioning.Corner.BOTTOM_START)); - - // Don't listen to date changes while we're setting up the popup so we don't - // have to worry about change events when we call setDate(). - this.getHandler().unlisten(this.datePicker_, goog.ui.DatePicker.Events.CHANGE, - this.onDateChanged_); - this.datePicker_.setDate(null); - - // Forward the change event onto our listeners. Done before we start - // listening to date changes again, so that listeners can change the date - // without firing more events. - this.dispatchEvent(goog.ui.PopupBase.EventType.SHOW); - - this.getHandler().listen(this.datePicker_, goog.ui.DatePicker.Events.CHANGE, - this.onDateChanged_); - this.popup_.setVisible(true); - if (this.allowAutoFocus_) { - this.getElement().focus(); // Our element contains the date picker. - } -}; - - -/** - * Handles click events on the targets and shows the date picker. - * @param {goog.events.Event} event The click event. - * @private - */ -goog.ui.PopupDatePicker.prototype.showPopup_ = function(event) { - this.showPopup(/** @type {Element} */ (event.currentTarget)); -}; - - -/** - * Hides this popup. - */ -goog.ui.PopupDatePicker.prototype.hidePopup = function() { - this.popup_.setVisible(false); - if (this.allowAutoFocus_ && this.lastTarget_) { - this.lastTarget_.focus(); - } -}; - - -/** - * Called when the date is changed. - * - * @param {goog.events.Event} event The date change event. - * @private - */ -goog.ui.PopupDatePicker.prototype.onDateChanged_ = function(event) { - this.hidePopup(); - - // Forward the change event onto our listeners. - this.dispatchEvent(event); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupmenu.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupmenu.js.svn-base deleted file mode 100644 index 02bde14..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupmenu.js.svn-base +++ /dev/null @@ -1,557 +0,0 @@ -// 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 menu class for showing popups. A single popup can be - * attached to multiple anchor points. The menu will try to reposition itself - * if it goes outside the viewport. - * - * Decoration is the same as goog.ui.Menu except that the outer DIV can have a - * 'for' property, which is the ID of the element which triggers the popup. - * - * Decorate Example: - * <button id="dButton">Decorated Popup</button> - * <div id="dMenu" for="dButton" class="goog-menu"> - * <div class="goog-menuitem">A a</div> - * <div class="goog-menuitem">B b</div> - * <div class="goog-menuitem">C c</div> - * <div class="goog-menuitem">D d</div> - * <div class="goog-menuitem">E e</div> - * <div class="goog-menuitem">F f</div> - * </div> - * - * TESTED=FireFox 2.0, IE6, Opera 9, Chrome. - * TODO(user): Key handling is flakey in Opera and Chrome - * - * @see ../demos/popupmenu.html - */ - -goog.provide('goog.ui.PopupMenu'); - -goog.require('goog.events.EventType'); -goog.require('goog.positioning.AnchoredViewportPosition'); -goog.require('goog.positioning.Corner'); -goog.require('goog.positioning.MenuAnchoredPosition'); -goog.require('goog.positioning.ViewportClientPosition'); -goog.require('goog.structs'); -goog.require('goog.structs.Map'); -goog.require('goog.style'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.Menu'); -goog.require('goog.ui.PopupBase'); -goog.require('goog.userAgent'); - - - -/** - * A basic menu class. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @param {goog.ui.MenuRenderer=} opt_renderer Renderer used to render or - * decorate the container; defaults to {@link goog.ui.MenuRenderer}. - * @extends {goog.ui.Menu} - * @constructor - */ -goog.ui.PopupMenu = function(opt_domHelper, opt_renderer) { - goog.ui.Menu.call(this, opt_domHelper, opt_renderer); - - this.setAllowAutoFocus(true); - - // Popup menus are hidden by default. - this.setVisible(false, true); - - /** - * Map of attachment points for the menu. Key -> Object - * @type {!goog.structs.Map} - * @private - */ - this.targets_ = new goog.structs.Map(); -}; -goog.inherits(goog.ui.PopupMenu, goog.ui.Menu); - - -/** - * If true, then if the menu will toggle off if it is already visible. - * @type {boolean} - * @private - */ -goog.ui.PopupMenu.prototype.toggleMode_ = false; - - -/** - * Time that the menu was last shown. - * @type {number} - * @private - */ -goog.ui.PopupMenu.prototype.lastHide_ = 0; - - -/** - * Current element where the popup menu is anchored. - * @type {Element} - * @private - */ -goog.ui.PopupMenu.prototype.currentAnchor_ = null; - - -/** - * Decorate an existing HTML structure with the menu. Menu items will be - * constructed from elements with classname 'goog-menuitem', separators will be - * made from HR elements. - * @param {Element} element Element to decorate. - */ -goog.ui.PopupMenu.prototype.decorateInternal = function(element) { - goog.ui.PopupMenu.superClass_.decorateInternal.call(this, element); - // 'for' is a custom attribute for attaching the menu to a click target - var htmlFor = element.getAttribute('for') || element.htmlFor; - if (htmlFor) { - this.attach( - this.getDomHelper().getElement(htmlFor), - goog.positioning.Corner.BOTTOM_LEFT); - } -}; - - -/** - * The menu has been added to the document. - */ -goog.ui.PopupMenu.prototype.enterDocument = function() { - goog.ui.PopupMenu.superClass_.enterDocument.call(this); - - goog.structs.forEach(this.targets_, this.attachEvent_, this); - - var handler = this.getHandler(); - handler.listen( - this, goog.ui.Component.EventType.ACTION, this.onAction_); - handler.listen(this.getDomHelper().getDocument(), - goog.events.EventType.MOUSEDOWN, this.onDocClick, true); - - // Webkit doesn't fire a mousedown event when opening the context menu, - // but we need one to update menu visibility properly. So in Safari handle - // contextmenu mouse events like mousedown. - // {@link http://bugs.webkit.org/show_bug.cgi?id=6595} - if (goog.userAgent.WEBKIT) { - handler.listen(this.getDomHelper().getDocument(), - goog.events.EventType.CONTEXTMENU, this.onDocClick, true); - } -}; - - -/** - * Attaches the menu to a new popup position and anchor element. A menu can - * only be attached to an element once, since attaching the same menu for - * multiple positions doesn't make sense. - * - * @param {Element} element Element whose click event should trigger the menu. - * @param {goog.positioning.Corner=} opt_targetCorner Corner of the target that - * the menu should be anchored to. - * @param {goog.positioning.Corner=} opt_menuCorner Corner of the menu that - * should be anchored. - * @param {boolean=} opt_contextMenu Whether the menu should show on - * {@link goog.events.EventType.CONTEXTMENU} events, false if it should - * show on {@link goog.events.EventType.MOUSEDOWN} events. Default is - * MOUSEDOWN. - * @param {goog.math.Box=} opt_margin Margin for the popup used in positioning - * algorithms. - */ -goog.ui.PopupMenu.prototype.attach = function( - element, opt_targetCorner, opt_menuCorner, opt_contextMenu, opt_margin) { - - if (this.isAttachTarget(element)) { - // Already in the popup, so just return. - return; - } - - var target = this.createAttachTarget(element, opt_targetCorner, - opt_menuCorner, opt_contextMenu, opt_margin); - - if (this.isInDocument()) { - this.attachEvent_(target); - } -}; - - -/** - * Creates an object describing how the popup menu should be attached to the - * anchoring element based on the given parameters. The created object is - * stored, keyed by {@code element} and is retrievable later by invoking - * {@link #getAttachTarget(element)} at a later point. - * - * Subclass may add more properties to the returned object, as needed. - * - * @param {Element} element Element whose click event should trigger the menu. - * @param {goog.positioning.Corner=} opt_targetCorner Corner of the target that - * the menu should be anchored to. - * @param {goog.positioning.Corner=} opt_menuCorner Corner of the menu that - * should be anchored. - * @param {boolean=} opt_contextMenu Whether the menu should show on - * {@link goog.events.EventType.CONTEXTMENU} events, false if it should - * show on {@link goog.events.EventType.MOUSEDOWN} events. Default is - * MOUSEDOWN. - * @param {goog.math.Box=} opt_margin Margin for the popup used in positioning - * algorithms. - * - * @return {Object} An object that describes how the popup menu should be - * attached to the anchoring element. - * - * @protected - */ -goog.ui.PopupMenu.prototype.createAttachTarget = function( - element, opt_targetCorner, opt_menuCorner, opt_contextMenu, opt_margin) { - if (!element) { - return null; - } - - var target = { - element_: element, - targetCorner_: opt_targetCorner, - menuCorner_: opt_menuCorner, - eventType_: opt_contextMenu ? goog.events.EventType.CONTEXTMENU : - goog.events.EventType.MOUSEDOWN, - margin_: opt_margin - }; - - this.targets_.set(goog.getUid(element), target); - - return target; -}; - - -/** - * Returns the object describing how the popup menu should be attach to given - * element or {@code null}. The object is created and the association is formed - * when {@link #attach} is invoked. - * - * @param {Element} element DOM element. - * @return {Object} The object created when {@link attach} is invoked on - * {@code element}. Returns {@code null} if the element does not trigger - * the menu (i.e. {@link attach} has never been invoked on - * {@code element}). - * @protected - */ -goog.ui.PopupMenu.prototype.getAttachTarget = function(element) { - return element ? - /** @type {Object} */(this.targets_.get(goog.getUid(element))) : - null; -}; - - -/** - * @param {Element} element Any DOM element. - * @return {boolean} Whether clicking on the given element will trigger the - * menu. - * - * @protected - */ -goog.ui.PopupMenu.prototype.isAttachTarget = function(element) { - return element ? this.targets_.containsKey(goog.getUid(element)) : false; -}; - - -/** - * @return {Element} The current element where the popup is anchored, if it's - * visible. - */ -goog.ui.PopupMenu.prototype.getAttachedElement = function() { - return this.currentAnchor_; -}; - - -/** - * Attaches an event listener to a target - * @param {Object} target The target to attach an event to. - * @private - */ -goog.ui.PopupMenu.prototype.attachEvent_ = function(target) { - this.getHandler().listen( - target.element_, target.eventType_, this.onTargetClick_); -}; - - -/** - * Detaches all listeners - */ -goog.ui.PopupMenu.prototype.detachAll = function() { - if (this.isInDocument()) { - var keys = this.targets_.getKeys(); - for (var i = 0; i < keys.length; i++) { - this.detachEvent_(/** @type {Object} */ (this.targets_.get(keys[i]))); - } - } - - this.targets_.clear(); -}; - - -/** - * Detaches a menu from a given element. - * @param {Element} element Element whose click event should trigger the menu. - */ -goog.ui.PopupMenu.prototype.detach = function(element) { - if (!this.isAttachTarget(element)) { - throw Error('Menu not attached to provided element, unable to detach.'); - } - - var key = goog.getUid(element); - if (this.isInDocument()) { - this.detachEvent_(/** @type {Object} */ (this.targets_.get(key))); - } - - this.targets_.remove(key); -}; - - -/** - * Detaches an event listener to a target - * @param {Object} target The target to detach events from. - * @private - */ -goog.ui.PopupMenu.prototype.detachEvent_ = function(target) { - this.getHandler().unlisten( - target.element_, target.eventType_, this.onTargetClick_); -}; - - -/** - * Sets whether the menu should toggle if it is already open. For context - * menus this should be false, for toolbar menus it makes more sense to be true. - * @param {boolean} toggle The new toggle mode. - */ -goog.ui.PopupMenu.prototype.setToggleMode = function(toggle) { - this.toggleMode_ = toggle; -}; - - -/** - * Gets whether the menu is in toggle mode - * @return {boolean} toggle. - */ -goog.ui.PopupMenu.prototype.getToggleMode = function() { - return this.toggleMode_; -}; - - -/** - * Show the menu using given positioning object. - * @param {goog.positioning.AbstractPosition} position The positioning instance. - * @param {goog.positioning.Corner=} opt_menuCorner The corner of the menu to be - * positioned. - * @param {goog.math.Box=} opt_margin A margin specified in pixels. - * @param {Element=} opt_anchor The element which acts as visual anchor for this - * menu. - */ -goog.ui.PopupMenu.prototype.showWithPosition = function(position, - opt_menuCorner, opt_margin, opt_anchor) { - var isVisible = this.isVisible(); - if (this.isOrWasRecentlyVisible() && this.toggleMode_) { - this.hide(); - return; - } - - // Set current anchor before dispatching BEFORE_SHOW. This is typically useful - // when we would need to make modifications based on the current anchor to the - // menu just before displaying it. - this.currentAnchor_ = opt_anchor || null; - - // Notify event handlers that the menu is about to be shown. - if (!this.dispatchEvent(goog.ui.Component.EventType.BEFORE_SHOW)) { - return; - } - - var menuCorner = typeof opt_menuCorner != 'undefined' ? - opt_menuCorner : - goog.positioning.Corner.TOP_START; - - // This is a little hacky so that we can position the menu with minimal - // flicker. - - if (!isVisible) { - // On IE, setting visibility = 'hidden' on a visible menu - // will cause a blur, forcing the menu to close immediately. - this.getElement().style.visibility = 'hidden'; - } - - goog.style.showElement(this.getElement(), true); - position.reposition(this.getElement(), menuCorner, opt_margin); - - if (!isVisible) { - this.getElement().style.visibility = 'visible'; - } - - this.setHighlightedIndex(-1); - - // setVisible dispatches a goog.ui.Component.EventType.SHOW event, which may - // be canceled to prevent the menu from being shown. - this.setVisible(true); -}; - - -/** - * Show the menu at a given attached target. - * @param {Object} target Popup target. - * @param {number} x The client-X associated with the show event. - * @param {number} y The client-Y associated with the show event. - * @protected - */ -goog.ui.PopupMenu.prototype.showMenu = function(target, x, y) { - var position = goog.isDef(target.targetCorner_) ? - new goog.positioning.AnchoredViewportPosition(target.element_, - target.targetCorner_, true) : - new goog.positioning.ViewportClientPosition(x, y); - if (position.setLastResortOverflow) { - // This is a ViewportClientPosition, so we can set the overflow policy. - // Allow the menu to slide from the corner rather than clipping if it is - // completely impossible to fit it otherwise. - position.setLastResortOverflow(goog.positioning.Overflow.ADJUST_X | - goog.positioning.Overflow.ADJUST_Y); - } - this.showWithPosition(position, target.menuCorner_, target.margin_, - target.element_); -}; - - -/** - * Shows the menu immediately at the given client coordinates. - * @param {number} x The client-X associated with the show event. - * @param {number} y The client-Y associated with the show event. - * @param {goog.positioning.Corner=} opt_menuCorner Corner of the menu that - * should be anchored. - */ -goog.ui.PopupMenu.prototype.showAt = function(x, y, opt_menuCorner) { - this.showWithPosition( - new goog.positioning.ViewportClientPosition(x, y), opt_menuCorner); -}; - - -/** - * Shows the menu immediately attached to the given element - * @param {Element} element The element to show at. - * @param {goog.positioning.Corner} targetCorner The corner of the target to - * anchor to. - * @param {goog.positioning.Corner=} opt_menuCorner Corner of the menu that - * should be anchored. - */ -goog.ui.PopupMenu.prototype.showAtElement = function(element, targetCorner, - opt_menuCorner) { - this.showWithPosition( - new goog.positioning.MenuAnchoredPosition(element, targetCorner, true), - opt_menuCorner, null, element); -}; - - -/** - * Hides the menu. - */ -goog.ui.PopupMenu.prototype.hide = function() { - if (!this.isVisible()) { - return; - } - - // setVisible dispatches a goog.ui.Component.EventType.HIDE event, which may - // be canceled to prevent the menu from being hidden. - this.setVisible(false); - if (!this.isVisible()) { - // HIDE event wasn't canceled; the menu is now hidden. - this.lastHide_ = goog.now(); - this.currentAnchor_ = null; - } -}; - - -/** - * Returns whether the menu is currently visible or was visible within about - * 150 ms ago. This stops the menu toggling back on if the toggleMode == false. - * @return {boolean} Whether the popup is currently visible or was visible - * within about 150 ms ago. - */ -goog.ui.PopupMenu.prototype.isOrWasRecentlyVisible = function() { - return this.isVisible() || this.wasRecentlyHidden(); -}; - - -/** - * Used to stop the menu toggling back on if the toggleMode == false. - * @return {boolean} Whether the menu was recently hidden. - * @protected - */ -goog.ui.PopupMenu.prototype.wasRecentlyHidden = function() { - return goog.now() - this.lastHide_ < goog.ui.PopupBase.DEBOUNCE_DELAY_MS; -}; - - -/** - * Dismiss the popup menu when an action fires. - * @param {goog.events.Event=} opt_e The optional event. - * @private - */ -goog.ui.PopupMenu.prototype.onAction_ = function(opt_e) { - this.hide(); -}; - - -/** - * Handles a browser event on one of the popup targets - * @param {goog.events.BrowserEvent} e The browser event. - * @private - */ -goog.ui.PopupMenu.prototype.onTargetClick_ = function(e) { - var keys = this.targets_.getKeys(); - for (var i = 0; i < keys.length; i++) { - var target = /** @type {Object} */(this.targets_.get(keys[i])); - if (target.element_ == e.currentTarget) { - this.showMenu(target, - /** @type {number} */ (e.clientX), - /** @type {number} */ (e.clientY)); - e.preventDefault(); - e.stopPropagation(); - return; - } - } -}; - - -/** - * Handles click events that propagate to the document. - * @param {goog.events.BrowserEvent} e The browser event. - * @protected - */ -goog.ui.PopupMenu.prototype.onDocClick = function(e) { - if (this.isVisible() && - !this.containsElement(/** @type {Element} */ (e.target))) { - this.hide(); - } -}; - - -/** - * Handles the key event target loosing focus. - * @param {goog.events.BrowserEvent} e The browser event. - * @protected - */ -goog.ui.PopupMenu.prototype.handleBlur = function(e) { - goog.ui.PopupMenu.superClass_.handleBlur.call(this, e); - this.hide(); -}; - - -/** @override */ -goog.ui.PopupMenu.prototype.disposeInternal = function() { - // Always call the superclass' disposeInternal() first (Bug 715885). - goog.ui.PopupMenu.superClass_.disposeInternal.call(this); - - // Disposes of the attachment target map. - if (this.targets_) { - this.targets_.clear(); - delete this.targets_; - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupmenu_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupmenu_test.html.svn-base deleted file mode 100644 index ecfde16..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/popupmenu_test.html.svn-base +++ /dev/null @@ -1,308 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.PopupMenu</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.events.EventHandler'); - goog.require('goog.events.EventType'); - goog.require('goog.math.Box'); - goog.require('goog.positioning.Corner'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.PopupMenu'); -</script> -</head> -<body> -<div id="popup-anchor"></div> -<script> - -var anchor = goog.dom.getElement('popup-anchor'); - -// Event handler -var handler; -var showPopup; -var beforeShowPopupCalled; -var popup; - -function setUp() { - handler = new goog.events.EventHandler(); - popup = new goog.ui.PopupMenu(); - popup.render(); -} - -function tearDown() { - handler.dispose(); - popup.dispose(); -} - -/** - * Asserts properties of {@code target} matches the expected value. - * - * @param {Object} target The target specifying how the popup menu should be - * attached to an anchor. - * @param {Element} expectedElement The expected anchoring element. - * @param {goog.positioning.Corner} expectedTargetCorner The expected value of - * the {@code target.targetCorner_} property. - * @param {goog.positioning.Corner} expectedMenuCorner The expected value of - * the {@code target.menuCorner_} property. - * @param {goog.events.EventType} expectedEventType The expected value of the - * {@code target.eventType_} property. - * @param {goog.math.Box} expectedMargin The expected value of the - * {@code target.margin_} property. - */ -function assertTarget(target, expectedElement, expectedTargetCorner, - expectedMenuCorner, expectedEventType, expectedMargin) { - var expectedTarget = { - element_: expectedElement, - targetCorner_: expectedTargetCorner, - menuCorner_: expectedMenuCorner, - eventType_: expectedEventType, - margin_: expectedMargin - } - - assertObjectEquals('Target does not match.', expectedTarget, target); -} - -/** - * Test menu receives BEFORE_SHOW event before it's displayed. - */ -function testBeforeShowEvent() { - var target = popup.createAttachTarget(anchor); - popup.attach(anchor); - - function beforeShowPopup(e) { - // Ensure that the element is not yet visible. - assertFalse('The element should not be shown when BEFORE_SHOW event is ' + - 'being handled', - goog.style.isElementShown(popup.getElement())); - // Verify that current anchor is set before dispatching BEFORE_SHOW. - assertNotNullNorUndefined(popup.getAttachedElement()); - assertEquals('The attached anchor element is incorrect', - target.element_, popup.getAttachedElement()); - beforeShowPopupCalled = true; - return showPopup; - - }; - function onShowPopup(e) { - assertEquals('The attached anchor element is incorrect', - target.element_, popup.getAttachedElement()); - }; - - handler.listen(popup, - goog.ui.Menu.EventType.BEFORE_SHOW, - beforeShowPopup); - handler.listen(popup, - goog.ui.Menu.EventType.SHOW, - onShowPopup); - - beforeShowPopupCalled = false; - showPopup = false; - popup.showMenu(target, 0, 0); - assertTrue('BEFORE_SHOW event handler should be called on #showMenu', - beforeShowPopupCalled); - assertFalse('The element should not be shown when BEFORE_SHOW handler ' + - 'returned false', - goog.style.isElementShown(popup.getElement())); - - beforeShowPopupCalled = false; - showPopup = true; - popup.showMenu(target, 0, 0); - assertTrue('The element should be shown when BEFORE_SHOW handler ' + - 'returned true', - goog.style.isElementShown(popup.getElement())); -} - -/** - * Test the behavior of {@link PopupMenu.isAttachTarget}. - */ -function testIsAttachTarget() { - // Before 'attach' is called. - assertFalse('Menu should not be attached to the element', - popup.isAttachTarget(anchor)); - - popup.attach(anchor); - assertTrue('Menu should be attached to the anchor', - popup.isAttachTarget(anchor)); - - popup.detach(anchor); - assertFalse('Menu is expected to be detached from the element', - popup.isAttachTarget(anchor)); -} - -/** - * Tests the behavior of {@link PopupMenu.createAttachTarget}. - */ -function testCreateAttachTarget() { - // Randomly picking parameters. - var targetCorner = goog.positioning.Corner.TOP_END; - var menuCorner = goog.positioning.Corner.BOTTOM_LEFT; - var contextMenu = false; // Show menu on mouse down event. - var margin = new goog.math.Box(0, 10, 5, 25); - - // Simply setting the required parameters. - var target = popup.createAttachTarget(anchor); - assertTrue(popup.isAttachTarget(anchor)); - assertTarget(target, anchor, undefined, undefined, - goog.events.EventType.MOUSEDOWN, undefined); - - // Creating another target with all the parameters. - target = popup.createAttachTarget(anchor, targetCorner, menuCorner, - contextMenu, margin); - assertTrue(popup.isAttachTarget(anchor)); - assertTarget(target, anchor, targetCorner, menuCorner, - goog.events.EventType.MOUSEDOWN, margin); - - // Finally, switch up the 'contextMenu' - target = popup.createAttachTarget(anchor, undefined, undefined, - true /*opt_contextMenu*/, undefined); - assertTarget(target, anchor, undefined, undefined, - goog.events.EventType.CONTEXTMENU, undefined); -} - -/** - * Tests the behavior of {@link PopupMenu.getAttachTarget}. - */ -function testGetAttachTarget() { - // Before the menu is attached to the anchor. - var target = popup.getAttachTarget(anchor); - assertTrue('Not expecting a target before the element is attach to the menu', - target == null); - - // Randomly picking parameters. - var targetCorner = goog.positioning.Corner.TOP_END; - var menuCorner = goog.positioning.Corner.BOTTOM_LEFT; - var contextMenu = false; // Show menu on mouse down event. - var margin = new goog.math.Box(0, 10, 5, 25); - - popup.attach(anchor, targetCorner, menuCorner, contextMenu, margin); - target = popup.getAttachTarget(anchor); - assertTrue('Failed to get target after attaching element to menu', - target != null); - - // Make sure we got the right target back. - assertTarget(target, anchor, targetCorner, menuCorner, - goog.events.EventType.MOUSEDOWN, margin); -} - -function testSmallViewportSliding() { - popup.getElement().style.position = 'absolute'; - popup.getElement().style.outline = '1px solid blue'; - var item = new goog.ui.MenuItem('Test Item'); - popup.addChild(item, true); - item.getElement().style.overflow = 'hidden'; - - var viewport = goog.style.getClientViewportElement(); - var viewportRect = goog.style.getVisibleRectForElement(viewport); - - var middlePos = Math.floor((viewportRect.right - viewportRect.left) / 2); - var leftwardPos = Math.floor((viewportRect.right - viewportRect.left) / 3); - var rightwardPos = - Math.floor((viewportRect.right - viewportRect.left) / 3 * 2); - - // Can interpret these positions as widths relative to the viewport as well. - var smallWidth = leftwardPos; - var mediumWidth = middlePos; - var largeWidth = rightwardPos; - - // Test small menu first. This should be small enough that it will display - // its upper left corner where we tell it to in all three positions. - popup.getElement().style.width = smallWidth + 'px'; - - var target = popup.createAttachTarget(anchor); - popup.attach(anchor); - - popup.showMenu(target, leftwardPos, 0); - assertObjectEquals( - 'Popup in wrong position: small size, leftward pos', - new goog.math.Coordinate(leftwardPos, 0), - goog.style.getPosition(popup.getElement())); - - popup.showMenu(target, middlePos, 0); - assertObjectEquals( - 'Popup in wrong position: small size, middle pos', - new goog.math.Coordinate(middlePos, 0), - goog.style.getPosition(popup.getElement())); - - popup.showMenu(target, rightwardPos, 0); - assertObjectEquals( - 'Popup in wrong position: small size, rightward pos', - new goog.math.Coordinate(rightwardPos, 0), - goog.style.getPosition(popup.getElement())); - - // Test medium menu next. This should display with its upper left corner - // at the target when leftward and middle, but on the right it should - // position its upper right corner at the target instead. - popup.getElement().style.width = mediumWidth + 'px'; - - popup.showMenu(target, leftwardPos, 0); - assertObjectEquals( - 'Popup in wrong position: medium size, leftward pos', - new goog.math.Coordinate(leftwardPos, 0), - goog.style.getPosition(popup.getElement())); - - popup.showMenu(target, middlePos, 0); - assertObjectEquals( - 'Popup in wrong position: medium size, middle pos', - new goog.math.Coordinate(middlePos, 0), - goog.style.getPosition(popup.getElement())); - - popup.showMenu(target, rightwardPos, 0); - assertObjectEquals( - 'Popup in wrong position: medium size, rightward pos', - new goog.math.Coordinate(rightwardPos - mediumWidth, 0), - goog.style.getPosition(popup.getElement())); - - // Test large menu next. This should display with its upper left corner at - // the target when leftward, and its upper right corner at the target when - // rightward, but right in the middle neither corner can be at the target and - // keep the entire menu onscreen, so it should place its upper right corner - // at the very right edge of the viewport. - popup.getElement().style.width = largeWidth + 'px'; - popup.showMenu(target, leftwardPos, 0); - assertObjectEquals( - 'Popup in wrong position: large size, leftward pos', - new goog.math.Coordinate(leftwardPos, 0), - goog.style.getPosition(popup.getElement())); - - popup.showMenu(target, middlePos, 0); - assertObjectEquals( - 'Popup in wrong position: large size, middle pos', - new goog.math.Coordinate( - viewportRect.right - viewportRect.left - largeWidth, 0), - goog.style.getPosition(popup.getElement())); - - popup.showMenu(target, rightwardPos, 0); - assertObjectEquals( - 'Popup in wrong position: large size, rightward pos', - new goog.math.Coordinate(rightwardPos - largeWidth, 0), - goog.style.getPosition(popup.getElement())); - - // Make sure that the menu still displays correctly if we give the target - // a target corner. We can't set the overflow policy in that case, but it - // should still display. - popup.detach(anchor); - anchor.style.position = 'absolute'; - anchor.style.left = '24px'; - anchor.style.top = '24px'; - var targetCorner = goog.positioning.Corner.TOP_END; - target = popup.createAttachTarget(anchor, targetCorner); - popup.attach(anchor, targetCorner); - popup.getElement().style.width = smallWidth + 'px'; - popup.showMenu(target, leftwardPos, 0); - assertObjectEquals( - 'Popup in wrong position: small size, leftward pos, with target corner', - new goog.math.Coordinate(24, 24), - goog.style.getPosition(popup.getElement())); -} - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/progressbar.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/progressbar.js.svn-base deleted file mode 100644 index ab32145..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/progressbar.js.svn-base +++ /dev/null @@ -1,391 +0,0 @@ -// 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 Implementation of a progress bar. - * - * @author arv@google.com (Erik Arvidsson) - * @see ../demos/progressbar.html - */ - - -goog.provide('goog.ui.ProgressBar'); -goog.provide('goog.ui.ProgressBar.Orientation'); - -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.classes'); -goog.require('goog.events'); -goog.require('goog.events.EventType'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.RangeModel'); -goog.require('goog.userAgent'); - - - -/** - * This creates a progress bar object. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Component} - */ -goog.ui.ProgressBar = function(opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - - /** - * The underlying data model for the progress bar. - * @type {goog.ui.RangeModel} - * @private - */ - this.rangeModel_ = new goog.ui.RangeModel; - goog.events.listen(this.rangeModel_, goog.ui.Component.EventType.CHANGE, - this.handleChange_, false, this); -}; -goog.inherits(goog.ui.ProgressBar, goog.ui.Component); - - -/** - * Enum for representing the orientation of the progress bar. - * - * @enum {string} - */ -goog.ui.ProgressBar.Orientation = { - VERTICAL: 'vertical', - HORIZONTAL: 'horizontal' -}; - - -/** - * Map from progress bar orientation to CSS class names. - * @type {Object} - * @private - */ -goog.ui.ProgressBar.ORIENTATION_TO_CSS_NAME_ = {}; -goog.ui.ProgressBar.ORIENTATION_TO_CSS_NAME_[ - goog.ui.ProgressBar.Orientation.VERTICAL] = - goog.getCssName('progress-bar-vertical'); -goog.ui.ProgressBar.ORIENTATION_TO_CSS_NAME_[ - goog.ui.ProgressBar.Orientation.HORIZONTAL] = - goog.getCssName('progress-bar-horizontal'); - - -/** - * Creates the DOM nodes needed for the progress bar - */ -goog.ui.ProgressBar.prototype.createDom = function() { - this.thumbElement_ = this.createThumb_(); - var cs = goog.ui.ProgressBar.ORIENTATION_TO_CSS_NAME_[this.orientation_]; - this.setElementInternal( - this.getDomHelper().createDom('div', cs, this.thumbElement_)); - this.setValueState_(); - this.setMinimumState_(); - this.setMaximumState_(); -}; - - -/** - * Called when the DOM for the component is for sure in the document. - */ -goog.ui.ProgressBar.prototype.enterDocument = function() { - goog.ui.ProgressBar.superClass_.enterDocument.call(this); - this.attachEvents_(); - this.updateUi_(); - - // state live = polite will notify the user of updates, - // but will not interrupt ongoing feedback - goog.dom.a11y.setRole(this.getElement(), 'progressbar'); - goog.dom.a11y.setState(this.getElement(), 'live', 'polite'); -}; - - -/** - * Called when the DOM for the component is for sure in the document. - */ -goog.ui.ProgressBar.prototype.exitDocument = function() { - goog.ui.ProgressBar.superClass_.exitDocument.call(this); - this.detachEvents_(); -}; - - -/** - * This creates the thumb element. - * @private - * @return {HTMLDivElement} The created thumb element. - */ -goog.ui.ProgressBar.prototype.createThumb_ = function() { - return /** @type {HTMLDivElement} */ (this.getDomHelper().createDom('div', - goog.getCssName('progress-bar-thumb'))); -}; - - -/** - * Adds the initial event listeners to the element. - * @private - */ -goog.ui.ProgressBar.prototype.attachEvents_ = function() { - if (goog.userAgent.IE && goog.userAgent.VERSION < 7) { - goog.events.listen(this.getElement(), goog.events.EventType.RESIZE, - this.updateUi_, false, this); - } -}; - - -/** - * Removes the event listeners added by attachEvents_. - * @private - */ -goog.ui.ProgressBar.prototype.detachEvents_ = function() { - if (goog.userAgent.IE && goog.userAgent.VERSION < 7) { - goog.events.unlisten(this.getElement(), goog.events.EventType.RESIZE, - this.updateUi_, false, this); - } -}; - - -/** - * Decorates an existing HTML DIV element as a progress bar input. If the - * element contains a child with a class name of 'progress-bar-thumb' that will - * be used as the thumb. - * @param {HTMLElement} element The HTML element to decorate. - */ -goog.ui.ProgressBar.prototype.decorateInternal = function(element) { - goog.ui.ProgressBar.superClass_.decorateInternal.call(this, element); - goog.dom.classes.add(this.getElement(), goog.ui.ProgressBar. - ORIENTATION_TO_CSS_NAME_[this.orientation_]); - - // find thumb - var thumb = goog.dom.getElementsByTagNameAndClass( - null, goog.getCssName('progress-bar-thumb'), this.getElement())[0]; - if (!thumb) { - thumb = this.createThumb_(); - this.getElement().appendChild(thumb); - } - this.thumbElement_ = thumb; -}; - - -/** - * @return {number} The value. - */ -goog.ui.ProgressBar.prototype.getValue = function() { - return this.rangeModel_.getValue(); -}; - - -/** - * Sets the value - * @param {number} v The value. - */ -goog.ui.ProgressBar.prototype.setValue = function(v) { - this.rangeModel_.setValue(v); - if (this.getElement()) { - this.setValueState_(); - } -}; - - -/** - * Sets the state for a11y of the current value. - * @private - */ -goog.ui.ProgressBar.prototype.setValueState_ = function() { - goog.dom.a11y.setState(this.getElement(), 'valuenow', this.getValue()); -}; - - -/** - * @return {number} The minimum value. - */ -goog.ui.ProgressBar.prototype.getMinimum = function() { - return this.rangeModel_.getMinimum(); -}; - - -/** - * Sets the minimum number - * @param {number} v The minimum value. - */ -goog.ui.ProgressBar.prototype.setMinimum = function(v) { - this.rangeModel_.setMinimum(v); - if (this.getElement()) { - this.setMinimumState_(); - } -}; - - -/** - * Sets the state for a11y of the minimum value. - * @private - */ -goog.ui.ProgressBar.prototype.setMinimumState_ = function() { - goog.dom.a11y.setState(this.getElement(), 'valuemin', this.getMinimum()); -}; - - -/** - * @return {number} The maximum value. - */ -goog.ui.ProgressBar.prototype.getMaximum = function() { - return this.rangeModel_.getMaximum(); -}; - - -/** - * Sets the maximum number - * @param {number} v The maximum value. - */ -goog.ui.ProgressBar.prototype.setMaximum = function(v) { - this.rangeModel_.setMaximum(v); - if (this.getElement()) { - this.setMaximumState_(); - } -}; - - -/** - * Sets the state for a11y of the maximum valiue. - * @private - */ -goog.ui.ProgressBar.prototype.setMaximumState_ = function() { - goog.dom.a11y.setState(this.getElement(), 'valuemax', this.getMaximum()); -}; - - -/** - * - * @type {goog.ui.ProgressBar.Orientation} - * @private - */ -goog.ui.ProgressBar.prototype.orientation_ = - goog.ui.ProgressBar.Orientation.HORIZONTAL; - - -/** - * Call back when the internal range model changes - * @param {goog.events.Event} e The event object. - * @private - */ -goog.ui.ProgressBar.prototype.handleChange_ = function(e) { - this.updateUi_(); - this.dispatchEvent(goog.ui.Component.EventType.CHANGE); -}; - - -/** - * This is called when we need to update the size of the thumb. This happens - * when first created as well as when the value and the orientation changes. - * @private - */ -goog.ui.ProgressBar.prototype.updateUi_ = function() { - if (this.thumbElement_) { - var min = this.getMinimum(); - var max = this.getMaximum(); - var val = this.getValue(); - var ratio = (val - min) / (max - min); - var size = Math.round(ratio * 100); - if (this.orientation_ == goog.ui.ProgressBar.Orientation.VERTICAL) { - // Note(arv): IE up to version 6 has some serious computation bugs when - // using percentages or bottom. We therefore first set the height to - // 100% and measure that and base the top and height on that size instead. - if (goog.userAgent.IE && goog.userAgent.VERSION < 7) { - this.thumbElement_.style.top = 0; - this.thumbElement_.style.height = '100%'; - var h = this.thumbElement_.offsetHeight; - var bottom = Math.round(ratio * h); - this.thumbElement_.style.top = h - bottom + 'px'; - this.thumbElement_.style.height = bottom + 'px'; - } else { - this.thumbElement_.style.top = (100 - size) + '%'; - this.thumbElement_.style.height = size + '%'; - } - } else { - this.thumbElement_.style.width = size + '%'; - } - } -}; - - -/** - * This is called when we need to setup the UI sizes and positions. This - * happens when we create the element and when we change the orientation. - * @private - */ -goog.ui.ProgressBar.prototype.initializeUi_ = function() { - var tStyle = this.thumbElement_.style; - if (this.orientation_ == goog.ui.ProgressBar.Orientation.VERTICAL) { - tStyle.left = 0; - tStyle.width = '100%'; - } else { - tStyle.top = tStyle.left = 0; - tStyle.height = '100%'; - } -}; - - -/** - * Changes the orientation - * @param {goog.ui.ProgressBar.Orientation} orient The orientation. - */ -goog.ui.ProgressBar.prototype.setOrientation = function(orient) { - if (this.orientation_ != orient) { - var oldCss = - goog.ui.ProgressBar.ORIENTATION_TO_CSS_NAME_[this.orientation_]; - var newCss = goog.ui.ProgressBar.ORIENTATION_TO_CSS_NAME_[orient]; - this.orientation_ = orient; - - // Update the DOM - if (this.getElement()) { - goog.dom.classes.swap(this.getElement(), oldCss, newCss); - this.initializeUi_(); - this.updateUi_(); - } - } -}; - - -/** - * @return {goog.ui.ProgressBar.Orientation} The orientation of the - * progress bar. - */ -goog.ui.ProgressBar.prototype.getOrientation = function() { - return this.orientation_; -}; - - -/** @override */ -goog.ui.ProgressBar.prototype.disposeInternal = function() { - this.detachEvents_(); - goog.ui.ProgressBar.superClass_.disposeInternal.call(this); - this.thumbElement_ = null; - this.rangeModel_.dispose(); -}; - - -/** - * @return {?number} The step value used to determine how to round the value. - */ -goog.ui.ProgressBar.prototype.getStep = function() { - return this.rangeModel_.getStep(); -}; - - -/** - * Sets the step value. The step value is used to determine how to round the - * value. - * @param {?number} step The step size. - */ -goog.ui.ProgressBar.prototype.setStep = function(step) { - this.rangeModel_.setStep(step); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/prompt.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/prompt.js.svn-base deleted file mode 100644 index 27f2776..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/prompt.js.svn-base +++ /dev/null @@ -1,394 +0,0 @@ -// 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 DHTML prompt to replace javascript's prompt(). - * - * @see ../demos/prompt.html - */ - - -goog.provide('goog.ui.Prompt'); - -goog.require('goog.Timer'); -goog.require('goog.dom'); -goog.require('goog.events'); -goog.require('goog.events.EventType'); -goog.require('goog.functions'); -goog.require('goog.ui.Component.Error'); -goog.require('goog.ui.Dialog'); -goog.require('goog.ui.Dialog.ButtonSet'); -goog.require('goog.ui.Dialog.DefaultButtonKeys'); -goog.require('goog.ui.Dialog.EventType'); -goog.require('goog.userAgent'); - - - -/** - * Creates an object that represents a prompt (used in place of javascript's - * prompt). The html structure of the prompt is the same as the layout for - * dialog.js except for the addition of a text box which is placed inside the - * "Content area" and has the default class-name 'modal-dialog-userInput' - * - * @param {string} promptTitle The title of the prompt. - * @param {string} promptText The text of the prompt. - * @param {Function} callback The function to call when the user selects Ok or - * Cancel. The function should expect a single argument which represents - * what the user entered into the prompt. If the user presses cancel, the - * value of the argument will be null. - * @param {string=} opt_defaultValue Optional default value that should be in - * the text box when the prompt appears. - * @param {string=} opt_class Optional prefix for the classes. - * @param {boolean=} opt_useIframeForIE For IE, workaround windowed controls - * z-index issue by using a an iframe instead of a div for bg element. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper; see {@link - * goog.ui.Component} for semantics. - * @constructor - * @extends {goog.ui.Dialog} - */ -goog.ui.Prompt = function(promptTitle, promptText, callback, opt_defaultValue, - opt_class, opt_useIframeForIE, opt_domHelper) { - goog.ui.Dialog.call(this, opt_class, opt_useIframeForIE, opt_domHelper); - - /** - * The id of the input element. - * @type {string} - * @private - */ - this.inputElementId_ = this.makeId('ie'); - - this.setTitle(promptTitle); - this.setContent('<label for="' + this.inputElementId_ + '">' + promptText + - '</label><br><br>'); - this.callback_ = callback; - this.defaultValue_ = goog.isDef(opt_defaultValue) ? opt_defaultValue : ''; - - /** @desc label for a dialog button. */ - var MSG_PROMPT_OK = goog.getMsg('OK'); - /** @desc label for a dialog button. */ - var MSG_PROMPT_CANCEL = goog.getMsg('Cancel'); - var buttonSet = new goog.ui.Dialog.ButtonSet(opt_domHelper); - buttonSet.set(goog.ui.Dialog.DefaultButtonKeys.OK, MSG_PROMPT_OK, true); - buttonSet.set(goog.ui.Dialog.DefaultButtonKeys.CANCEL, - MSG_PROMPT_CANCEL, false, true); - this.setButtonSet(buttonSet); -}; -goog.inherits(goog.ui.Prompt, goog.ui.Dialog); - - -/** - * Callback function which is invoked with the response to the prompt - * @type {Function} - * @private - */ -goog.ui.Prompt.prototype.callback_ = goog.nullFunction; - - -/** - * Default value to display in prompt window - * @type {string} - * @private - */ -goog.ui.Prompt.prototype.defaultValue_ = ''; - - -/** - * Element in which user enters response (HTML <input> text box) - * @type {HTMLInputElement} - * @private - */ -goog.ui.Prompt.prototype.userInputEl_ = null; - - -/** - * Tracks whether the prompt is in the process of closing to prevent multiple - * calls to the callback when the user presses enter. - * @type {boolean} - * @private - */ -goog.ui.Prompt.prototype.isClosing_ = false; - - -/** - * Number of rows in the user input element. - * The default is 1 which means use an <input> element. - * @type {number} - * @private - */ -goog.ui.Prompt.prototype.rows_ = 1; - - -/** - * Number of cols in the user input element. - * The default is 0 which means use browser default. - * @type {number} - * @private - */ -goog.ui.Prompt.prototype.cols_ = 0; - - -/** - * The input decorator function. - * @type {function(Element)?} - * @private - */ -goog.ui.Prompt.prototype.inputDecoratorFn_ = null; - - -/** - * A validation function that takes a string and returns true if the string is - * accepted, false otherwise. - * @type {function(string):boolean} - * @private - */ -goog.ui.Prompt.prototype.validationFn_ = goog.functions.TRUE; - - -/** - * Sets the validation function that takes a string and returns true if the - * string is accepted, false otherwise. - * @param {function(string): boolean} fn The validation function to use on user - * input. - */ -goog.ui.Prompt.prototype.setValidationFunction = function(fn) { - this.validationFn_ = fn; -}; - - -/** @override */ -goog.ui.Prompt.prototype.enterDocument = function() { - if (this.inputDecoratorFn_) { - this.inputDecoratorFn_(this.userInputEl_); - } - goog.ui.Prompt.superClass_.enterDocument.call(this); - this.getHandler().listen(this, - goog.ui.Dialog.EventType.SELECT, this.onPromptExit_); - - this.getHandler().listen(this.userInputEl_, - [goog.events.EventType.KEYUP, goog.events.EventType.CHANGE], - this.handleInputChanged_); -}; - - -/** - * Sets an input decorator function. This function will be called in - * #enterDocument and will be passed the input element. This is useful for - * attaching handlers to the input element for specific change events, - * for example. - * @param {function(Element)} inputDecoratorFn A function to call on the input - * element on #enterDocument. - */ -goog.ui.Prompt.prototype.setInputDecoratorFn = function(inputDecoratorFn) { - this.inputDecoratorFn_ = inputDecoratorFn; -}; - - -/** - * Set the number of rows in the user input element. - * A values of 1 means use an <input> element. If the prompt is already - * rendered then you cannot change from <input> to <textarea> or vice versa. - * @param {number} rows Number of rows for user input element. - * @throws {goog.ui.Component.Error.ALREADY_RENDERED} If the component is - * already rendered and an attempt to change between <input> and <textarea> - * is made. - */ -goog.ui.Prompt.prototype.setRows = function(rows) { - if (this.isInDocument()) { - if (this.userInputEl_.tagName.toLowerCase() == 'input') { - if (rows > 1) { - throw Error(goog.ui.Component.Error.ALREADY_RENDERED); - } - } else { - if (rows <= 1) { - throw Error(goog.ui.Component.Error.ALREADY_RENDERED); - } - this.userInputEl_.rows = rows; - } - } - this.rows_ = rows; -}; - - -/** - * @return {number} The number of rows in the user input element. - */ -goog.ui.Prompt.prototype.getRows = function() { - return this.rows_; -}; - - -/** - * Set the number of cols in the user input element. - * @param {number} cols Number of cols for user input element. - */ -goog.ui.Prompt.prototype.setCols = function(cols) { - this.cols_ = cols; - if (this.userInputEl_) { - if (this.userInputEl_.tagName.toLowerCase() == 'input') { - this.userInputEl_.size = cols; - } else { - this.userInputEl_.cols = cols; - } - } -}; - - -/** - * @return {number} The number of cols in the user input element. - */ -goog.ui.Prompt.prototype.getCols = function() { - return this.cols_; -}; - - -/** - * Create the initial DOM representation for the prompt. - */ -goog.ui.Prompt.prototype.createDom = function() { - goog.ui.Prompt.superClass_.createDom.call(this); - - var cls = this.getClass(); - - // add input box to the content - var attrs = { - 'className': goog.getCssName(cls, 'userInput'), - 'value': this.defaultValue_}; - if (this.rows_ == 1) { - // If rows == 1 then use an input element. - this.userInputEl_ = /** @type {HTMLInputElement} */ - (this.getDomHelper().createDom('input', attrs)); - this.userInputEl_.type = 'text'; - if (this.cols_) { - this.userInputEl_.size = this.cols_; - } - } else { - // If rows > 1 then use a textarea. - this.userInputEl_ = /** @type {HTMLInputElement} */ - (this.getDomHelper().createDom('textarea', attrs)); - this.userInputEl_.rows = this.rows_; - if (this.cols_) { - this.userInputEl_.cols = this.cols_; - } - } - - this.userInputEl_.id = this.inputElementId_; - var contentEl = this.getContentElement(); - contentEl.appendChild(this.getDomHelper().createDom( - 'div', {'style': 'overflow: auto'}, this.userInputEl_)); - - if (this.rows_ > 1) { - // Set default button to null so <enter> will work properly in the textarea - this.getButtonSet().setDefault(null); - } -}; - - -/** - * Handles input change events on the input field. Disables the OK button if - * validation fails on the new input value. - * @private - */ -goog.ui.Prompt.prototype.handleInputChanged_ = function() { - this.updateOkButtonState_(); -}; - - -/** - * Set OK button enabled/disabled state based on input. - * @private - */ -goog.ui.Prompt.prototype.updateOkButtonState_ = function() { - var enableOkButton = this.validationFn_(this.userInputEl_.value); - var buttonSet = this.getButtonSet(); - buttonSet.setButtonEnabled(goog.ui.Dialog.DefaultButtonKeys.OK, - enableOkButton); -}; - - -/** - * Causes the prompt to appear, centered on the screen, gives focus - * to the text box, and selects the text - * @param {boolean} visible Whether the dialog should be visible. - */ -goog.ui.Prompt.prototype.setVisible = function(visible) { - goog.ui.Dialog.prototype.setVisible.call(this, visible); - if (visible) { - this.isClosing_ = false; - this.userInputEl_.value = this.defaultValue_; - this.focus(); - this.updateOkButtonState_(); - } -}; - - -/** - * Overrides setFocus to put focus on the input element. - * @override - */ -goog.ui.Prompt.prototype.focus = function() { - if (goog.userAgent.OPERA) { - // select() doesn't focus <input> elements in Opera. - this.userInputEl_.focus(); - } - this.userInputEl_.select(); -}; - - -/** - * Sets the default value of the prompt when it is displayed. - * @param {string} defaultValue The default value to display. - */ -goog.ui.Prompt.prototype.setDefaultValue = function(defaultValue) { - this.defaultValue_ = defaultValue; -}; - - -/** - * Handles the closing of the prompt, invoking the callback function that was - * registered to handle the value returned by the prompt. - * @param {goog.ui.Dialog.Event} e The dialog's selection event. - * @private - */ -goog.ui.Prompt.prototype.onPromptExit_ = function(e) { - /* - * The timeouts below are required for one edge case. If after the dialog - * hides, suppose validation of the input fails which displays an alert. If - * the user pressed the Enter key to dismiss the alert that was displayed it - * can trigger the event handler a second time. This timeout ensures that the - * alert is displayed only after the prompt is able to clean itself up. - */ - if (!this.isClosing_) { - this.isClosing_ = true; - if (e.key == 'ok') { - goog.Timer.callOnce( - goog.bind(this.callback_, this, this.userInputEl_.value), 1); - } else { - goog.Timer.callOnce(goog.bind(this.callback_, this, null), 1); - } - } -}; - - -/** @override */ -goog.ui.Prompt.prototype.disposeInternal = function() { - goog.dom.removeNode(this.userInputEl_); - - goog.events.unlisten(this, goog.ui.Dialog.EventType.SELECT, - this.onPromptExit_, true, this); - - goog.ui.Prompt.superClass_.disposeInternal.call(this); - - this.defaulValue_ = null; - this.userInputEl_ = null; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/prompt_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/prompt_test.html.svn-base deleted file mode 100644 index 30b0ee0..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/prompt_test.html.svn-base +++ /dev/null @@ -1,144 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2010 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.Prompt</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom.selection'); - goog.require('goog.functions'); - goog.require('goog.string'); - goog.require('goog.ui.BidiInput'); - goog.require('goog.ui.Prompt'); - goog.require('goog.userAgent.product'); - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.events'); -</script> -<link rel="stylesheet" type="text/css" href="../css/common.css"/> -<link rel="stylesheet" type="text/css" href="../css/dialog.css"/> -</head> -<body> - -<input type='button' value='Prompt' onclick='newPrompt();' /> - -<script> - -var prompt; - -function setUp() { - document.body.focus(); -} - -function tearDown() { - goog.dispose(prompt); -} - -function testFocusOnInputElement() { - // FF does not perform focus if the window is not active in the first place. - if (goog.userAgent.GECKO && document.hasFocus && !document.hasFocus()) { - return; - } - - var promptResult = undefined; - prompt = new goog.ui.Prompt('title', 'Prompt:', function(result) { - promptResult = result; - }, 'defaultValue'); - prompt.setVisible(true); - - if (goog.userAgent.product.CHROME) { - // For some reason, this test fails non-deterministically on Chrome, - // but only on the test farm. - return; - } - assertEquals('defaultValue', - goog.dom.selection.getText(prompt.userInputEl_)); -} - - -function testValidationFunction() { - var promptResult = undefined; - prompt = new goog.ui.Prompt('title', 'Prompt:', function(result) { - promptResult = result; - }, ''); - prompt.setValidationFunction(goog.functions.not(goog.string.isEmpty)); - prompt.setVisible(true); - - var buttonSet = prompt.getButtonSet(); - var okButton = buttonSet.getButton(goog.ui.Dialog.DefaultButtonKeys.OK); - assertTrue(okButton.disabled); - - prompt.userInputEl_.value = ''; - goog.testing.events.fireKeySequence(prompt.userInputEl_, - goog.events.KeyCodes.SPACE); - assertTrue(okButton.disabled); - prompt.userInputEl_.value = 'foo'; - goog.testing.events.fireKeySequence(prompt.userInputEl_, - goog.events.KeyCodes.X); - assertFalse(okButton.disabled); -} - -function testBidiInput() { - var shalomInHebrew = '\u05e9\u05dc\u05d5\u05dd'; - var promptResult = undefined; - prompt = new goog.ui.Prompt('title', 'Prompt:', goog.functions.NULL, ''); - var bidiInput = new goog.ui.BidiInput(); - prompt.setInputDecoratorFn(goog.bind(bidiInput.decorate, bidiInput)); - prompt.setVisible(true); - - prompt.userInputEl_.value = shalomInHebrew; - goog.testing.events.fireKeySequence(prompt.userInputEl_, - goog.events.KeyCodes.SPACE); - goog.testing.events.fireBrowserEvent( - {'target' : prompt.userInputEl_, 'type' : 'input'}); - bidiInput.inputHandler_.dispatchEvent( - goog.events.InputHandler.EventType.INPUT); - assertEquals('rtl', prompt.userInputEl_.dir); - - prompt.userInputEl_.value = 'shalomInEnglish'; - goog.testing.events.fireKeySequence(prompt.userInputEl_, - goog.events.KeyCodes.SPACE); - goog.testing.events.fireBrowserEvent( - {'target' : prompt.userInputEl_, 'type' : 'input'}); - bidiInput.inputHandler_.dispatchEvent( - goog.events.InputHandler.EventType.INPUT); - assertEquals('ltr', prompt.userInputEl_.dir); - goog.dispose(bidiInput); -} - -function testBidiInput_off() { - var shalomInHebrew = '\u05e9\u05dc\u05d5\u05dd'; - var promptResult = undefined; - prompt = new goog.ui.Prompt('title', 'Prompt:', goog.functions.NULL, ''); - prompt.setVisible(true); - - prompt.userInputEl_.value = shalomInHebrew; - goog.testing.events.fireKeySequence(prompt.userInputEl_, - goog.events.KeyCodes.SPACE); - goog.testing.events.fireBrowserEvent( - {'target' : prompt.userInputEl_, 'type' : 'input'}); - assertEquals('', prompt.userInputEl_.dir); - - prompt.userInputEl_.value = 'shalomInEnglish'; - goog.testing.events.fireKeySequence(prompt.userInputEl_, - goog.events.KeyCodes.SPACE); - assertEquals('', prompt.userInputEl_.dir); -} - -// An interactive test so we can manually see what it looks like. -function newPrompt() { - prompt = new goog.ui.Prompt('title', 'Prompt:', function(result) { - alert('Result: ' + result); - goog.dispose(prompt); - }, 'defaultValue'); - prompt.setVisible(true); -} - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/rangemodel.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/rangemodel.js.svn-base deleted file mode 100644 index 0995437..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/rangemodel.js.svn-base +++ /dev/null @@ -1,302 +0,0 @@ -// 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 Implementation of a range model. This is an implementation of - * the BoundedRangeModel as described by Java at - * http://java.sun.com/javase/6/docs/api/javax/swing/BoundedRangeModel.html. - * - * One good way to understand the range model is to think of a scroll bar for - * a scrollable element. In that case minimum is 0, maximum is scrollHeight, - * value is scrollTop and extent is clientHeight. - * - * Based on http://webfx.eae.net/dhtml/slider/js/range.js - * - * @author arv@google.com (Erik Arvidsson) - */ - -goog.provide('goog.ui.RangeModel'); - -goog.require('goog.events.EventTarget'); -goog.require('goog.ui.Component.EventType'); - - - -/** - * Creates a range model - * @extends {goog.events.EventTarget} - * @constructor - */ -goog.ui.RangeModel = function() { - goog.events.EventTarget.call(this); -}; -goog.inherits(goog.ui.RangeModel, goog.events.EventTarget); - - -/** - * @type {number} - * @private - */ -goog.ui.RangeModel.prototype.value_ = 0; - - -/** - * @type {number} - * @private - */ -goog.ui.RangeModel.prototype.minimum_ = 0; - - -/** - * @type {number} - * @private - */ -goog.ui.RangeModel.prototype.maximum_ = 100; - - -/** - * @type {number} - * @private - */ -goog.ui.RangeModel.prototype.extent_ = 0; - - -/** - * @type {?number} - * @private - */ -goog.ui.RangeModel.prototype.step_ = 1; - - -/** - * This is true if something is changed as a side effect. This happens when for - * example we set the maximum below the current value. - * @type {boolean} - * @private - */ -goog.ui.RangeModel.prototype.isChanging_ = false; - - -/** - * If set to true, we do not fire any change events. - * @type {boolean} - * @private - */ -goog.ui.RangeModel.prototype.mute_ = false; - - -/** - * Sets the model to mute / unmute. - * @param {boolean} muteValue Whether or not to mute the range, i.e., - * suppress any CHANGE events. - */ -goog.ui.RangeModel.prototype.setMute = function(muteValue) { - this.mute_ = muteValue; -}; - - -/** - * Sets the value. - * @param {number} value The new value. - */ -goog.ui.RangeModel.prototype.setValue = function(value) { - value = this.roundToStepWithMin(value); - if (this.value_ != value) { - if (value + this.extent_ > this.maximum_) { - this.value_ = this.maximum_ - this.extent_; - } else if (value < this.minimum_) { - this.value_ = this.minimum_; - } else { - this.value_ = value; - } - if (!this.isChanging_ && !this.mute_) { - this.dispatchEvent(goog.ui.Component.EventType.CHANGE); - } - } -}; - - -/** - * @return {number} the current value. - */ -goog.ui.RangeModel.prototype.getValue = function() { - return this.roundToStepWithMin(this.value_); -}; - - -/** - * Sets the extent. The extent is the 'size' of the value. - * @param {number} extent The new extent. - */ -goog.ui.RangeModel.prototype.setExtent = function(extent) { - extent = this.roundToStepWithMin(extent); - if (this.extent_ != extent) { - if (extent < 0) { - this.extent_ = 0; - } else if (this.value_ + extent > this.maximum_) { - this.extent_ = this.maximum_ - this.value_; - } else { - this.extent_ = extent; - } - if (!this.isChanging_ && !this.mute_) { - this.dispatchEvent(goog.ui.Component.EventType.CHANGE); - } - } -}; - - -/** - * @return {number} The extent for the range model. - */ -goog.ui.RangeModel.prototype.getExtent = function() { - return this.roundToStep(this.extent_); -}; - - -/** - * Sets the minimum - * @param {number} minimum The new minimum. - */ -goog.ui.RangeModel.prototype.setMinimum = function(minimum) { - // Don't round minimum because it is the base - if (this.minimum_ != minimum) { - var oldIsChanging = this.isChanging_; - this.isChanging_ = true; - - this.minimum_ = minimum; - - if (minimum + this.extent_ > this.maximum_) { - this.extent_ = this.maximum_ - this.minimum_; - } - if (minimum > this.value_) { - this.setValue(minimum); - } - if (minimum > this.maximum_) { - this.extent_ = 0; - this.setMaximum(minimum); - this.setValue(minimum); - } - - - this.isChanging_ = oldIsChanging; - if (!this.isChanging_ && !this.mute_) { - this.dispatchEvent(goog.ui.Component.EventType.CHANGE); - } - } -}; - - -/** - * @return {number} The minimum value for the range model. - */ -goog.ui.RangeModel.prototype.getMinimum = function() { - return this.roundToStepWithMin(this.minimum_); -}; - - -/** - * Sets the maximum - * @param {number} maximum The new maximum. - */ -goog.ui.RangeModel.prototype.setMaximum = function(maximum) { - maximum = this.roundToStepWithMin(maximum); - if (this.maximum_ != maximum) { - var oldIsChanging = this.isChanging_; - this.isChanging_ = true; - - this.maximum_ = maximum; - - if (maximum < this.value_ + this.extent_) { - this.setValue(maximum - this.extent_); - } - if (maximum < this.minimum_) { - this.extent_ = 0; - this.setMinimum(maximum); - this.setValue(this.maximum_); - } - if (maximum < this.minimum_ + this.extent_) { - this.extent_ = this.maximum_ - this.minimum_; - } - - this.isChanging_ = oldIsChanging; - if (!this.isChanging_ && !this.mute_) { - this.dispatchEvent(goog.ui.Component.EventType.CHANGE); - } - } -}; - - -/** - * @return {number} The maximimum value for the range model. - */ -goog.ui.RangeModel.prototype.getMaximum = function() { - return this.roundToStepWithMin(this.maximum_); -}; - - -/** - * Returns the step value. The step value is used to determine how to round the - * value. - * @return {?number} The maximimum value for the range model. - */ -goog.ui.RangeModel.prototype.getStep = function() { - return this.step_; -}; - - -/** - * Sets the step. The step value is used to determine how to round the value. - * @param {?number} step The step size. - */ -goog.ui.RangeModel.prototype.setStep = function(step) { - if (this.step_ != step) { - this.step_ = step; - - // adjust value, extent and maximum - var oldIsChanging = this.isChanging_; - this.isChanging_ = true; - - this.setMaximum(this.getMaximum()); - this.setExtent(this.getExtent()); - this.setValue(this.getValue()); - - this.isChanging_ = oldIsChanging; - if (!this.isChanging_ && !this.mute_) { - this.dispatchEvent(goog.ui.Component.EventType.CHANGE); - } - } -}; - - -/** - * Rounds to the closest step using the minimum value as the base. - * @param {number} value The number to round. - * @return {number} The number rounded to the closest step. - */ -goog.ui.RangeModel.prototype.roundToStepWithMin = function(value) { - if (this.step_ == null) return value; - return this.minimum_ + - Math.round((value - this.minimum_) / this.step_) * this.step_; -}; - - -/** - * Rounds to the closest step. - * @param {number} value The number to round. - * @return {number} The number rounded to the closest step. - */ -goog.ui.RangeModel.prototype.roundToStep = function(value) { - if (this.step_ == null) return value; - return Math.round(value / this.step_) * this.step_; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/rangemodel_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/rangemodel_test.html.svn-base deleted file mode 100644 index c2a560c..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/rangemodel_test.html.svn-base +++ /dev/null @@ -1,270 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2006 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.RangeModel</title> -<script src="../base.js"></script> -<script> - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.RangeModel'); -</script> -</head> -<body> -<script> - - function reset(rm, step) { - rm.setStep(step || 1); - rm.setExtent(0); - rm.setMinimum(0); - rm.setMaximum(100); - rm.setValue(0); - } - - function getDescriptiveString(rm) { - return rm.getMinimum() + ' < ' + rm.getValue() + '[' + rm.getExtent() + - '] < ' + rm.getMaximum(); - } - - function testValue() { - var rm = new goog.ui.RangeModel; - - assertEquals(0, rm.getValue()); - rm.setValue(50); - assertEquals(50, rm.getValue()); - - // setting smaller than min should keep min - rm.setValue(-1); - assertEquals(0, rm.getValue()); - - // setting larger than max should keep max - extent - rm.setValue(101); - assertEquals(100, rm.getValue()); - rm.setValue(0); - rm.setExtent(10); - rm.setValue(100); - assertEquals(90, rm.getValue()); - - //////////////// - // Change step - reset(rm, 3); - - assertEquals(0, rm.getValue()); - rm.setValue(50); - assertEquals(51, rm.getValue()); - - // setting smaller than min should keep min - rm.setValue(-1); - assertEquals(0, rm.getValue()); - - // setting larger than max should keep max - extent - rm.setValue(101); - assertEquals(99, rm.getValue()); - rm.setValue(0); - rm.setExtent(10); - rm.setValue(100); - assertEquals(90, rm.getValue()); - - } - - function testMinium() { - var rm = new goog.ui.RangeModel; - - rm.setValue(50); - rm.setMinimum(10); - assertEquals(10, rm.getMinimum()); - - reset(rm); - - // setting larger than value should change value - rm.setMinimum(10); - assertEquals(10, rm.getMinimum()); - assertEquals(10, rm.getValue()); - - // setting larger than max should set max = min - rm.setMinimum(200); - assertEquals(200, rm.getMinimum()); - assertEquals(200, rm.getValue()); - assertEquals(200, rm.getMaximum()); - assertEquals(0, rm.getExtent()); - - reset(rm); - - // should change extent - rm.setExtent(10); - rm.setMinimum(95); - assertEquals(95, rm.getMinimum()); - assertEquals(95, rm.getValue()); - assertEquals(100, rm.getMaximum()); - assertEquals(5, rm.getExtent()); - - //////////////// - // Change step - reset(rm, 3); - - rm.setValue(50); - rm.setMinimum(10); - assertEquals(10, rm.getMinimum()); - - reset(rm, 3); - - // setting larger than value should change value - rm.setMinimum(10); - assertEquals(10, rm.getMinimum()); - assertEquals(10, rm.getValue()); - - // setting larger than max should set max = min - rm.setMinimum(200); - assertEquals(200, rm.getMinimum()); - assertEquals(200, rm.getValue()); - assertEquals(200, rm.getMaximum()); - assertEquals(0, rm.getExtent()); - - reset(rm, 3); - - // should change extent - rm.setExtent(10); // 0 < 0[9] < 99 - rm.setMinimum(95); // 95 < 95[3] < 98 - assertEquals(95, rm.getMinimum()); - assertEquals(95, rm.getValue()); - assertEquals(98, rm.getMaximum()); - assertEquals(3, rm.getExtent()); - } - - function testMaximum() { - var rm = new goog.ui.RangeModel; - - rm.setMaximum(50); - assertEquals(50, rm.getMaximum()); - - reset(rm); - - // setting to smaller than minimum should change minimum, value and extent - rm.setValue(5); - rm.setExtent(10); - rm.setMinimum(50); - rm.setMaximum(40); - assertEquals(40, rm.getMaximum()); - assertEquals(0, rm.getExtent()); - assertEquals(40, rm.getValue()); - assertEquals(40, rm.getMinimum()); - - reset(rm); - - // setting smaller than value should change value to max - extent - rm.setExtent(10); - rm.setValue(50); - rm.setMaximum(40); - assertEquals(40, rm.getMaximum()); - assertEquals(30, rm.getValue()); - - reset(rm); - - // should change value, and keep extent constant, - // unless extent is > max - min. - rm.setExtent(10); - rm.setValue(90); - rm.setMaximum(95); - assertEquals(95, rm.getMaximum()); - assertEquals(10, rm.getExtent()); - assertEquals(85, rm.getValue()); - - //////////////// - // Change step - reset(rm, 3); - - rm.setMaximum(50); // 0 < 0[0] < 51 - assertEquals(51, rm.getMaximum()); - - reset(rm, 3); - - // setting to smaller than minimum should change minimum, value and extent - rm.setValue(5); // 0 < 6[0] < 99 - rm.setExtent(10); // 0 < 6[9] < 99 - rm.setMinimum(50); // 50 < 50[9] < 98 - rm.setMaximum(40); // 41 < 41[0] < 41 - assertEquals(41, rm.getMaximum()); - assertEquals(0, rm.getExtent()); - assertEquals(41, rm.getValue()); - assertEquals(41, rm.getMinimum()); - - reset(rm, 3); - - // setting smaller than value should change value to max - extent - rm.setExtent(10); // 0 < 0[9] < 99 - rm.setValue(50); // 0 < 51[9] < 99 - rm.setMaximum(40); // 0 < 30[9] < 39 - assertEquals(39, rm.getMaximum()); - assertEquals(30, rm.getValue()); - - reset(rm, 3); - - // should change value, and keep extent constant, - // unless extent is > max - min. - rm.setExtent(10); // 0 < 0[9] < 99 - rm.setValue(90); // 0 < 90[9] < 99 - rm.setMaximum(95); // 0 < 90[6] < 96 - assertEquals(96, rm.getMaximum()); - assertEquals(87, rm.getValue()); - assertEquals(9, rm.getExtent()); - } - - function testExtent() { - var rm = new goog.ui.RangeModel; - - rm.setExtent(10); - assertEquals(10, rm.getExtent()); - - rm.setExtent(-10); - assertEquals(0, rm.getExtent()); - - rm.setValue(50); - rm.setExtent(100); - assertEquals(50, rm.getExtent()); - assertEquals(50, rm.getValue()); - - //////////////// - // Change step - reset(rm, 3); - - rm.setExtent(10); // 0 < 0[9] < 99 - assertEquals(9, rm.getExtent()); - - rm.setExtent(-10); - assertEquals(0, rm.getExtent()); - - rm.setValue(50); // 0 < 51[9] < 99 - rm.setExtent(100); // 0 < 51[48] < 99 - assertEquals(48, rm.getExtent()); - assertEquals(51, rm.getValue()); - } - - function testRoundToStep() { - var rm = new goog.ui.RangeModel; - rm.setStep(0.5); - - assertEquals(1, rm.roundToStep(1)); - assertEquals(0.5, rm.roundToStep(0.5)); - assertEquals(1, rm.roundToStep(0.75)); - assertEquals(0.5, rm.roundToStep(0.74)); - } - - function testRoundToStepWithMin() { - var rm = new goog.ui.RangeModel; - rm.setStep(0.5); - rm.setMinimum(0.25); - - assertEquals(1.25, rm.roundToStepWithMin(1)); - assertEquals(0.75, rm.roundToStepWithMin(0.5)); - assertEquals(0.75, rm.roundToStepWithMin(0.75)); - assertEquals(0.75, rm.roundToStepWithMin(0.74)); - } - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/ratings.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/ratings.js.svn-base deleted file mode 100644 index 3ce08c9..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/ratings.js.svn-base +++ /dev/null @@ -1,441 +0,0 @@ -// 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 A base ratings widget that allows the user to select a rating, - * like "star video" in Google Video. This fires a "change" event when the user - * selects a rating. - * - * Keyboard: - * ESC = Clear (if supported) - * Home = 1 star - * End = Full rating - * Left arrow = Decrease rating - * Right arrow = Increase rating - * 0 = Clear (if supported) - * 1 - 9 = nth star - * - * @see ../demos/ratings.html - */ - -goog.provide('goog.ui.Ratings'); -goog.provide('goog.ui.Ratings.EventType'); - -goog.require('goog.dom.a11y'); -goog.require('goog.dom.classes'); -goog.require('goog.events.EventType'); -goog.require('goog.ui.Component'); - - - -/** - * A UI Control used for rating things, i.e. videos on Google Video. - * @param {Array.<string>=} opt_ratings Ratings. Default: [1,2,3,4,5]. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Component} - */ -goog.ui.Ratings = function(opt_ratings, opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - - /** - * Ordered ratings that can be picked, Default: [1,2,3,4,5] - * @type {Array.<string>} - * @private - */ - this.ratings_ = opt_ratings || ['1', '2', '3', '4', '5']; - - /** - * Array containing references to the star elements - * @type {Array.<Element>} - * @private - */ - this.stars_ = []; -}; -goog.inherits(goog.ui.Ratings, goog.ui.Component); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.Ratings.CSS_CLASS = goog.getCssName('goog-ratings'); - - -/** - * The last index to be highlighted - * @type {number} - * @private - */ -goog.ui.Ratings.prototype.highlightedIndex_ = -1; - - -/** - * The currently selected index - * @type {number} - * @private - */ -goog.ui.Ratings.prototype.selectedIndex_ = -1; - - -/** - * An attached form field to set the value to - * @type {HTMLInputElement|HTMLSelectElement|null} - * @private - */ -goog.ui.Ratings.prototype.attachedFormField_ = null; - - -/** - * Enums for Ratings event type. - * @enum {string} - */ -goog.ui.Ratings.EventType = { - CHANGE: 'change', - HIGHLIGHT_CHANGE: 'highlightchange', - HIGHLIGHT: 'highlight', - UNHIGHLIGHT: 'unhighlight' -}; - - -/** - * Decorate a HTML structure already in the document. Expects the structure: - * <pre> - * - div - * - select - * - option 1 #text = 1 star - * - option 2 #text = 2 stars - * - option 3 #text = 3 stars - * - option N (where N is max number of ratings) - * </pre> - * - * The div can contain other elements for graceful degredation, but they will be - * hidden when the decoration occurs. - * - * @param {Element} el Div element to decorate. - */ -goog.ui.Ratings.prototype.decorateInternal = function(el) { - var select = el.getElementsByTagName('select')[0]; - if (!select) { - throw Error('Can not decorate ' + el + ', with Ratings. Must ' + - 'contain select box'); - } - this.ratings_.length = 0; - for (var i = 0, n = select.options.length; i < n; i++) { - var option = select.options[i]; - this.ratings_.push(option.text); - } - this.setSelectedIndex(select.selectedIndex); - select.style.display = 'none'; - this.attachedFormField_ = select; - this.createDom(); - el.insertBefore(this.getElement(), select); -}; - - -/** - * Render the rating widget inside the provided element. This will override the - * current content of the element. - */ -goog.ui.Ratings.prototype.enterDocument = function() { - var el = this.getElement(); - el.tabIndex = 0; - goog.dom.classes.add(el, this.getCssClass()); - goog.dom.a11y.setRole(el, 'slider'); - goog.dom.a11y.setState(el, 'valuemin', 0); - var max = this.ratings_.length - 1; - goog.dom.a11y.setState(el, 'valuemax', max); - var handler = this.getHandler(); - handler.listen(el, 'keydown', this.onKeyDown_); - - // Create the elements for the stars - for (var i = 0; i < this.ratings_.length; i++) { - var star = this.getDomHelper().createDom('span', { - 'title': this.ratings_[i], - 'class': this.getClassName_(i, false), - 'index': i}); - this.stars_.push(star); - el.appendChild(star); - } - - handler.listen(el, goog.events.EventType.CLICK, this.onClick_); - handler.listen(el, goog.events.EventType.MOUSEOUT, this.onMouseOut_); - handler.listen(el, goog.events.EventType.MOUSEOVER, this.onMouseOver_); - - this.highlightIndex_(this.selectedIndex_); -}; - - -/** - * Should be called when the widget is removed from the document but may be - * reused. This removes all the listeners the widget has attached and destroys - * the DOM nodes it uses. - */ -goog.ui.Ratings.prototype.exitDocument = function() { - goog.ui.Ratings.superClass_.exitDocument.call(this); - for (var i = 0; i < this.stars_.length; i++) { - this.getDomHelper().removeNode(this.stars_[i]); - } - this.stars_.length = 0; -}; - - -/** @override */ -goog.ui.Ratings.prototype.disposeInternal = function() { - goog.ui.Ratings.superClass_.disposeInternal.call(this); - this.ratings_.length = 0; - this.rendered_ = false; -}; - - -/** - * Returns the base CSS class used by subcomponents of this component. - * @return {string} Component-specific CSS class. - */ -goog.ui.Ratings.prototype.getCssClass = function() { - return goog.ui.Ratings.CSS_CLASS; -}; - - -/** - * Sets the selected index. If the provided index is greater than the number of - * ratings then the max is set. 0 is the first item, -1 is no selection. - * @param {number} index The index of the rating to select. - */ -goog.ui.Ratings.prototype.setSelectedIndex = function(index) { - index = Math.max(-1, Math.min(index, this.ratings_.length - 1)); - if (index != this.selectedIndex_) { - this.selectedIndex_ = index; - this.highlightIndex_(this.selectedIndex_); - if (this.attachedFormField_) { - if (this.attachedFormField_.tagName == 'SELECT') { - this.attachedFormField_.selectedIndex = index; - } else { - this.attachedFormField_.value = - /** @type {string} */ (this.getValue()); - } - goog.dom.a11y.setState(this.getElement(), - 'valuenow', - this.ratings_[index]); - } - this.dispatchEvent(goog.ui.Ratings.EventType.CHANGE); - } -}; - - -/** - * @return {number} The index of the currently selected rating. - */ -goog.ui.Ratings.prototype.getSelectedIndex = function() { - return this.selectedIndex_; -}; - - -/** - * Returns the rating value of the currently selected rating - * @return {?string} The value of the currently selected rating (or null). - */ -goog.ui.Ratings.prototype.getValue = function() { - return this.selectedIndex_ == -1 ? null : this.ratings_[this.selectedIndex_]; -}; - - -/** - * Returns the index of the currently highlighted rating, -1 if the mouse isn't - * currently over the widget - * @return {number} The index of the currently highlighted rating. - */ -goog.ui.Ratings.prototype.getHighlightedIndex = function() { - return this.highlightedIndex_; -}; - - -/** - * Returns the value of the currently highlighted rating, null if the mouse - * isn't currently over the widget - * @return {?string} The value of the currently highlighted rating, or null. - */ -goog.ui.Ratings.prototype.getHighlightedValue = function() { - return this.highlightedIndex_ == -1 ? null : - this.ratings_[this.highlightedIndex_]; -}; - - -/** - * Sets the array of ratings that the comonent - * @param {Array.<string>} ratings Array of value to use as ratings. - */ -goog.ui.Ratings.prototype.setRatings = function(ratings) { - this.ratings_ = ratings; - // TODO(user): If rendered update stars -}; - - -/** - * Gets the array of ratings that the component - * @return {Array.<string>} Array of ratings. - */ -goog.ui.Ratings.prototype.getRatings = function() { - return this.ratings_; -}; - - -/** - * Attaches an input or select element to the ratings widget. The value or - * index of the field will be updated along with the ratings widget. - * @param {HTMLSelectElement|HTMLInputElement} field The field to attach to. - */ -goog.ui.Ratings.prototype.setAttachedFormField = function(field) { - this.attachedFormField_ = field; -}; - - -/** - * Returns the attached input or select element to the ratings widget. - * @return {HTMLSelectElement|HTMLInputElement|null} The attached form field. - */ -goog.ui.Ratings.prototype.getAttachedFormField = function() { - return this.attachedFormField_; -}; - - -/** - * Handle the mouse moving over a star. - * @param {goog.events.BrowserEvent} e The browser event. - * @private - */ -goog.ui.Ratings.prototype.onMouseOver_ = function(e) { - if (goog.isDef(e.target.index)) { - var n = e.target.index; - if (this.highlightedIndex_ != n) { - this.highlightIndex_(n); - this.highlightedIndex_ = n; - this.dispatchEvent(goog.ui.Ratings.EventType.HIGHLIGHT_CHANGE); - this.dispatchEvent(goog.ui.Ratings.EventType.HIGHLIGHT); - } - } -}; - - -/** - * Handle the mouse moving over a star. - * @param {goog.events.BrowserEvent} e The browser event. - * @private - */ -goog.ui.Ratings.prototype.onMouseOut_ = function(e) { - // Only remove the highlight if the mouse is not moving to another star - if (e.relatedTarget && !goog.isDef(e.relatedTarget.index)) { - this.highlightIndex_(this.selectedIndex_); - this.highlightedIndex_ = -1; - this.dispatchEvent(goog.ui.Ratings.EventType.HIGHLIGHT_CHANGE); - this.dispatchEvent(goog.ui.Ratings.EventType.UNHIGHLIGHT); - } -}; - - -/** - * Handle the mouse moving over a star. - * @param {goog.events.BrowserEvent} e The browser event. - * @private - */ -goog.ui.Ratings.prototype.onClick_ = function(e) { - if (goog.isDef(e.target.index)) { - this.setSelectedIndex(e.target.index); - } -}; - - -/** - * Handle the key down event. 0 = unselected in this case, 1 = the first rating - * @param {goog.events.BrowserEvent} e The browser event. - * @private - */ -goog.ui.Ratings.prototype.onKeyDown_ = function(e) { - switch (e.keyCode) { - case 27: // esc - this.setSelectedIndex(-1); - break; - case 36: // home - this.setSelectedIndex(0); - break; - case 35: // end - this.setSelectedIndex(this.ratings_.length); - break; - case 37: // left arrow - this.setSelectedIndex(this.getSelectedIndex() - 1); - break; - case 39: // right arrow - this.setSelectedIndex(this.getSelectedIndex() + 1); - break; - default: - // Detected a numeric key stroke, such as 0 - 9. 0 clears, 1 is first - // star, 9 is 9th star or last if there are less than 9 stars. - var num = parseInt(String.fromCharCode(e.keyCode), 10); - if (!isNaN(num)) { - this.setSelectedIndex(num - 1); - } - } -}; - - -/** - * Highlights the ratings up to the selected index - * @param {number} n Index to highlight. - * @private - */ -goog.ui.Ratings.prototype.highlightIndex_ = function(n) { - for (var i = 0, star; star = this.stars_[i]; i++) { - goog.dom.classes.set(star, this.getClassName_(i, i <= n)); - } -}; - - -/** - * Get the class name for a given rating. All stars have the class: - * goog-ratings-star. - * Other possible classnames dependent on position and state are: - * goog-ratings-firststar-on - * goog-ratings-firststar-off - * goog-ratings-midstar-on - * goog-ratings-midstar-off - * goog-ratings-laststar-on - * goog-ratings-laststar-off - * @param {number} i Index to get class name for. - * @param {boolean} on Whether it should be on. - * @return {string} The class name. - * @private - */ -goog.ui.Ratings.prototype.getClassName_ = function(i, on) { - var className; - var baseClass = this.getCssClass(); - - if (i === 0) { - className = goog.getCssName(baseClass, 'firststar'); - } else if (i == this.ratings_.length - 1) { - className = goog.getCssName(baseClass, 'laststar'); - } else { - className = goog.getCssName(baseClass, 'midstar'); - } - - if (on) { - className = goog.getCssName(className, 'on'); - } else { - className = goog.getCssName(className, 'off'); - } - - return goog.getCssName(baseClass, 'star') + ' ' + className; -}; - - diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/registry.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/registry.js.svn-base deleted file mode 100644 index 71f6b63..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/registry.js.svn-base +++ /dev/null @@ -1,167 +0,0 @@ -// 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 Global renderer and decorator registry. - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.registry'); - -goog.require('goog.dom.classes'); - - -/** - * Given a {@link goog.ui.Component} constructor, returns an instance of its - * default renderer. If the default renderer is a singleton, returns the - * singleton instance; otherwise returns a new instance of the renderer class. - * @param {Function} componentCtor Component constructor function (for example - * {@code goog.ui.Button}). - * @return {goog.ui.ControlRenderer?} Renderer instance (for example the - * singleton instance of {@code goog.ui.ButtonRenderer}), or null if - * no default renderer was found. - */ -goog.ui.registry.getDefaultRenderer = function(componentCtor) { - // Locate the default renderer based on the constructor's unique ID. If no - // renderer is registered for this class, walk up the superClass_ chain. - var key; - /** @type {Function|undefined} */ var rendererCtor; - while (componentCtor) { - key = goog.getUid(componentCtor); - if ((rendererCtor = goog.ui.registry.defaultRenderers_[key])) { - break; - } - componentCtor = componentCtor.superClass_ ? - componentCtor.superClass_.constructor : null; - } - - // If the renderer has a static getInstance method, return the singleton - // instance; otherwise create and return a new instance. - if (rendererCtor) { - return goog.isFunction(rendererCtor.getInstance) ? - rendererCtor.getInstance() : new rendererCtor(); - } - - return null; -}; - - -/** - * Sets the default renderer for the given {@link goog.ui.Component} - * constructor. - * @param {Function} componentCtor Component constructor function (for example - * {@code goog.ui.Button}). - * @param {Function} rendererCtor Renderer constructor function (for example - * {@code goog.ui.ButtonRenderer}). - * @throws {Error} If the arguments aren't functions. - */ -goog.ui.registry.setDefaultRenderer = function(componentCtor, rendererCtor) { - // In this case, explicit validation has negligible overhead (since each - // renderer is only registered once), and helps catch subtle bugs. - if (!goog.isFunction(componentCtor)) { - throw Error('Invalid component class ' + componentCtor); - } - if (!goog.isFunction(rendererCtor)) { - throw Error('Invalid renderer class ' + rendererCtor); - } - - // Map the component constructor's unique ID to the renderer constructor. - var key = goog.getUid(componentCtor); - goog.ui.registry.defaultRenderers_[key] = rendererCtor; -}; - - -/** - * Returns the {@link goog.ui.Component} instance created by the decorator - * factory function registered for the given CSS class name, or null if no - * decorator factory function was found. - * @param {string} className CSS class name. - * @return {goog.ui.Component?} Component instance. - */ -goog.ui.registry.getDecoratorByClassName = function(className) { - return className in goog.ui.registry.decoratorFunctions_ ? - goog.ui.registry.decoratorFunctions_[className]() : null; -}; - - -/** - * Maps a CSS class name to a function that returns a new instance of - * {@link goog.ui.Component} or a subclass, suitable to decorate an element - * that has the specified CSS class. - * @param {string} className CSS class name. - * @param {Function} decoratorFn No-argument function that returns a new - * instance of a {@link goog.ui.Component} to decorate an element. - * @throws {Error} If the class name or the decorator function is invalid. - */ -goog.ui.registry.setDecoratorByClassName = function(className, decoratorFn) { - // In this case, explicit validation has negligible overhead (since each - // decorator is only registered once), and helps catch subtle bugs. - if (!className) { - throw Error('Invalid class name ' + className); - } - if (!goog.isFunction(decoratorFn)) { - throw Error('Invalid decorator function ' + decoratorFn); - } - - goog.ui.registry.decoratorFunctions_[className] = decoratorFn; -}; - - -/** - * Returns an instance of {@link goog.ui.Component} or a subclass suitable to - * decorate the given element, based on its CSS class. - * @param {Element} element Element to decorate. - * @return {goog.ui.Component?} Component to decorate the element (null if - * none). - */ -goog.ui.registry.getDecorator = function(element) { - var decorator; - var classNames = goog.dom.classes.get(element); - for (var i = 0, len = classNames.length; i < len; i++) { - if ((decorator = goog.ui.registry.getDecoratorByClassName(classNames[i]))) { - return decorator; - } - } - return null; -}; - - -/** - * Resets the global renderer and decorator registry. - */ -goog.ui.registry.reset = function() { - goog.ui.registry.defaultRenderers_ = {}; - goog.ui.registry.decoratorFunctions_ = {}; -}; - - -/** - * Map of {@link goog.ui.Component} constructor unique IDs to the constructors - * of their default {@link goog.ui.Renderer}s. - * @type {Object} - * @private - */ -goog.ui.registry.defaultRenderers_ = {}; - - -/** - * Map of CSS class names to registry factory functions. The keys are - * class names. The values are function objects that return new instances - * of {@link goog.ui.registry} or one of its subclasses, suitable to - * decorate elements marked with the corresponding CSS class. Used by - * containers while decorating their children. - * @type {Object} - * @private - */ -goog.ui.registry.decoratorFunctions_ = {}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/registry_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/registry_test.html.svn-base deleted file mode 100644 index a7a8a58..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/registry_test.html.svn-base +++ /dev/null @@ -1,237 +0,0 @@ -<!DOCTYPE html> -<!-- Author: attila@google.com (Attila Bodis) --> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.registry</title> - <script src="../base.js"></script> - <script> - goog.require('goog.object'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.registry'); - </script> -</head> -<body> - <div id="x" class="fake-component-x"></div> - <div id="y" class="fake-component-y fake-component-x"></div> - <div id="z" class="fake-component-z"></div> - <div id="u"></div> - <script> - // Fake component and renderer implementations, for testing only. - - // UnknownComponent has no default renderer or decorator registered. - function UnknownComponent() { - } - - // FakeComponentX's default renderer is FakeRenderer. It also has a - // decorator. - function FakeComponentX() { - this.element = null; - } - - FakeComponentX.prototype.decorate = function(element) { - this.element = element; - }; - - // FakeComponentY doesn't have an explicitly registered default - // renderer; it should inherit the default renderer from its superclass. - // It does have a decorator registered. - function FakeComponentY() { - FakeComponentX.call(this); - } - goog.inherits(FakeComponentY, FakeComponentX); - - // FakeComponentZ is just another component. Its default renderer is - // FakeSingletonRenderer, but it has no decorator registered. - function FakeComponentZ() { - } - - // FakeRenderer is a stateful renderer. - function FakeRenderer() { - } - - // FakeSingletonRenderer is a stateless renderer that can be used as a - // singleton. - function FakeSingletonRenderer() { - } - - FakeSingletonRenderer.instance_ = new FakeSingletonRenderer(); - - FakeSingletonRenderer.getInstance = function() { - return FakeSingletonRenderer.instance_; - }; - - function setUp() { - goog.ui.registry.setDefaultRenderer(FakeComponentX, FakeRenderer); - goog.ui.registry.setDefaultRenderer(FakeComponentZ, - FakeSingletonRenderer); - - goog.ui.registry.setDecoratorByClassName('fake-component-x', - function() { - return new FakeComponentX(); - }); - goog.ui.registry.setDecoratorByClassName('fake-component-y', - function() { - return new FakeComponentY(); - }); - } - - function tearDown() { - goog.ui.registry.reset(); - } - - function testGetDefaultRenderer() { - var rx1 = goog.ui.registry.getDefaultRenderer(FakeComponentX); - var rx2 = goog.ui.registry.getDefaultRenderer(FakeComponentX); - assertTrue('FakeComponentX\'s default renderer must be a FakeRenderer', - rx1 instanceof FakeRenderer); - assertNotEquals('Each call to getDefaultRenderer must create a new ' + - 'FakeRenderer', rx1, rx2); - - var ry = goog.ui.registry.getDefaultRenderer(FakeComponentY); - assertTrue('FakeComponentY must inherit its default renderer from ' + - 'its superclass', ry instanceof FakeRenderer); - - var rz1 = goog.ui.registry.getDefaultRenderer(FakeComponentZ); - var rz2 = goog.ui.registry.getDefaultRenderer(FakeComponentZ); - assertTrue('FakeComponentZ\' default renderer must be a ' + - 'FakeSingletonRenderer', rz1 instanceof FakeSingletonRenderer); - assertEquals('Each call to getDefaultRenderer must return the ' + - 'singleton instance of FakeSingletonRenderer', rz1, rz2); - - assertNull('getDefaultRenderer must return null for unknown component', - goog.ui.registry.getDefaultRenderer(UnknownComponent)); - } - - function testSetDefaultRenderer() { - var rx1 = goog.ui.registry.getDefaultRenderer(FakeComponentX); - assertTrue('FakeComponentX\'s renderer must be FakeRenderer', - rx1 instanceof FakeRenderer); - - var ry1 = goog.ui.registry.getDefaultRenderer(FakeComponentY); - assertTrue('FakeComponentY must inherit its default renderer from ' + - 'its superclass', ry1 instanceof FakeRenderer); - - goog.ui.registry.setDefaultRenderer(FakeComponentX, - FakeSingletonRenderer); - - var rx2 = goog.ui.registry.getDefaultRenderer(FakeComponentX); - assertEquals('FakeComponentX\'s renderer must be FakeSingletonRenderer', - FakeSingletonRenderer.getInstance(), rx2); - - var ry2 = goog.ui.registry.getDefaultRenderer(FakeComponentY); - assertEquals('FakeComponentY must inherit the new default renderer ' + - 'from its superclass', FakeSingletonRenderer.getInstance(), ry2); - - goog.ui.registry.setDefaultRenderer(FakeComponentY, FakeRenderer); - - var rx3 = goog.ui.registry.getDefaultRenderer(FakeComponentX); - assertEquals('FakeComponentX\'s renderer must be unchanged', - FakeSingletonRenderer.getInstance(), rx3); - - var ry3 = goog.ui.registry.getDefaultRenderer(FakeComponentY); - assertTrue('FakeComponentY must now have its own default renderer', - ry3 instanceof FakeRenderer); - - assertThrows('Calling setDefaultRenderer with non-function component ' + - 'must throw error', - function() { - goog.ui.registry.setDefaultRenderer('Not function', FakeRenderer); - }); - - assertThrows('Calling setDefaultRenderer with non-function renderer ' + - 'must throw error', - function() { - goog.ui.registry.setDefaultRenderer(FakeComponentX, 'Not function'); - }); - } - - function testGetDecoratorByClassName() { - var dx1 = goog.ui.registry.getDecoratorByClassName('fake-component-x'); - var dx2 = goog.ui.registry.getDecoratorByClassName('fake-component-x'); - assertTrue('fake-component-x must be decorated by a FakeComponentX', - dx1 instanceof FakeComponentX); - assertNotEquals('Each call to getDecoratorByClassName must return a ' + - 'new FakeComponentX instance', dx1, dx2); - - var dy1 = goog.ui.registry.getDecoratorByClassName('fake-component-y'); - var dy2 = goog.ui.registry.getDecoratorByClassName('fake-component-y'); - assertTrue('fake-component-y must be decorated by a FakeComponentY', - dy1 instanceof FakeComponentY); - assertNotEquals('Each call to getDecoratorByClassName must return a ' + - 'new FakeComponentY instance', dy1, dy2); - - assertNull('getDecoratorByClassName must return null for unknown class', - goog.ui.registry.getDecoratorByClassName('fake-component-z')); - assertNull('getDecoratorByClassName must return null for empty string', - goog.ui.registry.getDecoratorByClassName('')); - } - - function testSetDecoratorByClassName() { - var dx1, dx2; - - dx1 = goog.ui.registry.getDecoratorByClassName('fake-component-x'); - assertTrue('fake-component-x must be decorated by a FakeComponentX', - dx1 instanceof FakeComponentX); - goog.ui.registry.setDecoratorByClassName('fake-component-x', - function() { - return new UnknownComponent(); - }); - dx2 = goog.ui.registry.getDecoratorByClassName('fake-component-x'); - assertTrue('fake-component-x must now be decorated by UnknownComponent', - dx2 instanceof UnknownComponent); - - assertThrows('Calling setDecoratorByClassName with invalid class name ' + - 'must throw error', - function() { - goog.ui.registry.setDecoratorByClassName('', function() { - return new UnknownComponent(); - }); - }); - - assertThrows('Calling setDecoratorByClassName with non-function ' + - 'decorator must throw error', - function() { - goog.ui.registry.setDecoratorByClassName('fake-component-x', - 'Not function'); - }); - } - - function testGetDecorator() { - var dx = goog.ui.registry.getDecorator(document.getElementById('x')); - assertTrue('Decorator for element with fake-component-x class must be ' + - 'a FakeComponentX', dx instanceof FakeComponentX); - - var dy = goog.ui.registry.getDecorator(document.getElementById('y')); - assertTrue('Decorator for element with fake-component-y class must be ' - + 'a FakeComponentY', dy instanceof FakeComponentY); - - var dz = goog.ui.registry.getDecorator(document.getElementById('z')); - assertNull('Decorator for element with unknown class must be null', dz); - - var du = goog.ui.registry.getDecorator(document.getElementById('u')); - assertNull('Decorator for element without CSS class must be null', du); - } - - function testReset() { - assertNotEquals('Some renderers must be registered', 0, - goog.object.getCount(goog.ui.registry.defaultRenderers_)); - assertNotEquals('Some decorators must be registered', 0, - goog.object.getCount(goog.ui.registry.decoratorFunctions_)); - - goog.ui.registry.reset(); - - assertTrue('No renderers must be registered', - goog.object.isEmpty(goog.ui.registry.defaultRenderers_)); - assertTrue('No decorators must be registered', - goog.object.isEmpty(goog.ui.registry.decoratorFunctions_)); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/richtextspellchecker.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/richtextspellchecker.js.svn-base deleted file mode 100644 index 7b84c12..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/richtextspellchecker.js.svn-base +++ /dev/null @@ -1,602 +0,0 @@ -// 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 Rich text spell checker implementation. - * - * @author eae@google.com (Emil A Eklund) - * @author sergeys@google.com (Sergey Solyanik) - * @see ../demos/richtextspellchecker.html - */ - -goog.provide('goog.ui.RichTextSpellChecker'); - -goog.require('goog.Timer'); -goog.require('goog.dom'); -goog.require('goog.dom.NodeType'); -goog.require('goog.events'); -goog.require('goog.events.EventType'); -goog.require('goog.string.StringBuffer'); -goog.require('goog.ui.AbstractSpellChecker'); -goog.require('goog.ui.AbstractSpellChecker.AsyncResult'); - - - -/** - * Rich text spell checker implementation. - * - * @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.AbstractSpellChecker} - */ -goog.ui.RichTextSpellChecker = function(handler, opt_domHelper) { - goog.ui.AbstractSpellChecker.call(this, handler, opt_domHelper); - - /** - * String buffer for use in reassembly of the original text. - * @type {goog.string.StringBuffer} - * @private - */ - this.workBuffer_ = new goog.string.StringBuffer(); - - /** - * Bound async function (to avoid rebinding it on every call). - * @type {Function} - * @private - */ - this.boundContinueAsyncFn_ = goog.bind(this.continueAsync_, this); -}; -goog.inherits(goog.ui.RichTextSpellChecker, goog.ui.AbstractSpellChecker); - - -/** - * Root node for rich editor. - * @type {Node} - * @private - */ -goog.ui.RichTextSpellChecker.prototype.rootNode_; - - -/** - * Current node where spell checker has interrupted to go to the next stack - * frame. - * @type {Node} - * @private - */ -goog.ui.RichTextSpellChecker.prototype.currentNode_; - - -/** - * Counter of inserted elements. Used in processing loop to attempt to preserve - * existing nodes if they contain no misspellings. - * @type {number} - * @private - */ -goog.ui.RichTextSpellChecker.prototype.elementsInserted_ = 0; - - -/** - * Number of words to scan to precharge the dictionary. - * @type {number} - * @private - */ -goog.ui.RichTextSpellChecker.prototype.dictionaryPreScanSize_ = 1000; - - -/** - * Class name for word spans. - * @type {string} - */ -goog.ui.RichTextSpellChecker.prototype.wordClassName = - goog.getCssName('goog-spellcheck-word'); - - -/** - * DomHelper to be used for interacting with the editable document/element. - * - * @type {goog.dom.DomHelper|undefined} - * @private - */ -goog.ui.RichTextSpellChecker.prototype.editorDom_; - - -/** - * Tag name porition of the marker for the text that does not need to be checked - * for spelling. - * - * @type {string|undefined} - */ -goog.ui.RichTextSpellChecker.prototype.excludeTag; - - -/** - * CSS Style text for invalid words. As it's set inside the rich edit iframe - * classes defined in the parent document are not availble, thus the style is - * set inline. - * @type {string} - */ -goog.ui.RichTextSpellChecker.prototype.invalidWordCssText = - 'background: yellow;'; - - -/** - * Creates the initial DOM representation for the component. - * - * @throws {Error} Not supported. Use decorate. - * @see #decorate - */ -goog.ui.RichTextSpellChecker.prototype.createDom = function() { - throw Error('Render not supported for goog.ui.RichTextSpellChecker.'); -}; - - -/** - * Decorates the element for the UI component. - * - * @param {Element} element Element to decorate. - */ -goog.ui.RichTextSpellChecker.prototype.decorateInternal = function(element) { - this.setElementInternal(element); - if (element.contentDocument || element.contentWindow) { - var doc = element.contentDocument || element.contentWindow.document; - this.rootNode_ = doc.body; - this.editorDom_ = goog.dom.getDomHelper(doc); - } else { - this.rootNode_ = element; - this.editorDom_ = goog.dom.getDomHelper(element); - } -}; - - -/** - * Called when the component's element is known to be in the document. - */ -goog.ui.RichTextSpellChecker.prototype.enterDocument = function() { - goog.ui.RichTextSpellChecker.superClass_.enterDocument.call(this); - this.initSuggestionsMenu(); -}; - - -/** - * Checks spelling for all text and displays correction UI. - */ -goog.ui.RichTextSpellChecker.prototype.check = function() { - this.blockReadyEvents(); - this.preChargeDictionary_(this.rootNode_, this.dictionaryPreScanSize_); - this.unblockReadyEvents(); - - goog.events.listen(this.handler_, goog.spell.SpellCheck.EventType.READY, - this.onDictionaryCharged_, true, this); - this.handler_.processPending(); -}; - - -/** - * Processes nodes recursively. - * - * @param {Node} node Node to start with. - * @param {number} words Max number of words to process. - * @private - */ -goog.ui.RichTextSpellChecker.prototype.preChargeDictionary_ = function(node, - words) { - while (node) { - var next = this.nextNode_(node); - if (this.isExcluded_(node)) { - node = next; - continue; - } - if (node.nodeType == goog.dom.NodeType.TEXT) { - if (node.nodeValue) { - words -= this.populateDictionary(node.nodeValue, words); - if (words <= 0) { - return; - } - } - } else if (node.nodeType == goog.dom.NodeType.ELEMENT) { - if (node.firstChild) { - next = node.firstChild; - } - } - node = next; - } -}; - - -/** - * Starts actual processing after the dictionary is charged. - * @param {goog.events.Event} e goog.spell.SpellCheck.EventType.READY event. - * @private - */ -goog.ui.RichTextSpellChecker.prototype.onDictionaryCharged_ = function(e) { - e.stopPropagation(); - goog.events.unlisten(this.handler_, goog.spell.SpellCheck.EventType.READY, - this.onDictionaryCharged_, true, this); - - // Now actually do the spell checking. - this.wordElements_ = {}; - this.initializeAsyncMode(); - this.elementsInserted_ = 0; - var result = this.processNode_(this.rootNode_); - if (result == goog.ui.AbstractSpellChecker.AsyncResult.PENDING) { - goog.Timer.callOnce(this.boundContinueAsyncFn_); - return; - } - this.finishAsyncProcessing(); - this.finishCheck_(); -}; - - -/** - * Continues asynchrnonous spell checking. - * @private - */ -goog.ui.RichTextSpellChecker.prototype.continueAsync_ = function() { - var result = this.continueAsyncProcessing(); - if (result == goog.ui.AbstractSpellChecker.AsyncResult.PENDING) { - goog.Timer.callOnce(this.boundContinueAsyncFn_); - return; - } - result = this.processNode_(this.currentNode_); - if (result == goog.ui.AbstractSpellChecker.AsyncResult.PENDING) { - goog.Timer.callOnce(this.boundContinueAsyncFn_); - return; - } - this.finishAsyncProcessing(); - this.finishCheck_(); -}; - - -/** - * Finalizes spelling check. - * @private - */ -goog.ui.RichTextSpellChecker.prototype.finishCheck_ = function() { - delete this.currentNode_; - this.handler_.processPending(); - - if (!this.isVisible_) { - goog.events.listen(this.rootNode_, goog.events.EventType.CLICK, - this.onWordClick_, false, this); - } - goog.ui.RichTextSpellChecker.superClass_.check.call(this); -}; - - -/** - * Finds next node in our enumeration of the tree. - * - * @param {Node} node The node to which we're computing the next node for. - * @return {Node} The next node or null if none was found. - * @private - */ -goog.ui.RichTextSpellChecker.prototype.nextNode_ = function(node) { - while (node != this.rootNode_) { - if (node.nextSibling) { - return node.nextSibling; - } - node = node.parentNode; - } - return null; -}; - - -/** - * Determines if the node is text node without any children. - * - * @param {Node} node The node to check. - * @return {boolean} Whether the node is a text leaf node. - * @private - */ -goog.ui.RichTextSpellChecker.prototype.isTextLeaf_ = function(node) { - return node != null && - node.nodeType == goog.dom.NodeType.TEXT && - !node.firstChild; -}; - - -/** @override */ -goog.ui.RichTextSpellChecker.prototype.setExcludeMarker = function(marker) { - var parts = marker.split('.'); - this.excludeTag = parts[0] || undefined; - this.excludeMarker = parts[1] || undefined; -}; - - -/** - * Determines if the node is excluded from checking. - * - * @param {Node} node The node to check. - * @return {boolean} Whether the node is excluded. - * @private - */ -goog.ui.RichTextSpellChecker.prototype.isExcluded_ = function(node) { - return !!(this.excludeMarker && node.className && - node.className.indexOf(this.excludeMarker) != -1 && - (!this.excludeTag || node.tagName == this.excludeTag)); -}; - - -/** - * Processes nodes recursively. - * - * @param {Node} node Node where to start. - * @return {goog.ui.AbstractSpellChecker.AsyncResult|undefined} Result code. - * @private - */ -goog.ui.RichTextSpellChecker.prototype.processNode_ = function(node) { - delete this.currentNode_; - while (node) { - var next = this.nextNode_(node); - if (this.isExcluded_(node)) { - node = next; - continue; - } - if (node.nodeType == goog.dom.NodeType.TEXT) { - var deleteNode = true; - if (node.nodeValue) { - var currentElements = this.elementsInserted_; - var result = this.processTextAsync(node, node.nodeValue); - if (result == goog.ui.AbstractSpellChecker.AsyncResult.PENDING) { - // This markes node for deletion (empty nodes get deleted couple - // of lines down this function). This is so our algorithm terminates. - // In this case the node may be needlessly recreated, but it - // happens rather infrequently and saves a lot of code. - node.nodeValue = ''; - this.currentNode_ = node; - return result; - } - // If we did not add nodes in processing, the current element is still - // valid. Let's preserve it! - if (currentElements == this.elementsInserted_) { - deleteNode = false; - } - } - if (deleteNode) { - goog.dom.removeNode(node); - } - } else if (node.nodeType == goog.dom.NodeType.ELEMENT) { - // If this is a spell checker element... - if (node.className == this.wordClassName) { - // First, reconsolidate the text nodes inside the element - editing - // in IE splits them up. - var runner = node.firstChild; - while (runner) { - if (this.isTextLeaf_(runner)) { - while (this.isTextLeaf_(runner.nextSibling)) { - // Yes, this is not super efficient in IE, but it will almost - // never happen. - runner.nodeValue += runner.nextSibling.nodeValue; - goog.dom.removeNode(runner.nextSibling); - } - } - runner = runner.nextSibling; - } - // Move its contents out and reprocess it on the next iteration. - if (node.firstChild) { - next = node.firstChild; - while (node.firstChild) { - node.parentNode.insertBefore(node.firstChild, node); - } - } - // get rid of the empty shell. - goog.dom.removeNode(node); - } else { - if (node.firstChild) { - next = node.firstChild; - } - } - } - node = next; - } -}; - - -/** - * Processes word. - * - * @param {Node} node Node containing word. - * @param {string} word Word to process. - * @param {goog.spell.SpellCheck.WordStatus} status Status of the word. - * @protected - */ -goog.ui.RichTextSpellChecker.prototype.processWord = function(node, word, - status) { - node.parentNode.insertBefore(this.createWordElement_(word, status), node); - this.elementsInserted_++; -}; - - -/** - * Processes recognized text and separators. - * - * @param {Node} node Node containing separator. - * @param {string} text Text to process. - * @protected - */ -goog.ui.RichTextSpellChecker.prototype.processRange = function(node, text) { - // The text does not change, it only gets split, so if the lengths are the - // same, the text is the same, so keep the existing node. - if (node.nodeType == goog.dom.NodeType.TEXT && node.nodeValue.length == - text.length) { - return; - } - - node.parentNode.insertBefore(this.editorDom_.createTextNode(text), node); - this.elementsInserted_++; -}; - - -/** - * 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 the word. - * @return {HTMLSpanElement} The created element. - * @private - */ -goog.ui.RichTextSpellChecker.prototype.createWordElement_ = function(word, - status) { - var parameters = this.getElementProperties(status); - var el = /** @type {HTMLSpanElement} */ (this.editorDom_.createDom('span', - parameters, word)); - this.registerWordElement_(word, el); - return el; -}; - - -/** - * Updates or replaces element based on word status. - * @see goog.ui.AbstractSpellChecker.prototype.updateElement_ - * - * Overridden from AbstractSpellChecker because we need to be mindful of - * deleting the currentNode_ - this can break our pending processing. - * - * @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.RichTextSpellChecker.prototype.updateElement = function(el, word, - status) { - if (status == goog.spell.SpellCheck.WordStatus.VALID && el != - this.currentNode_ && el.nextSibling != this.currentNode_) { - this.removeMarkup(el); - } else { - goog.dom.setProperties(el, this.getElementProperties(status)); - } -}; - - -/** - * Hides correction UI. - */ -goog.ui.RichTextSpellChecker.prototype.resume = function() { - goog.ui.RichTextSpellChecker.superClass_.resume.call(this); - - this.restoreNode_(this.rootNode_); - - goog.events.unlisten(this.rootNode_, goog.events.EventType.CLICK, - this.onWordClick_, false, this); -}; - - -/** - * Processes nodes recursively, removes all spell checker markup, and - * consolidates text nodes. - * - * @param {Node} node node on which to recurse. - * @private - */ -goog.ui.RichTextSpellChecker.prototype.restoreNode_ = function(node) { - while (node) { - if (this.isExcluded_(node)) { - node = node.nextSibling; - continue; - } - // Contents of the child of the element is usually 1 text element, but the - // user can actually add multiple nodes in it during editing. So we move - // all the children out, prepend, and reprocess (pointer is set back to - // the first node that's been moved out, and the loop repeats). - if (node.nodeType == goog.dom.NodeType.ELEMENT && node.className == - this.wordClassName) { - var firstElement = node.firstChild; - var next; - for (var child = firstElement; child; child = next) { - next = child.nextSibling; - node.parentNode.insertBefore(child, node); - } - next = firstElement || node.nextSibling; - goog.dom.removeNode(node); - node = next; - continue; - } - // If this is a chain of text elements, we're trying to consolidate it. - var textLeaf = this.isTextLeaf_(node); - if (textLeaf) { - var textNodes = 1; - var next = node.nextSibling; - while (this.isTextLeaf_(node.previousSibling)) { - node = node.previousSibling; - ++textNodes; - } - while (this.isTextLeaf_(next)) { - next = next.nextSibling; - ++textNodes; - } - if (textNodes > 1) { - this.workBuffer_.append(node.nodeValue); - while (this.isTextLeaf_(node.nextSibling)) { - this.workBuffer_.append(node.nextSibling.nodeValue); - goog.dom.removeNode(node.nextSibling); - } - node.nodeValue = this.workBuffer_.toString(); - this.workBuffer_.clear(); - } - } - // Process child nodes, if any. - if (node.firstChild) { - this.restoreNode_(node.firstChild); - } - node = node.nextSibling; - } -}; - - -/** - * Returns desired element properties for the specified status. - * - * @param {goog.spell.SpellCheck.WordStatus} status Status of the word. - * @return {Object} Properties to apply to word element. - * @protected - */ -goog.ui.RichTextSpellChecker.prototype.getElementProperties = - function(status) { - return { - 'class': this.wordClassName, - 'style': (status == goog.spell.SpellCheck.WordStatus.INVALID) ? - this.invalidWordCssText : '' - }; -}; - - -/** - * Handler for click events. - * - * @param {goog.events.BrowserEvent} event Event object. - * @private - */ -goog.ui.RichTextSpellChecker.prototype.onWordClick_ = function(event) { - var target = /** @type {Element} */ (event.target); - if (event.target.className == this.wordClassName && - this.handler_.checkWord(goog.dom.getTextContent(target)) == - goog.spell.SpellCheck.WordStatus.INVALID) { - - this.showSuggestionsMenu(target, event); - - // Prevent document click handler from closing the menu. - event.stopPropagation(); - } -}; - - -/** @override */ -goog.ui.RichTextSpellChecker.prototype.disposeInternal = function() { - goog.ui.RichTextSpellChecker.superClass_.disposeInternal.call(this); - this.rootNode_ = null; - this.editorDom_ = null; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/richtextspellchecker_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/richtextspellchecker_test.html.svn-base deleted file mode 100644 index c99e6f5..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/richtextspellchecker_test.html.svn-base +++ /dev/null @@ -1,224 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2007 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.RichTextSpellChecker</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.string.StringBuffer'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.RichTextSpellChecker'); -</script> -</head> -<body> - -<div id="test1"></div> -<div id="test2"></div> -<div id="test3"></div> - -<script> - -var attributeSet = ['b', 'u', 'del', 'i']; -var vocabulary = ['test', 'words', 'a', 'few', 'missspelling', 'iggnore']; - -// We don't use Math.random() to make test predictable. Math.random is not -// repeatable, so a success on the dev machine != success in the lab (or on -// other dev machines). This is the same pseudorandom logic that CRT rand() -// uses. -var rseed = 1; -function random(range) { - rseed = (rseed * 1103515245 + 12345) & 0xffffffff; - return ((rseed >> 16) & 0x7fff) % range; -}; - -function localSpellCheckingFunction(words, spellChecker, callback) { - var len = words.length; - var results = []; - for (var i = 0; i < len; i++) { - var word = words[i]; - var found = false; - // Last two words are considered misspellings - for (var j = 0 ; j < vocabulary.length - 2 ; ++j) { - if (vocabulary[j] == word) { - found = true; - break; - } - } - if (found) { - results.push([word, goog.spell.SpellCheck.WordStatus.VALID]); - } else { - results.push([word, goog.spell.SpellCheck.WordStatus.INVALID, - ['foo','bar']]); - } - } - callback.call(spellChecker, results); -}; - -function generateRandomSpace() { - var string = ''; - var nSpace = 1 + random(4); - for (var i = 0; i < nSpace ; ++i) { - string += ' '; - } - return string; -}; - -function generateRandomString(maxWords) { - var string = ''; - var nWords = 1 + random(maxWords); - for (var i = 0; i < nWords ; ++i) { - string += vocabulary[random(vocabulary.length)]; - string += generateRandomSpace(); - } - return string; -}; - -function generateRandomHtml(rootNode, branchFactor, attributes, numAttr) { - if (numAttr == 0) { - var text = document.createTextNode(generateRandomString(10)); - rootNode.appendChild(text); - return; - } - - var lastElementWasText = false; - for (var i = 0; i < branchFactor; ++i) { - var rand = random(10); - if (rand < 8 && !lastElementWasText) { - lastElementWasText = true; - var text = document.createTextNode(generateRandomString(10)); - rootNode.appendChild(text); - } else { - lastElementWasText = false; - - var rand = random(numAttr); - var index = 0; - for (;;) { - while (attributes[index] == null) { - ++index; - } - if (rand == 0) - break; - ++index; - --rand; - }; - - var attr = attributes[index]; - var el = document.createElement(attr); - rootNode.appendChild(el); - rand = random(10); - if (rand == 0) { - el.className = 'goog-quote'; - } - attributes[index] = null; - generateRandomHtml(el, branchFactor, attributes, numAttr-1); - attributes[index] = attr; - } - } -}; - -var timerQueue = []; -function processTimerQueue() { - while (timerQueue.length > 0) { - var fn = timerQueue.shift(); - fn(); - } -}; - -function localTimer(fn, delay, obj) { - if (obj) { - fn = goog.bind(fn, obj); - } - timerQueue.push(fn); - return timerQueue.length; -}; - -function testDocumentIntegrity() { - var handler = new goog.spell.SpellCheck(localSpellCheckingFunction); - var s = new goog.ui.RichTextSpellChecker(handler); - s.asyncWordsPerBatch_ = 100; - var el = document.getElementById('test1'); - s.decorate(el); - generateRandomHtml(el, 4, attributeSet, attributeSet.length); - var el2 = el.cloneNode(true); - - var timerSav = goog.Timer.callOnce; - goog.Timer.callOnce = localTimer; - - s.setExcludeMarker('goog-quote'); - s.check(); - processTimerQueue(); - s.ignoreWord('iggnore'); - processTimerQueue(); - s.check(); - processTimerQueue(); - s.resume(); - processTimerQueue(); - - goog.Timer.callOnce = timerSav; - - assertEquals('Spell checker run should not change the underlying element.', - el2.innerHTML, el.innerHTML); - s.dispose(); -}; - -function testBiggerDocument() { - var handler = new goog.spell.SpellCheck(localSpellCheckingFunction); - var s = new goog.ui.RichTextSpellChecker(handler); - var el = document.getElementById('test2'); - s.decorate(el); - generateRandomHtml(el, 4, attributeSet, attributeSet.length); - var el2 = el.cloneNode(true); - - var timerSav = goog.Timer.callOnce; - goog.Timer.callOnce = localTimer; - - s.check(); - processTimerQueue(); - s.resume(); - processTimerQueue(); - - goog.Timer.callOnce = timerSav; - - assertEquals('Spell checker run should not change the underlying element.', - el2.innerHTML, el.innerHTML); - s.dispose(); -}; - -function testElementOverflow() { - var handler = new goog.spell.SpellCheck(localSpellCheckingFunction); - var s = new goog.ui.RichTextSpellChecker(handler); - s.asyncWordsPerBatch_ = 100; - var el = document.getElementById('test3'); - s.decorate(el); - var text = generateRandomString(200); - el.appendChild(document.createTextNode(text)); - - var el2 = el.cloneNode(true); - - var timerSav = goog.Timer.callOnce; - goog.Timer.callOnce = localTimer; - - s.check(); - processTimerQueue(); - s.check(); - processTimerQueue(); - s.resume(); - processTimerQueue(); - - goog.Timer.callOnce = timerSav; - - assertEquals('Spell checker run should not change the underlying element.', - el2.innerHTML, el.innerHTML); - s.dispose(); -}; - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/roundedpanel.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/roundedpanel.js.svn-base deleted file mode 100644 index 88545f7..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/roundedpanel.js.svn-base +++ /dev/null @@ -1,618 +0,0 @@ -// 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 definition for a rounded corner panel. - * @supported IE 6.0+, Safari 2.0+, Firefox 1.5+, Opera 9.2+. - * @see ../demos/roundedpanel.html - */ - -goog.provide('goog.ui.BaseRoundedPanel'); -goog.provide('goog.ui.CssRoundedPanel'); -goog.provide('goog.ui.GraphicsRoundedPanel'); -goog.provide('goog.ui.RoundedPanel'); -goog.provide('goog.ui.RoundedPanel.Corner'); - -goog.require('goog.dom'); -goog.require('goog.dom.classes'); -goog.require('goog.graphics'); -goog.require('goog.graphics.SolidFill'); -goog.require('goog.graphics.Stroke'); -goog.require('goog.math.Coordinate'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); -goog.require('goog.userAgent'); - - -/** - * Factory method that returns an instance of a BaseRoundedPanel. - * @param {number} radius The radius of the rounded corner(s), in pixels. - * @param {number} borderWidth The thickness of the border, in pixels. - * @param {string} borderColor The border color of the panel. - * @param {string=} opt_backgroundColor The background color of the panel. - * @param {number=} opt_corners The corners of the panel to be rounded. Any - * corners not specified will be rendered as square corners. Will default - * to all square corners if not specified. - * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the - * document we want to render in. - * @return {goog.ui.BaseRoundedPanel} An instance of a - * goog.ui.BaseRoundedPanel subclass. - */ -goog.ui.RoundedPanel.create = function(radius, - borderWidth, - borderColor, - opt_backgroundColor, - opt_corners, - opt_domHelper) { - // This variable checks for the presence of Safari 3.0+ or Gecko 1.9+, - // which can leverage special CSS styles to create rounded corners. - var isCssReady = goog.userAgent.WEBKIT && goog.userAgent.isVersion('500') || - goog.userAgent.GECKO && goog.userAgent.isVersion('1.9a'); - - if (isCssReady) { - // Safari 3.0+ and Firefox 3.0+ support this instance. - return new goog.ui.CssRoundedPanel( - radius, - borderWidth, - borderColor, - opt_backgroundColor, - opt_corners, - opt_domHelper); - } else { - return new goog.ui.GraphicsRoundedPanel( - radius, - borderWidth, - borderColor, - opt_backgroundColor, - opt_corners, - opt_domHelper); - } -}; - - -/** - * Enum for specifying which corners to render. - * @enum {number} - */ -goog.ui.RoundedPanel.Corner = { - NONE: 0, - BOTTOM_LEFT: 2, - TOP_LEFT: 4, - LEFT: 6, // BOTTOM_LEFT | TOP_LEFT - TOP_RIGHT: 8, - TOP: 12, // TOP_LEFT | TOP_RIGHT - BOTTOM_RIGHT: 1, - BOTTOM: 3, // BOTTOM_LEFT | BOTTOM_RIGHT - RIGHT: 9, // TOP_RIGHT | BOTTOM_RIGHT - ALL: 15 // TOP | BOTTOM -}; - - -/** - * CSS class name suffixes for the elements comprising the RoundedPanel. - * @enum {string} - * @private - */ -goog.ui.RoundedPanel.Classes_ = { - BACKGROUND: goog.getCssName('goog-roundedpanel-background'), - PANEL: goog.getCssName('goog-roundedpanel'), - CONTENT: goog.getCssName('goog-roundedpanel-content') -}; - - - -/** - * Base class for the hierarchy of RoundedPanel classes. Do not - * instantiate directly. Instead, call goog.ui.RoundedPanel.create(). - * The HTML structure for the RoundedPanel is: - * <pre> - * - div (Contains the background and content. Class name: goog-roundedpanel) - * - div (Contains the background/rounded corners. Class name: - * goog-roundedpanel-bg) - * - div (Contains the content. Class name: goog-roundedpanel-content) - * </pre> - * @param {number} radius The radius of the rounded corner(s), in pixels. - * @param {number} borderWidth The thickness of the border, in pixels. - * @param {string} borderColor The border color of the panel. - * @param {string=} opt_backgroundColor The background color of the panel. - * @param {number=} opt_corners The corners of the panel to be rounded. Any - * corners not specified will be rendered as square corners. Will default - * to all square corners if not specified. - * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the - * document we want to render in. - * @extends {goog.ui.Component} - * @constructor - */ -goog.ui.BaseRoundedPanel = function(radius, - borderWidth, - borderColor, - opt_backgroundColor, - opt_corners, - opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - - /** - * The radius of the rounded corner(s), in pixels. - * @type {number} - * @private - */ - this.radius_ = radius; - - /** - * The thickness of the border, in pixels. - * @type {number} - * @private - */ - this.borderWidth_ = borderWidth; - - /** - * The border color of the panel. - * @type {string} - * @private - */ - this.borderColor_ = borderColor; - - /** - * The background color of the panel. - * @type {?string} - * @private - */ - this.backgroundColor_ = opt_backgroundColor || null; - - /** - * The corners of the panel to be rounded; defaults to - * goog.ui.RoundedPanel.Corner.NONE - * @type {number} - * @private - */ - this.corners_ = opt_corners || goog.ui.RoundedPanel.Corner.NONE; -}; -goog.inherits(goog.ui.BaseRoundedPanel, goog.ui.Component); - - -/** - * The element containing the rounded corners and background. - * @type {Element} - * @private - */ -goog.ui.BaseRoundedPanel.prototype.backgroundElement_; - - -/** - * The element containing the actual content. - * @type {Element} - * @private - */ -goog.ui.BaseRoundedPanel.prototype.contentElement_; - - -/** - * This method performs all the necessary DOM manipulation to create the panel. - * Overrides {@link goog.ui.Component#decorateInternal}. - * @param {Element} element The element to decorate. - * @protected - */ -goog.ui.BaseRoundedPanel.prototype.decorateInternal = function(element) { - goog.ui.BaseRoundedPanel.superClass_.decorateInternal.call(this, element); - goog.dom.classes.add(this.getElement(), goog.ui.RoundedPanel.Classes_.PANEL); - - // Create backgroundElement_, and add it to the DOM. - this.backgroundElement_ = this.getDomHelper().createElement('div'); - this.backgroundElement_.className = goog.ui.RoundedPanel.Classes_.BACKGROUND; - this.getElement().appendChild(this.backgroundElement_); - - // Set contentElement_ by finding a child node within element_ with the - // proper class name. If none exists, create it and add it to the DOM. - this.contentElement_ = goog.dom.getElementsByTagNameAndClass( - null, goog.ui.RoundedPanel.Classes_.CONTENT, this.getElement())[0]; - if (!this.contentElement_) { - this.contentElement_ = this.getDomHelper().createDom('div'); - this.contentElement_.className = goog.ui.RoundedPanel.Classes_.CONTENT; - this.getElement().appendChild(this.contentElement_); - } -}; - - -/** @override */ -goog.ui.BaseRoundedPanel.prototype.disposeInternal = function() { - if (this.backgroundElement_) { - this.getDomHelper().removeNode(this.backgroundElement_); - this.backgroundElement_ = null; - } - this.contentElement_ = null; - goog.ui.BaseRoundedPanel.superClass_.disposeInternal.call(this); -}; - - -/** - * Returns the DOM element containing the actual content. - * @return {Element} The element containing the actual content (null if none). - */ -goog.ui.BaseRoundedPanel.prototype.getContentElement = function() { - return this.contentElement_; -}; - - - -/** - * RoundedPanel class specifically for browsers that support CSS attributes - * for elements with rounded borders (ex. Safari 3.0+, Firefox 3.0+). Do not - * instantiate directly. Instead, call goog.ui.RoundedPanel.create(). - * @param {number} radius The radius of the rounded corner(s), in pixels. - * @param {number} borderWidth The thickness of the border, in pixels. - * @param {string} borderColor The border color of the panel. - * @param {string=} opt_backgroundColor The background color of the panel. - * @param {number=} opt_corners The corners of the panel to be rounded. Any - * corners not specified will be rendered as square corners. Will - * default to all square corners if not specified. - * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the - * document we want to render in. - * @extends {goog.ui.BaseRoundedPanel} - * @constructor - */ -goog.ui.CssRoundedPanel = function(radius, - borderWidth, - borderColor, - opt_backgroundColor, - opt_corners, - opt_domHelper) { - goog.ui.BaseRoundedPanel.call(this, - radius, - borderWidth, - borderColor, - opt_backgroundColor, - opt_corners, - opt_domHelper); -}; -goog.inherits(goog.ui.CssRoundedPanel, goog.ui.BaseRoundedPanel); - - -/** - * This method performs all the necessary DOM manipulation to create the panel. - * Overrides {@link goog.ui.Component#decorateInternal}. - * @param {Element} element The element to decorate. - * @protected - */ -goog.ui.CssRoundedPanel.prototype.decorateInternal = function(element) { - goog.ui.CssRoundedPanel.superClass_.decorateInternal.call(this, element); - - // Set the border width and background color, if needed. - this.backgroundElement_.style.border = this.borderWidth_ + - 'px solid ' + - this.borderColor_; - if (this.backgroundColor_) { - this.backgroundElement_.style.backgroundColor = this.backgroundColor_; - } - - // Set radii of the appropriate rounded corners. - if (this.corners_ == goog.ui.RoundedPanel.Corner.ALL) { - var styleName = this.getStyle_(goog.ui.RoundedPanel.Corner.ALL); - this.backgroundElement_.style[styleName] = this.radius_ + 'px'; - } else { - var topLeftRadius = - this.corners_ & goog.ui.RoundedPanel.Corner.TOP_LEFT ? - this.radius_ : - 0; - var cornerStyle = this.getStyle_(goog.ui.RoundedPanel.Corner.TOP_LEFT); - this.backgroundElement_.style[cornerStyle] = topLeftRadius + 'px'; - var topRightRadius = - this.corners_ & goog.ui.RoundedPanel.Corner.TOP_RIGHT ? - this.radius_ : - 0; - cornerStyle = this.getStyle_(goog.ui.RoundedPanel.Corner.TOP_RIGHT); - this.backgroundElement_.style[cornerStyle] = topRightRadius + 'px'; - var bottomRightRadius = - this.corners_ & goog.ui.RoundedPanel.Corner.BOTTOM_RIGHT ? - this.radius_ : - 0; - cornerStyle = this.getStyle_(goog.ui.RoundedPanel.Corner.BOTTOM_RIGHT); - this.backgroundElement_.style[cornerStyle] = bottomRightRadius + 'px'; - var bottomLeftRadius = - this.corners_ & goog.ui.RoundedPanel.Corner.BOTTOM_LEFT ? - this.radius_ : - 0; - cornerStyle = this.getStyle_(goog.ui.RoundedPanel.Corner.BOTTOM_LEFT); - this.backgroundElement_.style[cornerStyle] = bottomLeftRadius + 'px'; - } -}; - - -/** - * This method returns the CSS style based on the corner of the panel, and the - * user-agent. - * @param {number} corner The corner whose style name to retrieve. - * @private - * @return {string} The CSS style based on the specified corner. - */ -goog.ui.CssRoundedPanel.prototype.getStyle_ = function(corner) { - // Determine the proper corner to work with. - var cssCorner, suffixLeft, suffixRight; - if (goog.userAgent.WEBKIT) { - suffixLeft = 'Left'; - suffixRight = 'Right'; - } else { - suffixLeft = 'left'; - suffixRight = 'right'; - } - switch (corner) { - case goog.ui.RoundedPanel.Corner.ALL: - cssCorner = ''; - break; - case goog.ui.RoundedPanel.Corner.TOP_LEFT: - cssCorner = 'Top' + suffixLeft; - break; - case goog.ui.RoundedPanel.Corner.TOP_RIGHT: - cssCorner = 'Top' + suffixRight; - break; - case goog.ui.RoundedPanel.Corner.BOTTOM_LEFT: - cssCorner = 'Bottom' + suffixLeft; - break; - case goog.ui.RoundedPanel.Corner.BOTTOM_RIGHT: - cssCorner = 'Bottom' + suffixRight; - break; - } - - return goog.userAgent.WEBKIT ? - 'WebkitBorder' + cssCorner + 'Radius' : - 'MozBorderRadius' + cssCorner; -}; - - - -/** - * RoundedPanel class that uses goog.graphics to create the rounded corners. - * Do not instantiate directly. Instead, call goog.ui.RoundedPanel.create(). - * @param {number} radius The radius of the rounded corner(s), in pixels. - * @param {number} borderWidth The thickness of the border, in pixels. - * @param {string} borderColor The border color of the panel. - * @param {string=} opt_backgroundColor The background color of the panel. - * @param {number=} opt_corners The corners of the panel to be rounded. Any - * corners not specified will be rendered as square corners. Will - * default to all square corners if not specified. - * @param {goog.dom.DomHelper=} opt_domHelper The DOM helper object for the - * document we want to render in. - * @extends {goog.ui.BaseRoundedPanel} - * @constructor - */ -goog.ui.GraphicsRoundedPanel = function(radius, - borderWidth, - borderColor, - opt_backgroundColor, - opt_corners, - opt_domHelper) { - goog.ui.BaseRoundedPanel.call(this, - radius, - borderWidth, - borderColor, - opt_backgroundColor, - opt_corners, - opt_domHelper); -}; -goog.inherits(goog.ui.GraphicsRoundedPanel, goog.ui.BaseRoundedPanel); - - -/** - * A 4-element array containing the circle centers for the arcs in the - * bottom-left, top-left, top-right, and bottom-right corners, respectively. - * @type {Array.<goog.math.Coordinate>} - * @private - */ -goog.ui.GraphicsRoundedPanel.prototype.arcCenters_; - - -/** - * A 4-element array containing the start coordinates for rendering the arcs - * in the bottom-left, top-left, top-right, and bottom-right corners, - * respectively. - * @type {Array.<goog.math.Coordinate>} - * @private - */ -goog.ui.GraphicsRoundedPanel.prototype.cornerStarts_; - - -/** - * A 4-element array containing the arc end angles for the bottom-left, - * top-left, top-right, and bottom-right corners, respectively. - * @type {Array.<number>} - * @private - */ -goog.ui.GraphicsRoundedPanel.prototype.endAngles_; - - -/** - * Graphics object for rendering the background. - * @type {goog.graphics.AbstractGraphics} - * @private - */ -goog.ui.GraphicsRoundedPanel.prototype.graphics_; - - -/** - * A 4-element array containing the rounded corner radii for the bottom-left, - * top-left, top-right, and bottom-right corners, respectively. - * @type {Array.<number>} - * @private - */ -goog.ui.GraphicsRoundedPanel.prototype.radii_; - - -/** - * A 4-element array containing the arc start angles for the bottom-left, - * top-left, top-right, and bottom-right corners, respectively. - * @type {Array.<number>} - * @private - */ -goog.ui.GraphicsRoundedPanel.prototype.startAngles_; - - -/** - * Thickness constant used as an offset to help determine where to start - * rendering. - * @type {number} - * @private - */ -goog.ui.GraphicsRoundedPanel.BORDER_WIDTH_FACTOR_ = 1 / 2; - - -/** - * This method performs all the necessary DOM manipulation to create the panel. - * Overrides {@link goog.ui.Component#decorateInternal}. - * @param {Element} element The element to decorate. - * @protected - */ -goog.ui.GraphicsRoundedPanel.prototype.decorateInternal = - function(element) { - goog.ui.GraphicsRoundedPanel.superClass_.decorateInternal.call(this, - element); - - // Calculate the points and angles for creating the rounded corners. Then - // instantiate a Graphics object for drawing purposes. - var elementSize = goog.style.getSize(this.getElement()); - this.calculateArcParameters_(elementSize); - this.graphics_ = goog.graphics.createGraphics( - /** @type {number} */ (elementSize.width), - /** @type {number} */ (elementSize.height), - /** @type {number} */ (elementSize.width), - /** @type {number} */ (elementSize.height), - this.getDomHelper()); - this.graphics_.createDom(); - - // Create the path, starting from the bottom-right corner, moving clockwise. - // End with the top-right corner. - var path = new goog.graphics.Path(); - for (var i = 0; i < 4; i++) { - if (this.radii_[i]) { - // If radius > 0, draw an arc, moving to the first point and drawing - // a line to the others. - var cx = this.arcCenters_[i].x; - var cy = this.arcCenters_[i].y; - var rx = this.radii_[i]; - var ry = rx; - var fromAngle = this.startAngles_[i]; - var extent = this.endAngles_[i] - fromAngle; - var startX = cx + goog.math.angleDx(fromAngle, rx); - var startY = cy + goog.math.angleDy(fromAngle, ry); - if (i > 0) { - var currentPoint = path.getCurrentPoint(); - if (!currentPoint || startX != currentPoint[0] || - startY != currentPoint[1]) { - path.lineTo(startX, startY); - } - } else { - path.moveTo(startX, startY); - } - path.arcTo(rx, ry, fromAngle, extent); - } else if (i == 0) { - // If we're just starting out (ie. i == 0), move to the starting point. - path.moveTo(this.cornerStarts_[i].x, - this.cornerStarts_[i].y); - } else { - // Otherwise, draw a line to the starting point. - path.lineTo(this.cornerStarts_[i].x, - this.cornerStarts_[i].y); - } - } - - // Close the path, create a stroke object, and fill the enclosed area, if - // needed. Then render the path. - path.close(); - var stroke = this.borderWidth_ ? - new goog.graphics.Stroke(this.borderWidth_, this.borderColor_) : - null; - var fill = this.backgroundColor_ ? - new goog.graphics.SolidFill(this.backgroundColor_, 1) : - null; - this.graphics_.drawPath(path, stroke, fill); - this.graphics_.render(this.backgroundElement_); -}; - - -/** @override */ -goog.ui.GraphicsRoundedPanel.prototype.disposeInternal = function() { - goog.ui.GraphicsRoundedPanel.superClass_.disposeInternal.call(this); - this.graphics_.dispose(); - delete this.graphics_; - delete this.radii_; - delete this.cornerStarts_; - delete this.arcCenters_; - delete this.startAngles_; - delete this.endAngles_; -}; - - -/** - * Calculates the start coordinates, circle centers, and angles, for the rounded - * corners at each corner of the panel. - * @param {goog.math.Size} elementSize The size of element_. - * @private - */ -goog.ui.GraphicsRoundedPanel.prototype.calculateArcParameters_ = - function(elementSize) { - // Initialize the arrays containing the key points and angles. - this.radii_ = []; - this.cornerStarts_ = []; - this.arcCenters_ = []; - this.startAngles_ = []; - this.endAngles_ = []; - - // Set the start points, circle centers, and angles for the bottom-right, - // bottom-left, top-left and top-right corners, in that order. - var angleInterval = 90; - var borderWidthOffset = this.borderWidth_ * - goog.ui.GraphicsRoundedPanel.BORDER_WIDTH_FACTOR_; - var radius, xStart, yStart, xCenter, yCenter, startAngle, endAngle; - for (var i = 0; i < 4; i++) { - var corner = Math.pow(2, i); // Determines which corner we're dealing with. - var isLeft = corner & goog.ui.RoundedPanel.Corner.LEFT; - var isTop = corner & goog.ui.RoundedPanel.Corner.TOP; - - // Calculate the radius and the start coordinates. - radius = corner & this.corners_ ? this.radius_ : 0; - switch (corner) { - case goog.ui.RoundedPanel.Corner.BOTTOM_LEFT: - xStart = borderWidthOffset + radius; - yStart = elementSize.height - borderWidthOffset; - break; - case goog.ui.RoundedPanel.Corner.TOP_LEFT: - xStart = borderWidthOffset; - yStart = radius + borderWidthOffset; - break; - case goog.ui.RoundedPanel.Corner.TOP_RIGHT: - xStart = elementSize.width - radius - borderWidthOffset; - yStart = borderWidthOffset; - break; - case goog.ui.RoundedPanel.Corner.BOTTOM_RIGHT: - xStart = elementSize.width - borderWidthOffset; - yStart = elementSize.height - radius - borderWidthOffset; - break; - } - - // Calculate the circle centers and start/end angles. - xCenter = isLeft ? - radius + borderWidthOffset : - elementSize.width - radius - borderWidthOffset; - yCenter = isTop ? - radius + borderWidthOffset : - elementSize.height - radius - borderWidthOffset; - startAngle = angleInterval * i; - endAngle = startAngle + angleInterval; - - // Append the radius, angles, and coordinates to their arrays. - this.radii_[i] = radius; - this.cornerStarts_[i] = new goog.math.Coordinate(xStart, yStart); - this.arcCenters_[i] = new goog.math.Coordinate(xCenter, yCenter); - this.startAngles_[i] = startAngle; - this.endAngles_[i] = endAngle; - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/roundedpanel_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/roundedpanel_test.html.svn-base deleted file mode 100644 index 243a37f..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/roundedpanel_test.html.svn-base +++ /dev/null @@ -1,57 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - - Unit test file for goog.ui.RoundedPanel component ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.RoundedPanel</title> - <script src="../base.js"></script> - <script> - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.RoundedPanel'); - goog.require('goog.userAgent'); - </script> -</head> -<body> - <script> - /** - * Tests goog.ui.RoundedPanel.create(), ensuring that the proper instance is - * created based on user-agent - */ - function testRoundedPanelCreate() { - var rcp = goog.ui.RoundedPanel.create(15, - 5, - '#cccccc', - '#cccccc', - goog.ui.RoundedPanel.Corner.ALL); - - if (goog.userAgent.GECKO && goog.userAgent.isVersion('1.9a')) { - assertTrue('For Firefox 3.0+ (uses Gecko 1.9+), an instance of ' + - 'goog.ui.CssRoundedPanel should be returned.', - rcp instanceof goog.ui.CssRoundedPanel); - } else if (goog.userAgent.WEBKIT && goog.userAgent.isVersion('500')) { - assertTrue('For Safari 3.0+, an instance of goog.ui.CssRoundedPanel ' + - 'should be returned.', rcp instanceof goog.ui.CssRoundedPanel); - } else if (goog.userAgent.GECKO || - goog.userAgent.IE || - goog.userAgent.OPERA || - goog.userAgent.WEBKIT) { - assertTrue('For Gecko 1.8- (ex. Firefox 2.0-, Camino 1.5-, etc.), ' + - 'IE, Opera, and Safari 2.0-, an instance of ' + - 'goog.ui.GraphicsRoundedPanel should be returned.', - rcp instanceof goog.ui.GraphicsRoundedPanel); - } else { - assertNull('For non-supported user-agents, null is returned.', rcp); - } - }; - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/roundedtabrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/roundedtabrenderer.js.svn-base deleted file mode 100644 index 3c0fc36..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/roundedtabrenderer.js.svn-base +++ /dev/null @@ -1,197 +0,0 @@ -// 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 Rounded corner tab renderer for {@link goog.ui.Tab}s. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.RoundedTabRenderer'); - -goog.require('goog.dom'); -goog.require('goog.ui.Tab'); -goog.require('goog.ui.TabBar.Location'); -goog.require('goog.ui.TabRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * Rounded corner tab renderer for {@link goog.ui.Tab}s. - * @constructor - * @extends {goog.ui.TabRenderer} - */ -goog.ui.RoundedTabRenderer = function() { - goog.ui.TabRenderer.call(this); -}; -goog.inherits(goog.ui.RoundedTabRenderer, goog.ui.TabRenderer); -goog.addSingletonGetter(goog.ui.RoundedTabRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.RoundedTabRenderer.CSS_CLASS = goog.getCssName('goog-rounded-tab'); - - -/** - * Returns the CSS class name to be applied to the root element of all tabs - * rendered or decorated using this renderer. - * @return {string} Renderer-specific CSS class name. - * @override - */ -goog.ui.RoundedTabRenderer.prototype.getCssClass = function() { - return goog.ui.RoundedTabRenderer.CSS_CLASS; -}; - - -/** - * Creates the tab's DOM structure, based on the containing tab bar's location - * relative to tab contents. For example, the DOM for a tab in a tab bar - * located above tab contents would look like this: - * <pre> - * <div class="goog-rounded-tab" title="..."> - * <table class="goog-rounded-tab-table"> - * <tbody> - * <tr> - * <td nowrap> - * <div class="goog-rounded-tab-outer-edge"></div> - * <div class="goog-rounded-tab-inner-edge"></div> - * </td> - * </tr> - * <tr> - * <td nowrap> - * <div class="goog-rounded-tab-caption">Hello, world</div> - * </td> - * </tr> - * </tbody> - * </table> - * </div> - * </pre> - * @param {goog.ui.Control} tab Tab to render. - * @return {Element} Root element for the tab. - * @override - */ -goog.ui.RoundedTabRenderer.prototype.createDom = function(tab) { - return this.decorate(tab, - goog.ui.RoundedTabRenderer.superClass_.createDom.call(this, tab)); -}; - - -/** - * Decorates the element with the tab. Overrides the superclass implementation - * by wrapping the tab's content in a table that implements rounded corners. - * @param {goog.ui.Control} tab Tab to decorate the element. - * @param {Element} element Element to decorate. - * @return {Element} Decorated element. - * @override - */ -goog.ui.RoundedTabRenderer.prototype.decorate = function(tab, element) { - var tabBar = tab.getParent(); - - if (!this.getContentElement(element)) { - // The element to be decorated doesn't appear to have the full tab DOM, - // so we have to create it. - element.appendChild(this.createTab(tab.getDomHelper(), element.childNodes, - tabBar.getLocation())); - } - - return goog.ui.RoundedTabRenderer.superClass_.decorate.call(this, tab, - element); -}; - - -/** - * Creates a table implementing a rounded corner tab. - * @param {goog.dom.DomHelper} dom DOM helper to use for element construction. - * @param {goog.ui.ControlContent} caption Text caption or DOM structure - * to display as the tab's caption. - * @param {goog.ui.TabBar.Location} location Tab bar location relative to the - * tab contents. - * @return {Element} Table implementing a rounded corner tab. - * @protected - */ -goog.ui.RoundedTabRenderer.prototype.createTab = function(dom, caption, - location) { - var rows = []; - - if (location != goog.ui.TabBar.Location.BOTTOM) { - // This is a left, right, or top tab, so it needs a rounded top edge. - rows.push(this.createEdge(dom, /* isTopEdge */ true)); - } - rows.push(this.createCaption(dom, caption)); - if (location != goog.ui.TabBar.Location.TOP) { - // This is a left, right, or bottom tab, so it needs a rounded bottom edge. - rows.push(this.createEdge(dom, /* isTopEdge */ false)); - } - - return dom.createDom('table', { - 'cellPadding': 0, - 'cellSpacing': 0, - 'className': goog.getCssName(this.getStructuralCssClass(), 'table') - }, dom.createDom('tbody', null, rows)); -}; - - -/** - * Creates a table row implementing the tab caption. - * @param {goog.dom.DomHelper} dom DOM helper to use for element construction. - * @param {goog.ui.ControlContent} caption Text caption or DOM structure - * to display as the tab's caption. - * @return {Element} Tab caption table row. - * @protected - */ -goog.ui.RoundedTabRenderer.prototype.createCaption = function(dom, caption) { - var baseClass = this.getStructuralCssClass(); - return dom.createDom('tr', null, - dom.createDom('td', {'noWrap': true}, - dom.createDom('div', goog.getCssName(baseClass, 'caption'), - caption))); -}; - - -/** - * Creates a table row implementing a rounded tab edge. - * @param {goog.dom.DomHelper} dom DOM helper to use for element construction. - * @param {boolean} isTopEdge Whether to create a top or bottom edge. - * @return {Element} Rounded tab edge table row. - * @protected - */ -goog.ui.RoundedTabRenderer.prototype.createEdge = function(dom, isTopEdge) { - var baseClass = this.getStructuralCssClass(); - var inner = dom.createDom('div', goog.getCssName(baseClass, 'inner-edge')); - var outer = dom.createDom('div', goog.getCssName(baseClass, 'outer-edge')); - return dom.createDom('tr', null, - dom.createDom('td', {'noWrap': true}, - isTopEdge ? [outer, inner] : [inner, outer])); -}; - - -/** @override */ -goog.ui.RoundedTabRenderer.prototype.getContentElement = function(element) { - var baseClass = this.getStructuralCssClass(); - return element && goog.dom.getElementsByTagNameAndClass( - 'div', goog.getCssName(baseClass, 'caption'), element)[0]; -}; - - -// Register a decorator factory function for goog.ui.Tabs using the rounded -// tab renderer. -goog.ui.registry.setDecoratorByClassName(goog.ui.RoundedTabRenderer.CSS_CLASS, - function() { - return new goog.ui.Tab(null, goog.ui.RoundedTabRenderer.getInstance()); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/scrollfloater.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/scrollfloater.js.svn-base deleted file mode 100644 index aebc73d..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/scrollfloater.js.svn-base +++ /dev/null @@ -1,433 +0,0 @@ -// 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 for making an element detach and float to remain - * visible when otherwise it would have scrolled up out of view. - * <p> - * The element remains at its normal position in the layout until scrolling - * would cause its top edge to scroll off the top of the viewport; at that - * point, the element is replaced with an invisible placeholder (to keep the - * layout stable), reattached in the dom tree to a new parent (the body element - * by default), and set to "fixed" positioning (emulated for IE < 7) so that it - * remains at its original X position while staying fixed to the top of the - * viewport in the Y dimension. - * <p> - * When the window is scrolled up past the point where the original element - * would be fully visible again, the element snaps back into place, replacing - * the placeholder. - * - * @see ../demos/scrollfloater.html - * - * Adapted from http://go/elementfloater.js - */ - - -goog.provide('goog.ui.ScrollFloater'); -goog.provide('goog.ui.ScrollFloater.EventType'); - -goog.require('goog.dom'); -goog.require('goog.dom.classes'); -goog.require('goog.events.EventType'); -goog.require('goog.object'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); -goog.require('goog.userAgent'); - - - -/** - * Creates a ScrollFloater; see file overview for details. - * - * @param {Element=} opt_parentElement Where to attach the element when it's - * floating. Default is the document body. If the floating element - * contains form inputs, it will be necessary to attach it to the - * corresponding form element, or to an element in the DOM subtree under - * the form element. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Component} - */ -goog.ui.ScrollFloater = function(opt_parentElement, opt_domHelper) { - // If a parentElement is supplied, we want to use its domHelper, - // ignoring the caller-supplied one. - var domHelper = opt_parentElement ? - goog.dom.getDomHelper(opt_parentElement) : opt_domHelper; - - goog.ui.Component.call(this, domHelper); - - /** - * The element to which the scroll-floated element will be attached - * when it is floating. - * @type {Element} - * @private - */ - this.parentElement_ = - opt_parentElement || this.getDomHelper().getDocument().body; - - /** - * The original styles applied to the element before it began floating; - * used to restore those styles when the element stops floating. - * @type {Object} - * @private - */ - this.originalStyles_ = {}; -}; -goog.inherits(goog.ui.ScrollFloater, goog.ui.Component); - - -/** - * Events dispatched by this component. - * @enum {string} - */ -goog.ui.ScrollFloater.EventType = { - /** - * Dispatched when the component starts floating. The event is - * cancellable. - */ - FLOAT: 'float', - - /** - * Dispatched when the component stops floating and returns to its - * original state. The event is cancellable. - */ - DOCK: 'dock' -}; - - -/** - * The placeholder element dropped in to hold the layout for - * the floated element. - * @type {Element} - * @private - */ -goog.ui.ScrollFloater.prototype.placeholder_; - - -/** - * Whether scrolling is enabled for this element; true by default. - * The {@link #setScrollingEnabled} method can be used to change this value. - * @type {boolean} - * @private - */ -goog.ui.ScrollFloater.prototype.scrollingEnabled_ = true; - - -/** - * A flag indicating whether this instance is currently floating. - * @type {boolean} - * @private - */ -goog.ui.ScrollFloater.prototype.floating_ = false; - - -/** - * The original vertical page offset at which the top of the element - * was rendered. - * @type {number} - * @private - */ -goog.ui.ScrollFloater.prototype.originalOffset_; - - -/** - * The style properties which are stored when we float an element, so they - * can be restored when it 'docks' again. - * @type {Array.<string>} - * @private - */ -goog.ui.ScrollFloater.STORED_STYLE_PROPS_ = [ - 'position', 'top', 'left', 'width', 'cssFloat']; - - -/** - * The style elements managed for the placeholder object. - * @type {Array.<string>} - * @private - */ -goog.ui.ScrollFloater.PLACEHOLDER_STYLE_PROPS_ = [ - 'position', 'top', 'left', 'display', 'cssFloat', - 'marginTop', 'marginLeft', 'marginRight', 'marginBottom']; - - -/** - * The class name applied to the floating element. - * @type {string} - * @private - */ -goog.ui.ScrollFloater.CSS_CLASS_ = goog.getCssName('goog-scrollfloater'); - - -/** - * Delegates dom creation to superclass, then constructs and - * decorates required DOM elements. - */ -goog.ui.ScrollFloater.prototype.createDom = function() { - goog.ui.ScrollFloater.superClass_.createDom.call(this); - - this.decorateInternal(this.getElement()); -}; - - -/** - * Decorates the floated element with the standard ScrollFloater CSS class. - * @param {Element} element The element to decorate. - */ -goog.ui.ScrollFloater.prototype.decorateInternal = function(element) { - goog.ui.ScrollFloater.superClass_.decorateInternal.call(this, element); - - goog.dom.classes.add(element, goog.ui.ScrollFloater.CSS_CLASS_); -}; - - -/** @override */ -goog.ui.ScrollFloater.prototype.enterDocument = function() { - goog.ui.ScrollFloater.superClass_.enterDocument.call(this); - - if (!this.placeholder_) { - this.placeholder_ = - this.getDomHelper().createDom('div', {'style': 'visibility:hidden'}); - } - - this.originalOffset_ = goog.style.getPageOffsetTop(this.getElement()); - this.setScrollingEnabled(this.scrollingEnabled_); - this.getHandler().listen( - window, goog.events.EventType.SCROLL, this.update_); - this.getHandler().listen( - window, goog.events.EventType.RESIZE, this.handleResize_); -}; - - -/** @override */ -goog.ui.ScrollFloater.prototype.disposeInternal = function() { - goog.ui.ScrollFloater.superClass_.disposeInternal.call(this); - - delete this.placeholder_; -}; - - -/** - * Sets whether the element should be floated if it scrolls out of view. - * @param {boolean} enable Whether floating is enabled for this element. - */ -goog.ui.ScrollFloater.prototype.setScrollingEnabled = function(enable) { - this.scrollingEnabled_ = enable; - - if (enable) { - this.applyIeBgHack_(); - this.update_(); - } else { - this.stopFloating_(); - } -}; - - -/** - * @return {boolean} Whether the component is enabled for scroll-floating. - */ -goog.ui.ScrollFloater.prototype.isScrollingEnabled = function() { - return this.scrollingEnabled_; -}; - - -/** - * @return {boolean} Whether the component is currently scroll-floating. - */ -goog.ui.ScrollFloater.prototype.isFloating = function() { - return this.floating_; -}; - - -/** - * When a scroll event occurs, compares the element's position to the current - * document scroll position, and stops or starts floating behavior if needed. - * @param {goog.events.Event=} opt_e The event, which is ignored. - * @private - */ -goog.ui.ScrollFloater.prototype.update_ = function(opt_e) { - if (this.scrollingEnabled_) { - var doc = this.getDomHelper().getDocument(); - var currentScrollTop = this.getDomHelper().getDocumentScroll().y; - - if (currentScrollTop > this.originalOffset_) { - this.startFloating_(); - } else { - this.stopFloating_(); - } - } -}; - - -/** - * Begins floating behavior, making the element position:fixed (or IE hacked - * equivalent) and inserting a placeholder where it used to be to keep the - * layout from shifting around. - * @private - */ -goog.ui.ScrollFloater.prototype.startFloating_ = function() { - // Ignore if the component is floating or the FLOAT event is cancelled. - if (this.floating_ || - !this.dispatchEvent(goog.ui.ScrollFloater.EventType.FLOAT)) { - return; - } - - var elem = this.getElement(); - var doc = this.getDomHelper().getDocument(); - - // Read properties of element before modifying it. - var originalLeft_ = goog.style.getPageOffsetLeft(elem); - var originalWidth_ = goog.style.getContentBoxSize(elem).width; - - this.originalStyles_ = {}; - - // Store styles while not floating so we can restore them when the - // element stops floating. - goog.object.forEach(goog.ui.ScrollFloater.STORED_STYLE_PROPS_, - function(property) { - this.originalStyles_[property] = elem.style[property]; - }, - this); - - // Copy relevant styles to placeholder so it will be layed out the same - // as the element that's about to be floated. - goog.object.forEach(goog.ui.ScrollFloater.PLACEHOLDER_STYLE_PROPS_, - function(property) { - this.placeholder_.style[property] = - elem.style[property] || - goog.style.getCascadedStyle(elem, property) || - goog.style.getComputedStyle(elem, property); - }, - this); - - goog.style.setSize(this.placeholder_, elem.offsetWidth, elem.offsetHeight); - - // Make element float. - - goog.style.setStyle(elem, { - 'left': originalLeft_ + 'px', - 'width': originalWidth_ + 'px', - 'cssFloat': 'none' - }); - - // If parents are the same, avoid detaching and reattaching elem. - // This prevents Flash embeds from being reloaded, for example. - if (elem.parentNode == this.parentElement_) { - elem.parentNode.insertBefore(this.placeholder_, elem); - } else { - elem.parentNode.replaceChild(this.placeholder_, elem); - this.parentElement_.appendChild(elem); - } - - // Versions of IE below 7-in-standards-mode don't handle 'position: fixed', - // so we must emulate it using an IE-specific idiom for JS-based calculated - // style values. - - if (this.needsIePositionHack_()) { - elem.style.position = 'absolute'; - elem.style.setExpression('top', - 'document.compatMode=="CSS1Compat"?' + - 'documentElement.scrollTop:document.body.scrollTop'); - } else { - elem.style.position = 'fixed'; - elem.style.top = '0'; - } - - this.floating_ = true; -}; - - -/** - * Stops floating behavior, returning element to its original state. - * @private - */ -goog.ui.ScrollFloater.prototype.stopFloating_ = function() { - // Ignore if the component is docked or the DOCK event is cancelled. - if (!this.floating_ || - !this.dispatchEvent(goog.ui.ScrollFloater.EventType.DOCK)) { - return; - } - - var elem = this.getElement(); - - for (var prop in this.originalStyles_) { - elem.style[prop] = this.originalStyles_[prop]; - } - - if (this.needsIePositionHack_()) { - elem.style.removeExpression('top'); - } - - // If placeholder_ was inserted and didn't replace elem then elem has - // the right parent already, no need to replace (which removes elem before - // inserting it). - if (this.placeholder_.parentNode == this.parentElement_) { - this.placeholder_.parentNode.removeChild(this.placeholder_); - } else { - this.placeholder_.parentNode.replaceChild(elem, this.placeholder_); - } - this.floating_ = false; -}; - - -/** - * Responds to window resize events by snapping the floater back to the new - * version of its original position, then allowing it to float again if - * appropriate. - * @private - */ -goog.ui.ScrollFloater.prototype.handleResize_ = function() { - this.stopFloating_(); - this.originalOffset_ = goog.style.getPageOffsetTop(this.getElement()); - this.update_(); -}; - - -/** - * Determines whether we need to apply the position hack to emulated position: - * fixed on this browser. - * @return {boolean} Whether the current browser needs the position hack. - * @private - */ -goog.ui.ScrollFloater.prototype.needsIePositionHack_ = function() { - return goog.userAgent.IE && - !(goog.userAgent.isVersion('7') && - this.getDomHelper().isCss1CompatMode()); -}; - - -/** - * Sets some magic CSS properties that make float-scrolling work smoothly - * in IE6 (and IE7 in quirks mode). Without this hack, the floating element - * will appear jumpy when you scroll the document. This involves modifying - * the background of the HTML element (or BODY in quirks mode). If there's - * already a background image in use this is not required. - * For further reading, see - * http://annevankesteren.nl/2005/01/position-fixed-in-ie - * @private - */ -goog.ui.ScrollFloater.prototype.applyIeBgHack_ = function() { - if (this.needsIePositionHack_()) { - var doc = this.getDomHelper().getDocument(); - var topLevelElement = goog.style.getClientViewportElement(doc); - - if (topLevelElement.currentStyle.backgroundImage == 'none') { - // Using an https URL if the current windowbp is https avoids an IE - // "This page contains a mix of secure and nonsecure items" warning. - topLevelElement.style.backgroundImage = - this.getDomHelper().getWindow().location.protocol == 'https:' ? - 'url(https:///)' : 'url(about:blank)'; - topLevelElement.style.backgroundAttachment = 'fixed'; - } - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/scrollfloater_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/scrollfloater_test.html.svn-base deleted file mode 100644 index 7c951d2..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/scrollfloater_test.html.svn-base +++ /dev/null @@ -1,124 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.ScrollFloater</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.style'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.ScrollFloater'); - goog.require('goog.ui.ScrollFloater.EventType'); -</script> -</head> -<body> -<script> - - function testScrollFloater() { - var scrollFloater = new goog.ui.ScrollFloater(); - var floater = goog.dom.getElement('floater'); - scrollFloater.decorate(floater); - - assertTrue('Default state is enabled', scrollFloater.isScrollingEnabled()); - assertFalse('On unscrolled page should not be floating', - scrollFloater.isFloating()); - - scrollFloater.setScrollingEnabled(false); - - assertFalse('We can disable the floater', - scrollFloater.isScrollingEnabled()); - scrollFloater.dispose(); - } - - function testScrollFloaterEvents() { - var scrollFloater = new goog.ui.ScrollFloater(); - var floater = goog.dom.getElement('floater'); - scrollFloater.decorate(floater); - - var floatWasCalled = false; - var callRecorder = function() { floatWasCalled = true; }; - goog.events.listen( - scrollFloater, goog.ui.ScrollFloater.EventType.FLOAT, callRecorder); - scrollFloater.startFloating_(); - assertTrue('FLOAT event was called', floatWasCalled); - assertTrue('Should be floating', scrollFloater.isFloating()); - - var dockWasCalled = false; - callRecorder = function() { dockWasCalled = true; }; - goog.events.listen( - scrollFloater, goog.ui.ScrollFloater.EventType.DOCK, callRecorder); - scrollFloater.stopFloating_(); - assertTrue('DOCK event was called', dockWasCalled); - assertFalse('Should not be floating', scrollFloater.isFloating()); - - scrollFloater.dispose(); - } - - function testScrollFloaterEventCancellation() { - var scrollFloater = new goog.ui.ScrollFloater(); - var floater = goog.dom.getElement('floater'); - scrollFloater.decorate(floater); - - // Event handler that returns false to cancel the event. - var eventCanceller = function() { return false; }; - - // Have eventCanceller handle the FLOAT event and verify cancellation. - goog.events.listen( - scrollFloater, goog.ui.ScrollFloater.EventType.FLOAT, eventCanceller); - scrollFloater.startFloating_(); - assertFalse('Should not be floating', scrollFloater.isFloating()); - - // Detach eventCanceller and enable floating. - goog.events.unlisten( - scrollFloater, goog.ui.ScrollFloater.EventType.FLOAT, eventCanceller); - scrollFloater.startFloating_(); - - // Have eventCanceller handle the DOCK event and verify cancellation. - goog.events.listen( - scrollFloater, goog.ui.ScrollFloater.EventType.DOCK, eventCanceller); - scrollFloater.stopFloating_(); - assertTrue('Should still be floating', scrollFloater.isFloating()); - - scrollFloater.dispose(); - } - - function testScrollFloaterUpdateStyleOnFloatEvent() { - var scrollFloater = new goog.ui.ScrollFloater(); - var floater = goog.dom.getElement('floater'); - scrollFloater.decorate(floater); - - // Event handler that sets the font size of the scrollfloater to 20px. - var updateStyle = function(e) { - goog.style.setStyle(e.target.getElement(), 'font-size', '20px'); - }; - - // Set the current font size to 10px. - goog.style.setStyle(scrollFloater.getElement(), 'font-size', '10px'); - goog.events.listen( - scrollFloater, goog.ui.ScrollFloater.EventType.FLOAT, updateStyle); - scrollFloater.startFloating_(); - - // Ensure event handler got called and updated the font size. - assertEquals('Font size should be 20px', - '20px', goog.style.getStyle(scrollFloater.getElement(), 'font-size')); - - scrollFloater.dispose(); - } - -</script> - -<div id="floater"> -Content to be scroll-floated. -</div> - -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/select.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/select.js.svn-base deleted file mode 100644 index 7b4a725..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/select.js.svn-base +++ /dev/null @@ -1,420 +0,0 @@ -// 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 that supports single selection from a dropdown menu, - * with semantics similar to the native HTML <code><select></code> - * element. - * - * @author attila@google.com (Attila Bodis) - * @see ../demos/select.html - */ - -goog.provide('goog.ui.Select'); - -goog.require('goog.dom.a11y'); -goog.require('goog.dom.a11y.Role'); -goog.require('goog.dom.a11y.State'); -goog.require('goog.events.EventType'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.MenuButton'); -goog.require('goog.ui.SelectionModel'); -goog.require('goog.ui.registry'); - - - -/** - * A selection control. Extends {@link goog.ui.MenuButton} by composing a - * menu with a selection model, and automatically updating the button's caption - * based on the current selection. - * - * @param {goog.ui.ControlContent} caption Default caption or existing DOM - * structure to display as the button's caption when nothing is selected. - * @param {goog.ui.Menu=} opt_menu Menu containing selection options. - * @param {goog.ui.ButtonRenderer=} opt_renderer Renderer used to render or - * decorate the control; defaults to {@link goog.ui.MenuButtonRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for - * document interaction. - * @constructor - * @extends {goog.ui.MenuButton} - */ -goog.ui.Select = function(caption, opt_menu, opt_renderer, opt_domHelper) { - goog.ui.MenuButton.call(this, caption, opt_menu, opt_renderer, opt_domHelper); - this.setDefaultCaption(caption); - this.setPreferredAriaRole(goog.dom.a11y.Role.LISTBOX); -}; -goog.inherits(goog.ui.Select, goog.ui.MenuButton); - - -/** - * The selection model controlling the items in the menu. - * @type {goog.ui.SelectionModel} - * @private - */ -goog.ui.Select.prototype.selectionModel_ = null; - - -/** - * Default caption to be shown when no option is selected. - * @type {goog.ui.ControlContent} - * @private - */ -goog.ui.Select.prototype.defaultCaption_ = null; - - -/** - * Configures the component after its DOM has been rendered, and sets up event - * handling. Overrides {@link goog.ui.MenuButton#enterDocument}. - */ -goog.ui.Select.prototype.enterDocument = function() { - goog.ui.Select.superClass_.enterDocument.call(this); - this.updateCaption(); - this.listenToSelectionModelEvents_(); - // Need to set HASPOPUP to false since it's set to true in the parent class. - goog.dom.a11y.setState(this.getElement(), - goog.dom.a11y.State.HASPOPUP, 'false'); -}; - - -/** - * Decorates the given element with this control. Overrides the superclass - * implementation by initializing the default caption on the select button. - * @param {Element} element Element to decorate. - */ -goog.ui.Select.prototype.decorateInternal = function(element) { - goog.ui.Select.superClass_.decorateInternal.call(this, element); - var caption = this.getCaption(); - if (caption) { - // Initialize the default caption. - this.setDefaultCaption(caption); - } else { - // There is no default caption; select the first option. - this.setSelectedIndex(0); - } -}; - - -/** @override */ -goog.ui.Select.prototype.disposeInternal = function() { - goog.ui.Select.superClass_.disposeInternal.call(this); - - if (this.selectionModel_) { - this.selectionModel_.dispose(); - this.selectionModel_ = null; - } - - this.defaultCaption_ = null; -}; - - -/** - * Handles {@link goog.ui.Component.EventType.ACTION} events dispatched by - * the menu item clicked by the user. Updates the selection model, calls - * the superclass implementation to hide the menu, stops the propagation of - * the event, and dispatches an ACTION event on behalf of the select control - * itself. Overrides {@link goog.ui.MenuButton#handleMenuAction}. - * @param {goog.events.Event} e Action event to handle. - */ -goog.ui.Select.prototype.handleMenuAction = function(e) { - this.setSelectedItem(/** @type {goog.ui.MenuItem} */ (e.target)); - goog.ui.Select.superClass_.handleMenuAction.call(this, e); - e.stopPropagation(); - this.dispatchEvent(goog.ui.Component.EventType.ACTION); -}; - - -/** - * Handles {@link goog.events.EventType.SELECT} events raised by the - * selection model when the selection changes. Updates the contents of the - * select button. - * @param {goog.events.Event} e Selection event to handle. - */ -goog.ui.Select.prototype.handleSelectionChange = function(e) { - var item = this.getSelectedItem(); - goog.ui.Select.superClass_.setValue.call(this, item && item.getValue()); - this.updateCaption(); -}; - - -/** - * Replaces the menu currently attached to the control (if any) with the given - * argument, and updates the selection model. Does nothing if the new menu is - * the same as the old one. Overrides {@link goog.ui.MenuButton#setMenu}. - * @param {goog.ui.Menu} menu New menu to be attached to the menu button. - * @return {goog.ui.Menu|undefined} Previous menu (undefined if none). - */ -goog.ui.Select.prototype.setMenu = function(menu) { - // Call superclass implementation to replace the menu. - var oldMenu = goog.ui.Select.superClass_.setMenu.call(this, menu); - - // Do nothing unless the new menu is different from the current one. - if (menu != oldMenu) { - // Clear the old selection model (if any). - if (this.selectionModel_) { - this.selectionModel_.clear(); - } - - // Initialize new selection model (unless the new menu is null). - if (menu) { - if (this.selectionModel_) { - menu.forEachChild(function(child, index) { - this.setCorrectAriaRole_(child); - this.selectionModel_.addItem(child); - }, this); - } else { - this.createSelectionModel_(menu); - } - } - } - - return oldMenu; -}; - - -/** - * Returns the default caption to be shown when no option is selected. - * @return {goog.ui.ControlContent} Default caption. - */ -goog.ui.Select.prototype.getDefaultCaption = function() { - return this.defaultCaption_; -}; - - -/** - * Sets the default caption to the given string or DOM structure. - * @param {goog.ui.ControlContent} caption Default caption to be shown - * when no option is selected. - */ -goog.ui.Select.prototype.setDefaultCaption = function(caption) { - this.defaultCaption_ = caption; - this.updateCaption(); -}; - - -/** - * Adds a new menu item at the end of the menu. - * @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu item to add to the - * menu. - */ -goog.ui.Select.prototype.addItem = function(item) { - this.setCorrectAriaRole_(item); - goog.ui.Select.superClass_.addItem.call(this, item); - - if (this.selectionModel_) { - this.selectionModel_.addItem(item); - } else { - this.createSelectionModel_(this.getMenu()); - } -}; - - -/** - * Adds a new menu item at a specific index in the menu. - * @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu item to add to the - * menu. - * @param {number} index Index at which to insert the menu item. - */ -goog.ui.Select.prototype.addItemAt = function(item, index) { - this.setCorrectAriaRole_(item); - goog.ui.Select.superClass_.addItemAt.call(this, item, index); - - if (this.selectionModel_) { - this.selectionModel_.addItemAt(item, index); - } else { - this.createSelectionModel_(this.getMenu()); - } -}; - - -/** - * Removes an item from the menu and disposes it. - * @param {goog.ui.MenuItem} item The menu item to remove. - */ -goog.ui.Select.prototype.removeItem = function(item) { - goog.ui.Select.superClass_.removeItem.call(this, item); - if (this.selectionModel_) { - this.selectionModel_.removeItem(item); - } -}; - - -/** - * Removes a menu item at a given index in the menu and disposes it. - * @param {number} index Index of item. - */ -goog.ui.Select.prototype.removeItemAt = function(index) { - goog.ui.Select.superClass_.removeItemAt.call(this, index); - if (this.selectionModel_) { - this.selectionModel_.removeItemAt(index); - } -}; - - -/** - * Selects the specified option (assumed to be in the select menu), and - * deselects the previously selected option, if any. A null argument clears - * the selection. - * @param {goog.ui.MenuItem} item Option to be selected (null to clear - * the selection). - */ -goog.ui.Select.prototype.setSelectedItem = function(item) { - if (this.selectionModel_) { - this.selectionModel_.setSelectedItem(item); - } -}; - - -/** - * Selects the option at the specified index, or clears the selection if the - * index is out of bounds. - * @param {number} index Index of the option to be selected. - */ -goog.ui.Select.prototype.setSelectedIndex = function(index) { - if (this.selectionModel_) { - this.setSelectedItem(/** @type {goog.ui.MenuItem} */ - (this.selectionModel_.getItemAt(index))); - } -}; - - -/** - * Selects the first option found with an associated value equal to the - * argument, or clears the selection if no such option is found. A null - * argument also clears the selection. Overrides {@link - * goog.ui.Button#setValue}. - * @param {*} value Value of the option to be selected (null to clear - * the selection). - */ -goog.ui.Select.prototype.setValue = function(value) { - if (goog.isDefAndNotNull(value) && this.selectionModel_) { - for (var i = 0, item; item = this.selectionModel_.getItemAt(i); i++) { - if (item && typeof item.getValue == 'function' && - item.getValue() == value) { - this.setSelectedItem(/** @type {goog.ui.MenuItem} */ (item)); - return; - } - } - } - - this.setSelectedItem(null); -}; - - -/** - * Returns the currently selected option. - * @return {goog.ui.MenuItem} The currently selected option (null if none). - */ -goog.ui.Select.prototype.getSelectedItem = function() { - return this.selectionModel_ ? - /** @type {goog.ui.MenuItem} */ (this.selectionModel_.getSelectedItem()) : - null; -}; - - -/** - * Returns the index of the currently selected option. - * @return {number} 0-based index of the currently selected option (-1 if none). - */ -goog.ui.Select.prototype.getSelectedIndex = function() { - return this.selectionModel_ ? this.selectionModel_.getSelectedIndex() : -1; -}; - - -/** - * @return {goog.ui.SelectionModel} The selection model. - * @protected - */ -goog.ui.Select.prototype.getSelectionModel = function() { - return this.selectionModel_; -}; - - -/** - * Creates a new selection model and sets up an event listener to handle - * {@link goog.events.EventType.SELECT} events dispatched by it. - * @param {goog.ui.Component=} opt_component If provided, will add the - * component's children as items to the selection model. - * @private - */ -goog.ui.Select.prototype.createSelectionModel_ = function(opt_component) { - this.selectionModel_ = new goog.ui.SelectionModel(); - if (opt_component) { - opt_component.forEachChild(function(child, index) { - this.setCorrectAriaRole_(child); - this.selectionModel_.addItem(child); - }, this); - } - this.listenToSelectionModelEvents_(); -}; - - -/** - * Subscribes to events dispatched by the selection model. - * @private - */ -goog.ui.Select.prototype.listenToSelectionModelEvents_ = function() { - if (this.selectionModel_) { - this.getHandler().listen(this.selectionModel_, goog.events.EventType.SELECT, - this.handleSelectionChange); - } -}; - - -/** - * Updates the caption to be shown in the select button. If no option is - * selected and a default caption is set, sets the caption to the default - * caption; otherwise to the empty string. - * @protected - */ -goog.ui.Select.prototype.updateCaption = function() { - var item = this.getSelectedItem(); - this.setContent(item ? item.getCaption() : this.defaultCaption_); -}; - - -/** - * Sets the correct ARIA role for the menu item or separator. - * @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item The item to set. - * @private - */ -goog.ui.Select.prototype.setCorrectAriaRole_ = function(item) { - item.setPreferredAriaRole(item instanceof goog.ui.MenuItem ? - goog.dom.a11y.Role.OPTION : goog.dom.a11y.Role.SEPARATOR); -}; - - -/** - * Opens or closes the menu. Overrides {@link goog.ui.MenuButton#setOpen} by - * highlighting the currently selected option on open. - * @param {boolean} open Whether to open or close the menu. - * @param {goog.events.Event=} opt_e Mousedown event that caused the menu to - * be opened. - * @override - */ -goog.ui.Select.prototype.setOpen = function(open, opt_e) { - goog.ui.Select.superClass_.setOpen.call(this, open, opt_e); - - if (this.isOpen()) { - this.getMenu().setHighlightedIndex(this.getSelectedIndex()); - } -}; - - -// Register a decorator factory function for goog.ui.Selects. -goog.ui.registry.setDecoratorByClassName( - goog.getCssName('goog-select'), function() { - // Select defaults to using MenuButtonRenderer, since it shares its L&F. - return new goog.ui.Select(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/select_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/select_test.html.svn-base deleted file mode 100644 index e80c81f..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/select_test.html.svn-base +++ /dev/null @@ -1,176 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2010 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> - <meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.Select</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.dom.a11y'); - goog.require('goog.dom.a11y.Role'); - goog.require('goog.dom.a11y.State'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Component.EventType'); - goog.require('goog.ui.MenuItem'); - goog.require('goog.ui.Select'); - </script> -</head> -<body> - -<div id="sandbox"></div> -<script> - -var defaultCaption = 'initial caption'; -var sandbox = goog.dom.getElement('sandbox'); -var select; - -function setUp() { - select = new goog.ui.Select(defaultCaption); -} - -function tearDown() { - select.dispose(); - goog.dom.removeChildren(sandbox); -} - -/** - * Checks that the default caption passed in the constructor and in the setter - * is returned by getDefaultCaption, and acts as a default caption, i.e. is - * shown as a caption when no items are selected. - */ -function testDefaultCaption() { - select.render(sandbox); - var item1 = new goog.ui.MenuItem("item 1"); - select.addItem(item1); - select.addItem(new goog.ui.MenuItem("item 2")); - assertEquals(defaultCaption, select.getDefaultCaption()); - assertEquals(defaultCaption, select.getCaption()); - - var newCaption = 'new caption'; - select.setDefaultCaption(newCaption); - assertEquals(newCaption, select.getDefaultCaption()); - assertEquals(newCaption, select.getCaption()); - - select.setSelectedItem(item1); - assertNotEquals(newCaption, select.getCaption()); - - select.setSelectedItem(null); - assertEquals(newCaption, select.getCaption()); -} - -// Confirms that aria roles for select conform to spec: -// http://www.w3.org/TR/wai-aria/roles#listbox -// Basically the select should have a role of LISTBOX and all the items should -// have a role of OPTION. -function testAriaRoles() { - select.render(sandbox); - var item1 = new goog.ui.MenuItem("item 1"); - select.addItem(item1); - var item2 = new goog.ui.MenuItem("item 2"); - select.addItem(item2); - - assertEquals(goog.dom.a11y.Role.LISTBOX, - goog.dom.a11y.getRole(select.getElement())); - assertEquals('false', goog.dom.a11y.getState(select.getElement(), - goog.dom.a11y.State.HASPOPUP)); - assertEquals(goog.dom.a11y.Role.OPTION, - goog.dom.a11y.getRole(item1.getElement())); - assertEquals(goog.dom.a11y.Role.OPTION, - goog.dom.a11y.getRole(item2.getElement())); -} - -/** - * Checks that the select control handles ACTION events from its items. - */ -function testHandlesItemActions() { - select.render(sandbox); - var item1 = new goog.ui.MenuItem("item 1"); - var item2 = new goog.ui.MenuItem("item 2"); - select.addItem(item1); - select.addItem(item2); - - item1.dispatchEvent(goog.ui.Component.EventType.ACTION); - assertEquals(item1, select.getSelectedItem()); - assertEquals(item1.getCaption(), select.getCaption()); - - item2.dispatchEvent(goog.ui.Component.EventType.ACTION); - assertEquals(item2, select.getSelectedItem()); - assertEquals(item2.getCaption(), select.getCaption()); -} - -/** - * Tests goog.ui.Select.prototype.setValue. - */ -function testSetValue() { - select.render(sandbox); - var item1 = new goog.ui.MenuItem("item 1", 1); - var item2 = new goog.ui.MenuItem("item 2", 2); - select.addItem(item1); - select.addItem(item2); - - select.setValue(1); - assertEquals(item1, select.getSelectedItem()); - - select.setValue(2); - assertEquals(item2, select.getSelectedItem()); - - select.setValue(3); - assertNull(select.getSelectedItem()); -} - -/** - * Checks that the current selection is cleared when the selected item is - * removed. - */ -function testSelectionIsClearedWhenSelectedItemIsRemoved() { - select.render(sandbox); - var item1 = new goog.ui.MenuItem("item 1"); - select.addItem(item1); - select.addItem(new goog.ui.MenuItem("item 2")); - - select.setSelectedItem(item1); - select.removeItem(item1); - assertNull(select.getSelectedItem()); -} - -/** - * Check that the select control is subscribed to its selection model events - * after being added, removed and added back again into the document. - */ -function testExitAndEnterDocument() { - var component = new goog.ui.Component(); - component.render(sandbox); - - var item1 = new goog.ui.MenuItem("item 1"); - var item2 = new goog.ui.MenuItem("item 2"); - var item3 = new goog.ui.MenuItem("item 3"); - - select.addItem(item1); - select.addItem(item2); - select.addItem(item3); - - component.addChild(select, true); - item2.dispatchEvent(goog.ui.Component.EventType.ACTION); - assertEquals(item2.getCaption(), select.getCaption()); - - component.removeChild(select, true); - item1.dispatchEvent(goog.ui.Component.EventType.ACTION); - assertEquals(item2.getCaption(), select.getCaption()); - - component.addChild(select, true); - item3.dispatchEvent(goog.ui.Component.EventType.ACTION); - assertEquals(item3.getCaption(), select.getCaption()); -} - -</script> - -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/selectionmenubutton.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/selectionmenubutton.js.svn-base deleted file mode 100644 index 7160d30..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/selectionmenubutton.js.svn-base +++ /dev/null @@ -1,298 +0,0 @@ -// 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(); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/selectionmenubutton_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/selectionmenubutton_test.html.svn-base deleted file mode 100644 index 167393f..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/selectionmenubutton_test.html.svn-base +++ /dev/null @@ -1,237 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2009 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - - @author zhyder@google.com (Zohair Hyder) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.SelectionMenuButton</title> -<style type='text/css'> -.goog-menu { - position: absolute; - color: #aaa; -} -</style> -<script src="../base.js"></script> -<script> - goog.require('goog.Timer'); - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.events.Event'); - goog.require('goog.events.KeyCodes'); - goog.require('goog.positioning'); - goog.require('goog.positioning.Overflow'); - goog.require('goog.style'); - goog.require('goog.testing.PropertyReplacer'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.SelectionMenuButton'); -</script> -</head> -<body> -<script> - -var selectionMenuButton; -var clonedSelectionMenuButtonDom; - - -function setUp() { - clonedSelectionMenuButtonDom = - goog.dom.getElement('demoSelectionMenuButton').cloneNode(true); - - selectionMenuButton = new goog.ui.SelectionMenuButton(); -} - -function tearDown() { - selectionMenuButton.dispose(); - - var element = goog.dom.getElement('demoSelectionMenuButton'); - element.parentNode.replaceChild(clonedSelectionMenuButtonDom, element); -} - - -/** - * Open the menu and click on the menu item inside. - */ -function testBasicButtonBehavior() { - var node = goog.dom.getElement('demoSelectionMenuButton'); - selectionMenuButton.decorate(node); - goog.testing.events.fireClickSequence(node); - - assertTrue('Menu must open after click', selectionMenuButton.isOpen()); - - var menuItemClicked = 0; - var lastMenuItemClicked = null; - goog.events.listen(selectionMenuButton.getMenu(), - goog.ui.Component.EventType.ACTION, - function(e) { - menuItemClicked++; - lastMenuItemClicked = e.target - }); - - var menuItem2 = goog.dom.getElement('menuItem2'); - goog.testing.events.fireClickSequence(menuItem2); - assertFalse('Menu must close on clicking when open', - selectionMenuButton.isOpen()); - assertEquals('Number of menu items clicked should be 1', 1, menuItemClicked); - assertEquals('menuItem2 should be the last menuitem clicked', menuItem2, - lastMenuItemClicked.getElement()); -} - - -/** - * Tests that the checkbox fires the same events as the first 2 items. - */ -function testCheckboxFireEvents() { - var node = goog.dom.getElement('demoSelectionMenuButton'); - selectionMenuButton.decorate(node); - - var menuItemClicked = 0; - var lastMenuItemClicked = null; - goog.events.listen(selectionMenuButton.getMenu(), - goog.ui.Component.EventType.ACTION, - function(e) { - menuItemClicked++; - lastMenuItemClicked = e.target; - }); - - var checkbox = goog.dom.getElement('demoCheckbox'); - assertFalse('Checkbox must be unchecked (i.e. unselected)', checkbox.checked); - - checkbox.checked = true; - goog.testing.events.fireClickSequence(checkbox); - assertFalse('Menu must be closed when clicking checkbox', - selectionMenuButton.isOpen()); - assertEquals('Number of menu items clicked should be 1', 1, menuItemClicked); - assertEquals('menuItem1 should be the last menuitem clicked', - goog.dom.getElement('menuItem1'), - lastMenuItemClicked.getElement()); - - checkbox.checked = false; - goog.testing.events.fireClickSequence(checkbox); - assertFalse('Menu must be closed when clicking checkbox', - selectionMenuButton.isOpen()); - assertEquals('Number of menu items clicked should be 2', 2, menuItemClicked); - assertEquals('menuItem2 should be the last menuitem clicked', - goog.dom.getElement('menuItem2'), lastMenuItemClicked.getElement()); -} - - -/** - * Tests that the checkbox state gets updated when the first 2 events fire - */ -function testCheckboxReceiveEvents() { - var node = goog.dom.getElement('demoSelectionMenuButton'); - selectionMenuButton.decorate(node); - - var checkbox = goog.dom.getElement('demoCheckbox'); - assertFalse('Checkbox must be unchecked (i.e. unselected)', checkbox.checked); - - goog.testing.events.fireClickSequence(goog.dom.getElement('menuItem1')); - assertTrue('Checkbox must be checked (i.e. selected)', checkbox.checked); - - goog.testing.events.fireClickSequence(goog.dom.getElement('menuItem2')); - assertFalse('Checkbox must be unchecked (i.e. unselected)', checkbox.checked); -} - - -/** - * Tests that set/getSelectionState correctly changes the state - */ -function testSelectionState() { - var node = goog.dom.getElement('demoSelectionMenuButton'); - selectionMenuButton.decorate(node); - - var checkbox = goog.dom.getElement('demoCheckbox'); - assertFalse('Checkbox must be unchecked (i.e. unselected)', checkbox.checked); - - selectionMenuButton.setSelectionState( - goog.ui.SelectionMenuButton.SelectionState.ALL); - assertTrue('Checkbox should be checked when selecting all', checkbox.checked); - assertEquals('selectionState should be ALL', - selectionMenuButton.getSelectionState(), - goog.ui.SelectionMenuButton.SelectionState.ALL); - - selectionMenuButton.setSelectionState( - goog.ui.SelectionMenuButton.SelectionState.NONE); - assertFalse('Checkbox should be checked when selecting all', - checkbox.checked); - assertEquals('selectionState should be NONE', - selectionMenuButton.getSelectionState(), - goog.ui.SelectionMenuButton.SelectionState.NONE); - - selectionMenuButton.setSelectionState( - goog.ui.SelectionMenuButton.SelectionState.SOME); - assertTrue('Checkbox should be checked when selecting all', checkbox.checked); - assertEquals('selectionState should be SOME', - selectionMenuButton.getSelectionState(), - goog.ui.SelectionMenuButton.SelectionState.SOME); -} - - -/** - * Tests that the checkbox gets disabled when the button is disabled - */ -function testCheckboxDisabled() { - var node = goog.dom.getElement('demoSelectionMenuButton'); - selectionMenuButton.decorate(node); - - var checkbox = goog.dom.getElement('demoCheckbox'); - assertFalse('Checkbox must be enabled', checkbox.disabled); - - selectionMenuButton.setEnabled(false); - assertTrue('Checkbox must be disabled', checkbox.disabled); - - selectionMenuButton.setEnabled(true); - assertFalse('Checkbox must be enabled', checkbox.disabled); -} - - -/** - * Tests that clicking the checkbox does not open the menu - */ -function testCheckboxClickMenuClosed() { - var node = goog.dom.getElement('demoSelectionMenuButton'); - selectionMenuButton.decorate(node); - - var checkbox = goog.dom.getElement('demoCheckbox'); - goog.testing.events.fireMouseDownEvent(checkbox); - assertFalse('Menu must be closed when mousedown checkbox', - selectionMenuButton.isOpen()); - goog.testing.events.fireMouseUpEvent(checkbox); - assertFalse('Menu must remain closed when mouseup checkbox', - selectionMenuButton.isOpen()); - - selectionMenuButton.setOpen(true); - goog.testing.events.fireClickSequence(checkbox); - assertFalse('Menu must close when clickin checkbox', - selectionMenuButton.isOpen()); - -} - - -</script> - -<p> - Here's a selectionmenu defined in markup: -</p> -<div id="demoSelectionMenuButton" class="goog-selectionmenubutton-button"> - <input id="demoCheckbox" class="goog-selectionmenubutton-checkbox" type="checkbox"></input> - <div id="demoMenu" class="goog-menu"> - <div id='menuItem1' class="goog-menuitem">All</div> - <div id='menuItem2' class="goog-menuitem">None</div> - <div id='menuItem3' class="goog-menuitem">Read</div> - <div id='menuItem4' class="goog-menuitem">Unread</div> - </div> -</div> - -<div id="footer"></div> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/selectionmodel.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/selectionmodel.js.svn-base deleted file mode 100644 index 8e14e34..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/selectionmodel.js.svn-base +++ /dev/null @@ -1,300 +0,0 @@ -// 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 Single-selection model implemenation. - * - * TODO(attila): Add keyboard & mouse event hooks? - * TODO(attila): Add multiple selection? - * - * @author attila@google.com (Attila Bodis) - */ - - -goog.provide('goog.ui.SelectionModel'); - -goog.require('goog.array'); -goog.require('goog.events.EventTarget'); -goog.require('goog.events.EventType'); - - - -/** - * Single-selection model. Dispatches a {@link goog.events.EventType.SELECT} - * event when a selection is made. - * @param {Array.<Object>=} opt_items Array of items; defaults to empty. - * @extends {goog.events.EventTarget} - * @constructor - */ -goog.ui.SelectionModel = function(opt_items) { - goog.events.EventTarget.call(this); - - /** - * Array of items controlled by the selection model. If the items support - * the {@code setSelected(Boolean)} interface, they will be (de)selected - * as needed. - * @type {!Array.<Object>} - * @private - */ - this.items_ = []; - this.addItems(opt_items); -}; -goog.inherits(goog.ui.SelectionModel, goog.events.EventTarget); - - -/** - * The currently selected item (null if none). - * @type {Object} - * @private - */ -goog.ui.SelectionModel.prototype.selectedItem_ = null; - - -/** - * Selection handler function. Called with two arguments (the item to be - * selected or deselected, and a Boolean indicating whether the item is to - * be selected or deselected). - * @type {Function} - * @private - */ -goog.ui.SelectionModel.prototype.selectionHandler_ = null; - - -/** - * Returns the selection handler function used by the selection model to change - * the internal selection state of items under its control. - * @return {Function} Selection handler function (null if none). - */ -goog.ui.SelectionModel.prototype.getSelectionHandler = function() { - return this.selectionHandler_; -}; - - -/** - * Sets the selection handler function to be used by the selection model to - * change the internal selection state of items under its control. The - * function must take two arguments: an item and a Boolean to indicate whether - * the item is to be selected or deselected. Selection handler functions are - * only needed if the items in the selection model don't natively support the - * {@code setSelected(Boolean)} interface. - * @param {Function} handler Selection handler function. - */ -goog.ui.SelectionModel.prototype.setSelectionHandler = function(handler) { - this.selectionHandler_ = handler; -}; - - -/** - * Returns the number of items controlled by the selection model. - * @return {number} Number of items. - */ -goog.ui.SelectionModel.prototype.getItemCount = function() { - return this.items_.length; -}; - - -/** - * Returns the 0-based index of the given item within the selection model, or - * -1 if no such item is found. - * @param {Object|undefined} item Item to look for. - * @return {number} Index of the given item (-1 if none). - */ -goog.ui.SelectionModel.prototype.indexOfItem = function(item) { - return item ? goog.array.indexOf(this.items_, item) : -1; -}; - - -/** - * @return {Object|undefined} The first item, or undefined if there are no items - * in the model. - */ -goog.ui.SelectionModel.prototype.getFirst = function() { - return this.items_[0]; -}; - - -/** - * @return {Object|undefined} The last item, or undefined if there are no items - * in the model. - */ -goog.ui.SelectionModel.prototype.getLast = function() { - return this.items_[this.items_.length - 1]; -}; - - -/** - * Returns the item at the given 0-based index. - * @param {number} index Index of the item to return. - * @return {Object} Item at the given index (null if none). - */ -goog.ui.SelectionModel.prototype.getItemAt = function(index) { - return this.items_[index] || null; -}; - - -/** - * Bulk-adds items to the selection model. This is more efficient than calling - * {@link #addItem} for each new item. - * @param {Array.<Object>|undefined} items New items to add. - */ -goog.ui.SelectionModel.prototype.addItems = function(items) { - if (items) { - // New items shouldn't be selected. - goog.array.forEach(items, function(item) { - this.selectItem_(item, false); - }, this); - goog.array.extend(this.items_, items); - } -}; - - -/** - * Adds an item at the end of the list. - * @param {Object} item Item to add. - */ -goog.ui.SelectionModel.prototype.addItem = function(item) { - this.addItemAt(item, this.getItemCount()); -}; - - -/** - * Adds an item at the given index. - * @param {Object} item Item to add. - * @param {number} index Index at which to add the new item. - */ -goog.ui.SelectionModel.prototype.addItemAt = function(item, index) { - if (item) { - // New items must not be selected. - this.selectItem_(item, false); - goog.array.insertAt(this.items_, item, index); - } -}; - - -/** - * Removes the given item (if it exists). Dispatches a {@code SELECT} event if - * the removed item was the currently selected item. - * @param {Object} item Item to remove. - */ -goog.ui.SelectionModel.prototype.removeItem = function(item) { - if (item && goog.array.remove(this.items_, item)) { - if (item == this.selectedItem_) { - this.selectedItem_ = null; - this.dispatchEvent(goog.events.EventType.SELECT); - } - } -}; - - -/** - * Removes the item at the given index. - * @param {number} index Index of the item to remove. - */ -goog.ui.SelectionModel.prototype.removeItemAt = function(index) { - this.removeItem(this.getItemAt(index)); -}; - - -/** - * @return {Object} The currently selected item, or null if none. - */ -goog.ui.SelectionModel.prototype.getSelectedItem = function() { - return this.selectedItem_; -}; - - -/** - * @return {!Array.<Object>} All items in the selection model. - */ -goog.ui.SelectionModel.prototype.getItems = function() { - return goog.array.clone(this.items_); -}; - - -/** - * Selects the given item, deselecting any previously selected item, and - * dispatches a {@code SELECT} event. - * @param {Object} item Item to select (null to clear the selection). - */ -goog.ui.SelectionModel.prototype.setSelectedItem = function(item) { - if (item != this.selectedItem_) { - this.selectItem_(this.selectedItem_, false); - this.selectedItem_ = item; - this.selectItem_(item, true); - } - - // Always dispatch a SELECT event; let listeners decide what to do if the - // selected item hasn't changed. - this.dispatchEvent(goog.events.EventType.SELECT); -}; - - -/** - * @return {number} The 0-based index of the currently selected item, or -1 - * if none. - */ -goog.ui.SelectionModel.prototype.getSelectedIndex = function() { - return this.indexOfItem(this.selectedItem_); -}; - - -/** - * Selects the item at the given index, deselecting any previously selected - * item, and dispatches a {@code SELECT} event. - * @param {number} index Index to select (-1 to clear the selection). - */ -goog.ui.SelectionModel.prototype.setSelectedIndex = function(index) { - this.setSelectedItem(this.getItemAt(index)); -}; - - -/** - * Clears the selection model by removing all items from the selection. - */ -goog.ui.SelectionModel.prototype.clear = function() { - goog.array.clear(this.items_); - this.selectedItem_ = null; -}; - - -/** @override */ -goog.ui.SelectionModel.prototype.disposeInternal = function() { - goog.ui.SelectionModel.superClass_.disposeInternal.call(this); - delete this.items_; - this.selectedItem_ = null; -}; - - -/** - * Private helper; selects or deselects the given item based on the value of - * the {@code select} argument. If a selection handler has been registered - * (via {@link #setSelectionHandler}, calls it to update the internal selection - * state of the item. Otherwise, attempts to call {@code setSelected(Boolean)} - * on the item itself, provided the object supports that interface. - * @param {Object} item Item to select or deselect. - * @param {boolean} select If true, the object will be selected; if false, it - * will be deselected. - * @private - */ -goog.ui.SelectionModel.prototype.selectItem_ = function(item, select) { - if (item) { - if (typeof this.selectionHandler_ == 'function') { - // Use the registered selection handler function. - this.selectionHandler_(item, select); - } else if (typeof item.setSelected == 'function') { - // Call setSelected() on the item, if it supports it. - item.setSelected(select); - } - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/selectionmodel_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/selectionmodel_test.html.svn-base deleted file mode 100644 index 64f1551..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/selectionmodel_test.html.svn-base +++ /dev/null @@ -1,225 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2011 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> - <title>Closure Unit Tests - goog.ui.SelectionModel</title> - <script src="../base.js"></script> - <script> - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.recordFunction'); - goog.require('goog.ui.SelectionModel'); - </script> -</head> -<body> - -<script> - -var selectionModel, items, addedItem, addedItems; - -function setUp() { - items = [1, 2, 3, 4]; - addedItem = 5; - addedItems = [6, 7, 8]; - selectionModel = new goog.ui.SelectionModel(items); -} - -function tearDown() { - goog.dispose(selectionModel); -} - -/* - * Checks that the selection model returns the correct item count. - */ -function testGetItemCount() { - assertEquals(items.length, selectionModel.getItemCount()); -} - -/* - * Checks that the correct first element is returned by the selection model. - */ -function testGetFirst() { - assertEquals(items[0], selectionModel.getFirst()); -} - -/* - * Checks that the correct last element is returned by the selection model. - */ -function testGetLast() { - assertEquals(items[items.length - 1], selectionModel.getLast()); -} - -/* - * Tests the behavior of goog.ui.SelectionModel.getItemAt(index). - */ -function testGetItemAt() { - goog.array.forEach(items, - function(item, i) { - assertEquals(item, selectionModel.getItemAt(i)); - }); -} - -/* - * Checks that an item can be correctly added to the selection model. - */ -function testAddItem() { - assertEquals(items.length, selectionModel.getItemCount()); - - selectionModel.addItem(addedItem); - - assertEquals(items.length + 1, selectionModel.getItemCount()); - assertEquals(addedItem, selectionModel.getLast()); -} - -/* - * Checks that an item can be added to the selection model at a specific index. - */ -function testAddItemAt() { - assertEquals(items.length, selectionModel.getItemCount()); - - var insertIndex = 2; - assertEquals(items[insertIndex], selectionModel.getItemAt(insertIndex)); - - selectionModel.addItemAt(addedItem, insertIndex); - - var resultArray = goog.array.clone(items); - goog.array.insertAt(resultArray, addedItem, insertIndex); - - assertEquals(items.length + 1, selectionModel.getItemCount()); - assertEquals(addedItem, selectionModel.getItemAt(insertIndex)); - assertArrayEquals(resultArray, selectionModel.getItems()); -} - -/* - * Checks that multiple items can be correctly added to the selection model. - */ -function testAddItems() { - assertEquals(items.length, selectionModel.getItemCount()); - - selectionModel.addItems(addedItems); - - assertEquals(items.length + addedItems.length, selectionModel.getItemCount()); - - var resultArray = goog.array.concat(items, addedItems); - assertArrayEquals(resultArray, selectionModel.getItems()); -} - -/* - * Checks that all elements can be removed from the selection model. - */ -function testClear() { - assertArrayEquals(items, selectionModel.getItems()); - - selectionModel.clear(); - - assertArrayEquals([], selectionModel.getItems()); -} - -/* - * Checks that all items can be obtained from the selection model. - */ -function testGetItems() { - assertArrayEquals(items, selectionModel.getItems()); -}; - -/* - * Checks that an item's index can be found in the selection model. - */ -function testIndexOfItem() { - goog.array.forEach(items, - function(item, i) { - assertEquals(i, selectionModel.indexOfItem(item)); - }); -} - -/* - * Checks that an item can be removed from the selection model. - */ -function testRemoveItem() { - assertEquals(items.length, selectionModel.getItemCount()); - - var resultArray = goog.array.clone(items); - goog.array.removeAt(resultArray, 2); - - selectionModel.removeItem(items[2]); - - assertEquals(items.length - 1, selectionModel.getItemCount()); - assertArrayEquals(resultArray, selectionModel.getItems()); -} - -/* - * Checks that an item at a particular index can be removed from the selection - * model. - */ -function testRemoveItemAt() { - assertEquals(items.length, selectionModel.getItemCount()); - - var resultArray = goog.array.clone(items); - var removeIndex = 2; - - goog.array.removeAt(resultArray, removeIndex); - - selectionModel.removeItemAt(removeIndex); - - assertEquals(items.length - 1, selectionModel.getItemCount()); - assertNotEquals(items[removeIndex], selectionModel.getItemAt(removeIndex)); - assertArrayEquals(resultArray, selectionModel.getItems()); -} - -/* - * Checks that item selection at a particular index works. - */ -function testSelectedIndex() { - // Default selected index is -1 - assertEquals(-1, selectionModel.getSelectedIndex()); - - selectionModel.setSelectedIndex(2); - - assertEquals(2, selectionModel.getSelectedIndex()); - assertEquals(items[2], selectionModel.getSelectedItem()); -} - -/* - * Checks that items can be selected in the selection model. - */ -function testSelectedItem() { - assertNull(selectionModel.getSelectedItem()); - - selectionModel.setSelectedItem(items[1]); - - assertNotNull(selectionModel.getSelectedItem()); - assertEquals(items[1], selectionModel.getSelectedItem()); - assertEquals(1, selectionModel.getSelectedIndex()); -} - -/* - * Checks that an installed handler is called on selection change. - */ -function testSelectionHandler() { - var myRecordFunction = new goog.testing.recordFunction(); - - selectionModel.setSelectionHandler(myRecordFunction); - - // Select index 2 - selectionModel.setSelectedIndex(2); - // De-select 2 and select 3 - selectionModel.setSelectedIndex(3); - - var recordCalls = myRecordFunction.getCalls(); - - assertEquals(3, recordCalls.length); - // Calls: Select items[2], de-select items[2], select items[3] - assertArrayEquals([items[2], true], recordCalls[0].getArguments()); - assertArrayEquals([items[2], false], recordCalls[1].getArguments()); - assertArrayEquals([items[3], true], recordCalls[2].getArguments()); -} -</script> - -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/separator.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/separator.js.svn-base deleted file mode 100644 index 457ad56..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/separator.js.svn-base +++ /dev/null @@ -1,75 +0,0 @@ -// 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 a separator, with renderers for both - * horizontal (menu) and vertical (toolbar) separators. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.Separator'); - -goog.require('goog.dom.a11y'); -goog.require('goog.ui.Component.State'); -goog.require('goog.ui.Control'); -goog.require('goog.ui.MenuSeparatorRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * Class representing a separator. Although it extends {@link goog.ui.Control}, - * the Separator class doesn't allocate any event handlers, nor does it change - * its appearance on mouseover, etc. - * @param {goog.ui.MenuSeparatorRenderer=} opt_renderer Renderer to render or - * decorate the separator; defaults to {@link goog.ui.MenuSeparatorRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for - * document interaction. - * @constructor - * @extends {goog.ui.Control} - */ -goog.ui.Separator = function(opt_renderer, opt_domHelper) { - goog.ui.Control.call(this, null, opt_renderer || - goog.ui.MenuSeparatorRenderer.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); - - // Separators are always considered disabled. - this.setStateInternal(goog.ui.Component.State.DISABLED); -}; -goog.inherits(goog.ui.Separator, goog.ui.Control); - - -/** - * Configures the component after its DOM has been rendered. Overrides - * {@link goog.ui.Control#enterDocument} by making sure no event handler - * is allocated. - */ -goog.ui.Separator.prototype.enterDocument = function() { - goog.ui.Separator.superClass_.enterDocument.call(this); - goog.dom.a11y.setRole(this.getElement(), '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(); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/serverchart.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/serverchart.js.svn-base deleted file mode 100644 index f844506..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/serverchart.js.svn-base +++ /dev/null @@ -1,1831 +0,0 @@ -// 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 generating chart PNGs using Google Chart Server. - * - * @see ../demos/serverchart.html - */ - - -/** - * Namespace for chart functions - */ -goog.provide('goog.ui.ServerChart'); -goog.provide('goog.ui.ServerChart.AxisDisplayType'); -goog.provide('goog.ui.ServerChart.ChartType'); -goog.provide('goog.ui.ServerChart.EncodingType'); -goog.provide('goog.ui.ServerChart.Event'); -goog.provide('goog.ui.ServerChart.LegendPosition'); -goog.provide('goog.ui.ServerChart.MaximumValue'); -goog.provide('goog.ui.ServerChart.MultiAxisAlignment'); -goog.provide('goog.ui.ServerChart.MultiAxisType'); -goog.provide('goog.ui.ServerChart.UriParam'); -goog.provide('goog.ui.ServerChart.UriTooLongEvent'); - -goog.require('goog.Uri'); -goog.require('goog.array'); -goog.require('goog.asserts'); -goog.require('goog.events.Event'); -goog.require('goog.string'); -goog.require('goog.ui.Component'); - - - -/** - * Will construct a chart using Google's chartserver. - * - * @param {goog.ui.ServerChart.ChartType} type The chart type. - * @param {number=} opt_width The width of the chart. - * @param {number=} opt_height The height of the chart. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM Helper. - * @param {string=} opt_uri Optional uri used to connect to the chart server, if - * different than goog.ui.ServerChart.CHART_SERVER_SCHEME_INDEPENDENT_URI. - * @constructor - * @extends {goog.ui.Component} - */ -goog.ui.ServerChart = function(type, opt_width, opt_height, opt_domHelper, - opt_uri) { - goog.ui.Component.call(this, opt_domHelper); - - /** - * Image URI. - * @type {goog.Uri} - * @private - */ - this.uri_ = new goog.Uri( - opt_uri || goog.ui.ServerChart.CHART_SERVER_SCHEME_INDEPENDENT_URI); - - /** - * Encoding method for the URI data format. - * @type {goog.ui.ServerChart.EncodingType} - * @private - */ - this.encodingType_ = goog.ui.ServerChart.EncodingType.AUTOMATIC; - - /** - * Two-dimensional array of the data sets on the chart. - * @type {Array.<Array.<number>>} - * @private - */ - this.dataSets_ = []; - - /** - * Colors for each data set. - * @type {Array.<string>} - * @private - */ - this.setColors_ = []; - - /** - * Legend texts for each data set. - * @type {Array.<string>} - * @private - */ - this.setLegendTexts_ = []; - - /** - * Labels on the X-axis. - * @type {Array.<string>} - * @private - */ - this.xLabels_ = []; - - /** - * Labels on the left along the Y-axis. - * @type {Array.<string>} - * @private - */ - this.leftLabels_ = []; - - /** - * Labels on the right along the Y-axis. - * @type {Array.<string>} - * @private - */ - this.rightLabels_ = []; - - /** - * Axis type for each multi-axis in the chart. The indices into this array - * also work as the reference index for all other multi-axis properties. - * @type {Array.<goog.ui.ServerChart.MultiAxisType>} - * @private - */ - this.multiAxisType_ = []; - - /** - * Axis text for each multi-axis in the chart, indexed by the indices from - * multiAxisType_ in a sparse array. - * @type {Object} - * @private - */ - this.multiAxisLabelText_ = {}; - - - /** - * Axis position for each multi-axis in the chart, indexed by the indices - * from multiAxisType_ in a sparse array. - * @type {Object} - * @private - */ - this.multiAxisLabelPosition_ = {}; - - /** - * Axis range for each multi-axis in the chart, indexed by the indices from - * multiAxisType_ in a sparse array. - * @type {Object} - * @private - */ - this.multiAxisRange_ = {}; - - /** - * Axis style for each multi-axis in the chart, indexed by the indices from - * multiAxisType_ in a sparse array. - * @type {Object} - * @private - */ - this.multiAxisLabelStyle_ = {}; - - this.setType(type); - this.setSize(opt_width, opt_height); - - /** - * Minimum value for the chart (used for normalization). By default, - * this is set to infinity, and is eventually updated to the lowest given - * value in the data. The minimum value is then subtracted from all other - * values. For a pie chart, subtracting the minimum value does not make - * sense, so minValue_ is set to zero because 0 is the additive identity. - * @type {number} - * @private - */ - this.minValue_ = this.isPieChart() ? 0 : Infinity; -}; -goog.inherits(goog.ui.ServerChart, goog.ui.Component); - - -/** - * Base scheme-independent URI for the chart renderer. - * @type {string} - */ -goog.ui.ServerChart.CHART_SERVER_SCHEME_INDEPENDENT_URI = - '//chart.googleapis.com/chart'; - - -/** - * Base HTTP URI for the chart renderer. - * @type {string} - */ -goog.ui.ServerChart.CHART_SERVER_HTTP_URI = - 'http://chart.googleapis.com/chart'; - - -/** - * Base HTTPS URI for the chart renderer. - * @type {string} - */ -goog.ui.ServerChart.CHART_SERVER_HTTPS_URI = - 'https://chart.googleapis.com/chart'; - - -/** - * Base URI for the chart renderer. - * @type {string} - * @deprecated Use - * {@link goog.ui.ServerChart.CHART_SERVER_SCHEME_INDEPENDENT_URI}, - * {@link goog.ui.ServerChart.CHART_SERVER_HTTP_URI} or - * {@link goog.ui.ServerChart.CHART_SERVER_HTTPS_URI} instead. - */ -goog.ui.ServerChart.CHART_SERVER_URI = - goog.ui.ServerChart.CHART_SERVER_HTTP_URI; - - -/** - * The 0 - 1.0 ("fraction of the range") value to use when getMinValue() == - * getMaxValue(). This determines, for example, the vertical position - * of the line in a flat line-chart. - * @type {number} - */ -goog.ui.ServerChart.DEFAULT_NORMALIZATION = 0.5; - - -/** - * The upper limit on the length of the chart image URI, after encoding. - * If the URI's length equals or exceeds it, goog.ui.ServerChart.UriTooLongEvent - * is dispatched on the goog.ui.ServerChart object. - * @type {number} - * @private - */ -goog.ui.ServerChart.prototype.uriLengthLimit_ = 2048; - - -/** - * Number of gridlines along the X-axis. - * @type {number} - * @private - */ -goog.ui.ServerChart.prototype.gridX_ = 0; - - -/** - * Number of gridlines along the Y-axis. - * @type {number} - * @private - */ -goog.ui.ServerChart.prototype.gridY_ = 0; - - -/** - * Maximum value for the chart (used for normalization). The minimum is - * declared in the constructor. - * @type {number} - * @private - */ -goog.ui.ServerChart.prototype.maxValue_ = -Infinity; - - -/** - * Chart title. - * @type {?string} - * @private - */ -goog.ui.ServerChart.prototype.title_ = null; - - -/** - * Chart title size. - * @type {number} - * @private - */ -goog.ui.ServerChart.prototype.titleSize_ = 13.5; - - -/** - * Chart title color. - * @type {string} - * @private - */ -goog.ui.ServerChart.prototype.titleColor_ = '333333'; - - -/** - * Chart legend. - * @type {Array.<string>?} - * @private - */ -goog.ui.ServerChart.prototype.legend_ = null; - - -/** - * ChartServer supports using data sets to position markers. A data set - * that is being used for positioning only can be made "invisible", in other - * words, the caller can indicate to ChartServer that ordinary chart elements - * (e.g. bars in a bar chart) should not be drawn on the data points of the - * invisible data set. Such data sets must be provided at the end of the - * chd parameter, and if invisible data sets are being used, the chd - * parameter must indicate the number of visible data sets. - * @type {?number} - * @private - */ -goog.ui.ServerChart.prototype.numVisibleDataSets_ = null; - - -/** - * Creates the DOM node (image) needed for the Chart - */ -goog.ui.ServerChart.prototype.createDom = function() { - var size = this.getSize(); - this.setElementInternal(this.getDomHelper().createDom( - 'img', {'src': this.getUri(), - 'class': goog.getCssName('goog-serverchart-image'), - 'width': size[0], 'height': size[1]})); -}; - - -/** - * Decorate an image already in the DOM. - * Expects the following structure: - * <pre> - * - img - * </pre> - * - * @param {Element} img Image to decorate. - */ -goog.ui.ServerChart.prototype.decorateInternal = function(img) { - img.src = this.getUri(); - this.setElementInternal(img); -}; - - -/** - * Updates the image if any of the data or settings have changed. - */ -goog.ui.ServerChart.prototype.updateChart = function() { - if (this.getElement()) { - this.getElement().src = this.getUri(); - } -}; - - -/** - * Sets the URI of the chart. - * - * @param {goog.Uri} uri The chart URI. - */ -goog.ui.ServerChart.prototype.setUri = function(uri) { - this.uri_ = uri; -}; - - -/** - * Returns the URI of the chart. - * - * @return {goog.Uri} The chart URI. - */ -goog.ui.ServerChart.prototype.getUri = function() { - this.computeDataString_(); - return this.uri_; -}; - - -/** - * Returns the upper limit on the length of the chart image URI, after encoding. - * If the URI's length equals or exceeds it, goog.ui.ServerChart.UriTooLongEvent - * is dispatched on the goog.ui.ServerChart object. - * - * @return {number} The chart URI length limit. - */ -goog.ui.ServerChart.prototype.getUriLengthLimit = function() { - return this.uriLengthLimit_; -}; - - -/** - * Sets the upper limit on the length of the chart image URI, after encoding. - * If the URI's length equals or exceeds it, goog.ui.ServerChart.UriTooLongEvent - * is dispatched on the goog.ui.ServerChart object. - * - * @param {number} uriLengthLimit The chart URI length limit. - */ -goog.ui.ServerChart.prototype.setUriLengthLimit = function(uriLengthLimit) { - this.uriLengthLimit_ = uriLengthLimit; -}; - - -/** - * Sets the 'chg' parameter of the chart Uri. - * This is used by various types of charts to specify Grids. - * - * @param {string} value Value for the 'chg' parameter in the chart Uri. - */ -goog.ui.ServerChart.prototype.setGridParameter = function(value) { - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.GRID, value); -}; - - -/** - * Returns the 'chg' parameter of the chart Uri. - * This is used by various types of charts to specify Grids. - * - * @return {string|undefined} The 'chg' parameter of the chart Uri. - */ -goog.ui.ServerChart.prototype.getGridParameter = function() { - return /** @type {string} */ ( - this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.GRID)); -}; - - -/** - * Sets the 'chm' parameter of the chart Uri. - * This is used by various types of charts to specify Markers. - * - * @param {string} value Value for the 'chm' parameter in the chart Uri. - */ -goog.ui.ServerChart.prototype.setMarkerParameter = function(value) { - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.MARKERS, value); -}; - - -/** - * Returns the 'chm' parameter of the chart Uri. - * This is used by various types of charts to specify Markers. - * - * @return {string|undefined} The 'chm' parameter of the chart Uri. - */ -goog.ui.ServerChart.prototype.getMarkerParameter = function() { - return /** @type {string} */ ( - this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.MARKERS)); -}; - - -/** - * Sets the 'chp' parameter of the chart Uri. - * This is used by various types of charts to specify certain options. - * e.g., finance charts use this to designate which line is the 0 axis. - * - * @param {string|number} value Value for the 'chp' parameter in the chart Uri. - */ -goog.ui.ServerChart.prototype.setMiscParameter = function(value) { - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.MISC_PARAMS, - String(value)); -}; - - -/** - * Returns the 'chp' parameter of the chart Uri. - * This is used by various types of charts to specify certain options. - * e.g., finance charts use this to designate which line is the 0 axis. - * - * @return {string|undefined} The 'chp' parameter of the chart Uri. - */ -goog.ui.ServerChart.prototype.getMiscParameter = function() { - return /** @type {string} */ ( - this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.MISC_PARAMS)); -}; - - -/** - * Enum of chart data encoding types - * - * @enum {string} - */ -goog.ui.ServerChart.EncodingType = { - AUTOMATIC: '', - EXTENDED: 'e', - SIMPLE: 's', - TEXT: 't' -}; - - -/** - * Enum of chart types with their short names used by the chartserver. - * - * @enum {string} - */ -goog.ui.ServerChart.ChartType = { - BAR: 'br', - CLOCK: 'cf', - CONCENTRIC_PIE: 'pc', - FILLEDLINE: 'lr', - FINANCE: 'lfi', - GOOGLEOMETER: 'gom', - HORIZONTAL_GROUPED_BAR: 'bhg', - HORIZONTAL_STACKED_BAR: 'bhs', - LINE: 'lc', - MAP: 't', - MAPUSA: 'tuss', - MAPWORLD: 'twoc', - PIE: 'p', - PIE3D: 'p3', - RADAR: 'rs', - SCATTER: 's', - SPARKLINE: 'ls', - VENN: 'v', - VERTICAL_GROUPED_BAR: 'bvg', - VERTICAL_STACKED_BAR: 'bvs', - XYLINE: 'lxy' -}; - - -/** - * Enum of multi-axis types. - * - * @enum {string} - */ -goog.ui.ServerChart.MultiAxisType = { - X_AXIS: 'x', - LEFT_Y_AXIS: 'y', - RIGHT_Y_AXIS: 'r', - TOP_AXIS: 't' -}; - - -/** - * Enum of multi-axis alignments. - * - * @enum {number} - */ -goog.ui.ServerChart.MultiAxisAlignment = { - ALIGN_LEFT: -1, - ALIGN_CENTER: 0, - ALIGN_RIGHT: 1 -}; - - -/** - * Enum of legend positions. - * - * @enum {string} - */ -goog.ui.ServerChart.LegendPosition = { - TOP: 't', - BOTTOM: 'b', - LEFT: 'l', - RIGHT: 'r' -}; - - -/** - * Enum of line and tick options for an axis. - * - * @enum {string} - */ -goog.ui.ServerChart.AxisDisplayType = { - LINE_AND_TICKS: 'lt', - LINE: 'l', - TICKS: 't' -}; - - -/** - * Enum of chart maximum values in pixels, as listed at: - * http://code.google.com/apis/chart/basics.html - * - * @enum {number} - */ -goog.ui.ServerChart.MaximumValue = { - WIDTH: 1000, - HEIGHT: 1000, - MAP_WIDTH: 440, - MAP_HEIGHT: 220, - TOTAL_AREA: 300000 -}; - - -/** - * Enum of ChartServer URI parameters. - * - * @enum {string} - */ -goog.ui.ServerChart.UriParam = { - BACKGROUND_FILL: 'chf', - BAR_HEIGHT: 'chbh', - DATA: 'chd', - DATA_COLORS: 'chco', - DATA_LABELS: 'chld', - DATA_SCALING: 'chds', - DIGITAL_SIGNATURE: 'sig', - GEOGRAPHICAL_REGION: 'chtm', - GRID: 'chg', - LABEL_COLORS: 'chlc', - LEFT_Y_LABELS: 'chly', - LEGEND: 'chdl', - LEGEND_POSITION: 'chdlp', - LEGEND_TEXTS: 'chdl', - LINE_STYLES: 'chls', - MARGINS: 'chma', - MARKERS: 'chm', - MISC_PARAMS: 'chp', - MULTI_AXIS_LABEL_POSITION: 'chxp', - MULTI_AXIS_LABEL_TEXT: 'chxl', - MULTI_AXIS_RANGE: 'chxr', - MULTI_AXIS_STYLE: 'chxs', - MULTI_AXIS_TYPES: 'chxt', - RIGHT_LABELS: 'chlr', - RIGHT_LABEL_POSITIONS: 'chlrp', - SIZE: 'chs', - TITLE: 'chtt', - TITLE_FORMAT: 'chts', - TYPE: 'cht', - X_AXIS_STYLE: 'chx', - X_LABELS: 'chl' -}; - - -/** - * Sets the background fill. - * - * @param {Array.<Object>} fill An array of background fill specification - * objects. Each object may have the following properties: - * {string} area The area to fill, either 'bg' for background or 'c' for - * chart area. The default is 'bg'. - * {string} color (required) The color of the background fill. - * // TODO(user): Add support for gradient/stripes, which requires - * // a different object structure. - */ -goog.ui.ServerChart.prototype.setBackgroundFill = function(fill) { - var value = []; - goog.array.forEach(fill, function(spec) { - spec.area = spec.area || 'bg'; - spec.effect = spec.effect || 's'; - value.push([spec.area, spec.effect, spec.color].join(',')); - }); - value = value.join('|'); - this.setParameterValue(goog.ui.ServerChart.UriParam.BACKGROUND_FILL, value); -}; - - -/** - * Returns the background fill. - * - * @return {Array.<Object>} An array of background fill specifications. - * If the fill specification string is in an unsupported format, the method - * returns an empty array. - */ -goog.ui.ServerChart.prototype.getBackgroundFill = function() { - var value = - this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.BACKGROUND_FILL); - var result = []; - if (goog.isDefAndNotNull(value)) { - var fillSpecifications = value.split('|'); - var valid = true; - goog.array.forEach(fillSpecifications, function(spec) { - spec = spec.split(','); - if (valid && spec[1] == 's') { - result.push({area: spec[0], effect: spec[1], color: spec[2]}); - } else { - // If the format is unsupported, return an empty array. - result = []; - valid = false; - } - }); - } - return result; -}; - - -/** - * Sets the encoding type. - * - * @param {goog.ui.ServerChart.EncodingType} type Desired data encoding type. - */ -goog.ui.ServerChart.prototype.setEncodingType = function(type) { - this.encodingType_ = type; -}; - - -/** - * Gets the encoding type. - * - * @return {goog.ui.ServerChart.EncodingType} The encoding type. - */ -goog.ui.ServerChart.prototype.getEncodingType = function() { - return this.encodingType_; -}; - - -/** - * Sets the chart type. - * - * @param {goog.ui.ServerChart.ChartType} type The desired chart type. - */ -goog.ui.ServerChart.prototype.setType = function(type) { - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.TYPE, type); -}; - - -/** - * Returns the chart type. - * - * @return {goog.ui.ServerChart.ChartType} The chart type. - */ -goog.ui.ServerChart.prototype.getType = function() { - return /** @type {goog.ui.ServerChart.ChartType} */ ( - this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.TYPE)); -}; - - -/** - * Sets the chart size. - * - * @param {number=} opt_width Optional chart width, defaults to 300. - * @param {number=} opt_height Optional chart height, defaults to 150. - */ -goog.ui.ServerChart.prototype.setSize = function(opt_width, opt_height) { - var sizeString = [opt_width || 300, opt_height || 150].join('x'); - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.SIZE, sizeString); -}; - - -/** - * Returns the chart size. - * - * @return {Array.<string>} [Width, Height]. - */ -goog.ui.ServerChart.prototype.getSize = function() { - var sizeStr = this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.SIZE); - return sizeStr.split('x'); -}; - - -/** - * Sets the minimum value of the chart. - * - * @param {number} minValue The minimum value of the chart. - */ -goog.ui.ServerChart.prototype.setMinValue = function(minValue) { - this.minValue_ = minValue; -}; - - -/** - * @return {number} The minimum value of the chart. - */ -goog.ui.ServerChart.prototype.getMinValue = function() { - return this.minValue_; -}; - - -/** - * Sets the maximum value of the chart. - * - * @param {number} maxValue The maximum value of the chart. - */ -goog.ui.ServerChart.prototype.setMaxValue = function(maxValue) { - this.maxValue_ = maxValue; -}; - - -/** - * @return {number} The maximum value of the chart. - */ -goog.ui.ServerChart.prototype.getMaxValue = function() { - return this.maxValue_; -}; - - -/** - * Sets the chart margins. - * - * @param {number} leftMargin The size in pixels of the left margin. - * @param {number} rightMargin The size in pixels of the right margin. - * @param {number} topMargin The size in pixels of the top margin. - * @param {number} bottomMargin The size in pixels of the bottom margin. - */ -goog.ui.ServerChart.prototype.setMargins = function(leftMargin, rightMargin, - topMargin, bottomMargin) { - var margins = [leftMargin, rightMargin, topMargin, bottomMargin].join(','); - var UriParam = goog.ui.ServerChart.UriParam; - this.uri_.setParameterValue(UriParam.MARGINS, margins); -}; - - -/** - * Sets the number of grid lines along the X-axis. - * - * @param {number} gridlines The number of X-axis grid lines. - */ -goog.ui.ServerChart.prototype.setGridX = function(gridlines) { - // Need data for this to work. - this.gridX_ = gridlines; - this.setGrids_(this.gridX_, this.gridY_); -}; - - -/** - * @return {number} The number of gridlines along the X-axis. - */ -goog.ui.ServerChart.prototype.getGridX = function() { - return this.gridX_; -}; - - -/** - * Sets the number of grid lines along the Y-axis. - * - * @param {number} gridlines The number of Y-axis grid lines. - */ -goog.ui.ServerChart.prototype.setGridY = function(gridlines) { - // Need data for this to work. - this.gridY_ = gridlines; - this.setGrids_(this.gridX_, this.gridY_); -}; - - -/** - * @return {number} The number of gridlines along the Y-axis. - */ -goog.ui.ServerChart.prototype.getGridY = function() { - return this.gridY_; -}; - - -/** - * Sets the grids for the chart - * - * @private - * @param {number} x The number of grid lines along the x-axis. - * @param {number} y The number of grid lines along the y-axis. - */ -goog.ui.ServerChart.prototype.setGrids_ = function(x, y) { - var gridArray = [x == 0 ? 0 : 100 / x, - y == 0 ? 0 : 100 / y]; - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.GRID, - gridArray.join(',')); -}; - - -/** - * Sets the X Labels for the chart. - * - * @param {Array.<string>} labels The X Labels for the chart. - */ -goog.ui.ServerChart.prototype.setXLabels = function(labels) { - this.xLabels_ = labels; - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.X_LABELS, - this.xLabels_.join('|')); -}; - - -/** - * @return {Array.<string>} The X Labels for the chart. - */ -goog.ui.ServerChart.prototype.getXLabels = function() { - return this.xLabels_; -}; - - -/** - * @return {boolean} Whether the chart is a bar chart. - */ -goog.ui.ServerChart.prototype.isBarChart = function() { - var type = this.getType(); - return type == goog.ui.ServerChart.ChartType.BAR || - type == goog.ui.ServerChart.ChartType.HORIZONTAL_GROUPED_BAR || - type == goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR || - type == goog.ui.ServerChart.ChartType.VERTICAL_GROUPED_BAR || - type == goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR; -}; - - -/** - * @return {boolean} Whether the chart is a pie chart. - */ -goog.ui.ServerChart.prototype.isPieChart = function() { - var type = this.getType(); - return type == goog.ui.ServerChart.ChartType.PIE || - type == goog.ui.ServerChart.ChartType.PIE3D || - type == goog.ui.ServerChart.ChartType.CONCENTRIC_PIE; -}; - - -/** - * @return {boolean} Whether the chart is a grouped bar chart. - */ -goog.ui.ServerChart.prototype.isGroupedBarChart = function() { - var type = this.getType(); - return type == goog.ui.ServerChart.ChartType.HORIZONTAL_GROUPED_BAR || - type == goog.ui.ServerChart.ChartType.VERTICAL_GROUPED_BAR; -}; - - -/** - * @return {boolean} Whether the chart is a horizontal bar chart. - */ -goog.ui.ServerChart.prototype.isHorizontalBarChart = function() { - var type = this.getType(); - return type == goog.ui.ServerChart.ChartType.BAR || - type == goog.ui.ServerChart.ChartType.HORIZONTAL_GROUPED_BAR || - type == goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR; -}; - - -/** - * @return {boolean} Whether the chart is a line chart. - */ -goog.ui.ServerChart.prototype.isLineChart = function() { - var type = this.getType(); - return type == goog.ui.ServerChart.ChartType.FILLEDLINE || - type == goog.ui.ServerChart.ChartType.LINE || - type == goog.ui.ServerChart.ChartType.SPARKLINE || - type == goog.ui.ServerChart.ChartType.XYLINE; -}; - - -/** - * @return {boolean} Whether the chart is a map. - */ -goog.ui.ServerChart.prototype.isMap = function() { - var type = this.getType(); - return type == goog.ui.ServerChart.ChartType.MAP || - type == goog.ui.ServerChart.ChartType.MAPUSA || - type == goog.ui.ServerChart.ChartType.MAPWORLD; -}; - - -/** - * @return {boolean} Whether the chart is a stacked bar chart. - */ -goog.ui.ServerChart.prototype.isStackedBarChart = function() { - var type = this.getType(); - return type == goog.ui.ServerChart.ChartType.BAR || - type == goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR || - type == goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR; -}; - - -/** - * @return {boolean} Whether the chart is a vertical bar chart. - */ -goog.ui.ServerChart.prototype.isVerticalBarChart = function() { - var type = this.getType(); - return type == goog.ui.ServerChart.ChartType.VERTICAL_GROUPED_BAR || - type == goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR; -}; - - -/** - * Sets the Left Labels for the chart. - * NOTE: The array should start with the lowest value, and then - * move progessively up the axis. So if you want labels - * from 0 to 100 with 0 at bottom of the graph, then you would - * want to pass something like [0,25,50,75,100]. - * - * @param {Array.<string>} labels The Left Labels for the chart. - */ -goog.ui.ServerChart.prototype.setLeftLabels = function(labels) { - this.leftLabels_ = labels; - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.LEFT_Y_LABELS, - this.leftLabels_.reverse().join('|')); -}; - - -/** - * @return {Array.<string>} The Left Labels for the chart. - */ -goog.ui.ServerChart.prototype.getLeftLabels = function() { - return this.leftLabels_; -}; - - -/** - * Sets the given ChartServer parameter. - * - * @param {goog.ui.ServerChart.UriParam} key The ChartServer parameter to set. - * @param {string} value The value to set for the ChartServer parameter. - */ -goog.ui.ServerChart.prototype.setParameterValue = function(key, value) { - this.uri_.setParameterValue(key, value); -}; - - -/** - * Removes the given ChartServer parameter. - * - * @param {goog.ui.ServerChart.UriParam} key The ChartServer parameter to - * remove. - */ -goog.ui.ServerChart.prototype.removeParameter = function(key) { - this.uri_.removeParameter(key); -}; - - -/** - * Sets the Right Labels for the chart. - * NOTE: The array should start with the lowest value, and then - * move progessively up the axis. So if you want labels - * from 0 to 100 with 0 at bottom of the graph, then you would - * want to pass something like [0,25,50,75,100]. - * - * @param {Array.<string>} labels The Right Labels for the chart. - */ -goog.ui.ServerChart.prototype.setRightLabels = function(labels) { - this.rightLabels_ = labels; - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.RIGHT_LABELS, - this.rightLabels_.reverse().join('|')); -}; - - -/** - * @return {Array.<string>} The Right Labels for the chart. - */ -goog.ui.ServerChart.prototype.getRightLabels = function() { - return this.rightLabels_; -}; - - -/** - * Sets the position relative to the chart where the legend is to be displayed. - * - * @param {goog.ui.ServerChart.LegendPosition} value Legend position. - */ -goog.ui.ServerChart.prototype.setLegendPosition = function(value) { - this.uri_.setParameterValue( - goog.ui.ServerChart.UriParam.LEGEND_POSITION, value); -}; - - -/** - * Returns the position relative to the chart where the legend is to be - * displayed. - * - * @return {goog.ui.ServerChart.LegendPosition} Legend position. - */ -goog.ui.ServerChart.prototype.getLegendPosition = function() { - return /** @type {goog.ui.ServerChart.LegendPosition} */ ( - this.uri_.getParameterValue( - goog.ui.ServerChart.UriParam.LEGEND_POSITION)); -}; - - -/** - * Sets the number of "visible" data sets. All data sets that come after - * the visible data set are not drawn as part of the chart. Instead, they - * are available for positioning markers. - - * @param {?number} n The number of visible data sets, or null if all data - * sets are to be visible. - */ -goog.ui.ServerChart.prototype.setNumVisibleDataSets = function(n) { - this.numVisibleDataSets_ = n; -}; - - -/** - * Returns the number of "visible" data sets. All data sets that come after - * the visible data set are not drawn as part of the chart. Instead, they - * are available for positioning markers. - * - * @return {?number} The number of visible data sets, or null if all data - * sets are visible. - */ -goog.ui.ServerChart.prototype.getNumVisibleDataSets = function() { - return this.numVisibleDataSets_; -}; - - -/** - * Sets the weight function for a Venn Diagram along with the associated - * colors and legend text. Weights are assigned as follows: - * weights[0] is relative area of circle A. - * weights[1] is relative area of circle B. - * weights[2] is relative area of circle C. - * weights[3] is relative area of overlap of circles A and B. - * weights[4] is relative area of overlap of circles A and C. - * weights[5] is relative area of overlap of circles B and C. - * weights[6] is relative area of overlap of circles A, B and C. - * For a two circle Venn Diagram the weights are assigned as follows: - * weights[0] is relative area of circle A. - * weights[1] is relative area of circle B. - * weights[2] is relative area of overlap of circles A and B. - * - * @param {Array.<number>} weights The relative weights of the circles. - * @param {Array.<string>=} opt_legendText The legend labels for the circles. - * @param {Array.<string>=} opt_colors The colors for the circles. - */ -goog.ui.ServerChart.prototype.setVennSeries = function( - weights, opt_legendText, opt_colors) { - if (this.getType() != goog.ui.ServerChart.ChartType.VENN) { - throw Error('Can only set a weight function for a Venn diagram.'); - } - var dataMin = this.arrayMin_(weights); - if (dataMin < this.minValue_) { - this.minValue_ = dataMin; - } - var dataMax = this.arrayMax_(weights); - if (dataMax > this.maxValue_) { - this.maxValue_ = dataMax; - } - if (goog.isDef(opt_legendText)) { - goog.array.forEach( - opt_legendText, - goog.bind(function(legend) { - this.setLegendTexts_.push(legend); - }, this)); - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.LEGEND_TEXTS, - this.setLegendTexts_.join('|')); - } - // If the caller only gave three weights, then they wanted a two circle - // Venn Diagram. Create a 3 circle weight function where circle C has - // area zero. - if (weights.length == 3) { - weights[3] = weights[2]; - weights[2] = 0.0; - } - this.dataSets_.push(weights); - if (goog.isDef(opt_colors)) { - goog.array.forEach(opt_colors, goog.bind(function(color) { - this.setColors_.push(color); - }, this)); - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.DATA_COLORS, - this.setColors_.join(',')); - } -}; - - -/** - * Sets the title of the chart. - * - * @param {string} title The chart title. - */ -goog.ui.ServerChart.prototype.setTitle = function(title) { - this.title_ = title; - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.TITLE, - this.title_.replace(/\n/g, '|')); -}; - - -/** - * Sets the size of the chart title. - * - * @param {number} size The title size, in points. - */ -goog.ui.ServerChart.prototype.setTitleSize = function(size) { - this.titleSize_ = size; - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.TITLE_FORMAT, - this.titleColor_ + ',' + this.titleSize_); -}; - - -/** - * @return {number} size The title size, in points. - */ -goog.ui.ServerChart.prototype.getTitleSize = function() { - return this.titleSize_; -}; - - -/** - * Sets the color of the chart title. - * - * NOTE: The color string should NOT have a '#' at the beginning of it. - * - * @param {string} color The hex value for the title color. - */ -goog.ui.ServerChart.prototype.setTitleColor = function(color) { - this.titleColor_ = color; - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.TITLE_FORMAT, - this.titleColor_ + ',' + this.titleSize_); -}; - - -/** - * @return {string} color The hex value for the title color. - */ -goog.ui.ServerChart.prototype.getTitleColor = function() { - return this.titleColor_; -}; - - -/** - * Adds a legend to the chart. - * - * @param {Array.<string>} legend The legend to add. - */ -goog.ui.ServerChart.prototype.setLegend = function(legend) { - this.legend_ = legend; - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.LEGEND, - this.legend_.join('|')); -}; - - -/** - * Sets the data scaling. - * NOTE: This also changes the encoding type because data scaling will - * only work with {@code goog.ui.ServerChart.EncodingType.TEXT} - * encoding. - * @param {number} minimum The lowest number to apply to the data. - * @param {number} maximum The highest number to apply to the data. - */ -goog.ui.ServerChart.prototype.setDataScaling = function(minimum, maximum) { - this.encodingType_ = goog.ui.ServerChart.EncodingType.TEXT; - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.DATA_SCALING, - minimum + ',' + maximum); -}; - - -/** - * Sets the widths of the bars and the spaces between the bars in a bar - * chart. - * NOTE: If the space between groups is specified but the space between - * bars is left undefined, the space between groups will be interpreted - * as the space between bars because this is the behavior exposed - * in the external developers guide. - * @param {number} barWidth The width of a bar in pixels. - * @param {number=} opt_spaceBars The width of the space between - * bars in a group in pixels. - * @param {number=} opt_spaceGroups The width of the space between - * groups. - */ -goog.ui.ServerChart.prototype.setBarSpaceWidths = function(barWidth, - opt_spaceBars, - opt_spaceGroups) { - var widths = [barWidth]; - if (goog.isDef(opt_spaceBars)) { - widths.push(opt_spaceBars); - } - if (goog.isDef(opt_spaceGroups)) { - widths.push(opt_spaceGroups); - } - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT, - widths.join(',')); -}; - - -/** - * Specifies that the bar width in a bar chart should be calculated - * automatically given the space available in the chart, while optionally - * setting the spaces between the bars. - * NOTE: If the space between groups is specified but the space between - * bars is left undefined, the space between groups will be interpreted - * as the space between bars because this is the behavior exposed - * in the external developers guide. - * @param {number=} opt_spaceBars The width of the space between - * bars in a group in pixels. - * @param {number=} opt_spaceGroups The width of the space between - * groups. - */ -goog.ui.ServerChart.prototype.setAutomaticBarWidth = function(opt_spaceBars, - opt_spaceGroups) { - var widths = ['a']; - if (goog.isDef(opt_spaceBars)) { - widths.push(opt_spaceBars); - } - if (goog.isDef(opt_spaceGroups)) { - widths.push(opt_spaceGroups); - } - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT, - widths.join(',')); -}; - - -/** - * Adds a multi-axis to the chart, and sets its type. Multiple axes of the same - * type can be added. - * - * @param {goog.ui.ServerChart.MultiAxisType} axisType The desired axis type. - * @return {number} The index of the newly inserted axis, suitable for feeding - * to the setMultiAxis*() functions. - */ -goog.ui.ServerChart.prototype.addMultiAxis = function(axisType) { - this.multiAxisType_.push(axisType); - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.MULTI_AXIS_TYPES, - this.multiAxisType_.join(',')); - return this.multiAxisType_.length - 1; -}; - - -/** - * Returns the axis type for the given axis, or all of them in an array if the - * axis number is not given. - * - * @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis. - * @return {goog.ui.ServerChart.MultiAxisType| - * Array.<goog.ui.ServerChart.MultiAxisType>} - * The axis type for the given axis, or all of them in an array if the - * axis number is not given. - */ -goog.ui.ServerChart.prototype.getMultiAxisType = function(opt_axisNumber) { - if (goog.isDef(opt_axisNumber)) { - return this.multiAxisType_[opt_axisNumber]; - } - return this.multiAxisType_; -}; - - -/** - * Sets the label text (usually multiple values) for a given axis, overwriting - * any existing values. - * - * @param {number} axisNumber The axis index, as returned by addMultiAxis. - * @param {Array.<string>} labelText The actual label text to be added. - */ -goog.ui.ServerChart.prototype.setMultiAxisLabelText = function(axisNumber, - labelText) { - this.multiAxisLabelText_[axisNumber] = labelText; - - var axisString = this.computeMultiAxisDataString_(this.multiAxisLabelText_, - ':|', - '|', - '|'); - this.uri_.setParameterValue( - goog.ui.ServerChart.UriParam.MULTI_AXIS_LABEL_TEXT, - axisString); -}; - - -/** - * Returns the label text, or all of them in a two-dimensional array if the - * axis number is not given. - * - * @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis. - * @return {Object|Array.<string>} The label text, or all of them in a - * two-dimensional array if the axis number is not given. - */ -goog.ui.ServerChart.prototype.getMultiAxisLabelText = function(opt_axisNumber) { - if (goog.isDef(opt_axisNumber)) { - return this.multiAxisLabelText_[opt_axisNumber]; - } - return this.multiAxisLabelText_; -}; - - -/** - * Sets the label positions for a given axis, overwriting any existing values. - * The label positions are assumed to be floating-point numbers within the - * range of the axis. - * - * @param {number} axisNumber The axis index, as returned by addMultiAxis. - * @param {Array.<number>} labelPosition The actual label positions to be added. - */ -goog.ui.ServerChart.prototype.setMultiAxisLabelPosition = function( - axisNumber, labelPosition) { - this.multiAxisLabelPosition_[axisNumber] = labelPosition; - - var positionString = this.computeMultiAxisDataString_( - this.multiAxisLabelPosition_, - ',', - ',', - '|'); - this.uri_.setParameterValue( - goog.ui.ServerChart.UriParam.MULTI_AXIS_LABEL_POSITION, - positionString); -}; - - -/** - * Returns the label positions for a given axis number, or all of them in a - * two-dimensional array if the axis number is not given. - * - * @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis. - * @return {Object|Array.<number>} The label positions for a given axis number, - * or all of them in a two-dimensional array if the axis number is not - * given. - */ -goog.ui.ServerChart.prototype.getMultiAxisLabelPosition = - function(opt_axisNumber) { - if (goog.isDef(opt_axisNumber)) { - return this.multiAxisLabelPosition_[opt_axisNumber]; - } - return this.multiAxisLabelPosition_; -}; - - -/** - * Sets the label range for a given axis, overwriting any existing range. - * The default range is from 0 to 100. If the start value is larger than the - * end value, the axis direction is reversed. rangeStart and rangeEnd must - * be two different finite numbers. - * - * @param {number} axisNumber The axis index, as returned by addMultiAxis. - * @param {number} rangeStart The new start of the range. - * @param {number} rangeEnd The new end of the range. - * @param {number=} opt_interval The interval between axis labels. - */ -goog.ui.ServerChart.prototype.setMultiAxisRange = function(axisNumber, - rangeStart, - rangeEnd, - opt_interval) { - goog.asserts.assert(rangeStart != rangeEnd, - 'Range start and end cannot be the same value.'); - goog.asserts.assert(isFinite(rangeStart) && isFinite(rangeEnd), - 'Range start and end must be finite numbers.'); - this.multiAxisRange_[axisNumber] = [rangeStart, rangeEnd]; - if (goog.isDef(opt_interval)) { - this.multiAxisRange_[axisNumber].push(opt_interval); - } - var rangeString = this.computeMultiAxisDataString_(this.multiAxisRange_, - ',', ',', '|'); - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.MULTI_AXIS_RANGE, - rangeString); -}; - - -/** - * Returns the label range for a given axis number as a two-element array of - * (range start, range end), or all of them in a two-dimensional array if the - * axis number is not given. - * - * @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis. - * @return {Object|Array.<number>} The label range for a given axis number as a - * two-element array of (range start, range end), or all of them in a - * two-dimensional array if the axis number is not given. - */ -goog.ui.ServerChart.prototype.getMultiAxisRange = function(opt_axisNumber) { - if (goog.isDef(opt_axisNumber)) { - return this.multiAxisRange_[opt_axisNumber]; - } - return this.multiAxisRange_; -}; - - -/** - * Sets the label style for a given axis, overwriting any existing style. - * The default style is as follows: Default is x-axis labels are centered, left - * hand y-axis labels are right aligned, right hand y-axis labels are left - * aligned. The font size and alignment are optional parameters. - * - * NOTE: The color string should NOT have a '#' at the beginning of it. - * - * @param {number} axisNumber The axis index, as returned by addMultiAxis. - * @param {string} color The hex value for this label's color. - * @param {number=} opt_fontSize The label font size, in pixels. - * @param {goog.ui.ServerChart.MultiAxisAlignment=} opt_alignment The label - * alignment. - * @param {goog.ui.ServerChart.AxisDisplayType=} opt_axisDisplay The axis - * line and ticks. - */ -goog.ui.ServerChart.prototype.setMultiAxisLabelStyle = function(axisNumber, - color, - opt_fontSize, - opt_alignment, - opt_axisDisplay) { - var style = [color]; - if (goog.isDef(opt_fontSize) || goog.isDef(opt_alignment)) { - style.push(opt_fontSize || ''); - } - if (goog.isDef(opt_alignment)) { - style.push(opt_alignment); - } - if (opt_axisDisplay) { - style.push(opt_axisDisplay); - } - this.multiAxisLabelStyle_[axisNumber] = style; - var styleString = this.computeMultiAxisDataString_(this.multiAxisLabelStyle_, - ',', - ',', - '|'); - this.uri_.setParameterValue( - goog.ui.ServerChart.UriParam.MULTI_AXIS_STYLE, - styleString); -}; - - -/** - * Returns the label style for a given axis number as a one- to three-element - * array, or all of them in a two-dimensional array if the axis number is not - * given. - * - * @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis. - * @return {Object|Array.<number>} The label style for a given axis number as a - * one- to three-element array, or all of them in a two-dimensional array if - * the axis number is not given. - */ -goog.ui.ServerChart.prototype.getMultiAxisLabelStyle = - function(opt_axisNumber) { - if (goog.isDef(opt_axisNumber)) { - return this.multiAxisLabelStyle_[opt_axisNumber]; - } - return this.multiAxisLabelStyle_; -}; - - -/** - * Adds a data set. - * NOTE: The color string should NOT have a '#' at the beginning of it. - * - * @param {Array.<number|null>} data An array of numbers (values can be - * NaN or null). - * @param {string} color The hex value for this data set's color. - * @param {string=} opt_legendText The legend text, if any, for this data - * series. NOTE: If specified, all previously added data sets must also - * have a legend text. - */ -goog.ui.ServerChart.prototype.addDataSet = function(data, - color, - opt_legendText) { - var dataMin = this.arrayMin_(data); - if (dataMin < this.minValue_) { - this.minValue_ = dataMin; - } - - var dataMax = this.arrayMax_(data); - if (dataMax > this.maxValue_) { - this.maxValue_ = dataMax; - } - - if (goog.isDef(opt_legendText)) { - if (this.setLegendTexts_.length < this.dataSets_.length) { - throw Error('Cannot start adding legends text after first element.'); - } - this.setLegendTexts_.push(opt_legendText); - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.LEGEND_TEXTS, - this.setLegendTexts_.join('|')); - } - - this.dataSets_.push(data); - this.setColors_.push(color); - - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.DATA_COLORS, - this.setColors_.join(',')); -}; - - -/** - * Clears the data sets from the graph. All data, including the colors and - * legend text, is cleared. - */ -goog.ui.ServerChart.prototype.clearDataSets = function() { - var queryData = this.uri_.getQueryData(); - queryData.remove(goog.ui.ServerChart.UriParam.LEGEND_TEXTS); - queryData.remove(goog.ui.ServerChart.UriParam.DATA_COLORS); - queryData.remove(goog.ui.ServerChart.UriParam.DATA); - this.setLegendTexts_.length = 0; - this.setColors_.length = 0; - this.dataSets_.length = 0; -}; - - -/** - * Returns the given data set or all of them in a two-dimensional array if - * the set number is not given. - * - * @param {number=} opt_setNumber Optional data set number to get. - * @return {Array} The given data set or all of them in a two-dimensional array - * if the set number is not given. - */ -goog.ui.ServerChart.prototype.getData = function(opt_setNumber) { - if (goog.isDef(opt_setNumber)) { - return this.dataSets_[opt_setNumber]; - } - return this.dataSets_; -}; - - -/** - * Computes the data string using the data in this.dataSets_ and sets - * the object's URI accordingly. If the URI's length equals or exceeds the - * limit, goog.ui.ServerChart.UriTooLongEvent is dispatched on the - * goog.ui.ServerChart object. - * @private - */ -goog.ui.ServerChart.prototype.computeDataString_ = function() { - var ok; - if (this.encodingType_ != goog.ui.ServerChart.EncodingType.AUTOMATIC) { - ok = this.computeDataStringForEncoding_(this.encodingType_); - } else { - ok = this.computeDataStringForEncoding_( - goog.ui.ServerChart.EncodingType.EXTENDED); - if (!ok) { - ok = this.computeDataStringForEncoding_( - goog.ui.ServerChart.EncodingType.SIMPLE); - } - } - if (!ok) { - this.dispatchEvent( - new goog.ui.ServerChart.UriTooLongEvent(this.uri_.toString())); - } -}; - - -/** - * Computes the data string using the data in this.dataSets_ and the encoding - * specified by the encoding parameter, which must not be AUTOMATIC, and sets - * the object's URI accordingly. - * @param {goog.ui.ServerChart.EncodingType} encoding The data encoding to use; - * must not be AUTOMATIC. - * @return {boolean} False if the resulting URI is too long. - * @private - */ -goog.ui.ServerChart.prototype.computeDataStringForEncoding_ = function( - encoding) { - var dataStrings = []; - for (var i = 0, setLen = this.dataSets_.length; i < setLen; ++i) { - dataStrings[i] = this.getChartServerValues_(this.dataSets_[i], - this.minValue_, - this.maxValue_, - encoding); - } - var delimiter = encoding == goog.ui.ServerChart.EncodingType.TEXT ? '|' : ','; - dataStrings = dataStrings.join(delimiter); - var data; - if (this.numVisibleDataSets_ == null) { - data = goog.string.buildString(encoding, ':', dataStrings); - } else { - data = goog.string.buildString(encoding, this.numVisibleDataSets_, ':', - dataStrings); - } - this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.DATA, data); - return this.uri_.toString().length < this.uriLengthLimit_; -}; - - -/** - * Computes a multi-axis data string from the given data and separators. The - * general data format for each index/element in the array will be - * "<arrayIndex><indexSeparator><arrayElement.join(elementSeparator)>", with - * axisSeparator used between multiple elements. - * @param {Object} data The data to compute the data string for, as a - * sparse array of arrays. NOTE: The function uses the length of - * multiAxisType_ to determine the upper bound for the outer array. - * @param {string} indexSeparator The separator string inserted between each - * index and the data itself, commonly a comma (,). - * @param {string} elementSeparator The separator string inserted between each - * element inside each sub-array in the data, if there are more than one; - * commonly a comma (,). - * @param {string} axisSeparator The separator string inserted between each - * axis specification, if there are more than one; usually a pipe sign (|). - * @return {string} The multi-axis data string. - * @private - */ -goog.ui.ServerChart.prototype.computeMultiAxisDataString_ = function( - data, - indexSeparator, - elementSeparator, - axisSeparator) { - var elementStrings = []; - for (var i = 0, setLen = this.multiAxisType_.length; i < setLen; ++i) { - if (data[i]) { - elementStrings.push(i + indexSeparator + data[i].join(elementSeparator)); - } - } - return elementStrings.join(axisSeparator); -}; - - -/** - * Array of possible ChartServer data values - * @type {string} - */ -goog.ui.ServerChart.CHART_VALUES = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + - 'abcdefghijklmnopqrstuvwxyz' + - '0123456789'; - - -/** - * Array of extended ChartServer data values - * @type {string} - */ -goog.ui.ServerChart.CHART_VALUES_EXTENDED = goog.ui.ServerChart.CHART_VALUES + - '-.'; - - -/** - * Upper bound for extended values - */ -goog.ui.ServerChart.EXTENDED_UPPER_BOUND = - Math.pow(goog.ui.ServerChart.CHART_VALUES_EXTENDED.length, 2) - 1; - - -/** - * Converts a single number to an encoded data value suitable for ChartServer. - * The TEXT encoding is the number in decimal; the SIMPLE encoding is a single - * character, and the EXTENDED encoding is two characters. See - * http://code.google.com/apis/chart/docs/data_formats.html for the detailed - * specification of these encoding formats. - * - * @private - * @param {?number} value The value to convert (null for a missing data point). - * @param {number} minValue The minimum value (used for normalization). - * @param {number} maxValue The maximum value (used for normalization). - * @param {goog.ui.ServerChart.EncodingType} encoding The data encoding to use; - * must not be AUTOMATIC. - * @return {string} The encoded data value. - */ -goog.ui.ServerChart.prototype.getConvertedValue_ = function(value, - minValue, - maxValue, - encoding) { - goog.asserts.assert(minValue <= maxValue, - 'minValue should be less than or equal to maxValue'); - var isExtended = (encoding == goog.ui.ServerChart.EncodingType.EXTENDED); - - if (goog.isNull(value) || !goog.isDef(value) || isNaN(value) || - value < minValue || value > maxValue) { - return isExtended ? '__' : '_'; - } - - if (encoding == goog.ui.ServerChart.EncodingType.TEXT) { - return String(value); - } - - var frac = goog.ui.ServerChart.DEFAULT_NORMALIZATION; - if (maxValue > minValue) { - frac = (value - minValue) / (maxValue - minValue); - // Previous checks of value ensure that 0 <= frac <= 1 at this point. - } - - if (isExtended) { - var maxIndex = goog.ui.ServerChart.CHART_VALUES_EXTENDED.length; - var upperBound = goog.ui.ServerChart.EXTENDED_UPPER_BOUND; - var index1 = Math.floor(frac * upperBound / maxIndex); - var index2 = Math.floor((frac * upperBound) % maxIndex); - var extendedVals = goog.ui.ServerChart.CHART_VALUES_EXTENDED; - return extendedVals.charAt(index1) + extendedVals.charAt(index2); - } - - var index = Math.round(frac * (goog.ui.ServerChart.CHART_VALUES.length - 1)); - return goog.ui.ServerChart.CHART_VALUES.charAt(index); -}; - - -/** - * Creates the chd string for chartserver. - * - * @private - * @param {Array.<number>} values An array of numbers to graph. - * @param {number} minValue The minimum value (used for normalization). - * @param {number} maxValue The maximum value (used for normalization). - * @param {goog.ui.ServerChart.EncodingType} encoding The data encoding to use; - * must not be AUTOMATIC. - * @return {string} The chd string for chartserver. - */ -goog.ui.ServerChart.prototype.getChartServerValues_ = function(values, - minValue, - maxValue, - encoding) { - var s = []; - for (var i = 0, valuesLen = values.length; i < valuesLen; ++i) { - s.push(this.getConvertedValue_(values[i], minValue, - maxValue, encoding)); - } - return s.join( - this.encodingType_ == goog.ui.ServerChart.EncodingType.TEXT ? ',' : ''); -}; - - -/** - * Finds the minimum value in an array and returns it. - * Needed because Math.min does not handle sparse arrays the way we want. - * - * @param {Array.<number?>} ary An array of values. - * @return {number} The minimum value. - * @private - */ -goog.ui.ServerChart.prototype.arrayMin_ = function(ary) { - var min = Infinity; - for (var i = 0, aryLen = ary.length; i < aryLen; ++i) { - var value = ary[i]; - if (value != null && value < min) { - min = value; - } - } - return min; -}; - - -/** - * Finds the maximum value in an array and returns it. - * Needed because Math.max does not handle sparse arrays the way we want. - * - * @param {Array.<number?>} ary An array of values. - * @return {number} The maximum value. - * @private - */ -goog.ui.ServerChart.prototype.arrayMax_ = function(ary) { - var max = -Infinity; - for (var i = 0, aryLen = ary.length; i < aryLen; ++i) { - var value = ary[i]; - if (value != null && value > max) { - max = value; - } - } - return max; -}; - - -/** @override */ -goog.ui.ServerChart.prototype.disposeInternal = function() { - goog.ui.ServerChart.superClass_.disposeInternal.call(this); - delete this.xLabels_; - delete this.leftLabels_; - delete this.rightLabels_; - delete this.gridX_; - delete this.gridY_; - delete this.setColors_; - delete this.setLegendTexts_; - delete this.dataSets_; - this.uri_ = null; - delete this.minValue_; - delete this.maxValue_; - this.title_ = null; - delete this.multiAxisType_; - delete this.multiAxisLabelText_; - delete this.multiAxisLabelPosition_; - delete this.multiAxisRange_; - delete this.multiAxisLabelStyle_; - this.legend_ = null; -}; - - -/** - * Event types dispatched by the ServerChart object - * @enum {string} - */ -goog.ui.ServerChart.Event = { - /** - * Dispatched when the resulting URI reaches or exceeds the URI length limit. - */ - URI_TOO_LONG: 'uritoolong' -}; - - - -/** - * Class for the event dispatched on the ServerChart when the resulting URI - * exceeds the URI length limit. - * @constructor - * @param {string} uri The overly-long URI string. - * @extends {goog.events.Event} - */ -goog.ui.ServerChart.UriTooLongEvent = function(uri) { - goog.events.Event.call(this, goog.ui.ServerChart.Event.URI_TOO_LONG); - - /** - * The overly-long URI string. - * @type {string} - */ - this.uri = uri; -}; -goog.inherits(goog.ui.ServerChart.UriTooLongEvent, goog.events.Event); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/serverchart_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/serverchart_test.html.svn-base deleted file mode 100644 index dd50875..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/serverchart_test.html.svn-base +++ /dev/null @@ -1,634 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2007 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.serverchart</title> -<script src="../base.js"></script> -<script> - goog.require('goog.ui.ServerChart'); - goog.require('goog.testing.jsunit'); -</script> -</head> -<body> -<script> - -function testSchemeIndependentBarChartRequest() { - var bar = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.BAR, - 180, - 104, - null); - tryToCreateBarChart(bar); - var uri = bar.getUri(); - var schemeIndependentUri = new goog.Uri( - goog.ui.ServerChart.CHART_SERVER_SCHEME_INDEPENDENT_URI); - assertEquals('', uri.getScheme()); - assertEquals(schemeIndependentUri.getDomain(), uri.getDomain()); -} - -function testHttpBarChartRequest() { - var bar = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.BAR, - 180, - 104, - null, - goog.ui.ServerChart.CHART_SERVER_HTTP_URI); - tryToCreateBarChart(bar); - var uri = bar.getUri(); - var httpUri = new goog.Uri(goog.ui.ServerChart.CHART_SERVER_HTTP_URI); - assertEquals('http', uri.getScheme()); - assertEquals(httpUri.getDomain(), uri.getDomain()); -} - -function testHttpsBarChartRequest() { - var bar = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.BAR, - 180, - 104, - null, - goog.ui.ServerChart.CHART_SERVER_HTTPS_URI); - tryToCreateBarChart(bar); - var uri = bar.getUri(); - var httpsUri = new goog.Uri(goog.ui.ServerChart.CHART_SERVER_HTTPS_URI); - assertEquals('https', uri.getScheme()); - assertEquals(httpsUri.getDomain(), uri.getDomain()); -} - -function testMinValue() { - var pie = new goog.ui.ServerChart(goog.ui.ServerChart.ChartType.PIE3D, - 180, 104); - pie.addDataSet([1, 2, 3], '000000'); - assertEquals(pie.getMinValue(), 0); - - var line = new goog.ui.ServerChart(goog.ui.ServerChart.ChartType.LINE, - 180, 104); - line.addDataSet([1, 2, 3], '000000'); - assertEquals(line.getMinValue(), 1); -} - -function testMargins() { - var pie = new goog.ui.ServerChart(goog.ui.ServerChart.ChartType.PIE3D, - 180, 104); - pie.setMargins(1, 2, 3, 4); - assertEquals('1,2,3,4', - pie.getUri().getParameterValue(goog.ui.ServerChart.UriParam.MARGINS)); -} - -function testSetParameterValue() { - var scatter = new goog.ui.ServerChart(goog.ui.ServerChart.ChartType.SCATTER, - 180, 104); - var key = goog.ui.ServerChart.UriParam.DATA_COLORS; - var value = '000000,FF0000|00FF00|0000FF'; - scatter.setParameterValue(key, value); - - assertEquals('unexpected parameter value', value, - scatter.getUri().getParameterValue(key)); - - scatter.removeParameter(key); - - assertUndefined('parameter not removed', - scatter.getUri().getParameterValue(key)); -} - -function testTypes() { - var chart; - - chart = new goog.ui.ServerChart(goog.ui.ServerChart.ChartType.CONCENTRIC_PIE, - 180, 104); - - assertTrue(chart.isPieChart()); - assertFalse(chart.isBarChart()); - assertFalse(chart.isMap()); - assertFalse(chart.isLineChart()); - - chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_GROUPED_BAR, 180, 104); - - assertFalse(chart.isPieChart()); - assertTrue(chart.isBarChart()); - assertTrue(chart.isHorizontalBarChart()); - assertTrue(chart.isGroupedBarChart()); - assertFalse(chart.isVerticalBarChart()); - assertFalse(chart.isStackedBarChart()); - - chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.BAR, 180, 104); - assertTrue(chart.isBarChart()); - assertTrue(chart.isStackedBarChart()); - assertFalse(chart.isGroupedBarChart()); - - chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.XYLINE, 180, 104); - assertTrue('I thought lxy was a line chart', chart.isLineChart()); - assertFalse('lxy is definitely not a pie chart', chart.isPieChart()); -} - -function testBarChartRequest() { - var bar = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.BAR, 180, 104); - tryToCreateBarChart(bar); - var httpUri = new goog.Uri(goog.ui.ServerChart.CHART_SERVER_URI); - var uri = bar.getUri(); - assertEquals(httpUri.getDomain(), uri.getDomain()); -} - -function tryToCreateBarChart(bar) { - bar.addDataSet([8,23,7], '008000'); - bar.addDataSet([31,11,7], 'ffcc33'); - bar.addDataSet([2,43,70,3,43,74], '3072f3'); - bar.setLeftLabels(['','20K','','60K','','100K']); - bar.setXLabels(['O','N','D']); - bar.setMaxValue(100); - var uri = bar.getUri(); - assertEquals( - 'br', - uri.getParameterValue(goog.ui.ServerChart.UriParam.TYPE)); - assertEquals( - '180x104', - uri.getParameterValue(goog.ui.ServerChart.UriParam.SIZE)); - assertEquals( - 'e:D6NtDQ,S7F4DQ,AAaxsZApaxvA', - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA)); - assertEquals( - '008000,ffcc33,3072f3', - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA_COLORS)); - assertEquals( - '100K||60K||20K|', - uri.getParameterValue(goog.ui.ServerChart.UriParam.LEFT_Y_LABELS)); - assertEquals( - 'O|N|D', - uri.getParameterValue(goog.ui.ServerChart.UriParam.X_LABELS)); -} - -function testClearDataSets() { - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.BAR, 180, 104); - tryToCreateBarChart(chart); - var uriBefore = chart.getUri().toString(); - chart.clearDataSets(); - tryToCreateBarChart(chart); - var uriAfter = chart.getUri().toString(); - assertEquals(uriBefore, uriAfter); -} - -function testMultipleDatasetsTextEncoding() { - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.BAR, 180, 104); - chart.setEncodingType(goog.ui.ServerChart.EncodingType.TEXT); - chart.addDataSet([0, 25, 100], '008000'); - chart.addDataSet([12, 2, 7.1], '112233'); - chart.addDataSet([82, 16, 2], '3072f3'); - var uri = chart.getUri(); - assertEquals( - 't:0,25,100|12,2,7.1|82,16,2', - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA)); -} - -function testVennDiagramRequest() { - var venn = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.VENN, 300,200); - venn.setTitle('Google Employees'); - var weights = [80, // Size of circle A - 60, // Size of circle B - 40, // Size of circle C - 20, // Overlap of A and B - 20, // Overlap of A and C - 20, // Overlap of B and C - 5]; // Overlap of A, B and C - var labels = [ - 'C Hackers', // Label for A - 'LISP Gurus', // Label for B - 'Java Jockeys']; // Label for C - venn.setVennSeries(weights, labels); - var uri = venn.getUri(); - var httpUri = new goog.Uri(goog.ui.ServerChart.CHART_SERVER_URI); - assertEquals(httpUri.getDomain(), uri.getDomain()); - assertEquals( - 'v', - uri.getParameterValue(goog.ui.ServerChart.UriParam.TYPE)); - assertEquals( - '300x200', - uri.getParameterValue(goog.ui.ServerChart.UriParam.SIZE)); - assertEquals( - 'e:..u7d3MzMzMzAA', - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA)); - assertEquals( - 'Google Employees', - uri.getParameterValue(goog.ui.ServerChart.UriParam.TITLE)); - assertEquals( - labels.join('|'), - uri.getParameterValue(goog.ui.ServerChart.UriParam.LEGEND_TEXTS)); -} - - -function testSparklineChartRequest() { - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.SPARKLINE, 300,200); - chart.addDataSet([8,23,7], '008000'); - chart.addDataSet([31,11,7], 'ffcc33'); - chart.addDataSet([2,43,70,3,43,74], '3072f3'); - chart.setLeftLabels(['','20K','','60K','','100K']); - chart.setXLabels(['O','N','D']); - chart.setMaxValue(100); - var uri = chart.getUri(); - assertEquals( - 'ls', - uri.getParameterValue(goog.ui.ServerChart.UriParam.TYPE)); - assertEquals( - '300x200', - uri.getParameterValue(goog.ui.ServerChart.UriParam.SIZE)); - assertEquals( - 'e:D6NtDQ,S7F4DQ,AAaxsZApaxvA', - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA)); - assertEquals( - '008000,ffcc33,3072f3', - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA_COLORS)); - assertEquals( - '100K||60K||20K|', - uri.getParameterValue(goog.ui.ServerChart.UriParam.LEFT_Y_LABELS)); - assertEquals( - 'O|N|D', - uri.getParameterValue(goog.ui.ServerChart.UriParam.X_LABELS)); -} - -function testLegendPositionRequest() { - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.SPARKLINE, 300,200); - chart.addDataSet([0, 100], '008000', 'foo'); - chart.setLegendPosition(goog.ui.ServerChart.LegendPosition.TOP); - assertEquals('t', chart.getLegendPosition()); - var uri = chart.getUri(); - assertEquals( - 't', - uri.getParameterValue(goog.ui.ServerChart.UriParam.LEGEND_POSITION)); -} - -function testSetGridParameter() { - var gridArg = '20,20,4,4'; - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.SPARKLINE, 300,200); - chart.addDataSet([0, 100], '008000', 'foo'); - chart.setGridParameter(gridArg); - assertEquals(gridArg, chart.getGridParameter()); - var uri = chart.getUri(); - assertEquals( - gridArg, - uri.getParameterValue(goog.ui.ServerChart.UriParam.GRID)); -} - -function testSetMarkerParameter() { - var markerArg = 's,FF0000,0,-1,5'; - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.SPARKLINE, 300,200); - chart.addDataSet([0, 100], '008000', 'foo'); - chart.setMarkerParameter(markerArg); - assertEquals(markerArg, chart.getMarkerParameter()); - var uri = chart.getUri(); - assertEquals( - markerArg, - uri.getParameterValue(goog.ui.ServerChart.UriParam.MARKERS)); -} - -function testNullDataPointRequest() { - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.SPARKLINE, 300,200); - chart.addDataSet([40, null, 10], '008000'); - assertEquals(10, chart.getMinValue()); - assertEquals(40, chart.getMaxValue()); - var uri = chart.getUri(); - assertEquals( - 'e:..__AA', - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA)); - - chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.SPARKLINE, 300,200); - chart.addDataSet([-5, null, -1], '008000'); - assertEquals(-5, chart.getMinValue()); - assertEquals(-1, chart.getMaxValue()); - uri = chart.getUri(); - assertEquals( - 'e:AA__..', - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA)); -} - -function testSetBarSpaceWidths() { - var noSpaceBetweenBarsSpecified = '20'; - var noSpaceBetweenBarsChart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR); - noSpaceBetweenBarsChart.setBarSpaceWidths(20); - var uri = noSpaceBetweenBarsChart.getUri(); - assertEquals(noSpaceBetweenBarsSpecified, - uri.getParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT)); - - var spaceBetweenBarsSpecified = '20,5'; - var spaceBetweenBarsChart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR); - spaceBetweenBarsChart.setBarSpaceWidths(20, 5); - var uri = spaceBetweenBarsChart.getUri(); - assertEquals(spaceBetweenBarsSpecified, - uri.getParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT)); - - var spaceBetweenGroupsSpecified = '20,5,6'; - var spaceBetweenGroupsChart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR); - spaceBetweenGroupsChart.setBarSpaceWidths(20, 5, 6); - var uri = spaceBetweenGroupsChart.getUri(); - assertEquals(spaceBetweenGroupsSpecified, - uri.getParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT)); - - var groupsButNotBarsSpecified = '20,6'; - var groupsButNotBarsChart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR); - groupsButNotBarsChart.setBarSpaceWidths(20, undefined, 6); - var uri = groupsButNotBarsChart.getUri(); - assertEquals(groupsButNotBarsSpecified, - uri.getParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT)); -} - -function testSetAutomaticBarWidth() { - var noSpaceBetweenBarsSpecified = 'a'; - var noSpaceBetweenBarsChart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR); - noSpaceBetweenBarsChart.setAutomaticBarWidth(); - var uri = noSpaceBetweenBarsChart.getUri(); - assertEquals(noSpaceBetweenBarsSpecified, - uri.getParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT)); - - var spaceBetweenBarsSpecified = 'a,5'; - var spaceBetweenBarsChart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR); - spaceBetweenBarsChart.setAutomaticBarWidth(5); - uri = spaceBetweenBarsChart.getUri(); - assertEquals(spaceBetweenBarsSpecified, - uri.getParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT)); - - var spaceBetweenGroupsSpecified = 'a,5,6'; - var spaceBetweenGroupsChart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR); - spaceBetweenGroupsChart.setAutomaticBarWidth(5, 6); - uri = spaceBetweenGroupsChart.getUri(); - assertEquals(spaceBetweenGroupsSpecified, - uri.getParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT)); - - var groupsButNotBarsSpecified = 'a,6'; - var groupsButNotBarsChart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR); - groupsButNotBarsChart.setAutomaticBarWidth(undefined, 6); - uri = groupsButNotBarsChart.getUri(); - assertEquals(groupsButNotBarsSpecified, - uri.getParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT)); -} - -function testSetDataScaling() { - var dataScalingArg = '0,160'; - var dataArg = 't:0,50,100,130'; - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR, 300, 200); - chart.addDataSet([0,50,100,130], '008000'); - chart.setDataScaling(0,160); - var uri = chart.getUri(); - assertEquals(dataScalingArg, - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA_SCALING)); - assertEquals( - dataArg, - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA)); -} - -function testSetMultiAxisLabelStyle() { - var noFontSizeChart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR, 300, 200); - noFontSizeChart.addDataSet([0,50,100,130], '008000'); - var axisNumber = noFontSizeChart.addMultiAxis( - goog.ui.ServerChart.MultiAxisType.LEFT_Y_AXIS); - var noFontSizeArgs = axisNumber + ',009000'; - noFontSizeChart.setMultiAxisLabelStyle(axisNumber, '009000'); - var noFontSizeUri = noFontSizeChart.getUri(); - assertEquals(noFontSizeArgs, - noFontSizeUri.getParameterValue( - goog.ui.ServerChart.UriParam.MULTI_AXIS_STYLE)); - - var noAlignChart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR, 300, 200); - noAlignChart.addDataSet([0,50,100,130], '008000'); - var xAxisNumber = noAlignChart.addMultiAxis( - goog.ui.ServerChart.MultiAxisType.X_AXIS); - var yAxisNumber = noAlignChart.addMultiAxis( - goog.ui.ServerChart.MultiAxisType.LEFT_Y_AXIS); - var noAlignArgs = xAxisNumber + ',009000,12|' + yAxisNumber + ',007000,14'; - noAlignChart.setMultiAxisLabelStyle(xAxisNumber, '009000', 12); - noAlignChart.setMultiAxisLabelStyle(yAxisNumber, '007000', 14); - var noAlignUri = noAlignChart.getUri(); - assertEquals(noAlignArgs, - noAlignUri.getParameterValue( - goog.ui.ServerChart.UriParam.MULTI_AXIS_STYLE)); - - var noLineTicksChart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR, 300, 200); - noLineTicksChart.addDataSet([0,50,100,130], '008000'); - axisNumber = noLineTicksChart.addMultiAxis( - goog.ui.ServerChart.MultiAxisType.LEFT_Y_AXIS); - var noLineTicksArgs = axisNumber + ',009000,12,0'; - noLineTicksChart.setMultiAxisLabelStyle(axisNumber, '009000', 12, - goog.ui.ServerChart.MultiAxisAlignment.ALIGN_CENTER); - var noLineTicksUri = noLineTicksChart.getUri(); - assertEquals(noLineTicksArgs, - noLineTicksUri.getParameterValue( - goog.ui.ServerChart.UriParam.MULTI_AXIS_STYLE)); - - - var allParamsChart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR, 300, 200); - allParamsChart.addDataSet([0,50,100,130], '008000'); - axisNumber = allParamsChart.addMultiAxis( - goog.ui.ServerChart.MultiAxisType.LEFT_Y_AXIS); - var allParamsArgs = axisNumber + ',009000,12,0,lt'; - allParamsChart.setMultiAxisLabelStyle(axisNumber, '009000', 12, - goog.ui.ServerChart.MultiAxisAlignment.ALIGN_CENTER, - goog.ui.ServerChart.AxisDisplayType.LINE_AND_TICKS); - var allParamsUri = allParamsChart.getUri(); - assertEquals(allParamsArgs, - allParamsUri.getParameterValue( - goog.ui.ServerChart.UriParam.MULTI_AXIS_STYLE)); -} - -function testSetBackgroundFill() { - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR, 300, 200); - assertEquals(0, chart.getBackgroundFill().length); - chart.setBackgroundFill([{color: '00ff00'}]); - assertObjectEquals({ - area: 'bg', - effect: 's', - color: '00ff00'}, chart.getBackgroundFill()[0]); - chart.setBackgroundFill([ - {color: '00ff00'}, - {area: 'c', color: '00ff00'} - ]); - assertObjectEquals({ - area: 'bg', - effect: 's', - color: '00ff00'}, chart.getBackgroundFill()[0]); - assertObjectEquals({ - area: 'c', - effect: 's', - color: '00ff00'}, chart.getBackgroundFill()[1]); - - chart.setParameterValue(goog.ui.ServerChart.UriParam.BACKGROUND_FILL, - 'bg,s,00ff00|c,lg,45,ff00ff|bg,s,ff00ff'); - assertEquals(0, chart.getBackgroundFill().length); -} - -function testSetMultiAxisRange() { - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR, 300, 200); - var x = chart.addMultiAxis(goog.ui.ServerChart.MultiAxisType.X_AXIS); - var top = chart.addMultiAxis(goog.ui.ServerChart.MultiAxisType.TOP_AXIS); - chart.setMultiAxisRange(x, -500, 500, 100); - chart.setMultiAxisRange(top, 0, 10); - var range = chart.getMultiAxisRange(); - - assertArrayEquals(range[x], [-500, 500, 100]); - assertArrayEquals(range[top], [0, 10]); -} - -function testGetConvertedValue() { - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR); - - assertThrows('No exception thrown when minValue > maxValue', function() { - var result = chart.getConvertedValue_( - 90, 24, 3, goog.ui.ServerChart.EncodingType.SIMPLE); - }); - - assertEquals('_', chart.getConvertedValue_(90, 100, 101, - goog.ui.ServerChart.EncodingType.SIMPLE)); - - assertEquals('_', chart.getConvertedValue_( - null, 0, 5, goog.ui.ServerChart.EncodingType.SIMPLE)); - assertEquals('__', chart.getConvertedValue_( - null, 0, 150, goog.ui.ServerChart.EncodingType.EXTENDED)); - assertEquals('24', chart.getConvertedValue_( - 24, 1, 200, goog.ui.ServerChart.EncodingType.TEXT)); - assertEquals('H', chart.getConvertedValue_( - 24, 1, 200, goog.ui.ServerChart.EncodingType.SIMPLE)); - assertEquals('HZ', chart.getConvertedValue_( - 24, 1, 200, goog.ui.ServerChart.EncodingType.EXTENDED)); - - // Out-of-range values should give a missing data point, not an empty string. - assertEquals('__', chart.getConvertedValue_( - 0, 1, 200, goog.ui.ServerChart.EncodingType.EXTENDED)); - assertEquals('__', chart.getConvertedValue_( - 201, 1, 200, goog.ui.ServerChart.EncodingType.EXTENDED)); - assertEquals('_', chart.getConvertedValue_( - 0, 1, 200, goog.ui.ServerChart.EncodingType.SIMPLE)); - assertEquals('_', chart.getConvertedValue_( - 201, 1, 200, goog.ui.ServerChart.EncodingType.SIMPLE)); - assertEquals('_', chart.getConvertedValue_( - 0, 1, 200, goog.ui.ServerChart.EncodingType.TEXT)); - assertEquals('_', chart.getConvertedValue_( - 201, 1, 200, goog.ui.ServerChart.EncodingType.TEXT)); -} - -function testGetChartServerValues() { - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR); - var values = [0, 1, 2, 56, 90, 120]; - var minValue = 0; - var maxValue = 140; - var expectedSimple = 'AABYn0'; - assertEquals(expectedSimple, - chart.getChartServerValues_(values, minValue, maxValue)); - var expectedText = '0,1,2,56,90,120'; - assertEquals(expectedSimple, - chart.getChartServerValues_(values, minValue, maxValue)); -} - -function testUriLengthLimit() { - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.SPARKLINE, 300,200); - var longUri = null; - goog.events.listen(chart, goog.ui.ServerChart.Event.URI_TOO_LONG, - function(e) {longUri = e.uri;}); - assertEquals(goog.ui.ServerChart.EncodingType.AUTOMATIC, - chart.getEncodingType()); - chart.addDataSet([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], - '008000'); - assertEquals( - 'e:AAHHOOVVccjjqqxx44..AAHHOOVVccjjqqxx44..', - chart.getUri().getParameterValue(goog.ui.ServerChart.UriParam.DATA)); - chart.setUriLengthLimit(100); - assertEquals( - 's:AHOUbipv29AHOUbipv29', - chart.getUri().getParameterValue(goog.ui.ServerChart.UriParam.DATA)); - chart.setUriLengthLimit(80); - assertEquals(null, longUri) - chart.getUri(); - assertNotEquals(null, longUri); -} - -function testVisibleDataSets() { - var uri; - - var bar = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.BAR, 180, 104); - bar.addDataSet([8,23,7], '008000'); - bar.addDataSet([31,11,7], 'ffcc33'); - bar.addDataSet([2,43,70,3,43,74], '3072f3'); - bar.setMaxValue(100); - - bar.setNumVisibleDataSets(0); - uri = bar.getUri(); - assertEquals( - 'e0:D6NtDQ,S7F4DQ,AAaxsZApaxvA', - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA)); - - bar.setNumVisibleDataSets(1); - uri = bar.getUri(); - assertEquals( - 'e1:D6NtDQ,S7F4DQ,AAaxsZApaxvA', - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA)); - - bar.setNumVisibleDataSets(2); - uri = bar.getUri(); - assertEquals( - 'e2:D6NtDQ,S7F4DQ,AAaxsZApaxvA', - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA)); - - bar.setNumVisibleDataSets(null); - uri = bar.getUri(); - assertEquals( - 'e:D6NtDQ,S7F4DQ,AAaxsZApaxvA', - uri.getParameterValue(goog.ui.ServerChart.UriParam.DATA)); -} - -function testTitle() { - var chart = new goog.ui.ServerChart( - goog.ui.ServerChart.ChartType.BAR, 180, 104); - assertEquals('Default title size', 13.5, chart.getTitleSize()); - assertEquals('Default title color', '333333', chart.getTitleColor()); - chart.setTitle('Test title'); - chart.setTitleSize(7); - chart.setTitleColor('ff0000'); - var uri = chart.getUri(); - assertEquals( - 'Changing chart title failed', - 'Test title', - uri.getParameterValue(goog.ui.ServerChart.UriParam.TITLE)); - assertEquals( - 'Changing title size and color failed', - 'ff0000,7', - uri.getParameterValue(goog.ui.ServerChart.UriParam.TITLE_FORMAT)); - assertEquals('New title size', 7, chart.getTitleSize()); - assertEquals('New title color', 'ff0000', chart.getTitleColor()); -} -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/slider.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/slider.js.svn-base deleted file mode 100644 index e6956e7..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/slider.js.svn-base +++ /dev/null @@ -1,126 +0,0 @@ -// 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 A slider implementation that allows to select a value within a - * range by dragging a thumb. The selected value is exposed through getValue(). - * - * To decorate, the slider should be bound to an element with the class name - * 'goog-slider-[vertical / horizontal]' containing a child with the classname - * 'goog-slider-thumb'. - * - * Decorate Example: - * <div id="slider" class="goog-slider-horizontal"> - * <div class="goog-twothumbslider-thumb"> - * </div> - * <script> - * - * var slider = new goog.ui.Slider; - * slider.decorate(document.getElementById('slider')); - * - * @author arv@google.com (Erik Arvidsson) - * @see ../demos/slider.html - */ - -// Implementation note: We implement slider by inheriting from baseslider, -// which allows to select sub-ranges within a range using two thumbs. All we do -// is we co-locate the two thumbs into one. - -goog.provide('goog.ui.Slider'); -goog.provide('goog.ui.Slider.Orientation'); - -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.a11y.Role'); -goog.require('goog.ui.SliderBase'); -goog.require('goog.ui.SliderBase.Orientation'); - - - -/** - * This creates a slider object. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.SliderBase} - */ -goog.ui.Slider = function(opt_domHelper) { - goog.ui.SliderBase.call(this, opt_domHelper); - this.rangeModel.setExtent(0); -}; -goog.inherits(goog.ui.Slider, goog.ui.SliderBase); - - -/** - * Expose Enum of superclass (representing the orientation of the slider) within - * Slider namespace. - * - * @enum {string} - */ -goog.ui.Slider.Orientation = goog.ui.SliderBase.Orientation; - - -/** - * The prefix we use for the CSS class names for the slider and its elements. - * @type {string} - */ -goog.ui.Slider.CSS_CLASS_PREFIX = goog.getCssName('goog-slider'); - - -/** - * CSS class name for the single thumb element. - * @type {string} - */ -goog.ui.Slider.THUMB_CSS_CLASS = - goog.getCssName(goog.ui.Slider.CSS_CLASS_PREFIX, 'thumb'); - - -/** - * Returns CSS class applied to the slider element. - * @param {goog.ui.SliderBase.Orientation} orient Orientation of the slider. - * @return {string} The CSS class applied to the slider element. - * @protected - */ -goog.ui.Slider.prototype.getCssClass = function(orient) { - return orient == goog.ui.SliderBase.Orientation.VERTICAL ? - goog.getCssName(goog.ui.Slider.CSS_CLASS_PREFIX, 'vertical') : - goog.getCssName(goog.ui.Slider.CSS_CLASS_PREFIX, 'horizontal'); -}; - - -/** @override */ -goog.ui.Slider.prototype.createThumbs = function() { - // find thumb - var element = this.getElement(); - var thumb = goog.dom.getElementsByTagNameAndClass( - null, goog.ui.Slider.THUMB_CSS_CLASS, element)[0]; - if (!thumb) { - thumb = this.createThumb_(); - element.appendChild(thumb); - } - this.valueThumb = this.extentThumb = thumb; -}; - - -/** - * Creates the thumb element. - * @return {HTMLDivElement} The created thumb element. - * @private - */ -goog.ui.Slider.prototype.createThumb_ = function() { - var thumb = - this.getDomHelper().createDom('div', goog.ui.Slider.THUMB_CSS_CLASS); - goog.dom.a11y.setRole(thumb, goog.dom.a11y.Role.BUTTON); - return /** @type {HTMLDivElement} */ (thumb); -}; - diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/sliderbase.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/sliderbase.js.svn-base deleted file mode 100644 index b387704..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/sliderbase.js.svn-base +++ /dev/null @@ -1,1253 +0,0 @@ -// 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 Implementation of a basic slider control. - * - * Models a control that allows to select a sub-range within a given - * range of values using two thumbs. The underlying range is modeled - * as a range model, where the min thumb points to value of the - * rangemodel, and the max thumb points to value + extent of the range - * model. - * - * The currently selected range is exposed through methods - * getValue() and getExtent(). - * - * The reason for modelling the basic slider state as value + extent is - * to be able to capture both, a two-thumb slider to select a range, and - * a single-thumb slider to just select a value (in the latter case, extent - * is always zero). We provide subclasses (twothumbslider.js and slider.js) - * that model those special cases of this control. - * - * All rendering logic is left out, so that the subclasses can define - * their own rendering. To do so, the subclasses overwrite: - * - createDom - * - decorateInternal - * - getCssClass - * - * @author arv@google.com (Erik Arvidsson) - * @author reto@google.com (Reto Strobl) - */ - -goog.provide('goog.ui.SliderBase'); -goog.provide('goog.ui.SliderBase.Orientation'); - -goog.require('goog.Timer'); -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.a11y.Role'); -goog.require('goog.dom.a11y.State'); -goog.require('goog.dom.classes'); -goog.require('goog.events'); -goog.require('goog.events.EventType'); -goog.require('goog.events.KeyCodes'); -goog.require('goog.events.KeyHandler'); -goog.require('goog.events.KeyHandler.EventType'); -goog.require('goog.events.MouseWheelHandler'); -goog.require('goog.events.MouseWheelHandler.EventType'); -goog.require('goog.fx.AnimationParallelQueue'); -goog.require('goog.fx.Dragger'); -goog.require('goog.fx.Dragger.EventType'); -goog.require('goog.fx.Transition.EventType'); -goog.require('goog.fx.dom.ResizeHeight'); -goog.require('goog.fx.dom.ResizeWidth'); -goog.require('goog.fx.dom.SlideFrom'); -goog.require('goog.math'); -goog.require('goog.math.Coordinate'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.RangeModel'); - - - -/** - * This creates a SliderBase object. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Component} - */ -goog.ui.SliderBase = function(opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - this.rangeModel = new goog.ui.RangeModel; - // Don't use getHandler because it gets cleared in exitDocument. - goog.events.listen(this.rangeModel, goog.ui.Component.EventType.CHANGE, - this.handleRangeModelChange, false, this); -}; -goog.inherits(goog.ui.SliderBase, goog.ui.Component); - - -/** - * Enum for representing the orientation of the slider. - * - * @enum {string} - */ -goog.ui.SliderBase.Orientation = { - VERTICAL: 'vertical', - HORIZONTAL: 'horizontal' -}; - - -/** - * Orientation of the slider. - * @type {goog.ui.SliderBase.Orientation} - * @private - */ -goog.ui.SliderBase.prototype.orientation_ = - goog.ui.SliderBase.Orientation.HORIZONTAL; - - -/** - * When the user holds down the mouse on the slider background, the closest - * thumb will move in "lock-step" towards the mouse. This number indicates how - * long each step should take (in milliseconds). - * @type {number} - * @private - */ -goog.ui.SliderBase.MOUSE_DOWN_INCREMENT_INTERVAL_ = 200; - - -/** - * How long the animations should take (in milliseconds). - * @type {number} - * @private - */ -goog.ui.SliderBase.ANIMATION_INTERVAL_ = 100; - - -/** - * The underlying range model - * @type {goog.ui.RangeModel} - * @protected - */ -goog.ui.SliderBase.prototype.rangeModel; - - -/** - * The minThumb dom-element, pointing to the start of the selected range. - * @type {HTMLDivElement} - * @protected - */ -goog.ui.SliderBase.prototype.valueThumb; - - -/** - * The maxThumb dom-element, pointing to the end of the selected range. - * @type {HTMLDivElement} - * @protected - */ -goog.ui.SliderBase.prototype.extentThumb; - - -/** - * The dom-element highlighting the selected range. - * @type {HTMLDivElement} - * @protected - */ -goog.ui.SliderBase.prototype.rangeHighlight; - - -/** - * The thumb that we should be moving (only relevant when timed move is active). - * @type {HTMLDivElement} - * @private - */ -goog.ui.SliderBase.prototype.thumbToMove_; - - -/** - * The object handling keyboard events. - * @type {goog.events.KeyHandler} - * @private - */ -goog.ui.SliderBase.prototype.keyHandler_; - - -/** - * The object handling mouse wheel events. - * @type {goog.events.MouseWheelHandler} - * @private - */ -goog.ui.SliderBase.prototype.mouseWheelHandler_; - - -/** - * The Dragger for dragging the valueThumb. - * @type {goog.fx.Dragger} - * @private - */ -goog.ui.SliderBase.prototype.valueDragger_; - - -/** - * The Dragger for dragging the extentThumb. - * @type {goog.fx.Dragger} - * @private - */ -goog.ui.SliderBase.prototype.extentDragger_; - - -/** - * If we are currently animating the thumb. - * @private - * @type {boolean} - */ -goog.ui.SliderBase.prototype.isAnimating_ = false; - - -/** - * Whether clicking on the backgtround should move directly to that point. - * @private - * @type {boolean} - */ -goog.ui.SliderBase.prototype.moveToPointEnabled_ = false; - - -/** - * The amount to increment/decrement for page up/down as well as when holding - * down the mouse button on the background. - * @private - * @type {number} - */ -goog.ui.SliderBase.prototype.blockIncrement_ = 10; - - -/** - * The minimal extent. The class will ensure that the extent cannot shrink - * to a value smaller than minExtent. - * @private - * @type {number} - */ -goog.ui.SliderBase.prototype.minExtent_ = 0; - - -// TODO: Make this return a base CSS class (without orientation), in subclasses. -/** - * Returns the CSS class applied to the slider element for the given - * orientation. Subclasses must override this method. - * @param {goog.ui.SliderBase.Orientation} orient The orientation. - * @return {string} The CSS class applied to slider elements. - * @protected - */ -goog.ui.SliderBase.prototype.getCssClass = goog.abstractMethod; - - -/** @override */ -goog.ui.SliderBase.prototype.createDom = function() { - goog.ui.SliderBase.superClass_.createDom.call(this); - var element = - this.getDomHelper().createDom('div', this.getCssClass(this.orientation_)); - this.decorateInternal(element); -}; - - -/** - * Subclasses must implement this method and set the valueThumb and - * extentThumb to non-null values. They can also set the rangeHighlight - * element if a range highlight is desired. - * @type {function() : void} - * @protected - */ -goog.ui.SliderBase.prototype.createThumbs = goog.abstractMethod; - - -/** - * CSS class name applied to the slider while its thumbs are being dragged. - * @type {string} - * @private - */ -goog.ui.SliderBase.SLIDER_DRAGGING_CSS_CLASS_ = - goog.getCssName('goog-slider-dragging'); - - -/** - * CSS class name applied to a thumb while it's being dragged. - * @type {string} - * @private - */ -goog.ui.SliderBase.THUMB_DRAGGING_CSS_CLASS_ = - goog.getCssName('goog-slider-thumb-dragging'); - - -/** @override */ -goog.ui.SliderBase.prototype.decorateInternal = function(element) { - goog.ui.SliderBase.superClass_.decorateInternal.call(this, element); - goog.dom.classes.add(element, this.getCssClass(this.orientation_)); - this.createThumbs(); - this.setAriaRoles(); -}; - - -/** - * Called when the DOM for the component is for sure in the document. - * Subclasses should override this method to set this element's role. - */ -goog.ui.SliderBase.prototype.enterDocument = function() { - goog.ui.SliderBase.superClass_.enterDocument.call(this); - - // Attach the events - this.valueDragger_ = new goog.fx.Dragger(this.valueThumb); - this.extentDragger_ = new goog.fx.Dragger(this.extentThumb); - // The slider is handling the positioning so make the defaultActions empty. - this.valueDragger_.defaultAction = this.extentDragger_.defaultAction = - goog.nullFunction; - this.keyHandler_ = new goog.events.KeyHandler(this.getElement()); - this.mouseWheelHandler_ = new goog.events.MouseWheelHandler( - this.getElement()); - this.getHandler(). - listen(this.valueDragger_, goog.fx.Dragger.EventType.BEFOREDRAG, - this.handleBeforeDrag_). - listen(this.extentDragger_, goog.fx.Dragger.EventType.BEFOREDRAG, - this.handleBeforeDrag_). - listen(this.valueDragger_, - [goog.fx.Dragger.EventType.START, goog.fx.Dragger.EventType.END], - this.handleThumbDragStartEnd_). - listen(this.extentDragger_, - [goog.fx.Dragger.EventType.START, goog.fx.Dragger.EventType.END], - this.handleThumbDragStartEnd_). - listen(this.keyHandler_, goog.events.KeyHandler.EventType.KEY, - this.handleKeyDown_). - listen(this.getElement(), goog.events.EventType.MOUSEDOWN, - this.handleMouseDown_). - listen(this.mouseWheelHandler_, - goog.events.MouseWheelHandler.EventType.MOUSEWHEEL, - this.handleMouseWheel_); - - this.getElement().tabIndex = 0; - this.updateUi_(); -}; - - -/** @override */ -goog.ui.SliderBase.prototype.exitDocument = function() { - goog.base(this, 'exitDocument'); - goog.disposeAll(this.valueDragger_, this.extentDragger_, this.keyHandler_, - this.mouseWheelHandler_); -}; - - -/** - * Handler for the before drag event. We use the event properties to determine - * the new value. - * @param {goog.fx.DragEvent} e The drag event used to drag the thumb. - * @private - */ -goog.ui.SliderBase.prototype.handleBeforeDrag_ = function(e) { - var thumbToDrag = e.dragger == this.valueDragger_ ? - this.valueThumb : this.extentThumb; - var value; - if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { - var availHeight = this.getElement().clientHeight - thumbToDrag.offsetHeight; - value = (availHeight - e.top) / availHeight * - (this.getMaximum() - this.getMinimum()) + this.getMinimum(); - } else { - var availWidth = this.getElement().clientWidth - thumbToDrag.offsetWidth; - value = (e.left / availWidth) * (this.getMaximum() - this.getMinimum()) + - this.getMinimum(); - } - // Bind the value within valid range before calling setThumbPosition_. - // This is necessary because setThumbPosition_ is a no-op for values outside - // of the legal range. For drag operations, we want the handle to snap to the - // last valid value instead of remaining at the previous position. - if (e.dragger == this.valueDragger_) { - value = Math.min(Math.max(value, this.getMinimum()), - this.getValue() + this.getExtent()); - } else { - value = Math.min(Math.max(value, this.getValue()), this.getMaximum()); - } - this.setThumbPosition_(thumbToDrag, value); -}; - - -/** - * Handler for the start/end drag event on the thumgs. Adds/removes - * the "-dragging" CSS classes on the slider and thumb. - * @param {goog.fx.DragEvent} e The drag event used to drag the thumb. - * @private - */ -goog.ui.SliderBase.prototype.handleThumbDragStartEnd_ = function(e) { - var enable = e.type == goog.fx.Dragger.EventType.START; - goog.dom.classes.enable(this.getElement(), - goog.ui.SliderBase.SLIDER_DRAGGING_CSS_CLASS_, enable); - goog.dom.classes.enable(e.target.handle, - goog.ui.SliderBase.THUMB_DRAGGING_CSS_CLASS_, enable); -}; - - -/** - * Event handler for the key down event. This is used to update the value - * based on the key pressed. - * @param {goog.events.KeyEvent} e The keyboard event object. - * @private - */ -goog.ui.SliderBase.prototype.handleKeyDown_ = function(e) { - var handled = true; - switch (e.keyCode) { - case goog.events.KeyCodes.HOME: - this.animatedSetValue(this.getMinimum()); - break; - case goog.events.KeyCodes.END: - this.animatedSetValue(this.getMaximum()); - break; - case goog.events.KeyCodes.PAGE_UP: - this.moveThumbs(this.getBlockIncrement()); - break; - case goog.events.KeyCodes.PAGE_DOWN: - this.moveThumbs(-this.getBlockIncrement()); - break; - case goog.events.KeyCodes.LEFT: - case goog.events.KeyCodes.DOWN: - this.moveThumbs(e.shiftKey ? - -this.getBlockIncrement() : -this.getUnitIncrement()); - break; - case goog.events.KeyCodes.RIGHT: - case goog.events.KeyCodes.UP: - this.moveThumbs(e.shiftKey ? - this.getBlockIncrement() : this.getUnitIncrement()); - break; - - default: - handled = false; - } - - if (handled) { - e.preventDefault(); - } -}; - - -/** - * Handler for the mouse down event. - * @param {goog.events.Event} e The mouse event object. - * @private - */ -goog.ui.SliderBase.prototype.handleMouseDown_ = function(e) { - if (this.getElement().focus) { - this.getElement().focus(); - } - - // Known Element. - var target = /** @type {Element} */ (e.target); - - if (!goog.dom.contains(this.valueThumb, target) && - !goog.dom.contains(this.extentThumb, target)) { - if (this.moveToPointEnabled_) { - // just set the value directly based on the position of the click - this.animatedSetValue(this.getValueFromMousePosition_(e)); - } else { - // start a timer that incrementally moves the handle - this.startBlockIncrementing_(e); - } - } -}; - - -/** - * Handler for the mouse wheel event. - * @param {goog.events.MouseWheelEvent} e The mouse wheel event object. - * @private - */ -goog.ui.SliderBase.prototype.handleMouseWheel_ = function(e) { - // Just move one unit increment per mouse wheel event - var direction = e.detail > 0 ? -1 : 1; - this.moveThumbs(direction * this.getUnitIncrement()); - e.preventDefault(); -}; - - -/** - * Starts the animation that causes the thumb to increment/decrement by the - * block increment when the user presses down on the background. - * @param {goog.events.Event} e The mouse event object. - * @private - */ -goog.ui.SliderBase.prototype.startBlockIncrementing_ = function(e) { - this.storeMousePos_(e); - this.thumbToMove_ = this.getClosestThumb_(this.getValueFromMousePosition_(e)); - if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { - this.incrementing_ = this.lastMousePosition_ < this.thumbToMove_.offsetTop; - } else { - this.incrementing_ = this.lastMousePosition_ > - this.thumbToMove_.offsetLeft + - this.thumbToMove_.offsetWidth; - } - - var doc = goog.dom.getOwnerDocument(this.getElement()); - this.getHandler(). - listen(doc, goog.events.EventType.MOUSEUP, this.handleMouseUp_, true). - listen(this.getElement(), goog.events.EventType.MOUSEMOVE, - this.storeMousePos_); - - if (!this.incTimer_) { - this.incTimer_ = new goog.Timer( - goog.ui.SliderBase.MOUSE_DOWN_INCREMENT_INTERVAL_); - this.getHandler().listen(this.incTimer_, goog.Timer.TICK, - this.handleTimerTick_); - } - this.handleTimerTick_(); - this.incTimer_.start(); -}; - - -/** - * Handler for the tick event dispatched by the timer used to update the value - * in a block increment. This is also called directly from - * startBlockIncrementing_. - * @private - */ -goog.ui.SliderBase.prototype.handleTimerTick_ = function() { - var value; - if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { - var mouseY = this.lastMousePosition_; - var thumbY = this.thumbToMove_.offsetTop; - if (this.incrementing_) { - if (mouseY < thumbY) { - value = this.getThumbPosition_(this.thumbToMove_) + - this.getBlockIncrement(); - } - } else { - var thumbH = this.thumbToMove_.offsetHeight; - if (mouseY > thumbY + thumbH) { - value = this.getThumbPosition_(this.thumbToMove_) - - this.getBlockIncrement(); - } - } - } else { - var mouseX = this.lastMousePosition_; - var thumbX = this.thumbToMove_.offsetLeft; - if (this.incrementing_) { - var thumbW = this.thumbToMove_.offsetWidth; - if (mouseX > thumbX + thumbW) { - value = this.getThumbPosition_(this.thumbToMove_) + - this.getBlockIncrement(); - } - } else { - if (mouseX < thumbX) { - value = this.getThumbPosition_(this.thumbToMove_) - - this.getBlockIncrement(); - } - } - } - - if (goog.isDef(value)) { // not all code paths sets the value variable - this.setThumbPosition_(this.thumbToMove_, value); - } -}; - - -/** - * Handler for the mouse up event. - * @param {goog.events.Event} e The event object. - * @private - */ -goog.ui.SliderBase.prototype.handleMouseUp_ = function(e) { - if (this.incTimer_) { - this.incTimer_.stop(); - } - - var doc = goog.dom.getOwnerDocument(this.getElement()); - this.getHandler(). - unlisten(doc, goog.events.EventType.MOUSEUP, this.handleMouseUp_, true). - unlisten(this.getElement(), goog.events.EventType.MOUSEMOVE, - this.storeMousePos_); -}; - - -/** - * Returns the relative mouse position to the slider. - * @param {goog.events.Event} e The mouse event object. - * @return {number} The relative mouse position to the slider. - * @private - */ -goog.ui.SliderBase.prototype.getRelativeMousePos_ = function(e) { - var coord = goog.style.getRelativePosition(e, this.getElement()); - if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { - return coord.y; - } else { - return coord.x; - } -}; - - -/** - * Stores the current mouse position so that it can be used in the timer. - * @param {goog.events.Event} e The mouse event object. - * @private - */ -goog.ui.SliderBase.prototype.storeMousePos_ = function(e) { - this.lastMousePosition_ = this.getRelativeMousePos_(e); -}; - - -/** - * Returns the value to use for the current mouse position - * @param {goog.events.Event} e The mouse event object. - * @return {number} The value that this mouse position represents. - * @private - */ -goog.ui.SliderBase.prototype.getValueFromMousePosition_ = function(e) { - var min = this.getMinimum(); - var max = this.getMaximum(); - if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { - var thumbH = this.valueThumb.offsetHeight; - var availH = this.getElement().clientHeight - thumbH; - var y = this.getRelativeMousePos_(e) - thumbH / 2; - return (max - min) * (availH - y) / availH + min; - } else { - var thumbW = this.valueThumb.offsetWidth; - var availW = this.getElement().clientWidth - thumbW; - var x = this.getRelativeMousePos_(e) - thumbW / 2; - return (max - min) * x / availW + min; - } -}; - - -/** - * @param {HTMLDivElement} thumb The thumb object. - * @return {number} The position of the specified thumb. - * @private - */ -goog.ui.SliderBase.prototype.getThumbPosition_ = function(thumb) { - if (thumb == this.valueThumb) { - return this.rangeModel.getValue(); - } else if (thumb == this.extentThumb) { - return this.rangeModel.getValue() + this.rangeModel.getExtent(); - } else { - throw Error('Illegal thumb element. Neither minThumb nor maxThumb'); - } -}; - - -/** - * Moves the thumbs by the specified delta as follows - * - as long as both thumbs stay within [min,max], both thumbs are moved - * - once a thumb reaches or exceeds min (or max, respectively), it stays - * - at min (or max, respectively). - * In case both thumbs have reached min (or max), no change event will fire. - * @param {number} delta The delta by which to move the selected range. - */ -goog.ui.SliderBase.prototype.moveThumbs = function(delta) { - var newMinPos = this.getThumbPosition_(this.valueThumb) + delta; - var newMaxPos = this.getThumbPosition_(this.extentThumb) + delta; - // correct min / max positions to be within bounds - newMinPos = goog.math.clamp( - newMinPos, this.getMinimum(), this.getMaximum() - this.minExtent_); - newMaxPos = goog.math.clamp( - newMaxPos, this.getMinimum() + this.minExtent_, this.getMaximum()); - // Set value and extent atomically - this.setValueAndExtent(newMinPos, newMaxPos - newMinPos); -}; - - -/** - * Sets the position of the given thumb. The set is ignored and no CHANGE event - * fires if it violates the constraint minimum <= value (valueThumb position) <= - * value + extent (extentThumb position) <= maximum. - * - * Note: To keep things simple, the setThumbPosition_ function does not have the - * side-effect of "correcting" value or extent to fit the above constraint as it - * is the case in the underlying range model. Instead, we simply ignore the - * call. Callers must make these adjustements explicitly if they wish. - * @param {Element} thumb The thumb whose position to set. - * @param {number} position The position to move the thumb to. - * @private - */ -goog.ui.SliderBase.prototype.setThumbPosition_ = function(thumb, position) { - var intermediateExtent = null; - // Make sure the maxThumb stays within minThumb <= maxThumb <= maximum - if (thumb == this.extentThumb && - position <= this.rangeModel.getMaximum() && - position >= this.rangeModel.getValue() + this.minExtent_) { - // For the case where there is only one thumb, we don't want to set the - // extent twice, causing two change events, so delay setting until we know - // if there will be a subsequent change. - intermediateExtent = position - this.rangeModel.getValue(); - } - - // Make sure the minThumb stays within minimum <= minThumb <= maxThumb - var currentExtent = intermediateExtent || this.rangeModel.getExtent(); - if (thumb == this.valueThumb && - position >= this.getMinimum() && - position <= this.rangeModel.getValue() + - currentExtent - this.minExtent_) { - var newExtent = currentExtent - - (position - this.rangeModel.getValue()); - // The range model will round the value and extent. Since we're setting - // both, extent and value at the same time, it can happen that the - // rounded sum of position and extent is not equal to the sum of the - // position and extent rounded individually. If this happens, we simply - // ignore the update to prevent inconsistent moves of the extent thumb. - if (this.rangeModel.roundToStepWithMin(position) + - this.rangeModel.roundToStepWithMin(newExtent) == - this.rangeModel.roundToStepWithMin(position + newExtent)) { - // Atomically update the position and extent. - this.setValueAndExtent(position, newExtent); - intermediateExtent = null; - } - } - - // Need to be able to set extent to 0. - if (intermediateExtent != null) { - this.rangeModel.setExtent(intermediateExtent); - } -}; - - -/** - * Sets the value and extent of the underlying range model. We enforce that - * getMinimum() <= value <= getMaximum() - extent and - * getMinExtent <= extent <= getMaximum() - getValue() - * If this is not satisifed for the given extent, the call is ignored and no - * CHANGE event fires. This is a utility method to allow setting the thumbs - * simultaneously and ensuring that only one event fires. - * @param {number} value The value to which to set the value. - * @param {number} extent The value to which to set the extent. - */ -goog.ui.SliderBase.prototype.setValueAndExtent = function(value, extent) { - if (this.getMinimum() <= value && - value <= this.getMaximum() - extent && - this.minExtent_ <= extent && - extent <= this.getMaximum() - value) { - - if (value == this.getValue() && extent == this.getExtent()) { - return; - } - // because the underlying range model applies adjustements of value - // and extent to fit within bounds, we need to reset the extent - // first so these adjustements don't kick in. - this.rangeModel.setMute(true); - this.rangeModel.setExtent(0); - this.rangeModel.setValue(value); - this.rangeModel.setExtent(extent); - this.rangeModel.setMute(false); - this.updateUi_(); - this.dispatchEvent(goog.ui.Component.EventType.CHANGE); - } -}; - - -/** - * @return {number} The minimum value. - */ -goog.ui.SliderBase.prototype.getMinimum = function() { - return this.rangeModel.getMinimum(); -}; - - -/** - * Sets the minimum number. - * @param {number} min The minimum value. - */ -goog.ui.SliderBase.prototype.setMinimum = function(min) { - this.rangeModel.setMinimum(min); -}; - - -/** - * @return {number} The maximum value. - */ -goog.ui.SliderBase.prototype.getMaximum = function() { - return this.rangeModel.getMaximum(); -}; - - -/** - * Sets the maximum number. - * @param {number} max The maximum value. - */ -goog.ui.SliderBase.prototype.setMaximum = function(max) { - this.rangeModel.setMaximum(max); -}; - - -/** - * @return {HTMLDivElement} The value thumb element. - */ -goog.ui.SliderBase.prototype.getValueThumb = function() { - return this.valueThumb; -}; - - -/** - * @return {HTMLDivElement} The extent thumb element. - */ -goog.ui.SliderBase.prototype.getExtentThumb = function() { - return this.extentThumb; -}; - - -/** - * @param {number} position The position to get the closest thumb to. - * @return {HTMLDivElement} The thumb that is closest to the given position. - * @private - */ -goog.ui.SliderBase.prototype.getClosestThumb_ = function(position) { - if (position <= (this.rangeModel.getValue() + - this.rangeModel.getExtent() / 2)) { - return this.valueThumb; - } else { - return this.extentThumb; - } -}; - - -/** - * Call back when the internal range model changes. Sub-classes may override - * and re-enter this method to update a11y state. Consider protected. - * @param {goog.events.Event} e The event object. - * @protected - */ -goog.ui.SliderBase.prototype.handleRangeModelChange = function(e) { - this.updateUi_(); - this.updateAriaStates(); - this.dispatchEvent(goog.ui.Component.EventType.CHANGE); -}; - - -/** - * This is called when we need to update the size of the thumb. This happens - * when first created as well as when the value and the orientation changes. - * @private - */ -goog.ui.SliderBase.prototype.updateUi_ = function() { - if (this.valueThumb && !this.isAnimating_) { - var minCoord = this.getThumbCoordinateForValue_( - this.getThumbPosition_(this.valueThumb)); - var maxCoord = this.getThumbCoordinateForValue_( - this.getThumbPosition_(this.extentThumb)); - - if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { - this.valueThumb.style.top = minCoord.y + 'px'; - this.extentThumb.style.top = maxCoord.y + 'px'; - if (this.rangeHighlight) { - var highlightPositioning = this.calculateRangeHighlightPositioning_( - maxCoord.y, minCoord.y, this.valueThumb.offsetHeight); - this.rangeHighlight.style.top = highlightPositioning.offset + 'px'; - this.rangeHighlight.style.height = highlightPositioning.size + 'px'; - } - } else { - this.valueThumb.style.left = minCoord.x + 'px'; - this.extentThumb.style.left = maxCoord.x + 'px'; - if (this.rangeHighlight) { - var highlightPositioning = this.calculateRangeHighlightPositioning_( - minCoord.x, maxCoord.x, this.valueThumb.offsetWidth); - this.rangeHighlight.style.left = highlightPositioning.offset + 'px'; - this.rangeHighlight.style.width = highlightPositioning.size + 'px'; - } - } - } -}; - - -/** - * Calculates the start position (offset) and size of the range highlight, e.g. - * for a horizontal slider, this will return [left, width] for the highlight. - * @param {number} firstThumbPos The position of the first thumb along the - * slider axis. - * @param {number} secondThumbPos The position of the second thumb along the - * slider axis, must be >= firstThumbPos. - * @param {number} thumbSize The size of the thumb, along the slider axis. - * @return {{offset: number, size: number}} The positioning parameters for the - * range highlight. - * @private - */ -goog.ui.SliderBase.prototype.calculateRangeHighlightPositioning_ = function( - firstThumbPos, secondThumbPos, thumbSize) { - // Highlight is inset by half the thumb size, from the edges of the thumb. - var highlightInset = Math.ceil(thumbSize / 2); - var size = secondThumbPos - firstThumbPos + thumbSize - 2 * highlightInset; - // Don't return negative size since it causes an error. IE sometimes attempts - // to position the thumbs while slider size is 0, resulting in size < 0 here. - return { - offset: firstThumbPos + highlightInset, - size: Math.max(size, 0) - }; -}; - - -/** - * Returns the position to move the handle to for a given value - * @param {number} val The value to get the coordinate for. - * @return {goog.math.Coordinate} Coordinate with either x or y set. - * @private - */ -goog.ui.SliderBase.prototype.getThumbCoordinateForValue_ = function(val) { - var coord = new goog.math.Coordinate; - if (this.valueThumb) { - var min = this.getMinimum(); - var max = this.getMaximum(); - - // This check ensures the ratio never take NaN value, which is possible when - // the slider min & max are same numbers (i.e. 1). - var ratio = (val == min && min == max) ? 0 : (val - min) / (max - min); - - if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { - var thumbHeight = this.valueThumb.offsetHeight; - var h = this.getElement().clientHeight - thumbHeight; - var bottom = Math.round(ratio * h); - coord.y = h - bottom; - } else { - var w = this.getElement().clientWidth - this.valueThumb.offsetWidth; - var left = Math.round(ratio * w); - coord.x = left; - } - } - return coord; -}; - - -/** - * Sets the value and starts animating the handle towards that position. - * @param {number} v Value to set and animate to. - */ -goog.ui.SliderBase.prototype.animatedSetValue = function(v) { - // the value might be out of bounds - v = Math.min(this.getMaximum(), Math.max(v, this.getMinimum())); - - if (this.isAnimating_) { - this.currentAnimation_.stop(true); - } - - var animations = new goog.fx.AnimationParallelQueue(); - - var end; - var thumb = this.getClosestThumb_(v); - var coord = this.getThumbCoordinateForValue_(v); - - if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { - end = [thumb.offsetLeft, coord.y]; - } else { - end = [coord.x, thumb.offsetTop]; - } - - animations.add(new goog.fx.dom.SlideFrom(thumb, end, - goog.ui.SliderBase.ANIMATION_INTERVAL_)); - if (this.rangeHighlight) { - this.addRangeHighlightAnimations_(thumb, coord, animations); - } - - this.currentAnimation_ = animations; - this.getHandler().listen(animations, goog.fx.Transition.EventType.END, - this.endAnimation_); - - this.isAnimating_ = true; - this.setThumbPosition_(thumb, v); - animations.play(false); -}; - - -/** - * Adds animations for the range highlight element to the animation queue. - * - * @param {Element} thumb The thumb that's moving, must be - * either valueThumb or extentThumb. - * @param {goog.math.Coordinate} newCoord The new pixel coordinate of the - * thumb that's moving. - * @param {goog.fx.AnimationParallelQueue} animations The animation queue. - * @private - */ -goog.ui.SliderBase.prototype.addRangeHighlightAnimations_ = function(thumb, - newCoord, animations) { - var minCoord = this.getThumbCoordinateForValue_(this.rangeModel.getValue()); - var maxCoord = this.getThumbCoordinateForValue_( - this.rangeModel.getValue() + this.rangeModel.getExtent()); - if (thumb == this.valueThumb) { - minCoord = newCoord; - } else { - maxCoord = newCoord; - } - - if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { - var highlightPositioning = this.calculateRangeHighlightPositioning_( - maxCoord.y, minCoord.y, this.valueThumb.offsetHeight); - animations.add(new goog.fx.dom.SlideFrom(this.rangeHighlight, - [this.rangeHighlight.offsetLeft, highlightPositioning.offset], - goog.ui.SliderBase.ANIMATION_INTERVAL_)); - animations.add(new goog.fx.dom.ResizeHeight(this.rangeHighlight, - this.rangeHighlight.offsetHeight, highlightPositioning.size, - goog.ui.SliderBase.ANIMATION_INTERVAL_)); - } else { - var highlightPositioning = this.calculateRangeHighlightPositioning_( - minCoord.x, maxCoord.x, this.valueThumb.offsetWidth); - var newWidth = highlightPositioning[1]; - animations.add(new goog.fx.dom.SlideFrom(this.rangeHighlight, - [highlightPositioning.offset, this.rangeHighlight.offsetTop], - goog.ui.SliderBase.ANIMATION_INTERVAL_)); - animations.add(new goog.fx.dom.ResizeWidth(this.rangeHighlight, - this.rangeHighlight.offsetWidth, highlightPositioning.size, - goog.ui.SliderBase.ANIMATION_INTERVAL_)); - } -}; - - -/** - * Sets the isAnimating_ field to false once the animation is done. - * @param {goog.fx.AnimationEvent} e Event object passed by the animation - * object. - * @private - */ -goog.ui.SliderBase.prototype.endAnimation_ = function(e) { - this.isAnimating_ = false; -}; - - -/** - * Changes the orientation. - * @param {goog.ui.SliderBase.Orientation} orient The orientation. - */ -goog.ui.SliderBase.prototype.setOrientation = function(orient) { - if (this.orientation_ != orient) { - var oldCss = this.getCssClass(this.orientation_); - var newCss = this.getCssClass(orient); - this.orientation_ = orient; - - // Update the DOM - if (this.getElement()) { - goog.dom.classes.swap(this.getElement(), oldCss, newCss); - // we need to reset the left and top, plus range highlight - this.valueThumb.style.left = this.valueThumb.style.top = ''; - this.extentThumb.style.left = this.extentThumb.style.top = ''; - if (this.rangeHighlight) { - this.rangeHighlight.style.left = this.rangeHighlight.style.top = ''; - this.rangeHighlight.style.width = this.rangeHighlight.style.height = ''; - } - this.updateUi_(); - } - } -}; - - -/** - * @return {goog.ui.SliderBase.Orientation} the orientation of the slider. - */ -goog.ui.SliderBase.prototype.getOrientation = function() { - return this.orientation_; -}; - - -/** @override */ -goog.ui.SliderBase.prototype.disposeInternal = function() { - goog.ui.SliderBase.superClass_.disposeInternal.call(this); - if (this.incTimer_) { - this.incTimer_.dispose(); - } - delete this.incTimer_; - if (this.currentAnimation_) { - this.currentAnimation_.dispose(); - } - delete this.currentAnimation_; - delete this.valueThumb; - delete this.extentThumb; - if (this.rangeHighlight) { - delete this.rangeHighlight; - } - this.rangeModel.dispose(); - delete this.rangeModel; - if (this.keyHandler_) { - this.keyHandler_.dispose(); - delete this.keyHandler_; - } - if (this.mouseWheelHandler_) { - this.mouseWheelHandler_.dispose(); - delete this.mouseWheelHandler_; - } - if (this.valueDragger_) { - this.valueDragger_.dispose(); - delete this.valueDragger_; - } - if (this.extentDragger_) { - this.extentDragger_.dispose(); - delete this.extentDragger_; - } -}; - - -/** - * @return {number} The amount to increment/decrement for page up/down as well - * as when holding down the mouse button on the background. - */ -goog.ui.SliderBase.prototype.getBlockIncrement = function() { - return this.blockIncrement_; -}; - - -/** - * Sets the amount to increment/decrement for page up/down as well as when - * holding down the mouse button on the background. - * - * @param {number} value The value to set the block increment to. - */ -goog.ui.SliderBase.prototype.setBlockIncrement = function(value) { - this.blockIncrement_ = value; -}; - - -/** - * Sets the minimal value that the extent may have. - * - * @param {number} value The minimal value for the extent. - */ -goog.ui.SliderBase.prototype.setMinExtent = function(value) { - this.minExtent_ = value; -}; - - -/** - * The amount to increment/decrement for up, down, left and right arrow keys. - * @private - * @type {number} - */ -goog.ui.SliderBase.prototype.unitIncrement_ = 1; - - -/** - * @return {number} The amount to increment/decrement for up, down, left and - * right arrow keys. - */ -goog.ui.SliderBase.prototype.getUnitIncrement = function() { - return this.unitIncrement_; -}; - - -/** - * Sets the amount to increment/decrement for up, down, left and right arrow - * keys. - * @param {number} value The value to set the unit increment to. - */ -goog.ui.SliderBase.prototype.setUnitIncrement = function(value) { - this.unitIncrement_ = value; -}; - - -/** - * @return {?number} The step value used to determine how to round the value. - */ -goog.ui.SliderBase.prototype.getStep = function() { - return this.rangeModel.getStep(); -}; - - -/** - * Sets the step value. The step value is used to determine how to round the - * value. - * @param {?number} step The step size. - */ -goog.ui.SliderBase.prototype.setStep = function(step) { - this.rangeModel.setStep(step); -}; - - -/** - * @return {boolean} Whether clicking on the backgtround should move directly to - * that point. - */ -goog.ui.SliderBase.prototype.getMoveToPointEnabled = function() { - return this.moveToPointEnabled_; -}; - - -/** - * Sets whether clicking on the background should move directly to that point. - * @param {boolean} val Whether clicking on the background should move directly - * to that point. - */ -goog.ui.SliderBase.prototype.setMoveToPointEnabled = function(val) { - this.moveToPointEnabled_ = val; -}; - - -/** - * @return {number} The value of the underlying range model. - */ -goog.ui.SliderBase.prototype.getValue = function() { - return this.rangeModel.getValue(); -}; - - -/** - * Sets the value of the underlying range model. We enforce that - * getMinimum() <= value <= getMaximum() - getExtent() - * If this is not satisifed for the given value, the call is ignored and no - * CHANGE event fires. - * @param {number} value The value. - */ -goog.ui.SliderBase.prototype.setValue = function(value) { - // Set the position through the thumb method to enforce constraints. - this.setThumbPosition_(this.valueThumb, value); -}; - - -/** - * @return {number} The value of the extent of the underlying range model. - */ -goog.ui.SliderBase.prototype.getExtent = function() { - return this.rangeModel.getExtent(); -}; - - -/** - * Sets the extent of the underlying range model. We enforce that - * getMinExtent() <= extent <= getMaximum() - getValue() - * If this is not satisifed for the given extent, the call is ignored and no - * CHANGE event fires. - * @param {number} extent The value to which to set the extent. - */ -goog.ui.SliderBase.prototype.setExtent = function(extent) { - // Set the position through the thumb method to enforce constraints. - this.setThumbPosition_(this.extentThumb, (this.rangeModel.getValue() + - extent)); -}; - - -/** - * Change the visibility of the slider. - * You must call this if you had set the slider's value when it was invisible. - * @param {boolean} visible Whether to show the slider. - */ -goog.ui.SliderBase.prototype.setVisible = function(visible) { - goog.style.showElement(this.getElement(), visible); - if (visible) { - this.updateUi_(); - } -}; - - -/** - * Set a11y roles and state. - * @protected - */ -goog.ui.SliderBase.prototype.setAriaRoles = function() { - goog.dom.a11y.setRole(this.getElement(), goog.dom.a11y.Role.SLIDER); - this.updateAriaStates(); -}; - - -/** - * Set a11y roles and state when values change. - * @protected - */ -goog.ui.SliderBase.prototype.updateAriaStates = function() { - var element = this.getElement(); - if (element) { - goog.dom.a11y.setState(element, - goog.dom.a11y.State.VALUEMIN, - this.getMinimum()); - goog.dom.a11y.setState(element, - goog.dom.a11y.State.VALUEMAX, - this.getMaximum()); - goog.dom.a11y.setState(element, - goog.dom.a11y.State.VALUENOW, - this.getValue()); - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/sliderbase_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/sliderbase_test.html.svn-base deleted file mode 100644 index 72c8798..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/sliderbase_test.html.svn-base +++ /dev/null @@ -1,305 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.SliderBase</title> -<script src="../base.js"></script> -<script type="text/javascript"> - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.testing.MockClock'); - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.recordFunction'); - goog.require('goog.ui.SliderBase'); - goog.require('goog.userAgent'); -</script> -<style type="text/css"> - -#twoThumbSlider { - position: relative; - /* Extra 20px is so distance between thumb centers is 1000px */ - width: 1020px; -} - -#valueThumb, #extentThumb { - position: absolute; - width: 20px; -} - -#rangeHighlight { - position: absolute; -} - -</style> -</head> -<body> - -<div id="sandbox"></div> - -<script type="text/javascript"> -var oneThumbSlider; -var oneChangeEventCount; - -var twoThumbSlider; -var twoChangeEventCount; - -var mockClock; - -/** - * A basic class to implement the abstract goog.ui.SliderBase for testing. - * @constructor - * @extends {goog.ui.SliderBase} - */ -function OneThumbSlider() { - goog.ui.SliderBase.call(this); -} -goog.inherits(OneThumbSlider, goog.ui.SliderBase); - - -/** {@override} */ -OneThumbSlider.prototype.createThumbs = function() { - this.valueThumb = this.extentThumb = goog.dom.getElement('thumb'); -}; - - -/** {@override} */ -OneThumbSlider.prototype.getCssClass = function() { - return 'dummyCssClass'; -}; - - -/** - * A basic class to implement the abstract goog.ui.SliderBase for testing. - * @constructor - * @extends {goog.ui.SliderBase} - */ -function TwoThumbSlider() { - goog.ui.SliderBase.call(this); -} -goog.inherits(TwoThumbSlider, goog.ui.SliderBase); - - -/** {@override} */ -TwoThumbSlider.prototype.createThumbs = function() { - this.valueThumb = goog.dom.getElement('valueThumb'); - this.extentThumb = goog.dom.getElement('extentThumb'); - this.rangeHighlight = goog.dom.getElement('rangeHighlight'); -}; - - -/** {@override} */ -TwoThumbSlider.prototype.getCssClass = function() { - return 'dummyCssClass'; -}; - - -function setUp() { - var sandBox = goog.dom.getElement('sandbox'); - mockClock = new goog.testing.MockClock(true); - - var oneThumbElem = goog.dom.createDom( - 'div', {'id': 'oneThumbSlider'}, - goog.dom.createDom('span', {'id': 'thumb'})); - sandBox.appendChild(oneThumbElem); - oneThumbSlider = new OneThumbSlider(); - oneThumbSlider.decorate(oneThumbElem); - oneChangeEventCount = 0; - goog.events.listen(oneThumbSlider, goog.ui.Component.EventType.CHANGE, - function() { - oneChangeEventCount++; - }); - - var twoThumbElem = goog.dom.createDom( - 'div', {'id': 'twoThumbSlider'}, - goog.dom.createDom('div', {'id': 'rangeHighlight'}), - goog.dom.createDom('span', {'id': 'valueThumb'}), - goog.dom.createDom('span', {'id': 'extentThumb'})); - sandBox.appendChild(twoThumbElem); - twoThumbSlider = new TwoThumbSlider(); - twoThumbSlider.decorate(twoThumbElem); - twoChangeEventCount = 0; - goog.events.listen(twoThumbSlider, goog.ui.Component.EventType.CHANGE, - function() { - twoChangeEventCount++; - }); - -} - -function tearDown() { - goog.events.removeAll(); - oneThumbSlider.dispose(); - twoThumbSlider.dispose(); - mockClock.dispose(); - goog.dom.getElement('sandbox').innerHTML = ''; -} - -function testGetAndSetValue() { - oneThumbSlider.setValue(30); - assertEquals(30, oneThumbSlider.getValue()); - assertEquals('Setting valid value must dispatch only a single change event.', - 1, oneChangeEventCount); - - oneThumbSlider.setValue(30); - assertEquals(30, oneThumbSlider.getValue()); - assertEquals('Setting to same value must not dispatch change event.', - 1, oneChangeEventCount); - - oneThumbSlider.setValue(-30); - assertEquals('Setting invalid value must not change value.', - 30, oneThumbSlider.getValue()); - assertEquals('Setting invalid value must not dispatch change event.', - 1, oneChangeEventCount); - - - // Value thumb can't go past extent thumb, so we must move that first to - // allow setting value. - twoThumbSlider.setExtent(70); - twoChangeEventCount = 0; - twoThumbSlider.setValue(60); - assertEquals(60, twoThumbSlider.getValue()); - assertEquals('Setting valid value must dispatch only a single change event.', - 1, twoChangeEventCount); - - twoThumbSlider.setValue(60); - assertEquals(60, twoThumbSlider.getValue()); - assertEquals('Setting to same value must not dispatch change event.', - 1, twoChangeEventCount); - - twoThumbSlider.setValue(-60); - assertEquals('Setting invalid value must not change value.', - 60, twoThumbSlider.getValue()); - assertEquals('Setting invalid value must not dispatch change event.', - 1, twoChangeEventCount); -} - -function testGetAndSetExtent() { - // Note(user): With a one thumb slider the API only really makes sense if you - // always use setValue since there is no extent. - - twoThumbSlider.setExtent(7); - assertEquals(7, twoThumbSlider.getExtent()); - assertEquals('Setting valid value must dispatch only a single change event.', - 1, twoChangeEventCount); - - twoThumbSlider.setExtent(7); - assertEquals(7, twoThumbSlider.getExtent()); - assertEquals('Setting to same value must not dispatch change event.', - 1, twoChangeEventCount); - - twoThumbSlider.setExtent(-7); - assertEquals('Setting invalid value must not change value.', - 7, twoThumbSlider.getExtent()); - assertEquals('Setting invalid value must not dispatch change event.', - 1, twoChangeEventCount); -} - -function testRangeListener() { - var slider = new goog.ui.SliderBase; - slider.updateUi_= slider.updateAriaStates = function() {}; - slider.rangeModel.setValue(0); - - var f = goog.testing.recordFunction(); - goog.events.listen(slider, goog.ui.Component.EventType.CHANGE, f); - - slider.rangeModel.setValue(50); - assertEquals(1, f.getCallCount()); - - slider.exitDocument(); - slider.rangeModel.setValue(0); - assertEquals('The range model listener should not have been removed so we ' + - 'should have gotten a second event dispatch', - 2, f.getCallCount()); -} - -/** - * Verifies that rangeHighlight position and size are correct for the given - * startValue and endValue. Assumes slider has default min/max values [0, 100], - * width of 1020px, and thumb widths of 20px, with rangeHighlight drawn from - * the centers of the thumbs. - */ -function assertHighlightedRange(rangeHighlight, startValue, endValue) { - var rangeStr = '[' + startValue + ', ' + endValue + ']'; - var rangeStart = 10 + 10 * startValue; - assertEquals('Range highlight for ' + rangeStr + ' should start at ' + - rangeStart + 'px.', rangeStart, rangeHighlight.offsetLeft); - var rangeSize = 10 * (endValue - startValue); - assertEquals('Range highlight for ' + rangeStr + ' should have size ' + - rangeSize + 'px.', rangeSize, rangeHighlight.offsetWidth); -} - -function testRangeHighlight() { - var rangeHighlight = goog.dom.getElement('rangeHighlight'); - - // Test [0, 100] - twoThumbSlider.setValue(0); - twoThumbSlider.setExtent(100); - assertHighlightedRange(rangeHighlight, 0, 100); - - // Test [25, 75] - twoThumbSlider.setValue(25); - twoThumbSlider.setExtent(50); - assertHighlightedRange(rangeHighlight, 25, 75); - - // Test [50, 50] - twoThumbSlider.setValue(50); - twoThumbSlider.setExtent(0); - assertHighlightedRange(rangeHighlight, 50, 50); -} - -function testRangeHighlightAnimation() { - var animationDelay = 160; // Delay in ms, is a bit higher than actual delay. - if (goog.userAgent.IE) { - // For some reason, (probably due to how timing works), IE7 and IE8 will not - // stop if we don't wait for it. - animationDelay = 250; - } - - var rangeHighlight = goog.dom.getElement('rangeHighlight'); - twoThumbSlider.setValue(0); - twoThumbSlider.setExtent(100); - - // Animate right thumb, final range is [0, 75] - twoThumbSlider.animatedSetValue(75); - assertHighlightedRange(rangeHighlight, 0, 100); - mockClock.tick(animationDelay); - assertHighlightedRange(rangeHighlight, 0, 75); - - // Animate left thumb, final range is [25, 75] - twoThumbSlider.animatedSetValue(25); - assertHighlightedRange(rangeHighlight, 0, 75); - mockClock.tick(animationDelay); - assertHighlightedRange(rangeHighlight, 25, 75); -} - -/** - * Verifies that no error occurs and that the range highlight is sized correctly - * for a zero-size slider (i.e. doesn't attempt to set a negative size). The - * test tries to resize the slider from its original size to 0, then checks - * that the range highlight's size is correctly set to 0. - * - * The size verification is needed because Webkit/Gecko outright ignore calls - * to set negative sizes on an element, leaving it at its former size. IE - * throws an error in the same situation. - */ -function testRangeHighlightForZeroSizeSlider() { - // Make sure range highlight spans whole slider before zeroing width. - twoThumbSlider.setExtent(100); - twoThumbSlider.getElement().style.width = 0; - - // The setVisible call is used to force a UI update. - twoThumbSlider.setVisible(true); - assertEquals('Range highlight size should be 0 when slider size is 0', - 0, goog.dom.getElement('rangeHighlight').offsetWidth); -} - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/splitbehavior.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/splitbehavior.js.svn-base deleted file mode 100644 index d0050a2..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/splitbehavior.js.svn-base +++ /dev/null @@ -1,346 +0,0 @@ -// 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 Behavior for combining two controls. - * - * @see ../demos/split.html - */ - -goog.provide('goog.ui.SplitBehavior'); -goog.provide('goog.ui.SplitBehavior.DefaultHandlers'); - -goog.require('goog.Disposable'); -goog.require('goog.array'); -goog.require('goog.dispose'); -goog.require('goog.dom'); -goog.require('goog.dom.DomHelper'); -goog.require('goog.dom.classes'); -goog.require('goog.events'); -goog.require('goog.events.EventHandler'); -goog.require('goog.events.EventType'); -goog.require('goog.string'); -goog.require('goog.ui.ButtonSide'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.Component.Error'); -goog.require('goog.ui.INLINE_BLOCK_CLASSNAME'); -goog.require('goog.ui.decorate'); -goog.require('goog.ui.registry'); - - - -/** - * Creates a behavior for combining two controls. The behavior is triggered - * by a given event type which applies the behavior handler. - * Can be used to also render or decorate the controls. - * For a usage example see {@link goog.ui.ColorSplitBehavior} - * - * @param {goog.ui.Control} first A ui control. - * @param {goog.ui.Control} second A ui control. - * @param {function(goog.ui.Control,Event)=} opt_behaviorHandler A handler - * to apply for the behavior. - * @param {string=} opt_eventType The event type triggering the - * handler. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for - * document interaction. - * @constructor - * @extends {goog.Disposable} - */ -goog.ui.SplitBehavior = function(first, second, opt_behaviorHandler, - opt_eventType, opt_domHelper) { - goog.Disposable.call(this); - - /** - * @type {goog.ui.Control} - * @private - */ - this.first_ = first; - - /** - * @type {goog.ui.Control} - * @private - */ - this.second_ = second; - - /** - * Handler for this behavior. - * @type {function(goog.ui.Control,Event)} - * @private - */ - this.behaviorHandler_ = opt_behaviorHandler || - goog.ui.SplitBehavior.DefaultHandlers.CAPTION; - - /** - * Event type triggering the behavior. - * @type {string} - * @private - */ - this.eventType_ = opt_eventType || goog.ui.Component.EventType.ACTION; - - /** - * @type {goog.dom.DomHelper} - * @private - */ - this.dom_ = opt_domHelper || goog.dom.getDomHelper(); - - /** - * True iff the behavior is active. - * @type {boolean} - * @private - */ - this.isActive_ = false; - - /** - * Event handler. - * @type {goog.events.EventHandler} - * @private - */ - this.eventHandler_ = new goog.events.EventHandler(); - - /** - * Whether to dispose the first control when dispose is called. - * @type {boolean} - * @private - */ - this.disposeFirst_ = true; - - /** - * Whether to dispose the second control when dispose is called. - * @type {boolean} - * @private - */ - this.disposeSecond_ = true; -}; -goog.inherits(goog.ui.SplitBehavior, goog.Disposable); - - -/** - * Css class for elements rendered by this behavior. - * @type {string} - */ -goog.ui.SplitBehavior.CSS_CLASS = goog.getCssName('goog-split-behavior'); - - -/** - * An emum of split behavior handlers. - * @enum {function(goog.ui.Control,Event)} - */ -goog.ui.SplitBehavior.DefaultHandlers = { - NONE: goog.nullFunction, - CAPTION: function(targetControl, e) { - var item = (/** @type {goog.ui.MenuItem} */e.target); - var value = (/** @type {string} */((item && item.getValue()) || '')); - var button = (/** @type {goog.ui.Button} */targetControl); - button.setCaption && button.setCaption(value); - button.setValue && button.setValue(value); - }, - VALUE: function(targetControl, e) { - var item = (/** @type {goog.ui.MenuItem} */e.target); - var value = (/** @type {string} */(item && item.getValue()) || ''); - var button = (/** @type {goog.ui.Button} */targetControl); - button.setValue && button.setValue(value); - } -}; - - -/** - * The element containing the controls. - * @type {Element} - * @private - */ -goog.ui.SplitBehavior.prototype.element_ = null; - - -/** - * @return {Element} The element containing the controls. - */ -goog.ui.SplitBehavior.prototype.getElement = function() { - return this.element_; -}; - - -/** - * @return {function(goog.ui.Control,Event)} The behavior handler. - */ -goog.ui.SplitBehavior.prototype.getBehaviorHandler = function() { - return this.behaviorHandler_; -}; - - -/** - * @return {string} The behavior event type. - */ -goog.ui.SplitBehavior.prototype.getEventType = function() { - return this.eventType_; -}; - - -/** - * Sets the disposeControls flags. - * @param {boolean} disposeFirst Whether to dispose the first control - * when dispose is called. - * @param {boolean} disposeSecond Whether to dispose the second control - * when dispose is called. - */ -goog.ui.SplitBehavior.prototype.setDisposeControls = function(disposeFirst, - disposeSecond) { - this.disposeFirst_ = !!disposeFirst; - this.disposeSecond_ = !!disposeSecond; -}; - - -/** - * Sets the behavior handler. - * @param {function(goog.ui.Control,Event)} behaviorHandler The behavior - * handler. - */ -goog.ui.SplitBehavior.prototype.setHandler = function(behaviorHandler) { - this.behaviorHandler_ = behaviorHandler; - if (this.isActive_) { - this.setActive(false); - this.setActive(true); - } -}; - - -/** - * Sets the behavior event type. - * @param {string} eventType The behavior event type. - */ -goog.ui.SplitBehavior.prototype.setEventType = function(eventType) { - this.eventType_ = eventType; - if (this.isActive_) { - this.setActive(false); - this.setActive(true); - } -}; - - -/** - * Decorates an element and returns the behavior. - * @param {Element} element An element to decorate. - * @param {boolean=} opt_activate Whether to activate the behavior - * (default=true). - * @return {goog.ui.SplitBehavior} A split behavior. - */ -goog.ui.SplitBehavior.prototype.decorate = function(element, opt_activate) { - if (this.first_ || this.second_) { - throw Error('Cannot decorate controls are already set'); - } - this.decorateChildren_(element); - var activate = goog.isDefAndNotNull(opt_activate) ? !!opt_activate : true; - this.element_ = element; - this.setActive(activate); - return this; -}; - - -/** - * Renders an element and returns the behavior. - * @param {Element} element An element to decorate. - * @param {boolean=} opt_activate Whether to activate the behavior - * (default=true). - * @return {goog.ui.SplitBehavior} A split behavior. - */ -goog.ui.SplitBehavior.prototype.render = function(element, opt_activate) { - goog.dom.classes.add(element, goog.ui.SplitBehavior.CSS_CLASS); - this.first_.render(element); - this.second_.render(element); - this.collapseSides_(this.first_, this.second_); - var activate = goog.isDefAndNotNull(opt_activate) ? !!opt_activate : true; - this.element_ = element; - this.setActive(activate); - return this; -}; - - -/** - * Activate or deactivate the behavior. - * @param {boolean} activate Whether to activate or deactivate the behavior. - */ -goog.ui.SplitBehavior.prototype.setActive = function(activate) { - if (this.isActive_ == activate) { - return; - } - this.isActive_ = activate; - if (activate) { - this.eventHandler_.listen(this.second_, this.eventType_, - goog.bind(this.behaviorHandler_, this, this.first_)); - // TODO(user): should we call the handler here to sync between - // first_ and second_. - } else { - this.eventHandler_.removeAll(); - } -}; - - -/** @override */ -goog.ui.SplitBehavior.prototype.disposeInternal = function() { - this.setActive(false); - goog.dispose(this.eventHandler_); - if (this.disposeFirst_) { - goog.dispose(this.first_); - } - if (this.disposeSecond_) { - goog.dispose(this.second_); - } - goog.ui.SplitBehavior.superClass_.disposeInternal.call(this); -}; - - -/** - * Decorates two child nodes of the given element. - * @param {Element} element An element to render two of it's child nodes. - * @private - */ -goog.ui.SplitBehavior.prototype.decorateChildren_ = function( - element) { - var childNodes = element.childNodes; - var len = childNodes.length; - var finished = false; - for (var i = 0; i < len && !finished; i++) { - var child = childNodes[i]; - if (child.nodeType == goog.dom.NodeType.ELEMENT) { - if (!this.first_) { - this.first_ = (/** @type {goog.ui.Control} */ goog.ui.decorate(child)); - } else if (!this.second_) { - this.second_ = (/** @type {goog.ui.Control} */ goog.ui.decorate(child)); - finished = true; - } - } - } -}; - - -/** - * Collapse the the controls together. - * @param {goog.ui.Control} first The first element. - * @param {goog.ui.Control} second The second element. - * @private - */ -goog.ui.SplitBehavior.prototype.collapseSides_ = function(first, second) { - if (goog.isFunction(first.setCollapsed) && - goog.isFunction(second.setCollapsed)) { - first.setCollapsed(goog.ui.ButtonSide.END); - second.setCollapsed(goog.ui.ButtonSide.START); - } -}; - - -// Register a decorator factory function for goog.ui.Buttons. -goog.ui.registry.setDecoratorByClassName(goog.ui.SplitBehavior.CSS_CLASS, - function() { - return new goog.ui.SplitBehavior(null, null); - }); - diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/splitbehavior_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/splitbehavior_test.html.svn-base deleted file mode 100644 index 5e48f7e..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/splitbehavior_test.html.svn-base +++ /dev/null @@ -1,161 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2010 The Closure Library Authors. All Rights Reserved - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.SplitBehavior</title> -<script type="text/javascript" src="../base.js"></script> -<script type="text/javascript"> - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Component.EventType'); - goog.require('goog.ui.CustomButton'); - goog.require('goog.ui.Menu'); - goog.require('goog.ui.MenuButton'); - goog.require('goog.ui.MenuItem'); - goog.require('goog.ui.SplitBehavior'); - goog.require('goog.ui.decorate'); -</script> -</head> -<body> - -<div id="split"></div> - -<script type="text/javascript"> - -var splitbehavior; -var button; -var menuValues; -var menu; -var menuButton; -var splitDiv; - -function setUp() { - splitDiv = document.getElementById('split'); - button = new goog.ui.CustomButton('text'); - menu = new goog.ui.Menu(); - menuValues = ['a', 'b', 'c']; - goog.array.forEach(menuValues, function(val) { - menu.addItem(new goog.ui.MenuItem(val)); - }); - menuButton = new goog.ui.MenuButton('text', menu); - splitbehavior = new goog.ui.SplitBehavior(button, menuButton); -} - -function tearDown() { - button.dispose(); - menu.dispose(); - menuButton.dispose(); - splitbehavior.dispose(); - splitDiv.innerHTML = ''; - splitDiv.className = ''; -} - -function testRender() { - assertEquals('no elements in doc with goog-split-behavior class', - 0, goog.dom.getElementsByTagNameAndClass('div', - 'goog-split-behavior').length); - splitbehavior.render(splitDiv); - assertEquals('two childs are rendered', 2, splitDiv.childNodes.length); - assertEquals('one element in doc with goog-split-behavior class', - 1, goog.dom.getElementsByTagNameAndClass('div', - 'goog-split-behavior').length); - assertEquals('one goog-custom-button', - 1, goog.dom.getElementsByTagNameAndClass('div', - 'goog-custom-button', splitDiv).length); - assertEquals('one goog-menu-button', - 1, goog.dom.getElementsByTagNameAndClass('div', - 'goog-menu-button', splitDiv).length); -} - -function testDecorate() { - var decorateDiv = goog.dom.createDom('div', 'goog-split-behavior', - goog.dom.createDom('div', 'goog-custom-button'), - goog.dom.createDom('div', 'goog-menu-button')); - goog.dom.appendChild(splitDiv, decorateDiv); - var split = goog.ui.decorate(decorateDiv); - assertNotNull(split); - assertTrue('instance of SplitBehavior', - split.constructor == goog.ui.SplitBehavior); - assertNotNull(split.first_); - assertTrue('instance of CustomButton', - split.first_.constructor == goog.ui.CustomButton); - assertNotNull(split.second_); - assertTrue('instance of MenuButton', - split.second_.constructor == goog.ui.MenuButton); -} - -function testBehaviorDefault() { - splitbehavior.render(splitDiv); - assertEquals('original caption is "text"', 'text', button.getCaption()); - var menuItem = menuButton.getMenu().getChildAt(0); - var type = goog.ui.Component.EventType.ACTION; - goog.events.dispatchEvent(menuButton, new goog.events.Event(type, menuItem)); - assertEquals('caption is updated to "a"','a', button.getCaption()); -} - -function testBehaviorCustomEvent() { - splitbehavior.render(splitDiv); - assertEquals('original caption is "text"', 'text', button.getCaption()); - var type = goog.ui.Component.EventType.ENTER; - splitbehavior.setEventType(type); - var menuItem = menuButton.getMenu().getChildAt(0); - goog.events.dispatchEvent(menuButton, new goog.events.Event(type, menuItem)); - assertEquals('caption is updated to "a"', 'a', button.getCaption()); -} - -function testBehaviorCustomHandler() { - splitbehavior.render(splitDiv); - var called = false; - splitbehavior.setHandler(function() { called = true; }); - goog.events.dispatchEvent(menuButton, goog.ui.Component.EventType.ACTION); - assertTrue('custom handler is called', called); -} - -function testSetActive() { - splitbehavior.render(splitDiv, false); - assertEquals('original caption is "text"', 'text', button.getCaption()); - var menuItem = menuButton.getMenu().getChildAt(0); - var type = goog.ui.Component.EventType.ACTION; - goog.events.dispatchEvent(menuButton, new goog.events.Event(type, menuItem)); - assertEquals('caption remains "text"', 'text', button.getCaption()); - - splitbehavior.setActive(true); - goog.events.dispatchEvent(menuButton, new goog.events.Event(type, menuItem)); - assertEquals('caption is updated to "a"', 'a', button.getCaption()); -} - -function testDispose() { - goog.dispose(splitbehavior); - assertTrue(splitbehavior.isDisposed()); - assertTrue(splitbehavior.first_.isDisposed()); - assertTrue(splitbehavior.second_.isDisposed()); -} - -function testDisposeNoControls() { - splitbehavior.setDisposeControls(false); - goog.dispose(splitbehavior); - assertTrue(splitbehavior.isDisposed()); - assertFalse(splitbehavior.first_.isDisposed()); - assertFalse(splitbehavior.second_.isDisposed()); -} - -function testDisposeFirstAndNotSecondControl() { - splitbehavior.setDisposeControls(true, false); - goog.dispose(splitbehavior); - assertTrue(splitbehavior.isDisposed()); - assertTrue(splitbehavior.first_.isDisposed()); - assertFalse(splitbehavior.second_.isDisposed()); -} -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/splitpane.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/splitpane.js.svn-base deleted file mode 100644 index b6e3003..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/splitpane.js.svn-base +++ /dev/null @@ -1,855 +0,0 @@ -// 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 splitting two areas with draggable control for - * changing size. - * - * The DOM that is created (or that can be decorated) looks like this: - * <div class='goog-splitpane'> - * <div class='goog-splitpane-first-container'></div> - * <div class='goog-splitpane-second-container'></div> - * <div class='goog-splitpane-handle'></div> - * </div> - * - * The content to be split goes in the first and second DIVs, the third one - * is for managing (and styling) the splitter handle. - * - * @see ../demos/splitpane.html - */ - - -goog.provide('goog.ui.SplitPane'); -goog.provide('goog.ui.SplitPane.Orientation'); - -goog.require('goog.dom'); -goog.require('goog.dom.classes'); -goog.require('goog.events.EventType'); -goog.require('goog.fx.Dragger'); -goog.require('goog.fx.Dragger.EventType'); -goog.require('goog.math.Rect'); -goog.require('goog.math.Size'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.userAgent'); - - - -/** - * A left/right up/down Container SplitPane. - * Create SplitPane with two goog.ui.Component opjects to split. - * TODO(user): Support minimum splitpane size. - * TODO(user): Allow component change/orientation after init. - * TODO(user): Support hiding either side of handle (plus handle). - * TODO(user): Look at setBorderBoxSize fixes and revist borderwidth code. - * - * @param {goog.ui.Component} firstComponent Left or Top component. - * @param {goog.ui.Component} secondComponent Right or Bottom component. - * @param {goog.ui.SplitPane.Orientation} orientation SplitPane orientation. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @extends {goog.ui.Component} - * @constructor - */ -goog.ui.SplitPane = function(firstComponent, secondComponent, orientation, - opt_domHelper) { - goog.ui.Component.call(this, opt_domHelper); - - /** - * The orientation of the containers. - * @type {goog.ui.SplitPane.Orientation} - * @private - */ - this.orientation_ = orientation; - - /** - * The left/top component. - * @type {goog.ui.Component} - * @private - */ - this.firstComponent_ = firstComponent; - this.addChild(firstComponent); - - /** - * The right/bottom component. - * @type {goog.ui.Component} - * @private - */ - this.secondComponent_ = secondComponent; - this.addChild(secondComponent); -}; -goog.inherits(goog.ui.SplitPane, goog.ui.Component); - - -/** - * Events. - * @enum {string} - */ -goog.ui.SplitPane.EventType = { - /** - * Dispatched after handle drag end. - */ - HANDLE_DRAG_END: 'handle_drag_end' -}; - - -/** - * CSS class names for splitpane outer container. - * @type {string} - * @private - */ -goog.ui.SplitPane.CLASS_NAME_ = goog.getCssName('goog-splitpane'); - - -/** - * CSS class name for first splitpane container. - * @type {string} - * @private - */ -goog.ui.SplitPane.FIRST_CONTAINER_CLASS_NAME_ = - goog.getCssName('goog-splitpane-first-container'); - - -/** - * CSS class name for second splitpane container. - * @type {string} - * @private - */ -goog.ui.SplitPane.SECOND_CONTAINER_CLASS_NAME_ = - goog.getCssName('goog-splitpane-second-container'); - - -/** - * CSS class name for the splitpane handle. - * @type {string} - * @private - */ -goog.ui.SplitPane.HANDLE_CLASS_NAME_ = goog.getCssName('goog-splitpane-handle'); - - -/** - * CSS class name for the splitpane handle in horizontal orientation. - * @type {string} - * @private - */ -goog.ui.SplitPane.HANDLE_CLASS_NAME_HORIZONTAL_ = - goog.getCssName('goog-splitpane-handle-horizontal'); - - -/** - * CSS class name for the splitpane handle in horizontal orientation. - * @type {string} - * @private - */ -goog.ui.SplitPane.HANDLE_CLASS_NAME_VERTICAL_ = - goog.getCssName('goog-splitpane-handle-vertical'); - - -/** - * The dragger to move the drag handle. - * @type {goog.fx.Dragger?} - * @private - */ -goog.ui.SplitPane.prototype.splitDragger_ = null; - - -/** - * The left/top component dom container. - * @type {Element} - * @private - */ -goog.ui.SplitPane.prototype.firstComponentContainer_ = null; - - -/** - * The right/bottom component dom container. - * @type {Element} - * @private - */ -goog.ui.SplitPane.prototype.secondComponentContainer_ = null; - - -/** - * The size (width or height) of the splitpane handle, default = 5. - * @type {number} - * @private - */ -goog.ui.SplitPane.prototype.handleSize_ = 5; - - -/** - * The initial size (width or height) of the left or top component. - * @type {?number} - * @private - */ -goog.ui.SplitPane.prototype.initialSize_ = null; - - -/** - * The saved size (width or height) of the left or top component on a - * double-click (snap). - * This needs to be saved so it can be restored after another double-click. - * @type {?number} - * @private - */ -goog.ui.SplitPane.prototype.savedSnapSize_ = null; - - -/** - * The first component size, so we don't change it on a window resize. - * @type {?number} - * @private - */ -goog.ui.SplitPane.prototype.firstComponentSize_ = null; - - -/** - * If we resize as they user moves the handle (default = true). - * @type {boolean} - * @private - */ -goog.ui.SplitPane.prototype.continuousResize_ = true; - - -/** - * Iframe overlay to prevent iframes from grabbing events. - * @type {Element} - * @private - */ -goog.ui.SplitPane.prototype.iframeOverlay_ = null; - - -/** - * Z indices for iframe overlay and splitter handle. - * @enum {number} - * @private - */ -goog.ui.SplitPane.IframeOverlayIndex_ = { - HIDDEN: -1, - OVERLAY: 1, - SPLITTER_HANDLE: 2 -}; - - -/** -* Orientation values for the splitpane. -* @enum {string} -*/ -goog.ui.SplitPane.Orientation = { - - /** - * Horizontal orientation means splitter moves right-left. - */ - HORIZONTAL: 'horizontal', - - /** - * Vertical orientation means splitter moves up-down. - */ - VERTICAL: 'vertical' -}; - - -/** - * Create the DOM node & text node needed for the splitpane. - */ -goog.ui.SplitPane.prototype.createDom = function() { - var dom = this.getDomHelper(); - - // Create the components. - var firstContainer = dom.createDom('div', - goog.ui.SplitPane.FIRST_CONTAINER_CLASS_NAME_); - var secondContainer = dom.createDom('div', - goog.ui.SplitPane.SECOND_CONTAINER_CLASS_NAME_); - var splitterHandle = dom.createDom('div', - goog.ui.SplitPane.HANDLE_CLASS_NAME_); - - // Create the primary element, a DIV that holds the two containers and handle. - this.setElementInternal(dom.createDom('div', goog.ui.SplitPane.CLASS_NAME_, - firstContainer, secondContainer, splitterHandle)); - - this.firstComponentContainer_ = firstContainer; - this.secondComponentContainer_ = secondContainer; - this.splitpaneHandle_ = splitterHandle; - this.setUpHandle_(); - - this.finishSetup_(); -}; - - -/** - * Determines if a given element can be decorated by this type of component. - * @param {Element} element Element to decorate. - * @return {boolean} True if the element can be decorated, false otherwise. - */ -goog.ui.SplitPane.prototype.canDecorate = function(element) { - var className = goog.ui.SplitPane.FIRST_CONTAINER_CLASS_NAME_; - var firstContainer = goog.dom.getElementsByTagNameAndClass( - null, className, element)[0]; - if (!firstContainer) { - return false; - } - // Since we have this component, save it so we don't have to get it - // again in decorateInternal. Same w/other components. - this.firstComponentContainer_ = firstContainer; - - className = goog.ui.SplitPane.SECOND_CONTAINER_CLASS_NAME_; - var secondContainer = goog.dom.getElementsByTagNameAndClass( - null, className, element)[0]; - if (!secondContainer) { - return false; - } - this.secondComponentContainer_ = secondContainer; - - className = goog.ui.SplitPane.HANDLE_CLASS_NAME_; - var splitpaneHandle = goog.dom.getElementsByTagNameAndClass( - null, className, element)[0]; - if (!splitpaneHandle) { - return false; - } - this.splitpaneHandle_ = splitpaneHandle; - - // We found all the components we're looking for, so return true. - return true; -}; - - -/** - * Decorates the given HTML element as a SplitPane. Overrides {@link - * goog.ui.Component#decorateInternal}. Considered protected. - * @param {Element} element Element (SplitPane div) to decorate. - * @protected - */ -goog.ui.SplitPane.prototype.decorateInternal = function(element) { - goog.ui.SplitPane.superClass_.decorateInternal.call(this, element); - - this.setUpHandle_(); - - var elSize = goog.style.getBorderBoxSize(element); - this.setSize(new goog.math.Size(elSize.width, elSize.height)); - - this.finishSetup_(); -}; - - -/** - * Parent the passed in components to the split containers. Call their - * createDom methods if necessary. - * @private - */ -goog.ui.SplitPane.prototype.finishSetup_ = function() { - var dom = this.getDomHelper(); - - if (!this.firstComponent_.getElement()) { - this.firstComponent_.createDom(); - } - - dom.appendChild(this.firstComponentContainer_, - this.firstComponent_.getElement()); - - if (!this.secondComponent_.getElement()) { - this.secondComponent_.createDom(); - } - - dom.appendChild(this.secondComponentContainer_, - this.secondComponent_.getElement()); - - this.splitDragger_ = new goog.fx.Dragger(this.splitpaneHandle_, - this.splitpaneHandle_); - - this.firstComponentContainer_.style.position = 'absolute'; - this.secondComponentContainer_.style.position = 'absolute'; - var handleStyle = this.splitpaneHandle_.style; - handleStyle.position = 'absolute'; - handleStyle.overflow = 'hidden'; - handleStyle.zIndex = - goog.ui.SplitPane.IframeOverlayIndex_.SPLITTER_HANDLE; -}; - - -/** - * Setup all events and do an initial resize. - */ -goog.ui.SplitPane.prototype.enterDocument = function() { - goog.ui.SplitPane.superClass_.enterDocument.call(this); - - // If position is not set in the inline style of the element, it is not - // possible to get the element's real CSS position until the element is in - // the document. - // When position:relative is set in the CSS and the element is not in the - // document, Safari, Chrome, and Opera always return the empty string; while - // IE always return "static". - // Do the final check to see if element's position is set as "relative", - // "absolute" or "fixed". - var element = this.getElement(); - if (goog.style.getComputedPosition(element) == 'static') { - element.style.position = 'relative'; - } - - this.getHandler(). - listen(this.splitpaneHandle_, goog.events.EventType.DBLCLICK, - this.handleDoubleClick_). - listen(this.splitDragger_, goog.fx.Dragger.EventType.START, - this.handleDragStart_). - listen(this.splitDragger_, goog.fx.Dragger.EventType.DRAG, - this.handleDrag_). - listen(this.splitDragger_, goog.fx.Dragger.EventType.END, - this.handleDragEnd_); - - this.setFirstComponentSize(this.initialSize_); -}; - - -/** - * Sets the initial size of the left or top component. - * @param {number} size The size in Pixels of the container. - */ -goog.ui.SplitPane.prototype.setInitialSize = function(size) { - this.initialSize_ = size; -}; - - -/** - * Sets the SplitPane handle size. - * TODO(user): Make sure this works after initialization. - * @param {number} size The size of the handle in pixels. - */ -goog.ui.SplitPane.prototype.setHandleSize = function(size) { - this.handleSize_ = size; -}; - - -/** - * Sets whether we resize on handle drag. - * @param {boolean} continuous The continuous resize value. - */ -goog.ui.SplitPane.prototype.setContinuousResize = function(continuous) { - this.continuousResize_ = continuous; -}; - - -/** - * Returns whether the orientation for the split pane is vertical - * or not. - * @return {boolean} True if the orientation is vertical, false otherwise. - */ -goog.ui.SplitPane.prototype.isVertical = function() { - return this.orientation_ == goog.ui.SplitPane.Orientation.VERTICAL; -}; - - -/** - * Initializes the handle by assigning the correct height/width and adding - * the correct class as per the orientation. - * @private - */ -goog.ui.SplitPane.prototype.setUpHandle_ = function() { - if (this.isVertical()) { - this.splitpaneHandle_.style.height = this.handleSize_ + 'px'; - goog.dom.classes.add(this.splitpaneHandle_, - goog.ui.SplitPane.HANDLE_CLASS_NAME_VERTICAL_); - } else { - this.splitpaneHandle_.style.width = this.handleSize_ + 'px'; - goog.dom.classes.add(this.splitpaneHandle_, - goog.ui.SplitPane.HANDLE_CLASS_NAME_HORIZONTAL_); - } -}; - - -/** - * Sets the orientation class for the split pane handle. - * @protected - */ -goog.ui.SplitPane.prototype.setOrientationClassForHandle = function() { - if (this.isVertical()) { - goog.dom.classes.swap(this.splitpaneHandle_, - goog.ui.SplitPane.HANDLE_CLASS_NAME_HORIZONTAL_, - goog.ui.SplitPane.HANDLE_CLASS_NAME_VERTICAL_); - } else { - goog.dom.classes.swap(this.splitpaneHandle_, - goog.ui.SplitPane.HANDLE_CLASS_NAME_VERTICAL_, - goog.ui.SplitPane.HANDLE_CLASS_NAME_HORIZONTAL_); - } -}; - - -/** - * Sets the orientation of the split pane. - * @param {goog.ui.SplitPane.Orientation} orientation SplitPane orientation. - */ -goog.ui.SplitPane.prototype.setOrientation = function(orientation) { - if (this.orientation_ != orientation) { - this.orientation_ = orientation; - var isVertical = this.isVertical(); - - // If the split pane is already in document, then the positions and sizes - // need to be adjusted. - if (this.isInDocument()) { - this.setOrientationClassForHandle(); - // TODO(user): Should handleSize_ and initialSize_ also be adjusted ? - if (goog.isNumber(this.firstComponentSize_)) { - var splitpaneSize = goog.style.getBorderBoxSize(this.getElement()); - var ratio = isVertical ? splitpaneSize.height / splitpaneSize.width : - splitpaneSize.width / splitpaneSize.height; - // TODO(user): Fix the behaviour for the case when the handle is - // placed on either of the edges of the split pane. Also, similar - // behaviour is present in {@link #setSize}. Probably need to modify - // {@link #setFirstComponentSize}. - this.setFirstComponentSize(this.firstComponentSize_ * ratio); - } else { - this.setFirstComponentSize(); - } - } - } -}; - - -/** - * Gets the orientation of the split pane. - * @return {goog.ui.SplitPane.Orientation} The orientation. - */ -goog.ui.SplitPane.prototype.getOrientation = function() { - return this.orientation_; -}; - - -/** - * Move and resize a container. The sizing changes the BorderBoxSize. - * @param {Element} element The element to move and size. - * @param {goog.math.Rect} rect The top, left, width and height to change to. - * @private - */ -goog.ui.SplitPane.prototype.moveAndSize_ = function(element, rect) { - - goog.style.setPosition(element, rect.left, rect.top); - // TODO(user): Add a goog.math.Size.max call for below. - goog.style.setBorderBoxSize(element, - new goog.math.Size(Math.max(rect.width, 0), Math.max(rect.height, 0))); -}; - - -/** - * @return {?number} The size of the left/top component. - */ -goog.ui.SplitPane.prototype.getFirstComponentSize = function() { - return this.firstComponentSize_; -}; - - -/** - * Set the size of the left/top component, and resize the other component based - * on that size and handle size. - * @param {?number=} opt_size The size of the top or left, in pixels. - */ -goog.ui.SplitPane.prototype.setFirstComponentSize = function(opt_size) { - var top = 0, left = 0; - var splitpaneSize = goog.style.getBorderBoxSize(this.getElement()); - - var isVertical = this.isVertical(); - // Figure out first component size; it's either passed in, taken from the - // saved size, or is half of the total size. - var firstComponentSize = goog.isNumber(opt_size) ? opt_size : - goog.isNumber(this.firstComponentSize_) ? this.firstComponentSize_ : - Math.floor((isVertical ? splitpaneSize.height : splitpaneSize.width) / 2); - this.firstComponentSize_ = firstComponentSize; - - var firstComponentWidth; - var firstComponentHeight; - var secondComponentWidth; - var secondComponentHeight; - var handleWidth; - var handleHeight; - var secondComponentLeft; - var secondComponentTop; - var handleLeft; - var handleTop; - - if (isVertical) { - - // Width for the handle and the first and second components will be the - // width of the split pane. The height for the first component will be - // the calculated first component size. The height for the second component - // will be the total height minus the heights of the first component and - // the handle. - firstComponentHeight = firstComponentSize; - firstComponentWidth = splitpaneSize.width; - handleWidth = splitpaneSize.width; - handleHeight = this.handleSize_; - secondComponentHeight = splitpaneSize.height - firstComponentHeight - - handleHeight; - secondComponentWidth = splitpaneSize.width; - handleTop = top + firstComponentHeight; - handleLeft = left; - secondComponentTop = handleTop + handleHeight; - secondComponentLeft = left; - } else { - - // Height for the handle and the first and second components will be the - // height of the split pane. The width for the first component will be - // the calculated first component size. The width for the second component - // will be the total width minus the widths of the first component and - // the handle. - firstComponentWidth = firstComponentSize; - firstComponentHeight = splitpaneSize.height; - handleWidth = this.handleSize_; - handleHeight = splitpaneSize.height; - secondComponentWidth = splitpaneSize.width - firstComponentWidth - - handleWidth; - secondComponentHeight = splitpaneSize.height; - handleLeft = left + firstComponentWidth; - handleTop = top; - secondComponentLeft = handleLeft + handleWidth; - secondComponentTop = top; - } - - // Now move and size the containers. - this.moveAndSize_(this.firstComponentContainer_, - new goog.math.Rect(left, top, firstComponentWidth, firstComponentHeight)); - - if (typeof this.firstComponent_.resize == 'function') { - this.firstComponent_.resize(new goog.math.Size( - firstComponentWidth, firstComponentHeight)); - } - - this.moveAndSize_(this.splitpaneHandle_, new goog.math.Rect(handleLeft, - handleTop, handleWidth, handleHeight)); - - this.moveAndSize_(this.secondComponentContainer_, - new goog.math.Rect(secondComponentLeft, secondComponentTop, - secondComponentWidth, secondComponentHeight)); - - if (typeof this.secondComponent_.resize == 'function') { - this.secondComponent_.resize(new goog.math.Size(secondComponentWidth, - secondComponentHeight)); - } - // Fire a CHANGE event. - this.dispatchEvent(goog.ui.Component.EventType.CHANGE); -}; - - -/** - * Dummy object to work around compiler warning. - * TODO(arv): Fix compiler or refactor to not depend on resize() - * @private - * @type {Object} - */ -goog.ui.SplitPane.resizeWarningWorkaround_ = { - /** - * @param {goog.math.Size} size The new size. - */ - resize: function(size) {} -}; - - -/** - * Set the size of the splitpane. This is usually called by the controlling - * application. This will set the SplitPane BorderBoxSize. - * @param {goog.math.Size} size The size to set the splitpane. - */ -goog.ui.SplitPane.prototype.setSize = function(size) { - goog.style.setBorderBoxSize(this.getElement(), size); - if (this.iframeOverlay_) { - goog.style.setBorderBoxSize(this.iframeOverlay_, size); - } - this.setFirstComponentSize(); -}; - - -/** - * Snap the container to the left or top on a Double-click. - * @private - */ -goog.ui.SplitPane.prototype.snapIt_ = function() { - var handlePos = goog.style.getRelativePosition(this.splitpaneHandle_, - this.firstComponentContainer_); - var firstBorderBoxSize = - goog.style.getBorderBoxSize(this.firstComponentContainer_); - var firstContentBoxSize = - goog.style.getContentBoxSize(this.firstComponentContainer_); - - var isVertical = this.isVertical(); - - // Where do we snap the handle (what size to make the component) and what - // is the current handle position. - var snapSize; - var handlePosition; - if (isVertical) { - snapSize = firstBorderBoxSize.height - firstContentBoxSize.height; - handlePosition = handlePos.y; - } else { - snapSize = firstBorderBoxSize.width - firstContentBoxSize.width; - handlePosition = handlePos.x; - } - - if (snapSize == handlePosition) { - // This means we're 'unsnapping', set it back to where it was. - this.setFirstComponentSize(this.savedSnapSize_); - } else { - // This means we're 'snapping', set the size to snapSize, and hide the - // first component. - if (isVertical) { - this.savedSnapSize_ = goog.style.getBorderBoxSize( - this.firstComponentContainer_).height; - } else { - this.savedSnapSize_ = goog.style.getBorderBoxSize( - this.firstComponentContainer_).width; - } - this.setFirstComponentSize(snapSize); - } -}; - - -/** - * Handle the start drag event - set up the dragger. - * @param {goog.events.Event} e The event. - * @private - */ -goog.ui.SplitPane.prototype.handleDragStart_ = function(e) { - - // Setup iframe overlay to prevent iframes from grabbing events. - if (!this.iframeOverlay_) { - // Create the overlay. - var cssStyles = 'position: relative'; - - if (goog.userAgent.IE) { - // IE doesn't look at this div unless it has a background, so we'll - // put one on, but make it opaque. - cssStyles += ';background-color: #000;filter: Alpha(Opacity=0)'; - } - this.iframeOverlay_ = - this.getDomHelper().createDom('div', {'style': cssStyles}); - - this.getDomHelper().appendChild(this.getElement(), this.iframeOverlay_); - } - this.iframeOverlay_.style.zIndex = - goog.ui.SplitPane.IframeOverlayIndex_.OVERLAY; - - goog.style.setBorderBoxSize(this.iframeOverlay_, - goog.style.getBorderBoxSize(this.getElement())); - - var pos = goog.style.getPosition(this.firstComponentContainer_); - - // For the size of the limiting box, we add the container content box sizes - // so that if the handle is placed all the way to the end or the start, the - // border doesn't exceed the total size. For position, we add the difference - // between the border box and content box sizes of the first container to the - // position of the first container. The start position should be such that - // there is no overlap of borders. - var limitWidth = 0; - var limitHeight = 0; - var limitx = pos.x; - var limity = pos.y; - var firstBorderBoxSize = - goog.style.getBorderBoxSize(this.firstComponentContainer_); - var firstContentBoxSize = - goog.style.getContentBoxSize(this.firstComponentContainer_); - var secondContentBoxSize = - goog.style.getContentBoxSize(this.secondComponentContainer_); - if (this.isVertical()) { - limitHeight = firstContentBoxSize.height + secondContentBoxSize.height; - limity += firstBorderBoxSize.height - firstContentBoxSize.height; - } else { - limitWidth = firstContentBoxSize.width + secondContentBoxSize.width; - limitx += firstBorderBoxSize.width - firstContentBoxSize.width; - } - var limits = new goog.math.Rect(limitx, limity, limitWidth, limitHeight); - this.splitDragger_.setLimits(limits); -}; - - -/** - * Find the location relative to the splitpane. - * @param {number} left The x location relative to the window. - * @return {number} The relative x location. - * @private - */ -goog.ui.SplitPane.prototype.getRelativeLeft_ = function(left) { - return left - goog.style.getPosition(this.firstComponentContainer_).x; -}; - - -/** - * Find the location relative to the splitpane. - * @param {number} top The y location relative to the window. - * @return {number} The relative y location. - * @private - */ -goog.ui.SplitPane.prototype.getRelativeTop_ = function(top) { - return top - goog.style.getPosition(this.firstComponentContainer_).y; -}; - - -/** - * Handle the drag event. Move the containers. - * @param {goog.events.Event} e The event. - * @private - */ -goog.ui.SplitPane.prototype.handleDrag_ = function(e) { - if (this.continuousResize_) { - if (this.isVertical()) { - var top = this.getRelativeTop_(e.top); - this.setFirstComponentSize(top); - } else { - var left = this.getRelativeLeft_(e.left); - this.setFirstComponentSize(left); - } - } -}; - - -/** - * Handle the drag end event. If we're not doing continuous resize, - * resize the component. If we're doing continuous resize, the component - * is already the correct size. - * @param {goog.events.Event} e The event. - * @private - */ -goog.ui.SplitPane.prototype.handleDragEnd_ = function(e) { - // Push iframe overlay down. - this.iframeOverlay_.style.zIndex = - goog.ui.SplitPane.IframeOverlayIndex_.HIDDEN; - if (!this.continuousResize_) { - if (this.isVertical()) { - var top = this.getRelativeTop_(e.top); - this.setFirstComponentSize(top); - } else { - var left = this.getRelativeLeft_(e.left); - this.setFirstComponentSize(left); - } - } - - this.dispatchEvent(goog.ui.SplitPane.EventType.HANDLE_DRAG_END); -}; - - -/** - * Handle the Double-click. Call the snapIt method which snaps the container - * to the top or left. - * @param {goog.events.Event} e The event. - * @private - */ -goog.ui.SplitPane.prototype.handleDoubleClick_ = function(e) { - this.snapIt_(); -}; - - -/** @override */ -goog.ui.SplitPane.prototype.disposeInternal = function() { - goog.ui.SplitPane.superClass_.disposeInternal.call(this); - - this.splitDragger_.dispose(); - this.splitDragger_ = null; - - goog.dom.removeNode(this.iframeOverlay_); - this.iframeOverlay_ = null; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/splitpane_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/splitpane_test.html.svn-base deleted file mode 100644 index ef7a617..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/splitpane_test.html.svn-base +++ /dev/null @@ -1,172 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2009 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.SplitPane</title> -<script src="../base.js"></script> -<script type="text/javascript"> - goog.require('goog.dom'); - goog.require('goog.dom.classes'); - goog.require('goog.math.Size'); - goog.require('goog.style'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Component'); - goog.require('goog.ui.SplitPane'); - goog.require('goog.ui.SplitPane.Orientation'); -</script> -</head> -<body> - -<div id="sandbox"></div> - -<script type="text/javascript"> - -var splitpane; -var leftComponent; -var rightComponent; - -function setUp() { - leftComponent = new goog.ui.Component(); - rightComponent = new goog.ui.Component(); - splitpane = new goog.ui.SplitPane(leftComponent, rightComponent, - goog.ui.SplitPane.Orientation.HORIZONTAL); -} - -function tearDown() { - splitpane.dispose(); - leftComponent.dispose(); - rightComponent.dispose(); - goog.dom.getElement('sandbox').innerHTML = ''; -} - -function testRender() { - splitpane.render(goog.dom.getElement('sandbox')); - assertEquals(1, goog.dom.getElementsByTagNameAndClass('div', - 'goog-splitpane').length); - assertEquals(1, goog.dom.getElementsByTagNameAndClass('div', - 'goog-splitpane-first-container').length); - assertEquals(1, goog.dom.getElementsByTagNameAndClass('div', - 'goog-splitpane-second-container').length); - assertEquals(1, goog.dom.getElementsByTagNameAndClass('div', - 'goog-splitpane-handle').length); -} - -function testDecorate() { - var mainDiv = goog.dom.createDom('div', 'goog-splitpane', - goog.dom.createDom('div', 'goog-splitpane-first-container'), - goog.dom.createDom('div', 'goog-splitpane-second-container'), - goog.dom.createDom('div', 'goog-splitpane-handle')); - var sandbox = goog.dom.getElement('sandbox'); - goog.dom.appendChild(sandbox, mainDiv); - - splitpane.decorate(mainDiv); -} - -function testSetSize() { - splitpane.setInitialSize(200); - splitpane.setHandleSize(10); - splitpane.render(goog.dom.getElement('sandbox')); - - splitpane.setSize(new goog.math.Size(500, 300)); - assertEquals(200, splitpane.getFirstComponentSize()); - - var splitpaneSize = goog.style.getBorderBoxSize(splitpane.getElement()); - assertEquals(500, splitpaneSize.width); - assertEquals(300, splitpaneSize.height); -} - - -function testOrientationChange() { - splitpane.setInitialSize(200); - splitpane.setHandleSize(10); - splitpane.render(goog.dom.getElement('sandbox')); - splitpane.setSize(new goog.math.Size(500, 300)); - - var first = goog.dom.getElementsByTagNameAndClass('div', - 'goog-splitpane-first-container')[0]; - var second = goog.dom.getElementsByTagNameAndClass('div', - 'goog-splitpane-second-container')[0]; - var handle = goog.dom.getElementsByTagNameAndClass('div', - 'goog-splitpane-handle')[0]; - - var handleSize = goog.style.getBorderBoxSize(handle); - assertEquals(10, handleSize.width); - assertEquals(300, handleSize.height); - - var firstSize = goog.style.getBorderBoxSize(first); - assertEquals(200, firstSize.width); - assertEquals(300, firstSize.height); - - var secondSize = goog.style.getBorderBoxSize(second); - assertEquals(290, secondSize.width); // 500 - 200 - 10 = 290 - assertEquals(300, secondSize.height); - - splitpane.setOrientation(goog.ui.SplitPane.Orientation.VERTICAL); - - handleSize = goog.style.getBorderBoxSize(handle); - assertEquals(10, handleSize.height); - assertEquals(500, handleSize.width); - - firstSize = goog.style.getBorderBoxSize(first); - assertEquals(120, firstSize.height); // 200 * 300/500 = 120 - assertEquals(500, firstSize.width); - - secondSize = goog.style.getBorderBoxSize(second); - assertEquals(170, secondSize.height); // 300 - 120 - 10 = 170 - assertEquals(500, secondSize.width); - - splitpane.setOrientation(goog.ui.SplitPane.Orientation.HORIZONTAL); - - handleSize = goog.style.getBorderBoxSize(handle); - assertEquals(10, handleSize.width); - assertEquals(300, handleSize.height); - - firstSize = goog.style.getBorderBoxSize(first); - assertEquals(200, firstSize.width); - assertEquals(300, firstSize.height); - - secondSize = goog.style.getBorderBoxSize(second); - assertEquals(290, secondSize.width); - assertEquals(300, secondSize.height); -} - -function testDragEndEvent() { - splitpane.setInitialSize(200); - splitpane.setHandleSize(10); - splitpane.render(goog.dom.getElement('sandbox')); - var eventFired = false; - goog.events.listen(splitpane, goog.ui.SplitPane.EventType.HANDLE_DRAG_END, - function() { - eventFired = true; - }); - - var handle = goog.dom.getElementsByTagNameAndClass('div', - 'goog-splitpane-handle')[0]; - - goog.testing.events.fireMouseDownEvent(handle); - goog.testing.events.fireMouseMoveEvent(handle); - goog.testing.events.fireMouseUpEvent(handle); - assertTrue('HANDLE_DRAG_END event expected', eventFired); - - splitpane.setContinuousResize(false); - eventFired = false; - goog.testing.events.fireMouseDownEvent(handle); - goog.testing.events.fireMouseMoveEvent(handle); - goog.testing.events.fireMouseUpEvent(handle); - assertTrue('HANDLE_DRAG_END event expected', eventFired); -} - - - -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/submenu.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/submenu.js.svn-base deleted file mode 100644 index 69ae625..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/submenu.js.svn-base +++ /dev/null @@ -1,661 +0,0 @@ -// Copyright 2007 The Closure Library Authors. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS-IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/** - * @fileoverview A class representing menu items that open a submenu. - * @see goog.ui.Menu - * - * @see ../demos/submenus.html - * @see ../demos/submenus2.html - */ - -goog.provide('goog.ui.SubMenu'); - -goog.require('goog.Timer'); -goog.require('goog.dom'); -goog.require('goog.dom.classes'); -goog.require('goog.events.KeyCodes'); -goog.require('goog.positioning.AnchoredViewportPosition'); -goog.require('goog.positioning.Corner'); -goog.require('goog.style'); -goog.require('goog.ui.Component'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.Component.State'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.Menu'); -goog.require('goog.ui.MenuItem'); -goog.require('goog.ui.SubMenuRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * Class representing a submenu that can be added as an item to other menus. - * - * @param {goog.ui.ControlContent} content Text caption or DOM structure to - * display as the content of the submenu (use to add icons or styling to - * menus). - * @param {*=} opt_model Data/model associated with the menu item. - * @param {goog.dom.DomHelper=} opt_domHelper Optional dom helper used for dom - * interactions. - * @param {goog.ui.MenuItemRenderer=} opt_renderer Renderer used to render or - * decorate the component; defaults to {@link goog.ui.SubMenuRenderer}. - * @constructor - * @extends {goog.ui.MenuItem} - */ -goog.ui.SubMenu = function(content, opt_model, opt_domHelper, opt_renderer) { - goog.ui.MenuItem.call(this, content, opt_model, opt_domHelper, - opt_renderer || goog.ui.SubMenuRenderer.getInstance()); -}; -goog.inherits(goog.ui.SubMenu, goog.ui.MenuItem); - - -/** - * The delay before opening the sub menu in milliseconds. (This number is - * arbitrary, it would be good to get some user studies or a designer to play - * with some numbers). - * @type {number} - */ -goog.ui.SubMenu.MENU_DELAY_MS = 350; - - -/** - * Timer used to dismiss the submenu when the item becomes unhighlighted. - * @type {?number} - * @private - */ -goog.ui.SubMenu.prototype.dismissTimer_ = null; - - -/** - * Timer used to show the submenu on mouseover. - * @type {?number} - * @private - */ -goog.ui.SubMenu.prototype.showTimer_ = null; - - -/** - * Flag used to determine if the submenu has control of the keyevents. - * @type {boolean} - * @private - */ -goog.ui.SubMenu.prototype.hasKeyboardControl_ = false; - - -/** - * The lazily created sub menu. - * @type {goog.ui.Menu?} - * @private - */ -goog.ui.SubMenu.prototype.subMenu_ = null; - - -/** - * Whether or not the sub-menu was set explicitly. - * @type {boolean} - * @private - */ -goog.ui.SubMenu.prototype.externalSubMenu_ = false; - - -/** - * Whether or not to align the submenu at the end of the parent menu. - * If true, the menu expands to the right in LTR languages and to the left - * in RTL langauges. - * @type {boolean} - * @private - */ -goog.ui.SubMenu.prototype.alignToEnd_ = true; - - -/** - * Whether the position of this submenu may be adjusted to fit - * the visible area, as in {@link goog.ui.Popup.positionAtCoordinate}. - * @type {boolean} - * @private - */ -goog.ui.SubMenu.prototype.isPositionAdjustable_ = false; - - -/** @override */ -goog.ui.SubMenu.prototype.enterDocument = function() { - goog.ui.SubMenu.superClass_.enterDocument.call(this); - - this.getHandler().listen(this.getParent(), goog.ui.Component.EventType.HIDE, - this.onParentHidden_); - - if (this.subMenu_) { - this.setMenuListenersEnabled_(this.subMenu_, true); - } -}; - - -/** @override */ -goog.ui.SubMenu.prototype.exitDocument = function() { - this.getHandler().unlisten(this.getParent(), goog.ui.Component.EventType.HIDE, - this.onParentHidden_); - - if (this.subMenu_) { - this.setMenuListenersEnabled_(this.subMenu_, false); - if (!this.externalSubMenu_) { - this.subMenu_.exitDocument(); - goog.dom.removeNode(this.subMenu_.getElement()); - } - } - - goog.ui.SubMenu.superClass_.exitDocument.call(this); -}; - - -/** @override */ -goog.ui.SubMenu.prototype.disposeInternal = function() { - if (this.subMenu_ && !this.externalSubMenu_) { - this.subMenu_.dispose(); - } - this.subMenu_ = null; - goog.ui.SubMenu.superClass_.disposeInternal.call(this); -}; - - -/** - * @override - * Dismisses the submenu on a delay, with the result that the user needs less - * accuracy when moving to submenus. Alternate implementations could use - * geometry instead of a timer. - * @param {boolean} highlight Whether item should be highlighted. - * @param {boolean=} opt_btnPressed Whether the mouse button is held down. - */ -goog.ui.SubMenu.prototype.setHighlighted = function(highlight, - opt_btnPressed) { - goog.ui.SubMenu.superClass_.setHighlighted.call(this, highlight); - - if (opt_btnPressed) { - this.getMenu().setMouseButtonPressed(true); - } - - if (!highlight) { - if (this.dismissTimer_) { - goog.Timer.clear(this.dismissTimer_); - } - this.dismissTimer_ = goog.Timer.callOnce( - this.dismissSubMenu, goog.ui.SubMenu.MENU_DELAY_MS, this); - } -}; - - -/** - * Show the submenu and ensure that all siblings are hidden. - */ -goog.ui.SubMenu.prototype.showSubMenu = function() { - // Only show the menu if this item is still selected. This is called on a - // timeout, so make sure our parent still exists. - var parent = this.getParent(); - if (parent && parent.getHighlighted() == this) { - this.setSubMenuVisible_(true); - this.dismissSiblings_(); - this.keyboardSetFocus_ = false; - } -}; - - -/** - * Dismisses the menu and all further submenus. - */ -goog.ui.SubMenu.prototype.dismissSubMenu = function() { - // Because setHighlighted calls this function on a timeout, we need to make - // sure that the sub menu hasn't been disposed when we come back. - var subMenu = this.subMenu_; - if (subMenu && subMenu.getParent() == this) { - this.setSubMenuVisible_(false); - subMenu.forEachChild(function(child) { - if (typeof child.dismissSubMenu == 'function') { - child.dismissSubMenu(); - } - }); - } -}; - - -/** - * Clears the show and hide timers for the sub menu. - */ -goog.ui.SubMenu.prototype.clearTimers = function() { - if (this.dismissTimer_) { - goog.Timer.clear(this.dismissTimer_); - } - if (this.showTimer_) { - goog.Timer.clear(this.showTimer_); - } -}; - - -/** - * Sets the menu item to be visible or invisible. - * @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. - */ -goog.ui.SubMenu.prototype.setVisible = function(visible, opt_force) { - var visibilityChanged = goog.ui.SubMenu.superClass_.setVisible.call(this, - visible, opt_force); - // For menus that allow menu items to be hidden (i.e. ComboBox) ensure that - // the submenu is hidden. - if (visibilityChanged && !this.isVisible()) { - this.dismissSubMenu(); - } - return visibilityChanged; -}; - - -/** - * Dismiss all the sub menus of sibling menu items. - * @private - */ -goog.ui.SubMenu.prototype.dismissSiblings_ = function() { - this.getParent().forEachChild(function(child) { - if (child != this && typeof child.dismissSubMenu == 'function') { - child.dismissSubMenu(); - child.clearTimers(); - } - }, this); -}; - - -/** - * Handles a key event that is passed to the menu item from its parent because - * it is highlighted. If the right key is pressed the sub menu takes control - * and delegates further key events to its menu until it is dismissed OR the - * left key is pressed. - * TODO(user): RTL lookup - * @param {goog.events.KeyEvent} e A key event. - * @return {boolean} Whether the event was handled. - */ -goog.ui.SubMenu.prototype.handleKeyEvent = function(e) { - var keyCode = e.keyCode; - - if (!this.hasKeyboardControl_) { - // Menu item doesn't have keyboard control and the right key was pressed. - // So open take keyboard control and open the sub menu. - if (this.isEnabled() && (keyCode == goog.events.KeyCodes.RIGHT || - keyCode == this.getMnemonic())) { - this.showSubMenu(); - this.getMenu().highlightFirst(); - this.clearTimers(); - - // The menu item doesn't currently care about the key events so let the - // parent menu handle them accordingly . - } else { - return false; - } - - // Menu item has control, so let its menu try to handle the keys (this may - // in turn be handled by sub-sub menus). - } else if (this.getMenu().handleKeyEvent(e)) { - // Nothing to do - - // The menu has control and the key hasn't yet been handled, on left arrow - // we turn off key control. - } else if (keyCode == goog.events.KeyCodes.LEFT) { - this.dismissSubMenu(); - - } else { - // Submenu didn't handle the key so let the parent decide what to do. - return false; - } - - e.preventDefault(); - return true; -}; - - -/** - * Listens to the sub menus items and ensures that this menu item is selected - * while dismissing the others. This handles the case when the user mouses - * over other items on their way to the sub menu. - * @param {goog.events.Event} e Highlight event to handle. - * @private - */ -goog.ui.SubMenu.prototype.onChildHighlight_ = function(e) { - if (this.subMenu_.getParent() == this) { - this.clearTimers(); - this.getParentEventTarget().setHighlighted(this); - this.dismissSiblings_(); - } -}; - - -/** - * Listens to the parent menu's hide event and ensures that all submenus are - * hidden at the same time. - * @param {goog.events.Event} e The event. - * @private - */ -goog.ui.SubMenu.prototype.onParentHidden_ = function(e) { - // Ignore propagated events - if (e.target == this.getParentEventTarget()) { - // TODO(user): Using an event for this is expensive. Consider having a - // generalized interface that the parent menu calls on its children when - // it is hidden. - this.dismissSubMenu(); - this.clearTimers(); - } -}; - - -/** - * @override - * Sets a timer to show the submenu and then dispatches an ENTER event to the - * parent menu. - * @param {goog.events.BrowserEvent} e Mouse event to handle. - * @protected - */ -goog.ui.SubMenu.prototype.handleMouseOver = function(e) { - if (this.isEnabled()) { - this.clearTimers(); - this.showTimer_ = goog.Timer.callOnce( - this.showSubMenu, goog.ui.SubMenu.MENU_DELAY_MS, this); - } - goog.ui.SubMenu.superClass_.handleMouseOver.call(this, e); -}; - - -/** - * Overrides the default mouseup event handler, so that the ACTION isn't - * dispatched for the submenu itself, instead the submenu is shown instantly. - * @param {goog.events.BrowserEvent} e The browser event. - * @return {boolean} True if the action was allowed to proceed, false otherwise. - */ -goog.ui.SubMenu.prototype.performActionInternal = function(e) { - this.clearTimers(); - var shouldHandleClick = this.isSupportedState( - goog.ui.Component.State.SELECTED); - if (shouldHandleClick) { - return goog.ui.SubMenu.superClass_.performActionInternal.call(this, e); - } else { - this.showSubMenu(); - return true; - } -}; - - -/** - * Sets the visiblility of the sub menu. - * @param {boolean} visible Whether to show menu. - * @private - */ -goog.ui.SubMenu.prototype.setSubMenuVisible_ = function(visible) { - // Dispatch OPEN event before calling getMenu(), so we can create the menu - // lazily on first access. - this.dispatchEvent(goog.ui.Component.getStateTransitionEvent( - goog.ui.Component.State.OPENED, visible)); - var subMenu = this.getMenu(); - if (visible != subMenu.isVisible()) { - if (visible) { - // Lazy-render menu when first shown, if needed. - if (!subMenu.isInDocument()) { - subMenu.render(); - } - this.positionSubMenu_(); - subMenu.setHighlightedIndex(-1); - } - this.hasKeyboardControl_ = visible; - goog.dom.classes.enable(this.getElement(), - goog.getCssName('goog-submenu-open'), visible); - subMenu.setVisible(visible); - } -}; - - -/** - * Attaches or detaches menu event listeners to/from the given menu. Called - * each time a menu is attached to or detached from the submenu. - * @param {goog.ui.Menu} menu Menu on which to listen for events. - * @param {boolean} attach Whether to attach or detach event listeners. - * @private - */ -goog.ui.SubMenu.prototype.setMenuListenersEnabled_ = function(menu, attach) { - var handler = this.getHandler(); - var method = attach ? handler.listen : handler.unlisten; - method.call(handler, menu, goog.ui.Component.EventType.HIGHLIGHT, - this.onChildHighlight_); -}; - - -/** - * Sets whether the submenu is aligned at the end of the parent menu. - * @param {boolean} alignToEnd True to align to end, false to align to start. - */ -goog.ui.SubMenu.prototype.setAlignToEnd = function(alignToEnd) { - if (alignToEnd != this.alignToEnd_) { - this.alignToEnd_ = alignToEnd; - if (this.isInDocument()) { - // Completely re-render the widget. - var oldElement = this.getElement(); - this.exitDocument(); - - if (oldElement.nextSibling) { - this.renderBefore(/** @type {!Element} */ (oldElement.nextSibling)); - } else { - this.render(/** @type {Element} */ (oldElement.parentNode)); - } - } - } -}; - - -/** - * Determines whether the submenu is aligned at the end of the parent menu. - * @return {boolean} True if aligned to the end (the default), false if - * aligned to the start. - */ -goog.ui.SubMenu.prototype.isAlignedToEnd = function() { - return this.alignToEnd_; -}; - - -/** - * Positions the submenu. - * @private - */ -goog.ui.SubMenu.prototype.positionSubMenu_ = function() { - var position = new goog.positioning.AnchoredViewportPosition( - this.getElement(), this.isAlignedToEnd() ? - goog.positioning.Corner.TOP_END : goog.positioning.Corner.TOP_START, - this.isPositionAdjustable_); - - // TODO(user): Clean up popup code and have this be a one line call - var subMenu = this.getMenu(); - var el = subMenu.getElement(); - if (!subMenu.isVisible()) { - el.style.visibility = 'hidden'; - goog.style.showElement(el, true); - } - - position.reposition( - el, this.isAlignedToEnd() ? - goog.positioning.Corner.TOP_START : goog.positioning.Corner.TOP_END); - - if (!subMenu.isVisible()) { - goog.style.showElement(el, false); - el.style.visibility = 'visible'; - } -}; - - -// Methods delegated to sub-menu but accessible here for convinience - - -/** - * Adds a new menu item at the end of the menu. - * @param {goog.ui.MenuHeader|goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu - * item to add to the menu. - */ -goog.ui.SubMenu.prototype.addItem = function(item) { - this.getMenu().addChild(item, true); -}; - - -/** - * Adds a new menu item at a specific index in the menu. - * @param {goog.ui.MenuHeader|goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu - * item to add to the menu. - * @param {number} n Index at which to insert the menu item. - */ -goog.ui.SubMenu.prototype.addItemAt = function(item, n) { - this.getMenu().addChildAt(item, n, true); -}; - - -/** - * Removes an item from the menu and disposes it. - * @param {goog.ui.MenuItem} item The menu item to remove. - */ -goog.ui.SubMenu.prototype.removeItem = function(item) { - var child = this.getMenu().removeChild(item, true); - if (child) { - child.dispose(); - } -}; - - -/** - * Removes a menu item at a given index in the menu and disposes it. - * @param {number} n Index of item. - */ -goog.ui.SubMenu.prototype.removeItemAt = function(n) { - var child = this.getMenu().removeChildAt(n, true); - if (child) { - child.dispose(); - } -}; - - -/** - * Returns a reference to the menu item at a given index. - * @param {number} n Index of menu item. - * @return {goog.ui.Component} Reference to the menu item. - */ -goog.ui.SubMenu.prototype.getItemAt = function(n) { - return this.getMenu().getChildAt(n); -}; - - -/** - * Returns the number of items in the sub menu (including separators). - * @return {number} The number of items in the menu. - */ -goog.ui.SubMenu.prototype.getItemCount = function() { - return this.getMenu().getChildCount(); -}; - - -/** - * Returns the menu items contained in the sub menu. - * @return {Array.<goog.ui.MenuItem>} An array of menu items. - * @deprecated Use getItemAt/getItemCount instead. - */ -goog.ui.SubMenu.prototype.getItems = function() { - return this.getMenu().getItems(); -}; - - -/** - * Gets a reference to the submenu's actual menu. - * @return {goog.ui.Menu} Reference to the object representing the sub menu. - */ -goog.ui.SubMenu.prototype.getMenu = function() { - if (!this.subMenu_) { - this.setMenu( - new goog.ui.Menu(this.getDomHelper()), /* opt_internal */ true); - } else if (this.externalSubMenu_ && this.subMenu_.getParent() != this) { - // Since it is possible for the same popup menu to be attached to multiple - // submenus, we need to ensure that it has the correct parent event target. - this.subMenu_.setParent(this); - } - // Always create the menu DOM, for backward compatibility. - if (!this.subMenu_.getElement()) { - this.subMenu_.createDom(); - } - return this.subMenu_; -}; - - -/** - * Sets the submenu to a specific menu. - * @param {goog.ui.Menu} menu The menu to show when this item is selected. - * @param {boolean=} opt_internal Whether this menu is an "internal" menu, and - * should be disposed of when this object is disposed of. - */ -goog.ui.SubMenu.prototype.setMenu = function(menu, opt_internal) { - var oldMenu = this.subMenu_; - if (menu != oldMenu) { - if (oldMenu) { - this.dismissSubMenu(); - if (this.isInDocument()) { - this.setMenuListenersEnabled_(oldMenu, false); - } - } - - this.subMenu_ = menu; - this.externalSubMenu_ = !opt_internal; - - if (menu) { - menu.setParent(this); - // There's no need to dispatch a HIDE event during submenu construction. - menu.setVisible(false, /* opt_force */ true); - menu.setAllowAutoFocus(false); - menu.setFocusable(false); - if (this.isInDocument()) { - this.setMenuListenersEnabled_(menu, true); - } - } - } -}; - - -/** - * Returns true if the provided element is to be considered inside the menu for - * purposes such as dismissing the menu on an event. This is so submenus can - * make use of elements outside their own DOM. - * @param {Element} element The element to test for. - * @return {boolean} Whether or not the provided element is contained. - */ -goog.ui.SubMenu.prototype.containsElement = function(element) { - return this.getMenu().containsElement(element); -}; - - -/** - * @param {boolean} isAdjustable Whether this submenu is adjustable. - */ -goog.ui.SubMenu.prototype.setPositionAdjustable = function(isAdjustable) { - this.isPositionAdjustable_ = !!isAdjustable; -}; - - -/** - * @return {boolean} Whether this submenu is adjustable. - */ -goog.ui.SubMenu.prototype.isPositionAdjustable = function() { - return this.isPositionAdjustable_; -}; - - -// Register a decorator factory function for goog.ui.SubMenus. -goog.ui.registry.setDecoratorByClassName(goog.getCssName('goog-submenu'), - function() { - return new goog.ui.SubMenu(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/submenu_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/submenu_test.html.svn-base deleted file mode 100644 index bf84724..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/submenu_test.html.svn-base +++ /dev/null @@ -1,525 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - - @author nicksantos@google.com (Nick Santos) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.SubMenu</title> -<style type='text/css'> -.goog-menu { - position: absolute; - color: #000; - border: 1px solid #B5B6B5; - background-color: #F3F3F7; - cursor: default; - font: normal small arial, helvetica, sans-serif; - margin: 0; - padding: 0; - outline: none; -} - -.goog-menuitem { - padding: 2px 1.5em 2px 5px; - margin: 0; - list-style: none; -} - -.goog-menuitem-rtl { - padding: 2px 5px 2px 1.5em; -} - -.goog-submenu-arrow { - text-align: right; - position: absolute; - right: 0; - left: auto; -} - -.goog-menuitem-rtl .goog-submenu-arrow { - text-align: left; - position: absolute; - left: 0; - right: auto; -} - -.goog-menuitem-disabled .goog-submenu-arrow { - display: none; -} -</style> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.dom.classes'); - goog.require('goog.events'); - goog.require('goog.positioning'); - goog.require('goog.positioning.Overflow'); - goog.require('goog.style'); - goog.require('goog.testing.MockClock'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Component.EventType'); - goog.require('goog.ui.Menu'); - goog.require('goog.ui.MenuItem'); - goog.require('goog.ui.Popup'); - goog.require('goog.ui.SubMenu'); - goog.require('goog.ui.SubMenuRenderer'); - - -</script> -</head> -<body> -<script> - -var menu; -var clonedMenuDom; - -var mockClock; - -// mock out goog.positioning.positionAtCoordinate so that -// the menu always fits. (we don't care about testing the -// dynamic menu positioning if the menu doesn't fit in the window.) -var oldPositionFn = goog.positioning.positionAtCoordinate; -goog.positioning.positionAtCoordinate = function(absolutePos, movableElement, - movableElementCorner, - opt_margin, opt_overflow) { - return oldPositionFn.call(null, absolutePos, movableElement, - movableElementCorner, opt_margin, goog.positioning.Overflow.IGNORE); -}; - -function setUp() { - clonedMenuDom = goog.dom.getElement('demoMenu').cloneNode(true); - - menu = new goog.ui.Menu(); -} - -function tearDown() { - document.body.style.direction = 'ltr'; - menu.dispose(); - - var element = goog.dom.getElement('demoMenu'); - element.parentNode.replaceChild(clonedMenuDom, element); - - goog.dom.getElement('sandbox').innerHTML = ''; - - if (mockClock) { - mockClock.uninstall(); - mockClock = null; - } -} - -function testKeyHandling() { - menu.setFocusable(true); - menu.decorate(goog.dom.getElement('demoMenu')); - - var KeyCodes = goog.events.KeyCodes; - var plainItem = menu.getChildAt(0); - plainItem.setMnemonic(KeyCodes.F); - - var subMenuItem1 = menu.getChildAt(1); - subMenuItem1.setMnemonic(KeyCodes.S); - var subMenuItem1Menu = subMenuItem1.getMenu(); - menu.setHighlighted(plainItem); - - var fireKeySequence = goog.testing.events.fireKeySequence; - - assertTrue( - 'Expected RIGHT key to not be handled', - fireKeySequence(plainItem.getElement(), KeyCodes.RIGHT)); - assertFalse(subMenuItem1Menu.isVisible()); - - assertFalse( - 'Expected F key to be handled', - fireKeySequence(plainItem.getElement(), KeyCodes.F)); - - assertFalse( - 'Expected DOWN key to be handled', - fireKeySequence(plainItem.getElement(), KeyCodes.DOWN)); - assertEquals(subMenuItem1, menu.getChildAt(1)); - - assertFalse( - 'Expected RIGHT key to be handled', - fireKeySequence(subMenuItem1.getElement(), KeyCodes.RIGHT)); - assertTrue(subMenuItem1Menu.isVisible()); - - assertFalse( - 'Expected LEFT key to be handled', - fireKeySequence(subMenuItem1.getElement(), KeyCodes.LEFT)); - assertFalse(subMenuItem1Menu.isVisible()); - - assertFalse( - 'Expected UP key to be handled', - fireKeySequence(subMenuItem1.getElement(), KeyCodes.UP)); - - assertFalse( - 'Expected S key to be handled', - fireKeySequence(plainItem.getElement(), KeyCodes.S)); - assertTrue(subMenuItem1Menu.isVisible()); -} - -function testNormalLtrSubMenu() { - menu.decorate(goog.dom.getElement('demoMenu')); - var subMenu = menu.getChildAt(1); - assertArrowDirection(subMenu, false); - assertRenderDirection(subMenu, false); - assertArrowPosition(subMenu, false); -} - -function testNormalRtlSubMenu() { - document.body.style.direction = 'rtl'; - menu.decorate(goog.dom.getElement('demoMenu')); - var subMenu = menu.getChildAt(1); - assertArrowDirection(subMenu, true); - assertRenderDirection(subMenu, true); - assertArrowPosition(subMenu, true); -} - -function testLtrSubMenuAlignedToStart() { - menu.decorate(goog.dom.getElement('demoMenu')); - var subMenu = menu.getChildAt(1); - subMenu.setAlignToEnd(false); - assertArrowDirection(subMenu, true); - assertRenderDirection(subMenu, true); - assertArrowPosition(subMenu, false); -} - -function testNullContentElement() { - var subMenu = new goog.ui.SubMenu(); - subMenu.setContent('demo'); -} - -function testRtlSubMenuAlignedToStart() { - document.body.style.direction = 'rtl'; - menu.decorate(goog.dom.getElement('demoMenu')); - var subMenu = menu.getChildAt(1); - subMenu.setAlignToEnd(false); - assertArrowDirection(subMenu, false); - assertRenderDirection(subMenu, false); - assertArrowPosition(subMenu, true); -} - -function testSetContentKeepsArrow_ltr() { - document.body.style.direction = 'ltr'; - menu.decorate(goog.dom.getElement('demoMenu')); - var subMenu = menu.getChildAt(1); - subMenu.setAlignToEnd(false); - subMenu.setContent('test'); - assertArrowDirection(subMenu, true); - assertRenderDirection(subMenu, true); - assertArrowPosition(subMenu, false); -} - -function testSetContentKeepsArrow_rtl() { - document.body.style.direction = 'rtl'; - menu.decorate(goog.dom.getElement('demoMenu')); - var subMenu = menu.getChildAt(1); - subMenu.setAlignToEnd(false); - subMenu.setContent('test'); - assertArrowDirection(subMenu, false); - assertRenderDirection(subMenu, false); - assertArrowPosition(subMenu, true); -} - -function testExitDocument() { - menu.decorate(goog.dom.getElement('demoMenu')); - var subMenu = menu.getChildAt(1); - var innerMenu = subMenu.getMenu(); - - assertTrue('Top-level menu was not in document', menu.isInDocument()); - assertTrue('Submenu was not in document', subMenu.isInDocument()); - assertTrue('Inner menu was not in document', innerMenu.isInDocument()); - - menu.exitDocument(); - - assertFalse('Top-level menu was in document', menu.isInDocument()); - assertFalse('Submenu was in document', subMenu.isInDocument()); - assertFalse('Inner menu was in document', innerMenu.isInDocument()); -} - -function testDisposal() { - menu.decorate(goog.dom.getElement('demoMenu')); - var subMenu = menu.getChildAt(1); - var innerMenu = subMenu.getMenu(); - menu.dispose(); - - assert('Top-level menu was not disposed', menu.getDisposed()); - assert('Submenu was not disposed', subMenu.getDisposed()); - assert('Inner menu was not disposed', innerMenu.getDisposed()); -} - -function testShowAndDismissSubMenu() { - var openEventDispatched = false; - var closeEventDispatched = false; - - function handleEvent(e) { - switch (e.type) { - case goog.ui.Component.EventType.OPEN: - openEventDispatched = true; - break; - case goog.ui.Component.EventType.CLOSE: - closeEventDispatched = true; - break; - default: - fail('Invalid event type: ' + e.type); - } - } - - menu.decorate(goog.dom.getElement('demoMenu')); - var subMenu = menu.getChildAt(1); - subMenu.setHighlighted(true); - - goog.events.listen(subMenu, [ - goog.ui.Component.EventType.OPEN, - goog.ui.Component.EventType.CLOSE - ], handleEvent); - - assertFalse('Submenu must not have "-open" CSS class', - goog.dom.classes.has(subMenu.getElement(), 'goog-submenu-open')); - assertFalse('Popup menu must not be visible', - subMenu.getMenu().isVisible()); - assertFalse('No OPEN event must have been dispatched', openEventDispatched); - assertFalse('No CLOSE event must have been dispatched', closeEventDispatched); - - subMenu.showSubMenu(); - assertTrue('Submenu must have "-open" CSS class', - goog.dom.classes.has(subMenu.getElement(), 'goog-submenu-open')); - assertTrue('Popup menu must be visible', - subMenu.getMenu().isVisible()); - assertTrue('OPEN event must have been dispatched', openEventDispatched); - assertFalse('No CLOSE event must have been dispatched', closeEventDispatched); - - subMenu.dismissSubMenu(); - assertFalse('Submenu must not have "-open" CSS class', - goog.dom.classes.has(subMenu.getElement(), 'goog-submenu-open')); - assertFalse('Popup menu must not be visible', - subMenu.getMenu().isVisible()); - assertTrue('CLOSE event must have been dispatched', closeEventDispatched); - - goog.events.unlisten(subMenu, [ - goog.ui.Component.EventType.OPEN, - goog.ui.Component.EventType.CLOSE - ], handleEvent); -} - -function testLazyInstantiateSubMenu() { - menu.decorate(goog.dom.getElement('demoMenu')); - var subMenu = menu.getChildAt(1); - subMenu.setHighlighted(true); - - var lazyMenu; - - var key = goog.events.listen(subMenu, goog.ui.Component.EventType.OPEN, - function(e) { - lazyMenu = new goog.ui.Menu(); - lazyMenu.addItem(new goog.ui.MenuItem('foo')); - lazyMenu.addItem(new goog.ui.MenuItem('bar')); - subMenu.setMenu(lazyMenu, /* opt_internal */ false); - }); - - subMenu.showSubMenu(); - assertNotNull('Popup menu must have been created', lazyMenu); - assertEquals('Popup menu must be a child of the submenu', subMenu, - lazyMenu.getParent()); - assertTrue('Popup menu must have been rendered', lazyMenu.isInDocument()); - assertTrue('Popup menu must be visible', lazyMenu.isVisible()); - - menu.dispose(); - assertTrue('Submenu must have been disposed of', subMenu.isDisposed()); - assertFalse('Popup menu must not have been disposed of', - lazyMenu.isDisposed()); - - lazyMenu.dispose(); - - goog.events.unlistenByKey(key); -} - -function testReusableMenu() { - var subMenuOne = new goog.ui.SubMenu('SubMenu One'); - var subMenuTwo = new goog.ui.SubMenu('SubMenu Two'); - menu.addItem(subMenuOne); - menu.addItem(subMenuTwo); - menu.render(goog.dom.getElement('sandbox')); - - // It is possible for the same popup menu to be shared between different - // submenus. - var sharedMenu = new goog.ui.Menu(); - sharedMenu.addItem(new goog.ui.MenuItem('Hello')); - sharedMenu.addItem(new goog.ui.MenuItem('World')); - - assertNull('Shared menu must not have a parent', sharedMenu.getParent()); - - subMenuOne.setMenu(sharedMenu); - assertEquals('SubMenuOne must point to the shared menu', sharedMenu, - subMenuOne.getMenu()); - assertEquals('SubMenuOne must be the shared menu\'s parent', subMenuOne, - sharedMenu.getParent()); - - subMenuTwo.setMenu(sharedMenu); - assertEquals('SubMenuTwo must point to the shared menu', sharedMenu, - subMenuTwo.getMenu()); - assertEquals('SubMenuTwo must be the shared menu\'s parent', subMenuTwo, - sharedMenu.getParent()); - assertEquals('SubMenuOne must still point to the shared menu', sharedMenu, - subMenuOne.getMenu()); - - menu.setHighlighted(subMenuOne); - subMenuOne.showSubMenu(); - assertEquals('SubMenuOne must point to the shared menu', sharedMenu, - subMenuOne.getMenu()); - assertEquals('SubMenuOne must be the shared menu\'s parent', subMenuOne, - sharedMenu.getParent()); - assertEquals('SubMenuTwo must still point to the shared menu', sharedMenu, - subMenuTwo.getMenu()); - assertTrue('Shared menu must be visible', sharedMenu.isVisible()); - - menu.setHighlighted(subMenuTwo); - subMenuTwo.showSubMenu(); - assertEquals('SubMenuTwo must point to the shared menu', sharedMenu, - subMenuTwo.getMenu()); - assertEquals('SubMenuTwo must be the shared menu\'s parent', subMenuTwo, - sharedMenu.getParent()); - assertEquals('SubMenuOne must still point to the shared menu', sharedMenu, - subMenuOne.getMenu()); - assertTrue('Shared menu must be visible', sharedMenu.isVisible()); -} - -/** - * If you remove a submenu in the interval between when a mouseover event - * is fired on it, and showSubMenu() is called, showSubMenu causes a null - * value to be dereferenced. This test validates that the fix for this works. - * (See bug 1823144). - */ -function testDeleteItemDuringSubmenuDisplayInterval() { - mockClock = new goog.testing.MockClock(true); - - var submenu = new goog.ui.SubMenu('submenu'); - submenu.addItem(new goog.ui.MenuItem("submenu item 1")); - menu.addItem(submenu); - - // Trigger mouseover, and remove item before showSubMenu can be called. - var e = new goog.events.Event(); - submenu.handleMouseOver(e); - menu.removeItem(submenu); - mockClock.tick(goog.ui.SubMenu.MENU_DELAY_MS); - // (No JS error should occur.) -} - -function testShowSubMenuAfterRemoval() { - var submenu = new goog.ui.SubMenu('submenu'); - menu.addItem(submenu); - menu.removeItem(submenu); - submenu.showSubMenu(); - // (No JS error should occur.) -} - -function testSubmenuSelectable() { - var submenu = new goog.ui.SubMenu('submenu'); - submenu.addItem(new goog.ui.MenuItem('submenu item 1')); - menu.addItem(submenu); - submenu.setSelectable(true); - - var numClicks = 0; - var menuClickedFn = function(e) { - numClicks++; - } - - goog.events.listen(submenu, goog.ui.Component.EventType.ACTION, - menuClickedFn); - submenu.performActionInternal(null); - submenu.performActionInternal(null); - - assertEquals('The submenu should have fired an event', 2, numClicks); - - submenu.setSelectable(false); - submenu.performActionInternal(null); - - assertEquals('The submenu should not have fired any further events', 2, - numClicks); -} - -/** - * Asserts that this sub menu renders in the right direction relative to - * the parent menu. - * @param {goog.ui.SubMenu} subMenu The sub menu. - * @param {boolean} left True for left-pointing, false for right-pointing. - */ -function assertRenderDirection(subMenu, left) { - subMenu.getParent().setHighlighted(subMenu); - subMenu.showSubMenu(); - var menuItemPosition = goog.style.getPageOffset(subMenu.getElement()); - var menuPosition = goog.style.getPageOffset(subMenu.getMenu().getElement()); - assert(Math.abs(menuItemPosition.y - menuPosition.y) < 5); - assertEquals( - "Menu at: " + menuPosition.x + - ", submenu item at: " + menuItemPosition.x, - left, menuPosition.x < menuItemPosition.x); -} - -/** - * Asserts that this sub menu has a properly-oriented arrow. - * @param {goog.ui.SubMenu} subMenu The sub menu. - * @param {boolean} left True for left-pointing, false for right-pointing. - */ -function assertArrowDirection(subMenu, left) { - assertEquals( - left ? goog.ui.SubMenuRenderer.LEFT_ARROW_ : - goog.ui.SubMenuRenderer.RIGHT_ARROW_, - getArrowElement(subMenu).innerHTML); -} - -/** - * Asserts that the arrow position is correct. - * @param {goog.ui.SubMenu} subMenu The sub menu. - * @param {boolean} leftAlign True for left-aligned, false for right-aligned. - */ -function assertArrowPosition(subMenu, left) { - var arrow = getArrowElement(subMenu); - var expectedLeft = - left ? 0 : arrow.offsetParent.offsetWidth - arrow.offsetWidth; - var actualLeft = arrow.offsetLeft; - assertTrue('Expected left offset: ' + expectedLeft + '\n' + - 'Actual left offset: ' + actualLeft + '\n', - Math.abs(expectedLeft - actualLeft) < 5); -} - -/** - * Gets the arrow element of a sub menu. - * @param {goog.ui.SubMenu} subMenu The sub menu. - * @return {Element} The arrow. - */ -function getArrowElement(subMenu) { - return subMenu.getContentElement().lastChild; -} - -</script> - -<p> - Here's a menu (with submenus) defined in markup: -</p> -<div id="demoMenu" class="goog-menu"> - <div class="goog-menuitem">Open...</div> - <div class="goog-submenu">Open Recent - <div class="goog-menu"> - <div class="goog-menuitem">Annual Report.pdf</div> - <div class="goog-menuitem">Quarterly Update.pdf</div> - <div class="goog-menuitem">Enemies List.txt</div> - <div class="goog-submenu">More - <div class="goog-menu"> - <div class="goog-menuitem">Foo.txt</div> - <div class="goog-menuitem">Bar.txt</div> - </div> - </div> - </div> - </div> -</div> -<div id="sandbox"></div> - -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/submenurenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/submenurenderer.js.svn-base deleted file mode 100644 index 3836039..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/submenurenderer.js.svn-base +++ /dev/null @@ -1,222 +0,0 @@ -// 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.SubMenu}s. - * - */ - -goog.provide('goog.ui.SubMenuRenderer'); - -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.a11y.State'); -goog.require('goog.dom.classes'); -goog.require('goog.style'); -goog.require('goog.ui.Menu'); -goog.require('goog.ui.MenuItemRenderer'); - - - -/** - * Default renderer for {@link goog.ui.SubMenu}s. Each item has the following - * structure: - * <div class="goog-submenu"> - * ...(menuitem content)... - * <div class="goog-menu"> - * ... (submenu content) ... - * </div> - * </div> - * @constructor - * @extends {goog.ui.MenuItemRenderer} - */ -goog.ui.SubMenuRenderer = function() { - goog.ui.MenuItemRenderer.call(this); -}; -goog.inherits(goog.ui.SubMenuRenderer, goog.ui.MenuItemRenderer); -goog.addSingletonGetter(goog.ui.SubMenuRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.SubMenuRenderer.CSS_CLASS = goog.getCssName('goog-submenu'); - - -/** - * The CSS class for submenus that displays the submenu arrow. - * @type {string} - * @private - */ -goog.ui.SubMenuRenderer.CSS_CLASS_SUBMENU_ = - goog.getCssName('goog-submenu-arrow'); - - -/** - * Overrides {@link goog.ui.MenuItemRenderer#createDom} by adding - * the additional class 'goog-submenu' to the created element, - * and passes the element to {@link goog.ui.SubMenuItemRenderer#addArrow_} - * to add an child element that can be styled to show an arrow. - * @param {goog.ui.SubMenu} subMenu SubMenu to render. - * @return {Element} Root element for the item. - */ -goog.ui.SubMenuRenderer.prototype.createDom = function(subMenu) { - var element = goog.ui.SubMenuRenderer.superClass_.createDom.call(this, - subMenu); - goog.dom.classes.add(element, goog.ui.SubMenuRenderer.CSS_CLASS); - this.addArrow_(subMenu, element); - return element; -}; - - -/** - * Overrides {@link goog.ui.MenuItemRenderer#decorate} by adding - * the additional class 'goog-submenu' to the decorated element, - * and passing the element to {@link goog.ui.SubMenuItemRenderer#addArrow_} - * to add a child element that can be styled to show an arrow. - * Also searches the element for a child with the class goog-menu. If a - * matching child element is found, creates a goog.ui.Menu, uses it to - * decorate the child element, and passes that menu to subMenu.setMenu. - * @param {goog.ui.SubMenu} subMenu SubMenu to render. - * @param {Element} element Element to decorate. - * @return {Element} Root element for the item. - */ -goog.ui.SubMenuRenderer.prototype.decorate = function(subMenu, element) { - element = goog.ui.SubMenuRenderer.superClass_.decorate.call( - this, subMenu, element); - goog.dom.classes.add(element, goog.ui.SubMenuRenderer.CSS_CLASS); - this.addArrow_(subMenu, element); - - // Search for a child menu and decorate it. - var childMenuEls = goog.dom.getElementsByTagNameAndClass( - 'div', goog.getCssName('goog-menu'), element); - if (childMenuEls.length) { - var childMenu = new goog.ui.Menu(subMenu.getDomHelper()); - var childMenuEl = childMenuEls[0]; - // Hide the menu element before attaching it to the document body; see - // bug 1089244. - goog.style.showElement(childMenuEl, false); - subMenu.getDomHelper().getDocument().body.appendChild(childMenuEl); - childMenu.decorate(childMenuEl); - subMenu.setMenu(childMenu, true); - } - return element; -}; - - -/** - * Takes a menu item's root element, and sets its content to the given text - * caption or DOM structure. Overrides the superclass immplementation by - * making sure that the submenu arrow structure is preserved. - * @param {Element} element The item's root element. - * @param {goog.ui.ControlContent} content Text caption or DOM structure to be - * set as the item's content. - * @override - */ -goog.ui.SubMenuRenderer.prototype.setContent = function(element, content) { - // Save the submenu arrow element, if present. - var contentElement = this.getContentElement(element); - var arrowElement = contentElement && contentElement.lastChild; - goog.ui.SubMenuRenderer.superClass_.setContent.call(this, element, content); - // If the arrowElement was there, is no longer there, and really was an arrow, - // reappend it. - if (arrowElement && - contentElement.lastChild != arrowElement && - goog.dom.classes.has(arrowElement, - goog.ui.SubMenuRenderer.CSS_CLASS_SUBMENU_)) { - contentElement.appendChild(arrowElement); - } -}; - - -/** - * Overrides {@link goog.ui.MenuItemRenderer#initializeDom} to tweak - * the DOM structure for the span.goog-submenu-arrow element - * depending on the text direction (LTR or RTL). When the SubMenu is RTL - * the arrow will be given the additional class of goog-submenu-arrow-rtl, - * and the arrow will be moved up to be the first child in the SubMenu's - * element. Otherwise the arrow will have the class goog-submenu-arrow-ltr, - * and be kept as the last child of the SubMenu's element. - * @param {goog.ui.SubMenu} subMenu SubMenu whose DOM is to be initialized - * as it enters the document. - */ -goog.ui.SubMenuRenderer.prototype.initializeDom = function(subMenu) { - goog.ui.SubMenuRenderer.superClass_.initializeDom.call(this, subMenu); - var element = subMenu.getContentElement(); - var arrow = subMenu.getDomHelper().getElementsByTagNameAndClass( - 'span', goog.ui.SubMenuRenderer.CSS_CLASS_SUBMENU_, element)[0]; - goog.ui.SubMenuRenderer.setArrowTextContent_(subMenu, arrow); - if (arrow != element.lastChild) { - element.appendChild(arrow); - } - goog.dom.a11y.setState(subMenu.getElement(), goog.dom.a11y.State.HASPOPUP, - 'true'); -}; - - -/** - * Appends a child node with the class goog.getCssName('goog-submenu-arrow') or - * 'goog-submenu-arrow-rtl' which can be styled to show an arrow. - * @param {goog.ui.SubMenu} subMenu SubMenu to render. - * @param {Element} element Element to decorate. - * @private - */ -goog.ui.SubMenuRenderer.prototype.addArrow_ = function(subMenu, element) { - var arrow = subMenu.getDomHelper().createDom('span'); - arrow.className = goog.ui.SubMenuRenderer.CSS_CLASS_SUBMENU_; - goog.ui.SubMenuRenderer.setArrowTextContent_(subMenu, arrow); - this.getContentElement(element).appendChild(arrow); -}; - - -/** - * The unicode char for a left arrow. - * @type {string} - * @private - */ -goog.ui.SubMenuRenderer.LEFT_ARROW_ = '\u25C4'; - - -/** - * The unicode char for a right arrow. - * @type {string} - * @private - */ -goog.ui.SubMenuRenderer.RIGHT_ARROW_ = '\u25BA'; - - -/** - * Set the text content of an arrow. - * @param {goog.ui.SubMenu} subMenu The sub menu that owns the arrow. - * @param {Element} arrow The arrow element. - * @private - */ -goog.ui.SubMenuRenderer.setArrowTextContent_ = function(subMenu, arrow) { - // Fix arrow rtl - var leftArrow = goog.ui.SubMenuRenderer.LEFT_ARROW_; - var rightArrow = goog.ui.SubMenuRenderer.RIGHT_ARROW_; - if (subMenu.isRightToLeft()) { - goog.dom.classes.add(arrow, goog.getCssName('goog-submenu-arrow-rtl')); - // Unicode character - Black left-pointing pointer iff aligned to end. - goog.dom.setTextContent(arrow, subMenu.isAlignedToEnd() ? - leftArrow : rightArrow); - } else { - goog.dom.classes.remove(arrow, goog.getCssName('goog-submenu-arrow-rtl')); - // Unicode character - Black right-pointing pointer iff aligned to end. - goog.dom.setTextContent(arrow, subMenu.isAlignedToEnd() ? - rightArrow : leftArrow); - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tab.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tab.js.svn-base deleted file mode 100644 index 706e45e..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tab.js.svn-base +++ /dev/null @@ -1,103 +0,0 @@ -// 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 tab control, designed to be used in {@link goog.ui.TabBar}s. - * - * @author attila@google.com (Attila Bodis) - * @see ../demos/tabbar.html - */ - -goog.provide('goog.ui.Tab'); - -goog.require('goog.ui.Component.State'); -goog.require('goog.ui.Control'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.TabRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * Tab control, designed to be hosted in a {@link goog.ui.TabBar}. The tab's - * DOM may be different based on the configuration of the containing tab bar, - * so tabs should only be rendered or decorated as children of a tab bar. - * @param {goog.ui.ControlContent} content Text caption or DOM structure to - * display as the tab's caption (if any). - * @param {goog.ui.TabRenderer=} opt_renderer Optional renderer used to render - * or decorate the tab. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for - * document interaction. - * @constructor - * @extends {goog.ui.Control} - */ -goog.ui.Tab = function(content, opt_renderer, opt_domHelper) { - goog.ui.Control.call(this, content, - opt_renderer || goog.ui.TabRenderer.getInstance(), opt_domHelper); - - // Tabs support the SELECTED state. - this.setSupportedState(goog.ui.Component.State.SELECTED, true); - - // Tabs must dispatch state transition events for the DISABLED and SELECTED - // states in order for the tab bar to function properly. - this.setDispatchTransitionEvents( - goog.ui.Component.State.DISABLED | goog.ui.Component.State.SELECTED, - true); -}; -goog.inherits(goog.ui.Tab, goog.ui.Control); - - -/** - * Tooltip text for the tab, displayed on hover (if any). - * @type {string|undefined} - * @private - */ -goog.ui.Tab.prototype.tooltip_; - - -/** - * @return {string|undefined} Tab tooltip text (if any). - */ -goog.ui.Tab.prototype.getTooltip = function() { - return this.tooltip_; -}; - - -/** - * Sets the tab tooltip text. If the tab has already been rendered, updates - * its tooltip. - * @param {string} tooltip New tooltip text. - */ -goog.ui.Tab.prototype.setTooltip = function(tooltip) { - this.getRenderer().setTooltip(this.getElement(), tooltip); - this.setTooltipInternal(tooltip); -}; - - -/** - * Sets the tab tooltip text. Considered protected; to be called only by the - * renderer during element decoration. - * @param {string} tooltip New tooltip text. - * @protected - */ -goog.ui.Tab.prototype.setTooltipInternal = function(tooltip) { - this.tooltip_ = tooltip; -}; - - -// Register a decorator factory function for goog.ui.Tabs. -goog.ui.registry.setDecoratorByClassName(goog.ui.TabRenderer.CSS_CLASS, - function() { - return new goog.ui.Tab(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tab_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tab_test.html.svn-base deleted file mode 100644 index 7c470f2..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tab_test.html.svn-base +++ /dev/null @@ -1,62 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.Tab</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Component.State'); - goog.require('goog.ui.Tab'); - goog.require('goog.ui.TabRenderer'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var sandbox = goog.dom.getElement('sandbox'); - var tab; - - function setUp() { - tab = new goog.ui.Tab('Hello'); - } - - function tearDown() { - tab.dispose(); - goog.dom.removeChildren(sandbox); - } - - function testConstructor() { - assertNotNull('Tab must not be null', tab); - assertEquals('Tab must have expected content', 'Hello', tab.getContent()); - assertEquals('Tab\'s renderer must default to TabRenderer', - goog.ui.TabRenderer.getInstance(), tab.getRenderer()); - assertTrue('Tab must support the SELECTED state', - tab.isSupportedState(goog.ui.Component.State.SELECTED)); - assertTrue('SELECTED must be an auto-state', - tab.isAutoState(goog.ui.Component.State.SELECTED)); - assertTrue('Tab must dispatch transition events for the DISABLED state', - tab.isDispatchTransitionEvents(goog.ui.Component.State.DISABLED)); - assertTrue('Tab must dispatch transition events for the SELECTED state', - tab.isDispatchTransitionEvents(goog.ui.Component.State.SELECTED)); - } - - function testGetSetTooltip() { - assertUndefined('Tooltip must be undefined by default', tab.getTooltip()); - tab.setTooltip('Hello, world!'); - assertEquals('Tooltip must have expected value', 'Hello, world!', - tab.getTooltip()); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabbar.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabbar.js.svn-base deleted file mode 100644 index ceb6452..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabbar.js.svn-base +++ /dev/null @@ -1,394 +0,0 @@ -// 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 Tab bar UI component. - * - * @author attila@google.com (Attila Bodis) - * @see ../demos/tabbar.html - */ - -goog.provide('goog.ui.TabBar'); -goog.provide('goog.ui.TabBar.Location'); - -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.Container'); -goog.require('goog.ui.Container.Orientation'); -// We need to include following dependency because of the magic with -// goog.ui.registry.setDecoratorByClassName -goog.require('goog.ui.Tab'); -goog.require('goog.ui.TabBarRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * Tab bar UI component. A tab bar contains tabs, rendered above, below, - * before, or after tab contents. Tabs in tab bars dispatch the following - * events: - * <ul> - * <li>{@link goog.ui.Component.EventType.ACTION} when activated via the - * keyboard or the mouse, - * <li>{@link goog.ui.Component.EventType.SELECT} when selected, and - * <li>{@link goog.ui.Component.EventType.UNSELECT} when deselected. - * </ul> - * Clients may listen for all of the above events on the tab bar itself, and - * refer to the event target to identify the tab that dispatched the event. - * When an unselected tab is clicked for the first time, it dispatches both a - * {@code SELECT} event and an {@code ACTION} event; subsequent clicks on an - * already selected tab only result in {@code ACTION} events. - * - * @param {goog.ui.TabBar.Location=} opt_location Tab bar location; defaults to - * {@link goog.ui.TabBar.Location.TOP}. - * @param {goog.ui.TabBarRenderer=} opt_renderer Renderer used to render or - * decorate the container; defaults to {@link goog.ui.TabBarRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for document - * interaction. - * @constructor - * @extends {goog.ui.Container} - */ -goog.ui.TabBar = function(opt_location, opt_renderer, opt_domHelper) { - this.setLocation(opt_location || goog.ui.TabBar.Location.TOP); - - goog.ui.Container.call(this, this.getOrientation(), - opt_renderer || goog.ui.TabBarRenderer.getInstance(), - opt_domHelper); - - this.listenToTabEvents_(); -}; -goog.inherits(goog.ui.TabBar, goog.ui.Container); - - -/** - * Tab bar location relative to tab contents. - * @enum {string} - */ -goog.ui.TabBar.Location = { - // Above tab contents. - TOP: 'top', - // Below tab contents. - BOTTOM: 'bottom', - // To the left of tab contents (to the right if the page is right-to-left). - START: 'start', - // To the right of tab contents (to the left if the page is right-to-left). - END: 'end' -}; - - -/** - * Tab bar location; defaults to {@link goog.ui.TabBar.Location.TOP}. - * @type {goog.ui.TabBar.Location} - * @private - */ -goog.ui.TabBar.prototype.location_; - - -/** - * Whether keyboard navigation should change the selected tab, or just move - * the highlight. Defaults to true. - * @type {boolean} - * @private - */ -goog.ui.TabBar.prototype.autoSelectTabs_ = true; - - -/** - * The currently selected tab (null if none). - * @type {goog.ui.Control?} - * @private - */ -goog.ui.TabBar.prototype.selectedTab_ = null; - - -/** - * @override - */ -goog.ui.TabBar.prototype.enterDocument = function() { - goog.ui.TabBar.superClass_.enterDocument.call(this); - - this.listenToTabEvents_(); -}; - - -/** @override */ -goog.ui.TabBar.prototype.disposeInternal = function() { - goog.ui.TabBar.superClass_.disposeInternal.call(this); - this.selectedTab_ = null; -}; - - -/** - * Removes the tab from the tab bar. Overrides the superclass implementation - * by deselecting the tab being removed. Since {@link #removeChildAt} uses - * {@link #removeChild} internally, we only need to override this method. - * @param {string|goog.ui.Control} tab Tab to remove. - * @param {boolean=} opt_unrender Whether to call {@code exitDocument} on the - * removed tab, and detach its DOM from the document (defaults to false). - * @return {goog.ui.Control} The removed tab, if any. - * @override - */ -goog.ui.TabBar.prototype.removeChild = function(tab, opt_unrender) { - // This actually only accepts goog.ui.Controls. There's a TODO - // on the superclass method to fix this. - this.deselectIfSelected(/** @type {goog.ui.Control} */ (tab)); - return goog.ui.TabBar.superClass_.removeChild.call(this, tab, opt_unrender); -}; - - -/** - * @return {goog.ui.TabBar.Location} Tab bar location relative to tab contents. - */ -goog.ui.TabBar.prototype.getLocation = function() { - return this.location_; -}; - - -/** - * Sets the location of the tab bar relative to tab contents. - * @param {goog.ui.TabBar.Location} location Tab bar location relative to tab - * contents. - * @throws {Error} If the tab bar has already been rendered. - */ -goog.ui.TabBar.prototype.setLocation = function(location) { - // setOrientation() will take care of throwing an error if already rendered. - this.setOrientation(goog.ui.TabBar.getOrientationFromLocation(location)); - this.location_ = location; -}; - - -/** - * @return {boolean} Whether keyboard navigation should change the selected tab, - * or just move the highlight. - */ -goog.ui.TabBar.prototype.isAutoSelectTabs = function() { - return this.autoSelectTabs_; -}; - - -/** - * Enables or disables auto-selecting tabs using the keyboard. If auto-select - * is enabled, keyboard navigation switches tabs immediately, otherwise it just - * moves the highlight. - * @param {boolean} enable Whether keyboard navigation should change the - * selected tab, or just move the highlight. - */ -goog.ui.TabBar.prototype.setAutoSelectTabs = function(enable) { - this.autoSelectTabs_ = enable; -}; - - -/** - * Highlights the tab at the given index in response to a keyboard event. - * Overrides the superclass implementation by also selecting the tab if - * {@link #isAutoSelectTabs} returns true. - * @param {number} index Index of tab to highlight. - * @protected - * @override - */ -goog.ui.TabBar.prototype.setHighlightedIndexFromKeyEvent = function(index) { - goog.ui.TabBar.superClass_.setHighlightedIndexFromKeyEvent.call(this, index); - if (this.autoSelectTabs_) { - // Immediately select the tab. - this.setSelectedTabIndex(index); - } -}; - - -/** - * @return {goog.ui.Control?} The currently selected tab (null if none). - */ -goog.ui.TabBar.prototype.getSelectedTab = function() { - return this.selectedTab_; -}; - - -/** - * Selects the given tab. - * @param {goog.ui.Control?} tab Tab to select (null to select none). - */ -goog.ui.TabBar.prototype.setSelectedTab = function(tab) { - if (tab) { - // Select the tab and have it dispatch a SELECT event, to be handled in - // handleTabSelect() below. - tab.setSelected(true); - } else if (this.getSelectedTab()) { - // De-select the currently selected tab and have it dispatch an UNSELECT - // event, to be handled in handleTabUnselect() below. - this.getSelectedTab().setSelected(false); - } -}; - - -/** - * @return {number} Index of the currently selected tab (-1 if none). - */ -goog.ui.TabBar.prototype.getSelectedTabIndex = function() { - return this.indexOfChild(this.getSelectedTab()); -}; - - -/** - * Selects the tab at the given index. - * @param {number} index Index of the tab to select (-1 to select none). - */ -goog.ui.TabBar.prototype.setSelectedTabIndex = function(index) { - this.setSelectedTab(/** @type {goog.ui.Tab} */ (this.getChildAt(index))); -}; - - -/** - * If the specified tab is the currently selected tab, deselects it, and - * selects the closest selectable tab in the tab bar (first looking before, - * then after the deselected tab). Does nothing if the argument is not the - * currently selected tab. Called internally when a tab is removed, hidden, - * or disabled, to ensure that another tab is selected instead. - * @param {goog.ui.Control?} tab Tab to deselect (if any). - * @protected - */ -goog.ui.TabBar.prototype.deselectIfSelected = function(tab) { - if (tab && tab == this.getSelectedTab()) { - var index = this.indexOfChild(tab); - // First look for the closest selectable tab before this one. - for (var i = index - 1; - tab = /** @type {goog.ui.Tab} */ (this.getChildAt(i)); - i--) { - if (this.isSelectableTab(tab)) { - this.setSelectedTab(tab); - return; - } - } - // Next, look for the closest selectable tab after this one. - for (var j = index + 1; - tab = /** @type {goog.ui.Tab} */ (this.getChildAt(j)); - j++) { - if (this.isSelectableTab(tab)) { - this.setSelectedTab(tab); - return; - } - } - // If all else fails, just set the selection to null. - this.setSelectedTab(null); - } -}; - - -/** - * Returns true if the tab is selectable, false otherwise. Only visible and - * enabled tabs are selectable. - * @param {goog.ui.Control} tab Tab to check. - * @return {boolean} Whether the tab is selectable. - * @protected - */ -goog.ui.TabBar.prototype.isSelectableTab = function(tab) { - return tab.isVisible() && tab.isEnabled(); -}; - - -/** - * Handles {@code SELECT} events dispatched by tabs as they become selected. - * @param {goog.events.Event} e Select event to handle. - * @protected - */ -goog.ui.TabBar.prototype.handleTabSelect = function(e) { - if (this.selectedTab_ && this.selectedTab_ != e.target) { - // Deselect currently selected tab. - this.selectedTab_.setSelected(false); - } - this.selectedTab_ = /** @type {goog.ui.Tab} */ (e.target); -}; - - -/** - * Handles {@code UNSELECT} events dispatched by tabs as they become deselected. - * @param {goog.events.Event} e Unselect event to handle. - * @protected - */ -goog.ui.TabBar.prototype.handleTabUnselect = function(e) { - if (e.target == this.selectedTab_) { - this.selectedTab_ = null; - } -}; - - -/** - * Handles {@code DISABLE} events displayed by tabs. - * @param {goog.events.Event} e Disable event to handle. - * @protected - */ -goog.ui.TabBar.prototype.handleTabDisable = function(e) { - this.deselectIfSelected(/** @type {goog.ui.Tab} */ (e.target)); -}; - - -/** - * Handles {@code HIDE} events displayed by tabs. - * @param {goog.events.Event} e Hide event to handle. - * @protected - */ -goog.ui.TabBar.prototype.handleTabHide = function(e) { - this.deselectIfSelected(/** @type {goog.ui.Tab} */ (e.target)); -}; - - -/** - * Handles focus events dispatched by the tab bar's key event target. If no tab - * is currently highlighted, highlights the selected tab or the first tab if no - * tab is selected either. - * @param {goog.events.Event} e Focus event to handle. - * @protected - * @override - */ -goog.ui.TabBar.prototype.handleFocus = function(e) { - if (!this.getHighlighted()) { - this.setHighlighted(this.getSelectedTab() || - /** @type {goog.ui.Tab} */ (this.getChildAt(0))); - } -}; - - -/** - * Subscribes to events dispatched by tabs. - * @private - */ -goog.ui.TabBar.prototype.listenToTabEvents_ = function() { - // Listen for SELECT, UNSELECT, DISABLE, and HIDE events dispatched by tabs. - this.getHandler(). - listen(this, goog.ui.Component.EventType.SELECT, this.handleTabSelect). - listen(this, - goog.ui.Component.EventType.UNSELECT, - this.handleTabUnselect). - listen(this, goog.ui.Component.EventType.DISABLE, this.handleTabDisable). - listen(this, goog.ui.Component.EventType.HIDE, this.handleTabHide); -}; - - -/** - * Returns the {@link goog.ui.Container.Orientation} that is implied by the - * given {@link goog.ui.TabBar.Location}. - * @param {goog.ui.TabBar.Location} location Tab bar location. - * @return {goog.ui.Container.Orientation} Corresponding orientation. - */ -goog.ui.TabBar.getOrientationFromLocation = function(location) { - return location == goog.ui.TabBar.Location.START || - location == goog.ui.TabBar.Location.END ? - goog.ui.Container.Orientation.VERTICAL : - goog.ui.Container.Orientation.HORIZONTAL; -}; - - -// Register a decorator factory function for goog.ui.TabBars. -goog.ui.registry.setDecoratorByClassName(goog.ui.TabBarRenderer.CSS_CLASS, - function() { - return new goog.ui.TabBar(); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabbar_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabbar_test.html.svn-base deleted file mode 100644 index bf3c39e..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabbar_test.html.svn-base +++ /dev/null @@ -1,612 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.TabBar</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.events.Event'); - goog.require('goog.events.EventType'); - goog.require('goog.events.KeyCodes'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Component'); - goog.require('goog.ui.Component.EventType'); - goog.require('goog.ui.Container.Orientation'); - goog.require('goog.ui.Tab'); - goog.require('goog.ui.TabBar'); - goog.require('goog.ui.TabBar.Location'); - goog.require('goog.ui.TabBarRenderer'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var sandbox = goog.dom.getElement('sandbox'); - var tabBar; - - // Fake keyboard event object. - function FakeKeyEvent(keyCode) { - this.keyCode = keyCode; - this.defaultPrevented = false; - this.propagationStopped = false; - } - FakeKeyEvent.prototype.preventDefault = function() { - this.defaultPrevented = true; - }; - FakeKeyEvent.prototype.stopPropagation = function() { - this.propagationStopped = true; - }; - - function setUp() { - tabBar = new goog.ui.TabBar(); - } - - function tearDown() { - tabBar.dispose(); - goog.dom.removeChildren(sandbox); - } - - function testConstructor() { - assertNotNull('Tab bar must not be null', tabBar); - assertEquals('Tab bar renderer must default to expected value', - goog.ui.TabBarRenderer.getInstance(), tabBar.getRenderer()); - assertEquals('Tab bar location must default to expected value', - goog.ui.TabBar.Location.TOP, tabBar.getLocation()); - assertEquals('Tab bar orientation must default to expected value', - goog.ui.Container.Orientation.HORIZONTAL, tabBar.getOrientation()); - - var fakeRenderer = {}; - var fakeDomHelper = {}; - var bar = new goog.ui.TabBar(goog.ui.TabBar.Location.START, fakeRenderer, - fakeDomHelper); - assertNotNull('Tab bar must not be null', bar); - assertEquals('Tab bar renderer must have expected value', - fakeRenderer, bar.getRenderer()); - assertEquals('Tab bar DOM helper must have expected value', - fakeDomHelper, bar.getDomHelper()); - assertEquals('Tab bar location must have expected value', - goog.ui.TabBar.Location.START, bar.getLocation()); - assertEquals('Tab bar orientation must have expected value', - goog.ui.Container.Orientation.VERTICAL, bar.getOrientation()); - bar.dispose(); - } - - function testDispose() { - // Set tabBar.selectedTab_ to something non-null, just to test dispose(). - tabBar.selectedTab_ = {}; - assertNotNull('Selected tab must be non-null', tabBar.getSelectedTab()); - assertFalse('Tab bar must not have been disposed of', - tabBar.isDisposed()); - tabBar.dispose(); - assertNull('Selected tab must be null', tabBar.getSelectedTab()); - assertTrue('Tab bar must have been disposed of', tabBar.isDisposed()); - } - - function testAddRemoveChild() { - assertNull('No tab must be selected', tabBar.getSelectedTab()); - - var first = new goog.ui.Tab('First'); - tabBar.addChild(first); - assertEquals('First tab must have been added at the expected index', 0, - tabBar.indexOfChild(first)); - first.setSelected(true); - assertEquals('First tab must be selected', 0, - tabBar.getSelectedTabIndex()); - - var second = new goog.ui.Tab('Second'); - tabBar.addChild(second); - assertEquals('Second tab must have been added at the expected index', 1, - tabBar.indexOfChild(second)); - assertEquals('First tab must remain selected', 0, - tabBar.getSelectedTabIndex()); - - var firstRemoved = tabBar.removeChild(first); - assertEquals('removeChild() must return the removed tab', first, - firstRemoved); - assertEquals('First tab must no longer be in the tab bar', -1, - tabBar.indexOfChild(first)); - assertEquals('Second tab must be at the expected index', 0, - tabBar.indexOfChild(second)); - assertFalse('First tab must no longer be selected', first.isSelected()); - assertTrue('Remaining tab must be selected', second.isSelected()); - - var secondRemoved = tabBar.removeChild(second); - assertEquals('removeChild() must return the removed tab', second, - secondRemoved); - assertFalse('Tab must no longer be selected', second.isSelected()); - assertNull('No tab must be selected', tabBar.getSelectedTab()); - } - - function testGetSetLocation() { - assertEquals('Location must default to TOP', goog.ui.TabBar.Location.TOP, - tabBar.getLocation()); - tabBar.setLocation(goog.ui.TabBar.Location.START); - assertEquals('Location must have expected value', - goog.ui.TabBar.Location.START, tabBar.getLocation()); - tabBar.createDom(); - assertThrows('Attempting to change the location after the tab bar has ' + - 'been rendered must throw error', - function() { - tabBar.setLocation(goog.ui.TabBar.Location.BOTTOM); - }); - } - - function testIsSetAutoSelectTabs() { - assertTrue('Tab bar must auto-select tabs by default', - tabBar.isAutoSelectTabs()); - tabBar.setAutoSelectTabs(false); - assertFalse('Tab bar must no longer auto-select tabs by default', - tabBar.isAutoSelectTabs()); - tabBar.render(sandbox); - assertFalse('Rendering must not change auto-select setting', - tabBar.isAutoSelectTabs()); - tabBar.setAutoSelectTabs(true); - assertTrue('Tab bar must once again auto-select tabs', - tabBar.isAutoSelectTabs()); - } - - function setHighlightedIndexFromKeyEvent() { - var foo, bar, baz; - - // Create a tab bar with some tabs. - tabBar.addChild(foo = new goog.ui.Tab('foo')); - tabBar.addChild(bar = new goog.ui.Tab('bar')); - tabBar.addChild(baz = new goog.ui.Tab('baz')); - - // Verify baseline assumptions. - assertNull('No tab must be highlighted', tabBar.getHighlighted()); - assertNull('No tab must be selected', tabBar.getSelectedTab()); - assertTrue('Tab bar must auto-select tabs on keyboard highlight', - tabBar.isAutoSelectTabs()); - - // Highlight and selection must move together. - tabBar.setHighlightedIndexFromKeyEvent(0); - assertTrue('Foo must be highlighted', foo.isHighlighted()); - assertTrue('Foo must be selected', foo.isSelected()); - - // Highlight and selection must move together. - tabBar.setHighlightedIndexFromKeyEvent(1); - assertFalse('Foo must no longer be highlighted', foo.isHighlighted()); - assertFalse('Foo must no longer be selected', foo.isSelected()); - assertTrue('Bar must be highlighted', bar.isHighlighted()); - assertTrue('Bar must be selected', bar.isSelected()); - - // Turn off auto-select-on-keyboard-highlight. - tabBar.setAutoSelectTabs(false); - - // Selection must not change; only highlight should move. - tabBar.setHighlightedIndexFromKeyEvent(2); - assertFalse('Bar must no longer be highlighted', bar.isHighlighted()); - assertTrue('Bar must remain selected', bar.isSelected()); - assertTrue('Baz must be highlighted', baz.isHighlighted()); - assertFalse('Baz must not be selected', baz.isSelected()); - } - - function testGetSetSelectedTab() { - var foo, bar, baz; - - // Create a tab bar with some tabs. - tabBar.addChild(foo = new goog.ui.Tab('foo')); - tabBar.addChild(bar = new goog.ui.Tab('bar')); - tabBar.addChild(baz = new goog.ui.Tab('baz')); - - assertNull('No tab must be selected', tabBar.getSelectedTab()); - - tabBar.setSelectedTab(baz); - assertTrue('Baz must be selected', baz.isSelected()); - assertEquals('Baz must be the selected tab', baz, - tabBar.getSelectedTab()); - - tabBar.setSelectedTab(foo); - assertFalse('Baz must no longer be selected', baz.isSelected()); - assertTrue('Foo must be selected', foo.isSelected()); - assertEquals('Foo must be the selected tab', foo, - tabBar.getSelectedTab()); - - tabBar.setSelectedTab(foo); - assertTrue('Foo must remain selected', foo.isSelected()); - assertEquals('Foo must remain the selected tab', foo, - tabBar.getSelectedTab()); - - tabBar.setSelectedTab(null); - assertFalse('Foo must no longer be selected', foo.isSelected()); - assertNull('No tab must be selected', tabBar.getSelectedTab()); - } - - function testGetSetSelectedTabIndex() { - var foo, bar, baz; - - // Create a tab bar with some tabs. - tabBar.addChildAt(foo = new goog.ui.Tab('foo'), 0); - tabBar.addChildAt(bar = new goog.ui.Tab('bar'), 1); - tabBar.addChildAt(baz = new goog.ui.Tab('baz'), 2); - - assertEquals('No tab must be selected', -1, tabBar.getSelectedTabIndex()); - - tabBar.setSelectedTabIndex(2); - assertTrue('Baz must be selected', baz.isSelected()); - assertEquals('Baz must be the selected tab', 2, - tabBar.getSelectedTabIndex()); - - tabBar.setSelectedTabIndex(0); - assertFalse('Baz must no longer be selected', baz.isSelected()); - assertTrue('Foo must be selected', foo.isSelected()); - assertEquals('Foo must be the selected tab', 0, - tabBar.getSelectedTabIndex()); - - tabBar.setSelectedTabIndex(0); - assertTrue('Foo must remain selected', foo.isSelected()); - assertEquals('Foo must remain the selected tab', 0, - tabBar.getSelectedTabIndex()); - - tabBar.setSelectedTabIndex(-1); - assertFalse('Foo must no longer be selected', foo.isSelected()); - assertEquals('No tab must be selected', -1, tabBar.getSelectedTabIndex()); - } - - function testDeselectIfSelected() { - var foo, bar, baz; - - // Create a tab bar with some tabs. - tabBar.addChild(foo = new goog.ui.Tab('foo')); - tabBar.addChild(bar = new goog.ui.Tab('bar')); - tabBar.addChild(baz = new goog.ui.Tab('baz')); - - // Start with the middle tab selected. - bar.setSelected(true); - assertTrue('Bar must be selected', bar.isSelected()); - assertEquals('Bar must be the selected tab', bar, - tabBar.getSelectedTab()); - - // Should be a no-op. - tabBar.deselectIfSelected(null); - assertTrue('Bar must remain selected', bar.isSelected()); - assertEquals('Bar must remain the selected tab', bar, - tabBar.getSelectedTab()); - - // Should be a no-op. - tabBar.deselectIfSelected(foo); - assertTrue('Bar must remain selected', bar.isSelected()); - assertEquals('Bar must remain the selected tab', bar, - tabBar.getSelectedTab()); - - // Should deselect bar and select the previous tab (foo). - tabBar.deselectIfSelected(bar); - assertFalse('Bar must no longer be selected', bar.isSelected()); - assertTrue('Foo must be selected', foo.isSelected()); - assertEquals('Foo must be the selected tab', foo, - tabBar.getSelectedTab()); - - // Should deselect foo and select the next tab (bar). - tabBar.deselectIfSelected(foo); - assertFalse('Foo must no longer be selected', foo.isSelected()); - assertTrue('Bar must be selected', bar.isSelected()); - assertEquals('Bar must be the selected tab', bar, - tabBar.getSelectedTab()); - } - - function testHandleTabSelect() { - var foo, bar, baz; - - // Create a tab bar with some tabs. - tabBar.addChild(foo = new goog.ui.Tab('foo')); - tabBar.addChild(bar = new goog.ui.Tab('bar')); - tabBar.addChild(baz = new goog.ui.Tab('baz')); - - assertNull('No tab must be selected', tabBar.getSelectedTab()); - - tabBar.handleTabSelect(new goog.events.Event( - goog.ui.Component.EventType.SELECT, bar)); - assertEquals('Bar must be the selected tab', bar, - tabBar.getSelectedTab()); - - tabBar.handleTabSelect(new goog.events.Event( - goog.ui.Component.EventType.SELECT, bar)); - assertEquals('Bar must remain selected tab', bar, - tabBar.getSelectedTab()); - - tabBar.handleTabSelect(new goog.events.Event( - goog.ui.Component.EventType.SELECT, foo)); - assertEquals('Foo must now be the selected tab', foo, - tabBar.getSelectedTab()); - } - - function testHandleTabUnselect() { - var foo, bar, baz; - - // Create a tab bar with some tabs. - tabBar.addChild(foo = new goog.ui.Tab('foo')); - tabBar.addChild(bar = new goog.ui.Tab('bar')); - tabBar.addChild(baz = new goog.ui.Tab('baz')); - - bar.setSelected(true); - assertEquals('Bar must be the selected tab', bar, - tabBar.getSelectedTab()); - - tabBar.handleTabUnselect(new goog.events.Event( - goog.ui.Component.EventType.UNSELECT, foo)); - assertEquals('Bar must remain the selected tab', bar, - tabBar.getSelectedTab()); - - tabBar.handleTabUnselect(new goog.events.Event( - goog.ui.Component.EventType.SELECT, bar)); - assertNull('No tab must be selected', tabBar.getSelectedTab()); - } - - function testHandleTabDisable() { - var foo, bar, baz; - - // Create a tab bar with some tabs. - tabBar.addChild(foo = new goog.ui.Tab('foo')); - tabBar.addChild(bar = new goog.ui.Tab('bar')); - tabBar.addChild(baz = new goog.ui.Tab('baz')); - - // Start with the middle tab selected. - bar.setSelected(true); - assertTrue('Bar must be selected', bar.isSelected()); - assertEquals('Bar must be the selected tab', bar, - tabBar.getSelectedTab()); - - // Should deselect bar and select the previous enabled, visible tab (foo). - bar.setEnabled(false); - assertFalse('Bar must no longer be selected', bar.isSelected()); - assertTrue('Foo must be selected', foo.isSelected()); - assertEquals('Foo must be the selected tab', foo, - tabBar.getSelectedTab()); - - // Should deselect foo and select the next enabled, visible tab (baz). - foo.setEnabled(false); - assertFalse('Foo must no longer be selected', foo.isSelected()); - assertTrue('Baz must be selected', baz.isSelected()); - assertEquals('Baz must be the selected tab', baz, - tabBar.getSelectedTab()); - - // Should deselect baz. Since there are no enabled, visible tabs left, - // the tab bar should have no selected tab. - baz.setEnabled(false); - assertFalse('Baz must no longer be selected', baz.isSelected()); - assertNull('No tab must be selected', tabBar.getSelectedTab()); - } - - function testHandleTabHide() { - var foo, bar, baz; - - // Create a tab bar with some tabs. - tabBar.addChild(foo = new goog.ui.Tab('foo')); - tabBar.addChild(bar = new goog.ui.Tab('bar')); - tabBar.addChild(baz = new goog.ui.Tab('baz')); - - // Start with the middle tab selected. - bar.setSelected(true); - assertTrue('Bar must be selected', bar.isSelected()); - assertEquals('Bar must be the selected tab', bar, - tabBar.getSelectedTab()); - - // Should deselect bar and select the previous enabled, visible tab (foo). - bar.setVisible(false); - assertFalse('Bar must no longer be selected', bar.isSelected()); - assertTrue('Foo must be selected', foo.isSelected()); - assertEquals('Foo must be the selected tab', foo, - tabBar.getSelectedTab()); - - // Should deselect foo and select the next enabled, visible tab (baz). - foo.setVisible(false); - assertFalse('Foo must no longer be selected', foo.isSelected()); - assertTrue('Baz must be selected', baz.isSelected()); - assertEquals('Baz must be the selected tab', baz, - tabBar.getSelectedTab()); - - // Should deselect baz. Since there are no enabled, visible tabs left, - // the tab bar should have no selected tab. - baz.setVisible(false); - assertFalse('Baz must no longer be selected', baz.isSelected()); - assertNull('No tab must be selected', tabBar.getSelectedTab()); - } - - function testHandleFocus() { - var foo, bar, baz; - - // Create a tab bar with some tabs. - tabBar.addChild(foo = new goog.ui.Tab('foo'), true); - tabBar.addChild(bar = new goog.ui.Tab('bar'), true); - tabBar.addChild(baz = new goog.ui.Tab('baz'), true); - - // Render the tab bar into the document, so highlight handling works as - // expected. - tabBar.render(sandbox); - - // Start with the middle tab selected. - bar.setSelected(true); - assertTrue('Bar must be selected', bar.isSelected()); - assertEquals('Bar must be the selected tab', bar, - tabBar.getSelectedTab()); - - assertNull('No tab must be highlighted', tabBar.getHighlighted()); - tabBar.handleFocus(new goog.events.Event(goog.events.EventType.FOCUS, - tabBar.getElement())); - assertTrue('Bar must be highlighted', bar.isHighlighted()); - assertEquals('Bar must be the highlighted tab', bar, - tabBar.getHighlighted()); - } - - function testHandleFocusWithoutSelectedTab() { - var foo, bar, baz; - - // Create a tab bar with some tabs. - tabBar.addChild(foo = new goog.ui.Tab('foo'), true); - tabBar.addChild(bar = new goog.ui.Tab('bar'), true); - tabBar.addChild(baz = new goog.ui.Tab('baz'), true); - - // Render the tab bar into the document, so highlight handling works as - // expected. - tabBar.render(sandbox); - - // Start with no tab selected. - assertNull('No tab must be selected', tabBar.getSelectedTab()); - - assertNull('No tab must be highlighted', tabBar.getHighlighted()); - tabBar.handleFocus(new goog.events.Event(goog.events.EventType.FOCUS, - tabBar.getElement())); - assertTrue('Foo must be highlighted', foo.isHighlighted()); - assertEquals('Foo must be the highlighted tab', foo, - tabBar.getHighlighted()); - } - - function testGetOrientationFromLocation() { - assertEquals(goog.ui.Container.Orientation.HORIZONTAL, - goog.ui.TabBar.getOrientationFromLocation( - goog.ui.TabBar.Location.TOP)); - assertEquals(goog.ui.Container.Orientation.HORIZONTAL, - goog.ui.TabBar.getOrientationFromLocation( - goog.ui.TabBar.Location.BOTTOM)); - assertEquals(goog.ui.Container.Orientation.VERTICAL, - goog.ui.TabBar.getOrientationFromLocation( - goog.ui.TabBar.Location.START)); - assertEquals(goog.ui.Container.Orientation.VERTICAL, - goog.ui.TabBar.getOrientationFromLocation( - goog.ui.TabBar.Location.END)); - } - - function testKeyboardNavigation() { - var foo, bar, baz; - - // Create a tab bar with some tabs. - tabBar.addChild(foo = new goog.ui.Tab('foo'), true); - tabBar.addChild(bar = new goog.ui.Tab('bar'), true); - tabBar.addChild(baz = new goog.ui.Tab('baz'), true); - tabBar.render(sandbox); - - // Highlight the selected tab (this happens automatically when the tab - // bar receives keyboard focus). - tabBar.setSelectedTabIndex(0); - tabBar.getSelectedTab().setHighlighted(true); - - // Count events dispatched by each tab. - var eventCount = { - 'foo': {'select': 0, 'unselect': 0}, - 'bar': {'select': 0, 'unselect': 0}, - 'baz': {'select': 0, 'unselect': 0} - }; - - function countEvent(e) { - var tabId = e.target.getContent(); - var type = e.type; - eventCount[tabId][type]++; - } - - function getEventCount(tabId, type) { - return eventCount[tabId][type]; - } - - // Listen for SELECT and UNSELECT events on the tab bar. - goog.events.listen(tabBar, [ - goog.ui.Component.EventType.SELECT, - goog.ui.Component.EventType.UNSELECT - ], countEvent); - - // Verify baseline assumptions. - assertTrue('Tab bar must auto-select tabs', - tabBar.isAutoSelectTabs()); - assertEquals('First tab must be selected', 0, - tabBar.getSelectedTabIndex()); - - // Simulate a right arrow key event. - var rightEvent = new FakeKeyEvent(goog.events.KeyCodes.RIGHT); - assertTrue('Key event must have beeen handled', - tabBar.handleKeyEvent(rightEvent)); - assertTrue('Key event propagation must have been stopped', - rightEvent.propagationStopped); - assertTrue('Default key event must have been prevented', - rightEvent.defaultPrevented); - assertEquals('Foo must have dispatched UNSELECT', 1, - getEventCount('foo', goog.ui.Component.EventType.UNSELECT)); - assertEquals('Bar must have dispatched SELECT', 1, - getEventCount('bar', goog.ui.Component.EventType.SELECT)); - assertEquals('Bar must have been selected', bar, tabBar.getSelectedTab()); - - // Simulate a left arrow key event. - var leftEvent = new FakeKeyEvent(goog.events.KeyCodes.LEFT); - assertTrue('Key event must have beeen handled', - tabBar.handleKeyEvent(leftEvent)); - assertTrue('Key event propagation must have been stopped', - leftEvent.propagationStopped); - assertTrue('Default key event must have been prevented', - leftEvent.defaultPrevented); - assertEquals('Bar must have dispatched UNSELECT', 1, - getEventCount('bar', goog.ui.Component.EventType.UNSELECT)); - assertEquals('Foo must have dispatched SELECT', 1, - getEventCount('foo', goog.ui.Component.EventType.SELECT)); - assertEquals('Foo must have been selected', foo, tabBar.getSelectedTab()); - - // Disable tab auto-selection. - tabBar.setAutoSelectTabs(false); - - // Simulate another left arrow key event. - var anotherLeftEvent = new FakeKeyEvent(goog.events.KeyCodes.LEFT); - assertTrue('Key event must have beeen handled', - tabBar.handleKeyEvent(anotherLeftEvent)); - assertTrue('Key event propagation must have been stopped', - anotherLeftEvent.propagationStopped); - assertTrue('Default key event must have been prevented', - anotherLeftEvent.defaultPrevented); - assertEquals('Foo must remain selected', foo, tabBar.getSelectedTab()); - assertEquals('Foo must not have dispatched another UNSELECT event', 1, - getEventCount('foo', goog.ui.Component.EventType.UNSELECT)); - assertEquals('Baz must not have dispatched a SELECT event', 0, - getEventCount('baz', goog.ui.Component.EventType.SELECT)); - assertFalse('Baz must not be selected', baz.isSelected()); - assertTrue('Baz must be highlighted', baz.isHighlighted()); - - // Simulate 'g' key event. - var gEvent = new FakeKeyEvent(goog.events.KeyCodes.G); - assertFalse('Key event must not have beeen handled', - tabBar.handleKeyEvent(gEvent)); - assertFalse('Key event propagation must not have been stopped', - gEvent.propagationStopped); - assertFalse('Default key event must not have been prevented', - gEvent.defaultPrevented); - assertEquals('Foo must remain selected', foo, tabBar.getSelectedTab()); - - // Clean up. - goog.events.unlisten(tabBar, [ - goog.ui.Component.EventType.SELECT, - goog.ui.Component.EventType.UNSELECT - ], countEvent); - } - - function testExitAndEnterDocument() { - var component = new goog.ui.Component(); - component.render(sandbox); - - var tab1 = new goog.ui.Tab('tab1'); - var tab2 = new goog.ui.Tab('tab2'); - var tab3 = new goog.ui.Tab('tab3'); - tabBar.addChild(tab1, true); - tabBar.addChild(tab2, true); - tabBar.addChild(tab3, true); - - component.addChild(tabBar, true); - tab2.setSelected(true); - assertEquals(tabBar.getSelectedTab(), tab2); - - component.removeChild(tabBar, true); - tab1.setSelected(true); - assertEquals(tabBar.getSelectedTab(), tab2); - - component.addChild(tabBar, true); - tab3.setSelected(true); - assertEquals(tabBar.getSelectedTab(), tab3); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabbarrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabbarrenderer.js.svn-base deleted file mode 100644 index b072a3d..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabbarrenderer.js.svn-base +++ /dev/null @@ -1,175 +0,0 @@ -// 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.TabBar}s. Based on the - * original {@code TabPane} code. - * - * @author attila@google.com (Attila Bodis) - * @author eae@google.com (Emil A. Eklund) - */ - -goog.provide('goog.ui.TabBarRenderer'); - -goog.require('goog.dom.a11y.Role'); -goog.require('goog.object'); -goog.require('goog.ui.ContainerRenderer'); - - - -/** - * Default renderer for {@link goog.ui.TabBar}s, based on the {@code TabPane} - * code. The tab bar's DOM structure is determined by its orientation and - * location relative to tab contents. For example, a horizontal tab bar - * located above tab contents looks like this: - * <pre> - * <div class="goog-tab-bar goog-tab-bar-horizontal goog-tab-bar-top"> - * ...(tabs here)... - * </div> - * </pre> - * @constructor - * @extends {goog.ui.ContainerRenderer} - */ -goog.ui.TabBarRenderer = function() { - goog.ui.ContainerRenderer.call(this); -}; -goog.inherits(goog.ui.TabBarRenderer, goog.ui.ContainerRenderer); -goog.addSingletonGetter(goog.ui.TabBarRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.TabBarRenderer.CSS_CLASS = goog.getCssName('goog-tab-bar'); - - -/** - * Returns the CSS class name to be applied to the root element of all tab bars - * rendered or decorated using this renderer. - * @return {string} Renderer-specific CSS class name. - * @override - */ -goog.ui.TabBarRenderer.prototype.getCssClass = function() { - return goog.ui.TabBarRenderer.CSS_CLASS; -}; - - -/** - * Returns the ARIA role to be applied to the tab bar element. - * See http://wiki/Main/ARIA for more info. - * @return {goog.dom.a11y.Role} ARIA role. - * @override - */ -goog.ui.TabBarRenderer.prototype.getAriaRole = function() { - return goog.dom.a11y.Role.TAB_LIST; -}; - - -/** - * Sets the tab bar's state based on the given CSS class name, encountered - * during decoration. Overrides the superclass implementation by recognizing - * class names representing tab bar orientation and location. - * @param {goog.ui.Container} tabBar Tab bar to configure. - * @param {string} className CSS class name. - * @param {string} baseClass Base class name used as the root of state-specific - * class names (typically the renderer's own class name). - * @protected - * @override - */ -goog.ui.TabBarRenderer.prototype.setStateFromClassName = function(tabBar, - className, baseClass) { - // Create the class-to-location lookup table on first access. - if (!this.locationByClass_) { - this.createLocationByClassMap_(); - } - - // If the class name corresponds to a location, update the tab bar's location; - // otherwise let the superclass handle it. - var location = this.locationByClass_[className]; - if (location) { - tabBar.setLocation(location); - } else { - goog.ui.TabBarRenderer.superClass_.setStateFromClassName.call(this, tabBar, - className, baseClass); - } -}; - - -/** - * Returns all CSS class names applicable to the tab bar, based on its state. - * Overrides the superclass implementation by appending the location-specific - * class name to the list. - * @param {goog.ui.Container} tabBar Tab bar whose CSS classes are to be - * returned. - * @return {Array.<string>} Array of CSS class names applicable to the tab bar. - * @override - */ -goog.ui.TabBarRenderer.prototype.getClassNames = function(tabBar) { - var classNames = goog.ui.TabBarRenderer.superClass_.getClassNames.call(this, - tabBar); - - // Create the location-to-class lookup table on first access. - if (!this.classByLocation_) { - this.createClassByLocationMap_(); - } - - // Apped the class name corresponding to the tab bar's location to the list. - classNames.push(this.classByLocation_[tabBar.getLocation()]); - return classNames; -}; - - -/** - * Creates the location-to-class lookup table. - * @private - */ -goog.ui.TabBarRenderer.prototype.createClassByLocationMap_ = function() { - var baseClass = this.getCssClass(); - - /** - * Map of locations to location-specific structural class names, - * precomputed and cached on first use to minimize object allocations - * and string concatenation. - * @type {Object} - * @private - */ - this.classByLocation_ = goog.object.create( - goog.ui.TabBar.Location.TOP, goog.getCssName(baseClass, 'top'), - goog.ui.TabBar.Location.BOTTOM, goog.getCssName(baseClass, 'bottom'), - goog.ui.TabBar.Location.START, goog.getCssName(baseClass, 'start'), - goog.ui.TabBar.Location.END, goog.getCssName(baseClass, 'end')); -}; - - -/** - * Creates the class-to-location lookup table, used during decoration. - * @private - */ -goog.ui.TabBarRenderer.prototype.createLocationByClassMap_ = function() { - // We need the classByLocation_ map so we can transpose it. - if (!this.classByLocation_) { - this.createClassByLocationMap_(); - } - - /** - * Map of location-specific structural class names to locations, used during - * element decoration. Precomputed and cached on first use to minimize object - * allocations and string concatenation. - * @type {Object} - * @private - */ - this.locationByClass_ = goog.object.transpose(this.classByLocation_); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabbarrenderer_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabbarrenderer_test.html.svn-base deleted file mode 100644 index 317f760..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabbarrenderer_test.html.svn-base +++ /dev/null @@ -1,138 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.TabBarRenderer</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.dom.a11y.Role'); - goog.require('goog.dom.classes'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Container.Orientation'); - goog.require('goog.ui.Tab'); - goog.require('goog.ui.TabBar'); - goog.require('goog.ui.TabBar.Location'); - goog.require('goog.ui.TabBarRenderer'); - goog.require('goog.testing.ui.rendererasserts'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var sandbox = goog.dom.getElement('sandbox'); - var renderer = goog.ui.TabBarRenderer.getInstance(); - var tabBar; - - function setUp() { - tabBar = new goog.ui.TabBar(); - } - - function tearDown() { - tabBar.dispose(); - goog.dom.removeChildren(sandbox); - } - - function testConstructor() { - assertNotNull('Renderer must not be null', renderer); - } - - function testGetCssClass() { - assertEquals('getCssClass() must return expected value', - goog.ui.TabBarRenderer.CSS_CLASS, renderer.getCssClass()); - } - - function testGetAriaRole() { - assertEquals('getAriaRole() must return expected value', - goog.dom.a11y.Role.TAB_LIST, renderer.getAriaRole()); - } - - function testCreateDom() { - var element = renderer.createDom(tabBar); - assertNotNull('Created element must not be null', element); - assertEquals('Created element must be a DIV', 'DIV', element.tagName); - assertSameElements('Created element must have expected class names', - ['goog-tab-bar', 'goog-tab-bar-horizontal', 'goog-tab-bar-top'], - goog.dom.classes.get(element)); - } - - function testDecorate() { - sandbox.innerHTML = '<div id="start" class="goog-tab-bar-start"></div>'; - var element = renderer.decorate(tabBar, goog.dom.getElement('start')); - assertNotNull('Decorated element must not be null', element); - assertEquals('Decorated element must be as expected', - goog.dom.getElement('start'), element); - // Due to a bug in ContainerRenderer, the "-vertical" class isn't applied. - // TODO(attila): Fix this! - assertSameElements('Decorated element must have expected class names', - ['goog-tab-bar', 'goog-tab-bar-start'], - goog.dom.classes.get(element)); - } - - function testSetStateFromClassName() { - renderer.setStateFromClassName(tabBar, 'goog-tab-bar-bottom', - renderer.getCssClass()); - assertEquals('Location must be BOTTOM', goog.ui.TabBar.Location.BOTTOM, - tabBar.getLocation()); - assertEquals('Orientation must be HORIZONTAL', - goog.ui.Container.Orientation.HORIZONTAL, tabBar.getOrientation()); - - renderer.setStateFromClassName(tabBar, 'goog-tab-bar-end', - renderer.getCssClass()); - assertEquals('Location must be END', goog.ui.TabBar.Location.END, - tabBar.getLocation()); - assertEquals('Orientation must be VERTICAL', - goog.ui.Container.Orientation.VERTICAL, tabBar.getOrientation()); - - renderer.setStateFromClassName(tabBar, 'goog-tab-bar-top', - renderer.getCssClass()); - assertEquals('Location must be TOP', goog.ui.TabBar.Location.TOP, - tabBar.getLocation()); - assertEquals('Orientation must be HORIZONTAL', - goog.ui.Container.Orientation.HORIZONTAL, tabBar.getOrientation()); - - renderer.setStateFromClassName(tabBar, 'goog-tab-bar-start', - renderer.getCssClass()); - assertEquals('Location must be START', goog.ui.TabBar.Location.START, - tabBar.getLocation()); - assertEquals('Orientation must be VERTICAL', - goog.ui.Container.Orientation.VERTICAL, tabBar.getOrientation()); - } - - function testGetClassNames() { - assertSameElements('Class names for TOP location must be as expected', - ['goog-tab-bar', 'goog-tab-bar-horizontal', 'goog-tab-bar-top'], - renderer.getClassNames(tabBar)); - - tabBar.setLocation(goog.ui.TabBar.Location.START); - assertSameElements('Class names for START location must be as expected', - ['goog-tab-bar', 'goog-tab-bar-vertical', 'goog-tab-bar-start'], - renderer.getClassNames(tabBar)); - - tabBar.setLocation(goog.ui.TabBar.Location.BOTTOM); - assertSameElements('Class names for BOTTOM location must be as expected', - ['goog-tab-bar', 'goog-tab-bar-horizontal', 'goog-tab-bar-bottom'], - renderer.getClassNames(tabBar)); - - tabBar.setLocation(goog.ui.TabBar.Location.END); - assertSameElements('Class names for END location must be as expected', - ['goog-tab-bar', 'goog-tab-bar-vertical', 'goog-tab-bar-end'], - renderer.getClassNames(tabBar)); - } - - function testDoesntCallGetCssClassInConstructor() { - goog.testing.ui.rendererasserts. - assertNoGetCssClassCallsInConstructor(goog.ui.TabBarRenderer); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tablesorter.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tablesorter.js.svn-base deleted file mode 100644 index 5d4777a..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tablesorter.js.svn-base +++ /dev/null @@ -1,303 +0,0 @@ -// 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); - - -/** - * 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.getElementsByTagName(goog.dom.TagName.TR)[0]; - 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[0].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); - }; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tablesorter_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tablesorter_test.html.svn-base deleted file mode 100644 index d688345..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tablesorter_test.html.svn-base +++ /dev/null @@ -1,128 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- Author: robbyw@google.com (Robby Walker) --> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.TableSorter</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.events'); - goog.require('goog.ui.TableSorter'); - </script> -</head> -<body> - <div id="content"> - <table id="sortable"> - <thead> - <tr><th>alpha</th><th>number</th><th>not sortable</th></tr> - </thead> - <tbody> - <tr><td>C</td><td>10</td><td></td></tr> - <tr><td>A</td><td>10</td><td></td></tr> - <tr><td>C</td><td>17</td><td></td></tr> - <tr><td>B</td><td>0</td><td></td></tr> - <tr><td>C</td><td>3</td><td></td></tr> - </tbody> - </table> - </div> - <script> - var oldHtml = goog.dom.getElement('content').innerHTML; - var alphaHeader, numberHeader, notSortableHeader, table, tableSorter; - - function setUp() { - goog.dom.getElement('content').innerHTML = oldHtml; - table = goog.dom.getElement('sortable'); - alphaHeader = table.getElementsByTagName('TH')[0]; - numberHeader = table.getElementsByTagName('TH')[1]; - notSortableHeader = table.getElementsByTagName('TH')[2]; - - tableSorter = new goog.ui.TableSorter(); - tableSorter.setSortFunction(0, goog.ui.TableSorter.alphaSort); - tableSorter.setSortFunction(2, goog.ui.TableSorter.noSort); - tableSorter.decorate(table); - } - - function tearDown() { - tableSorter.dispose(); - assertEquals(0, goog.events.getTotalListenerCount()); - table = null; - } - - function testConstructor() { - assertNotNull('Should have successful construction', tableSorter); - assertNotNull('Should be in document', tableSorter); - } - - function testForwardAlpha() { - goog.testing.events.fireClickEvent(alphaHeader); - assertOrder(['A', '10', 'B', '0', 'C', '10', 'C', '17', 'C', '3']); - assertTrue(goog.dom.classes.has(alphaHeader, 'goog-tablesorter-sorted')); - assertEquals(0, tableSorter.getSortColumn()); - assertFalse(tableSorter.isSortReversed()); - } - - function testBackwardAlpha() { - goog.testing.events.fireClickEvent(alphaHeader); - goog.testing.events.fireClickEvent(alphaHeader); - assertOrder(['C', '10', 'C', '17', 'C', '3', 'B', '0', 'A', '10']); - assertTrue(goog.dom.classes.has(alphaHeader, - 'goog-tablesorter-sorted-reverse')); - assertEquals(0, tableSorter.getSortColumn()); - assertTrue(tableSorter.isSortReversed()); - } - - function testForwardNumeric() { - goog.testing.events.fireClickEvent(numberHeader); - assertOrder(['B', '0', 'C', '3', 'C', '10', 'A', '10', 'C', '17']); - assertTrue(goog.dom.classes.has(numberHeader, 'goog-tablesorter-sorted')); - assertEquals(1, tableSorter.getSortColumn()); - assertFalse(tableSorter.isSortReversed()); - } - - function testBackwardNumeric() { - goog.testing.events.fireClickEvent(numberHeader); - goog.testing.events.fireClickEvent(numberHeader); - assertOrder(['C', '17', 'C', '10', 'A', '10', 'C', '3', 'B', '0']); - assertTrue(goog.dom.classes.has(numberHeader, - 'goog-tablesorter-sorted-reverse')); - assertEquals(1, tableSorter.getSortColumn()); - assertTrue(tableSorter.isSortReversed()); - } - - function testAlphaThenNumeric() { - testForwardAlpha(); - goog.testing.events.fireClickEvent(numberHeader); - assertOrder(['B', '0', 'C', '3', 'A', '10', 'C', '10', 'C', '17']); - assertFalse(goog.dom.classes.has(alphaHeader, 'goog-tablesorter-sorted')); - assertEquals(1, tableSorter.getSortColumn()); - assertFalse(tableSorter.isSortReversed()); - } - - function testNotSortableUnchanged() { - goog.testing.events.fireClickEvent(notSortableHeader); - assertEquals(0, goog.dom.classes.get(notSortableHeader).length); - assertEquals(-1, tableSorter.getSortColumn()); - } - - function assertOrder(arr) { - var actual = []; - goog.array.forEach(table.getElementsByTagName('TD'), function(td, idx) { - var txt = goog.dom.getTextContent(td); - if (txt) { - actual.push(txt); - } - }); - assertArrayEquals(arr, actual); - } - - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabpane.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabpane.js.svn-base deleted file mode 100644 index dac3fa0..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabpane.js.svn-base +++ /dev/null @@ -1,675 +0,0 @@ -// 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); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabpane_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabpane_test.html.svn-base deleted file mode 100644 index d4e6b20..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabpane_test.html.svn-base +++ /dev/null @@ -1,107 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests - goog.ui.TabPane</title> -<script src="../base.js"></script> -<script> - goog.require('goog.ui.TabPane'); - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.testing.jsunit'); -</script> -</head> -<body> - -<div id='testBody'></div> - -<script> - - var tabPane; - var page1; - var page2; - var page3; - - function setUp() { - goog.dom.getElement('testBody').innerHTML = - "<div id='tabpane'></div>" - "<div id='page1Content'>" - " Content for page 1" - "</div>" - "<div id='page2Content'>" - " Content for page 2" - "</div>" - "<div id='page3Content'>" - " Content for page 3" - "</div>"; - - tabPane = new goog.ui.TabPane(goog.dom.getElement('tabpane')); - page1 = new goog.ui.TabPane.TabPage(goog.dom.getElement('page1Content'), - 'page1'); - page2 = new goog.ui.TabPane.TabPage(goog.dom.getElement('page2Content'), - 'page2'); - page3 = new goog.ui.TabPane.TabPage(goog.dom.getElement('page3Content'), - 'page3'); - - tabPane.addPage(page1); - tabPane.addPage(page2); - tabPane.addPage(page3); - } - - function tearDown() { - tabPane.dispose(); - } - - function testAllPagesEnabledAndSelectable() { - tabPane.setSelectedIndex(0); - var selected = tabPane.getSelectedPage(); - assertEquals('page1 should be selected', 'page1', selected.getTitle()); - assertEquals('goog-tabpane-tab-selected', - selected.getTitleElement().className); - - tabPane.setSelectedIndex(1); - selected = tabPane.getSelectedPage(); - assertEquals('page2 should be selected', 'page2', selected.getTitle()); - assertEquals('goog-tabpane-tab-selected', - selected.getTitleElement().className); - - tabPane.setSelectedIndex(2); - selected = tabPane.getSelectedPage(); - assertEquals('page3 should be selected', 'page3', selected.getTitle()); - assertEquals('goog-tabpane-tab-selected', - selected.getTitleElement().className); - } - - function testDisabledPageIsNotSelectable() { - page2.setEnabled(false); - assertEquals('goog-tabpane-tab-disabled', - page2.getTitleElement().className); - - tabPane.setSelectedIndex(0); - var selected = tabPane.getSelectedPage(); - assertEquals('page1 should be selected', 'page1', selected.getTitle()); - assertEquals('goog-tabpane-tab-selected', - selected.getTitleElement().className); - - tabPane.setSelectedIndex(1); - selected = tabPane.getSelectedPage(); - assertEquals('page1 should remain selected, as page2 is disabled', - 'page1', selected.getTitle()); - assertEquals('goog-tabpane-tab-selected', - selected.getTitleElement().className); - - tabPane.setSelectedIndex(2); - selected = tabPane.getSelectedPage(); - assertEquals('page3 should be selected', 'page3', selected.getTitle()); - assertEquals('goog-tabpane-tab-selected', - selected.getTitleElement().className); - } -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabrenderer.js.svn-base deleted file mode 100644 index 2a3a831..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabrenderer.js.svn-base +++ /dev/null @@ -1,153 +0,0 @@ -// 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.Tab}s. Based on the - * original {@code TabPane} code. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.TabRenderer'); - -goog.require('goog.dom.a11y.Role'); -goog.require('goog.ui.Component.State'); -goog.require('goog.ui.ControlRenderer'); - - - -/** - * Default renderer for {@link goog.ui.Tab}s, based on the {@code TabPane} code. - * @constructor - * @extends {goog.ui.ControlRenderer} - */ -goog.ui.TabRenderer = function() { - goog.ui.ControlRenderer.call(this); -}; -goog.inherits(goog.ui.TabRenderer, goog.ui.ControlRenderer); -goog.addSingletonGetter(goog.ui.TabRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.TabRenderer.CSS_CLASS = goog.getCssName('goog-tab'); - - -/** - * Returns the CSS class name to be applied to the root element of all tabs - * rendered or decorated using this renderer. - * @return {string} Renderer-specific CSS class name. - * @override - */ -goog.ui.TabRenderer.prototype.getCssClass = function() { - return goog.ui.TabRenderer.CSS_CLASS; -}; - - -/** - * Returns the ARIA role to be applied to the tab element. - * See http://wiki/Main/ARIA for more info. - * @return {goog.dom.a11y.Role} ARIA role. - * @override - */ -goog.ui.TabRenderer.prototype.getAriaRole = function() { - return goog.dom.a11y.Role.TAB; -}; - - -/** - * Returns the tab's contents wrapped in a DIV, with the renderer's own CSS - * class and additional state-specific classes applied to it. Creates the - * following DOM structure: - * <pre> - * <div class="goog-tab" title="Title">Content</div> - * </pre> - * @param {goog.ui.Control} tab Tab to render. - * @return {Element} Root element for the tab. - * @override - */ -goog.ui.TabRenderer.prototype.createDom = function(tab) { - var element = goog.ui.TabRenderer.superClass_.createDom.call(this, tab); - - var tooltip = tab.getTooltip(); - if (tooltip) { - // Only update the element if the tab has a tooltip. - this.setTooltip(element, tooltip); - } - - return element; -}; - - -/** - * Decorates the element with the tab. Initializes the tab's ID, content, - * tooltip, and state based on the ID of the element, its title, child nodes, - * and CSS classes, respectively. Returns the element. - * @param {goog.ui.Control} tab Tab to decorate the element. - * @param {Element} element Element to decorate. - * @return {Element} Decorated element. - * @override - */ -goog.ui.TabRenderer.prototype.decorate = function(tab, element) { - element = goog.ui.TabRenderer.superClass_.decorate.call(this, tab, element); - - var tooltip = this.getTooltip(element); - if (tooltip) { - // Only update the tab if the element has a tooltip. - tab.setTooltipInternal(tooltip); - } - - // If the tab is selected and hosted in a tab bar, update the tab bar's - // selection model. - if (tab.isSelected()) { - var tabBar = tab.getParent(); - if (tabBar && goog.isFunction(tabBar.setSelectedTab)) { - // We need to temporarily deselect the tab, so the tab bar can re-select - // it and thereby correctly initialize its state. We use the protected - // setState() method to avoid dispatching useless events. - tab.setState(goog.ui.Component.State.SELECTED, false); - tabBar.setSelectedTab(tab); - } - } - - return element; -}; - - -/** - * Takes a tab's root element, and returns its tooltip text, or the empty - * string if the element has no tooltip. - * @param {Element} element The tab's root element. - * @return {string} The tooltip text (empty string if none). - */ -goog.ui.TabRenderer.prototype.getTooltip = function(element) { - return element.title || ''; -}; - - -/** - * Takes a tab's root element and a tooltip string, and updates the element - * with the new tooltip. If the new tooltip is null or undefined, sets the - * element's title to the empty string. - * @param {Element} element The tab's root element. - * @param {string|null|undefined} tooltip New tooltip text (if any). - */ -goog.ui.TabRenderer.prototype.setTooltip = function(element, tooltip) { - if (element) { - element.title = tooltip || ''; - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabrenderer_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabrenderer_test.html.svn-base deleted file mode 100644 index c98072e..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tabrenderer_test.html.svn-base +++ /dev/null @@ -1,133 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- -Author: attila@google.com (Attila Bodis) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.TabRenderer</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.dom.a11y.Role'); - goog.require('goog.dom.classes'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Tab'); - goog.require('goog.ui.TabRenderer'); - goog.require('goog.testing.ui.rendererasserts'); - </script> -</head> -<body> - <div id="sandbox"></div> - <script> - var sandbox = goog.dom.getElement('sandbox'); - var renderer = goog.ui.TabRenderer.getInstance(); - var tab; - - function setUp() { - tab = new goog.ui.Tab('Hello'); - } - - function tearDown() { - tab.dispose(); - goog.dom.removeChildren(sandbox); - } - - function testConstructor() { - assertNotNull('Renderer must not be null', renderer); - } - - function testGetCssClass() { - assertEquals('CSS class must have expected value', - goog.ui.TabRenderer.CSS_CLASS, renderer.getCssClass()); - } - - function testGetAriaRole() { - assertEquals('ARIA role must have expected value', - goog.dom.a11y.Role.TAB, renderer.getAriaRole()); - } - - function testCreateDom() { - var element = renderer.createDom(tab); - assertNotNull('Element must not be null', element); - assertHTMLEquals('DOM must have expected structure', - '<div class="goog-tab">Hello</div>', goog.dom.getOuterHtml(element)); - } - - function testCreateDomWithTooltip() { - tab.setTooltip('Hello, world!'); - var element = renderer.createDom(tab); - assertNotNull('Element must not be null', element); - assertEquals('Element must have expected tooltip', 'Hello, world!', - renderer.getTooltip(element)); - } - - function testDecorate() { - sandbox.innerHTML = - '<div id="foo">Foo</div>\n' + - '<div id="bar" title="Yes">Bar</div>'; - - var foo = renderer.decorate(tab, goog.dom.getElement('foo')); - assertNotNull('Decorated element must not be null', foo); - assertSameElements('Decorated element must have expected class', - ['goog-tab'], goog.dom.classes.get(foo)); - assertEquals('Decorated tab must have expected content', 'Foo', - tab.getContent().nodeValue); - assertUndefined('Decorated tab must not have tooltip', tab.getTooltip()); - assertEquals('Decorated element must not have title', '', - renderer.getTooltip(foo)); - - var bar = renderer.decorate(tab, goog.dom.getElement('bar')); - assertNotNull('Decorated element must not be null', bar); - assertSameElements('Decorated element must have expected class', - ['goog-tab'], goog.dom.classes.get(bar)); - assertEquals('Decorated tab must have expected content', 'Bar', - tab.getContent().nodeValue); - assertEquals('Decorated tab must have expected tooltip', 'Yes', - tab.getTooltip()); - assertEquals('Decorated element must have expected title', 'Yes', - renderer.getTooltip(bar)); - } - - function testGetTooltip() { - sandbox.innerHTML = - '<div id="foo">Foo</div>\n' + - '<div id="bar" title="">Bar</div>\n' + - '<div id="baz" title="BazTitle">Baz</div>'; - assertEquals('getTooltip() must return empty string for no title', '', - renderer.getTooltip(goog.dom.getElement('foo'))); - assertEquals('getTooltip() must return empty string for empty title', '', - renderer.getTooltip(goog.dom.getElement('bar'))); - assertEquals('Tooltip must have expected value', 'BazTitle', - renderer.getTooltip(goog.dom.getElement('baz'))); - } - - function testSetTooltip() { - sandbox.innerHTML = '<div id="foo">Foo</div>'; - var element = goog.dom.getElement('foo'); - - renderer.setTooltip(null, null); // Must not error. - - renderer.setTooltip(element, null); - assertEquals('Tooltip must be the empty string', '', element.title); - - renderer.setTooltip(element, ''); - assertEquals('Tooltip must be the empty string', '', element.title); - - renderer.setTooltip(element, 'Foo'); - assertEquals('Tooltip must have expected value', 'Foo', element.title); - } - - function testDoesntCallGetCssClassInConstructor() { - goog.testing.ui.rendererasserts. - assertNoGetCssClassCallsInConstructor(goog.ui.TabRenderer); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/textarea.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/textarea.js.svn-base deleted file mode 100644 index 3b9083a..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/textarea.js.svn-base +++ /dev/null @@ -1,573 +0,0 @@ -// 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 content-aware textarea control that grows and shrinks - * automatically. This implementation extends {@link goog.ui.Control}. - * This code is inspired by Dojo Dijit's Textarea implementation with - * modifications to support native (when available) textarea resizing and - * minHeight and maxHeight enforcement. - * - * @see ../demos/textarea.html - */ - -goog.provide('goog.ui.Textarea'); - -goog.require('goog.Timer'); -goog.require('goog.events.EventType'); -goog.require('goog.events.KeyCodes'); -goog.require('goog.style'); -goog.require('goog.ui.Control'); -goog.require('goog.ui.TextareaRenderer'); -goog.require('goog.userAgent'); -goog.require('goog.userAgent.product'); - - - -/** - * A textarea control to handle growing/shrinking with textarea.value. - * - * @param {string} content Text to set as the textarea's value. - * @param {goog.ui.TextareaRenderer=} opt_renderer Renderer used to render or - * decorate the textarea. Defaults to {@link goog.ui.TextareaRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for - * document interaction. - * @constructor - * @extends {goog.ui.Control} - */ -goog.ui.Textarea = function(content, opt_renderer, opt_domHelper) { - goog.ui.Control.call(this, content, opt_renderer || - goog.ui.TextareaRenderer.getInstance(), opt_domHelper); - - this.setHandleMouseEvents(false); - this.setAllowTextSelection(true); - if (!content) { - this.setContentInternal(''); - } -}; -goog.inherits(goog.ui.Textarea, goog.ui.Control); - - -/** - * Some UAs will shrink the textarea automatically, some won't. - * @type {boolean} - * @private - */ -goog.ui.Textarea.NEEDS_HELP_SHRINKING_ = goog.userAgent.GECKO || - goog.userAgent.WEBKIT; - - -/** - * True if the resizing function is executing, false otherwise. - * @type {boolean} - * @private - */ -goog.ui.Textarea.prototype.isResizing_ = false; - - -/** - * The height of the textarea as last measured. - * @type {number} - * @private - */ -goog.ui.Textarea.prototype.height_ = 0; - - -/** - * A maximum height for the textarea. When set to 0, the default, there is no - * enforcement of this value during resize. - * @type {number} - * @private - */ -goog.ui.Textarea.prototype.maxHeight_ = 0; - - -/** - * A minimum height for the textarea. When set to 0, the default, there is no - * enforcement of this value during resize. - * @type {number} - * @private - */ -goog.ui.Textarea.prototype.minHeight_ = 0; - - -/** - * Whether or not textarea rendering characteristics have been discovered. - * Specifically we determine, at runtime: - * If the padding and border box is included in offsetHeight. - * @see {goog.ui.Textarea.prototype.needsPaddingBorderFix_} - * If the padding and border box is included in scrollHeight. - * @see {goog.ui.Textarea.prototype.scrollHeightIncludesPadding_} and - * @see {goog.ui.Textarea.prototype.scrollHeightIncludesBorder_} - * TODO(user): See if we can determine goog.ui.Textarea.NEEDS_HELP_SHRINKING_. - * @type {boolean} - * @private - */ -goog.ui.Textarea.prototype.hasDiscoveredTextareaCharacteristics_ = false; - - -/** - * If a user agent doesn't correctly support the box-sizing:border-box CSS - * value then we'll need to adjust our height calculations. - * @see {goog.ui.Textarea.prototype.discoverTextareaCharacteristics_} - * @type {boolean} - * @private - */ -goog.ui.Textarea.prototype.needsPaddingBorderFix_ = false; - - -/** - * Whether or not scrollHeight of a textarea includes the padding box. - * @type {boolean} - * @private - */ -goog.ui.Textarea.prototype.scrollHeightIncludesPadding_ = false; - - -/** - * Whether or not scrollHeight of a textarea includes the border box. - * @type {boolean} - * @private - */ -goog.ui.Textarea.prototype.scrollHeightIncludesBorder_ = false; - - -/** - * For storing the padding box size during enterDocument, to prevent possible - * measurement differences that can happen after text zooming. - * Note: runtime padding changes will cause problems with this. - * @type {goog.math.Box} - * @private - */ -goog.ui.Textarea.prototype.paddingBox_; - - -/** - * For storing the border box size during enterDocument, to prevent possible - * measurement differences that can happen after text zooming. - * Note: runtime border width changes will cause problems with this. - * @type {goog.math.Box} - * @private - */ -goog.ui.Textarea.prototype.borderBox_; - - -/** - * @return {number} The padding plus the border box height. - * @private - */ -goog.ui.Textarea.prototype.getPaddingBorderBoxHeight_ = function() { - var paddingBorderBoxHeight = this.paddingBox_.top + this.paddingBox_.bottom + - this.borderBox_.top + this.borderBox_.bottom; - return paddingBorderBoxHeight; -}; - - -/** - * @return {number} The minHeight value. - */ -goog.ui.Textarea.prototype.getMinHeight = function() { - return this.minHeight_; -}; - - -/** - * @return {number} The minHeight value with a potential padding fix. - * @private - */ -goog.ui.Textarea.prototype.getMinHeight_ = function() { - var minHeight = this.minHeight_; - var textarea = this.getElement(); - if (minHeight && textarea && this.needsPaddingBorderFix_) { - minHeight -= this.getPaddingBorderBoxHeight_(); - } - return minHeight; -}; - - -/** - * Sets a minimum height for the textarea, and calls resize if rendered. - * @param {number} height New minHeight value. - */ -goog.ui.Textarea.prototype.setMinHeight = function(height) { - this.minHeight_ = height; - this.resize(); -}; - - -/** - * @return {number} The maxHeight value. - */ -goog.ui.Textarea.prototype.getMaxHeight = function() { - return this.maxHeight_; -}; - - -/** - * @return {number} The maxHeight value with a potential padding fix. - * @private - */ -goog.ui.Textarea.prototype.getMaxHeight_ = function() { - var maxHeight = this.maxHeight_; - var textarea = this.getElement(); - if (maxHeight && textarea && this.needsPaddingBorderFix_) { - maxHeight -= this.getPaddingBorderBoxHeight_(); - } - return maxHeight; -}; - - -/** - * Sets a minimum height for the textarea, and calls resize if rendered. - * @param {number} height New maxHeight value. - */ -goog.ui.Textarea.prototype.setMaxHeight = function(height) { - this.maxHeight_ = height; - this.resize(); -}; - - -/** - * Sets the textarea's value. - * @param {*} value The value property for the textarea, will be cast to a - * string by the browser when setting textarea.value. - */ -goog.ui.Textarea.prototype.setValue = function(value) { - this.setContent(String(value)); -}; - - -/** - * Gets the textarea's value. - * @return {string} value The value of the textarea. - */ -goog.ui.Textarea.prototype.getValue = function() { - return this.getElement().value; -}; - - -/** @override */ -goog.ui.Textarea.prototype.setContent = function(content) { - goog.ui.Textarea.superClass_.setContent.call(this, content); - this.resize(); -}; - - -/** @override **/ -goog.ui.Textarea.prototype.setEnabled = function(enable) { - goog.ui.Textarea.superClass_.setEnabled.call(this, enable); - this.getElement().disabled = !enable; -}; - - -/** - * Resizes the textarea vertically. - */ -goog.ui.Textarea.prototype.resize = function() { - if (this.getElement()) { - this.grow_(); - } -}; - - -/** @override **/ -goog.ui.Textarea.prototype.enterDocument = function() { - var textarea = this.getElement(); - - // Eliminates the vertical scrollbar and changes the box-sizing mode for the - // textarea to the border-box (aka quirksmode) paradigm. - goog.style.setStyle(textarea, { - 'overflowY': 'hidden', - 'overflowX': 'auto', - 'boxSizing': 'border-box', - 'MsBoxSizing': 'border-box', - 'WebkitBoxSizing': 'border-box', - 'MozBoxSizing': 'border-box'}); - - this.paddingBox_ = goog.style.getPaddingBox(textarea); - this.borderBox_ = goog.style.getBorderBox(textarea); - - this.getHandler(). - listen(textarea, goog.events.EventType.SCROLL, this.grow_). - listen(textarea, goog.events.EventType.FOCUS, this.grow_). - listen(textarea, goog.events.EventType.KEYUP, this.grow_). - listen(textarea, goog.events.EventType.MOUSEUP, this.mouseUpListener_); - - this.resize(); -}; - - -/** - * Gets the textarea's content height + padding height + border height. - * This is done by getting the scrollHeight and adjusting from there. - * In the end this result is what we want the new offsetHeight to equal. - * @return {number} The height of the textarea. - * @private - */ -goog.ui.Textarea.prototype.getHeight_ = function() { - this.discoverTextareaCharacteristics_(); - var textarea = this.getElement(); - // Accounts for a possible (though unlikely) horizontal scrollbar. - var height = this.getElement().scrollHeight + - this.getHorizontalScrollBarHeight_(); - if (this.needsPaddingBorderFix_) { - height -= this.getPaddingBorderBoxHeight_(); - } else { - if (!this.scrollHeightIncludesPadding_) { - var paddingBox = this.paddingBox_; - var paddingBoxHeight = paddingBox.top + paddingBox.bottom; - height += paddingBoxHeight; - } - if (!this.scrollHeightIncludesBorder_) { - var borderBox = goog.style.getBorderBox(textarea); - var borderBoxHeight = borderBox.top + borderBox.bottom; - height += borderBoxHeight; - } - } - return height; -}; - - -/** - * Sets the textarea's height. - * @param {number} height The height to set. - * @private - */ -goog.ui.Textarea.prototype.setHeight_ = function(height) { - if (this.height_ != height) { - this.height_ = height; - this.getElement().style.height = height + 'px'; - } -}; - - -/** - * Sets the textarea's rows attribute to be the number of newlines + 1. - * This is necessary when the textarea is hidden, in which case scrollHeight - * is not available. - * @private - */ -goog.ui.Textarea.prototype.setHeightToEstimate_ = function() { - var textarea = this.getElement(); - textarea.style.height = 'auto'; - var newlines = textarea.value.match(/\n/g) || []; - textarea.rows = newlines.length + 1; -}; - - -/** - * Gets the the height of (possibly present) horizontal scrollbar. - * @return {number} The height of the horizontal scrollbar. - * @private - */ -goog.ui.Textarea.prototype.getHorizontalScrollBarHeight_ = - function() { - var textarea = this.getElement(); - var height = textarea.offsetHeight - textarea.clientHeight; - if (!this.scrollHeightIncludesPadding_) { - var paddingBox = this.paddingBox_; - var paddingBoxHeight = paddingBox.top + paddingBox.bottom; - height -= paddingBoxHeight; - } - if (!this.scrollHeightIncludesBorder_) { - var borderBox = goog.style.getBorderBox(textarea); - var borderBoxHeight = borderBox.top + borderBox.bottom; - height -= borderBoxHeight; - } - // Prevent negative number results, which sometimes show up. - return height > 0 ? height : 0; -}; - - -/** - * In order to assess the correct height for a textarea, we need to know - * whether the scrollHeight (the full height of the text) property includes - * the values for padding and borders. We can also test whether the - * box-sizing: border-box setting is working and then tweak accordingly. - * Instead of hardcoding a list of currently known behaviors and testing - * for quirksmode, we do a runtime check out of the flow. The performance - * impact should be very small. - * @private - */ -goog.ui.Textarea.prototype.discoverTextareaCharacteristics_ = function() { - if (!this.hasDiscoveredTextareaCharacteristics_) { - var textarea = /** @type {!Element} */ (this.getElement().cloneNode(false)); - // We need to overwrite/write box model specific styles that might - // affect height. - goog.style.setStyle(textarea, { - 'position': 'absolute', - 'height': 'auto', - 'top': '-9999px', - 'margin': '0', - 'padding': '1px', - 'border': '1px solid #000', - 'overflow': 'hidden' - }); - goog.dom.appendChild(this.getDomHelper().getDocument().body, textarea); - var initialScrollHeight = textarea.scrollHeight; - - textarea.style.padding = '10px'; - var paddingScrollHeight = textarea.scrollHeight; - this.scrollHeightIncludesPadding_ = paddingScrollHeight > - initialScrollHeight; - - initialScrollHeight = paddingScrollHeight; - textarea.style.borderWidth = '10px'; - var borderScrollHeight = textarea.scrollHeight; - this.scrollHeightIncludesBorder_ = borderScrollHeight > initialScrollHeight; - - // Tests if border-box sizing is working or not. - textarea.style.height = '100px'; - var offsetHeightAtHeight100 = textarea.offsetHeight; - if (offsetHeightAtHeight100 != 100) { - this.needsPaddingBorderFix_ = true; - } - - goog.dom.removeNode(textarea); - this.hasDiscoveredTextareaCharacteristics_ = true; - } -}; - - -/** - * Resizes the textarea to grow/shrink to match its contents. - * @param {goog.events.Event=} opt_e The browser event. - * @private - */ -goog.ui.Textarea.prototype.grow_ = function(opt_e) { - if (this.isResizing_) { - return; - } - var shouldCallShrink = false; - this.isResizing_ = true; - var textarea = this.getElement(); - if (textarea.scrollHeight) { - var setMinHeight = false; - var setMaxHeight = false; - var newHeight = this.getHeight_(); - var currentHeight = textarea.offsetHeight; - var minHeight = this.getMinHeight_(); - var maxHeight = this.getMaxHeight_(); - if (minHeight && newHeight < minHeight) { - this.setHeight_(minHeight); - setMinHeight = true; - } else if (maxHeight && newHeight > maxHeight) { - this.setHeight_(maxHeight); - // If the content is greater than the height, we'll want the vertical - // scrollbar back. - textarea.style.overflowY = ''; - setMaxHeight = true; - } else if (currentHeight != newHeight) { - this.setHeight_(newHeight); - // Makes sure that height_ is at least set. - } else if (!this.height_) { - this.height_ = newHeight; - } - if (!setMinHeight && !setMaxHeight && - goog.ui.Textarea.NEEDS_HELP_SHRINKING_) { - shouldCallShrink = true; - } - } else { - this.setHeightToEstimate_(); - } - this.isResizing_ = false; - - if (shouldCallShrink) { - this.shrink_(); - } -}; - - -/** - * Resizes the texarea to shrink to fit its contents. The way this works is - * by increasing the padding of the textarea by 1px (it's important here that - * we're in box-sizing: border-box mode). If the size of the textarea grows, - * then the box is filled up to the padding box with text. - * If it doesn't change, then we can shrink. - * @private - */ -goog.ui.Textarea.prototype.shrink_ = function() { - var textarea = this.getElement(); - if (!this.isResizing_) { - this.isResizing_ = true; - var isEmpty = false; - if (!textarea.value) { - // Prevents height from becoming 0. - textarea.value = ' '; - isEmpty = true; - } - var scrollHeight = textarea.scrollHeight; - if (!scrollHeight) { - this.setHeightToEstimate_(); - } else { - var currentHeight = this.getHeight_(); - var minHeight = this.getMinHeight_(); - var maxHeight = this.getMaxHeight_(); - if (!(minHeight && currentHeight <= minHeight) && - !(maxHeight && currentHeight >= maxHeight)) { - // Nudge the padding by 1px. - var paddingBox = this.paddingBox_; - textarea.style.paddingBottom = paddingBox.bottom + 1 + 'px'; - var heightAfterNudge = this.getHeight_(); - // If the one px of padding had no effect, then we can shrink. - if (heightAfterNudge == currentHeight) { - textarea.style.paddingBottom = paddingBox.bottom + scrollHeight + - 'px'; - textarea.scrollTop = 0; - var shrinkToHeight = this.getHeight_() - scrollHeight; - if (shrinkToHeight >= minHeight) { - this.setHeight_(shrinkToHeight); - } else { - this.setHeight_(minHeight); - } - } - textarea.style.paddingBottom = paddingBox.bottom + 'px'; - } - } - if (isEmpty) { - textarea.value = ''; - } - this.isResizing_ = false; - } -}; - - -/** - * We use this listener to check if the textarea has been natively resized - * and if so we reset minHeight so that we don't ever shrink smaller than - * the user's manually set height. Note that we cannot check size on mousedown - * and then just compare here because we cannot capture mousedown on - * the textarea resizer, while mouseup fires reliably. - * @param {goog.events.BrowserEvent} e The mousedown event. - * @private - */ -goog.ui.Textarea.prototype.mouseUpListener_ = function(e) { - var textarea = this.getElement(); - var height = textarea.offsetHeight; - - // This solves for when the MSIE DropShadow filter is enabled, - // as it affects the offsetHeight value, even with MsBoxSizing:border-box. - if (textarea['filters'] && textarea['filters'].length) { - var dropShadow = - textarea['filters']['item']('DXImageTransform.Microsoft.DropShadow'); - if (dropShadow) { - height -= dropShadow['offX']; - } - } - - if (height != this.height_) { - this.minHeight_ = height; - this.height_ = height; - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/textarea_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/textarea_test.html.svn-base deleted file mode 100644 index 61bb14d..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/textarea_test.html.svn-base +++ /dev/null @@ -1,305 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2010 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.Textarea</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.dom.classes'); - goog.require('goog.debug.DivConsole'); - goog.require('goog.debug.LogManager'); - goog.require('goog.debug.Logger'); - goog.require('goog.events'); - goog.require('goog.testing.ExpectedFailures'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.object'); - goog.require('goog.ui.Control'); - goog.require('goog.ui.ControlRenderer'); - goog.require('goog.ui.Textarea'); - goog.require('goog.ui.TextareaRenderer'); - goog.require('goog.userAgent'); - goog.require('goog.userAgent.product'); - goog.require('goog.userAgent.product.isVersion'); - </script> - <style> - textarea { - height: 25px; /* Need to force an initial height < our minHeight. */ - width: 150px; - padding: 2px; - margin: 0; - border: 1px solid #000; - } - .drop-shadowed { - filter:progid:DXImageTransform.Microsoft.DropShadow(color='#e7e7e7', - offX='5',offY='5'); - box-shadow: 5px 5px 0 #e7e7e7; - -moz-box-shadow: 5px 5px 0 #e7e7e7; - -webkit-box-shadow: 5px 5px 0 #e7e7e7; - } - </style> -</head> -<body> - <h1>goog.ui.Textarea tests</h1> - <p>Here's a textarea defined in markup:</p> - <textarea id="demo-textarea">Foo</textarea> - <div id="sandbox"></div> - <script> - var sandbox = goog.dom.getElement('sandbox'); - var textarea; - var demoTextareaElement = goog.dom.getElement('demo-textarea'); - var expectedFailures = new goog.testing.ExpectedFailures(); - - function setUp() { - textarea = new goog.ui.Textarea(); - } - - function tearDown() { - expectedFailures.handleTearDown(); - textarea.dispose(); - goog.dom.removeChildren(sandbox); - } - - /** - * @return {boolean} Whether we're on Mac Safari 3.x. - */ - function isMacSafari3() { - return goog.userAgent.WEBKIT && goog.userAgent.MAC && - !goog.userAgent.isVersion('527'); - } - - /** - * @return {boolean} Whether we're on Linux Firefox 3.6.3. - */ - function isLinuxFirefox363() { - return goog.userAgent.product.FIREFOX && goog.userAgent.LINUX && - goog.userAgent.product.isVersion('3.6.3') && - !goog.userAgent.product.isVersion('3.6.4'); - } - - /** - * @return {boolean} Whether we're on Firefox 3.0. - */ - function isFirefox3() { - return goog.userAgent.GECKO && - !goog.userAgent.isVersion('1.9.1'); - } - - function testConstructor() { - assertNotNull('Textarea must not be null', textarea); - assertEquals('Renderer must default to expected value', - goog.ui.TextareaRenderer.getInstance(), textarea.getRenderer()); - - var fakeDomHelper = { - 'getDocument': function() { return true; } - }; - var testTextarea = new goog.ui.Textarea('Hello', - goog.ui.TextareaRenderer.getInstance(), fakeDomHelper); - assertEquals('Content must have expected content', 'Hello', - testTextarea.getContent()); - assertEquals('Renderer must have expected value', - goog.ui.TextareaRenderer.getInstance(), testTextarea.getRenderer()); - assertEquals('DOM helper must have expected value', fakeDomHelper, - testTextarea.getDomHelper()); - testTextarea.dispose(); - } - - function testConstructorWithDecorator() { - var decoratedTextarea = new goog.ui.Textarea(); - decoratedTextarea.decorate(demoTextareaElement); - assertEquals('Textarea should have current content after decoration', - 'Foo', decoratedTextarea.getContent()); - var initialHeight = decoratedTextarea.getHeight_(); - var initialOffsetHeight = decoratedTextarea.getElement().offsetHeight; - // focus() will trigger the grow/shrink flow. - decoratedTextarea.getElement().focus(); - assertEquals('Height should not have changed without content change', - initialHeight, decoratedTextarea.getHeight_()); - assertEquals('offsetHeight should not have changed without content ' + - 'change', initialOffsetHeight, - decoratedTextarea.getElement().offsetHeight); - decoratedTextarea.dispose(); - } - - function testGetSetContent() { - textarea.render(sandbox); - assertEquals('Textarea\'s content must default to an empty string', - '', textarea.getContent()); - textarea.setContent(17); - assertEquals('Textarea element must have expected content', '17', - textarea.getElement().value); - textarea.setContent('foo'); - assertEquals('Textarea element must have updated content', 'foo', - textarea.getElement().value); - } - - function testGetSetValue() { - textarea.render(sandbox); - assertEquals('Textarea\'s content must default to an empty string', - '', textarea.getValue()); - textarea.setValue(17); - assertEquals('Textarea element must have expected content', '17', - textarea.getValue()); - textarea.setValue('17'); - assertEquals('Textarea element must have expected content', '17', - textarea.getValue()); - } - - function testBasicTextareaBehavior() { - textarea.render(sandbox); - var el = textarea.getElement(); - var heightBefore = textarea.getHeight_(); - textarea.setContent('Lorem ipsum dolor sit amet, consectetuer ' + - 'elit. Aenean sollicitudin ultrices urna. Proin vehicula mauris ac ' + - 'est. Ut scelerisque, risus ut facilisis dictum, est massa lacinia ' + - 'lorem, in fermentum purus ligula quis nunc.'); - var heightAfter = textarea.getHeight_(); - assertTrue('With this much content, height should have grown.', - heightAfter > heightBefore); - - textarea.setContent(''); - heightAfter = textarea.getHeight_(); - assertTrue('Textarea should shrink with no content.', - heightAfter <= heightBefore); - } - - function testGetHorizontalScrollBarHeight() { - textarea.render(sandbox); - var textareaEl = textarea.getElement(); - var scrollHeightWithoutScrollBar = textareaEl.scrollHeight; - var withoutScrollBarHeight = - textarea.getHorizontalScrollBarHeight_(); - assertEquals('ScrollbarHeight should be 0 with no scrollbar.', - 0, withoutScrollBarHeight); - - textarea.setContent('Onereallylongstringoftextlongenoughto' + - 'justifyascrollbar'); - textarea.getElement().style.overflow = 'scroll'; - textarea.getElement().style.overflowX = 'scroll'; - var scrollBarHeight = - textarea.getHorizontalScrollBarHeight_(); - var scrollHeight = textareaEl.scrollHeight; - - // Opera & Safari3 include scrollbars in scrollHeight. - expectedFailures.expectFailureFor(goog.userAgent.OPERA || - isMacSafari3() || isFirefox3()); - try { - assertTrue('ScrollbarHeight should be something > 0 (it is ' + - scrollBarHeight + ') and isFirefox3():' + isFirefox3() + ', ' + - goog.userAgent.VERSION, scrollBarHeight > 0); - } catch (e) { - expectedFailures.handleException(e); - } - } - - function testMinHeight() { - textarea.render(sandbox); - textarea.setMinHeight(50); - assertEquals('offsetHeight should be 50 initially', 50, - textarea.getElement().offsetHeight); - textarea.setContent('Lorem ipsum dolor sit amet, consectetuer ' + - 'elit. Aenean sollicitudin ultrices urna. Proin vehicula mauris ac ' + - 'est. Ut scelerisque, risus ut facilisis dictum, est massa lacinia ' + - 'lorem, in fermentum purus ligula quis nunc.'); - assertTrue('getHeight_() should be > 50', - textarea.getHeight_() > 50); - - textarea.setContent(''); - assertEquals('With no content, offsetHeight should go back to 50, ' + - 'the minHeight.', 50, textarea.getElement().offsetHeight); - - expectedFailures.expectFailureFor(isMacSafari3()); - try { - textarea.setMinHeight(0); - assertTrue('After setting minHeight to 0, offsetHeight should ' + - 'now be < 50, but it is ' + textarea.getElement().offsetHeight, - textarea.getElement().offsetHeight < 50); - } catch (e) { - expectedFailures.handleException(e); - } - } - - function testMouseUpListener() { - textarea.render(sandbox); - textarea.setMinHeight(100); - textarea.setMaxHeight(200); - textarea.mouseUpListener_({}); - assertEquals('After a mouseup which is not a resize, minHeight should ' + - 'still be 100', 100, textarea.minHeight_); - - // We need to test how CSS drop shadows effect this too. - goog.dom.classes.add(textarea.getElement(), 'drop-shadowed'); - textarea.mouseUpListener_({}); - assertEquals('After a mouseup which is not a resize, minHeight should ' + - 'still be 100 even with a shadow', 100, textarea.minHeight_); - - } - - function testMaxHeight() { - textarea.render(sandbox); - textarea.setMaxHeight(50); - assertTrue('Initial offsetHeight should be less than 50', - textarea.getElement().offsetHeight < 50); - var newContent = 'Lorem ipsum dolor sit amet, consectetuer adipiscing ' + - 'elit. Aenean sollicitudin ultrices urna. Proin vehicula mauris ac ' + - 'est. Ut scelerisque, risus ut facilisis dictum, est massa lacinia ' + - 'lorem, in fermentum purus ligula quis nunc.' - textarea.setContent(newContent); - - assertTrue('With lots of content, getHeight_() should be > 50', - textarea.getHeight_() > 50); - assertEquals('Even with lots of content, offsetHeight should be 50 ' + - 'with maxHeight set', 50, textarea.getElement().offsetHeight); - textarea.setMaxHeight(0); - assertTrue('After setting maxHeight to 0, offsetHeight should now ' + - 'be > 50', textarea.getElement().offsetHeight > 50); - } - - function testMinAndMaxHeight() { - textarea.render(sandbox); - textarea.setMinHeight(50); - textarea.setMaxHeight(150); - assertEquals('offsetHeight should be 50 initially', 50, - textarea.getElement().offsetHeight); - - textarea.setContent('Lorem ipsum dolor sit amet, consectetuer ' + - 'elit. Aenean sollicitudin ultrices urna. Proin vehicula mauris ac ' + - 'est. Ut scelerisque, risus ut facilisis dictum, est massa lacinia ' + - 'lorem, in fermentum purus ligula quis nunc.'); - - - var height = textarea.getHeight_(); - // For some reason Mac Safari 3 has 136 and Linux FF 3.6.3 has 146 here. - expectedFailures.expectFailureFor(isMacSafari3() || isLinuxFirefox363()); - try { - assertTrue('With lots of content, getHeight_() should be > 150 ' + - '(it is ' + height + ')', height > 150); - assertEquals('Even with lots of content, offsetHeight should be 150 ' + - 'with maxHeight set', 150, - textarea.getElement().offsetHeight); - - textarea.setMaxHeight(0); - assertTrue('After setting maxHeight to 0, offsetHeight should now ' + - 'be > 150 (it is ' + textarea.getElement().offsetHeight + ')', - textarea.getElement().offsetHeight > 150); - - textarea.setContent(''); - textarea.setMinHeight(0); - assertTrue('After setting minHeight to 0, with no contents, ' + - 'offsetHeight should now be < 50', - textarea.getElement().offsetHeight < 50); - } catch (e) { - expectedFailures.handleException(e); - } - } - - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/textarearenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/textarearenderer.js.svn-base deleted file mode 100644 index 426c2e5..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/textarearenderer.js.svn-base +++ /dev/null @@ -1,167 +0,0 @@ -// 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 Native browser textarea renderer for {@link goog.ui.Textarea}s. - */ - -goog.provide('goog.ui.TextareaRenderer'); - -goog.require('goog.ui.Component.State'); -goog.require('goog.ui.ControlRenderer'); - - - -/** - * Renderer for {@link goog.ui.Textarea}s. Renders and decorates native HTML - * textarea elements. Since native HTML textareas have built-in support for - * many features, overrides many expensive (and redundant) superclass methods to - * be no-ops. - * @constructor - * @extends {goog.ui.ControlRenderer} - */ -goog.ui.TextareaRenderer = function() { - goog.ui.ControlRenderer.call(this); -}; -goog.inherits(goog.ui.TextareaRenderer, goog.ui.ControlRenderer); -goog.addSingletonGetter(goog.ui.TextareaRenderer); - - -/** - * Default CSS class to be applied to the root element of components rendered - * by this renderer. - * @type {string} - */ -goog.ui.TextareaRenderer.CSS_CLASS = goog.getCssName('goog-textarea'); - - -/** @override */ -goog.ui.TextareaRenderer.prototype.getAriaRole = function() { - // textareas don't need ARIA roles to be recognized by screen readers. - return undefined; -}; - - -/** @override */ -goog.ui.TextareaRenderer.prototype.decorate = function(control, element) { - goog.ui.TextareaRenderer.superClass_.decorate.call(this, control, - element); - control.setContent(element.value); - return element; -}; - - -/** - * Returns the textarea's contents wrapped in an HTML textarea element. Sets - * the textarea's disabled attribute as needed. - * @param {goog.ui.Control} textarea Textarea to render. - * @return {Element} Root element for the Textarea control (an HTML textarea - * element). - * @override - */ -goog.ui.TextareaRenderer.prototype.createDom = function(textarea) { - this.setUpTextarea_(textarea); - var element = textarea.getDomHelper().createDom('textarea', { - 'class': this.getClassNames(textarea).join(' '), - 'disabled': !textarea.isEnabled() - }, textarea.getContent() || ''); - return element; -}; - - -/** - * Overrides {@link goog.ui.TextareaRenderer#canDecorate} by returning true only - * if the element is an HTML textarea. - * @param {Element} element Element to decorate. - * @return {boolean} Whether the renderer can decorate the element. - * @override - */ -goog.ui.TextareaRenderer.prototype.canDecorate = function(element) { - return element.tagName == goog.dom.TagName.TEXTAREA; -}; - - -/** - * Textareas natively support right-to-left rendering. - * @override - */ -goog.ui.TextareaRenderer.prototype.setRightToLeft = goog.nullFunction; - - -/** - * Textareas are always focusable as long as they are enabled. - * @override - */ -goog.ui.TextareaRenderer.prototype.isFocusable = function(textarea) { - return textarea.isEnabled(); -}; - - -/** - * Textareas natively support keyboard focus. - * @override - */ -goog.ui.TextareaRenderer.prototype.setFocusable = goog.nullFunction; - - -/** - * Textareas also expose the DISABLED state in the HTML textarea's - * {@code disabled} attribute. - * @override - */ -goog.ui.TextareaRenderer.prototype.setState = function(textarea, state, - enable) { - goog.ui.TextareaRenderer.superClass_.setState.call(this, textarea, state, - enable); - var element = textarea.getElement(); - if (element && state == goog.ui.Component.State.DISABLED) { - element.disabled = enable; - } -}; - - -/** - * Textareas don't need ARIA states to support accessibility, so this is - * a no-op. - * @override - */ -goog.ui.TextareaRenderer.prototype.updateAriaState = goog.nullFunction; - - -/** - * Sets up the textarea control such that it doesn't waste time adding - * functionality that is already natively supported by browser - * textareas. - * @param {goog.ui.Control} textarea Textarea control to configure. - * @private - */ -goog.ui.TextareaRenderer.prototype.setUpTextarea_ = function(textarea) { - textarea.setHandleMouseEvents(false); - textarea.setAutoStates(goog.ui.Component.State.ALL, false); - textarea.setSupportedState(goog.ui.Component.State.FOCUSED, false); -}; - - -/** @override **/ -goog.ui.TextareaRenderer.prototype.setContent = function(element, value) { - if (element) { - element.value = value; - } -}; - - -/** @override **/ -goog.ui.TextareaRenderer.prototype.getCssClass = function() { - return goog.ui.TextareaRenderer.CSS_CLASS; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/togglebutton.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/togglebutton.js.svn-base deleted file mode 100644 index bde3134..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/togglebutton.js.svn-base +++ /dev/null @@ -1,59 +0,0 @@ -// 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.State'); -goog.require('goog.ui.ControlContent'); -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); -}); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbar.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbar.js.svn-base deleted file mode 100644 index 4938aa9..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbar.js.svn-base +++ /dev/null @@ -1,46 +0,0 @@ -// 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 toolbar class that hosts {@link goog.ui.Control}s such as - * buttons and menus, along with toolbar-specific renderers of those controls. - * - * @author attila@google.com (Attila Bodis) - * @see ../demos/toolbar.html - */ - -goog.provide('goog.ui.Toolbar'); - -goog.require('goog.ui.Container'); -goog.require('goog.ui.ToolbarRenderer'); - - - -/** - * A toolbar class, implemented as a {@link goog.ui.Container} that defaults to - * having a horizontal orientation and {@link goog.ui.ToolbarRenderer} as its - * renderer. - * @param {goog.ui.ToolbarRenderer=} opt_renderer Renderer used to render or - * decorate the toolbar; defaults to {@link goog.ui.ToolbarRenderer}. - * @param {?goog.ui.Container.Orientation=} opt_orientation Toolbar orientation; - * defaults to {@code HORIZONTAL}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Container} - */ -goog.ui.Toolbar = function(opt_renderer, opt_orientation, opt_domHelper) { - goog.ui.Container.call(this, opt_orientation, opt_renderer || - goog.ui.ToolbarRenderer.getInstance(), opt_domHelper); -}; -goog.inherits(goog.ui.Toolbar, goog.ui.Container); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarbutton.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarbutton.js.svn-base deleted file mode 100644 index 573a5a4..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarbutton.js.svn-base +++ /dev/null @@ -1,56 +0,0 @@ -// 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 button control. - * - * @author attila@google.com (Attila Bodis) - * @author ssaviano@google.com (Steven Saviano) - */ - -goog.provide('goog.ui.ToolbarButton'); - -goog.require('goog.ui.Button'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.ToolbarButtonRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * A 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.ButtonRenderer=} 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.Button} - */ -goog.ui.ToolbarButton = function(content, opt_renderer, opt_domHelper) { - goog.ui.Button.call(this, content, opt_renderer || - goog.ui.ToolbarButtonRenderer.getInstance(), opt_domHelper); -}; -goog.inherits(goog.ui.ToolbarButton, goog.ui.Button); - - -// Registers a decorator factory function for toolbar buttons. -goog.ui.registry.setDecoratorByClassName( - goog.ui.ToolbarButtonRenderer.CSS_CLASS, - function() { - return new goog.ui.ToolbarButton(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarbuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarbuttonrenderer.js.svn-base deleted file mode 100644 index 109cde4..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarbuttonrenderer.js.svn-base +++ /dev/null @@ -1,56 +0,0 @@ -// 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 toolbar buttons. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.ToolbarButtonRenderer'); - -goog.require('goog.ui.CustomButtonRenderer'); - - - -/** - * Toolbar-specific renderer for {@link goog.ui.Button}s, based on {@link - * goog.ui.CustomButtonRenderer}. - * @constructor - * @extends {goog.ui.CustomButtonRenderer} - */ -goog.ui.ToolbarButtonRenderer = function() { - goog.ui.CustomButtonRenderer.call(this); -}; -goog.inherits(goog.ui.ToolbarButtonRenderer, goog.ui.CustomButtonRenderer); -goog.addSingletonGetter(goog.ui.ToolbarButtonRenderer); - - -/** - * Default CSS class to be applied to the root element of buttons rendered - * by this renderer. - * @type {string} - */ -goog.ui.ToolbarButtonRenderer.CSS_CLASS = - goog.getCssName('goog-toolbar-button'); - - -/** - * Returns the CSS class to be applied to the root element of buttons rendered - * using this renderer. - * @return {string} Renderer-specific CSS class. - */ -goog.ui.ToolbarButtonRenderer.prototype.getCssClass = function() { - return goog.ui.ToolbarButtonRenderer.CSS_CLASS; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarcolormenubutton.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarcolormenubutton.js.svn-base deleted file mode 100644 index 7762fce..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarcolormenubutton.js.svn-base +++ /dev/null @@ -1,59 +0,0 @@ -// 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 color menu button control. - * - * @author attila@google.com (Attila Bodis) - * @author ssaviano@google.com (Steven Saviano) - */ - -goog.provide('goog.ui.ToolbarColorMenuButton'); - -goog.require('goog.ui.ColorMenuButton'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.ToolbarColorMenuButtonRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * A color menu 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.Menu=} opt_menu Menu to render under the button when clicked; - * should contain at least one {@link goog.ui.ColorPalette} if present. - * @param {goog.ui.ColorMenuButtonRenderer=} opt_renderer Optional - * renderer used to render or decorate the button; defaults to - * {@link goog.ui.ToolbarColorMenuButtonRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for - * document interaction. - * @constructor - * @extends {goog.ui.ColorMenuButton} - */ -goog.ui.ToolbarColorMenuButton = function( - content, opt_menu, opt_renderer, opt_domHelper) { - goog.ui.ColorMenuButton.call(this, content, opt_menu, opt_renderer || - goog.ui.ToolbarColorMenuButtonRenderer.getInstance(), opt_domHelper); -}; -goog.inherits(goog.ui.ToolbarColorMenuButton, goog.ui.ColorMenuButton); - - -// Registers a decorator factory function for toolbar color menu buttons. -goog.ui.registry.setDecoratorByClassName( - goog.getCssName('goog-toolbar-color-menu-button'), - function() { - return new goog.ui.ToolbarColorMenuButton(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarcolormenubuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarcolormenubuttonrenderer.js.svn-base deleted file mode 100644 index 376df30..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarcolormenubuttonrenderer.js.svn-base +++ /dev/null @@ -1,96 +0,0 @@ -// 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 - */ -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. - */ -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.ColorMenuButton} button Button whose DOM is to be - * initialized as it enters the document. - */ -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); -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarcolormenubuttonrenderer_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarcolormenubuttonrenderer_test.html.svn-base deleted file mode 100644 index 395a866..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarcolormenubuttonrenderer_test.html.svn-base +++ /dev/null @@ -1,66 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2009 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- - - @author nicksantos@google.com (Nick Santos) ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> -<title>Closure Unit Tests for ToolbarColorMenuButtonRenderer</title> -<script src="../base.js"></script> -<script> - goog.require('goog.dom'); - goog.require('goog.testing.jsunit'); - goog.require('goog.testing.ui.RendererHarness'); - goog.require('goog.ui.ToolbarColorMenuButton'); - goog.require('goog.ui.ToolbarColorMenuButtonRenderer'); - goog.require('goog.testing.ui.rendererasserts'); -</script> -</head> -<body> - -<div id='root'> - <!-- A parent to attach rendered buttons to --> - <div id='parent'></div> - - <!-- A button to decorate --> - <div id='decoratedButton'><div>Foo</div></div> -</div> - -<script> - -var harness; - -function setUp() { - harness = new goog.testing.ui.RendererHarness( - goog.ui.ToolbarColorMenuButtonRenderer.getInstance(), - goog.dom.getElement('parent'), - goog.dom.getElement('decoratedButton')); -} - -function tearDown() { - harness.dispose(); -} - -function testEquality() { - harness.attachControlAndRender( - new goog.ui.ToolbarColorMenuButton('Foo')); - harness.attachControlAndDecorate( - new goog.ui.ToolbarColorMenuButton()); - harness.assertDomMatches(); -} - -function testDoesntCallGetCssClassInConstructor() { - goog.testing.ui.rendererasserts. - assertNoGetCssClassCallsInConstructor( - goog.ui.ToolbarColorMenuButtonRenderer); -} -</script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarmenubutton.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarmenubutton.js.svn-base deleted file mode 100644 index 41b1e06..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarmenubutton.js.svn-base +++ /dev/null @@ -1,58 +0,0 @@ -// 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 menu button control. - * - * @author attila@google.com (Attila Bodis) - * @author ssaviano@google.com (Steven Saviano) - */ - -goog.provide('goog.ui.ToolbarMenuButton'); - -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.MenuButton'); -goog.require('goog.ui.ToolbarMenuButtonRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * A menu 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.Menu=} opt_menu Menu to render under the button when clicked. - * @param {goog.ui.ButtonRenderer=} opt_renderer Optional renderer used to - * render or decorate the button; defaults to - * {@link goog.ui.ToolbarMenuButtonRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for - * document interaction. - * @constructor - * @extends {goog.ui.MenuButton} - */ -goog.ui.ToolbarMenuButton = function( - content, opt_menu, opt_renderer, opt_domHelper) { - goog.ui.MenuButton.call(this, content, opt_menu, opt_renderer || - goog.ui.ToolbarMenuButtonRenderer.getInstance(), opt_domHelper); -}; -goog.inherits(goog.ui.ToolbarMenuButton, goog.ui.MenuButton); - - -// Registers a decorator factory function for toolbar menu buttons. -goog.ui.registry.setDecoratorByClassName( - goog.ui.ToolbarMenuButtonRenderer.CSS_CLASS, - function() { - return new goog.ui.ToolbarMenuButton(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarmenubuttonrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarmenubuttonrenderer.js.svn-base deleted file mode 100644 index 7af8d7a..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarmenubuttonrenderer.js.svn-base +++ /dev/null @@ -1,56 +0,0 @@ -// 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 menu button renderer. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.ToolbarMenuButtonRenderer'); - -goog.require('goog.ui.MenuButtonRenderer'); - - - -/** - * Toolbar-specific renderer for {@link goog.ui.MenuButton}s, based on {@link - * goog.ui.MenuButtonRenderer}. - * @constructor - * @extends {goog.ui.MenuButtonRenderer} - */ -goog.ui.ToolbarMenuButtonRenderer = function() { - goog.ui.MenuButtonRenderer.call(this); -}; -goog.inherits(goog.ui.ToolbarMenuButtonRenderer, goog.ui.MenuButtonRenderer); -goog.addSingletonGetter(goog.ui.ToolbarMenuButtonRenderer); - - -/** - * Default CSS class to be applied to the root element of menu buttons rendered - * by this renderer. - * @type {string} - */ -goog.ui.ToolbarMenuButtonRenderer.CSS_CLASS = - goog.getCssName('goog-toolbar-menu-button'); - - -/** - * Returns the CSS class to be applied to the root element of menu buttons - * rendered using this renderer. - * @return {string} Renderer-specific CSS class. - */ -goog.ui.ToolbarMenuButtonRenderer.prototype.getCssClass = function() { - return goog.ui.ToolbarMenuButtonRenderer.CSS_CLASS; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarrenderer.js.svn-base deleted file mode 100644 index 3592b46..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarrenderer.js.svn-base +++ /dev/null @@ -1,96 +0,0 @@ -// 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.Toolbar}s. - * - * @author attila@google.com (Attila Bodis) - */ - -goog.provide('goog.ui.ToolbarRenderer'); - -goog.require('goog.dom.a11y.Role'); -goog.require('goog.ui.Container.Orientation'); -goog.require('goog.ui.ContainerRenderer'); -goog.require('goog.ui.Separator'); -goog.require('goog.ui.ToolbarSeparatorRenderer'); - - - -/** - * Default renderer for {@link goog.ui.Toolbar}s, based on {@link - * goog.ui.ContainerRenderer}. - * @constructor - * @extends {goog.ui.ContainerRenderer} - */ -goog.ui.ToolbarRenderer = function() { - goog.ui.ContainerRenderer.call(this); -}; -goog.inherits(goog.ui.ToolbarRenderer, goog.ui.ContainerRenderer); -goog.addSingletonGetter(goog.ui.ToolbarRenderer); - - -/** - * Default CSS class to be applied to the root element of toolbars rendered - * by this renderer. - * @type {string} - */ -goog.ui.ToolbarRenderer.CSS_CLASS = goog.getCssName('goog-toolbar'); - - -/** - * Returns the ARIA role to be applied to toolbar/menubar. - * @return {string} ARIA role. - * @override - */ -goog.ui.ToolbarRenderer.prototype.getAriaRole = function() { - return goog.dom.a11y.Role.TOOLBAR; -}; - - -/** - * Inspects the element, and creates an instance of {@link goog.ui.Control} or - * an appropriate subclass best suited to decorate it. Overrides the superclass - * implementation by recognizing HR elements as separators. - * @param {Element} element Element to decorate. - * @return {goog.ui.Control?} A new control suitable to decorate the element - * (null if none). - */ -goog.ui.ToolbarRenderer.prototype.getDecoratorForChild = function(element) { - return element.tagName == 'HR' ? - new goog.ui.Separator(goog.ui.ToolbarSeparatorRenderer.getInstance()) : - goog.ui.ToolbarRenderer.superClass_.getDecoratorForChild.call(this, - element); -}; - - -/** - * Returns the CSS class to be applied to the root element of containers - * rendered using this renderer. - * @return {string} Renderer-specific CSS class. - */ -goog.ui.ToolbarRenderer.prototype.getCssClass = function() { - return goog.ui.ToolbarRenderer.CSS_CLASS; -}; - - -/** - * Returns the default orientation of containers rendered or decorated by this - * renderer. This implementation returns {@code HORIZONTAL}. - * @return {goog.ui.Container.Orientation} Default orientation for containers - * created or decorated by this renderer. - */ -goog.ui.ToolbarRenderer.prototype.getDefaultOrientation = function() { - return goog.ui.Container.Orientation.HORIZONTAL; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarselect.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarselect.js.svn-base deleted file mode 100644 index fa205a6..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarselect.js.svn-base +++ /dev/null @@ -1,57 +0,0 @@ -// 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 select control. - * - * @author attila@google.com (Attila Bodis) - * @author ssaviano@google.com (Steven Saviano) - */ - -goog.provide('goog.ui.ToolbarSelect'); - -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.Select'); -goog.require('goog.ui.ToolbarMenuButtonRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * A select control for a toolbar. - * - * @param {goog.ui.ControlContent} caption Default caption or existing DOM - * structure to display as the button's caption when nothing is selected. - * @param {goog.ui.Menu=} opt_menu Menu containing selection options. - * @param {goog.ui.MenuButtonRenderer=} opt_renderer Renderer used to - * render or decorate the control; defaults to - * {@link goog.ui.ToolbarMenuButtonRenderer}. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for - * document interaction. - * @constructor - * @extends {goog.ui.Select} - */ -goog.ui.ToolbarSelect = function( - caption, opt_menu, opt_renderer, opt_domHelper) { - goog.ui.Select.call(this, caption, opt_menu, opt_renderer || - goog.ui.ToolbarMenuButtonRenderer.getInstance(), opt_domHelper); -}; -goog.inherits(goog.ui.ToolbarSelect, goog.ui.Select); - - -// Registers a decorator factory function for select controls used in toolbars. -goog.ui.registry.setDecoratorByClassName(goog.getCssName('goog-toolbar-select'), - function() { - return new goog.ui.ToolbarSelect(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarseparator.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarseparator.js.svn-base deleted file mode 100644 index f32b536..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarseparator.js.svn-base +++ /dev/null @@ -1,53 +0,0 @@ -// 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(); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarseparatorrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarseparatorrenderer.js.svn-base deleted file mode 100644 index 041a33b..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbarseparatorrenderer.js.svn-base +++ /dev/null @@ -1,88 +0,0 @@ -// 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.Separator} separator Separator to render. - * @return {Element} Root element for the separator. - */ -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.Separator} separator Separator to decorate the element. - * @param {Element} element Element to decorate. - * @return {Element} Decorated element. - */ -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. - */ -goog.ui.ToolbarSeparatorRenderer.prototype.getCssClass = function() { - return goog.ui.ToolbarSeparatorRenderer.CSS_CLASS; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbartogglebutton.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbartogglebutton.js.svn-base deleted file mode 100644 index a055fa3..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/toolbartogglebutton.js.svn-base +++ /dev/null @@ -1,55 +0,0 @@ -// 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); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tooltip.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tooltip.js.svn-base deleted file mode 100644 index d6a147d..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tooltip.js.svn-base +++ /dev/null @@ -1,995 +0,0 @@ -// 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 Tooltip widget implementation. - * - * @author eae@google.com (Emil A Eklund) - * @see ../demos/tooltip.html - */ - -goog.provide('goog.ui.Tooltip'); -goog.provide('goog.ui.Tooltip.CursorTooltipPosition'); -goog.provide('goog.ui.Tooltip.ElementTooltipPosition'); -goog.provide('goog.ui.Tooltip.State'); - -goog.require('goog.Timer'); -goog.require('goog.array'); -goog.require('goog.dom'); -goog.require('goog.events'); -goog.require('goog.events.EventType'); -goog.require('goog.math.Box'); -goog.require('goog.math.Coordinate'); -goog.require('goog.positioning'); -goog.require('goog.positioning.AnchoredPosition'); -goog.require('goog.positioning.Corner'); -goog.require('goog.positioning.Overflow'); -goog.require('goog.positioning.OverflowStatus'); -goog.require('goog.positioning.ViewportPosition'); -goog.require('goog.structs.Set'); -goog.require('goog.style'); -goog.require('goog.ui.Popup'); -goog.require('goog.ui.PopupBase'); - - - -/** - * Tooltip widget. Can be attached to one or more elements and is shown, with a - * slight delay, when the the cursor is over the element or the element gains - * focus. - * - * @param {Element|string=} opt_el Element to display tooltip for, either - * element reference or string id. - * @param {?string=} opt_str Text message to display in tooltip. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. - * @constructor - * @extends {goog.ui.Popup} - */ -goog.ui.Tooltip = function(opt_el, opt_str, opt_domHelper) { - /** - * Dom Helper - * @type {goog.dom.DomHelper} - * @private - */ - this.dom_ = opt_domHelper || (opt_el ? - goog.dom.getDomHelper(goog.dom.getElement(opt_el)) : - goog.dom.getDomHelper()); - - goog.ui.Popup.call(this, this.dom_.createDom( - 'div', {'style': 'position:absolute;display:none;'})); - - /** - * Cursor position relative to the page. - * @type {!goog.math.Coordinate} - * @protected - */ - this.cursorPosition = new goog.math.Coordinate(1, 1); - - /** - * Elements this widget is attached to. - * @type {goog.structs.Set} - * @private - */ - this.elements_ = new goog.structs.Set(); - - // Attach to element, if specified - if (opt_el) { - this.attach(opt_el); - } - - // Set message, if specified. - if (opt_str != null) { - this.setText(opt_str); - } -}; -goog.inherits(goog.ui.Tooltip, goog.ui.Popup); - - -/** - * List of active (open) tooltip widgets. Used to prevent multiple tooltips - * from appearing at once. - * - * @type {!Array.<goog.ui.Tooltip>} - * @private - */ -goog.ui.Tooltip.activeInstances_ = []; - - -/** - * Active element reference. Used by the delayed show functionality to keep - * track of the element the mouse is over or the element with focus. - * @type {Element} - * @private - */ -goog.ui.Tooltip.prototype.activeEl_ = null; - - -/** - * CSS class name for tooltip. - * - * @type {string} - */ -goog.ui.Tooltip.prototype.className = goog.getCssName('goog-tooltip'); - - -/** - * Delay in milliseconds since the last mouseover or mousemove before the - * tooltip is displayed for an element. - * - * @type {number} - * @private - */ -goog.ui.Tooltip.prototype.showDelayMs_ = 500; - - -/** - * Timer for when to show. - * - * @type {number|undefined} - * @protected - */ -goog.ui.Tooltip.prototype.showTimer; - - -/** - * Delay in milliseconds before tooltips are hidden. - * - * @type {number} - * @private - */ -goog.ui.Tooltip.prototype.hideDelayMs_ = 0; - - -/** - * Timer for when to hide. - * - * @type {number|undefined} - * @protected - */ -goog.ui.Tooltip.prototype.hideTimer; - - -/** - * Element that triggered the tooltip. Note that if a second element triggers - * this tooltip, anchor becomes that second element, even if its show is - * cancelled and the original tooltip survives. - * - * @type {Element|undefined} - * @protected - */ -goog.ui.Tooltip.prototype.anchor; - - -/** - * Possible states for the tooltip to be in. - * @enum {number} - */ -goog.ui.Tooltip.State = { - INACTIVE: 0, - WAITING_TO_SHOW: 1, - SHOWING: 2, - WAITING_TO_HIDE: 3, - UPDATING: 4 // waiting to show new hovercard while old one still showing. -}; - - -/** - * Popup activation types. Used to select a positioning strategy. - * @enum {number} - */ -goog.ui.Tooltip.Activation = { - CURSOR: 0, - FOCUS: 1 -}; - - -/** - * Whether the anchor has seen the cursor move or has received focus since the - * tooltip was last shown. Used to ignore mouse over events triggered by view - * changes and UI updates. - * @type {boolean|undefined} - * @private - */ -goog.ui.Tooltip.prototype.seenInteraction_; - - -/** - * Whether the cursor must have moved before the tooltip will be shown. - * @type {boolean|undefined} - * @private - */ -goog.ui.Tooltip.prototype.requireInteraction_; - - -/** - * If this tooltip's element contains another tooltip that becomes active, this - * property identifies that tooltip so that we can check if this tooltip should - * not be hidden because the nested tooltip is active. - * @type {goog.ui.Tooltip} - * @private - */ -goog.ui.Tooltip.prototype.childTooltip_; - - -/** - * If this tooltip is inside another tooltip's element, then it may have - * prevented that tooltip from hiding. When this tooltip hides, we'll need - * to check if the parent should be hidden as well. - * @type {goog.ui.Tooltip} - * @private - */ -goog.ui.Tooltip.prototype.parentTooltip_; - - -/** - * Returns the dom helper that is being used on this component. - * @return {goog.dom.DomHelper} The dom helper used on this component. - */ -goog.ui.Tooltip.prototype.getDomHelper = function() { - return this.dom_; -}; - - -/** - * @return {goog.ui.Tooltip} Active tooltip in a child element, or null if none. - * @protected - */ -goog.ui.Tooltip.prototype.getChildTooltip = function() { - return this.childTooltip_; -}; - - -/** - * Attach to element. Tooltip will be displayed when the cursor is over the - * element or when the element has been active for a few milliseconds. - * - * @param {Element|string} el Element to display tooltip for, either element - * reference or string id. - */ -goog.ui.Tooltip.prototype.attach = function(el) { - el = goog.dom.getElement(el); - - this.elements_.add(el); - goog.events.listen(el, goog.events.EventType.MOUSEOVER, - this.handleMouseOver, false, this); - goog.events.listen(el, goog.events.EventType.MOUSEOUT, - this.handleMouseOutAndBlur, false, this); - goog.events.listen(el, goog.events.EventType.MOUSEMOVE, - this.handleMouseMove, false, this); - goog.events.listen(el, goog.events.EventType.FOCUS, - this.handleFocus, false, this); - goog.events.listen(el, goog.events.EventType.BLUR, - this.handleMouseOutAndBlur, false, this); -}; - - -/** - * Detach from element(s). - * - * @param {Element|string=} opt_el Element to detach from, either element - * reference or string id. If no element is - * specified all are detached. - */ -goog.ui.Tooltip.prototype.detach = function(opt_el) { - if (opt_el) { - var el = goog.dom.getElement(opt_el); - this.detachElement_(el); - this.elements_.remove(el); - } else { - var a = this.elements_.getValues(); - for (var el, i = 0; el = a[i]; i++) { - this.detachElement_(el); - } - this.elements_.clear(); - } -}; - - -/** - * Detach from element. - * - * @param {Element} el Element to detach from. - * @private - */ -goog.ui.Tooltip.prototype.detachElement_ = function(el) { - goog.events.unlisten(el, goog.events.EventType.MOUSEOVER, - this.handleMouseOver, false, this); - goog.events.unlisten(el, goog.events.EventType.MOUSEOUT, - this.handleMouseOutAndBlur, false, this); - goog.events.unlisten(el, goog.events.EventType.MOUSEMOVE, - this.handleMouseMove, false, this); - goog.events.unlisten(el, goog.events.EventType.FOCUS, - this.handleFocus, false, this); - goog.events.unlisten(el, goog.events.EventType.BLUR, - this.handleMouseOutAndBlur, false, this); -}; - - -/** - * Sets delay in milliseconds before tooltip is displayed for an element. - * - * @param {number} delay The delay in milliseconds. - */ -goog.ui.Tooltip.prototype.setShowDelayMs = function(delay) { - this.showDelayMs_ = delay; -}; - - -/** - * @return {number} The delay in milliseconds before tooltip is displayed for an - * element. - */ -goog.ui.Tooltip.prototype.getShowDelayMs = function() { - return this.showDelayMs_; -}; - - -/** - * Sets delay in milliseconds before tooltip is hidden once the cursor leavs - * the element. - * - * @param {number} delay The delay in milliseconds. - */ -goog.ui.Tooltip.prototype.setHideDelayMs = function(delay) { - this.hideDelayMs_ = delay; -}; - - -/** - * @return {number} The delay in milliseconds before tooltip is hidden once the - * cursor leaves the element. - */ -goog.ui.Tooltip.prototype.getHideDelayMs = function() { - return this.hideDelayMs_; -}; - - -/** - * Sets tooltip message as plain text. - * - * @param {string} str Text message to display in tooltip. - */ -goog.ui.Tooltip.prototype.setText = function(str) { - goog.dom.setTextContent(this.getElement(), str); -}; - - -/** - * Sets tooltip message as HTML markup. - * - * @param {string} str HTML message to display in tooltip. - */ -goog.ui.Tooltip.prototype.setHtml = function(str) { - this.getElement().innerHTML = str; -}; - - -/** - * Sets tooltip element. - * - * @param {Element} el HTML element to use as the tooltip. - */ -goog.ui.Tooltip.prototype.setElement = function(el) { - var oldElement = this.getElement(); - if (oldElement) { - goog.dom.removeNode(oldElement); - } - goog.ui.Tooltip.superClass_.setElement.call(this, el); - if (el) { - var body = this.dom_.getDocument().body; - body.insertBefore(el, body.lastChild); - } -}; - - -/** - * @return {string} The tooltip message as plain text. - */ -goog.ui.Tooltip.prototype.getText = function() { - return goog.dom.getTextContent(this.getElement()); -}; - - -/** - * @return {string} The tooltip message as HTML. - */ -goog.ui.Tooltip.prototype.getHtml = function() { - return this.getElement().innerHTML; -}; - - -/** - * @return {goog.ui.Tooltip.State} Current state of tooltip. - */ -goog.ui.Tooltip.prototype.getState = function() { - return this.showTimer ? - (this.isVisible() ? goog.ui.Tooltip.State.UPDATING : - goog.ui.Tooltip.State.WAITING_TO_SHOW) : - this.hideTimer ? goog.ui.Tooltip.State.WAITING_TO_HIDE : - this.isVisible() ? goog.ui.Tooltip.State.SHOWING : - goog.ui.Tooltip.State.INACTIVE; -}; - - -/** - * Sets whether tooltip requires the mouse to have moved or the anchor receive - * focus before the tooltip will be shown. - * @param {boolean} requireInteraction Whether tooltip should require some user - * interaction before showing tooltip. - */ -goog.ui.Tooltip.prototype.setRequireInteraction = function(requireInteraction) { - this.requireInteraction_ = requireInteraction; -}; - - -/** - * Returns true if the coord is in the tooltip. - * @param {goog.math.Coordinate} coord Coordinate being tested. - * @return {boolean} Whether the coord is in the tooltip. - */ -goog.ui.Tooltip.prototype.isCoordinateInTooltip = function(coord) { - // Check if coord is inside the the tooltip - if (!this.isVisible()) { - return false; - } - - var offset = goog.style.getPageOffset(this.getElement()); - var size = goog.style.getSize(this.getElement()); - return offset.x <= coord.x && coord.x <= offset.x + size.width && - offset.y <= coord.y && coord.y <= offset.y + size.height; -}; - - -/** - * Called before the popup is shown. - * - * @return {boolean} Whether tooltip should be shown. - * @protected - */ -goog.ui.Tooltip.prototype.onBeforeShow = function() { - if (!goog.ui.PopupBase.prototype.onBeforeShow.call(this)) { - return false; - } - - // Hide all open tooltips except if this tooltip is triggered by an element - // inside another tooltip. - if (this.anchor) { - for (var tt, i = 0; tt = goog.ui.Tooltip.activeInstances_[i]; i++) { - if (!goog.dom.contains(tt.getElement(), this.anchor)) { - tt.setVisible(false); - } - } - } - goog.array.insert(goog.ui.Tooltip.activeInstances_, this); - - var element = this.getElement(); - element.className = this.className; - this.clearHideTimer(); - - // Register event handlers for tooltip. Used to prevent the tooltip from - // closing if the cursor is over the tooltip rather then the element that - // triggered it. - goog.events.listen(element, goog.events.EventType.MOUSEOVER, - this.handleTooltipMouseOver, false, this); - goog.events.listen(element, goog.events.EventType.MOUSEOUT, - this.handleTooltipMouseOut, false, this); - - this.clearShowTimer(); - return true; -}; - - -/** - * Called after the popup is hidden. - * - * @protected - * @suppress {underscore} - * @override - */ -goog.ui.Tooltip.prototype.onHide_ = function() { - goog.array.remove(goog.ui.Tooltip.activeInstances_, this); - - // Hide all open tooltips triggered by an element inside this tooltip. - var element = this.getElement(); - for (var tt, i = 0; tt = goog.ui.Tooltip.activeInstances_[i]; i++) { - if (tt.anchor && goog.dom.contains(element, tt.anchor)) { - tt.setVisible(false); - } - } - - // If this tooltip is inside another tooltip, start hide timer for that - // tooltip in case this tooltip was the only reason it was still showing. - if (this.parentTooltip_) { - this.parentTooltip_.startHideTimer(); - } - - goog.events.unlisten(element, goog.events.EventType.MOUSEOVER, - this.handleTooltipMouseOver, false, this); - goog.events.unlisten(element, goog.events.EventType.MOUSEOUT, - this.handleTooltipMouseOut, false, this); - - this.anchor = undefined; - // If we are still waiting to show a different hovercard, don't abort it - // because you think you haven't seen a mouse move: - if (this.getState() == goog.ui.Tooltip.State.INACTIVE) { - this.seenInteraction_ = false; - } - - goog.ui.PopupBase.prototype.onHide_.call(this); -}; - - -/** - * Called by timer from mouse over handler. Shows tooltip if cursor is still - * over the same element. - * - * @param {Element} el Element to show tooltip for. - * @param {goog.positioning.AbstractPosition=} opt_pos Position to display popup - * at. - */ -goog.ui.Tooltip.prototype.maybeShow = function(el, opt_pos) { - // Assert that the mouse is still over the same element, and that we have not - // detached from the anchor in the meantime. - if (this.anchor == el && this.elements_.contains(this.anchor)) { - if (this.seenInteraction_ || !this.requireInteraction_) { - // If it is currently showing, then hide it, and abort if it doesn't hide. - this.setVisible(false); - if (!this.isVisible()) { - this.positionAndShow_(el, opt_pos); - } - } else { - this.anchor = undefined; - } - } - this.showTimer = undefined; -}; - - -/** - * @return {goog.structs.Set} Elements this widget is attached to. - * @protected - */ -goog.ui.Tooltip.prototype.getElements = function() { - return this.elements_; -}; - - -/** - * @return {Element} Active element reference. - */ -goog.ui.Tooltip.prototype.getActiveElement = function() { - return this.activeEl_; -}; - - -/** - * @param {Element} activeEl Active element reference. - * @protected - */ -goog.ui.Tooltip.prototype.setActiveElement = function(activeEl) { - this.activeEl_ = activeEl; -}; - - -/** - * Shows tooltip for a specific element. - * - * @param {Element} el Element to show tooltip for. - * @param {goog.positioning.AbstractPosition=} opt_pos Position to display popup - * at. - */ -goog.ui.Tooltip.prototype.showForElement = function(el, opt_pos) { - this.attach(el); - this.activeEl_ = el; - - this.positionAndShow_(el, opt_pos); -}; - - -/** - * Sets tooltip position and shows it. - * - * @param {Element} el Element to show tooltip for. - * @param {goog.positioning.AbstractPosition=} opt_pos Position to display popup - * at. - * @private - */ -goog.ui.Tooltip.prototype.positionAndShow_ = function(el, opt_pos) { - this.anchor = el; - this.setPosition(opt_pos || - this.getPositioningStrategy(goog.ui.Tooltip.Activation.CURSOR)); - this.setVisible(true); -}; - - -/** - * Called by timer from mouse out handler. Hides tooltip if cursor is still - * outside element and tooltip, or if a child of tooltip has the focus. - * @param {Element} el Tooltip's anchor when hide timer was started. - */ -goog.ui.Tooltip.prototype.maybeHide = function(el) { - this.hideTimer = undefined; - if (el == this.anchor) { - if ((this.activeEl_ == null || (this.activeEl_ != this.getElement() && - !this.elements_.contains(this.activeEl_))) && - !this.hasActiveChild()) { - this.setVisible(false); - } - } -}; - - -/** - * @return {boolean} Whether tooltip element contains an active child tooltip, - * and should thus not be hidden. When the child tooltip is hidden, it - * will check if the parent should be hidden, too. - * @protected - */ -goog.ui.Tooltip.prototype.hasActiveChild = function() { - return !!(this.childTooltip_ && this.childTooltip_.activeEl_); -}; - - -/** - * Saves the current mouse cursor position to {@code this.cursorPosition}. - * @param {goog.events.BrowserEvent} event MOUSEOVER or MOUSEMOVE event. - * @private - */ -goog.ui.Tooltip.prototype.saveCursorPosition_ = function(event) { - var scroll = this.dom_.getDocumentScroll(); - this.cursorPosition.x = event.clientX + scroll.x; - this.cursorPosition.y = event.clientY + scroll.y; -}; - - -/** - * Handler for mouse over events. - * - * @param {goog.events.BrowserEvent} event Event object. - * @protected - */ -goog.ui.Tooltip.prototype.handleMouseOver = function(event) { - var el = this.getAnchorFromElement(/** @type {Element} */ (event.target)); - this.activeEl_ = /** @type {Element} */ (el); - this.clearHideTimer(); - if (el != this.anchor) { - this.anchor = el; - this.startShowTimer(/** @type {Element} */ (el)); - this.checkForParentTooltip_(); - this.saveCursorPosition_(event); - } -}; - - -/** - * Find anchor containing the given element, if any. - * - * @param {Element} el Element that triggered event. - * @return {Element} Element in elements_ array that contains given element, - * or null if not found. - * @protected - */ -goog.ui.Tooltip.prototype.getAnchorFromElement = function(el) { - // FireFox has a bug where mouse events relating to <input> elements are - // sometimes duplicated (often in FF2, rarely in FF3): once for the - // <input> element and once for a magic hidden <div> element. Javascript - // code does not have sufficient permissions to read properties on that - // magic element and thus will throw an error in this call to - // getAnchorFromElement_(). In that case we swallow the error. - // See https://bugzilla.mozilla.org/show_bug.cgi?id=330961 - try { - while (el && !this.elements_.contains(el)) { - el = /** @type {Element} */ (el.parentNode); - } - return el; - } catch (e) { - return null; - } -}; - - -/** - * Handler for mouse move events. - * - * @param {goog.events.BrowserEvent} event MOUSEMOVE event. - * @protected - */ -goog.ui.Tooltip.prototype.handleMouseMove = function(event) { - this.saveCursorPosition_(event); - this.seenInteraction_ = true; -}; - - -/** - * Handler for focus events. - * - * @param {goog.events.BrowserEvent} event Event object. - * @protected - */ -goog.ui.Tooltip.prototype.handleFocus = function(event) { - var el = this.getAnchorFromElement(/** @type {Element} */ (event.target)); - this.activeEl_ = el; - this.seenInteraction_ = true; - - if (this.anchor != el) { - this.anchor = el; - var pos = this.getPositioningStrategy(goog.ui.Tooltip.Activation.FOCUS); - this.clearHideTimer(); - this.startShowTimer(/** @type {Element} */ (el), pos); - - this.checkForParentTooltip_(); - } -}; - - -/** - * Return a Position instance for repositioning the tooltip. Override in - * subclasses to customize the way repositioning is done. - * - * @param {goog.ui.Tooltip.Activation} activationType Information about what - * kind of event caused the popup to be shown. - * @return {!goog.positioning.AbstractPosition} The position object used - * to position the tooltip. - * @protected - */ -goog.ui.Tooltip.prototype.getPositioningStrategy = function(activationType) { - if (activationType == goog.ui.Tooltip.Activation.CURSOR) { - var coord = this.cursorPosition.clone(); - return new goog.ui.Tooltip.CursorTooltipPosition(coord); - } - return new goog.ui.Tooltip.ElementTooltipPosition(this.activeEl_); -}; - - -/** - * Looks for an active tooltip whose element contains this tooltip's anchor. - * This allows us to prevent hides until they are really necessary. - * - * @private - */ -goog.ui.Tooltip.prototype.checkForParentTooltip_ = function() { - if (this.anchor) { - for (var tt, i = 0; tt = goog.ui.Tooltip.activeInstances_[i]; i++) { - if (goog.dom.contains(tt.getElement(), this.anchor)) { - tt.childTooltip_ = this; - this.parentTooltip_ = tt; - } - } - } -}; - - -/** - * Handler for mouse out and blur events. - * - * @param {goog.events.BrowserEvent} event Event object. - * @protected - */ -goog.ui.Tooltip.prototype.handleMouseOutAndBlur = function(event) { - var el = this.getAnchorFromElement(/** @type {Element} */ (event.target)); - var elTo = this.getAnchorFromElement( - /** @type {Element} */ (event.relatedTarget)); - if (el == elTo) { - // We haven't really left the anchor, just moved from one child to - // another. - return; - } - - if (el == this.activeEl_) { - this.activeEl_ = null; - } - - this.clearShowTimer(); - this.seenInteraction_ = false; - if (this.isVisible() && (!event.relatedTarget || - !goog.dom.contains(this.getElement(), event.relatedTarget))) { - this.startHideTimer(); - } else { - this.anchor = undefined; - } -}; - - -/** - * Handler for mouse over events for the tooltip element. - * - * @param {goog.events.BrowserEvent} event Event object. - * @protected - */ -goog.ui.Tooltip.prototype.handleTooltipMouseOver = function(event) { - var element = this.getElement(); - if (this.activeEl_ != element) { - this.clearHideTimer(); - this.activeEl_ = element; - } -}; - - -/** - * Handler for mouse out events for the tooltip element. - * - * @param {goog.events.BrowserEvent} event Event object. - * @protected - */ -goog.ui.Tooltip.prototype.handleTooltipMouseOut = function(event) { - var element = this.getElement(); - if (this.activeEl_ == element && (!event.relatedTarget || - !goog.dom.contains(element, event.relatedTarget))) { - this.activeEl_ = null; - this.startHideTimer(); - } -}; - - -/** - * Helper method, starts timer that calls maybeShow. Parameters are passed to - * the maybeShow method. - * - * @param {Element} el Element to show tooltip for. - * @param {goog.positioning.AbstractPosition=} opt_pos Position to display popup - * at. - * @protected - */ -goog.ui.Tooltip.prototype.startShowTimer = function(el, opt_pos) { - if (!this.showTimer) { - this.showTimer = goog.Timer.callOnce( - goog.bind(this.maybeShow, this, el, opt_pos), this.showDelayMs_); - } -}; - - -/** - * Helper method called to clear the show timer. - * - * @protected - */ -goog.ui.Tooltip.prototype.clearShowTimer = function() { - if (this.showTimer) { - goog.Timer.clear(this.showTimer); - this.showTimer = undefined; - } -}; - - -/** - * Helper method called to start the close timer. - * @protected - */ -goog.ui.Tooltip.prototype.startHideTimer = function() { - if (this.getState() == goog.ui.Tooltip.State.SHOWING) { - this.hideTimer = goog.Timer.callOnce( - goog.bind(this.maybeHide, this, this.anchor), this.getHideDelayMs()); - } -}; - - -/** - * Helper method called to clear the close timer. - * @protected - */ -goog.ui.Tooltip.prototype.clearHideTimer = function() { - if (this.hideTimer) { - goog.Timer.clear(this.hideTimer); - this.hideTimer = undefined; - } -}; - - -/** @override */ -goog.ui.Tooltip.prototype.disposeInternal = function() { - this.setVisible(false); - this.clearShowTimer(); - this.detach(); - if (this.getElement()) { - goog.dom.removeNode(this.getElement()); - } - this.activeEl_ = null; - delete this.dom_; - goog.ui.Tooltip.superClass_.disposeInternal.call(this); -}; - - - -/** - * Popup position implementation that positions the popup (the tooltip in this - * case) based on the cursor position. It's positioned below the cursor to the - * right if there's enough room to fit all of it inside the Viewport. Otherwise - * it's displayed as far right as possible either above or below the element. - * - * Used to position tooltips triggered by the cursor. - * - * @param {number|!goog.math.Coordinate} arg1 Left position or coordinate. - * @param {number=} opt_arg2 Top position. - * @constructor - * @extends {goog.positioning.ViewportPosition} - */ -goog.ui.Tooltip.CursorTooltipPosition = function(arg1, opt_arg2) { - goog.positioning.ViewportPosition.call(this, arg1, opt_arg2); -}; -goog.inherits(goog.ui.Tooltip.CursorTooltipPosition, - goog.positioning.ViewportPosition); - - -/** - * Repositions the popup based on cursor position. - * - * @param {Element} element The DOM element of the popup. - * @param {goog.positioning.Corner} popupCorner The corner of the popup element - * that that should be positioned adjacent to the anchorElement. - * @param {goog.math.Box=} opt_margin A margin specified in pixels. - */ -goog.ui.Tooltip.CursorTooltipPosition.prototype.reposition = function( - element, popupCorner, opt_margin) { - var viewportElt = goog.style.getClientViewportElement(element); - var viewport = goog.style.getVisibleRectForElement(viewportElt); - var margin = opt_margin ? new goog.math.Box(opt_margin.top + 10, - opt_margin.right, opt_margin.bottom, opt_margin.left + 10) : - new goog.math.Box(10, 0, 0, 10); - - if (goog.positioning.positionAtCoordinate(this.coordinate, element, - goog.positioning.Corner.TOP_START, margin, viewport, - goog.positioning.Overflow.ADJUST_X | goog.positioning.Overflow.FAIL_Y - ) & goog.positioning.OverflowStatus.FAILED) { - goog.positioning.positionAtCoordinate(this.coordinate, element, - goog.positioning.Corner.TOP_START, margin, viewport, - goog.positioning.Overflow.ADJUST_X | - goog.positioning.Overflow.ADJUST_Y); - } -}; - - - -/** - * Popup position implementation that positions the popup (the tooltip in this - * case) based on the element position. It's positioned below the element to the - * right if there's enough room to fit all of it inside the Viewport. Otherwise - * it's displayed as far right as possible either above or below the element. - * - * Used to position tooltips triggered by focus changes. - * - * @param {Element} element The element to anchor the popup at. - * @constructor - * @extends {goog.positioning.AnchoredPosition} - */ -goog.ui.Tooltip.ElementTooltipPosition = function(element) { - goog.positioning.AnchoredPosition.call(this, element, - goog.positioning.Corner.BOTTOM_RIGHT); -}; -goog.inherits(goog.ui.Tooltip.ElementTooltipPosition, - goog.positioning.AnchoredPosition); - - -/** - * Repositions the popup based on element position. - * - * @param {Element} element The DOM element of the popup. - * @param {goog.positioning.Corner} popupCorner The corner of the popup element - * that should be positioned adjacent to the anchorElement. - * @param {goog.math.Box=} opt_margin A margin specified in pixels. - */ -goog.ui.Tooltip.ElementTooltipPosition.prototype.reposition = function( - element, popupCorner, opt_margin) { - var offset = new goog.math.Coordinate(10, 0); - - if (goog.positioning.positionAtAnchor(this.element, this.corner, element, - popupCorner, offset, opt_margin, - goog.positioning.Overflow.ADJUST_X | goog.positioning.Overflow.FAIL_Y - ) & goog.positioning.OverflowStatus.FAILED) { - goog.positioning.positionAtAnchor(this.element, - goog.positioning.Corner.TOP_RIGHT, element, - goog.positioning.Corner.BOTTOM_LEFT, offset, opt_margin, - goog.positioning.Overflow.ADJUST_X | - goog.positioning.Overflow.ADJUST_Y); - } -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tooltip_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tooltip_test.html.svn-base deleted file mode 100644 index c41ffae..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tooltip_test.html.svn-base +++ /dev/null @@ -1,380 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- Author: attila@google.com (Attila Bodis) --> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.Tooltip</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.events'); - goog.require('goog.events.Event'); - goog.require('goog.events.EventHandler'); - goog.require('goog.events.EventType'); - goog.require('goog.positioning.AbsolutePosition'); - goog.require('goog.style'); - goog.require('goog.ui.Tooltip'); - goog.require('goog.testing.MockClock'); - goog.require('goog.testing.TestQueue'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.userAgent'); - </script> -</head> -<body> - <iframe id="testframe" style="width: 200px; height: 200px;" - src="blank_test_helper.html"> - </iframe> - <script> - /** - * A subclass of Tooltip that overrides {@code getPositioningStrategy} - * for testing purposes. - */ - function TestTooltip(el, text, dom) { - goog.ui.Tooltip.call(this, el, text, dom); - }; - goog.inherits(TestTooltip, goog.ui.Tooltip); - - - /** {@override} */ - TestTooltip.prototype.getPositioningStrategy = function() { - return new goog.positioning.AbsolutePosition(13, 17); - }; - - - var tt, clock, handler, eventQueue, dom; - - // Allow positions to be off by one in gecko as it reports scrolling - // offsets in steps of 2. - var ALLOWED_OFFSET = goog.userAgent.GECKO ? 1 : 0; - - function setUp() { - // We get access denied error when accessing the iframe in IE on the farm - // as IE doesn't have the same window size issues as firefox on the farm - // we bypass the iframe and use the current document instead. - if (goog.userAgent.IE) { - dom = goog.dom.getDomHelper(document); - } else { - var frame = document.getElementById('testframe'); - var doc = goog.dom.getFrameContentDocument(frame); - dom = goog.dom.getDomHelper(doc); - } - - // Host elements in fixed size iframe to avoid window size problems when - // running under Selenium. - dom.getDocument().body.innerHTML = - '<p id="notpopup">Content</p>' + - '<p id="hovertarget">Hover Here For Popup</p>' + - '<p id="second">Secondary target</p>'; - - tt = new goog.ui.Tooltip(undefined, undefined, dom); - tt.setElement(dom.createDom('div', {id: 'popup', - style: 'visibility:hidden'}, - 'Hello')); - clock = new goog.testing.MockClock(true); - eventQueue = new goog.testing.TestQueue(); - handler = new goog.events.EventHandler(eventQueue); - handler.listen(tt, goog.ui.PopupBase.EventType.SHOW, eventQueue.enqueue); - handler.listen(tt, goog.ui.PopupBase.EventType.HIDE, eventQueue.enqueue); - } - - function tearDown() { - // tooltip needs to be hidden as well as disposed of so that it doesn't - // leave global state hanging around to trip up other tests. - tt.onHide_(); - tt.dispose(); - clock.uninstall(); - handler.removeAll(); - } - - function testConstructor() { - var element = tt.getElement(); - assertNotNull('Tooltip should have non-null element', element); - assertEquals('Tooltip element should be the DIV we created', - dom.getElement('popup'), element); - assertEquals('Tooltip element should be a child of the document body', - dom.getDocument().body, element.parentNode); - } - - function testTooltipShowsAndHides() { - var hoverTarget = dom.getElement('hovertarget'); - var elsewhere = dom.getElement('notpopup'); - var element = tt.getElement(); - var position = new goog.math.Coordinate(5, 5); - assertNotNull('Tooltip should have non-null element', element); - assertEquals('Initial state should be inactive', - goog.ui.Tooltip.State.INACTIVE, tt.getState()); - tt.attach(hoverTarget); - tt.setShowDelayMs(100); - tt.setHideDelayMs(50); - goog.testing.events.fireMouseOverEvent(hoverTarget, elsewhere, position); - assertEquals(goog.ui.Tooltip.State.WAITING_TO_SHOW, tt.getState()); - clock.tick(101); - assertEquals('visible', tt.getElement().style.visibility); - assertEquals('tooltip y position (10px margin below the cursor)', '15px', - tt.getElement().style.top); - assertEquals(goog.ui.Tooltip.State.SHOWING, tt.getState()); - assertEquals(goog.ui.PopupBase.EventType.SHOW, eventQueue.dequeue().type); - assertTrue(eventQueue.isEmpty()); - - goog.testing.events.fireMouseOutEvent(hoverTarget, elsewhere); - assertEquals(goog.ui.Tooltip.State.WAITING_TO_HIDE, tt.getState()); - clock.tick(51); - assertEquals('hidden', tt.getElement().style.visibility); - assertEquals(goog.ui.Tooltip.State.INACTIVE, tt.getState()); - assertEquals(goog.ui.PopupBase.EventType.HIDE, eventQueue.dequeue().type); - assertTrue(eventQueue.isEmpty()); - } - - function testMultipleTargets() { - var firstTarget = dom.getElement('hovertarget'); - var secondTarget = dom.getElement('second'); - var elsewhere = dom.getElement('notpopup'); - var element = tt.getElement(); - - tt.attach(firstTarget); - tt.attach(secondTarget); - tt.setShowDelayMs(100); - tt.setHideDelayMs(50); - - // Move over first target - goog.testing.events.fireMouseOverEvent(firstTarget, elsewhere); - clock.tick(101); - assertEquals(goog.ui.PopupBase.EventType.SHOW, eventQueue.dequeue().type); - assertTrue(eventQueue.isEmpty()); - - // Move from first to second - goog.testing.events.fireMouseOutEvent(firstTarget, secondTarget); - goog.testing.events.fireMouseOverEvent(secondTarget, firstTarget); - assertEquals(goog.ui.Tooltip.State.UPDATING, tt.getState()); - assertTrue(eventQueue.isEmpty()); - - // Move from second to element (before second shows) - goog.testing.events.fireMouseOutEvent(secondTarget, element); - goog.testing.events.fireMouseOverEvent(element, secondTarget); - assertEquals(goog.ui.Tooltip.State.SHOWING, tt.getState()); - assertTrue(eventQueue.isEmpty()); - - // Move from element to second, and let it show - goog.testing.events.fireMouseOutEvent(element, secondTarget); - goog.testing.events.fireMouseOverEvent(secondTarget, element); - assertEquals(goog.ui.Tooltip.State.UPDATING, tt.getState()); - clock.tick(101); - assertEquals(goog.ui.Tooltip.State.SHOWING, tt.getState()); - assertEquals('Anchor should be second target', secondTarget, tt.anchor); - assertEquals(goog.ui.PopupBase.EventType.HIDE, eventQueue.dequeue().type); - assertEquals(goog.ui.PopupBase.EventType.SHOW, eventQueue.dequeue().type); - assertTrue(eventQueue.isEmpty()); - - // Move from second to first and then off without first showing - goog.testing.events.fireMouseOutEvent(secondTarget, firstTarget); - goog.testing.events.fireMouseOverEvent(firstTarget, secondTarget); - assertEquals(goog.ui.Tooltip.State.UPDATING, tt.getState()); - goog.testing.events.fireMouseOutEvent(firstTarget, elsewhere); - assertEquals(goog.ui.Tooltip.State.WAITING_TO_HIDE, tt.getState()); - clock.tick(51); - assertEquals('hidden', tt.getElement().style.visibility); - assertEquals(goog.ui.Tooltip.State.INACTIVE, tt.getState()); - assertEquals(goog.ui.PopupBase.EventType.HIDE, eventQueue.dequeue().type); - assertTrue(eventQueue.isEmpty()); - clock.tick(200); - - // Move from element to second, but detach second before it shows. - goog.testing.events.fireMouseOutEvent(element, secondTarget); - goog.testing.events.fireMouseOverEvent(secondTarget, element); - assertEquals(goog.ui.Tooltip.State.WAITING_TO_SHOW, tt.getState()); - tt.detach(secondTarget); - clock.tick(200); - assertEquals(goog.ui.Tooltip.State.INACTIVE, tt.getState()); - assertEquals('Anchor should be second target', secondTarget, tt.anchor); - assertTrue(eventQueue.isEmpty()); - } - - function testRequireInteraction() { - var hoverTarget = dom.getElement('hovertarget'); - var elsewhere = dom.getElement('notpopup'); - - tt.attach(hoverTarget); - tt.setShowDelayMs(100); - tt.setHideDelayMs(50); - tt.setRequireInteraction(true); - - goog.testing.events.fireMouseOverEvent(hoverTarget, elsewhere); - clock.tick(101); - assertEquals( - 'Tooltip should not show without mouse move event', - 'hidden', tt.getElement().style.visibility); - goog.testing.events.fireMouseMoveEvent(hoverTarget); - goog.testing.events.fireMouseOverEvent(hoverTarget, elsewhere); - clock.tick(101); - assertEquals( - 'Tooltip should show because we had mouse move event', - 'visible', tt.getElement().style.visibility); - - goog.testing.events.fireMouseOutEvent(hoverTarget, elsewhere); - clock.tick(51); - assertEquals('hidden', tt.getElement().style.visibility); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.FOCUS, hoverTarget)); - clock.tick(101); - assertEquals( - 'Tooltip should show because we had focus event', - 'visible', tt.getElement().style.visibility); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.BLUR, hoverTarget)); - clock.tick(51); - assertEquals('hidden', tt.getElement().style.visibility); - - goog.testing.events.fireMouseMoveEvent(hoverTarget); - goog.testing.events.fireMouseOverEvent(hoverTarget, elsewhere); - goog.testing.events.fireMouseOutEvent(hoverTarget, elsewhere); - goog.testing.events.fireMouseOverEvent(hoverTarget, elsewhere); - clock.tick(101); - assertEquals( - 'A cancelled trigger should also cancel the seen interaction', - 'hidden', tt.getElement().style.visibility); - } - - function testDispose() { - var element = tt.getElement(); - tt.dispose(); - assertTrue('Tooltip should have been disposed of', tt.isDisposed()); - assertNull('Tooltip element reference should have been nulled out', - tt.getElement()); - assertNotEquals('Tooltip element should not be a child of the body', - document.body, element.parentNode); - } - - function testNested() { - var ttNested; - tt.getElement().appendChild(dom.createDom( - 'span', {id: 'nested'}, 'Goodbye')); - ttNested = new goog.ui.Tooltip(undefined, undefined, dom); - ttNested.setElement(dom.createDom('div', {id: 'nestedPopup'}, 'hi')); - tt.setShowDelayMs(100); - tt.setHideDelayMs(50); - ttNested.setShowDelayMs(75); - ttNested.setHideDelayMs(25); - var nestedAnchor = dom.getElement('nested'); - var hoverTarget = dom.getElement('hovertarget'); - var outerTooltip = dom.getElement('popup'); - var innerTooltip = dom.getElement('nestedPopup'); - var elsewhere = dom.getElement('notpopup'); - - ttNested.attach(nestedAnchor); - tt.attach(hoverTarget); - - // Test mouse into, out of nested tooltip - goog.testing.events.fireMouseOverEvent(hoverTarget, elsewhere); - clock.tick(101); - goog.testing.events.fireMouseOutEvent(hoverTarget, outerTooltip); - goog.testing.events.fireMouseOverEvent(outerTooltip, hoverTarget); - clock.tick(51); - assertEquals('visible', tt.getElement().style.visibility); - goog.testing.events.fireMouseOutEvent(outerTooltip, nestedAnchor); - goog.testing.events.fireMouseOverEvent(nestedAnchor, outerTooltip); - clock.tick(76); - assertEquals('visible', tt.getElement().style.visibility); - assertEquals('visible', ttNested.getElement().style.visibility); - goog.testing.events.fireMouseOutEvent(nestedAnchor, outerTooltip); - goog.testing.events.fireMouseOverEvent(outerTooltip, nestedAnchor); - clock.tick(100); - assertEquals('visible', tt.getElement().style.visibility); - assertEquals('hidden', ttNested.getElement().style.visibility); - - // Go back in nested tooltip and then out through tooltip element. - goog.testing.events.fireMouseOutEvent(outerTooltip, nestedAnchor); - goog.testing.events.fireMouseOverEvent(nestedAnchor, outerTooltip); - clock.tick(76); - goog.testing.events.fireMouseOutEvent(nestedAnchor, innerTooltip); - goog.testing.events.fireMouseOverEvent(innerTooltip, nestedAnchor); - clock.tick(15); - assertEquals('visible', tt.getElement().style.visibility); - assertEquals('visible', ttNested.getElement().style.visibility); - goog.testing.events.fireMouseOutEvent(innerTooltip, elsewhere); - clock.tick(26); - assertEquals('hidden', ttNested.getElement().style.visibility); - clock.tick(51); - assertEquals('hidden', tt.getElement().style.visibility); - - // Test with focus - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.FOCUS, hoverTarget)); - clock.tick(101); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.BLUR, hoverTarget)); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.FOCUS, nestedAnchor)); - clock.tick(76); - assertEquals('visible', tt.getElement().style.visibility); - assertEquals('visible', ttNested.getElement().style.visibility); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.BLUR, nestedAnchor)); - goog.testing.events.fireBrowserEvent(new goog.events.Event( - goog.events.EventType.FOCUS, hoverTarget)); - clock.tick(26); - assertEquals('visible', tt.getElement().style.visibility); - assertEquals('hidden', ttNested.getElement().style.visibility); - - ttNested.onHide_(); - ttNested.dispose(); - } - - function testMemoryLeak() { - var listeners = goog.events.getTotalListenerCount(); - var anchor = dom.createElement('div'); - var tooltip = new goog.ui.Tooltip(anchor, ''); - tooltip.setVisible(true); - tooltip.dispose(); - assertEquals('no event listeners leaked', listeners, - goog.events.getTotalListenerCount()); - } - - function testPosition() { - dom.getDocument().body.style.paddingBottom = '150%'; // force scrollbar - var scrollEl = dom.getDocumentScrollElement(); - - var anchor = dom.getElement('hovertarget'); - var tooltip = new goog.ui.Tooltip(anchor, 'foo'); - tooltip.getElement().style.position = 'absolute'; - - tooltip.cursorPosition.x = 100; - tooltip.cursorPosition.y = 100; - tooltip.showForElement(anchor); - - assertEquals('Tooltip should be at cursor position', - '(110, 110)', // (100, 100) + padding (10, 10) - goog.style.getPageOffset(tooltip.getElement()).toString()); - - scrollEl.scrollTop = 50; - - var offset = goog.style.getPageOffset(tooltip.getElement()); - assertTrue('Tooltip should be at cursor position when scrolled', - Math.abs(offset.x - 110) <= ALLOWED_OFFSET); // 100 + padding 10 - assertTrue('Tooltip should be at cursor position when scrolled', - Math.abs(offset.y - 110) <= ALLOWED_OFFSET); // 100 + padding 10 - - tooltip.dispose(); - dom.getDocument().body.style.paddingTop = ''; - scrollEl.scrollTop = 0; - } - - function testPositionOverride() { - var anchor = dom.getElement('hovertarget'); - var tooltip = new TestTooltip(anchor, 'foo', dom); - - tooltip.showForElement(anchor); - - assertEquals('Tooltip should be at absolute position', '(13, 17)', - goog.style.getPageOffset(tooltip.getElement()).toString()); - tooltip.dispose(); - } - </script> -</body> -</html> diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tristatemenuitem.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tristatemenuitem.js.svn-base deleted file mode 100644 index 3bb8ba8..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tristatemenuitem.js.svn-base +++ /dev/null @@ -1,186 +0,0 @@ -// 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 menu item class that supports three state checkbox semantics. - * - * @author eae@google.com (Emil A Eklund) - */ - -goog.provide('goog.ui.TriStateMenuItem'); -goog.provide('goog.ui.TriStateMenuItem.State'); - -goog.require('goog.dom.classes'); -goog.require('goog.ui.Component.EventType'); -goog.require('goog.ui.Component.State'); -goog.require('goog.ui.ControlContent'); -goog.require('goog.ui.MenuItem'); -goog.require('goog.ui.TriStateMenuItemRenderer'); -goog.require('goog.ui.registry'); - - - -/** - * Class representing a three state checkbox menu item. - * - * @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 {Object=} opt_model Data/model associated with the menu item. - * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper used for - * document interactions. - * @param {goog.ui.MenuItemRenderer=} opt_renderer Optional renderer. - * @constructor - * @extends {goog.ui.MenuItem} - * - * TODO(attila): Figure out how to better integrate this into the - * goog.ui.Control state management framework. - */ -goog.ui.TriStateMenuItem = function(content, opt_model, opt_domHelper, - opt_renderer) { - goog.ui.MenuItem.call(this, content, opt_model, opt_domHelper, - opt_renderer || new goog.ui.TriStateMenuItemRenderer()); - this.setCheckable(true); -}; -goog.inherits(goog.ui.TriStateMenuItem, goog.ui.MenuItem); - - -/** - * Checked states for component. - * @enum {number} - */ -goog.ui.TriStateMenuItem.State = { - /** - * Component is not checked. - */ - NOT_CHECKED: 0, - - /** - * Component is partially checked. - */ - PARTIALLY_CHECKED: 1, - - /** - * Component is fully checked. - */ - FULLY_CHECKED: 2 -}; - - -/** - * Menu item's checked state. - * @type {goog.ui.TriStateMenuItem.State} - * @private - */ -goog.ui.TriStateMenuItem.prototype.checkState_ = - goog.ui.TriStateMenuItem.State.NOT_CHECKED; - - -/** - * Whether the partial state can be toggled. - * @type {boolean} - * @private - */ -goog.ui.TriStateMenuItem.prototype.allowPartial_ = false; - - -/** - * @return {goog.ui.TriStateMenuItem.State} The menu item's check state. - */ -goog.ui.TriStateMenuItem.prototype.getCheckedState = function() { - return this.checkState_; -}; - - -/** - * Sets the checked state. - * @param {goog.ui.TriStateMenuItem.State} state The checked state. - */ -goog.ui.TriStateMenuItem.prototype.setCheckedState = function(state) { - this.setCheckedState_(state); - this.allowPartial_ = - state == goog.ui.TriStateMenuItem.State.PARTIALLY_CHECKED; -}; - - -/** - * Sets the checked state and updates the CSS styling. Dispatches a - * {@code CHECK} or {@code UNCHECK} event prior to changing the component's - * state, which may be caught and canceled to prevent the component from - * changing state. - * @param {goog.ui.TriStateMenuItem.State} state The checked state. - * @private - */ -goog.ui.TriStateMenuItem.prototype.setCheckedState_ = function(state) { - if (this.dispatchEvent(state != goog.ui.TriStateMenuItem.State.NOT_CHECKED ? - goog.ui.Component.EventType.CHECK : - goog.ui.Component.EventType.UNCHECK)) { - this.setState(goog.ui.Component.State.CHECKED, - state != goog.ui.TriStateMenuItem.State.NOT_CHECKED); - this.checkState_ = state; - this.updatedCheckedStateClassNames_(); - } -}; - - -/** @override */ -goog.ui.TriStateMenuItem.prototype.performActionInternal = function(e) { - switch (this.getCheckedState()) { - case goog.ui.TriStateMenuItem.State.NOT_CHECKED: - this.setCheckedState_(this.allowPartial_ ? - goog.ui.TriStateMenuItem.State.PARTIALLY_CHECKED : - goog.ui.TriStateMenuItem.State.FULLY_CHECKED); - break; - case goog.ui.TriStateMenuItem.State.PARTIALLY_CHECKED: - this.setCheckedState_(goog.ui.TriStateMenuItem.State.FULLY_CHECKED); - break; - case goog.ui.TriStateMenuItem.State.FULLY_CHECKED: - this.setCheckedState_(goog.ui.TriStateMenuItem.State.NOT_CHECKED); - break; - } - - var checkboxClass = goog.getCssName( - this.getRenderer().getCssClass(), 'checkbox'); - var clickOnCheckbox = e.target && goog.dom.classes.has( - /** @type {Element} */ (e.target), checkboxClass); - - return this.dispatchEvent(clickOnCheckbox || this.allowPartial_ ? - goog.ui.Component.EventType.CHANGE : - goog.ui.Component.EventType.ACTION); -}; - - -/** - * Updates the extra class names applied to the menu item element. - * @private - */ -goog.ui.TriStateMenuItem.prototype.updatedCheckedStateClassNames_ = function() { - var renderer = this.getRenderer(); - renderer.enableExtraClassName( - this, goog.getCssName(renderer.getCssClass(), 'partially-checked'), - this.getCheckedState() == - goog.ui.TriStateMenuItem.State.PARTIALLY_CHECKED); - renderer.enableExtraClassName( - this, goog.getCssName(renderer.getCssClass(), 'fully-checked'), - this.getCheckedState() == goog.ui.TriStateMenuItem.State.FULLY_CHECKED); -}; - - -// Register a decorator factory function for goog.ui.TriStateMenuItemRenderer. -goog.ui.registry.setDecoratorByClassName( - goog.ui.TriStateMenuItemRenderer.CSS_CLASS, - function() { - // TriStateMenuItem defaults to using TriStateMenuItemRenderer. - return new goog.ui.TriStateMenuItem(null); - }); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tristatemenuitemrenderer.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tristatemenuitemrenderer.js.svn-base deleted file mode 100644 index 1a2048c..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/tristatemenuitemrenderer.js.svn-base +++ /dev/null @@ -1,87 +0,0 @@ -// 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.TriStateMenuItem}s. - * - * @author eae@google.com (Emil A Eklund) - */ - -goog.provide('goog.ui.TriStateMenuItemRenderer'); - -goog.require('goog.dom.classes'); -goog.require('goog.ui.MenuItemRenderer'); - - - -/** - * Default renderer for {@link goog.ui.TriStateMenuItemRenderer}s. Each item has - * the following structure: - * <div class="goog-tristatemenuitem"> - * <div class="goog-tristatemenuitem-checkbox"></div> - * <div>...(content)...</div> - * </div> - * @constructor - * @extends {goog.ui.MenuItemRenderer} - */ -goog.ui.TriStateMenuItemRenderer = function() { - goog.ui.MenuItemRenderer.call(this); -}; -goog.inherits(goog.ui.TriStateMenuItemRenderer, goog.ui.MenuItemRenderer); -goog.addSingletonGetter(goog.ui.TriStateMenuItemRenderer); - - -/** - * CSS class name the renderer applies to menu item elements. - * @type {string} - */ -goog.ui.TriStateMenuItemRenderer.CSS_CLASS = - goog.getCssName('goog-tristatemenuitem'); - - -/** - * Overrides {@link goog.ui.ControlRenderer#decorate} by initializing the - * menu item to checkable based on whether the element to be decorated has - * extra styling indicating that it should be. - * @param {goog.ui.MenuItem} item Menu item instance to decorate the element. - * @param {Element} element Element to decorate. - * @return {Element} Decorated element. - */ -goog.ui.TriStateMenuItemRenderer.prototype.decorate = function(item, element) { - element = goog.ui.TriStateMenuItemRenderer.superClass_.decorate.call(this, - item, element); - this.setSelectable(item, element, true); - - if (goog.dom.classes.has(element, - goog.getCssName(this.getCssClass(), 'fully-checked'))) { - item.setCheckedState(goog.ui.TriStateMenuItem.State.FULLY_CHECKED); - } else if (goog.dom.classes.has(element, - goog.getCssName(this.getCssClass(), 'partially-checked'))) { - item.setCheckedState(goog.ui.TriStateMenuItem.State.PARTIALLY_CHECKED); - } else { - item.setCheckedState(goog.ui.TriStateMenuItem.State.NOT_CHECKED); - } - - return element; -}; - - -/** - * Returns the CSS class to be applied to menu items rendered using this - * renderer. - * @return {string} Renderer-specific CSS class. - */ -goog.ui.TriStateMenuItemRenderer.prototype.getCssClass = function() { - return goog.ui.TriStateMenuItemRenderer.CSS_CLASS; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/twothumbslider.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/twothumbslider.js.svn-base deleted file mode 100644 index 22c821e..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/twothumbslider.js.svn-base +++ /dev/null @@ -1,153 +0,0 @@ -// 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.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.a11y.Role'); -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 - */ -goog.ui.TwoThumbSlider.prototype.getCssClass = function(orient) { - return goog.ui.TwoThumbSlider.CSS_CLASS_PREFIX + '-' + orient; -}; - - -/** - * 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.dom.a11y.setRole(thumb, goog.dom.a11y.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. - */ -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; -}; diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/zippy.js.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/zippy.js.svn-base deleted file mode 100644 index 0e954d1..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/zippy.js.svn-base +++ /dev/null @@ -1,444 +0,0 @@ -// 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 Zippy widget implementation. - * - * @author eae@google.com (Emil A Eklund) - * @see ../demos/zippy.html - */ - -goog.provide('goog.ui.Zippy'); -goog.provide('goog.ui.Zippy.Events'); -goog.provide('goog.ui.ZippyEvent'); - -goog.require('goog.dom'); -goog.require('goog.dom.a11y'); -goog.require('goog.dom.classes'); -goog.require('goog.events'); -goog.require('goog.events.Event'); -goog.require('goog.events.EventHandler'); -goog.require('goog.events.EventTarget'); -goog.require('goog.events.EventType'); -goog.require('goog.events.KeyCodes'); -goog.require('goog.style'); - - - -/** - * Zippy widget. Expandable/collapsible container, clicking the header toggles - * the visibility of the content. - * - * @extends {goog.events.EventTarget} - * @param {Element|string|null} header Header element, either element - * reference, string id or null if no header exists. - * @param {Element|string|function():Element=} opt_content Content element - * (if any), either element reference or string id. If skipped, the caller - * should handle the TOGGLE event in its own way. If a function is passed, - * then if will be called to create the content element the first time the - * zippy is expanded. - * @param {boolean=} opt_expanded Initial expanded/visibility state. Defaults to - * false. - * @param {Element|string=} opt_expandedHeader Element to use as the header when - * the zippy is expanded. - * @param {goog.dom.DomHelper=} opt_domHelper An optional DOM helper. - * @constructor - */ -goog.ui.Zippy = function(header, opt_content, opt_expanded, - opt_expandedHeader, opt_domHelper) { - goog.events.EventTarget.call(this); - - /** - * DomHelper used to interact with the document, allowing components to be - * created in a different window. - * @type {!goog.dom.DomHelper} - * @private - */ - this.dom_ = opt_domHelper || goog.dom.getDomHelper(); - - /** - * Header element or null if no header exists. - * @type {Element} - * @private - */ - this.elHeader_ = this.dom_.getElement(header) || null; - - /** - * When present, the header to use when the zippy is expanded. - * @type {Element} - * @private - */ - this.elExpandedHeader_ = this.dom_.getElement(opt_expandedHeader || null); - - /** - * Function that will create the content element, or false if there is no such - * function. - * @type {?function():Element} - * @private - */ - this.lazyCreateFunc_ = goog.isFunction(opt_content) ? opt_content : null; - - /** - * Content element. - * @type {Element} - * @private - */ - this.elContent_ = this.lazyCreateFunc_ || !opt_content ? null : - this.dom_.getElement(/** @type {Element} */ (opt_content)); - - /** - * Expanded state. - * @type {boolean} - * @private - */ - this.expanded_ = opt_expanded == true; - - /** - * A keyboard events handler. If there are two headers it is shared for both. - * @type {goog.events.EventHandler} - * @private - */ - this.keyboardEventHandler_ = new goog.events.EventHandler(this); - - /** - * A mouse events handler. If there are two headers it is shared for both. - * @type {goog.events.EventHandler} - * @private - */ - this.mouseEventHandler_ = new goog.events.EventHandler(this); - - var self = this; - function addHeaderEvents(el) { - if (el) { - el.tabIndex = 0; - goog.dom.a11y.setRole(el, self.getAriaRole()); - goog.dom.classes.add(el, goog.getCssName('goog-zippy-header')); - self.enableMouseEventsHandling_(el); - self.enableKeyboardEventsHandling_(el); - } - } - addHeaderEvents(this.elHeader_); - addHeaderEvents(this.elExpandedHeader_); - - // initialize based on expanded state - this.setExpanded(this.expanded_); -}; -goog.inherits(goog.ui.Zippy, goog.events.EventTarget); - - -/** - * Constants for event names - * - * @type {Object} - */ -goog.ui.Zippy.Events = { - // Zippy will dispatch an ACTION event for user interaction. Mimics - // {@code goog.ui.Controls#performActionInternal} by first changing - // the toggle state and then dispatching an ACTION event. - ACTION: 'action', - // Zippy state is toggled from collapsed to expanded or vice versa. - TOGGLE: 'toggle' -}; - - -/** - * Whether to listen for and handle mouse events; defaults to true. - * @type {boolean} - * @private - */ -goog.ui.Zippy.prototype.handleMouseEvents_ = true; - - -/** - * Whether to listen for and handle key events; defaults to true. - * @type {boolean} - * @private - */ -goog.ui.Zippy.prototype.handleKeyEvents_ = true; - - -/** @override */ -goog.ui.Zippy.prototype.disposeInternal = function() { - goog.ui.Zippy.superClass_.disposeInternal.call(this); - goog.dispose(this.keyboardEventHandler_); - goog.dispose(this.mouseEventHandler_); -}; - - -/** - * @return {goog.dom.a11y.Role} The ARIA role to be applied to Zippy element. - */ -goog.ui.Zippy.prototype.getAriaRole = function() { - return goog.dom.a11y.Role.TAB; -}; - - -/** - * @return {Element} The content element. - * @protected - */ -goog.ui.Zippy.prototype.getContentElement = function() { - return this.elContent_; -}; - - -/** - * @return {Element} The visible header element. - */ -goog.ui.Zippy.prototype.getVisibleHeaderElement = function() { - var expandedHeader = this.elExpandedHeader_; - return expandedHeader && goog.style.isElementShown(expandedHeader) ? - expandedHeader : this.elHeader_; -}; - - -/** - * Expands content pane. - */ -goog.ui.Zippy.prototype.expand = function() { - this.setExpanded(true); -}; - - -/** - * Collapses content pane. - */ -goog.ui.Zippy.prototype.collapse = function() { - this.setExpanded(false); -}; - - -/** - * Toggles expanded state. - */ -goog.ui.Zippy.prototype.toggle = function() { - this.setExpanded(!this.expanded_); -}; - - -/** - * Sets expanded state. - * - * @param {boolean} expanded Expanded/visibility state. - */ -goog.ui.Zippy.prototype.setExpanded = function(expanded) { - if (this.elContent_) { - // Hide the element, if one is provided. - goog.style.showElement(this.elContent_, expanded); - } else if (expanded && this.lazyCreateFunc_) { - // Assume that when the element is not hidden upon creation. - this.elContent_ = this.lazyCreateFunc_(); - } - if (this.elContent_) { - goog.dom.classes.add(this.elContent_, - goog.getCssName('goog-zippy-content')); - } - - if (this.elExpandedHeader_) { - // Hide the show header and show the hide one. - goog.style.showElement(this.elHeader_, !expanded); - goog.style.showElement(this.elExpandedHeader_, expanded); - } else { - // Update header image, if any. - this.updateHeaderClassName(expanded); - } - - this.setExpandedInternal(expanded); - - // Fire toggle event - this.dispatchEvent(new goog.ui.ZippyEvent(goog.ui.Zippy.Events.TOGGLE, - this, this.expanded_)); -}; - - -/** - * Sets expanded internal state. - * - * @param {boolean} expanded Expanded/visibility state. - * @protected - */ -goog.ui.Zippy.prototype.setExpandedInternal = function(expanded) { - this.expanded_ = expanded; -}; - - -/** - * @return {boolean} Whether the zippy is expanded. - */ -goog.ui.Zippy.prototype.isExpanded = function() { - return this.expanded_; -}; - - -/** - * Updates the header element's className and ARIA (accessibility) EXPANDED - * state. - * - * @param {boolean} expanded Expanded/visibility state. - * @protected - */ -goog.ui.Zippy.prototype.updateHeaderClassName = function(expanded) { - if (this.elHeader_) { - goog.dom.classes.enable(this.elHeader_, - goog.getCssName('goog-zippy-expanded'), expanded); - goog.dom.classes.enable(this.elHeader_, - goog.getCssName('goog-zippy-collapsed'), !expanded); - goog.dom.a11y.setState( - this.elHeader_, goog.dom.a11y.State.EXPANDED, expanded); - } -}; - - -/** - * @return {boolean} Whether the Zippy handles its own key events. - */ -goog.ui.Zippy.prototype.isHandleMouseEvents = function() { - return this.handleKeyEvents_; -}; - - -/** - * @return {boolean} Whether the Zippy handles its own mouse events. - */ -goog.ui.Zippy.prototype.isHandleKeyEvents = function() { - return this.handleMouseEvents_; -}; - - -/** - * Sets whether the Zippy handles it's own keyboard events. - * @param {boolean} enable Whether the Zippy handles keyboard events. - */ -goog.ui.Zippy.prototype.setHandleKeyboardEvents = function(enable) { - if (this.handleKeyEvents_ != enable) { - this.handleKeyEvents_ = enable; - if (enable) { - this.enableKeyboardEventsHandling_(this.elHeader_); - this.enableKeyboardEventsHandling_(this.elExpandedHeader_); - } else { - this.keyboardEventHandler_.removeAll(); - } - } -}; - - -/** - * Sets whether the Zippy handles it's own mouse events. - * @param {boolean} enable Whether the Zippy handles mouse events. - */ -goog.ui.Zippy.prototype.setHandleMouseEvents = function(enable) { - if (this.handleMouseEvents_ != enable) { - this.handleMouseEvents_ = enable; - if (enable) { - this.enableMouseEventsHandling_(this.elHeader_); - this.enableMouseEventsHandling_(this.elExpandedHeader_); - } else { - this.mouseEventHandler_.removeAll(); - } - } -}; - - -/** - * Enables keyboard events handling for the passed header element. - * @param {Element} header The header element. - * @private - */ -goog.ui.Zippy.prototype.enableKeyboardEventsHandling_ = function(header) { - if (header) { - this.keyboardEventHandler_.listen(header, goog.events.EventType.KEYDOWN, - this.onHeaderKeyDown_); - } -}; - - -/** - * Enables mouse events handling for the passed header element. - * @param {Element} header The header element. - * @private - */ -goog.ui.Zippy.prototype.enableMouseEventsHandling_ = function(header) { - if (header) { - this.mouseEventHandler_.listen(header, goog.events.EventType.CLICK, - this.onHeaderClick_); - } -}; - - -/** - * KeyDown event handler for header element. Enter and space toggles expanded - * state. - * - * @param {goog.events.BrowserEvent} event KeyDown event. - * @private - */ -goog.ui.Zippy.prototype.onHeaderKeyDown_ = function(event) { - if (event.keyCode == goog.events.KeyCodes.ENTER || - event.keyCode == goog.events.KeyCodes.SPACE) { - - this.toggle(); - this.dispatchActionEvent_(); - - // Prevent enter key from submitting form. - event.preventDefault(); - - event.stopPropagation(); - } -}; - - -/** - * Click event handler for header element. - * - * @param {goog.events.BrowserEvent} event Click event. - * @private - */ -goog.ui.Zippy.prototype.onHeaderClick_ = function(event) { - this.toggle(); - this.dispatchActionEvent_(); -}; - - -/** - * Dispatch an ACTION event whenever there is user interaction with the header. - * Please note that after the zippy state change is completed a TOGGLE event - * will be dispatched. However, the TOGGLE event is dispatch on every toggle, - * including programmatic call to {@code #toggle}. - * @private - */ -goog.ui.Zippy.prototype.dispatchActionEvent_ = function() { - this.dispatchEvent(new goog.events.Event(goog.ui.Zippy.Events.ACTION, this)); -}; - - - -/** - * Object representing a zippy toggle event. - * - * @param {string} type Event type. - * @param {goog.ui.Zippy} target Zippy widget initiating event. - * @param {boolean} expanded Expanded state. - * @extends {goog.events.Event} - * @constructor - */ -goog.ui.ZippyEvent = function(type, target, expanded) { - goog.events.Event.call(this, type, target); - - /** - * The expanded state. - * @type {boolean} - */ - this.expanded = expanded; -}; -goog.inherits(goog.ui.ZippyEvent, goog.events.Event); diff --git a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/zippy_test.html.svn-base b/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/zippy_test.html.svn-base deleted file mode 100644 index 9c92e68..0000000 --- a/contexts/data/lib/closure-library/closure/goog/ui/.svn/text-base/zippy_test.html.svn-base +++ /dev/null @@ -1,285 +0,0 @@ -<!DOCTYPE html> -<html> -<!-- -Copyright 2008 The Closure Library Authors. All Rights Reserved. - -Use of this source code is governed by the Apache License, Version 2.0. -See the COPYING file for details. ---> -<!-- ---> -<head> -<meta http-equiv="X-UA-Compatible" content="IE=edge"> - <title>Closure Unit Tests - goog.ui.Zippy</title> - <script src="../base.js"></script> - <script> - goog.require('goog.dom'); - goog.require('goog.dom.a11y'); - goog.require('goog.dom.a11y.State'); - goog.require('goog.dom.classes'); - goog.require('goog.events'); - goog.require('goog.object'); - goog.require('goog.testing.events'); - goog.require('goog.testing.jsunit'); - goog.require('goog.ui.Zippy'); - goog.require('goog.ui.ZippyEvent'); - goog.require('goog.ui.Zippy.Events'); - </script> - <style type="text/css"> - - .demo { - border: solid 1px red; - margin: 0 0 20px 0; - } - - .demo h2 { - background-color: yellow; - border: solid 1px #ccc; - padding: 2px; - margin: 0; - fint-size: 100%; - } - - .demo div { - border: solid 1px #ccc; - padding: 2px; - } - - </style> -</head> -<body> - - -<div class="demo" id="d1"> - - <h2 id="t1">handler</h2> - - <div id="c1"> - sem. Suspendisse porta felis ac ipsum. Sed tincidunt dui vitae nulla. Ut - blandit. Nunc non neque. Mauris placerat. Vestibulum mollis tellus id dolor. - Phasellus ac dolor molestie nunc euismod aliquam. Mauris tellus ipsum, - fringilla id, tincidunt eu, vestibulum sit amet, metus. Quisque congue - varius - ligula. Quisque ornare mollis enim. Aliquam erat volutpat. Nulla mattis - venenatis magna. - </div> -</div> - - -<script> - - var zippy, fakeZippy1, fakeZippy2, contentlessZippy, headerlessZippy; - var lazyZippy; - var lazyZippyCallCount; - var lazyZippyContentEl; - var dualHeaderZippy; - var dualHeaderZippyCollapsedHeaderEl; - var dualHeaderZippyExpandedHeaderEl; - - function setUp() { - zippy = new goog.ui.Zippy(goog.dom.getElement('t1'), - goog.dom.getElement('c1')); - - var fakeControlEl = document.createElement('button'); - var fakeContentEl = document.createElement('div'); - - fakeZippy1 = new goog.ui.Zippy(fakeControlEl.cloneNode(true), - fakeContentEl.cloneNode(true), true); - fakeZippy2 = new goog.ui.Zippy(fakeControlEl.cloneNode(true), - fakeContentEl.cloneNode(true), false); - contentlessZippy = new goog.ui.Zippy(fakeControlEl.cloneNode(true), - undefined, true); - headerlessZippy = new goog.ui.Zippy(null, fakeContentEl.cloneNode(true), - true); - - lazyZippyCallCount = 0; - lazyZippyContentEl = fakeContentEl.cloneNode(true); - lazyZippy = new goog.ui.Zippy(goog.dom.getElement('t1'), function() { - lazyZippyCallCount++; - return lazyZippyContentEl; - }); - dualHeaderZippyCollapsedHeaderEl = fakeControlEl.cloneNode(true); - dualHeaderZippyExpandedHeaderEl = fakeControlEl.cloneNode(true); - dualHeaderZippy = new goog.ui.Zippy(dualHeaderZippyCollapsedHeaderEl, - fakeContentEl.cloneNode(true), false, dualHeaderZippyExpandedHeaderEl); - } - - function testConstructor() { - assertNotNull('must not be null', zippy); - } - - function testIsExpanded() { - assertEquals("Default expanded must be false", false, zippy.isExpanded()); - assertEquals("Expanded must be true", true, fakeZippy1.isExpanded()); - assertEquals("Expanded must be false", false, fakeZippy2.isExpanded()); - assertEquals("Expanded must be true", true, headerlessZippy.isExpanded()); - assertEquals("Expanded must be false", false, lazyZippy.isExpanded()); - assertEquals("Expanded must be false", false, dualHeaderZippy.isExpanded()); - } - - function tearDown() { - zippy.dispose(); - fakeZippy1.dispose(); - fakeZippy2.dispose(); - contentlessZippy.dispose(); - headerlessZippy.dispose(); - lazyZippy.dispose(); - dualHeaderZippy.dispose(); - } - - function testExpandCollapse() { - zippy.expand(); - headerlessZippy.expand(); - assertEquals("expanded must be true", true, zippy.isExpanded()); - assertEquals("expanded must be true", true, headerlessZippy.isExpanded()); - - zippy.collapse(); - headerlessZippy.collapse(); - assertEquals("expanded must be false", false, zippy.isExpanded()); - assertEquals("expanded must be false", false, headerlessZippy.isExpanded()); - } - - function testExpandCollapse_lazyZippy() { - assertEquals("callback should not be called #1.", 0, lazyZippyCallCount); - lazyZippy.collapse(); - assertEquals("callback should not be called #2.", 0, lazyZippyCallCount); - - lazyZippy.expand(); - assertEquals("callback should be called once #1.", 1, lazyZippyCallCount); - assertEquals("expanded must be true", true, lazyZippy.isExpanded()); - assertEquals("contentEl should be visible", "", - lazyZippyContentEl.style.display); - - lazyZippy.collapse(); - assertEquals("callback should be called once #2.", 1, lazyZippyCallCount); - assertEquals("expanded must be false", false, lazyZippy.isExpanded()); - assertEquals("contentEl should not be visible", "none", - lazyZippyContentEl.style.display); - - lazyZippy.expand(); - assertEquals("callback should be called once #3.", 1, lazyZippyCallCount); - assertEquals("expanded must be true #2", true, lazyZippy.isExpanded()); - assertEquals("contentEl should be visible #2", "", - lazyZippyContentEl.style.display); - } - - function testExpandCollapse_dualHeaderZippy() { - dualHeaderZippy.expand(); - assertEquals("expanded must be true", true, dualHeaderZippy.isExpanded()); - assertFalse("collapsed header should not have state class name #1", - hasCollapseOrExpandClasses(dualHeaderZippyCollapsedHeaderEl)); - assertFalse("expanded header should not have state class name #1", - hasCollapseOrExpandClasses(dualHeaderZippyExpandedHeaderEl)); - - dualHeaderZippy.collapse(); - assertEquals("expanded must be false", false, dualHeaderZippy.isExpanded()); - assertFalse("collapsed header should not have state class name #2", - hasCollapseOrExpandClasses(dualHeaderZippyCollapsedHeaderEl)); - assertFalse("expanded header should not have state class name #2", - hasCollapseOrExpandClasses(dualHeaderZippyExpandedHeaderEl)); - } - - function testSetExpand() { - var expanded = !zippy.isExpanded(); - zippy.setExpanded(expanded); - assertEquals("expanded must be " + expanded, expanded, zippy.isExpanded()); - } - - function testCssClassesAndAria() { - assertTrue('goog-zippy-header is enabled', - goog.dom.classes.has(zippy.elHeader_, 'goog-zippy-header')); - assertEquals('header aria-expanded is false', 'false', - goog.dom.a11y.getState(zippy.elHeader_, 'expanded')); - zippy.setExpanded(true); - assertTrue('goog-zippy-content is enabled', - goog.dom.classes.has(zippy.getContentElement(), 'goog-zippy-content')); - assertEquals('header aria role is TAB', 'tab', - goog.dom.a11y.getRole(zippy.elHeader_)); - assertEquals('header aria-expanded is true', 'true', - goog.dom.a11y.getState(zippy.elHeader_, 'expanded')); - } - - function testHeaderTabIndex() { - assertEquals('Header tabIndex is 0', 0, zippy.elHeader_.tabIndex); - } - - function testGetVisibleHeaderElement() { - dualHeaderZippy.setExpanded(false); - assertEquals(dualHeaderZippyCollapsedHeaderEl, - dualHeaderZippy.getVisibleHeaderElement()); - dualHeaderZippy.setExpanded(true); - assertEquals(dualHeaderZippyExpandedHeaderEl, - dualHeaderZippy.getVisibleHeaderElement()) - } - - function testToggle() { - var expanded = !zippy.isExpanded(); - zippy.toggle(); - assertEquals("expanded must be " + expanded, expanded, zippy.isExpanded()); - } - - function testCustomEventTOGGLE() { - var dispatchedActionCount; - var handleAction = function() { - dispatchedActionCount++; - }; - - var doTest = function (zippyObj) { - dispatchedActionCount = 0; - goog.events.listen(zippyObj, goog.ui.Zippy.Events.TOGGLE, handleAction); - zippy.toggle(); - assertEquals("Custom Event must be called ", 1, dispatchedActionCount); - }; - - doTest(zippy); - doTest(fakeZippy1); - doTest(contentlessZippy); - doTest(headerlessZippy); - } - - function testActionEvent() { - var actionEventCount = 0; - var toggleEventCount = 0; - var handleEvent = function(e) { - if (e.type == goog.ui.Zippy.Events.TOGGLE) { - toggleEventCount++; - } else if (e.type == goog.ui.Zippy.Events.ACTION) { - actionEventCount++; - assertTrue('toggle must have been called first', - toggleEventCount >= actionEventCount); - } - }; - goog.events.listen(zippy, goog.object.getValues(goog.ui.Zippy.Events), - handleEvent); - goog.testing.events.fireClickSequence(zippy.elHeader_); - assertEquals('Zippy ACTION event fired', 1, actionEventCount); - assertEquals('Zippy TOGGLE event fired', 1, toggleEventCount); - - zippy.toggle(); - assertEquals('Zippy ACTION event NOT fired', 1, actionEventCount); - assertEquals('Zippy TOGGLE event fired', 2, toggleEventCount); - } - - function testBasicZippyBehavior() { - var dispatchedActionCount = 0; - var handleAction = function() { - dispatchedActionCount++; - }; - - goog.events.listen(zippy, goog.ui.Zippy.Events.TOGGLE, handleAction); - goog.testing.events.fireClickSequence(zippy.elHeader_); - assertEquals('Zippy must have dispatched TOGGLE on click', 1, - dispatchedActionCount); - - } - - function hasCollapseOrExpandClasses(el) { - var isCollapsed = goog.dom.classes.has(el, 'goog-zippy-collapsed'); - var isExpanded = goog.dom.classes.has(el, 'goog-zippy-expanded'); - return isCollapsed || isExpanded; - } - -</script> - -</body> -</html> |