code
stringlengths
1
2.08M
language
stringclasses
1 value
// 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.a11y.aria.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.a11y.aria.Role} ARIA role. * @override */ goog.ui.TabBarRenderer.prototype.getAriaRole = function() { return goog.a11y.aria.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_); };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A class for representing 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); });
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Renderer for {@link goog.ui.Palette}s. * * @author attila@google.com (Attila Bodis) */ goog.provide('goog.ui.PaletteRenderer'); goog.require('goog.a11y.aria'); goog.require('goog.a11y.aria.State'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.dom.NodeIterator'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.classes'); goog.require('goog.iter'); 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.Control} palette goog.ui.Palette to render. * @return {Element} Root element for the palette. * @override */ 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.a11y.aria.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) { var row = dom.createDom('tr', goog.getCssName(this.getCssClass(), 'row'), cells); goog.a11y.aria.setRole(row, 'row'); return row; }; /** * 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.a11y.aria.setRole(cell, 'gridcell'); if (!goog.dom.getTextContent(cell) && !goog.a11y.aria.getLabel(cell)) { goog.a11y.aria.setLabel(cell, this.findAriaLabelForCell_(cell)); } return cell; }; /** * Descends the DOM and tries to find an aria label for a grid cell * from the first child with a label or title. * @param {!Element} cell The cell. * @return {string} The label to use. * @private */ goog.ui.PaletteRenderer.prototype.findAriaLabelForCell_ = function(cell) { var iter = new goog.dom.NodeIterator(cell); var label = ''; var node; while (!label && (node = goog.iter.nextOrValue(iter, null))) { if (node.nodeType == goog.dom.NodeType.ELEMENT) { label = goog.a11y.aria.getLabel(/** @type {!Element} */ (node)) || node.title; } } return label; }; /** * 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). * @override */ 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.Control} palette Ignored. * @param {Element} element Ignored. * @return {null} Always null. * @override */ 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 {goog.ui.ControlContent} content Array of items to replace existing * palette items. * @override */ goog.ui.PaletteRenderer.prototype.setContent = function(element, content) { var items = /** @type {Array.<Node>} */ (content); 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 = this.getCellForItem(node); 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.a11y.aria.setState(table, goog.a11y.aria.State.ACTIVEDESCENDANT, cell.id); } }; /** * @param {Node} node Item whose cell is to be returned. * @return {Element} The grid cell for the palette item. */ goog.ui.PaletteRenderer.prototype.getCellForItem = function(node) { return /** @type {Element} */ (node ? node.parentNode : null); }; /** * 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. * @override */ goog.ui.PaletteRenderer.prototype.getCssClass = function() { return goog.ui.PaletteRenderer.CSS_CLASS; };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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.a11y.aria'); goog.require('goog.a11y.aria.State'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.classlist'); 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; /** * The label restore delay after leaving the input. * @type {number} Delay for restoring the label. * @protected */ goog.ui.LabelInput.prototype.labelRestoreDelayMs = 10; /** * 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. * @override */ 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 {Element} element The HTML input element to decorate. * @override */ 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; var el = this.getElement(); goog.asserts.assert(el); goog.dom.classlist.remove(el, this.LABEL_CLASS_NAME); } if (goog.ui.LabelInput.SUPPORTS_PLACEHOLDER_) { this.getElement().placeholder = this.label_; return; } var labelInputElement = this.getElement(); goog.asserts.assert(labelInputElement, 'The label input element cannot be null.'); goog.a11y.aria.setState(labelInputElement, goog.a11y.aria.State.LABEL, this.label_); }; /** @override */ 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; }; /** @override */ 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; var el = this.getElement(); goog.asserts.assert(el); goog.dom.classlist.remove(el, this.LABEL_CLASS_NAME); if (goog.ui.LabelInput.SUPPORTS_PLACEHOLDER_) { return; } if (!this.hasChanged() && !this.inFocusAndSelect_) { var me = this; var clearValue = function() { // Component could be disposed by the time this is called. if (me.getElement()) { 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_(); var labelInputElement = this.getElement(); // Check if this has been called before DOM structure building if (labelInputElement) { goog.a11y.aria.setState(labelInputElement, goog.a11y.aria.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() { var labelInputElement = this.getElement(); goog.asserts.assert(labelInputElement, 'The label input element cannot be null.'); if (!goog.ui.LabelInput.SUPPORTS_PLACEHOLDER_) { // if we haven't got a form yet try now this.attachEventsToForm_(); goog.a11y.aria.setState(labelInputElement, goog.a11y.aria.State.LABEL, this.label_); } else if (this.getElement().placeholder != this.label_) { this.getElement().placeholder = this.label_; } if (!this.hasChanged()) { if (!this.inFocusAndSelect_ && !this.hasFocus_) { var el = this.getElement(); goog.asserts.assert(el); goog.dom.classlist.add(el, 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_, this.labelRestoreDelayMs, this); } } else { var el = this.getElement(); goog.asserts.assert(el); goog.dom.classlist.remove(el, 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; var el = this.getElement(); goog.asserts.assert(el); goog.dom.classlist.enable(el, 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_; } };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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.setElementShown(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. * @override */ 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); };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Renderer for 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. * @override */ goog.ui.ToolbarButtonRenderer.prototype.getCssClass = function() { return goog.ui.ToolbarButtonRenderer.CSS_CLASS; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A menu item class that supports selection state. * * @author attila@google.com (Attila Bodis) */ goog.provide('goog.ui.Option'); goog.require('goog.ui.Component'); 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. * @override */ 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); });
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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_ = 1; /** * Currently highlighted column count. * @type {number} * @private */ goog.ui.DimensionPicker.prototype.highlightedColumns_ = 1; /** @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(1, 1); } }; /** @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); 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. * @override */ goog.ui.DimensionPicker.prototype.handleKeyEvent = function(e) { var rows = this.highlightedRows_; var columns = this.highlightedColumns_; switch (e.keyCode) { case goog.events.KeyCodes.DOWN: rows++; break; case goog.events.KeyCodes.UP: rows--; break; case goog.events.KeyCodes.LEFT: if (columns == 1) { // Delegate to parent. return false; } else { columns--; } break; case goog.events.KeyCodes.RIGHT: columns++; 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. If the dimensions are not valid * (not between 1 and the maximum number of columns/rows to show), they will * be changed to the closest valid value. * @param {(number|!goog.math.Size)} 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)) { columns = /** @type {!goog.math.Size} */ (columns); opt_rows = columns.height; columns = columns.width; } else { columns = /** @type {number} */ (columns); } // Ensure that the row and column values are within the minimum value (1) and // maxmimum values. columns = Math.max(1, columns); opt_rows = Math.max(1, opt_rows); columns = Math.min(this.maxColumns, columns); opt_rows = Math.min(this.maxRows, opt_rows); 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(); });
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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.setElementShown(this.getElement(), true); } goog.style.setPageOffset(this.getElement(), x, opt_y); if (!visible) { goog.style.setElementShown(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; }; /** @override */ goog.ui.Menu.prototype.setHighlightedIndex = function(index) { goog.base(this, 'setHighlightedIndex', index); // Bring the highlighted item into view. This has no effect if the menu is not // scrollable. var child = this.getChildAt(index); if (child) { goog.style.scrollIntoContainerView(child.getElement(), this.getElement()); } }; /** * 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]); } };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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. * @override */ 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. * @override */ 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. * @override */ 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. * @override */ 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. * @override */ 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_; };
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview An 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.Control} control goog.ui.Button to render. * @return {Element} Root element for the button. * @override */ goog.ui.Css3ButtonRenderer.prototype.createDom = function(control) { var button = /** @type {goog.ui.Button} */ (control); 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. * @override */ 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; });
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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. * @override */ 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(); } };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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.Component} 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(); });
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview SpriteInfo implementation. This is a simple wrapper class to * hold CSS metadata needed for sprited emoji. * * @see ../demos/popupemojipicker.html or emojipicker_test.html for examples * of how to use this class. * */ goog.provide('goog.ui.emoji.SpriteInfo'); /** * Creates a SpriteInfo object with the specified properties. If the image is * sprited via CSS, then only the first parameter needs a value. If the image * is sprited via metadata, then the first parameter should be left null. * * @param {?string} cssClass CSS class to properly display the sprited image. * @param {string=} opt_url Url of the sprite image. * @param {number=} opt_width Width of the image being sprited. * @param {number=} opt_height Height of the image being sprited. * @param {number=} opt_xOffset Positive x offset of the image being sprited * within the sprite. * @param {number=} opt_yOffset Positive y offset of the image being sprited * within the sprite. * @param {boolean=} opt_animated Whether the sprite is animated. * @constructor */ goog.ui.emoji.SpriteInfo = function(cssClass, opt_url, opt_width, opt_height, opt_xOffset, opt_yOffset, opt_animated) { if (cssClass != null) { this.cssClass_ = cssClass; } else { if (opt_url == undefined || opt_width === undefined || opt_height === undefined || opt_xOffset == undefined || opt_yOffset === undefined) { throw Error('Sprite info is not fully specified'); } this.url_ = opt_url; this.width_ = opt_width; this.height_ = opt_height; this.xOffset_ = opt_xOffset; this.yOffset_ = opt_yOffset; } this.animated_ = !!opt_animated; }; /** * Name of the CSS class to properly display the sprited image. * @type {string} * @private */ goog.ui.emoji.SpriteInfo.prototype.cssClass_; /** * Url of the sprite image. * @type {string|undefined} * @private */ goog.ui.emoji.SpriteInfo.prototype.url_; /** * Width of the image being sprited. * @type {number|undefined} * @private */ goog.ui.emoji.SpriteInfo.prototype.width_; /** * Height of the image being sprited. * @type {number|undefined} * @private */ goog.ui.emoji.SpriteInfo.prototype.height_; /** * Positive x offset of the image being sprited within the sprite. * @type {number|undefined} * @private */ goog.ui.emoji.SpriteInfo.prototype.xOffset_; /** * Positive y offset of the image being sprited within the sprite. * @type {number|undefined} * @private */ goog.ui.emoji.SpriteInfo.prototype.yOffset_; /** * Whether the emoji specified by the sprite is animated. * @type {boolean} * @private */ goog.ui.emoji.SpriteInfo.prototype.animated_; /** * Returns the css class of the sprited image. * @return {?string} Name of the CSS class to properly display the sprited * image. */ goog.ui.emoji.SpriteInfo.prototype.getCssClass = function() { return this.cssClass_ || null; }; /** * Returns the url of the sprite image. * @return {?string} Url of the sprite image. */ goog.ui.emoji.SpriteInfo.prototype.getUrl = function() { return this.url_ || null; }; /** * Returns whether the emoji specified by this sprite is animated. * @return {boolean} Whether the emoji is animated. */ goog.ui.emoji.SpriteInfo.prototype.isAnimated = function() { return this.animated_; }; /** * Returns the width of the image being sprited, appropriate for a CSS value. * @return {string} The width of the image being sprited. */ goog.ui.emoji.SpriteInfo.prototype.getWidthCssValue = function() { return goog.ui.emoji.SpriteInfo.getCssPixelValue_(this.width_); }; /** * Returns the height of the image being sprited, appropriate for a CSS value. * @return {string} The height of the image being sprited. */ goog.ui.emoji.SpriteInfo.prototype.getHeightCssValue = function() { return goog.ui.emoji.SpriteInfo.getCssPixelValue_(this.height_); }; /** * Returns the x offset of the image being sprited within the sprite, * appropriate for a CSS value. * @return {string} The x offset of the image being sprited within the sprite. */ goog.ui.emoji.SpriteInfo.prototype.getXOffsetCssValue = function() { return goog.ui.emoji.SpriteInfo.getOffsetCssValue_(this.xOffset_); }; /** * Returns the positive y offset of the image being sprited within the sprite, * appropriate for a CSS value. * @return {string} The y offset of the image being sprited within the sprite. */ goog.ui.emoji.SpriteInfo.prototype.getYOffsetCssValue = function() { return goog.ui.emoji.SpriteInfo.getOffsetCssValue_(this.yOffset_); }; /** * Returns a string appropriate for use as a CSS value. If the value is zero, * then there is no unit appended. * * @param {number|undefined} value A number to be turned into a * CSS size/location value. * @return {string} A string appropriate for use as a CSS value. * @private */ goog.ui.emoji.SpriteInfo.getCssPixelValue_ = function(value) { return !value ? '0' : value + 'px'; }; /** * Returns a string appropriate for use as a CSS value for a position offset, * such as the position argument for sprites. * * @param {number|undefined} posOffset A positive offset for a position. * @return {string} A string appropriate for use as a CSS value. * @private */ goog.ui.emoji.SpriteInfo.getOffsetCssValue_ = function(posOffset) { var offset = goog.ui.emoji.SpriteInfo.getCssPixelValue_(posOffset); return offset == '0' ? offset : '-' + offset; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Emoji Palette implementation. This provides a UI widget for * choosing an emoji from a palette of possible choices. EmojiPalettes are * contained within EmojiPickers. * * See ../demos/popupemojipicker.html for an example of how to instantiate * an emoji picker. * * Based on goog.ui.ColorPicker (colorpicker.js). * */ goog.provide('goog.ui.emoji.EmojiPalette'); goog.require('goog.events.Event'); goog.require('goog.events.EventType'); goog.require('goog.net.ImageLoader'); goog.require('goog.ui.Palette'); goog.require('goog.ui.emoji.Emoji'); goog.require('goog.ui.emoji.EmojiPaletteRenderer'); /** * A page of emoji to be displayed in an EmojiPicker. * * @param {Array.<Array>} emoji List of emoji for this page. * @param {?string=} opt_urlPrefix Prefix that should be prepended to all URL. * @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. * @extends {goog.ui.Palette} * @constructor */ goog.ui.emoji.EmojiPalette = function(emoji, opt_urlPrefix, opt_renderer, opt_domHelper) { goog.ui.Palette.call(this, null, opt_renderer || new goog.ui.emoji.EmojiPaletteRenderer(null), opt_domHelper); /** * All the different emoji that this palette can display. Maps emoji ids * (string) to the goog.ui.emoji.Emoji for that id. * * @type {Object} * @private */ this.emojiCells_ = {}; /** * Map of emoji id to index into this.emojiCells_. * * @type {Object} * @private */ this.emojiMap_ = {}; /** * List of the animated emoji in this palette. Each internal array is of type * [HTMLDivElement, goog.ui.emoji.Emoji], and represents the palette item * for that animated emoji, and the Emoji object. * * @type {Array.<Array.<(HTMLDivElement|goog.ui.emoji.Emoji)>>} * @private */ this.animatedEmoji_ = []; this.urlPrefix_ = opt_urlPrefix || ''; /** * Palette items that are displayed on this page of the emoji picker. Each * item is a div wrapped around a div or an img. * * @type {Array.<HTMLDivElement>} * @private */ this.emoji_ = this.getEmojiArrayFromProperties_(emoji); this.setContent(this.emoji_); }; goog.inherits(goog.ui.emoji.EmojiPalette, goog.ui.Palette); /** * Indicates a prefix that should be prepended to all URLs of images in this * emojipalette. This provides an optimization if the URLs are long, so that * the client does not have to send a long string for each emoji. * * @type {string} * @private */ goog.ui.emoji.EmojiPalette.prototype.urlPrefix_ = ''; /** * Whether the emoji images have been loaded. * * @type {boolean} * @private */ goog.ui.emoji.EmojiPalette.prototype.imagesLoaded_ = false; /** * Image loader for loading animated emoji. * * @type {goog.net.ImageLoader} * @private */ goog.ui.emoji.EmojiPalette.prototype.imageLoader_; /** * Helps create an array of emoji palette items from an array of emoji * properties. Each element will be either a div with background-image set to * a sprite, or an img element pointing directly to an emoji, and all elements * are wrapped with an outer div for alignment issues (i.e., this allows * centering the inner div). * * @param {Object} emojiGroup The group of emoji for this page. * @return {Array.<HTMLDivElement>} The emoji items. * @private */ goog.ui.emoji.EmojiPalette.prototype.getEmojiArrayFromProperties_ = function(emojiGroup) { var emojiItems = []; for (var i = 0; i < emojiGroup.length; i++) { var url = emojiGroup[i][0]; var id = emojiGroup[i][1]; var spriteInfo = emojiGroup[i][2]; var displayUrl = spriteInfo ? spriteInfo.getUrl() : this.urlPrefix_ + url; var item = this.getRenderer().createPaletteItem( this.getDomHelper(), id, spriteInfo, displayUrl); emojiItems.push(item); var emoji = new goog.ui.emoji.Emoji(url, id); this.emojiCells_[id] = emoji; this.emojiMap_[id] = i; // Keep track of sprited emoji that are animated, for later loading. if (spriteInfo && spriteInfo.isAnimated()) { this.animatedEmoji_.push([item, emoji]); } } // Create the image loader now so that tests can access it before it has // started loading images. if (this.animatedEmoji_.length > 0) { this.imageLoader_ = new goog.net.ImageLoader(); } this.imagesLoaded_ = true; return emojiItems; }; /** * Sends off requests for all the animated emoji and replaces their static * sprites when the images are done downloading. */ goog.ui.emoji.EmojiPalette.prototype.loadAnimatedEmoji = function() { if (this.animatedEmoji_.length > 0) { for (var i = 0; i < this.animatedEmoji_.length; i++) { var paletteItem = /** @type {Element} */ (this.animatedEmoji_[i][0]); var emoji = /** @type {goog.ui.emoji.Emoji} */ (this.animatedEmoji_[i][1]); var url = this.urlPrefix_ + emoji.getUrl(); this.imageLoader_.addImage(emoji.getId(), url); } this.getHandler().listen(this.imageLoader_, goog.events.EventType.LOAD, this.handleImageLoad_); this.imageLoader_.start(); } }; /** * Handles image load events from the ImageLoader. * * @param {goog.events.Event} e The event object. * @private */ goog.ui.emoji.EmojiPalette.prototype.handleImageLoad_ = function(e) { var id = e.target.id; var url = e.target.src; // Just to be safe, we check to make sure we have an id and src url from // the event target, which the ImageLoader sets to an Image object. if (id && url) { var item = this.emoji_[this.emojiMap_[id]]; if (item) { this.getRenderer().updateAnimatedPaletteItem(item, e.target); } } }; /** * Returns the image loader that this palette uses. Used for testing. * * @return {goog.net.ImageLoader} the image loader. */ goog.ui.emoji.EmojiPalette.prototype.getImageLoader = function() { return this.imageLoader_; }; /** @override */ goog.ui.emoji.EmojiPalette.prototype.disposeInternal = function() { goog.ui.emoji.EmojiPalette.superClass_.disposeInternal.call(this); if (this.imageLoader_) { this.imageLoader_.dispose(); this.imageLoader_ = null; } this.animatedEmoji_ = null; this.emojiCells_ = null; this.emojiMap_ = null; this.emoji_ = null; }; /** * Returns a goomoji id from an img or the containing td, or null if none * exists for that element. * * @param {Element} el The element to get the Goomoji id from. * @return {?string} A goomoji id from an img or the containing td, or null if * none exists for that element. * @private */ goog.ui.emoji.EmojiPalette.prototype.getGoomojiIdFromElement_ = function(el) { if (!el) { return null; } var item = this.getRenderer().getContainingItem(this, el); return item ? item.getAttribute(goog.ui.emoji.Emoji.ATTRIBUTE) : null; }; /** * @return {goog.ui.emoji.Emoji} The currently selected emoji from this palette. */ goog.ui.emoji.EmojiPalette.prototype.getSelectedEmoji = function() { var elem = /** @type {Element} */ (this.getSelectedItem()); var goomojiId = this.getGoomojiIdFromElement_(elem); return this.emojiCells_[goomojiId]; }; /** * @return {number} The number of emoji managed by this palette. */ goog.ui.emoji.EmojiPalette.prototype.getNumberOfEmoji = function() { return this.emojiCells_.length; }; /** * Returns the index of the specified emoji within this palette. * * @param {string} id Id of the emoji to look up. * @return {number} The index of the specified emoji within this palette. */ goog.ui.emoji.EmojiPalette.prototype.getEmojiIndex = function(id) { return this.emojiMap_[id]; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Emoji implementation. * */ goog.provide('goog.ui.emoji.Emoji'); /** * Creates an emoji. * * A simple wrapper for an emoji. * * @param {string} url URL pointing to the source image for the emoji. * @param {string} id The id of the emoji, e.g., 'std.1'. * @constructor */ goog.ui.emoji.Emoji = function(url, id) { /** * The URL pointing to the source image for the emoji * * @type {string} * @private */ this.url_ = url; /** * The id of the emoji * * @type {string} * @private */ this.id_ = id; }; /** * The name of the goomoji attribute, used for emoji image elements. * @type {string} */ goog.ui.emoji.Emoji.ATTRIBUTE = 'goomoji'; /** * @return {string} The URL for this emoji. */ goog.ui.emoji.Emoji.prototype.getUrl = function() { return this.url_; }; /** * @return {string} The id of this emoji. */ goog.ui.emoji.Emoji.prototype.getId = function() { return this.id_; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Emoji Picker implementation. This provides a UI widget for * choosing an emoji from a grid of possible choices. * * @see ../demos/popupemojipicker.html for an example of how to instantiate * an emoji picker. * * Based on goog.ui.ColorPicker (colorpicker.js). * * @see ../../demos/popupemojipicker.html */ goog.provide('goog.ui.emoji.EmojiPicker'); goog.require('goog.debug.Logger'); goog.require('goog.dom'); goog.require('goog.ui.Component'); goog.require('goog.ui.TabPane'); goog.require('goog.ui.TabPane.TabPage'); goog.require('goog.ui.emoji.Emoji'); goog.require('goog.ui.emoji.EmojiPalette'); goog.require('goog.ui.emoji.EmojiPaletteRenderer'); goog.require('goog.ui.emoji.ProgressiveEmojiPaletteRenderer'); /** * Creates a new, empty emoji picker. An emoji picker is a grid of emoji, each * cell of the grid containing a single emoji. The picker may contain multiple * pages of emoji. * * When a user selects an emoji, by either clicking or pressing enter, the * picker fires a goog.ui.Component.EventType.ACTION event with the id. The * client listens on this event and in the handler can retrieve the id of the * selected emoji and do something with it, for instance, inserting an image * tag into a rich text control. An emoji picker does not maintain state. That * is, once an emoji is selected, the emoji picker does not remember which emoji * was selected. * * The emoji picker is implemented as a tabpane with each tabpage being a table. * Each of the tables are the same size to prevent jittering when switching * between pages. * * @param {string} defaultImgUrl Url of the img that should be used to fill up * the cells in the emoji table, to prevent jittering. Should be the same * size as the emoji. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. * @extends {goog.ui.Component} * @constructor */ goog.ui.emoji.EmojiPicker = function(defaultImgUrl, opt_domHelper) { goog.ui.Component.call(this, opt_domHelper); this.defaultImgUrl_ = defaultImgUrl; /** * Emoji that this picker displays. * * @type {Array.<Object>} * @private */ this.emoji_ = []; /** * Pages of this emoji picker. * * @type {Array.<goog.ui.emoji.EmojiPalette>} * @private */ this.pages_ = []; /** * Keeps track of which pages in the picker have been loaded. Used for delayed * loading of tabs. * * @type {Array.<boolean>} * @private */ this.pageLoadStatus_ = []; /** * Tabpane to hold the pages of this emojipicker. * * @type {goog.ui.TabPane} * @private */ this.tabPane_ = null; this.getHandler().listen(this, goog.ui.Component.EventType.ACTION, this.onEmojiPaletteAction_); }; goog.inherits(goog.ui.emoji.EmojiPicker, goog.ui.Component); /** * Default number of rows per grid of emoji. * * @type {number} */ goog.ui.emoji.EmojiPicker.DEFAULT_NUM_ROWS = 5; /** * Default number of columns per grid of emoji. * * @type {number} */ goog.ui.emoji.EmojiPicker.DEFAULT_NUM_COLS = 10; /** * Default location of the tabs in relation to the emoji grids. * * @type {goog.ui.TabPane.TabLocation} */ goog.ui.emoji.EmojiPicker.DEFAULT_TAB_LOCATION = goog.ui.TabPane.TabLocation.TOP; /** * Number of rows per grid of emoji. * * @type {number} * @private */ goog.ui.emoji.EmojiPicker.prototype.numRows_ = goog.ui.emoji.EmojiPicker.DEFAULT_NUM_ROWS; /** * Number of columns per grid of emoji. * * @type {number} * @private */ goog.ui.emoji.EmojiPicker.prototype.numCols_ = goog.ui.emoji.EmojiPicker.DEFAULT_NUM_COLS; /** * Whether the number of rows in the picker should be automatically determined * by the specified number of columns so as to minimize/eliminate jitter when * switching between tabs. * * @type {boolean} * @private */ goog.ui.emoji.EmojiPicker.prototype.autoSizeByColumnCount_ = true; /** * Location of the tabs for the picker tabpane. * * @type {goog.ui.TabPane.TabLocation} * @private */ goog.ui.emoji.EmojiPicker.prototype.tabLocation_ = goog.ui.emoji.EmojiPicker.DEFAULT_TAB_LOCATION; /** * Whether the component is focusable. * @type {boolean} * @private */ goog.ui.emoji.EmojiPicker.prototype.focusable_ = true; /** * Url of the img that should be used for cells in the emoji picker that are * not filled with emoji, i.e., after all the emoji have already been placed * on a page. * * @type {string} * @private */ goog.ui.emoji.EmojiPicker.prototype.defaultImgUrl_; /** * If present, indicates a prefix that should be prepended to all URLs * of images in this emojipicker. This provides an optimization if the URLs * are long, so that the client does not have to send a long string for each * emoji. * * @type {string|undefined} * @private */ goog.ui.emoji.EmojiPicker.prototype.urlPrefix_; /** * If true, delay loading the images for the emojipalettes until after * construction. This gives a better user experience before the images are in * the cache, since other widgets waiting for construction of the emojipalettes * won't have to wait for all the images (which may be a substantial amount) to * load. * * @type {boolean} * @private */ goog.ui.emoji.EmojiPicker.prototype.delayedLoad_ = false; /** * Whether to use progressive rendering in the emojipicker's palette, if using * sprited imgs. If true, then uses img tags, which most browsers render * progressively (i.e., as the data comes in). If false, then uses div tags * with the background-image, which some newer browsers render progressively * but older ones do not. * * @type {boolean} * @private */ goog.ui.emoji.EmojiPicker.prototype.progressiveRender_ = false; /** * Whether to require the caller to manually specify when to start loading * animated emoji. This is primarily for unittests to be able to test the * structure of the emojipicker palettes before and after the animated emoji * have been loaded. * * @type {boolean} * @private */ goog.ui.emoji.EmojiPicker.prototype.manualLoadOfAnimatedEmoji_ = false; /** * Index of the active page in the picker. * * @type {number} * @private */ goog.ui.emoji.EmojiPicker.prototype.activePage_ = -1; /** * Adds a group of emoji to the picker. * * @param {string|Element} title Title for the group. * @param {Array.<Array.<string>>} emojiGroup A new group of emoji to be added * Each internal array contains [emojiUrl, emojiId]. */ goog.ui.emoji.EmojiPicker.prototype.addEmojiGroup = function(title, emojiGroup) { this.emoji_.push({title: title, emoji: emojiGroup}); }; /** * Gets the number of rows per grid in the emoji picker. * * @return {number} number of rows per grid. */ goog.ui.emoji.EmojiPicker.prototype.getNumRows = function() { return this.numRows_; }; /** * Gets the number of columns per grid in the emoji picker. * * @return {number} number of columns per grid. */ goog.ui.emoji.EmojiPicker.prototype.getNumColumns = function() { return this.numCols_; }; /** * Sets the number of rows per grid in the emoji picker. This should only be * called before the picker has been rendered. * * @param {number} numRows Number of rows per grid. */ goog.ui.emoji.EmojiPicker.prototype.setNumRows = function(numRows) { this.numRows_ = numRows; }; /** * Sets the number of columns per grid in the emoji picker. This should only be * called before the picker has been rendered. * * @param {number} numCols Number of columns per grid. */ goog.ui.emoji.EmojiPicker.prototype.setNumColumns = function(numCols) { this.numCols_ = numCols; }; /** * Sets whether to automatically size the emojipicker based on the number of * columns and the number of emoji in each group, so as to reduce jitter. * * @param {boolean} autoSize Whether to automatically size the picker. */ goog.ui.emoji.EmojiPicker.prototype.setAutoSizeByColumnCount = function(autoSize) { this.autoSizeByColumnCount_ = autoSize; }; /** * Sets the location of the tabs in relation to the emoji grids. This should * only be called before the picker has been rendered. * * @param {goog.ui.TabPane.TabLocation} tabLocation The location of the tabs. */ goog.ui.emoji.EmojiPicker.prototype.setTabLocation = function(tabLocation) { this.tabLocation_ = tabLocation; }; /** * Sets whether loading of images should be delayed until after dom creation. * Thus, this function must be called before {@link #createDom}. If set to true, * the client must call {@link #loadImages} when they wish the images to be * loaded. * * @param {boolean} shouldDelay Whether to delay loading the images. */ goog.ui.emoji.EmojiPicker.prototype.setDelayedLoad = function(shouldDelay) { this.delayedLoad_ = shouldDelay; }; /** * Sets whether to require the caller to manually specify when to start loading * animated emoji. This is primarily for unittests to be able to test the * structure of the emojipicker palettes before and after the animated emoji * have been loaded. This only affects sprited emojipickers with sprite data * for animated emoji. * * @param {boolean} manual Whether to load animated emoji manually. */ goog.ui.emoji.EmojiPicker.prototype.setManualLoadOfAnimatedEmoji = function(manual) { this.manualLoadOfAnimatedEmoji_ = manual; }; /** * 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} Whether the component is focusable. */ goog.ui.emoji.EmojiPicker.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 Whether the component is focusable. */ goog.ui.emoji.EmojiPicker.prototype.setFocusable = function(focusable) { this.focusable_ = focusable; for (var i = 0; i < this.pages_.length; i++) { if (this.pages_[i]) { this.pages_[i].setSupportedState(goog.ui.Component.State.FOCUSED, focusable); } } }; /** * Sets the URL prefix for the emoji URLs. * * @param {string} urlPrefix Prefix that should be prepended to all URLs. */ goog.ui.emoji.EmojiPicker.prototype.setUrlPrefix = function(urlPrefix) { this.urlPrefix_ = urlPrefix; }; /** * Sets the progressive rendering aspect of this emojipicker. Must be called * before createDom to have an effect. * * @param {boolean} progressive Whether this picker should render progressively. */ goog.ui.emoji.EmojiPicker.prototype.setProgressiveRender = function(progressive) { this.progressiveRender_ = progressive; }; /** * Logger for the emoji picker. * * @type {goog.debug.Logger} * @private */ goog.ui.emoji.EmojiPicker.prototype.logger_ = goog.debug.Logger.getLogger('goog.ui.emoji.EmojiPicker'); /** * Adjusts the number of rows to be the maximum row count out of all the emoji * groups, in order to prevent jitter in switching among the tabs. * * @private */ goog.ui.emoji.EmojiPicker.prototype.adjustNumRowsIfNecessary_ = function() { var currentMax = 0; for (var i = 0; i < this.emoji_.length; i++) { var numEmoji = this.emoji_[i].emoji.length; var rowsNeeded = Math.ceil(numEmoji / this.numCols_); if (rowsNeeded > currentMax) { currentMax = rowsNeeded; } } this.setNumRows(currentMax); }; /** * Causes the emoji imgs to be loaded into the picker. Used for delayed loading. * No-op if delayed loading is not set. */ goog.ui.emoji.EmojiPicker.prototype.loadImages = function() { if (!this.delayedLoad_) { return; } // Load the first page only this.loadPage_(0); this.activePage_ = 0; }; /** * @override * @suppress {deprecated} Using deprecated goog.ui.TabPane. */ goog.ui.emoji.EmojiPicker.prototype.createDom = function() { this.setElementInternal(this.getDomHelper().createDom('div')); if (this.autoSizeByColumnCount_) { this.adjustNumRowsIfNecessary_(); } if (this.emoji_.length == 0) { throw Error('Must add some emoji to the picker'); } // If there is more than one group of emoji, we construct a tabpane if (this.emoji_.length > 1) { // Give the tabpane a div to use as its content element, since tabpane // overwrites the CSS class of the element it's passed var div = this.getDomHelper().createDom('div'); this.getElement().appendChild(div); this.tabPane_ = new goog.ui.TabPane(div, this.tabLocation_, this.getDomHelper(), true /* use MOUSEDOWN */); } this.renderer_ = this.progressiveRender_ ? new goog.ui.emoji.ProgressiveEmojiPaletteRenderer(this.defaultImgUrl_) : new goog.ui.emoji.EmojiPaletteRenderer(this.defaultImgUrl_); for (var i = 0; i < this.emoji_.length; i++) { var emoji = this.emoji_[i].emoji; var page = this.delayedLoad_ ? this.createPlaceholderEmojiPage_(emoji) : this.createEmojiPage_(emoji, i); this.pages_.push(page); } this.activePage_ = 0; this.getElement().tabIndex = 0; }; /** * Used by unittests to manually load the animated emoji for this picker. */ goog.ui.emoji.EmojiPicker.prototype.manuallyLoadAnimatedEmoji = function() { for (var i = 0; i < this.pages_.length; i++) { this.pages_[i].loadAnimatedEmoji(); } }; /** * Creates a page if it has not already been loaded. This has the side effects * of setting the load status of the page to true. * * @param {Array.<Array.<string>>} emoji Emoji for this page. See * {@link addEmojiGroup} for more details. * @param {number} index Index of the page in the emojipicker. * @return {goog.ui.emoji.EmojiPalette} the emoji page. * @private */ goog.ui.emoji.EmojiPicker.prototype.createEmojiPage_ = function(emoji, index) { // Safeguard against trying to create the same page twice if (this.pageLoadStatus_[index]) { return null; } var palette = new goog.ui.emoji.EmojiPalette(emoji, this.urlPrefix_, this.renderer_, this.getDomHelper()); if (!this.manualLoadOfAnimatedEmoji_) { palette.loadAnimatedEmoji(); } palette.setSize(this.numCols_, this.numRows_); palette.setSupportedState(goog.ui.Component.State.FOCUSED, this.focusable_); palette.createDom(); palette.setParent(this); this.pageLoadStatus_[index] = true; return palette; }; /** * Returns an array of emoji whose real URLs have been replaced with the * default img URL. Used for delayed loading. * * @param {Array.<Array.<string>>} emoji Original emoji array. * @return {Array.<Array.<string>>} emoji array with all emoji pointing to the * default img. * @private */ goog.ui.emoji.EmojiPicker.prototype.getPlaceholderEmoji_ = function(emoji) { var placeholderEmoji = []; for (var i = 0; i < emoji.length; i++) { placeholderEmoji.push([this.defaultImgUrl_, emoji[i][1]]); } return placeholderEmoji; }; /** * Creates an emoji page using placeholder emoji pointing to the default * img instead of the real emoji. Used for delayed loading. * * @param {Array.<Array.<string>>} emoji Emoji for this page. See * {@link addEmojiGroup} for more details. * @return {goog.ui.emoji.EmojiPalette} the emoji page. * @private */ goog.ui.emoji.EmojiPicker.prototype.createPlaceholderEmojiPage_ = function(emoji) { var placeholderEmoji = this.getPlaceholderEmoji_(emoji); var palette = new goog.ui.emoji.EmojiPalette(placeholderEmoji, null, // no url prefix this.renderer_, this.getDomHelper()); palette.setSize(this.numCols_, this.numRows_); palette.setSupportedState(goog.ui.Component.State.FOCUSED, this.focusable_); palette.createDom(); palette.setParent(this); return palette; }; /** * EmojiPickers 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. * @override */ goog.ui.emoji.EmojiPicker.prototype.canDecorate = function(element) { return false; }; /** * @override * @suppress {deprecated} Using deprecated goog.ui.TabPane. */ goog.ui.emoji.EmojiPicker.prototype.enterDocument = function() { goog.ui.emoji.EmojiPicker.superClass_.enterDocument.call(this); for (var i = 0; i < this.pages_.length; i++) { this.pages_[i].enterDocument(); var pageElement = this.pages_[i].getElement(); // Add a new tab to the tabpane if there's more than one group of emoji. // If there is just one group of emoji, then we simply use the single // page's element as the content for the picker if (this.pages_.length > 1) { // Create a simple default title containg the page number if the title // was not provided in the emoji group params var title = this.emoji_[i].title || (i + 1); this.tabPane_.addPage(new goog.ui.TabPane.TabPage( pageElement, title, this.getDomHelper())); } else { this.getElement().appendChild(pageElement); } } // Initialize listeners. Note that we need to initialize this listener // after createDom, because addPage causes the goog.ui.TabPane.Events.CHANGE // event to fire, but we only want the handler (which loads delayed images) // to run after the picker has been constructed. if (this.tabPane_) { this.getHandler().listen( this.tabPane_, goog.ui.TabPane.Events.CHANGE, this.onPageChanged_); // Make the tabpane unselectable so that changing tabs doesn't disturb the // cursor goog.style.setUnselectable(this.tabPane_.getElement(), true); } this.getElement().unselectable = 'on'; }; /** @override */ goog.ui.emoji.EmojiPicker.prototype.exitDocument = function() { goog.ui.emoji.EmojiPicker.superClass_.exitDocument.call(this); for (var i = 0; i < this.pages_.length; i++) { this.pages_[i].exitDocument(); } }; /** @override */ goog.ui.emoji.EmojiPicker.prototype.disposeInternal = function() { goog.ui.emoji.EmojiPicker.superClass_.disposeInternal.call(this); if (this.tabPane_) { this.tabPane_.dispose(); this.tabPane_ = null; } for (var i = 0; i < this.pages_.length; i++) { this.pages_[i].dispose(); } this.pages_.length = 0; }; /** * @return {string} CSS class for the root element of EmojiPicker. */ goog.ui.emoji.EmojiPicker.prototype.getCssClass = function() { return goog.getCssName('goog-ui-emojipicker'); }; /** * Returns the currently selected emoji from this picker. If the picker is * using the URL prefix optimization, allocates a new emoji object with the * full URL. This method is meant to be used by clients of the emojipicker, * e.g., in a listener on goog.ui.component.EventType.ACTION that wants to use * the just-selected emoji. * * @return {goog.ui.emoji.Emoji} The currently selected emoji from this picker. */ goog.ui.emoji.EmojiPicker.prototype.getSelectedEmoji = function() { return this.urlPrefix_ ? new goog.ui.emoji.Emoji(this.urlPrefix_ + this.selectedEmoji_.getId(), this.selectedEmoji_.getId()) : this.selectedEmoji_; }; /** * Returns the number of emoji groups in this picker. * * @return {number} The number of emoji groups in this picker. */ goog.ui.emoji.EmojiPicker.prototype.getNumEmojiGroups = function() { return this.emoji_.length; }; /** * Returns a page from the picker. This should be considered protected, and is * ONLY FOR TESTING. * * @param {number} index Index of the page to return. * @return {goog.ui.emoji.EmojiPalette?} the page at the specified index or null * if none exists. */ goog.ui.emoji.EmojiPicker.prototype.getPage = function(index) { return this.pages_[index]; }; /** * Returns all the pages from the picker. This should be considered protected, * and is ONLY FOR TESTING. * * @return {Array.<goog.ui.emoji.EmojiPalette>?} the pages in the picker or * null if none exist. */ goog.ui.emoji.EmojiPicker.prototype.getPages = function() { return this.pages_; }; /** * Returns the tabpane if this is a multipage picker. This should be considered * protected, and is ONLY FOR TESTING. * * @return {goog.ui.TabPane} the tabpane if it is a multipage picker, * or null if it does not exist or is a single page picker. */ goog.ui.emoji.EmojiPicker.prototype.getTabPane = function() { return this.tabPane_; }; /** * @return {goog.ui.emoji.EmojiPalette} The active page of the emoji picker. * @private */ goog.ui.emoji.EmojiPicker.prototype.getActivePage_ = function() { return this.pages_[this.activePage_]; }; /** * Handles actions from the EmojiPalettes that this picker contains. * * @param {goog.ui.Component.EventType} e The event object. * @private */ goog.ui.emoji.EmojiPicker.prototype.onEmojiPaletteAction_ = function(e) { this.selectedEmoji_ = this.getActivePage_().getSelectedEmoji(); }; /** * Handles changes in the active page in the tabpane. * * @param {goog.ui.TabPaneEvent} e The event object. * @private */ goog.ui.emoji.EmojiPicker.prototype.onPageChanged_ = function(e) { var index = /** @type {number} */ (e.page.getIndex()); this.loadPage_(index); this.activePage_ = index; }; /** * Loads a page into the picker if it has not yet been loaded. * * @param {number} index Index of the page to load. * @private * @suppress {deprecated} Using deprecated goog.ui.TabPane. */ goog.ui.emoji.EmojiPicker.prototype.loadPage_ = function(index) { if (index < 0 || index > this.pages_.length) { throw Error('Index out of bounds'); } if (!this.pageLoadStatus_[index]) { var oldPage = this.pages_[index]; this.pages_[index] = this.createEmojiPage_(this.emoji_[index].emoji, index); this.pages_[index].enterDocument(); var pageElement = this.pages_[index].getElement(); if (this.pages_.length > 1) { this.tabPane_.removePage(index); var title = this.emoji_[index].title || (index + 1); this.tabPane_.addPage(new goog.ui.TabPane.TabPage( pageElement, title, this.getDomHelper()), index); this.tabPane_.setSelectedIndex(index); } else { var el = this.getElement(); el.appendChild(pageElement); } if (oldPage) { oldPage.dispose(); } } };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Popup Emoji Picker implementation. This provides a UI widget * for choosing an emoji from a grid of possible choices. The widget is a popup, * so it is suitable for a toolbar, for instance the TrogEdit toolbar. * * @see ../demos/popupemojipicker.html for an example of how to instantiate * an emoji picker. * * See goog.ui.emoji.EmojiPicker in emojipicker.js for more details. * * Based on goog.ui.PopupColorPicker (popupcolorpicker.js). * * @see ../../demos/popupemojipicker.html */ goog.provide('goog.ui.emoji.PopupEmojiPicker'); goog.require('goog.dom'); goog.require('goog.events.EventType'); goog.require('goog.positioning.AnchoredPosition'); goog.require('goog.ui.Component'); goog.require('goog.ui.Popup'); goog.require('goog.ui.emoji.EmojiPicker'); /** * Constructs a popup emoji picker widget. * * @param {string} defaultImgUrl Url of the img that should be used to fill up * the cells in the emoji table, to prevent jittering. Should be the same * size as the emoji. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. * @extends {goog.ui.Component} * @constructor */ goog.ui.emoji.PopupEmojiPicker = function(defaultImgUrl, opt_domHelper) { goog.ui.Component.call(this, opt_domHelper); this.emojiPicker_ = new goog.ui.emoji.EmojiPicker(defaultImgUrl, opt_domHelper); this.addChild(this.emojiPicker_); this.getHandler().listen(this.emojiPicker_, goog.ui.Component.EventType.ACTION, this.onEmojiPicked_); }; goog.inherits(goog.ui.emoji.PopupEmojiPicker, goog.ui.Component); /** * Instance of an emoji picker control. * @type {goog.ui.emoji.EmojiPicker} * @private */ goog.ui.emoji.PopupEmojiPicker.prototype.emojiPicker_ = null; /** * Instance of goog.ui.Popup used to manage the behavior of the emoji picker. * @type {goog.ui.Popup} * @private */ goog.ui.emoji.PopupEmojiPicker.prototype.popup_ = null; /** * Reference to the element that triggered the last popup. * @type {Element} * @private */ goog.ui.emoji.PopupEmojiPicker.prototype.lastTarget_ = null; /** * Whether the emoji picker can accept focus. * @type {boolean} * @private */ goog.ui.emoji.PopupEmojiPicker.prototype.focusable_ = true; /** * If true, then the emojipicker will toggle off if it is already visible. * Default is true. * @type {boolean} * @private */ goog.ui.emoji.PopupEmojiPicker.prototype.toggleMode_ = true; /** * Adds a group of emoji to the picker. * * @param {string|Element} title Title for the group. * @param {Array.<Array>} emojiGroup A new group of emoji to be added. Each * internal array contains [emojiUrl, emojiId]. */ goog.ui.emoji.PopupEmojiPicker.prototype.addEmojiGroup = function(title, emojiGroup) { this.emojiPicker_.addEmojiGroup(title, emojiGroup); }; /** * Sets whether the emoji picker should toggle if it is already open. * @param {boolean} toggle The toggle mode to use. */ goog.ui.emoji.PopupEmojiPicker.prototype.setToggleMode = function(toggle) { this.toggleMode_ = toggle; }; /** * Gets whether the emojipicker is in toggle mode * @return {boolean} toggle. */ goog.ui.emoji.PopupEmojiPicker.prototype.getToggleMode = function() { return this.toggleMode_; }; /** * Sets whether loading of images should be delayed until after dom creation. * Thus, this function must be called before {@link #createDom}. If set to true, * the client must call {@link #loadImages} when they wish the images to be * loaded. * * @param {boolean} shouldDelay Whether to delay loading the images. */ goog.ui.emoji.PopupEmojiPicker.prototype.setDelayedLoad = function(shouldDelay) { if (this.emojiPicker_) { this.emojiPicker_.setDelayedLoad(shouldDelay); } }; /** * Sets whether the emoji picker can accept focus. * @param {boolean} focusable Whether the emoji picker should accept focus. */ goog.ui.emoji.PopupEmojiPicker.prototype.setFocusable = function(focusable) { this.focusable_ = focusable; if (this.emojiPicker_) { // TODO(user): In next revision sort the behavior of passing state to // children correctly this.emojiPicker_.setFocusable(focusable); } }; /** * Sets the URL prefix for the emoji URLs. * * @param {string} urlPrefix Prefix that should be prepended to all URLs. */ goog.ui.emoji.PopupEmojiPicker.prototype.setUrlPrefix = function(urlPrefix) { this.emojiPicker_.setUrlPrefix(urlPrefix); }; /** * Sets the location of the tabs in relation to the emoji grids. This should * only be called before the picker has been rendered. * * @param {goog.ui.TabPane.TabLocation} tabLocation The location of the tabs. */ goog.ui.emoji.PopupEmojiPicker.prototype.setTabLocation = function(tabLocation) { this.emojiPicker_.setTabLocation(tabLocation); }; /** * Sets the number of rows per grid in the emoji picker. This should only be * called before the picker has been rendered. * * @param {number} numRows Number of rows per grid. */ goog.ui.emoji.PopupEmojiPicker.prototype.setNumRows = function(numRows) { this.emojiPicker_.setNumRows(numRows); }; /** * Sets the number of columns per grid in the emoji picker. This should only be * called before the picker has been rendered. * * @param {number} numCols Number of columns per grid. */ goog.ui.emoji.PopupEmojiPicker.prototype.setNumColumns = function(numCols) { this.emojiPicker_.setNumColumns(numCols); }; /** * Sets the progressive rendering aspect of this emojipicker. Must be called * before createDom to have an effect. * * @param {boolean} progressive Whether the picker should render progressively. */ goog.ui.emoji.PopupEmojiPicker.prototype.setProgressiveRender = function(progressive) { if (this.emojiPicker_) { this.emojiPicker_.setProgressiveRender(progressive); } }; /** * Returns the number of emoji groups in this picker. * * @return {number} The number of emoji groups in this picker. */ goog.ui.emoji.PopupEmojiPicker.prototype.getNumEmojiGroups = function() { return this.emojiPicker_.getNumEmojiGroups(); }; /** * Causes the emoji imgs to be loaded into the picker. Used for delayed loading. */ goog.ui.emoji.PopupEmojiPicker.prototype.loadImages = function() { if (this.emojiPicker_) { this.emojiPicker_.loadImages(); } }; /** @override */ goog.ui.emoji.PopupEmojiPicker.prototype.createDom = function() { goog.ui.emoji.PopupEmojiPicker.superClass_.createDom.call(this); this.emojiPicker_.createDom(); this.getElement().className = goog.getCssName('goog-ui-popupemojipicker'); this.getElement().appendChild(this.emojiPicker_.getElement()); this.popup_ = new goog.ui.Popup(this.getElement()); this.getElement().unselectable = 'on'; }; /** @override */ goog.ui.emoji.PopupEmojiPicker.prototype.disposeInternal = function() { goog.ui.emoji.PopupEmojiPicker.superClass_.disposeInternal.call(this); this.emojiPicker_ = null; this.lastTarget_ = null; if (this.popup_) { this.popup_.dispose(); this.popup_ = null; } }; /** * Attaches the popup emoji picker to an element. * * @param {Element} element The element to attach to. */ goog.ui.emoji.PopupEmojiPicker.prototype.attach = function(element) { // TODO(user): standardize event type, popups should use MOUSEDOWN, but // currently apps are using click. this.getHandler().listen(element, goog.events.EventType.CLICK, this.show_); }; /** * Detatches the popup emoji picker from an element. * * @param {Element} element The element to detach from. */ goog.ui.emoji.PopupEmojiPicker.prototype.detach = function(element) { this.getHandler().unlisten(element, goog.events.EventType.CLICK, this.show_); }; /** * @return {goog.ui.emoji.EmojiPicker} The emoji picker instance. */ goog.ui.emoji.PopupEmojiPicker.prototype.getEmojiPicker = function() { return this.emojiPicker_; }; /** * 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.emoji.PopupEmojiPicker.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.emoji.PopupEmojiPicker.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.emoji.PopupEmojiPicker.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.emoji.PopupEmojiPicker.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.emoji.PopupEmojiPicker.prototype.getPopup = function() { return this.popup_; }; /** * @return {Element} The last element that triggered the popup. */ goog.ui.emoji.PopupEmojiPicker.prototype.getLastTarget = function() { return this.lastTarget_; }; /** * @return {goog.ui.emoji.Emoji} The currently selected emoji. */ goog.ui.emoji.PopupEmojiPicker.prototype.getSelectedEmoji = function() { return this.emojiPicker_.getSelectedEmoji(); }; /** * Handles click events on the element this picker is attached to and shows the * emoji picker in a popup. * * @param {goog.events.BrowserEvent} e The browser event. * @private */ goog.ui.emoji.PopupEmojiPicker.prototype.show_ = function(e) { 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_, goog.positioning.Corner.BOTTOM_LEFT)); this.popup_.setVisible(true); }; /** * Handles selection of an emoji. * * @param {goog.events.Event} e The event object. * @private */ goog.ui.emoji.PopupEmojiPicker.prototype.onEmojiPicked_ = function(e) { this.popup_.setVisible(false); };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Emoji Palette renderer implementation. * */ goog.provide('goog.ui.emoji.EmojiPaletteRenderer'); goog.require('goog.a11y.aria'); goog.require('goog.dom'); goog.require('goog.ui.PaletteRenderer'); goog.require('goog.ui.emoji.Emoji'); goog.require('goog.ui.emoji.SpriteInfo'); /** * Renders an emoji palette. * * @param {?string} defaultImgUrl Url of the img that should be used to fill up * the cells in the emoji table, to prevent jittering. Will be stretched * to the emoji cell size. A good image is a transparent dot. * @constructor * @extends {goog.ui.PaletteRenderer} */ goog.ui.emoji.EmojiPaletteRenderer = function(defaultImgUrl) { goog.ui.PaletteRenderer.call(this); this.defaultImgUrl_ = defaultImgUrl; }; goog.inherits(goog.ui.emoji.EmojiPaletteRenderer, goog.ui.PaletteRenderer); /** * Globally unique ID sequence for cells rendered by this renderer class. * @type {number} * @private */ goog.ui.emoji.EmojiPaletteRenderer.cellId_ = 0; /** * Url of the img that should be used for cells in the emoji palette that are * not filled with emoji, i.e., after all the emoji have already been placed * on a page. * * @type {?string} * @private */ goog.ui.emoji.EmojiPaletteRenderer.prototype.defaultImgUrl_ = null; /** @override */ goog.ui.emoji.EmojiPaletteRenderer.getCssClass = function() { return goog.getCssName('goog-ui-emojipalette'); }; /** * Creates a palette item from the given emoji data. * * @param {goog.dom.DomHelper} dom DOM helper for constructing DOM elements. * @param {string} id Goomoji id for the emoji. * @param {goog.ui.emoji.SpriteInfo} spriteInfo Spriting info for the emoji. * @param {string} displayUrl URL of the image served for this cell, whether * an individual emoji image or a sprite. * @return {HTMLDivElement} The palette item for this emoji. */ goog.ui.emoji.EmojiPaletteRenderer.prototype.createPaletteItem = function(dom, id, spriteInfo, displayUrl) { var el; if (spriteInfo) { var cssClass = spriteInfo.getCssClass(); if (cssClass) { el = dom.createDom('div', cssClass); } else { el = this.buildElementFromSpriteMetadata(dom, spriteInfo, displayUrl); } } else { el = dom.createDom('img', {'src': displayUrl}); } var outerdiv = dom.createDom('div', goog.getCssName('goog-palette-cell-wrapper'), el); outerdiv.setAttribute(goog.ui.emoji.Emoji.ATTRIBUTE, id); return /** @type {HTMLDivElement} */ (outerdiv); }; /** * Modifies a palette item containing an animated emoji, in response to the * animated emoji being successfully downloaded. * * @param {Element} item The palette item to update. * @param {Image} animatedImg An Image object containing the animated emoji. */ goog.ui.emoji.EmojiPaletteRenderer.prototype.updateAnimatedPaletteItem = function(item, animatedImg) { // An animated emoji is one that had sprite info for a static version and is // now being updated. See createPaletteItem for the structure of the palette // items we're modifying. var inner = /** @type {Element} */ (item.firstChild); // The first case is a palette item with a CSS class representing the sprite, // and an animated emoji. var classes = goog.dom.classes.get(inner); if (classes && classes.length == 1) { inner.className = ''; } goog.style.setStyle(inner, { 'width': animatedImg.width, 'height': animatedImg.height, 'background-image': 'url(' + animatedImg.src + ')', 'background-position': '0 0' }); }; /** * Builds the inner contents of a palette item out of sprite metadata. * * @param {goog.dom.DomHelper} dom DOM helper for constructing DOM elements. * @param {goog.ui.emoji.SpriteInfo} spriteInfo The metadata to create the css * for the sprite. * @param {string} displayUrl The URL of the image for this cell. * @return {HTMLDivElement} The inner element for a palette item. */ goog.ui.emoji.EmojiPaletteRenderer.prototype.buildElementFromSpriteMetadata = function(dom, spriteInfo, displayUrl) { var width = spriteInfo.getWidthCssValue(); var height = spriteInfo.getHeightCssValue(); var x = spriteInfo.getXOffsetCssValue(); var y = spriteInfo.getYOffsetCssValue(); var el = dom.createDom('div'); goog.style.setStyle(el, { 'width': width, 'height': height, 'background-image': 'url(' + displayUrl + ')', 'background-repeat': 'no-repeat', 'background-position': x + ' ' + y }); return /** @type {HTMLDivElement} */ (el); }; /** @override */ goog.ui.emoji.EmojiPaletteRenderer.prototype.createCell = function(node, dom) { // Create a cell with the default img if we're out of items, in order to // prevent jitter in the table. If there's no default img url, just create an // empty div, to prevent trying to fetch a null url. if (!node) { var elem = this.defaultImgUrl_ ? dom.createDom('img', {'src': this.defaultImgUrl_}) : dom.createDom('div'); node = dom.createDom('div', goog.getCssName('goog-palette-cell-wrapper'), elem); } var cell = dom.createDom('td', { 'class': goog.getCssName(this.getCssClass(), 'cell'), // Cells must have an ID, for accessibility, so we generate one here. 'id': this.getCssClass() + '-cell-' + goog.ui.emoji.EmojiPaletteRenderer.cellId_++ }, node); goog.a11y.aria.setRole(cell, 'gridcell'); return cell; }; /** * 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). * @override */ goog.ui.emoji.EmojiPaletteRenderer.prototype.getContainingItem = function(palette, node) { var root = palette.getElement(); while (node && node.nodeType == goog.dom.NodeType.ELEMENT && node != root) { if (node.tagName == 'TD') { return node.firstChild; } node = node.parentNode; } return null; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Progressive Emoji Palette renderer implementation. * */ goog.provide('goog.ui.emoji.ProgressiveEmojiPaletteRenderer'); goog.require('goog.ui.emoji.EmojiPaletteRenderer'); /** * Progressively renders an emoji palette. The progressive renderer tries to * use img tags instead of background-image for sprited emoji, since most * browsers render img tags progressively (i.e., as the data comes in), while * only very new browsers render background-image progressively. * * @param {string} defaultImgUrl Url of the img that should be used to fill up * the cells in the emoji table, to prevent jittering. Will be stretched * to the emoji cell size. A good image is a transparent dot. * @constructor * @extends {goog.ui.emoji.EmojiPaletteRenderer} */ goog.ui.emoji.ProgressiveEmojiPaletteRenderer = function(defaultImgUrl) { goog.ui.emoji.EmojiPaletteRenderer.call(this, defaultImgUrl); }; goog.inherits(goog.ui.emoji.ProgressiveEmojiPaletteRenderer, goog.ui.emoji.EmojiPaletteRenderer); /** @override */ goog.ui.emoji.ProgressiveEmojiPaletteRenderer.prototype. buildElementFromSpriteMetadata = function(dom, spriteInfo, displayUrl) { var width = spriteInfo.getWidthCssValue(); var height = spriteInfo.getHeightCssValue(); var x = spriteInfo.getXOffsetCssValue(); var y = spriteInfo.getYOffsetCssValue(); // Need this extra div for proper vertical centering. var inner = dom.createDom('img', {'src': displayUrl}); var el = /** @type {HTMLDivElement} */ (dom.createDom('div', goog.getCssName('goog-palette-cell-extra'), inner)); goog.style.setStyle(el, { 'width': width, 'height': height, 'overflow': 'hidden', 'position': 'relative' }); goog.style.setStyle(inner, { 'left': x, 'top': y, 'position': 'absolute' }); return el; }; /** @override */ goog.ui.emoji.ProgressiveEmojiPaletteRenderer.prototype. updateAnimatedPaletteItem = function(item, animatedImg) { // Just to be safe, we check for the existence of the img element within this // palette item before attempting to modify it. var img; var el = item.firstChild; while (el) { if ('IMG' == el.tagName) { img = /** @type {Element} */ (el); break; } el = el.firstChild; } if (!el) { return; } img.width = animatedImg.width; img.height = animatedImg.height; goog.style.setStyle(img, { 'left': 0, 'top': 0 }); img.src = animatedImg.src; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview An alternative custom button renderer that uses even more CSS * voodoo than the default implementation to render custom buttons with fake * rounded corners and dimensionality (via a subtle flat shadow on the bottom * half of the button) without the use of images. * * Based on the Custom Buttons 3.1 visual specification, see * http://go/custombuttons * * @author eae@google.com (Emil A Eklund) * @see ../demos/imagelessbutton.html */ goog.provide('goog.ui.ImagelessButtonRenderer'); goog.require('goog.dom.classes'); goog.require('goog.ui.Button'); goog.require('goog.ui.ControlContent'); goog.require('goog.ui.CustomButtonRenderer'); goog.require('goog.ui.INLINE_BLOCK_CLASSNAME'); goog.require('goog.ui.registry'); /** * Custom renderer for {@link goog.ui.Button}s. Imageless buttons can contain * almost arbitrary HTML content, will flow like inline elements, but can be * styled like block-level elements. * * @constructor * @extends {goog.ui.CustomButtonRenderer} */ goog.ui.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">&nbsp;</div> * <div class="goog-imageless-button-content">Contents...</div> * </div> * </div> * </div> * </div> * @override */ goog.ui.ImagelessButtonRenderer.prototype.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">&nbsp;</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); var outerClassName = goog.getCssName(this.getCssClass(), 'outer-box'); if (outer && goog.dom.classes.has(outer, outerClassName)) { var inner = button.getDomHelper().getFirstElementChild(outer); var innerClassName = goog.getCssName(this.getCssClass(), 'inner-box'); if (inner && goog.dom.classes.has(inner, innerClassName)) { var pos = button.getDomHelper().getFirstElementChild(inner); var posClassName = goog.getCssName(this.getCssClass(), 'pos'); if (pos && goog.dom.classes.has(pos, posClassName)) { var shadow = button.getDomHelper().getFirstElementChild(pos); var shadowClassName = goog.getCssName( this.getCssClass(), 'top-shadow'); if (shadow && goog.dom.classes.has(shadow, shadowClassName)) { var content = button.getDomHelper().getNextElementSibling(shadow); var contentClassName = goog.getCssName( this.getCssClass(), 'content'); if (content && goog.dom.classes.has(content, contentClassName)) { // We have a proper box structure. return true; } } } } } return false; }; /** * Returns the CSS class to be applied to the root element of components * rendered using this renderer. * @return {string} Renderer-specific CSS class. * @override */ goog.ui.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; });
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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); } } };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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.AnimationFactory'); goog.provide('goog.ui.SliderBase.Orientation'); goog.require('goog.Timer'); goog.require('goog.a11y.aria'); goog.require('goog.a11y.aria.Role'); goog.require('goog.a11y.aria.State'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.classes'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.events.KeyCodes'); goog.require('goog.events.KeyHandler'); goog.require('goog.events.MouseWheelHandler'); goog.require('goog.fx.AnimationParallelQueue'); goog.require('goog.fx.Dragger'); goog.require('goog.fx.Transition'); goog.require('goog.fx.dom.ResizeHeight'); goog.require('goog.fx.dom.ResizeWidth'); goog.require('goog.fx.dom.Slide'); goog.require('goog.math'); goog.require('goog.math.Coordinate'); goog.require('goog.style'); goog.require('goog.style.bidi'); goog.require('goog.ui.Component'); 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); /** * The factory to use to generate additional animations when animating to a * new value. * @type {goog.ui.SliderBase.AnimationFactory} * @private */ this.additionalAnimations_ = null; /** * The model for the range of the slider. * @type {!goog.ui.RangeModel} */ 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); /** * Event types used to listen for dragging events. Note that extent drag events * are also sent for single-thumb sliders, since the one thumb controls both * value and extent together; in this case, they can simply be ignored. * @enum {string} */ goog.ui.SliderBase.EventType = { /** User started dragging the value thumb */ DRAG_VALUE_START: goog.events.getUniqueId('dragvaluestart'), /** User is done dragging the value thumb */ DRAG_VALUE_END: goog.events.getUniqueId('dragvalueend'), /** User started dragging the extent thumb */ DRAG_EXTENT_START: goog.events.getUniqueId('dragextentstart'), /** User is done dragging the extent thumb */ DRAG_EXTENT_END: goog.events.getUniqueId('dragextentend'), // Note that the following two events are sent twice, once for the value // dragger, and once of the extent dragger. If you need to differentiate // between the two, or if your code relies on receiving a single event per // START/END event, it should listen to one of the VALUE/EXTENT-specific // events. /** User started dragging a thumb */ DRAG_START: goog.events.getUniqueId('dragstart'), /** User is done dragging a thumb */ DRAG_END: goog.events.getUniqueId('dragend') }; /** * 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; /** * Whether the slider should handle mouse wheel events. * @private * @type {boolean} */ goog.ui.SliderBase.prototype.isHandleMouseWheel_ = true; /** * Whether the slider is enabled or not. * @private * @type {boolean} */ goog.ui.SliderBase.prototype.enabled_ = true; /** * Whether the slider implements the changes described in http://b/6324964, * making it truly RTL. This is a temporary flag to allow clients to transition * to the new behavior at their convenience. At some point it will be the * default. * @type {boolean} * @private */ goog.ui.SliderBase.prototype.flipForRtl_ = false; /** * Enables/disables true RTL behavior. This should be called immediately after * construction. This is a temporary flag to allow clients to transition * to the new behavior at their convenience. At some point it will be the * default. * @param {boolean} flipForRtl True if the slider should be flipped for RTL, * false otherwise. */ goog.ui.SliderBase.prototype.enableFlipForRtl = function(flipForRtl) { this.flipForRtl_ = flipForRtl; }; // 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'); /** * CSS class name applied when the slider is disabled. * @type {string} * @private */ goog.ui.SliderBase.DISABLED_CSS_CLASS_ = goog.getCssName('goog-slider-disabled'); /** @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. * @override */ 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); this.valueDragger_.enableRightPositioningForRtl(this.flipForRtl_); this.extentDragger_.enableRightPositioningForRtl(this.flipForRtl_); // 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.enableEventHandlers_(true); this.getElement().tabIndex = 0; this.updateUi_(); }; /** * Attaches/Detaches the event handlers on the slider. * @param {boolean} enable Whether to attach or detach the event handlers. * @private */ goog.ui.SliderBase.prototype.enableEventHandlers_ = function(enable) { if (enable) { 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_); if (this.isHandleMouseWheel()) { this.enableMouseWheelHandling_(true); } } else { this.getHandler(). unlisten(this.valueDragger_, goog.fx.Dragger.EventType.BEFOREDRAG, this.handleBeforeDrag_). unlisten(this.extentDragger_, goog.fx.Dragger.EventType.BEFOREDRAG, this.handleBeforeDrag_). unlisten(this.valueDragger_, [goog.fx.Dragger.EventType.START, goog.fx.Dragger.EventType.END], this.handleThumbDragStartEnd_). unlisten(this.extentDragger_, [goog.fx.Dragger.EventType.START, goog.fx.Dragger.EventType.END], this.handleThumbDragStartEnd_). unlisten(this.keyHandler_, goog.events.KeyHandler.EventType.KEY, this.handleKeyDown_). unlisten(this.getElement(), goog.events.EventType.MOUSEDOWN, this.handleMouseDown_); if (this.isHandleMouseWheel()) { this.enableMouseWheelHandling_(false); } } }; /** @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 isDragStart = e.type == goog.fx.Dragger.EventType.START; goog.dom.classes.enable(this.getElement(), goog.ui.SliderBase.SLIDER_DRAGGING_CSS_CLASS_, isDragStart); goog.dom.classes.enable(e.target.handle, goog.ui.SliderBase.THUMB_DRAGGING_CSS_CLASS_, isDragStart); var isValueDragger = e.dragger == this.valueDragger_; if (isDragStart) { this.dispatchEvent(goog.ui.SliderBase.EventType.DRAG_START); this.dispatchEvent(isValueDragger ? goog.ui.SliderBase.EventType.DRAG_VALUE_START : goog.ui.SliderBase.EventType.DRAG_EXTENT_START); } else { this.dispatchEvent(goog.ui.SliderBase.EventType.DRAG_END); this.dispatchEvent(isValueDragger ? goog.ui.SliderBase.EventType.DRAG_VALUE_END : goog.ui.SliderBase.EventType.DRAG_EXTENT_END); } }; /** * 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: var sign = this.flipForRtl_ && this.isRightToLeft() ? 1 : -1; this.moveThumbs(e.shiftKey ? sign * this.getBlockIncrement() : sign * this.getUnitIncrement()); break; case goog.events.KeyCodes.DOWN: this.moveThumbs(e.shiftKey ? -this.getBlockIncrement() : -this.getUnitIncrement()); break; case goog.events.KeyCodes.RIGHT: var sign = this.flipForRtl_ && this.isRightToLeft() ? -1 : 1; this.moveThumbs(e.shiftKey ? sign * this.getBlockIncrement() : sign * this.getUnitIncrement()); break; 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.getOffsetStart_(this.thumbToMove_) + this.thumbToMove_.offsetWidth; } var doc = goog.dom.getOwnerDocument(this.getElement()); this.getHandler(). listen(doc, goog.events.EventType.MOUSEUP, this.stopBlockIncrementing_, 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.getOffsetStart_(this.thumbToMove_); 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); } }; /** * Stops the block incrementing animation and unlistens the necessary * event handlers. * @private */ goog.ui.SliderBase.prototype.stopBlockIncrementing_ = function() { if (this.incTimer_) { this.incTimer_.stop(); } var doc = goog.dom.getOwnerDocument(this.getElement()); this.getHandler(). unlisten(doc, goog.events.EventType.MOUSEUP, this.stopBlockIncrementing_, 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 { if (this.flipForRtl_ && this.isRightToLeft()) { return this.getElement().clientWidth - coord.x; } 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. */ 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; } }; /** * @deprecated Since 25-June-2012. Use public method getValueFromMousePosition. * @private */ goog.ui.SliderBase.prototype.getValueFromMousePosition_ = goog.ui.SliderBase.prototype.getValueFromMousePosition; /** * @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'); } }; /** * Returns whether a thumb is currently being dragged with the mouse (or via * touch). Note that changing the value with keyboard, mouswheel, or via * move-to-point click immediately sends a CHANGE event without going through a * dragged state. * @return {boolean} Whether a dragger is currently being dragged. */ goog.ui.SliderBase.prototype.isDragging = function() { return this.valueDragger_.isDragging() || this.extentDragger_.isDragging(); }; /** * 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.handleRangeModelChange(null); } }; /** * @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 { var pos = (this.flipForRtl_ && this.isRightToLeft()) ? 'right' : 'left'; this.valueThumb.style[pos] = minCoord.x + 'px'; this.extentThumb.style[pos] = maxCoord.x + 'px'; if (this.rangeHighlight) { var highlightPositioning = this.calculateRangeHighlightPositioning_( minCoord.x, maxCoord.x, this.valueThumb.offsetWidth); this.rangeHighlight.style[pos] = 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. */ 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.x = this.getOffsetStart_(this.valueThumb); // Keep x the same. coord.y = h - bottom; } else { var w = this.getElement().clientWidth - this.valueThumb.offsetWidth; var left = Math.round(ratio * w); coord.x = left; coord.y = this.valueThumb.offsetTop; // Keep y the same. } } return coord; }; /** * @deprecated Since 25-June-2012. Use public method getThumbCoordinateForValue. * @private */ goog.ui.SliderBase.prototype.getThumbCoordinateForValue_ = goog.ui.SliderBase.prototype.getThumbCoordinateForValue; /** * 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 = goog.math.clamp(v, this.getMinimum(), this.getMaximum()); if (this.isAnimating_) { this.currentAnimation_.stop(true); } var animations = new goog.fx.AnimationParallelQueue(); var end; var thumb = this.getClosestThumb_(v); var previousValue = this.getValue(); var previousExtent = this.getExtent(); var previousThumbValue = this.getThumbPosition_(thumb); var previousCoord = this.getThumbCoordinateForValue(previousThumbValue); var stepSize = this.getStep(); // If the delta is less than a single step, increase it to a step, else the // range model will reduce it to zero. if (Math.abs(v - previousThumbValue) < stepSize) { var delta = v > previousThumbValue ? stepSize : -stepSize; v = previousThumbValue + delta; // The resulting value may be out of bounds, sanitize. v = goog.math.clamp(v, this.getMinimum(), this.getMaximum()); } this.setThumbPosition_(thumb, v); var coord = this.getThumbCoordinateForValue(this.getThumbPosition_(thumb)); if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { end = [this.getOffsetStart_(thumb), coord.y]; } else { end = [coord.x, thumb.offsetTop]; } var slide = new goog.fx.dom.Slide(thumb, [previousCoord.x, previousCoord.y], end, goog.ui.SliderBase.ANIMATION_INTERVAL_); slide.enableRightPositioningForRtl(this.flipForRtl_); animations.add(slide); if (this.rangeHighlight) { this.addRangeHighlightAnimations_(thumb, previousValue, previousExtent, coord, animations); } // Create additional animations to play if a factory has been set. if (this.additionalAnimations_) { var additionalAnimations = this.additionalAnimations_.createAnimations( previousValue, v, goog.ui.SliderBase.ANIMATION_INTERVAL_); goog.array.forEach(additionalAnimations, function(animation) { animations.add(animation); }); } this.currentAnimation_ = animations; this.getHandler().listen(animations, goog.fx.Transition.EventType.END, this.endAnimation_); this.isAnimating_ = true; animations.play(false); }; /** * @return {boolean} True if the slider is animating, false otherwise. */ goog.ui.SliderBase.prototype.isAnimating = function() { return this.isAnimating_; }; /** * Sets the factory that will be used to create additional animations to be * played when animating to a new value. These animations can be for any * element and the animations will be played in addition to the default * animation(s). The animations will also be played in the same parallel queue * ensuring that all animations are played at the same time. * @see #animatedSetValue * * @param {goog.ui.SliderBase.AnimationFactory} factory The animation factory to * use. This will not change the default animations played by the slider. * It will only allow for additional animations. */ goog.ui.SliderBase.prototype.setAdditionalAnimations = function(factory) { this.additionalAnimations_ = factory; }; /** * 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 {number} previousValue The previous value of the slider. * @param {number} previousExtent The previous extent of the * slider. * @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, previousValue, previousExtent, newCoord, animations) { var previousMinCoord = this.getThumbCoordinateForValue(previousValue); var previousMaxCoord = this.getThumbCoordinateForValue( previousValue + previousExtent); var minCoord = previousMinCoord; var maxCoord = previousMaxCoord; if (thumb == this.valueThumb) { minCoord = newCoord; } else { maxCoord = newCoord; } if (this.orientation_ == goog.ui.SliderBase.Orientation.VERTICAL) { var previousHighlightPositioning = this.calculateRangeHighlightPositioning_( previousMaxCoord.y, previousMinCoord.y, this.valueThumb.offsetHeight); var highlightPositioning = this.calculateRangeHighlightPositioning_( maxCoord.y, minCoord.y, this.valueThumb.offsetHeight); var slide = new goog.fx.dom.Slide(this.rangeHighlight, [this.getOffsetStart_(this.rangeHighlight), previousHighlightPositioning.offset], [this.getOffsetStart_(this.rangeHighlight), highlightPositioning.offset], goog.ui.SliderBase.ANIMATION_INTERVAL_); var resizeHeight = new goog.fx.dom.ResizeHeight(this.rangeHighlight, previousHighlightPositioning.size, highlightPositioning.size, goog.ui.SliderBase.ANIMATION_INTERVAL_); slide.enableRightPositioningForRtl(this.flipForRtl_); resizeHeight.enableRightPositioningForRtl(this.flipForRtl_); animations.add(slide); animations.add(resizeHeight); } else { var previousHighlightPositioning = this.calculateRangeHighlightPositioning_( previousMinCoord.x, previousMaxCoord.x, this.valueThumb.offsetWidth); var highlightPositioning = this.calculateRangeHighlightPositioning_( minCoord.x, maxCoord.x, this.valueThumb.offsetWidth); var newWidth = highlightPositioning[1]; var slide = new goog.fx.dom.Slide(this.rangeHighlight, [previousHighlightPositioning.offset, this.rangeHighlight.offsetTop], [highlightPositioning.offset, this.rangeHighlight.offsetTop], goog.ui.SliderBase.ANIMATION_INTERVAL_); var resizeWidth = new goog.fx.dom.ResizeWidth(this.rangeHighlight, previousHighlightPositioning.size, highlightPositioning.size, goog.ui.SliderBase.ANIMATION_INTERVAL_); slide.enableRightPositioningForRtl(this.flipForRtl_); resizeWidth.enableRightPositioningForRtl(this.flipForRtl_); animations.add(slide); animations.add(resizeWidth); } }; /** * 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 var pos = (this.flipForRtl_ && this.isRightToLeft()) ? 'right' : 'left'; this.valueThumb.style[pos] = this.valueThumb.style.top = ''; this.extentThumb.style[pos] = this.extentThumb.style.top = ''; if (this.rangeHighlight) { this.rangeHighlight.style[pos] = 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.setElementShown(this.getElement(), visible); if (visible) { this.updateUi_(); } }; /** * Set a11y roles and state. * @protected */ goog.ui.SliderBase.prototype.setAriaRoles = function() { var el = this.getElement(); goog.asserts.assert(el, 'The DOM element for the slider base cannot be null.'); goog.a11y.aria.setRole(el, goog.a11y.aria.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.a11y.aria.setState(element, goog.a11y.aria.State.VALUEMIN, this.getMinimum()); goog.a11y.aria.setState(element, goog.a11y.aria.State.VALUEMAX, this.getMaximum()); goog.a11y.aria.setState(element, goog.a11y.aria.State.VALUENOW, this.getValue()); } }; /** * Enables or disables mouse wheel handling for the slider. The mouse wheel * handler enables the user to change the value of slider using a mouse wheel. * * @param {boolean} enable Whether to enable mouse wheel handling. */ goog.ui.SliderBase.prototype.setHandleMouseWheel = function(enable) { if (this.isInDocument() && enable != this.isHandleMouseWheel()) { this.enableMouseWheelHandling_(enable); } this.isHandleMouseWheel_ = enable; }; /** * @return {boolean} Whether the slider handles mousewheel. */ goog.ui.SliderBase.prototype.isHandleMouseWheel = function() { return this.isHandleMouseWheel_; }; /** * Enable/Disable mouse wheel handling. * @param {boolean} enable Whether to enable mouse wheel handling. * @private */ goog.ui.SliderBase.prototype.enableMouseWheelHandling_ = function(enable) { if (enable) { if (!this.mouseWheelHandler_) { this.mouseWheelHandler_ = new goog.events.MouseWheelHandler( this.getElement()); } this.getHandler().listen(this.mouseWheelHandler_, goog.events.MouseWheelHandler.EventType.MOUSEWHEEL, this.handleMouseWheel_); } else { this.getHandler().unlisten(this.mouseWheelHandler_, goog.events.MouseWheelHandler.EventType.MOUSEWHEEL, this.handleMouseWheel_); } }; /** * Enables or disables the slider. A disabled slider will ignore all * user-initiated events. Also fires goog.ui.Component.EventType.ENABLE/DISABLE * event as appropriate. * @param {boolean} enable Whether to enable the slider or not. */ goog.ui.SliderBase.prototype.setEnabled = function(enable) { if (this.enabled_ == enable) { return; } var eventType = enable ? goog.ui.Component.EventType.ENABLE : goog.ui.Component.EventType.DISABLE; if (this.dispatchEvent(eventType)) { this.enabled_ = enable; this.enableEventHandlers_(enable); if (!enable) { // Disabling a slider is equivalent to a mouse up event when the block // increment (if happening) should be halted and any possible event // handlers be appropriately unlistened. this.stopBlockIncrementing_(); } goog.dom.classes.enable(this.getElement(), goog.ui.SliderBase.DISABLED_CSS_CLASS_, !enable); } }; /** * @return {boolean} Whether the slider is enabled or not. */ goog.ui.SliderBase.prototype.isEnabled = function() { return this.enabled_; }; /** * @param {Element} element An element for which we want offsetLeft. * @return {number} Returns the element's offsetLeft, accounting for RTL if * flipForRtl_ is true. * @private */ goog.ui.SliderBase.prototype.getOffsetStart_ = function(element) { return this.flipForRtl_ ? goog.style.bidi.getOffsetStart(element) : element.offsetLeft; }; /** * The factory for creating additional animations to be played when animating to * a new value. * @interface */ goog.ui.SliderBase.AnimationFactory = function() {}; /** * Creates an additonal animation to play when animating to a new value. * * @param {number} previousValue The previous value (before animation). * @param {number} newValue The new value (after animation). * @param {number} interval The animation interval. * @return {!Array.<!goog.fx.TransitionBase>} The additional animations to play. */ goog.ui.SliderBase.AnimationFactory.prototype.createAnimations;
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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.a11y.aria'); goog.require('goog.a11y.aria.Role'); goog.require('goog.a11y.aria.State'); goog.require('goog.asserts'); 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. * @override */ 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. * @override */ goog.ui.Ratings.prototype.enterDocument = function() { var el = this.getElement(); goog.asserts.assert(el, 'The DOM element for ratings cannot be null.'); el.tabIndex = 0; goog.dom.classes.add(el, this.getCssClass()); goog.a11y.aria.setRole(el, goog.a11y.aria.Role.SLIDER); goog.a11y.aria.setState(el, goog.a11y.aria.State.VALUEMIN, 0); var max = this.ratings_.length - 1; goog.a11y.aria.setState(el, goog.a11y.aria.State.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. * @override */ 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()); } var ratingsElement = this.getElement(); goog.asserts.assert(ratingsElement, 'The DOM ratings element cannot be null.'); goog.a11y.aria.setState(ratingsElement, goog.a11y.aria.State.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; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides the base goog.ui.Control and goog.ui.ControlRenderer * for media types, as well as a media model consistent with the Yahoo Media RSS * specification {@link http://search.yahoo.com/mrss/}. * * The goog.ui.media.* package is basically a set of goog.ui.ControlRenderers * subclasses (such as goog.ui.media.Youtube, goog.ui.media.Picasa, etc) that * should all work with the same goog.ui.Control (goog.ui.media.Media) logic. * * This design guarantees that all different types of medias will behave alike * (in a base level) but will look different. * * In MVC terms, {@link goog.ui.media.Media} is the Controller, * {@link goog.ui.media.MediaRenderer} + CSS definitions are the View and * {@code goog.ui.media.MediaModel} is the data Model. Typically, * MediaRenderer will be subclassed to provide media specific renderers. * MediaRenderer subclasses are also responsible for defining the data model. * * This design is strongly patterned after: * http://go/closure_control_subclassing * * goog.ui.media.MediaRenderer handles the basic common ways to display media, * such as displaying tooltips, frames, minimize/maximize buttons, play buttons, * etc. Its subclasses are responsible for rendering media specific DOM * structures, like youtube flash players, picasa albums, etc. * * goog.ui.media.Media handles the Control of Medias, by listening to events * and firing the appropriate actions. It knows about the existence of captions, * minimize/maximize buttons, and takes all the actions needed to change states, * including delegating the UI actions to MediaRenderers. * * Although MediaRenderer is a base class designed to be subclassed, it can * be used by itself: * * <pre> * var renderer = new goog.ui.media.MediaRenderer(); * var control = new goog.ui.media.Media('hello world', renderer); * var control.render(goog.dom.getElement('mediaHolder')); * </pre> * * It requires a few CSS rules to be defined, which you should use to control * how the component is displayed. {@link goog.ui.ControlRenderer}s is very CSS * intensive, which separates the UI structure (the HTML DOM elements, which is * created by the {@code goog.ui.media.MediaRenderer}) from the UI view (which * nodes are visible, which aren't, where they are positioned. These are defined * on the CSS rules for each state). A few examples of CSS selectors that needs * to be defined are: * * <ul> * <li>.goog-ui-media * <li>.goog-ui-media-hover * <li>.goog-ui-media-selected * </ul> * * If you want to have different custom renderers CSS namespaces (eg. you may * want to show a small thumbnail, or you may want to hide the caption, etc), * you can do so by using: * * <pre> * var renderer = goog.ui.ControlRenderer.getCustomRenderer( * goog.ui.media.MediaRenderer, 'my-custom-namespace'); * var media = new goog.ui.media.Media('', renderer); * media.render(goog.dom.getElement('parent')); * </pre> * * Which will allow you to set your own .my-custom-namespace-hover, * .my-custom-namespace-selected CSS selectors. * * NOTE(user): it seems like an overkill to subclass goog.ui.Control instead of * using a factory, but we wanted to make sure we had more control over the * events for future media implementations. Since we intent to use it in many * different places, it makes sense to have a more flexible design that lets us * control the inner workings of goog.ui.Control. * * TODO(user): implement, as needed, the Media specific state changes UI, such * as minimize/maximize buttons, expand/close buttons, etc. * */ goog.provide('goog.ui.media.Media'); goog.provide('goog.ui.media.MediaRenderer'); goog.require('goog.style'); goog.require('goog.ui.Component.State'); goog.require('goog.ui.Control'); goog.require('goog.ui.ControlRenderer'); /** * Provides the control mechanism of media types. * * @param {goog.ui.media.MediaModel} dataModel The data model to be used by the * renderer. * @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.Control} */ goog.ui.media.Media = function(dataModel, opt_renderer, opt_domHelper) { goog.ui.Control.call(this, null, opt_renderer, opt_domHelper); // Sets up the data model. this.setDataModel(dataModel); this.setSupportedState(goog.ui.Component.State.OPENED, true); this.setSupportedState(goog.ui.Component.State.SELECTED, true); // TODO(user): had to do this to for mouseDownHandler not to // e.preventDefault(), because it was not allowing the event to reach the // flash player. figure out a better way to not e.preventDefault(). this.setAllowTextSelection(true); // Media items don't use RTL styles, so avoid accessing computed styles to // figure out if the control is RTL. this.setRightToLeft(false); }; goog.inherits(goog.ui.media.Media, goog.ui.Control); /** * The media data model used on the renderer. * * @type {goog.ui.media.MediaModel} * @private */ goog.ui.media.Media.prototype.dataModel_; /** * Sets the media model to be used on the renderer. * @param {goog.ui.media.MediaModel} dataModel The media model the renderer * should use. */ goog.ui.media.Media.prototype.setDataModel = function(dataModel) { this.dataModel_ = dataModel; }; /** * Gets the media model renderer is using. * @return {goog.ui.media.MediaModel} The media model being used. */ goog.ui.media.Media.prototype.getDataModel = function() { return this.dataModel_; }; /** * Base class of all media renderers. Provides the common renderer functionality * of medias. * * The current common functionality shared by Medias is to have an outer frame * that gets highlighted on mouse hover. * * TODO(user): implement more common UI behavior, as needed. * * NOTE(user): I am not enjoying how the subclasses are changing their state * through setState() ... maybe provide abstract methods like * goog.ui.media.MediaRenderer.prototype.preview = goog.abstractMethod; * goog.ui.media.MediaRenderer.prototype.play = goog.abstractMethod; * goog.ui.media.MediaRenderer.prototype.minimize = goog.abstractMethod; * goog.ui.media.MediaRenderer.prototype.maximize = goog.abstractMethod; * and call them on this parent class setState ? * * @constructor * @extends {goog.ui.ControlRenderer} */ goog.ui.media.MediaRenderer = function() { goog.ui.ControlRenderer.call(this); }; goog.inherits(goog.ui.media.MediaRenderer, goog.ui.ControlRenderer); /** * Builds the common DOM structure of medias. Builds an outer div, and appends * a child div with the {@code goog.ui.Control.getContent} content. Marks the * caption with a {@code this.getClassClass()} + '-caption' css flag, so that * specific renderers can hide/show the caption as desired. * * @param {goog.ui.Control} control The control instance. * @return {Element} The DOM structure that represents control. * @suppress {visibility} Calling protected control.setElementInternal(). * @override */ goog.ui.media.MediaRenderer.prototype.createDom = function(control) { var domHelper = control.getDomHelper(); var div = domHelper.createElement('div'); div.className = this.getClassNames(control).join(' '); var dataModel = control.getDataModel(); // Only creates DOMs if the data is available. if (dataModel.getCaption()) { var caption = domHelper.createElement('div'); caption.className = goog.getCssName(this.getCssClass(), 'caption'); caption.appendChild(domHelper.createDom( 'p', goog.getCssName(this.getCssClass(), 'caption-text'), dataModel.getCaption())); domHelper.appendChild(div, caption); } if (dataModel.getDescription()) { var description = domHelper.createElement('div'); description.className = goog.getCssName(this.getCssClass(), 'description'); description.appendChild(domHelper.createDom( 'p', goog.getCssName(this.getCssClass(), 'description-text'), dataModel.getDescription())); domHelper.appendChild(div, description); } // Creates thumbnails of the media. var thumbnails = dataModel.getThumbnails() || []; for (var index = 0; index < thumbnails.length; index++) { var thumbnail = thumbnails[index]; var thumbnailElement = domHelper.createElement('img'); thumbnailElement.src = thumbnail.getUrl(); thumbnailElement.className = this.getThumbnailCssName(index); // Check that the size is defined and that the size's height and width // are defined. Undefined height and width is deprecated but still // seems to exist in some cases. var size = thumbnail.getSize(); if (size && goog.isDefAndNotNull(size.height) && goog.isDefAndNotNull(size.width)) { goog.style.setSize(thumbnailElement, size); } domHelper.appendChild(div, thumbnailElement); } if (dataModel.getPlayer()) { // if medias have players, allow UI for a play button. var playButton = domHelper.createElement('div'); playButton.className = goog.getCssName(this.getCssClass(), 'playbutton'); domHelper.appendChild(div, playButton); } control.setElementInternal(div); this.setState( control, /** @type {goog.ui.Component.State} */ (control.getState()), true); return div; }; /** * Returns a renamable CSS class name for a numbered thumbnail. The default * implementation generates the class names goog-ui-media-thumbnail0, * goog-ui-media-thumbnail1, and the generic goog-ui-media-thumbnailn. * Subclasses can override this method when their media requires additional * specific class names (Applications are supposed to know how many thumbnails * media will have). * * @param {number} index The thumbnail index. * @return {string} CSS class name. * @protected */ goog.ui.media.MediaRenderer.prototype.getThumbnailCssName = function(index) { switch (index) { case 0: return goog.getCssName(this.getCssClass(), 'thumbnail0'); case 1: return goog.getCssName(this.getCssClass(), 'thumbnail1'); case 2: return goog.getCssName(this.getCssClass(), 'thumbnail2'); case 3: return goog.getCssName(this.getCssClass(), 'thumbnail3'); case 4: return goog.getCssName(this.getCssClass(), 'thumbnail4'); default: return goog.getCssName(this.getCssClass(), 'thumbnailn'); } };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview provides a reusable FlickrSet photo UI component given a public * FlickrSetModel. * * goog.ui.media.FlickrSet is actually a {@link goog.ui.ControlRenderer}, a * stateless class - that could/should be used as a Singleton with the static * method {@code goog.ui.media.FlickrSet.getInstance} -, that knows how to * render Flickr sets. It is designed to be used with a {@link goog.ui.Control}, * which will actually control the media renderer and provide the * {@link goog.ui.Component} base. This design guarantees that all different * types of medias will behave alike but will look different. * * goog.ui.media.FlickrSet expects a {@code goog.ui.media.FlickrSetModel} on * {@code goog.ui.Control.getModel} as data models, and renders a flash object * that will show the contents of that set. * * Example of usage: * * <pre> * var flickrSet = goog.ui.media.FlickrSetModel.newInstance(flickrSetUrl); * goog.ui.media.FlickrSet.newControl(flickrSet).render(); * </pre> * * FlickrSet medias currently support the following states: * * <ul> * <li> {@link goog.ui.Component.State.DISABLED}: shows 'flash not available' * <li> {@link goog.ui.Component.State.HOVER}: mouse cursor is over the video * <li> {@link goog.ui.Component.State.SELECTED}: flash video is shown * </ul> * * Which can be accessed by * <pre> * video.setEnabled(true); * video.setHighlighted(true); * video.setSelected(true); * </pre> * * * @supported IE6, FF2+, Safari. Requires flash to actually work. * * TODO(user): Support non flash users. Maybe show a link to the Flick set, * or fetch the data and rendering it using javascript (instead of a broken * 'You need to install flash' message). */ goog.provide('goog.ui.media.FlickrSet'); goog.provide('goog.ui.media.FlickrSetModel'); goog.require('goog.object'); goog.require('goog.ui.media.FlashObject'); goog.require('goog.ui.media.Media'); goog.require('goog.ui.media.MediaModel'); goog.require('goog.ui.media.MediaModel.Player'); goog.require('goog.ui.media.MediaRenderer'); /** * Subclasses a goog.ui.media.MediaRenderer to provide a FlickrSet specific * media renderer. * * This class knows how to parse FlickrSet URLs, and render the DOM structure * of flickr set players. This class is meant to be used as a singleton static * stateless class, that takes {@code goog.ui.media.Media} instances and renders * it. It expects {@code goog.ui.media.Media.getModel} to return a well formed, * previously constructed, set id {@see goog.ui.media.FlickrSet.parseUrl}, * which is the data model this renderer will use to construct the DOM * structure. {@see goog.ui.media.FlickrSet.newControl} for a example of * constructing a control with this renderer. * * This design is patterned after * http://go/closure_control_subclassing * * It uses {@link goog.ui.media.FlashObject} to embed the flash object. * * @constructor * @extends {goog.ui.media.MediaRenderer} */ goog.ui.media.FlickrSet = function() { goog.ui.media.MediaRenderer.call(this); }; goog.inherits(goog.ui.media.FlickrSet, goog.ui.media.MediaRenderer); goog.addSingletonGetter(goog.ui.media.FlickrSet); /** * Default CSS class to be applied to the root element of components rendered * by this renderer. * * @type {string} */ goog.ui.media.FlickrSet.CSS_CLASS = goog.getCssName('goog-ui-media-flickrset'); /** * Flash player URL. Uses Flickr's flash player by default. * * @type {string} * @private */ goog.ui.media.FlickrSet.flashUrl_ = 'http://www.flickr.com/apps/slideshow/show.swf?v=63961'; /** * A static convenient method to construct a goog.ui.media.Media control out of * a FlickrSet URL. It extracts the set id information on the URL, sets it * as the data model goog.ui.media.FlickrSet renderer uses, sets the states * supported by the renderer, and returns a Control that binds everything * together. This is what you should be using for constructing FlickrSet videos, * except if you need more fine control over the configuration. * * @param {goog.ui.media.FlickrSetModel} dataModel The Flickr Set data model. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for * document interaction. * @return {goog.ui.media.Media} A Control binded to the FlickrSet renderer. * @throws exception in case {@code flickrSetUrl} is an invalid flickr set URL. * TODO(user): use {@link goog.ui.media.MediaModel} once it is checked in. */ goog.ui.media.FlickrSet.newControl = function(dataModel, opt_domHelper) { var control = new goog.ui.media.Media( dataModel, goog.ui.media.FlickrSet.getInstance(), opt_domHelper); control.setSelected(true); return control; }; /** * A static method that sets which flash URL this class should use. Use this if * you want to host your own flash flickr player. * * @param {string} flashUrl The URL of the flash flickr player. */ goog.ui.media.FlickrSet.setFlashUrl = function(flashUrl) { goog.ui.media.FlickrSet.flashUrl_ = flashUrl; }; /** * Creates the initial DOM structure of the flickr set, which is basically a * the flash object pointing to a flickr set player. * * @param {goog.ui.Control} c The media control. * @return {Element} The DOM structure that represents this control. * @override */ goog.ui.media.FlickrSet.prototype.createDom = function(c) { var control = /** @type {goog.ui.media.Media} */ (c); var div = goog.ui.media.FlickrSet.superClass_.createDom.call(this, control); var model = /** @type {goog.ui.media.FlickrSetModel} */ (control.getDataModel()); // TODO(user): find out what is the policy about hosting this SWF. figure out // if it works over https. var flash = new goog.ui.media.FlashObject( model.getPlayer().getUrl() || '', control.getDomHelper()); flash.addFlashVars(model.getPlayer().getVars()); flash.render(div); return div; }; /** * 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.media.FlickrSet.prototype.getCssClass = function() { return goog.ui.media.FlickrSet.CSS_CLASS; }; /** * The {@code goog.ui.media.FlickrAlbum} media data model. It stores a required * {@code userId} and {@code setId} fields, sets the flickr Set URL, and * allows a few optional parameters. * * @param {string} userId The flickr userId associated with this set. * @param {string} setId The flickr setId associated with this set. * @param {string=} opt_caption An optional caption of the flickr set. * @param {string=} opt_description An optional description of the flickr set. * @constructor * @extends {goog.ui.media.MediaModel} */ goog.ui.media.FlickrSetModel = function(userId, setId, opt_caption, opt_description) { goog.ui.media.MediaModel.call( this, goog.ui.media.FlickrSetModel.buildUrl(userId, setId), opt_caption, opt_description, goog.ui.media.MediaModel.MimeType.FLASH); /** * The Flickr user id. * @type {string} * @private */ this.userId_ = userId; /** * The Flickr set id. * @type {string} * @private */ this.setId_ = setId; var flashVars = { 'offsite': 'true', 'lang': 'en', 'page_show_url': '/photos/' + userId + '/sets/' + setId + '/show/', 'page_show_back_url': '/photos/' + userId + '/sets/' + setId, 'set_id': setId }; var player = new goog.ui.media.MediaModel.Player( goog.ui.media.FlickrSet.flashUrl_, flashVars); this.setPlayer(player); }; goog.inherits(goog.ui.media.FlickrSetModel, goog.ui.media.MediaModel); /** * Regular expression used to extract the username and set id out of the flickr * URLs. * * Copied from http://go/markdownlite.js and {@link FlickrExtractor.xml}. * * @type {RegExp} * @private * @const */ goog.ui.media.FlickrSetModel.MATCHER_ = /(?:http:\/\/)?(?:www\.)?flickr\.com\/(?:photos\/([\d\w@\-]+)\/sets\/(\d+))\/?/i; /** * Takes a {@code flickrSetUrl} and extracts the flickr username and set id. * * @param {string} flickrSetUrl A Flickr set URL. * @param {string=} opt_caption An optional caption of the flickr set. * @param {string=} opt_description An optional description of the flickr set. * @return {goog.ui.media.FlickrSetModel} The data model that represents the * Flickr set. * @throws exception in case the parsing fails */ goog.ui.media.FlickrSetModel.newInstance = function(flickrSetUrl, opt_caption, opt_description) { if (goog.ui.media.FlickrSetModel.MATCHER_.test(flickrSetUrl)) { var data = goog.ui.media.FlickrSetModel.MATCHER_.exec(flickrSetUrl); return new goog.ui.media.FlickrSetModel( data[1], data[2], opt_caption, opt_description); } throw Error('failed to parse flickr url: ' + flickrSetUrl); }; /** * Takes a flickr username and set id and returns an URL. * * @param {string} userId The owner of the set. * @param {string} setId The set id. * @return {string} The URL of the set. */ goog.ui.media.FlickrSetModel.buildUrl = function(userId, setId) { return 'http://flickr.com/photos/' + userId + '/sets/' + setId; }; /** * Gets the Flickr user id. * @return {string} The Flickr user id. */ goog.ui.media.FlickrSetModel.prototype.getUserId = function() { return this.userId_; }; /** * Gets the Flickr set id. * @return {string} The Flickr set id. */ goog.ui.media.FlickrSetModel.prototype.getSetId = function() { return this.setId_; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview provides a reusable picasa album UI component given a public * picasa album URL. * * TODO(user): implement the javascript viewer, for users without flash. Get it * from the Gmail Picasa gadget. * * goog.ui.media.PicasaAlbum is actually a {@link goog.ui.ControlRenderer}, a * stateless class - that could/should be used as a Singleton with the static * method {@code goog.ui.media.PicasaAlbum.getInstance} -, that knows how to * render picasa albums. It is designed to be used with a * {@link goog.ui.Control}, which will actually control the media renderer and * provide the {@link goog.ui.Component} base. This design guarantees that all * different types of medias will behave alike but will look different. * * goog.ui.media.PicasaAlbum expects {@code goog.ui.media.PicasaAlbumModel}s on * {@code goog.ui.Control.getModel} as data models, and render a flash object * that will show a slideshow with the contents of that album URL. * * Example of usage: * * <pre> * var album = goog.ui.media.PicasaAlbumModel.newInstance( * 'http://picasaweb.google.com/username/SanFranciscoCalifornia'); * goog.ui.media.PicasaAlbum.newControl(album).render(); * </pre> * * picasa medias currently support the following states: * * <ul> * <li> {@link goog.ui.Component.State.DISABLED}: shows 'flash not available' * <li> {@link goog.ui.Component.State.HOVER}: mouse cursor is over the album * <li> {@link goog.ui.Component.State.SELECTED}: flash album is shown * </ul> * * Which can be accessed by * * <pre> * picasa.setEnabled(true); * picasa.setHighlighted(true); * picasa.setSelected(true); * </pre> * * * @supported IE6, FF2+, Safari. Requires flash to actually work. * * TODO(user): test on other browsers */ goog.provide('goog.ui.media.PicasaAlbum'); goog.provide('goog.ui.media.PicasaAlbumModel'); goog.require('goog.object'); goog.require('goog.ui.media.FlashObject'); goog.require('goog.ui.media.Media'); goog.require('goog.ui.media.MediaModel'); goog.require('goog.ui.media.MediaModel.Player'); goog.require('goog.ui.media.MediaRenderer'); /** * Subclasses a goog.ui.media.MediaRenderer to provide a Picasa specific media * renderer. * * This class knows how to parse picasa URLs, and render the DOM structure * of picasa album players and previews. This class is meant to be used as a * singleton static stateless class, that takes {@code goog.ui.media.Media} * instances and renders it. It expects {@code goog.ui.media.Media.getModel} to * return a well formed, previously constructed, object with a user and album * fields {@see goog.ui.media.PicasaAlbum.parseUrl}, which is the data model * this renderer will use to construct the DOM structure. * {@see goog.ui.media.PicasaAlbum.newControl} for a example of constructing a * control with this renderer. * * goog.ui.media.PicasaAlbum currently displays a picasa-made flash slideshow * with the photos, but could possibly display a handwritten js photo viewer, * in case flash is not available. * * This design is patterned after http://go/closure_control_subclassing * * It uses {@link goog.ui.media.FlashObject} to embed the flash object. * * @constructor * @extends {goog.ui.media.MediaRenderer} */ goog.ui.media.PicasaAlbum = function() { goog.ui.media.MediaRenderer.call(this); }; goog.inherits(goog.ui.media.PicasaAlbum, goog.ui.media.MediaRenderer); goog.addSingletonGetter(goog.ui.media.PicasaAlbum); /** * Default CSS class to be applied to the root element of components rendered * by this renderer. * * @type {string} */ goog.ui.media.PicasaAlbum.CSS_CLASS = goog.getCssName('goog-ui-media-picasa'); /** * A static convenient method to construct a goog.ui.media.Media control out of * a picasa data model. It sets it as the data model goog.ui.media.PicasaAlbum * renderer uses, sets the states supported by the renderer, and returns a * Control that binds everything together. This is what you should be using for * constructing Picasa albums, except if you need finer control over the * configuration. * * @param {goog.ui.media.PicasaAlbumModel} dataModel A picasa album data model. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for * document interaction. * @return {goog.ui.media.Media} A Control instance binded to the Picasa * renderer. */ goog.ui.media.PicasaAlbum.newControl = function(dataModel, opt_domHelper) { var control = new goog.ui.media.Media( dataModel, goog.ui.media.PicasaAlbum.getInstance(), opt_domHelper); control.setSelected(true); return control; }; /** * Creates the initial DOM structure of the picasa album, which is basically a * the flash object pointing to a flash picasa album player. * * @param {goog.ui.Control} c The media control. * @return {Element} The DOM structure that represents the control. * @override */ goog.ui.media.PicasaAlbum.prototype.createDom = function(c) { var control = /** @type {goog.ui.media.Media} */ (c); var div = goog.ui.media.PicasaAlbum.superClass_.createDom.call(this, control); var picasaAlbum = /** @type {goog.ui.media.PicasaAlbumModel} */ (control.getDataModel()); var authParam = picasaAlbum.getAuthKey() ? ('&authkey=' + picasaAlbum.getAuthKey()) : ''; var flash = new goog.ui.media.FlashObject( picasaAlbum.getPlayer().getUrl() || '', control.getDomHelper()); flash.addFlashVars(picasaAlbum.getPlayer().getVars()); flash.render(div); return div; }; /** * 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.media.PicasaAlbum.prototype.getCssClass = function() { return goog.ui.media.PicasaAlbum.CSS_CLASS; }; /** * The {@code goog.ui.media.PicasaAlbum} media data model. It stores a required * {@code userId} and {@code albumId} fields, sets the picasa album URL, and * allows a few optional parameters. * * @param {string} userId The picasa userId associated with this album. * @param {string} albumId The picasa albumId associated with this album. * @param {string=} opt_authKey An optional authentication key, used on private * albums. * @param {string=} opt_caption An optional caption of the picasa album. * @param {string=} opt_description An optional description of the picasa album. * @param {boolean=} opt_autoplay Whether to autoplay the slideshow. * @constructor * @extends {goog.ui.media.MediaModel} */ goog.ui.media.PicasaAlbumModel = function(userId, albumId, opt_authKey, opt_caption, opt_description, opt_autoplay) { goog.ui.media.MediaModel.call( this, goog.ui.media.PicasaAlbumModel.buildUrl(userId, albumId), opt_caption, opt_description, goog.ui.media.MediaModel.MimeType.FLASH); /** * The Picasa user id. * @type {string} * @private */ this.userId_ = userId; /** * The Picasa album id. * @type {string} * @private */ this.albumId_ = albumId; /** * The Picasa authentication key, used on private albums. * @type {?string} * @private */ this.authKey_ = opt_authKey || null; var authParam = opt_authKey ? ('&authkey=' + opt_authKey) : ''; var flashVars = { 'host': 'picasaweb.google.com', 'RGB': '0x000000', 'feed': 'http://picasaweb.google.com/data/feed/api/user/' + userId + '/album/' + albumId + '?kind=photo&alt=rss' + authParam }; flashVars[opt_autoplay ? 'autoplay' : 'noautoplay'] = '1'; var player = new goog.ui.media.MediaModel.Player( 'http://picasaweb.google.com/s/c/bin/slideshow.swf', flashVars); this.setPlayer(player); }; goog.inherits(goog.ui.media.PicasaAlbumModel, goog.ui.media.MediaModel); /** * Regular expression used to extract the picasa username and albumid out of * picasa URLs. * * Copied from http://go/markdownlite.js, * and {@link PicasaWebExtractor.xml}. * * @type {RegExp} * @private * @const */ goog.ui.media.PicasaAlbumModel.MATCHER_ = /https?:\/\/(?:www\.)?picasaweb\.(?:google\.)?com\/([\d\w\.]+)\/([\d\w_\-\.]+)(?:\?[\w\d\-_=&amp;;\.]*&?authKey=([\w\d\-_=;\.]+))?(?:#([\d]+)?)?/im; /** * Gets a {@code picasaUrl} and extracts the user and album id. * * @param {string} picasaUrl A picasa album URL. * @param {string=} opt_caption An optional caption of the picasa album. * @param {string=} opt_description An optional description of the picasa album. * @param {boolean=} opt_autoplay Whether to autoplay the slideshow. * @return {goog.ui.media.PicasaAlbumModel} The picasa album data model that * represents the picasa URL. * @throws exception in case the parsing fails */ goog.ui.media.PicasaAlbumModel.newInstance = function(picasaUrl, opt_caption, opt_description, opt_autoplay) { if (goog.ui.media.PicasaAlbumModel.MATCHER_.test(picasaUrl)) { var data = goog.ui.media.PicasaAlbumModel.MATCHER_.exec(picasaUrl); return new goog.ui.media.PicasaAlbumModel( data[1], data[2], data[3], opt_caption, opt_description, opt_autoplay); } throw Error('failed to parse user and album from picasa url: ' + picasaUrl); }; /** * The opposite of {@code newInstance}: takes an {@code userId} and an * {@code albumId} and builds a URL. * * @param {string} userId The user that owns the album. * @param {string} albumId The album id. * @return {string} The URL of the album. */ goog.ui.media.PicasaAlbumModel.buildUrl = function(userId, albumId) { return 'http://picasaweb.google.com/' + userId + '/' + albumId; }; /** * Gets the Picasa user id. * @return {string} The Picasa user id. */ goog.ui.media.PicasaAlbumModel.prototype.getUserId = function() { return this.userId_; }; /** * Gets the Picasa album id. * @return {string} The Picasa album id. */ goog.ui.media.PicasaAlbumModel.prototype.getAlbumId = function() { return this.albumId_; }; /** * Gets the Picasa album authentication key. * @return {?string} The Picasa album authentication key. */ goog.ui.media.PicasaAlbumModel.prototype.getAuthKey = function() { return this.authKey_; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview provides a reusable mp3 UI component given a mp3 URL. * * goog.ui.media.Mp3 is actually a {@link goog.ui.ControlRenderer}, a stateless * class - that could/should be used as a Singleton with the static method * {@code goog.ui.media.Mp3.getInstance} -, that knows how to render Mp3s. It is * designed to be used with a {@link goog.ui.Control}, which will actually * control the media renderer and provide the {@link goog.ui.Component} base. * This design guarantees that all different types of medias will behave alike * but will look different. * * goog.ui.media.Mp3 expects mp3 urls on {@code goog.ui.Control.getModel} as * data models, and render a flash object that will play that URL. * * Example of usage: * * <pre> * goog.ui.media.Mp3.newControl('http://hostname/file.mp3').render(); * </pre> * * Mp3 medias currently support the following states: * * <ul> * <li> {@link goog.ui.Component.State.DISABLED}: shows 'flash not available' * <li> {@link goog.ui.Component.State.HOVER}: mouse cursor is over the mp3 * <li> {@link goog.ui.Component.State.SELECTED}: mp3 is playing * </ul> * * Which can be accessed by * * <pre> * mp3.setEnabled(true); * mp3.setHighlighted(true); * mp3.setSelected(true); * </pre> * * * @supported IE6, FF2+, Safari. Requires flash to actually work. * * TODO(user): test on other browsers */ goog.provide('goog.ui.media.Mp3'); goog.require('goog.string'); goog.require('goog.ui.media.FlashObject'); goog.require('goog.ui.media.Media'); goog.require('goog.ui.media.MediaRenderer'); /** * Subclasses a goog.ui.media.MediaRenderer to provide a Mp3 specific media * renderer. * * This class knows how to parse mp3 URLs, and render the DOM structure * of mp3 flash players. This class is meant to be used as a singleton static * stateless class, that takes {@code goog.ui.media.Media} instances and renders * it. It expects {@code goog.ui.media.Media.getModel} to return a well formed, * previously checked, mp3 URL {@see goog.ui.media.PicasaAlbum.parseUrl}, * which is the data model this renderer will use to construct the DOM * structure. {@see goog.ui.media.PicasaAlbum.newControl} for an example of * constructing a control with this renderer. * * This design is patterned after http://go/closure_control_subclassing * * It uses {@link goog.ui.media.FlashObject} to embed the flash object. * * @constructor * @extends {goog.ui.media.MediaRenderer} */ goog.ui.media.Mp3 = function() { goog.ui.media.MediaRenderer.call(this); }; goog.inherits(goog.ui.media.Mp3, goog.ui.media.MediaRenderer); goog.addSingletonGetter(goog.ui.media.Mp3); /** * Flash player arguments. We expect that {@code flashUrl_} will contain a flash * movie that takes an audioUrl parameter on its URL, containing the URL of the * mp3 to be played. * * @type {string} * @private */ goog.ui.media.Mp3.PLAYER_ARGUMENTS_ = 'audioUrl=%s'; /** * Default CSS class to be applied to the root element of components rendered * by this renderer. * * @type {string} */ goog.ui.media.Mp3.CSS_CLASS = goog.getCssName('goog-ui-media-mp3'); /** * Flash player URL. Uses Google Reader's mp3 flash player by default. * * @type {string} * @private */ goog.ui.media.Mp3.flashUrl_ = 'http://www.google.com/reader/ui/3523697345-audio-player.swf'; /** * Regular expression to check if a given URL is a valid mp3 URL. * * Copied from http://go/markdownlite.js. * * NOTE(user): although it would be easier to use goog.string.endsWith('.mp3'), * in the future, we want to provide media inlining, which is basically getting * a text and replacing all mp3 references with an mp3 player, so it makes sense * to share the same regular expression to match everything. * * @type {RegExp} */ goog.ui.media.Mp3.MATCHER = /(https?:\/\/[\w-%&\/.=:#\+~\(\)]+\.(mp3)+(\?[\w-%&\/.=:#\+~\(\)]+)?)/i; /** * A static convenient method to construct a goog.ui.media.Media control out of * a mp3 URL. It checks the mp3 URL, sets it as the data model * goog.ui.media.Mp3 renderer uses, sets the states supported by the renderer, * and returns a Control that binds everything together. This is what you * should be using for constructing Mp3 videos, except if you need more fine * control over the configuration. * * @param {goog.ui.media.MediaModel} dataModel A media model that must contain * an mp3 url on {@code dataModel.getUrl}. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for * document interaction. * @return {goog.ui.media.Media} A goog.ui.Control subclass with the mp3 * renderer. */ goog.ui.media.Mp3.newControl = function(dataModel, opt_domHelper) { var control = new goog.ui.media.Media( dataModel, goog.ui.media.Mp3.getInstance(), opt_domHelper); // mp3 ui doesn't have a non selected view: it shows the mp3 player by // default. control.setSelected(true); return control; }; /** * A static method that sets which flash URL this class should use. Use this if * you want to host your own flash mp3 player. * * @param {string} flashUrl The URL of the flash mp3 player. */ goog.ui.media.Mp3.setFlashUrl = function(flashUrl) { goog.ui.media.Mp3.flashUrl_ = flashUrl; }; /** * A static method that builds a URL that will contain the flash player that * will play the {@code mp3Url}. * * @param {string} mp3Url The URL of the mp3 music. * @return {string} An URL of a flash player that will know how to play the * given {@code mp3Url}. */ goog.ui.media.Mp3.buildFlashUrl = function(mp3Url) { var flashUrl = goog.ui.media.Mp3.flashUrl_ + '?' + goog.string.subs( goog.ui.media.Mp3.PLAYER_ARGUMENTS_, goog.string.urlEncode(mp3Url)); return flashUrl; }; /** * Creates the initial DOM structure of a mp3 video, which is basically a * the flash object pointing to a flash mp3 player. * * @param {goog.ui.Control} c The media control. * @return {Element} A DOM structure that represents the control. * @override */ goog.ui.media.Mp3.prototype.createDom = function(c) { var control = /** @type {goog.ui.media.Media} */ (c); var div = goog.ui.media.Mp3.superClass_.createDom.call(this, control); var dataModel = /** @type {goog.ui.media.MediaModel} */ (control.getDataModel()); var flashUrl = goog.ui.media.Mp3.flashUrl_ + '?' + goog.string.subs( goog.ui.media.Mp3.PLAYER_ARGUMENTS_, goog.string.urlEncode(dataModel.getUrl())); var flash = new goog.ui.media.FlashObject( dataModel.getPlayer().getUrl(), control.getDomHelper()); flash.setFlashVar('playerMode', 'embedded'); flash.render(div); return div; }; /** * 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.media.Mp3.prototype.getCssClass = function() { return goog.ui.media.Mp3.CSS_CLASS; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview provides a reusable youtube UI component given a youtube data * model. * * goog.ui.media.Youtube is actually a {@link goog.ui.ControlRenderer}, a * stateless class - that could/should be used as a Singleton with the static * method {@code goog.ui.media.Youtube.getInstance} -, that knows how to render * youtube videos. It is designed to be used with a {@link goog.ui.Control}, * which will actually control the media renderer and provide the * {@link goog.ui.Component} base. This design guarantees that all different * types of medias will behave alike but will look different. * * goog.ui.media.Youtube expects {@code goog.ui.media.YoutubeModel} on * {@code goog.ui.Control.getModel} as data models, and render a flash object * that will play that URL. * * Example of usage: * * <pre> * var video = goog.ui.media.YoutubeModel.newInstance( * 'http://www.youtube.com/watch?v=ddl5f44spwQ'); * goog.ui.media.Youtube.newControl(video).render(); * </pre> * * youtube medias currently support the following states: * * <ul> * <li> {@link goog.ui.Component.State.DISABLED}: shows 'flash not available' * <li> {@link goog.ui.Component.State.HOVER}: mouse cursor is over the video * <li> {@link !goog.ui.Component.State.SELECTED}: a static thumbnail is shown * <li> {@link goog.ui.Component.State.SELECTED}: video is playing * </ul> * * Which can be accessed by * <pre> * youtube.setEnabled(true); * youtube.setHighlighted(true); * youtube.setSelected(true); * </pre> * * This package also provides a few static auxiliary methods, such as: * * <pre> * var videoId = goog.ui.media.Youtube.parseUrl( * 'http://www.youtube.com/watch?v=ddl5f44spwQ'); * </pre> * * * @supported IE6, FF2+, Safari. Requires flash to actually work. * * TODO(user): test on other browsers */ goog.provide('goog.ui.media.Youtube'); goog.provide('goog.ui.media.YoutubeModel'); goog.require('goog.string'); goog.require('goog.ui.Component.Error'); goog.require('goog.ui.Component.State'); goog.require('goog.ui.media.FlashObject'); goog.require('goog.ui.media.Media'); goog.require('goog.ui.media.MediaModel'); goog.require('goog.ui.media.MediaModel.Player'); goog.require('goog.ui.media.MediaModel.Thumbnail'); goog.require('goog.ui.media.MediaRenderer'); /** * Subclasses a goog.ui.media.MediaRenderer to provide a Youtube specific media * renderer. * * This class knows how to parse youtube urls, and render the DOM structure * of youtube video players and previews. This class is meant to be used as a * singleton static stateless class, that takes {@code goog.ui.media.Media} * instances and renders it. It expects {@code goog.ui.media.Media.getModel} to * return a well formed, previously constructed, youtube video id, which is the * data model this renderer will use to construct the DOM structure. * {@see goog.ui.media.Youtube.newControl} for a example of constructing a * control with this renderer. * * goog.ui.media.Youtube currently supports all {@link goog.ui.Component.State}. * It will change its DOM structure between SELECTED and !SELECTED, and rely on * CSS definitions on the others. On !SELECTED, the renderer will render a * youtube static <img>, with a thumbnail of the video. On SELECTED, the * renderer will append to the DOM a flash object, that contains the youtube * video. * * This design is patterned after http://go/closure_control_subclassing * * It uses {@link goog.ui.media.FlashObject} to embed the flash object. * * @constructor * @extends {goog.ui.media.MediaRenderer} */ goog.ui.media.Youtube = function() { goog.ui.media.MediaRenderer.call(this); }; goog.inherits(goog.ui.media.Youtube, goog.ui.media.MediaRenderer); goog.addSingletonGetter(goog.ui.media.Youtube); /** * A static convenient method to construct a goog.ui.media.Media control out of * a youtube model. It sets it as the data model goog.ui.media.Youtube renderer * uses, sets the states supported by the renderer, and returns a Control that * binds everything together. This is what you should be using for constructing * Youtube videos, except if you need finer control over the configuration. * * @param {goog.ui.media.YoutubeModel} youtubeModel The youtube data model. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for * document interaction. * @return {goog.ui.media.Media} A Control binded to the youtube renderer. * @suppress {visibility} Calling protected control.setStateInternal(). */ goog.ui.media.Youtube.newControl = function(youtubeModel, opt_domHelper) { var control = new goog.ui.media.Media( youtubeModel, goog.ui.media.Youtube.getInstance(), opt_domHelper); control.setStateInternal(goog.ui.Component.State.ACTIVE); return control; }; /** * Default CSS class to be applied to the root element of components rendered * by this renderer. * @type {string} */ goog.ui.media.Youtube.CSS_CLASS = goog.getCssName('goog-ui-media-youtube'); /** * Changes the state of a {@code control}. Currently only changes the DOM * structure when the youtube movie is SELECTED (by default fired by a MOUSEUP * on the thumbnail), which means we have to embed the youtube flash video and * play it. * * @param {goog.ui.Control} c The media control. * @param {goog.ui.Component.State} state The state to be set or cleared. * @param {boolean} enable Whether the state is enabled or disabled. * @override */ goog.ui.media.Youtube.prototype.setState = function(c, state, enable) { var control = /** @type {goog.ui.media.Media} */ (c); goog.ui.media.Youtube.superClass_.setState.call(this, control, state, enable); // control.createDom has to be called before any state is set. // Use control.setStateInternal if you need to set states if (!control.getElement()) { throw Error(goog.ui.Component.Error.STATE_INVALID); } var domHelper = control.getDomHelper(); var dataModel = /** @type {goog.ui.media.YoutubeModel} */ (control.getDataModel()); if (!!(state & goog.ui.Component.State.SELECTED) && enable) { var flashEls = domHelper.getElementsByTagNameAndClass( 'div', goog.ui.media.FlashObject.CSS_CLASS, control.getElement()); if (flashEls.length > 0) { return; } var youtubeFlash = new goog.ui.media.FlashObject( dataModel.getPlayer().getUrl() || '', domHelper); control.addChild(youtubeFlash, true); } }; /** * 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.media.Youtube.prototype.getCssClass = function() { return goog.ui.media.Youtube.CSS_CLASS; }; /** * The {@code goog.ui.media.Youtube} media data model. It stores a required * {@code videoId} field, sets the youtube URL, and allows a few optional * parameters. * * @param {string} videoId The youtube video id. * @param {string=} opt_caption An optional caption of the youtube video. * @param {string=} opt_description An optional description of the youtube * video. * @constructor * @extends {goog.ui.media.MediaModel} */ goog.ui.media.YoutubeModel = function(videoId, opt_caption, opt_description) { goog.ui.media.MediaModel.call( this, goog.ui.media.YoutubeModel.buildUrl(videoId), opt_caption, opt_description, goog.ui.media.MediaModel.MimeType.FLASH); /** * The Youtube video id. * @type {string} * @private */ this.videoId_ = videoId; this.setThumbnails([new goog.ui.media.MediaModel.Thumbnail( goog.ui.media.YoutubeModel.getThumbnailUrl(videoId))]); this.setPlayer(new goog.ui.media.MediaModel.Player( this.getFlashUrl(videoId, true))); }; goog.inherits(goog.ui.media.YoutubeModel, goog.ui.media.MediaModel); /** * A youtube regular expression matcher. It matches the VIDEOID of URLs like * http://www.youtube.com/watch?v=VIDEOID. Based on: * googledata/contentonebox/opencob/specs/common/YTPublicExtractorCard.xml * @type {RegExp} * @private * @const */ // Be careful about the placement of the dashes in the character classes. Eg, // use "[\\w=-]" instead of "[\\w-=]" if you mean to include the dash as a // character and not create a character range like "[a-f]". goog.ui.media.YoutubeModel.MATCHER_ = new RegExp( // Lead in. 'http://(?:[a-zA-Z]{2,3}\\.)?' + // Watch URL prefix. This should handle new URLs of the form: // http://www.youtube.com/watch#!v=jqxENMKaeCU&feature=related // where the parameters appear after "#!" instead of "?". '(?:youtube\\.com/watch)' + // Get the video id: // The video ID is a parameter v=[videoid] either right after the "?" // or after some other parameters. '(?:\\?(?:[\\w=-]+&(?:amp;)?)*v=([\\w-]+)' + '(?:&(?:amp;)?[\\w=-]+)*)?' + // Get any extra arguments in the URL's hash part. '(?:#[!]?(?:' + // Video ID from the v=[videoid] parameter, optionally surrounded by other // & separated parameters. '(?:(?:[\\w=-]+&(?:amp;)?)*(?:v=([\\w-]+))' + '(?:&(?:amp;)?[\\w=-]+)*)' + '|' + // Continue supporting "?" for the video ID // and "#" for other hash parameters. '(?:[\\w=&-]+)' + '))?' + // Should terminate with a non-word, non-dash (-) character. '[^\\w-]?', 'i'); /** * A auxiliary static method that parses a youtube URL, extracting the ID of the * video, and builds a YoutubeModel. * * @param {string} youtubeUrl A youtube URL. * @param {string=} opt_caption An optional caption of the youtube video. * @param {string=} opt_description An optional description of the youtube * video. * @return {goog.ui.media.YoutubeModel} The data model that represents the * youtube URL. * @see goog.ui.media.YoutubeModel.getVideoId() * @throws Error in case the parsing fails. */ goog.ui.media.YoutubeModel.newInstance = function(youtubeUrl, opt_caption, opt_description) { var extract = goog.ui.media.YoutubeModel.MATCHER_.exec(youtubeUrl); if (extract) { var videoId = extract[1] || extract[2]; return new goog.ui.media.YoutubeModel( videoId, opt_caption, opt_description); } throw Error('failed to parse video id from youtube url: ' + youtubeUrl); }; /** * The opposite of {@code goog.ui.media.Youtube.newInstance}: it takes a videoId * and returns a youtube URL. * * @param {string} videoId The youtube video ID. * @return {string} The youtube URL. */ goog.ui.media.YoutubeModel.buildUrl = function(videoId) { return 'http://www.youtube.com/watch?v=' + goog.string.urlEncode(videoId); }; /** * A static auxiliary method that builds a static image URL with a preview of * the youtube video. * * NOTE(user): patterned after Gmail's gadgets/youtube, * * TODO(user): how do I specify the width/height of the resulting image on the * url ? is there an official API for http://ytimg.com ? * * @param {string} youtubeId The youtube video ID. * @return {string} An URL that contains an image with a preview of the youtube * movie. */ goog.ui.media.YoutubeModel.getThumbnailUrl = function(youtubeId) { return 'http://i.ytimg.com/vi/' + youtubeId + '/default.jpg'; }; /** * An auxiliary method that builds URL of the flash movie to be embedded, * out of the youtube video id. * * @param {string} videoId The youtube video ID. * @param {boolean=} opt_autoplay Whether the flash movie should start playing * as soon as it is shown, or if it should show a 'play' button. * @return {string} The flash URL to be embedded on the page. */ goog.ui.media.YoutubeModel.prototype.getFlashUrl = function(videoId, opt_autoplay) { var autoplay = opt_autoplay ? '&autoplay=1' : ''; // YouTube video ids are extracted from youtube URLs, which are user // generated input. the video id is later used to embed a flash object, // which is generated through HTML construction. We goog.string.urlEncode // the video id to make sure the URL is safe to be embedded. return 'http://www.youtube.com/v/' + goog.string.urlEncode(videoId) + '&hl=en&fs=1' + autoplay; }; /** * Gets the Youtube video id. * @return {string} The Youtube video id. */ goog.ui.media.YoutubeModel.prototype.getVideoId = function() { return this.videoId_; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides the base media model consistent with the Yahoo Media * RSS specification {@link http://search.yahoo.com/mrss/}. */ goog.provide('goog.ui.media.MediaModel'); goog.provide('goog.ui.media.MediaModel.Category'); goog.provide('goog.ui.media.MediaModel.Credit'); goog.provide('goog.ui.media.MediaModel.Credit.Role'); goog.provide('goog.ui.media.MediaModel.Credit.Scheme'); goog.provide('goog.ui.media.MediaModel.Medium'); goog.provide('goog.ui.media.MediaModel.MimeType'); goog.provide('goog.ui.media.MediaModel.Player'); goog.provide('goog.ui.media.MediaModel.SubTitle'); goog.provide('goog.ui.media.MediaModel.Thumbnail'); goog.require('goog.array'); /** * An base data value class for all media data models. * * MediaModels are exact matches to the fields defined in the Yahoo RSS media * specification {@link http://search.yahoo.com/mrss/}. * * The current common data shared by medias is to have URLs, mime types, * captions, descriptions, thumbnails and players. Some of these may not be * available, or applications may not want to render them, so {@code null} * values are allowed. {@code goog.ui.media.MediaRenderer} checks whether the * values are available before creating DOMs for them. * * TODO(user): support asynchronous data models by subclassing * {@link goog.events.EventTarget} or {@link goog.ds.DataNode}. Understand why * {@link http://goto/datanode} is not available in closure. Add setters to * MediaModel once this is supported. * * @param {string=} opt_url An optional URL of the media. * @param {string=} opt_caption An optional caption of the media. * @param {string=} opt_description An optional description of the media. * @param {goog.ui.media.MediaModel.MimeType=} opt_type The type of the media. * @param {goog.ui.media.MediaModel.Medium=} opt_medium The medium of the media. * @param {number=} opt_duration The duration of the media in seconds. * @param {number=} opt_width The width of the media in pixels. * @param {number=} opt_height The height of the media in pixels. * @constructor */ goog.ui.media.MediaModel = function(opt_url, opt_caption, opt_description, opt_type, opt_medium, opt_duration, opt_width, opt_height) { /** * The URL of the media. * @type {string|undefined} * @private */ this.url_ = opt_url; /** * The caption of the media. * @type {string|undefined} * @private */ this.caption_ = opt_caption; /** * A description of the media, typically user generated comments about it. * @type {string|undefined} * @private */ this.description_ = opt_description; /** * The mime type of the media. * @type {goog.ui.media.MediaModel.MimeType|undefined} * @private */ this.type_ = opt_type; /** * The medium of the media. * @type {goog.ui.media.MediaModel.Medium|undefined} * @private */ this.medium_ = opt_medium; /** * The duration of the media in seconds. * @type {number|undefined} * @private */ this.duration_ = opt_duration; /** * The width of the media in pixels. * @type {number|undefined} * @private */ this.width_ = opt_width; /** * The height of the media in pixels. * @type {number|undefined} * @private */ this.height_ = opt_height; /** * A list of thumbnails representations of the media (eg different sizes of * the same photo, etc). * @type {Array.<goog.ui.media.MediaModel.Thumbnail>} * @private */ this.thumbnails_ = []; /** * The list of categories that are applied to this media. * @type {Array.<goog.ui.media.MediaModel.Category>} * @private */ this.categories_ = []; /** * The list of credits that pertain to this media object. * @type {!Array.<goog.ui.media.MediaModel.Credit>} * @private */ this.credits_ = []; /** * The list of subtitles for the media object. * @type {Array.<goog.ui.media.MediaModel.SubTitle>} * @private */ this.subTitles_ = []; }; /** * The supported media mime types, a subset of the media types found here: * {@link http://www.iana.org/assignments/media-types/} and here * {@link http://en.wikipedia.org/wiki/Internet_media_type} * @enum {string} */ goog.ui.media.MediaModel.MimeType = { HTML: 'text/html', PLAIN: 'text/plain', FLASH: 'application/x-shockwave-flash', JPEG: 'image/jpeg', GIF: 'image/gif', PNG: 'image/png' }; /** * Supported mediums, found here: * {@link http://video.search.yahoo.com/mrss} * @enum {string} */ goog.ui.media.MediaModel.Medium = { IMAGE: 'image', AUDIO: 'audio', VIDEO: 'video', DOCUMENT: 'document', EXECUTABLE: 'executable' }; /** * The media player. * @type {goog.ui.media.MediaModel.Player} * @private */ goog.ui.media.MediaModel.prototype.player_; /** * Gets the URL of this media. * @return {string|undefined} The URL of the media. */ goog.ui.media.MediaModel.prototype.getUrl = function() { return this.url_; }; /** * Sets the URL of this media. * @param {string} url The URL of the media. * @return {!goog.ui.media.MediaModel} The object itself, used for chaining. */ goog.ui.media.MediaModel.prototype.setUrl = function(url) { this.url_ = url; return this; }; /** * Gets the caption of this media. * @return {string|undefined} The caption of the media. */ goog.ui.media.MediaModel.prototype.getCaption = function() { return this.caption_; }; /** * Sets the caption of this media. * @param {string} caption The caption of the media. * @return {!goog.ui.media.MediaModel} The object itself, used for chaining. */ goog.ui.media.MediaModel.prototype.setCaption = function(caption) { this.caption_ = caption; return this; }; /** * Gets the media mime type. * @return {goog.ui.media.MediaModel.MimeType|undefined} The media mime type. */ goog.ui.media.MediaModel.prototype.getType = function() { return this.type_; }; /** * Sets the media mime type. * @param {goog.ui.media.MediaModel.MimeType} type The media mime type. * @return {!goog.ui.media.MediaModel} The object itself, used for chaining. */ goog.ui.media.MediaModel.prototype.setType = function(type) { this.type_ = type; return this; }; /** * Gets the media medium. * @return {goog.ui.media.MediaModel.Medium|undefined} The media medium. */ goog.ui.media.MediaModel.prototype.getMedium = function() { return this.medium_; }; /** * Sets the media medium. * @param {goog.ui.media.MediaModel.Medium} medium The media medium. * @return {!goog.ui.media.MediaModel} The object itself, used for chaining. */ goog.ui.media.MediaModel.prototype.setMedium = function(medium) { this.medium_ = medium; return this; }; /** * Gets the description of this media. * @return {string|undefined} The description of the media. */ goog.ui.media.MediaModel.prototype.getDescription = function() { return this.description_; }; /** * Sets the description of this media. * @param {string} description The description of the media. * @return {!goog.ui.media.MediaModel} The object itself, used for chaining. */ goog.ui.media.MediaModel.prototype.setDescription = function(description) { this.description_ = description; return this; }; /** * Gets the thumbnail urls. * @return {Array.<goog.ui.media.MediaModel.Thumbnail>} The list of thumbnails. */ goog.ui.media.MediaModel.prototype.getThumbnails = function() { return this.thumbnails_; }; /** * Sets the thumbnail list. * @param {Array.<goog.ui.media.MediaModel.Thumbnail>} thumbnails The list of * thumbnail. * @return {!goog.ui.media.MediaModel} The object itself, used for chaining. */ goog.ui.media.MediaModel.prototype.setThumbnails = function(thumbnails) { this.thumbnails_ = thumbnails; return this; }; /** * Gets the duration of the media. * @return {number|undefined} The duration in seconds. */ goog.ui.media.MediaModel.prototype.getDuration = function() { return this.duration_; }; /** * Sets duration of the media. * @param {number} duration The duration of the media, in seconds. * @return {!goog.ui.media.MediaModel} The object itself, used for chaining. */ goog.ui.media.MediaModel.prototype.setDuration = function(duration) { this.duration_ = duration; return this; }; /** * Gets the width of the media in pixels. * @return {number|undefined} The width in pixels. */ goog.ui.media.MediaModel.prototype.getWidth = function() { return this.width_; }; /** * Sets the width of the media. * @param {number} width The width of the media, in pixels. * @return {!goog.ui.media.MediaModel} The object itself, used for chaining. */ goog.ui.media.MediaModel.prototype.setWidth = function(width) { this.width_ = width; return this; }; /** * Gets the height of the media in pixels. * @return {number|undefined} The height in pixels. */ goog.ui.media.MediaModel.prototype.getHeight = function() { return this.height_; }; /** * Sets the height of the media. * @param {number} height The height of the media, in pixels. * @return {!goog.ui.media.MediaModel} The object itself, used for chaining. */ goog.ui.media.MediaModel.prototype.setHeight = function(height) { this.height_ = height; return this; }; /** * Gets the player data. * @return {goog.ui.media.MediaModel.Player|undefined} The media player data. */ goog.ui.media.MediaModel.prototype.getPlayer = function() { return this.player_; }; /** * Sets the player data. * @param {goog.ui.media.MediaModel.Player} player The media player data. * @return {!goog.ui.media.MediaModel} The object itself, used for chaining. */ goog.ui.media.MediaModel.prototype.setPlayer = function(player) { this.player_ = player; return this; }; /** * Gets the categories of the media. * @return {Array.<goog.ui.media.MediaModel.Category>} The categories of the * media. */ goog.ui.media.MediaModel.prototype.getCategories = function() { return this.categories_; }; /** * Sets the categories of the media * @param {Array.<goog.ui.media.MediaModel.Category>} categories The categories * of the media. * @return {!goog.ui.media.MediaModel} The object itself, used for chaining. */ goog.ui.media.MediaModel.prototype.setCategories = function(categories) { this.categories_ = categories; return this; }; /** * Finds the first category with the given scheme. * @param {string} scheme The scheme to search for. * @return {goog.ui.media.MediaModel.Category} The category that has the * given scheme. May be null. */ goog.ui.media.MediaModel.prototype.findCategoryWithScheme = function(scheme) { if (!this.categories_) { return null; } var category = goog.array.find(this.categories_, function(category) { return category ? (scheme == category.getScheme()) : false; }); return /** @type {goog.ui.media.MediaModel.Category} */ (category); }; /** * Gets the credits of the media. * @return {!Array.<goog.ui.media.MediaModel.Credit>} The credits of the media. */ goog.ui.media.MediaModel.prototype.getCredits = function() { return this.credits_; }; /** * Sets the credits of the media * @param {!Array.<goog.ui.media.MediaModel.Credit>} credits The credits of the * media. * @return {!goog.ui.media.MediaModel} The object itself, used for chaining. */ goog.ui.media.MediaModel.prototype.setCredits = function(credits) { this.credits_ = credits; return this; }; /** * Finds all credits with the given role. * @param {string} role The role to search for. * @return {!Array.<!goog.ui.media.MediaModel.Credit>} An array of credits * with the given role. May be empty. */ goog.ui.media.MediaModel.prototype.findCreditsWithRole = function(role) { var credits = goog.array.filter(this.credits_, function(credit) { return role == credit.getRole(); }); return /** @type {!Array.<!goog.ui.media.MediaModel.Credit>} */ (credits); }; /** * Gets the subtitles for the media. * @return {Array.<goog.ui.media.MediaModel.SubTitle>} The subtitles. */ goog.ui.media.MediaModel.prototype.getSubTitles = function() { return this.subTitles_; }; /** * Sets the subtitles for the media * @param {Array.<goog.ui.media.MediaModel.SubTitle>} subtitles The subtitles. * @return {!goog.ui.media.MediaModel} The object itself. */ goog.ui.media.MediaModel.prototype.setSubTitles = function(subtitles) { this.subTitles_ = subtitles; return this; }; /** * Constructs a thumbnail containing details of the thumbnail's image URL and * optionally its size. * @param {string} url The URL of the thumbnail's image. * @param {goog.math.Size=} opt_size The size of the thumbnail's image if known. * @constructor */ goog.ui.media.MediaModel.Thumbnail = function(url, opt_size) { /** * The thumbnail's image URL. * @type {string} * @private */ this.url_ = url; /** * The size of the thumbnail's image if known. * @type {goog.math.Size} * @private */ this.size_ = opt_size || null; }; /** * Gets the thumbnail URL. * @return {string} The thumbnail's image URL. */ goog.ui.media.MediaModel.Thumbnail.prototype.getUrl = function() { return this.url_; }; /** * Sets the thumbnail URL. * @param {string} url The thumbnail's image URL. * @return {goog.ui.media.MediaModel.Thumbnail} The object itself, used for * chaining. */ goog.ui.media.MediaModel.Thumbnail.prototype.setUrl = function(url) { this.url_ = url; return this; }; /** * Gets the thumbnail size. * @return {goog.math.Size} The size of the thumbnail's image if known. */ goog.ui.media.MediaModel.Thumbnail.prototype.getSize = function() { return this.size_; }; /** * Sets the thumbnail size. * @param {goog.math.Size} size The size of the thumbnail's image. * @return {goog.ui.media.MediaModel.Thumbnail} The object itself, used for * chaining. */ goog.ui.media.MediaModel.Thumbnail.prototype.setSize = function(size) { this.size_ = size; return this; }; /** * Constructs a player containing details of the player's URL and * optionally its size. * @param {string} url The URL of the player. * @param {Object=} opt_vars Optional map of arguments to the player. * @param {goog.math.Size=} opt_size The size of the player if known. * @constructor */ goog.ui.media.MediaModel.Player = function(url, opt_vars, opt_size) { /** * The player's URL. * @type {string} * @private */ this.url_ = url; /** * Player arguments, typically flash arguments. * @type {Object} * @private */ this.vars_ = opt_vars || null; /** * The size of the player if known. * @type {goog.math.Size} * @private */ this.size_ = opt_size || null; }; /** * Gets the player url. * @return {string} The thumbnail's image URL. */ goog.ui.media.MediaModel.Player.prototype.getUrl = function() { return this.url_; }; /** * Sets the player url. * @param {string} url The thumbnail's image URL. * @return {goog.ui.media.MediaModel.Player} The object itself, used for * chaining. */ goog.ui.media.MediaModel.Player.prototype.setUrl = function(url) { this.url_ = url; return this; }; /** * Gets the player arguments. * @return {Object} The media player arguments. */ goog.ui.media.MediaModel.Player.prototype.getVars = function() { return this.vars_; }; /** * Sets the player arguments. * @param {Object} vars The media player arguments. * @return {goog.ui.media.MediaModel.Player} The object itself, used for * chaining. */ goog.ui.media.MediaModel.Player.prototype.setVars = function(vars) { this.vars_ = vars; return this; }; /** * Gets the size of the player. * @return {goog.math.Size} The size of the player if known. */ goog.ui.media.MediaModel.Player.prototype.getSize = function() { return this.size_; }; /** * Sets the size of the player. * @param {goog.math.Size} size The size of the player. * @return {goog.ui.media.MediaModel.Player} The object itself, used for * chaining. */ goog.ui.media.MediaModel.Player.prototype.setSize = function(size) { this.size_ = size; return this; }; /** * A taxonomy to be set that gives an indication of the type of media content, * and its particular contents. * @param {string} scheme The URI that identifies the categorization scheme. * @param {string} value The value of the category. * @param {string=} opt_label The human readable label that can be displayed in * end user applications. * @constructor */ goog.ui.media.MediaModel.Category = function(scheme, value, opt_label) { /** * The URI that identifies the categorization scheme. * @type {string} * @private */ this.scheme_ = scheme; /** * The value of the category. * @type {string} * @private */ this.value_ = value; /** * The human readable label that can be displayed in end user applications. * @type {string} * @private */ this.label_ = opt_label || ''; }; /** * Gets the category scheme. * @return {string} The category scheme URI. */ goog.ui.media.MediaModel.Category.prototype.getScheme = function() { return this.scheme_; }; /** * Sets the category scheme. * @param {string} scheme The category's scheme. * @return {goog.ui.media.MediaModel.Category} The object itself, used for * chaining. */ goog.ui.media.MediaModel.Category.prototype.setScheme = function(scheme) { this.scheme_ = scheme; return this; }; /** * Gets the categor's value. * @return {string} The category's value. */ goog.ui.media.MediaModel.Category.prototype.getValue = function() { return this.value_; }; /** * Sets the category value. * @param {string} value The category value to be set. * @return {goog.ui.media.MediaModel.Category} The object itself, used for * chaining. */ goog.ui.media.MediaModel.Category.prototype.setValue = function(value) { this.value_ = value; return this; }; /** * Gets the label of the category. * @return {string} The label of the category. */ goog.ui.media.MediaModel.Category.prototype.getLabel = function() { return this.label_; }; /** * Sets the label of the category. * @param {string} label The label of the category. * @return {goog.ui.media.MediaModel.Category} The object itself, used for * chaining. */ goog.ui.media.MediaModel.Category.prototype.setLabel = function(label) { this.label_ = label; return this; }; /** * Indicates an entity that has contributed to a media object. Based on * 'media.credit' in the rss spec. * @param {string} value The name of the entity being credited. * @param {goog.ui.media.MediaModel.Credit.Role=} opt_role The role the entity * played. * @param {goog.ui.media.MediaModel.Credit.Scheme=} opt_scheme The URI that * identifies the role scheme. * @constructor */ goog.ui.media.MediaModel.Credit = function(value, opt_role, opt_scheme) { /** * The name of entity being credited. * @type {string} * @private */ this.value_ = value; /** * The role the entity played. * @type {goog.ui.media.MediaModel.Credit.Role|undefined} * @private */ this.role_ = opt_role; /** * The URI that identifies the role scheme * @type {goog.ui.media.MediaModel.Credit.Scheme|undefined} * @private */ this.scheme_ = opt_scheme; }; /** * The types of known roles. * @enum {string} */ goog.ui.media.MediaModel.Credit.Role = { UPLOADER: 'uploader', OWNER: 'owner' }; /** * The types of known schemes. * @enum {string} */ goog.ui.media.MediaModel.Credit.Scheme = { EUROPEAN_BROADCASTING: 'urn:ebu', YAHOO: 'urn:yvs', YOUTUBE: 'urn:youtube' }; /** * Gets the name of the entity being credited. * @return {string} The name of the entity. */ goog.ui.media.MediaModel.Credit.prototype.getValue = function() { return this.value_; }; /** * Sets the value of the credit object. * @param {string} value The value. * @return {goog.ui.media.MediaModel.Credit} The object itself. */ goog.ui.media.MediaModel.Credit.prototype.setValue = function(value) { this.value_ = value; return this; }; /** * Gets the role of the entity being credited. * @return {goog.ui.media.MediaModel.Credit.Role|undefined} The role of the * entity. */ goog.ui.media.MediaModel.Credit.prototype.getRole = function() { return this.role_; }; /** * Sets the role of the credit object. * @param {goog.ui.media.MediaModel.Credit.Role} role The role. * @return {goog.ui.media.MediaModel.Credit} The object itself. */ goog.ui.media.MediaModel.Credit.prototype.setRole = function(role) { this.role_ = role; return this; }; /** * Gets the scheme of the credit object. * @return {goog.ui.media.MediaModel.Credit.Scheme|undefined} The URI that * identifies the role scheme. */ goog.ui.media.MediaModel.Credit.prototype.getScheme = function() { return this.scheme_; }; /** * Sets the scheme of the credit object. * @param {goog.ui.media.MediaModel.Credit.Scheme} scheme The scheme. * @return {goog.ui.media.MediaModel.Credit} The object itself. */ goog.ui.media.MediaModel.Credit.prototype.setScheme = function(scheme) { this.scheme_ = scheme; return this; }; /** * A reference to the subtitle URI for a media object. * Implements the 'media.subTitle' in the rss spec. * * @param {string} href The subtitle's URI. * to fetch the subtitle file. * @param {string} lang An RFC 3066 language. * @param {string} type The MIME type of the URI. * @constructor */ goog.ui.media.MediaModel.SubTitle = function(href, lang, type) { /** * The subtitle href. * @type {string} * @private */ this.href_ = href; /** * The RFC 3066 language. * @type {string} * @private */ this.lang_ = lang; /** * The MIME type of the resource. * @type {string} * @private */ this.type_ = type; }; /** * Sets the href for the subtitle object. * @param {string} href The subtitle's URI. * @return {goog.ui.media.MediaModel.SubTitle} The object itself. */ goog.ui.media.MediaModel.SubTitle.prototype.setHref = function(href) { this.href_ = href; return this; }; /** * Get the href for the subtitle object. * @return {string} href The subtitle's URI. */ goog.ui.media.MediaModel.SubTitle.prototype.getHref = function() { return this.href_; }; /** * Sets the language for the subtitle object. * @param {string} lang The RFC 3066 language. * @return {goog.ui.media.MediaModel.SubTitle} The object itself. */ goog.ui.media.MediaModel.SubTitle.prototype.setLang = function(lang) { this.lang_ = lang; return this; }; /** * Get the lang for the subtitle object. * @return {string} lang The RFC 3066 language. */ goog.ui.media.MediaModel.SubTitle.prototype.getLang = function() { return this.lang_; }; /** * Sets the type for the subtitle object. * @param {string} type The MIME type. * @return {goog.ui.media.MediaModel.SubTitle} The object itself. */ goog.ui.media.MediaModel.SubTitle.prototype.setType = function(type) { this.type_ = type; return this; }; /** * Get the type for the subtitle object. * @return {string} type The MIME type. */ goog.ui.media.MediaModel.SubTitle.prototype.getType = function() { return this.type_; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview provides a reusable Vimeo video UI component given a public * Vimeo video URL. * * goog.ui.media.Vimeo is actually a {@link goog.ui.ControlRenderer}, a * stateless class - that could/should be used as a Singleton with the static * method {@code goog.ui.media.Vimeo.getInstance} -, that knows how to render * video videos. It is designed to be used with a {@link goog.ui.Control}, * which will actually control the media renderer and provide the * {@link goog.ui.Component} base. This design guarantees that all different * types of medias will behave alike but will look different. * * goog.ui.media.Vimeo expects vimeo video IDs on * {@code goog.ui.Control.getModel} as data models, and renders a flash object * that will show the contents of that video. * * Example of usage: * * <pre> * var video = goog.ui.media.VimeoModel.newInstance('http://vimeo.com/30012'); * goog.ui.media.Vimeo.newControl(video).render(); * </pre> * * Vimeo medias currently support the following states: * * <ul> * <li> {@link goog.ui.Component.State.DISABLED}: shows 'flash not available' * <li> {@link goog.ui.Component.State.HOVER}: mouse cursor is over the video * <li> {@link goog.ui.Component.State.SELECTED}: flash video is shown * </ul> * * Which can be accessed by * <pre> * video.setEnabled(true); * video.setHighlighted(true); * video.setSelected(true); * </pre> * * * @supported IE6, FF2+, Safari. Requires flash to actually work. * * TODO(user): test on other browsers */ goog.provide('goog.ui.media.Vimeo'); goog.provide('goog.ui.media.VimeoModel'); goog.require('goog.string'); goog.require('goog.ui.media.FlashObject'); goog.require('goog.ui.media.Media'); goog.require('goog.ui.media.MediaModel'); goog.require('goog.ui.media.MediaModel.Player'); goog.require('goog.ui.media.MediaRenderer'); /** * Subclasses a goog.ui.media.MediaRenderer to provide a Vimeo specific media * renderer. * * This class knows how to parse Vimeo URLs, and render the DOM structure * of vimeo video players. This class is meant to be used as a singleton static * stateless class, that takes {@code goog.ui.media.Media} instances and renders * it. It expects {@code goog.ui.media.Media.getModel} to return a well formed, * previously constructed, vimeoId {@see goog.ui.media.Vimeo.parseUrl}, which is * the data model this renderer will use to construct the DOM structure. * {@see goog.ui.media.Vimeo.newControl} for a example of constructing a control * with this renderer. * * This design is patterned after http://go/closure_control_subclassing * * It uses {@link goog.ui.media.FlashObject} to embed the flash object. * * @constructor * @extends {goog.ui.media.MediaRenderer} */ goog.ui.media.Vimeo = function() { goog.ui.media.MediaRenderer.call(this); }; goog.inherits(goog.ui.media.Vimeo, goog.ui.media.MediaRenderer); goog.addSingletonGetter(goog.ui.media.Vimeo); /** * Default CSS class to be applied to the root element of components rendered * by this renderer. * * @type {string} */ goog.ui.media.Vimeo.CSS_CLASS = goog.getCssName('goog-ui-media-vimeo'); /** * A static convenient method to construct a goog.ui.media.Media control out of * a Vimeo URL. It extracts the videoId information on the URL, sets it * as the data model goog.ui.media.Vimeo renderer uses, sets the states * supported by the renderer, and returns a Control that binds everything * together. This is what you should be using for constructing Vimeo videos, * except if you need more fine control over the configuration. * * @param {goog.ui.media.VimeoModel} dataModel A vimeo video URL. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for * document interaction. * @return {goog.ui.media.Media} A Control binded to the Vimeo renderer. */ goog.ui.media.Vimeo.newControl = function(dataModel, opt_domHelper) { var control = new goog.ui.media.Media( dataModel, goog.ui.media.Vimeo.getInstance(), opt_domHelper); // vimeo videos don't have any thumbnail for now, so we show the // "selected" version of the UI at the start, which is the // flash player. control.setSelected(true); return control; }; /** * Creates the initial DOM structure of the vimeo video, which is basically a * the flash object pointing to a vimeo video player. * * @param {goog.ui.Control} c The media control. * @return {Element} The DOM structure that represents this control. * @override */ goog.ui.media.Vimeo.prototype.createDom = function(c) { var control = /** @type {goog.ui.media.Media} */ (c); var div = goog.ui.media.Vimeo.superClass_.createDom.call(this, control); var dataModel = /** @type {goog.ui.media.VimeoModel} */ (control.getDataModel()); var flash = new goog.ui.media.FlashObject( dataModel.getPlayer().getUrl() || '', control.getDomHelper()); flash.render(div); return div; }; /** * 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.media.Vimeo.prototype.getCssClass = function() { return goog.ui.media.Vimeo.CSS_CLASS; }; /** * The {@code goog.ui.media.Vimeo} media data model. It stores a required * {@code videoId} field, sets the vimeo URL, and allows a few optional * parameters. * * @param {string} videoId The vimeo video id. * @param {string=} opt_caption An optional caption of the vimeo video. * @param {string=} opt_description An optional description of the vimeo video. * @param {boolean=} opt_autoplay Whether to autoplay video. * @constructor * @extends {goog.ui.media.MediaModel} */ goog.ui.media.VimeoModel = function(videoId, opt_caption, opt_description, opt_autoplay) { goog.ui.media.MediaModel.call( this, goog.ui.media.VimeoModel.buildUrl(videoId), opt_caption, opt_description, goog.ui.media.MediaModel.MimeType.FLASH); /** * The Vimeo video id. * @type {string} * @private */ this.videoId_ = videoId; this.setPlayer(new goog.ui.media.MediaModel.Player( goog.ui.media.VimeoModel.buildFlashUrl(videoId, opt_autoplay))); }; goog.inherits(goog.ui.media.VimeoModel, goog.ui.media.MediaModel); /** * Regular expression used to extract the vimeo video id out of vimeo URLs. * * Copied from http://go/markdownlite.js * * TODO(user): add support to https. * * @type {RegExp} * @private * @const */ goog.ui.media.VimeoModel.MATCHER_ = /https?:\/\/(?:www\.)?vimeo\.com\/(?:hd#)?([0-9]+)/i; /** * Takes a {@code vimeoUrl} and extracts the video id. * * @param {string} vimeoUrl A vimeo video URL. * @param {string=} opt_caption An optional caption of the vimeo video. * @param {string=} opt_description An optional description of the vimeo video. * @param {boolean=} opt_autoplay Whether to autoplay video. * @return {goog.ui.media.VimeoModel} The vimeo data model that represents this * URL. * @throws exception in case the parsing fails */ goog.ui.media.VimeoModel.newInstance = function(vimeoUrl, opt_caption, opt_description, opt_autoplay) { if (goog.ui.media.VimeoModel.MATCHER_.test(vimeoUrl)) { var data = goog.ui.media.VimeoModel.MATCHER_.exec(vimeoUrl); return new goog.ui.media.VimeoModel( data[1], opt_caption, opt_description, opt_autoplay); } throw Error('failed to parse vimeo url: ' + vimeoUrl); }; /** * The opposite of {@code goog.ui.media.Vimeo.parseUrl}: it takes a videoId * and returns a vimeo URL. * * @param {string} videoId The vimeo video ID. * @return {string} The vimeo URL. */ goog.ui.media.VimeoModel.buildUrl = function(videoId) { return 'http://vimeo.com/' + goog.string.urlEncode(videoId); }; /** * Builds a flash url from the vimeo {@code videoId}. * * @param {string} videoId The vimeo video ID. * @param {boolean=} opt_autoplay Whether the flash movie should start playing * as soon as it is shown, or if it should show a 'play' button. * @return {string} The vimeo flash URL. */ goog.ui.media.VimeoModel.buildFlashUrl = function(videoId, opt_autoplay) { var autoplay = opt_autoplay ? '&autoplay=1' : ''; return 'http://vimeo.com/moogaloop.swf?clip_id=' + goog.string.urlEncode(videoId) + '&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0color=&' + 'fullscreen=1' + autoplay; }; /** * Gets the Vimeo video id. * @return {string} The Vimeo video id. */ goog.ui.media.VimeoModel.prototype.getVideoId = function() { return this.videoId_; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Wrapper on a Flash object embedded in the HTML page. * This class contains routines for writing the HTML to create the Flash object * using a goog.ui.Component approach. Tested on Firefox 1.5, 2 and 3, IE6, 7, * Konqueror, Chrome and Safari. * * Based on http://go/flashobject.js * * Based on the following compatibility test suite: * http://www.bobbyvandersluis.com/flashembed/testsuite/ * * TODO(user): take a look at swfobject, and maybe use it instead of the current * flash embedding method. * * Examples of usage: * * <pre> * var flash = new goog.ui.media.FlashObject('http://hostname/flash.swf'); * flash.setFlashVar('myvar', 'foo'); * flash.render(goog.dom.getElement('parent')); * </pre> * * TODO(user, jessan): create a goog.ui.media.BrowserInterfaceFlashObject that * subclasses goog.ui.media.FlashObject to provide all the goodness of * http://go/browserinterface.as * */ goog.provide('goog.ui.media.FlashObject'); goog.provide('goog.ui.media.FlashObject.ScriptAccessLevel'); goog.provide('goog.ui.media.FlashObject.Wmodes'); goog.require('goog.asserts'); goog.require('goog.debug.Logger'); goog.require('goog.events.Event'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventType'); goog.require('goog.object'); goog.require('goog.string'); goog.require('goog.structs.Map'); goog.require('goog.style'); goog.require('goog.ui.Component'); goog.require('goog.userAgent'); goog.require('goog.userAgent.flash'); /** * A very simple flash wrapper, that allows you to create flash object * programmatically, instead of embedding your own HTML. It extends * {@link goog.ui.Component}, which makes it very easy to be embedded on the * page. * * @param {string} flashUrl The flash SWF URL. * @param {goog.dom.DomHelper=} opt_domHelper An optional DomHelper. * @extends {goog.ui.Component} * @constructor */ goog.ui.media.FlashObject = function(flashUrl, opt_domHelper) { goog.ui.Component.call(this, opt_domHelper); /** * The URL of the flash movie to be embedded. * * @type {string} * @private */ this.flashUrl_ = flashUrl; /** * An event handler used to handle events consistently between browsers. * @type {goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); /** * A map of variables to be passed to the flash movie. * * @type {goog.structs.Map} * @private */ this.flashVars_ = new goog.structs.Map(); }; goog.inherits(goog.ui.media.FlashObject, goog.ui.Component); /** * Different states of loaded-ness in which the SWF itself can be * * Talked about at: * http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_12059&sliceId=1 * * @enum {number} * @private */ goog.ui.media.FlashObject.SwfReadyStates_ = { LOADING: 0, UNINITIALIZED: 1, LOADED: 2, INTERACTIVE: 3, COMPLETE: 4 }; /** * The different modes for displaying a SWF. Note that different wmodes * can result in different bugs in different browsers and also that * both OPAQUE and TRANSPARENT will result in a performance hit. * * @enum {string} */ goog.ui.media.FlashObject.Wmodes = { /** * Allows for z-ordering of the SWF. */ OPAQUE: 'opaque', /** * Allows for z-ordering of the SWF and plays the SWF with a transparent BG. */ TRANSPARENT: 'transparent', /** * The default wmode. Does not allow for z-ordering of the SWF. */ WINDOW: 'window' }; /** * The different levels of allowScriptAccess. * * Talked about at: * http://kb2.adobe.com/cps/164/tn_16494.html * * @enum {string} */ goog.ui.media.FlashObject.ScriptAccessLevel = { /* * The flash object can always communicate with its container page. */ ALWAYS: 'always', /* * The flash object can only communicate with its container page if they are * hosted in the same domain. */ SAME_DOMAIN: 'sameDomain', /* * The flash can not communicate with its container page. */ NEVER: 'never' }; /** * The component CSS namespace. * * @type {string} */ goog.ui.media.FlashObject.CSS_CLASS = goog.getCssName('goog-ui-media-flash'); /** * The flash object CSS class. * * @type {string} */ goog.ui.media.FlashObject.FLASH_CSS_CLASS = goog.getCssName('goog-ui-media-flash-object'); /** * Template for the object tag for IE. * * @type {string} * @private */ goog.ui.media.FlashObject.IE_HTML_ = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' + ' id="%s"' + ' name="%s"' + ' class="%s"' + '>' + '<param name="movie" value="%s"/>' + '<param name="quality" value="high"/>' + '<param name="FlashVars" value="%s"/>' + '<param name="bgcolor" value="%s"/>' + '<param name="AllowScriptAccess" value="%s"/>' + '<param name="allowFullScreen" value="true"/>' + '<param name="SeamlessTabbing" value="false"/>' + '%s' + '</object>'; /** * Template for the wmode param for IE. * * @type {string} * @private */ goog.ui.media.FlashObject.IE_WMODE_PARAMS_ = '<param name="wmode" value="%s"/>'; /** * Template for the embed tag for FF. * * @type {string} * @private */ goog.ui.media.FlashObject.FF_HTML_ = '<embed quality="high"' + ' id="%s"' + ' name="%s"' + ' class="%s"' + ' src="%s"' + ' FlashVars="%s"' + ' bgcolor="%s"' + ' AllowScriptAccess="%s"' + ' allowFullScreen="true"' + ' SeamlessTabbing="false"' + ' type="application/x-shockwave-flash"' + ' pluginspage="http://www.macromedia.com/go/getflashplayer"' + ' %s>' + '</embed>'; /** * Template for the wmode param for Firefox. * * @type {string} * @private */ goog.ui.media.FlashObject.FF_WMODE_PARAMS_ = 'wmode=%s'; /** * A logger used for debugging. * * @type {goog.debug.Logger} * @private */ goog.ui.media.FlashObject.prototype.logger_ = goog.debug.Logger.getLogger('goog.ui.media.FlashObject'); /** * The wmode for the SWF. * * @type {goog.ui.media.FlashObject.Wmodes} * @private */ goog.ui.media.FlashObject.prototype.wmode_ = goog.ui.media.FlashObject.Wmodes.WINDOW; /** * The minimum required flash version. * * @type {?string} * @private */ goog.ui.media.FlashObject.prototype.requiredVersion_; /** * The flash movie width. * * @type {string} * @private */ goog.ui.media.FlashObject.prototype.width_; /** * The flash movie height. * * @type {string} * @private */ goog.ui.media.FlashObject.prototype.height_; /** * The flash movie background color. * * @type {string} * @private */ goog.ui.media.FlashObject.prototype.backgroundColor_ = '#000000'; /** * The flash movie allowScriptAccess setting. * * @type {string} * @private */ goog.ui.media.FlashObject.prototype.allowScriptAccess_ = goog.ui.media.FlashObject.ScriptAccessLevel.SAME_DOMAIN; /** * Sets the flash movie Wmode. * * @param {goog.ui.media.FlashObject.Wmodes} wmode the flash movie Wmode. * @return {goog.ui.media.FlashObject} The flash object instance for chaining. */ goog.ui.media.FlashObject.prototype.setWmode = function(wmode) { this.wmode_ = wmode; return this; }; /** * @return {string} Returns the flash movie wmode. */ goog.ui.media.FlashObject.prototype.getWmode = function() { return this.wmode_; }; /** * Adds flash variables. * * @param {goog.structs.Map|Object} map A key-value map of variables. * @return {goog.ui.media.FlashObject} The flash object instance for chaining. */ goog.ui.media.FlashObject.prototype.addFlashVars = function(map) { this.flashVars_.addAll(map); return this; }; /** * Sets a flash variable. * * @param {string} key The name of the flash variable. * @param {string} value The value of the flash variable. * @return {goog.ui.media.FlashObject} The flash object instance for chaining. */ goog.ui.media.FlashObject.prototype.setFlashVar = function(key, value) { this.flashVars_.set(key, value); return this; }; /** * Sets flash variables. You can either pass a Map of key->value pairs or you * can pass a key, value pair to set a specific variable. * * TODO(user, martino): Get rid of this method. * * @deprecated Use {@link #addFlashVars} or {@link #setFlashVar} instead. * @param {goog.structs.Map|Object|string} flashVar A map of variables (given * as a goog.structs.Map or an Object literal) or a key to the optional * {@code opt_value}. * @param {string=} opt_value The optional value for the flashVar key. * @return {goog.ui.media.FlashObject} The flash object instance for chaining. */ goog.ui.media.FlashObject.prototype.setFlashVars = function(flashVar, opt_value) { if (flashVar instanceof goog.structs.Map || goog.typeOf(flashVar) == 'object') { this.addFlashVars(/**@type {!goog.structs.Map|!Object}*/(flashVar)); } else { goog.asserts.assert(goog.isString(flashVar) && goog.isDef(opt_value), 'Invalid argument(s)'); this.setFlashVar(/**@type {string}*/(flashVar), /**@type {string}*/(opt_value)); } return this; }; /** * @return {goog.structs.Map} The current flash variables. */ goog.ui.media.FlashObject.prototype.getFlashVars = function() { return this.flashVars_; }; /** * Sets the background color of the movie. * * @param {string} color The new color to be set. * @return {goog.ui.media.FlashObject} The flash object instance for chaining. */ goog.ui.media.FlashObject.prototype.setBackgroundColor = function(color) { this.backgroundColor_ = color; return this; }; /** * @return {string} The background color of the movie. */ goog.ui.media.FlashObject.prototype.getBackgroundColor = function() { return this.backgroundColor_; }; /** * Sets the allowScriptAccess setting of the movie. * * @param {string} value The new value to be set. * @return {goog.ui.media.FlashObject} The flash object instance for chaining. */ goog.ui.media.FlashObject.prototype.setAllowScriptAccess = function(value) { this.allowScriptAccess_ = value; return this; }; /** * @return {string} The allowScriptAccess setting color of the movie. */ goog.ui.media.FlashObject.prototype.getAllowScriptAccess = function() { return this.allowScriptAccess_; }; /** * Sets the width and height of the movie. * * @param {number|string} width The width of the movie. * @param {number|string} height The height of the movie. * @return {goog.ui.media.FlashObject} The flash object instance for chaining. */ goog.ui.media.FlashObject.prototype.setSize = function(width, height) { this.width_ = goog.isString(width) ? width : Math.round(width) + 'px'; this.height_ = goog.isString(height) ? height : Math.round(height) + 'px'; if (this.getElement()) { goog.style.setSize(this.getFlashElement(), this.width_, this.height_); } return this; }; /** * @return {?string} The flash required version. */ goog.ui.media.FlashObject.prototype.getRequiredVersion = function() { return this.requiredVersion_; }; /** * Sets the minimum flash required version. * * @param {?string} version The minimum required version for this movie to work, * or null if you want to unset it. * @return {goog.ui.media.FlashObject} The flash object instance for chaining. */ goog.ui.media.FlashObject.prototype.setRequiredVersion = function(version) { this.requiredVersion_ = version; return this; }; /** * Returns whether this SWF has a minimum required flash version. * * @return {boolean} Whether a required version was set or not. */ goog.ui.media.FlashObject.prototype.hasRequiredVersion = function() { return this.requiredVersion_ != null; }; /** * Writes the Flash embedding {@code HTMLObjectElement} to this components root * element and adds listeners for all events to handle them consistently. * @override */ goog.ui.media.FlashObject.prototype.enterDocument = function() { goog.ui.media.FlashObject.superClass_.enterDocument.call(this); // The SWF tag must be written after this component's element is appended to // the DOM. Otherwise Flash's ExternalInterface is broken in IE. this.getElement().innerHTML = this.generateSwfTag_(); if (this.width_ && this.height_) { this.setSize(this.width_, this.height_); } // Sinks all the events on the bubble phase. // // Flash plugins propagates events from/to the plugin to the browser // inconsistently: // // 1) FF2 + linux: the flash plugin will stop the propagation of all events // from the plugin to the browser. // 2) FF3 + mac: the flash plugin will propagate events on the <embed> object // but that will get propagated to its parents. // 3) Safari 3.1.1 + mac: the flash plugin will propagate the event to the // <object> tag that event will propagate to its parents. // 4) IE7 + windows: the flash plugin will eat all events, not propagating // anything to the javascript. // 5) Chrome + windows: the flash plugin will eat all events, not propagating // anything to the javascript. // // To overcome this inconsistency, all events from/to the plugin are sinked, // since you can't assume that the events will be propagated. // // NOTE(user): we only sink events on the bubbling phase, since there are no // inexpensive/scalable way to stop events on the capturing phase unless we // added an event listener on the document for each flash object. this.eventHandler_.listen( this.getElement(), goog.object.getValues(goog.events.EventType), goog.events.Event.stopPropagation); }; /** * Creates the DOM structure. * * @override */ goog.ui.media.FlashObject.prototype.createDom = function() { if (this.hasRequiredVersion() && !goog.userAgent.flash.isVersion( /** @type {string} */ (this.getRequiredVersion()))) { this.logger_.warning('Required flash version not found:' + this.getRequiredVersion()); throw Error(goog.ui.Component.Error.NOT_SUPPORTED); } var element = this.getDomHelper().createElement('div'); element.className = goog.ui.media.FlashObject.CSS_CLASS; this.setElementInternal(element); }; /** * Writes the HTML to embed the flash object. * * @return {string} Browser appropriate HTML to add the SWF to the DOM. * @private */ goog.ui.media.FlashObject.prototype.generateSwfTag_ = function() { var template = goog.userAgent.IE ? goog.ui.media.FlashObject.IE_HTML_ : goog.ui.media.FlashObject.FF_HTML_; var params = goog.userAgent.IE ? goog.ui.media.FlashObject.IE_WMODE_PARAMS_ : goog.ui.media.FlashObject.FF_WMODE_PARAMS_; params = goog.string.subs(params, this.wmode_); var keys = this.flashVars_.getKeys(); var values = this.flashVars_.getValues(); var flashVars = []; for (var i = 0; i < keys.length; i++) { var key = goog.string.urlEncode(keys[i]); var value = goog.string.urlEncode(values[i]); flashVars.push(key + '=' + value); } // TODO(user): find a more efficient way to build the HTML. return goog.string.subs( template, this.getId(), this.getId(), goog.ui.media.FlashObject.FLASH_CSS_CLASS, goog.string.htmlEscape(this.flashUrl_), goog.string.htmlEscape(flashVars.join('&')), this.backgroundColor_, this.allowScriptAccess_, params); }; /** * @return {HTMLObjectElement} The flash element or null if the element can't * be found. */ goog.ui.media.FlashObject.prototype.getFlashElement = function() { return /** @type {HTMLObjectElement} */(this.getElement() ? this.getElement().firstChild : null); }; /** @override */ goog.ui.media.FlashObject.prototype.disposeInternal = function() { goog.ui.media.FlashObject.superClass_.disposeInternal.call(this); this.flashVars_ = null; this.eventHandler_.dispose(); this.eventHandler_ = null; }; /** * @return {boolean} whether the SWF has finished loading or not. */ goog.ui.media.FlashObject.prototype.isLoaded = function() { if (!this.isInDocument() || !this.getElement()) { return false; } if (this.getFlashElement().readyState && this.getFlashElement().readyState == goog.ui.media.FlashObject.SwfReadyStates_.COMPLETE) { return true; } if (this.getFlashElement().PercentLoaded && this.getFlashElement().PercentLoaded() == 100) { return true; } return false; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview provides a reusable photo UI component that renders photos that * contains metadata (such as captions, description, thumbnail/high resolution * versions, etc). * * goog.ui.media.Photo is actually a {@link goog.ui.ControlRenderer}, * a stateless class - that could/should be used as a Singleton with the static * method {@code goog.ui.media.Photo.getInstance} -, that knows how to render * Photos. It is designed to be used with a {@link goog.ui.Control}, which will * actually control the media renderer and provide the {@link goog.ui.Component} * base. This design guarantees that all different types of medias will behave * alike but will look different. * * goog.ui.media.Photo expects {@code goog.ui.media.MediaModel} on * {@code goog.ui.Control.getModel} as data models. * * Example of usage: * * <pre> * var photo = goog.ui.media.Photo.newControl( * new goog.ui.media.MediaModel('http://hostname/file.jpg')); * photo.render(goog.dom.getElement('parent')); * </pre> * * Photo medias currently support the following states: * * <ul> * <li> {@link goog.ui.Component.State.HOVER}: mouse cursor is over the photo. * <li> {@link goog.ui.Component.State.SELECTED}: photo is being displayed. * </ul> * * Which can be accessed by * * <pre> * photo.setHighlighted(true); * photo.setSelected(true); * </pre> * */ goog.provide('goog.ui.media.Photo'); goog.require('goog.ui.media.Media'); goog.require('goog.ui.media.MediaRenderer'); /** * Subclasses a goog.ui.media.MediaRenderer to provide a Photo specific media * renderer. Provides a base class for any other renderer that wants to display * photos. * * This class is meant to be used as a singleton static stateless class, that * takes {@code goog.ui.media.Media} instances and renders it. * * This design is patterned after * http://go/closure_control_subclassing * * @constructor * @extends {goog.ui.media.MediaRenderer} */ goog.ui.media.Photo = function() { goog.ui.media.MediaRenderer.call(this); }; goog.inherits(goog.ui.media.Photo, goog.ui.media.MediaRenderer); goog.addSingletonGetter(goog.ui.media.Photo); /** * Default CSS class to be applied to the root element of components rendered * by this renderer. * * @type {string} */ goog.ui.media.Photo.CSS_CLASS = goog.getCssName('goog-ui-media-photo'); /** * A static convenient method to construct a goog.ui.media.Media control out of * a photo {@code goog.ui.media.MediaModel}. It sets it as the data model * goog.ui.media.Photo renderer uses, sets the states supported by the renderer, * and returns a Control that binds everything together. This is what you * should be using for constructing Photos, except if you need finer control * over the configuration. * * @param {goog.ui.media.MediaModel} dataModel The photo data model. * @return {goog.ui.media.Media} A goog.ui.Control subclass with the photo * renderer. */ goog.ui.media.Photo.newControl = function(dataModel) { var control = new goog.ui.media.Media( dataModel, goog.ui.media.Photo.getInstance()); return control; }; /** * Creates the initial DOM structure of a photo. * * @param {goog.ui.Control} c The media control. * @return {Element} A DOM structure that represents the control. * @override */ goog.ui.media.Photo.prototype.createDom = function(c) { var control = /** @type {goog.ui.media.Media} */ (c); var div = goog.ui.media.Photo.superClass_.createDom.call(this, control); var img = control.getDomHelper().createDom('img', { src: control.getDataModel().getPlayer().getUrl(), className: goog.getCssName(this.getCssClass(), 'image') }); div.appendChild(img); return div; }; /** * 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.media.Photo.prototype.getCssClass = function() { return goog.ui.media.Photo.CSS_CLASS; };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview provides a reusable GoogleVideo UI component given a public * GoogleVideo video URL. * * goog.ui.media.GoogleVideo is actually a {@link goog.ui.ControlRenderer}, a * stateless class - that could/should be used as a Singleton with the static * method {@code goog.ui.media.GoogleVideo.getInstance} -, that knows how to * render GoogleVideo videos. It is designed to be used with a * {@link goog.ui.Control}, which will actually control the media renderer and * provide the {@link goog.ui.Component} base. This design guarantees that all * different types of medias will behave alike but will look different. * * goog.ui.media.GoogleVideo expects {@code goog.ui.media.GoogleVideoModel} on * {@code goog.ui.Control.getModel} as data models, and renders a flash object * that will show the contents of that video. * * Example of usage: * * <pre> * var video = goog.ui.media.GoogleVideoModel.newInstance( * 'http://video.google.com/videoplay?docid=6698933542780842398'); * goog.ui.media.GoogleVideo.newControl(video).render(); * </pre> * * GoogleVideo medias currently support the following states: * * <ul> * <li> {@link goog.ui.Component.State.DISABLED}: shows 'flash not available' * <li> {@link goog.ui.Component.State.HOVER}: mouse cursor is over the video * <li> {@link goog.ui.Component.State.SELECTED}: flash video is shown * </ul> * * Which can be accessed by * <pre> * video.setEnabled(true); * video.setHighlighted(true); * video.setSelected(true); * </pre> * * * @supported IE6+, FF2+, Chrome, Safari. Requires flash to actually work. */ goog.provide('goog.ui.media.GoogleVideo'); goog.provide('goog.ui.media.GoogleVideoModel'); goog.require('goog.string'); goog.require('goog.ui.media.FlashObject'); goog.require('goog.ui.media.Media'); goog.require('goog.ui.media.MediaModel'); goog.require('goog.ui.media.MediaModel.Player'); goog.require('goog.ui.media.MediaRenderer'); /** * Subclasses a goog.ui.media.MediaRenderer to provide a GoogleVideo specific * media renderer. * * This class knows how to parse GoogleVideo URLs, and render the DOM structure * of GoogleVideo video players. This class is meant to be used as a singleton * static stateless class, that takes {@code goog.ui.media.Media} instances and * renders it. It expects {@code goog.ui.media.Media.getModel} to return a well * formed, previously constructed, GoogleVideo video id, which is the data model * this renderer will use to construct the DOM structure. * {@see goog.ui.media.GoogleVideo.newControl} for a example of constructing a * control with this renderer. * * This design is patterned after http://go/closure_control_subclassing * * It uses {@link goog.ui.media.FlashObject} to embed the flash object. * * @constructor * @extends {goog.ui.media.MediaRenderer} */ goog.ui.media.GoogleVideo = function() { goog.ui.media.MediaRenderer.call(this); }; goog.inherits(goog.ui.media.GoogleVideo, goog.ui.media.MediaRenderer); goog.addSingletonGetter(goog.ui.media.GoogleVideo); /** * A static convenient method to construct a goog.ui.media.Media control out of * a GoogleVideo model. It sets it as the data model goog.ui.media.GoogleVideo * renderer uses, sets the states supported by the renderer, and returns a * Control that binds everything together. This is what you should be using for * constructing GoogleVideo videos, except if you need finer control over the * configuration. * * @param {goog.ui.media.GoogleVideoModel} dataModel The GoogleVideo data model. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for * document interaction. * @return {goog.ui.media.Media} A Control binded to the GoogleVideo renderer. */ goog.ui.media.GoogleVideo.newControl = function(dataModel, opt_domHelper) { var control = new goog.ui.media.Media( dataModel, goog.ui.media.GoogleVideo.getInstance(), opt_domHelper); // GoogleVideo videos don't have any thumbnail for now, so we show the // "selected" version of the UI at the start, which is the flash player. control.setSelected(true); return control; }; /** * Default CSS class to be applied to the root element of components rendered * by this renderer. * * @type {string} */ goog.ui.media.GoogleVideo.CSS_CLASS = goog.getCssName('goog-ui-media-googlevideo'); /** * Creates the initial DOM structure of the GoogleVideo video, which is * basically a the flash object pointing to a GoogleVideo video player. * * @param {goog.ui.Control} c The media control. * @return {Element} The DOM structure that represents this control. * @override */ goog.ui.media.GoogleVideo.prototype.createDom = function(c) { var control = /** @type {goog.ui.media.Media} */ (c); var div = goog.base(this, 'createDom', control); var dataModel = /** @type {goog.ui.media.GoogleVideoModel} */ (control.getDataModel()); var flash = new goog.ui.media.FlashObject( dataModel.getPlayer().getUrl() || '', control.getDomHelper()); flash.render(div); return div; }; /** * 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.media.GoogleVideo.prototype.getCssClass = function() { return goog.ui.media.GoogleVideo.CSS_CLASS; }; /** * The {@code goog.ui.media.GoogleVideo} media data model. It stores a required * {@code videoId} field, sets the GoogleVideo URL, and allows a few optional * parameters. * * @param {string} videoId The GoogleVideo video id. * @param {string=} opt_caption An optional caption of the GoogleVideo video. * @param {string=} opt_description An optional description of the GoogleVideo * video. * @param {boolean=} opt_autoplay Whether to autoplay video. * @constructor * @extends {goog.ui.media.MediaModel} */ goog.ui.media.GoogleVideoModel = function(videoId, opt_caption, opt_description, opt_autoplay) { goog.ui.media.MediaModel.call( this, goog.ui.media.GoogleVideoModel.buildUrl(videoId), opt_caption, opt_description, goog.ui.media.MediaModel.MimeType.FLASH); /** * The GoogleVideo video id. * @type {string} * @private */ this.videoId_ = videoId; this.setPlayer(new goog.ui.media.MediaModel.Player( goog.ui.media.GoogleVideoModel.buildFlashUrl(videoId, opt_autoplay))); }; goog.inherits(goog.ui.media.GoogleVideoModel, goog.ui.media.MediaModel); /** * Regular expression used to extract the GoogleVideo video id (docid) out of * GoogleVideo URLs. * * @type {RegExp} * @private * @const */ goog.ui.media.GoogleVideoModel.MATCHER_ = /^http:\/\/(?:www\.)?video\.google\.com\/videoplay.*[\?#]docid=(-?[0-9]+)#?$/i; /** * A auxiliary static method that parses a GoogleVideo URL, extracting the ID of * the video, and builds a GoogleVideoModel. * * @param {string} googleVideoUrl A GoogleVideo video URL. * @param {string=} opt_caption An optional caption of the GoogleVideo video. * @param {string=} opt_description An optional description of the GoogleVideo * video. * @param {boolean=} opt_autoplay Whether to autoplay video. * @return {goog.ui.media.GoogleVideoModel} The data model that represents the * GoogleVideo URL. * @see goog.ui.media.GoogleVideoModel.getVideoId() * @throws Error in case the parsing fails. */ goog.ui.media.GoogleVideoModel.newInstance = function(googleVideoUrl, opt_caption, opt_description, opt_autoplay) { if (goog.ui.media.GoogleVideoModel.MATCHER_.test(googleVideoUrl)) { var data = goog.ui.media.GoogleVideoModel.MATCHER_.exec(googleVideoUrl); return new goog.ui.media.GoogleVideoModel( data[1], opt_caption, opt_description, opt_autoplay); } throw Error('failed to parse video id from GoogleVideo url: ' + googleVideoUrl); }; /** * The opposite of {@code goog.ui.media.GoogleVideo.newInstance}: it takes a * videoId and returns a GoogleVideo URL. * * @param {string} videoId The GoogleVideo video ID. * @return {string} The GoogleVideo URL. */ goog.ui.media.GoogleVideoModel.buildUrl = function(videoId) { return 'http://video.google.com/videoplay?docid=' + goog.string.urlEncode(videoId); }; /** * An auxiliary method that builds URL of the flash movie to be embedded, * out of the GoogleVideo video id. * * @param {string} videoId The GoogleVideo video ID. * @param {boolean=} opt_autoplay Whether the flash movie should start playing * as soon as it is shown, or if it should show a 'play' button. * @return {string} The flash URL to be embedded on the page. */ goog.ui.media.GoogleVideoModel.buildFlashUrl = function(videoId, opt_autoplay) { var autoplay = opt_autoplay ? '&autoplay=1' : ''; return 'http://video.google.com/googleplayer.swf?docid=' + goog.string.urlEncode(videoId) + '&hl=en&fs=true' + autoplay; }; /** * Gets the GoogleVideo video id. * @return {string} The GoogleVideo video id. */ goog.ui.media.GoogleVideoModel.prototype.getVideoId = function() { return this.videoId_; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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;
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Class 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.array'); goog.require('goog.dom'); goog.require('goog.dom.classes'); goog.require('goog.events.EventType'); 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. * @override */ 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. * @override */ 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_); var win = this.getDomHelper().getWindow(); this.getHandler(). listen(win, goog.events.EventType.SCROLL, this.update_). listen(win, 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.array.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.array.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'; } } };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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_; };
JavaScript
// Copyright 2013 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Tests for goog.ui.MockActivityMonitorTest. * @author nnaze@google.com (Nathan Naze) */ /** @suppress {extraProvide} */ goog.provide('goog.ui.MockActivityMonitorTest'); goog.require('goog.events'); goog.require('goog.functions'); goog.require('goog.testing.jsunit'); goog.require('goog.testing.recordFunction'); goog.require('goog.ui.ActivityMonitor'); goog.require('goog.ui.MockActivityMonitor'); goog.setTestOnly('goog.ui.MockActivityMonitorTest'); var googNow = goog.now; var monitor; var recordedFunction; var replacer; function setUp() { monitor = new goog.ui.MockActivityMonitor(); recordedFunction = goog.testing.recordFunction(); goog.events.listen( monitor, goog.ui.ActivityMonitor.Event.ACTIVITY, recordedFunction); } function tearDown() { goog.dispose(monitor); goog.now = googNow; } function testEventFireSameTime() { goog.now = goog.functions.constant(1000); monitor.simulateEvent(); assertEquals(1, recordedFunction.getCallCount()); monitor.simulateEvent(); assertEquals(2, recordedFunction.getCallCount()); } function testEventFireDifferingTime() { goog.now = goog.functions.constant(1000); monitor.simulateEvent(); assertEquals(1, recordedFunction.getCallCount()); goog.now = goog.functions.constant(1001); monitor.simulateEvent(); assertEquals(2, recordedFunction.getCallCount()); }
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview An 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. * @override */ 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()); });
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A menu item class that supports checkbox semantics. * * @author attila@google.com (Attila Bodis) */ goog.provide('goog.ui.CheckBoxMenuItem'); 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); });
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Renderer for {@link goog.ui.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.Control} item goog.ui.MenuItem to decorate the element. * @param {Element} element Element to decorate. * @return {Element} Decorated element. * @override */ 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; }; /** @override */ goog.ui.TriStateMenuItemRenderer.prototype.getCssClass = function() { return goog.ui.TriStateMenuItemRenderer.CSS_CLASS; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Renderer for {@link goog.ui.MenuItem}s. * * @author attila@google.com (Attila Bodis) */ goog.provide('goog.ui.MenuItemRenderer'); goog.require('goog.a11y.aria'); goog.require('goog.a11y.aria.Role'); goog.require('goog.dom'); 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; }; /** @override */ goog.ui.MenuItemRenderer.prototype.getAriaRole = function() { return goog.a11y.aria.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)); this.setAriaStates(item, element); 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'))) { (/** @type {goog.ui.MenuItem} */ (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 && goog.dom.classes.has(child, contentClassName); }; /** * 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.a11y.aria.setRole(element, selectable ? goog.a11y.aria.Role.MENU_ITEM_RADIO : /** @type {string} */ (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.a11y.aria.setRole(element, checkable ? goog.a11y.aria.Role.MENU_ITEM_CHECKBOX : /** @type {string} */ (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 && goog.dom.classes.has(child, checkboxClassName); } 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; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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 {Array.<string|undefined>} */ goog.ui.RichTextSpellChecker.prototype.excludeTags; /** * 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 * @override */ 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. * @override */ 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); } }; /** @override */ goog.ui.RichTextSpellChecker.prototype.enterDocument = function() { goog.ui.RichTextSpellChecker.superClass_.enterDocument.call(this); this.initSuggestionsMenu(); }; /** * Checks spelling for all text and displays correction UI. * @override */ 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.clearWordElements(); 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) { if (marker) { if (typeof marker == 'string') { marker = [marker]; } this.excludeTags = []; this.excludeMarker = []; for (var i = 0; i < marker.length; i++) { var parts = marker[i].split('.'); if (parts.length == 2) { this.excludeTags.push(parts[0]); this.excludeMarker.push(parts[1]); } else { this.excludeMarker.push(parts[0]); this.excludeTags.push(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) { if (this.excludeMarker && node.className) { for (var i = 0; i < this.excludeMarker.length; i++) { var excludeTag = this.excludeTags[i]; var excludeClass = this.excludeMarker[i]; var isExcluded = !!(excludeClass && node.className.indexOf(excludeClass) != -1 && (!excludeTag || node.tagName == excludeTag)); if (isExcluded) { return true; } } } return false; }; /** * 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 * @override */ 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 * @override */ 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_++; }; /** * @override * @suppress {accessControls} */ 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 * @override */ 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. * @override */ 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 * @override */ 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; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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.classlist'); goog.require('goog.events'); goog.require('goog.events.InputHandler'); goog.require('goog.events.KeyCodes'); goog.require('goog.events.KeyHandler'); goog.require('goog.positioning.Corner'); goog.require('goog.positioning.MenuAnchoredPosition'); 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_, type: 'text', 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 = '&#x25BC;'; 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.classlist.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. * @override */ 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 {Element} The input element. */ goog.ui.ComboBox.prototype.getInputElement = function() { return this.input_; }; /** * @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; if (this.labelInput_) { this.labelInput_.setLabel(this.defaultText_); } }; /** * @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_ && this.menu_.isVisible()) { var position = new goog.positioning.MenuAnchoredPosition(this.getElement(), goog.positioning.Corner.BOTTOM_START, true); position.reposition(this.menu_.getElement(), goog.positioning.Corner.TOP_START); } }; /** * 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.classlist.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.classlist.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. * @param {goog.ui.MenuItemRenderer=} opt_renderer Optional renderer. * @constructor * @extends {goog.ui.MenuItem} */ goog.ui.ComboBoxItem = function(content, opt_data, opt_domHelper, opt_renderer) { goog.ui.MenuItem.call(this, content, opt_data, opt_domHelper, opt_renderer); }; 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)) ]); } } };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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; var renderer = /** @type {!goog.ui.ButtonRenderer} */ (this.getRenderer()); renderer.setValue(this.getElement(), /** @type {string} */ (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); });
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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, 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_; /** * 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.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. * @override */ goog.ui.AdvancedTooltip.prototype.isCoordinateInTooltip = function(coord) { // Check if coord is inside the bounding box of the tooltip if (this.hotSpotPadding_) { var offset = goog.style.getPageOffset(this.getElement()); var size = goog.style.getSize(this.getElement()); return offset.x - this.hotSpotPadding_.left <= coord.x && coord.x <= offset.x + size.width + this.hotSpotPadding_.right && offset.y - this.hotSpotPadding_.top <= coord.y && coord.y <= offset.y + size.height + this.hotSpotPadding_.bottom; } 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. * @override */ 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 * @override */ 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 * @override */ goog.ui.AdvancedTooltip.prototype.handleTooltipMouseOver = function(event) { if (this.getActiveElement() != this.getElement()) { this.tracking_ = false; this.setActiveElement(this.getElement()); } }; /** * Override hide delay with cursor tracking hide delay while tracking. * @return {number} Hide delay to use. * @override */ 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. * @deprecated Not ever necessary to call this function. Hot spot is calculated * as neccessary. */ goog.ui.AdvancedTooltip.prototype.resetHotSpot = goog.nullFunction;
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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.a11y.aria'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.classes'); goog.require('goog.events'); goog.require('goog.events.EventType'); goog.require('goog.ui.Component'); 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 * @override */ 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_(); }; /** @override */ goog.ui.ProgressBar.prototype.enterDocument = function() { goog.ui.ProgressBar.superClass_.enterDocument.call(this); this.attachEvents_(); this.updateUi_(); var element = this.getElement(); goog.asserts.assert(element, 'The progress bar DOM element cannot be null.'); // state live = polite will notify the user of updates, // but will not interrupt ongoing feedback goog.a11y.aria.setRole(element, 'progressbar'); goog.a11y.aria.setState(element, 'live', 'polite'); }; /** @override */ 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 {Element} element The HTML element to decorate. * @override */ 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() { var element = this.getElement(); goog.asserts.assert(element, 'The progress bar DOM element cannot be null.'); goog.a11y.aria.setState(element, '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() { var element = this.getElement(); goog.asserts.assert(element, 'The progress bar DOM element cannot be null.'); goog.a11y.aria.setState(element, '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() { var element = this.getElement(); goog.asserts.assert(element, 'The progress bar DOM element cannot be null.'); goog.a11y.aria.setState(element, '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); };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Renderer for {@link goog.ui.Toolbar}s. * * @author attila@google.com (Attila Bodis) */ goog.provide('goog.ui.ToolbarRenderer'); goog.require('goog.a11y.aria.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.a11y.aria.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). * @override */ 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. * @override */ 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. * @override */ goog.ui.ToolbarRenderer.prototype.getDefaultOrientation = function() { return goog.ui.Container.Orientation.HORIZONTAL; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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.a11y.aria'); goog.require('goog.a11y.aria.State'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.string'); goog.require('goog.style'); 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"> * &nbsp; * </div> * </div> * Overrides {@link goog.ui.FlatButtonRenderer#createDom}. * @param {goog.ui.Control} control Button to render. * @return {Element} Root element for the button. * @override */ goog.ui.FlatMenuButtonRenderer.prototype.createDom = function(control) { var button = /** @type {goog.ui.Button} */ (control); 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). * @override */ 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.Control} button Menu button to decorate the element. * @param {Element} element Element to decorate. * @return {Element} Decorated element. * @override */ 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.setElementShown(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"> * &nbsp; * </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 &nbsp; return dom.createDom('div', goog.ui.INLINE_BLOCK_CLASSNAME + ' ' + goog.getCssName(this.getCssClass(), 'dropdown'), '\u00A0'); }; /** * Returns the CSS class to be applied to the root element of components * rendered using this renderer. * @return {string} Renderer-specific CSS class. * @override */ goog.ui.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()); });
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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); };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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); });
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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.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. Initialized lazily as often never needed. * @type {?Array.<string>} * @private */ goog.ui.ColorPalette.prototype.normalizedColors_ = null; /** * Array of labels for the colors. Will be used for the tooltips and * accessibility. * @type {?Array.<string>} * @private */ goog.ui.ColorPalette.prototype.labels_ = 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. * @param {Array.<string>=} opt_labels The array of labels to be used as * tooltips. When not provided, the color value will be used. */ goog.ui.ColorPalette.prototype.setColors = function(colors, opt_labels) { this.colors_ = colors; this.labels_ = opt_labels || null; 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. * @protected */ goog.ui.ColorPalette.prototype.createColorNodes = function() { return goog.array.map(this.colors_, function(color, index) { var swatch = this.getDomHelper().createDom('div', { 'class': goog.getCssName(this.getRenderer().getCssClass(), 'colorswatch'), 'style': 'background-color:' + color }); if (this.labels_ && this.labels_[index]) { swatch.title = this.labels_[index]; } else { 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; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview The 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'; };
JavaScript
// Copyright 2009 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Character Picker widget for picking any Unicode character. * * @see ../demos/charpicker.html */ goog.provide('goog.ui.CharPicker'); goog.require('goog.a11y.aria'); goog.require('goog.array'); goog.require('goog.asserts'); 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.i18n.uChar.NameFetcher'); 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 {!goog.i18n.uChar.NameFetcher} charNameFetcher Object which fetches * the names of the characters that are shown in the widget. These names * may be stored locally or come from an external source. * @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, charNameFetcher, opt_recents, opt_initCategory, opt_initSubcategory, opt_rowCount, opt_columnCount, opt_domHelper) { goog.ui.Component.call(this, opt_domHelper); /** * Object used to retrieve character names. * @type {!goog.i18n.uChar.NameFetcher} * @private */ this.charNameFetcher_ = charNameFetcher; /** * 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 name in preview. * @type {Element} * @private */ goog.ui.CharPicker.prototype.charNameEl_ = null; /** * Element displaying character in preview. * @type {Element} * @private */ goog.ui.CharPicker.prototype.zoomEl_ = null; /** * Element displaying character number (codepoint) 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() { goog.dispose(this.hc_); this.hc_ = null; goog.dispose(this.eventHandler_); 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 component 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.charNameEl_ = goog.dom.createDom('div', {id: 'charName', className: goog.getCssName('goog-char-picker-name')}); 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.charNameEl_, this.unicodeEl_); goog.style.setElementShown(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 = goog.i18n.uChar.toHexString(ch); // Clear the character name since we don't want to show old data because // it is retrieved asynchronously and the DOM object is re-used self.charNameEl_.innerHTML = ''; self.charNameFetcher_.getName(ch, function(charName) { if (charName) { self.charNameEl_.innerHTML = charName; } }); } } 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_). listen( this.recentgrid_, goog.ui.Component.EventType.FOCUS, this.handleFocus_). listen( this.grid_, goog.ui.Component.EventType.FOCUS, this.handleFocus_); 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); }; /** * Handles the button focus by updating the aria label with the character name * so it becomes possible to get spoken feedback while tabbing through the * visible symbols. * @param {goog.events.Event} e The focus event. * @private */ goog.ui.CharPicker.prototype.handleFocus_ = function(e) { var button = e.target; var element = button.getElement(); var ch = this.getChar_(element); // Clear the aria label to avoid speaking the old value in case the button // element has no char attribute or the character name cannot be retrieved. goog.a11y.aria.setState(element, goog.a11y.aria.State.LABEL, ''); if (ch) { // This is working with screen readers because the call to getName is // synchronous once the values have been prefetched by the RemoteNameFetcher // and because it is always synchronous when using the LocalNameFetcher. // Also, the special character itself is not used as the label because some // screen readers, notably ChromeVox, are not able to speak them. // TODO(user): Consider changing the NameFetcher API to provide a // method that lets the caller retrieve multiple character names at once // so that this asynchronous gymnastic can be avoided. this.charNameFetcher_.getName(ch, function(charName) { if (charName) { goog.a11y.aria.setState( element, goog.a11y.aria.State.LABEL, charName); } }); } }; /** * 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 = goog.i18n.uChar.toHexString(ch); this.zoomEl_.innerHTML = ch; this.unicodeEl_.innerHTML = unicode; this.charNameEl_.innerHTML = ''; 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.charNameFetcher_.prefetch(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 = this.charNameFetcher_.isNameAvailable(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); } }; /** * 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()); // Dispatch the focus event so we can update the aria description while // the user tabs through the cells. button.setDispatchTransitionEvents(goog.ui.Component.State.FOCUSED, true); grid.addChild(button, true); button.setVisible(false); var buttonEl = button.getElement(); goog.asserts.assert(buttonEl, 'The button DOM element cannot be null.'); // Override the button role so the user doesn't hear "button" each time he // tabs through the cells. goog.a11y.aria.setRole(buttonEl, ''); } }; /** * 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); 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. */ 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 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; };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Default renderer for {@link goog.ui.Checkbox}s. * */ goog.provide('goog.ui.CheckboxRenderer'); goog.require('goog.a11y.aria'); goog.require('goog.a11y.aria.Role'); goog.require('goog.a11y.aria.State'); goog.require('goog.array'); goog.require('goog.asserts'); 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.asserts.assert(element, 'The element cannot be null.'); goog.a11y.aria.setState(element, goog.a11y.aria.State.CHECKED, this.ariaStateFromCheckState_(checked)); return element; }; /** * Returns the ARIA role to be applied to checkboxes. * @return {goog.a11y.aria.Role} ARIA role. * @override */ goog.ui.CheckboxRenderer.prototype.getAriaRole = function() { return goog.a11y.aria.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.a11y.aria.setState(element, goog.a11y.aria.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.a11y.aria.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); };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Wrapper around {@link goog.ui.Dialog}, to provide * dialogs that are smarter about interacting with a rich text editor. * */ goog.provide('goog.ui.editor.AbstractDialog'); goog.provide('goog.ui.editor.AbstractDialog.Builder'); goog.provide('goog.ui.editor.AbstractDialog.EventType'); goog.require('goog.dom'); goog.require('goog.dom.classes'); goog.require('goog.events.EventTarget'); goog.require('goog.ui.Dialog'); goog.require('goog.ui.Dialog.ButtonSet'); goog.require('goog.ui.Dialog.DefaultButtonKeys'); goog.require('goog.ui.Dialog.Event'); goog.require('goog.ui.Dialog.EventType'); // *** Public interface ***************************************************** // /** * Creates an object that represents a dialog box. * @param {goog.dom.DomHelper} domHelper DomHelper to be used to create the * dialog's dom structure. * @constructor * @extends {goog.events.EventTarget} */ goog.ui.editor.AbstractDialog = function(domHelper) { goog.events.EventTarget.call(this); this.dom = domHelper; }; goog.inherits(goog.ui.editor.AbstractDialog, goog.events.EventTarget); /** * Causes the dialog box to appear, centered on the screen. Lazily creates the * dialog if needed. */ goog.ui.editor.AbstractDialog.prototype.show = function() { // Lazily create the wrapped dialog to be shown. if (!this.dialogInternal_) { this.dialogInternal_ = this.createDialogControl(); this.dialogInternal_.addEventListener(goog.ui.Dialog.EventType.AFTER_HIDE, this.handleAfterHide_, false, this); } this.dialogInternal_.setVisible(true); }; /** * Hides the dialog, causing AFTER_HIDE to fire. */ goog.ui.editor.AbstractDialog.prototype.hide = function() { if (this.dialogInternal_) { // This eventually fires the wrapped dialog's AFTER_HIDE event, calling our // handleAfterHide_(). this.dialogInternal_.setVisible(false); } }; /** * @return {boolean} Whether the dialog is open. */ goog.ui.editor.AbstractDialog.prototype.isOpen = function() { return !!this.dialogInternal_ && this.dialogInternal_.isVisible(); }; /** * Runs the handler registered on the OK button event and closes the dialog if * that handler succeeds. * This is useful in cases such as double-clicking an item in the dialog is * equivalent to selecting it and clicking the default button. * @protected */ goog.ui.editor.AbstractDialog.prototype.processOkAndClose = function() { // Fake an OK event from the wrapped dialog control. var evt = new goog.ui.Dialog.Event(goog.ui.Dialog.DefaultButtonKeys.OK, null); if (this.handleOk(evt)) { // handleOk calls dispatchEvent, so if any listener calls preventDefault it // will return false and we won't hide the dialog. this.hide(); } }; // *** Dialog events ******************************************************** // /** * Event type constants for events the dialog fires. * @enum {string} */ goog.ui.editor.AbstractDialog.EventType = { // This event is fired after the dialog is hidden, no matter if it was closed // via OK or Cancel or is being disposed without being hidden first. AFTER_HIDE: 'afterhide', // Either the cancel or OK events can be canceled via preventDefault or by // returning false from their handlers to stop the dialog from closing. CANCEL: 'cancel', OK: 'ok' }; // *** Inner helper class *************************************************** // /** * A builder class for the dialog control. All methods except build return this. * @param {goog.ui.editor.AbstractDialog} editorDialog Editor dialog object * that will wrap the wrapped dialog object this builder will create. * @constructor */ goog.ui.editor.AbstractDialog.Builder = function(editorDialog) { // We require the editor dialog to be passed in so that the builder can set up // ok/cancel listeners by default, making it easier for most dialogs. this.editorDialog_ = editorDialog; this.wrappedDialog_ = new goog.ui.Dialog('', true, this.editorDialog_.dom); this.buttonSet_ = new goog.ui.Dialog.ButtonSet(this.editorDialog_.dom); this.buttonHandlers_ = {}; this.addClassName(goog.getCssName('tr-dialog')); }; /** * Sets the title of the dialog. * @param {string} title Title HTML (escaped). * @return {goog.ui.editor.AbstractDialog.Builder} This. */ goog.ui.editor.AbstractDialog.Builder.prototype.setTitle = function(title) { this.wrappedDialog_.setTitle(title); return this; }; /** * Adds an OK button to the dialog. Clicking this button will cause {@link * handleOk} to run, subsequently dispatching an OK event. * @param {string=} opt_label The caption for the button, if not "OK". * @return {goog.ui.editor.AbstractDialog.Builder} This. */ goog.ui.editor.AbstractDialog.Builder.prototype.addOkButton = function(opt_label) { var key = goog.ui.Dialog.DefaultButtonKeys.OK; /** @desc Label for an OK button in an editor dialog. */ var MSG_TR_DIALOG_OK = goog.getMsg('OK'); // True means this is the default/OK button. this.buttonSet_.set(key, opt_label || MSG_TR_DIALOG_OK, true); this.buttonHandlers_[key] = goog.bind(this.editorDialog_.handleOk, this.editorDialog_); return this; }; /** * Adds a Cancel button to the dialog. Clicking this button will cause {@link * handleCancel} to run, subsequently dispatching a CANCEL event. * @param {string=} opt_label The caption for the button, if not "Cancel". * @return {goog.ui.editor.AbstractDialog.Builder} This. */ goog.ui.editor.AbstractDialog.Builder.prototype.addCancelButton = function(opt_label) { var key = goog.ui.Dialog.DefaultButtonKeys.CANCEL; /** @desc Label for a cancel button in an editor dialog. */ var MSG_TR_DIALOG_CANCEL = goog.getMsg('Cancel'); // False means it's not the OK button, true means it's the Cancel button. this.buttonSet_.set(key, opt_label || MSG_TR_DIALOG_CANCEL, false, true); this.buttonHandlers_[key] = goog.bind(this.editorDialog_.handleCancel, this.editorDialog_); return this; }; /** * Adds a custom button to the dialog. * @param {string} label The caption for the button. * @param {function(goog.ui.Dialog.EventType):*} handler Function called when * the button is clicked. It is recommended that this function be a method * in the concrete subclass of AbstractDialog using this Builder, and that * it dispatch an event (see {@link handleOk}). * @param {string=} opt_buttonId Identifier to be used to access the button when * calling AbstractDialog.getButtonElement(). * @return {goog.ui.editor.AbstractDialog.Builder} This. */ goog.ui.editor.AbstractDialog.Builder.prototype.addButton = function(label, handler, opt_buttonId) { // We don't care what the key is, just that we can match the button with the // handler function later. var key = opt_buttonId || goog.string.createUniqueString(); this.buttonSet_.set(key, label); this.buttonHandlers_[key] = handler; return this; }; /** * Puts a CSS class on the dialog's main element. * @param {string} className The class to add. * @return {goog.ui.editor.AbstractDialog.Builder} This. */ goog.ui.editor.AbstractDialog.Builder.prototype.addClassName = function(className) { goog.dom.classes.add(this.wrappedDialog_.getDialogElement(), className); return this; }; /** * Sets the content element of the dialog. * @param {Element} contentElem An element for the main body. * @return {goog.ui.editor.AbstractDialog.Builder} This. */ goog.ui.editor.AbstractDialog.Builder.prototype.setContent = function(contentElem) { goog.dom.appendChild(this.wrappedDialog_.getContentElement(), contentElem); return this; }; /** * Builds the wrapped dialog control. May only be called once, after which * no more methods may be called on this builder. * @return {goog.ui.Dialog} The wrapped dialog control. */ goog.ui.editor.AbstractDialog.Builder.prototype.build = function() { if (this.buttonSet_.isEmpty()) { // If caller didn't set any buttons, add an OK and Cancel button by default. this.addOkButton(); this.addCancelButton(); } this.wrappedDialog_.setButtonSet(this.buttonSet_); var handlers = this.buttonHandlers_; this.buttonHandlers_ = null; this.wrappedDialog_.addEventListener(goog.ui.Dialog.EventType.SELECT, // Listen for the SELECT event, which means a button was clicked, and // call the handler associated with that button via the key property. function(e) { if (handlers[e.key]) { return handlers[e.key](e); } }); // All editor dialogs are modal. this.wrappedDialog_.setModal(true); var dialog = this.wrappedDialog_; this.wrappedDialog_ = null; return dialog; }; /** * Editor dialog that will wrap the wrapped dialog this builder will create. * @type {goog.ui.editor.AbstractDialog} * @private */ goog.ui.editor.AbstractDialog.Builder.prototype.editorDialog_; /** * wrapped dialog control being built by this builder. * @type {goog.ui.Dialog} * @private */ goog.ui.editor.AbstractDialog.Builder.prototype.wrappedDialog_; /** * Set of buttons to be added to the wrapped dialog control. * @type {goog.ui.Dialog.ButtonSet} * @private */ goog.ui.editor.AbstractDialog.Builder.prototype.buttonSet_; /** * Map from keys that will be returned in the wrapped dialog SELECT events to * handler functions to be called to handle those events. * @type {Object} * @private */ goog.ui.editor.AbstractDialog.Builder.prototype.buttonHandlers_; // *** Protected interface ************************************************** // /** * The DOM helper for the parent document. * @type {goog.dom.DomHelper} * @protected */ goog.ui.editor.AbstractDialog.prototype.dom; /** * Creates and returns the goog.ui.Dialog control that is being wrapped * by this object. * @return {goog.ui.Dialog} Created Dialog control. * @protected */ goog.ui.editor.AbstractDialog.prototype.createDialogControl = goog.abstractMethod; /** * Returns the HTML Button element for the OK button in this dialog. * @return {Element} The button element if found, else null. * @protected */ goog.ui.editor.AbstractDialog.prototype.getOkButtonElement = function() { return this.getButtonElement(goog.ui.Dialog.DefaultButtonKeys.OK); }; /** * Returns the HTML Button element for the Cancel button in this dialog. * @return {Element} The button element if found, else null. * @protected */ goog.ui.editor.AbstractDialog.prototype.getCancelButtonElement = function() { return this.getButtonElement(goog.ui.Dialog.DefaultButtonKeys.CANCEL); }; /** * Returns the HTML Button element for the button added to this dialog with * the given button id. * @param {string} buttonId The id of the button to get. * @return {Element} The button element if found, else null. * @protected */ goog.ui.editor.AbstractDialog.prototype.getButtonElement = function(buttonId) { return this.dialogInternal_.getButtonSet().getButton(buttonId); }; /** * Creates and returns the event object to be used when dispatching the OK * event to listeners, or returns null to prevent the dialog from closing. * Subclasses should override this to return their own subclass of * goog.events.Event that includes all data a plugin would need from the dialog. * @param {goog.events.Event} e The event object dispatched by the wrapped * dialog. * @return {goog.events.Event} The event object to be used when dispatching the * OK event to listeners. * @protected */ goog.ui.editor.AbstractDialog.prototype.createOkEvent = goog.abstractMethod; /** * Handles the event dispatched by the wrapped dialog control when the user * clicks the OK button. Attempts to create the OK event object and dispatches * it if successful. * @param {goog.ui.Dialog.Event} e wrapped dialog OK event object. * @return {boolean} Whether the default action (closing the dialog) should * still be executed. This will be false if the OK event could not be * created to be dispatched, or if any listener to that event returs false * or calls preventDefault. * @protected */ goog.ui.editor.AbstractDialog.prototype.handleOk = function(e) { var eventObj = this.createOkEvent(e); if (eventObj) { return this.dispatchEvent(eventObj); } else { return false; } }; /** * Handles the event dispatched by the wrapped dialog control when the user * clicks the Cancel button. Simply dispatches a CANCEL event. * @return {boolean} Returns false if any of the handlers called prefentDefault * on the event or returned false themselves. * @protected */ goog.ui.editor.AbstractDialog.prototype.handleCancel = function() { return this.dispatchEvent(goog.ui.editor.AbstractDialog.EventType.CANCEL); }; /** * Disposes of the dialog. If the dialog is open, it will be hidden and * AFTER_HIDE will be dispatched. * @override * @protected */ goog.ui.editor.AbstractDialog.prototype.disposeInternal = function() { if (this.dialogInternal_) { this.hide(); this.dialogInternal_.dispose(); this.dialogInternal_ = null; } goog.ui.editor.AbstractDialog.superClass_.disposeInternal.call(this); }; // *** Private implementation *********************************************** // /** * The wrapped dialog widget. * @type {goog.ui.Dialog} * @private */ goog.ui.editor.AbstractDialog.prototype.dialogInternal_; /** * Cleans up after the dialog is hidden and fires the AFTER_HIDE event. Should * be a listener for the wrapped dialog's AFTER_HIDE event. * @private */ goog.ui.editor.AbstractDialog.prototype.handleAfterHide_ = function() { this.dispatchEvent(goog.ui.editor.AbstractDialog.EventType.AFTER_HIDE); };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Messages common to Editor UI components. * * @author robbyw@google.com (Robby Walker) */ goog.provide('goog.ui.editor.messages'); /** @desc Link button / bubble caption. */ goog.ui.editor.messages.MSG_LINK_CAPTION = goog.getMsg('Link'); /** @desc Title for the dialog that edits a link. */ goog.ui.editor.messages.MSG_EDIT_LINK = goog.getMsg('Edit Link'); /** @desc Prompt the user for the text of the link they've written. */ goog.ui.editor.messages.MSG_TEXT_TO_DISPLAY = goog.getMsg('Text to display:'); /** @desc Prompt the user for the URL of the link they've created. */ goog.ui.editor.messages.MSG_LINK_TO = goog.getMsg('Link to:'); /** @desc Prompt the user to type a web address for their link. */ goog.ui.editor.messages.MSG_ON_THE_WEB = goog.getMsg('Web address'); /** @desc More details on what linking to a web address involves.. */ goog.ui.editor.messages.MSG_ON_THE_WEB_TIP = goog.getMsg( 'Link to a page or file somewhere else on the web'); /** * @desc Text for a button that allows the user to test the link that * they created. */ goog.ui.editor.messages.MSG_TEST_THIS_LINK = goog.getMsg('Test this link'); /** * @desc Explanation for how to create a link with the link-editing dialog. */ goog.ui.editor.messages.MSG_TR_LINK_EXPLANATION = goog.getMsg( '{$startBold}Not sure what to put in the box?{$endBold} ' + 'First, find the page on the web that you want to ' + 'link to. (A {$searchEngineLink}search engine{$endLink} ' + 'might be useful.) Then, copy the web address from ' + "the box in your browser's address bar, and paste it into " + 'the box above.', {'startBold': '<b>', 'endBold': '</b>', 'searchEngineLink': "<a href='http://www.google.com/' target='_new'>", 'endLink': '</a>'}); /** @desc Prompt for the URL of a link that the user is creating. */ goog.ui.editor.messages.MSG_WHAT_URL = goog.getMsg( 'To what URL should this link go?'); /** * @desc Prompt for an email address, so that the user can create a link * that sends an email. */ goog.ui.editor.messages.MSG_EMAIL_ADDRESS = goog.getMsg('Email address'); /** * @desc Explanation of the prompt for an email address in a link. */ goog.ui.editor.messages.MSG_EMAIL_ADDRESS_TIP = goog.getMsg( 'Link to an email address'); /** @desc Error message when the user enters an invalid email address. */ goog.ui.editor.messages.MSG_INVALID_EMAIL = goog.getMsg( 'Invalid email address'); /** * @desc When the user creates a mailto link, asks them what email * address clicking on this link will send mail to. */ goog.ui.editor.messages.MSG_WHAT_EMAIL = goog.getMsg( 'To what email address should this link?'); /** * @desc Warning about the dangers of creating links with email * addresses in them. */ goog.ui.editor.messages.MSG_EMAIL_EXPLANATION = goog.getMsg( '{$preb}Be careful.{$postb} ' + 'Remember that any time you include an email address on a web page, ' + 'nasty spammers can find it too.', {'preb': '<b>', 'postb': '</b>'}); /** * @desc Label for the checkbox that allows the user to specify what when this * link is clicked, it should be opened in a new window. */ goog.ui.editor.messages.MSG_OPEN_IN_NEW_WINDOW = goog.getMsg( 'Open this link in a new window'); /** @desc Image bubble caption. */ goog.ui.editor.messages.MSG_IMAGE_CAPTION = goog.getMsg('Image');
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('goog.ui.editor.EquationEditorDialog'); goog.require('goog.editor.Command'); goog.require('goog.ui.editor.AbstractDialog'); goog.require('goog.ui.editor.EquationEditorOkEvent'); goog.require('goog.ui.equation.ChangeEvent'); goog.require('goog.ui.equation.TexEditor'); /** * Equation editor dialog (based on goog.ui.editor.AbstractDialog). * @param {Object} context The context that this dialog runs in. * @param {goog.dom.DomHelper} domHelper DomHelper to be used to create the * dialog's dom structure. * @param {string} equation Initial equation. * @param {string} helpUrl URL pointing to help documentation. * @constructor * @extends {goog.ui.editor.AbstractDialog} */ goog.ui.editor.EquationEditorDialog = function(context, domHelper, equation, helpUrl) { goog.ui.editor.AbstractDialog.call(this, domHelper); this.equationEditor_ = new goog.ui.equation.TexEditor(context, helpUrl); this.equationEditor_.render(); this.equationEditor_.setEquation(equation); this.equationEditor_.addEventListener(goog.editor.Command.EQUATION, this.onChange_, false, this); }; goog.inherits(goog.ui.editor.EquationEditorDialog, goog.ui.editor.AbstractDialog); /** * The equation editor actual UI. * @type {goog.ui.equation.TexEditor} * @private */ goog.ui.editor.EquationEditorDialog.prototype.equationEditor_; /** * The dialog's OK button element. * @type {Element?} * @private */ goog.ui.editor.EquationEditorDialog.prototype.okButton_; /** @override */ goog.ui.editor.EquationEditorDialog.prototype.createDialogControl = function() { var builder = new goog.ui.editor.AbstractDialog.Builder(this); /** * @desc The title of the equation editor dialog. */ var MSG_EE_DIALOG_TITLE = goog.getMsg('Equation Editor'); /** * @desc Button label for the equation editor dialog for adding * a new equation. */ var MSG_EE_BUTTON_SAVE_NEW = goog.getMsg('Insert equation'); /** * @desc Button label for the equation editor dialog for saving * a modified equation. */ var MSG_EE_BUTTON_SAVE_MODIFY = goog.getMsg('Save changes'); var okButtonText = this.equationEditor_.getEquation() ? MSG_EE_BUTTON_SAVE_MODIFY : MSG_EE_BUTTON_SAVE_NEW; builder.setTitle(MSG_EE_DIALOG_TITLE) .setContent(this.equationEditor_.getElement()) .addOkButton(okButtonText) .addCancelButton(); return builder.build(); }; /** * @override */ goog.ui.editor.EquationEditorDialog.prototype.createOkEvent = function(e) { if (this.equationEditor_.isValid()) { // Equation is not valid, don't close the dialog. return null; } var equationHtml = this.equationEditor_.getHtml(); return new goog.ui.editor.EquationEditorOkEvent(equationHtml); }; /** * Handles CHANGE event fired when user changes equation. * @param {goog.ui.equation.ChangeEvent} e The event object. * @private */ goog.ui.editor.EquationEditorDialog.prototype.onChange_ = function(e) { if (!this.okButton_) { this.okButton_ = this.getButtonElement( goog.ui.Dialog.DefaultButtonKeys.OK); } this.okButton_.disabled = !e.isValid; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Factory functions for creating a default editing toolbar. * * @author attila@google.com (Attila Bodis) * @author jparent@google.com (Julie Parent) * @see ../../demos/editor/editor.html */ goog.provide('goog.ui.editor.ButtonDescriptor'); goog.provide('goog.ui.editor.DefaultToolbar'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.dom.classes'); goog.require('goog.editor.Command'); goog.require('goog.style'); goog.require('goog.ui.editor.ToolbarFactory'); goog.require('goog.ui.editor.messages'); goog.require('goog.userAgent'); // Font menu creation. /** @desc Font menu item caption for the default sans-serif font. */ goog.ui.editor.DefaultToolbar.MSG_FONT_NORMAL = goog.getMsg('Normal'); /** @desc Font menu item caption for the default serif font. */ goog.ui.editor.DefaultToolbar.MSG_FONT_NORMAL_SERIF = goog.getMsg('Normal / serif'); /** * Common font descriptors for all locales. Each descriptor has the following * attributes: * <ul> * <li>{@code caption} - Caption to show in the font menu (e.g. 'Tahoma') * <li>{@code value} - Value for the corresponding 'font-family' CSS style * (e.g. 'Tahoma, Arial, sans-serif') * </ul> * @type {!Array.<{caption:string, value:string}>} * @private */ goog.ui.editor.DefaultToolbar.FONTS_ = [ { caption: goog.ui.editor.DefaultToolbar.MSG_FONT_NORMAL, value: 'arial,sans-serif' }, { caption: goog.ui.editor.DefaultToolbar.MSG_FONT_NORMAL_SERIF, value: 'times new roman,serif' }, {caption: 'Courier New', value: 'courier new,monospace'}, {caption: 'Georgia', value: 'georgia,serif'}, {caption: 'Trebuchet', value: 'trebuchet ms,sans-serif'}, {caption: 'Verdana', value: 'verdana,sans-serif'} ]; /** * Locale-specific font descriptors. The object is a map of locale strings to * arrays of font descriptors. * @type {!Object.<!Array.<{caption:string, value:string}>>} * @private */ goog.ui.editor.DefaultToolbar.I18N_FONTS_ = { 'ja': [{ caption: '\uff2d\uff33 \uff30\u30b4\u30b7\u30c3\u30af', value: 'ms pgothic,sans-serif' }, { caption: '\uff2d\uff33 \uff30\u660e\u671d', value: 'ms pmincho,serif' }, { caption: '\uff2d\uff33 \u30b4\u30b7\u30c3\u30af', value: 'ms gothic,monospace' }], 'ko': [{ caption: '\uad74\ub9bc', value: 'gulim,sans-serif' }, { caption: '\ubc14\ud0d5', value: 'batang,serif' }, { caption: '\uad74\ub9bc\uccb4', value: 'gulimche,monospace' }], 'zh-tw': [{ caption: '\u65b0\u7d30\u660e\u9ad4', value: 'pmingliu,serif' }, { caption: '\u7d30\u660e\u9ad4', value: 'mingliu,serif' }], 'zh-cn': [{ caption: '\u5b8b\u4f53', value: 'simsun,serif' }, { caption: '\u9ed1\u4f53', value: 'simhei,sans-serif' }, { caption: 'MS Song', value: 'ms song,monospace' }] }; /** * Default locale for font names. * @type {string} * @private */ goog.ui.editor.DefaultToolbar.locale_ = 'en-us'; /** * Sets the locale for the font names. If not set, defaults to 'en-us'. * Used only for default creation of font names name. Must be set * before font name menu is created. * @param {string} locale Locale to use for the toolbar font names. */ goog.ui.editor.DefaultToolbar.setLocale = function(locale) { goog.ui.editor.DefaultToolbar.locale_ = locale; }; /** * Initializes the given font menu button by adding default fonts to the menu. * If goog.ui.editor.DefaultToolbar.setLocale was called to specify a locale * for which locale-specific default fonts exist, those are added before * common fonts. * @param {!goog.ui.Select} button Font menu button. */ goog.ui.editor.DefaultToolbar.addDefaultFonts = function(button) { // Normalize locale to lowercase, with a hyphen (see bug 1036165). var locale = goog.ui.editor.DefaultToolbar.locale_.replace(/_/, '-').toLowerCase(); // Add locale-specific default fonts, if any. var fontlist = []; if (locale in goog.ui.editor.DefaultToolbar.I18N_FONTS_) { fontlist = goog.ui.editor.DefaultToolbar.I18N_FONTS_[locale]; } if (fontlist.length) { goog.ui.editor.ToolbarFactory.addFonts(button, fontlist); } // Add locale-independent default fonts. goog.ui.editor.ToolbarFactory.addFonts(button, goog.ui.editor.DefaultToolbar.FONTS_); }; // Font size menu creation. /** @desc Font size menu item caption for the 'Small' size. */ goog.ui.editor.DefaultToolbar.MSG_FONT_SIZE_SMALL = goog.getMsg('Small'); /** @desc Font size menu item caption for the 'Normal' size. */ goog.ui.editor.DefaultToolbar.MSG_FONT_SIZE_NORMAL = goog.getMsg('Normal'); /** @desc Font size menu item caption for the 'Large' size. */ goog.ui.editor.DefaultToolbar.MSG_FONT_SIZE_LARGE = goog.getMsg('Large'); /** @desc Font size menu item caption for the 'Huge' size. */ goog.ui.editor.DefaultToolbar.MSG_FONT_SIZE_HUGE = goog.getMsg('Huge'); /** * Font size descriptors, each with the following attributes: * <ul> * <li>{@code caption} - Caption to show in the font size menu (e.g. 'Huge') * <li>{@code value} - Value for the corresponding HTML font size (e.g. 6) * </ul> * @type {!Array.<{caption:string, value:number}>} * @private */ goog.ui.editor.DefaultToolbar.FONT_SIZES_ = [ {caption: goog.ui.editor.DefaultToolbar.MSG_FONT_SIZE_SMALL, value: 1}, {caption: goog.ui.editor.DefaultToolbar.MSG_FONT_SIZE_NORMAL, value: 2}, {caption: goog.ui.editor.DefaultToolbar.MSG_FONT_SIZE_LARGE, value: 4}, {caption: goog.ui.editor.DefaultToolbar.MSG_FONT_SIZE_HUGE, value: 6} ]; /** * Initializes the given font size menu button by adding default font sizes to * it. * @param {!goog.ui.Select} button Font size menu button. */ goog.ui.editor.DefaultToolbar.addDefaultFontSizes = function(button) { goog.ui.editor.ToolbarFactory.addFontSizes(button, goog.ui.editor.DefaultToolbar.FONT_SIZES_); }; // Header format menu creation. /** @desc Caption for "Heading" block format option. */ goog.ui.editor.DefaultToolbar.MSG_FORMAT_HEADING = goog.getMsg('Heading'); /** @desc Caption for "Subheading" block format option. */ goog.ui.editor.DefaultToolbar.MSG_FORMAT_SUBHEADING = goog.getMsg('Subheading'); /** @desc Caption for "Minor heading" block format option. */ goog.ui.editor.DefaultToolbar.MSG_FORMAT_MINOR_HEADING = goog.getMsg('Minor heading'); /** @desc Caption for "Normal" block format option. */ goog.ui.editor.DefaultToolbar.MSG_FORMAT_NORMAL = goog.getMsg('Normal'); /** * Format option descriptors, each with the following attributes: * <ul> * <li>{@code caption} - Caption to show in the menu (e.g. 'Minor heading') * <li>{@code command} - Corresponding {@link goog.dom.TagName} (e.g. * 'H4') * </ul> * @type {!Array.<{caption: string, command: !goog.dom.TagName}>} * @private */ goog.ui.editor.DefaultToolbar.FORMAT_OPTIONS_ = [ { caption: goog.ui.editor.DefaultToolbar.MSG_FORMAT_HEADING, command: goog.dom.TagName.H2 }, { caption: goog.ui.editor.DefaultToolbar.MSG_FORMAT_SUBHEADING, command: goog.dom.TagName.H3 }, { caption: goog.ui.editor.DefaultToolbar.MSG_FORMAT_MINOR_HEADING, command: goog.dom.TagName.H4 }, { caption: goog.ui.editor.DefaultToolbar.MSG_FORMAT_NORMAL, command: goog.dom.TagName.P } ]; /** * Initializes the given "Format block" menu button by adding default format * options to the menu. * @param {!goog.ui.Select} button "Format block" menu button. */ goog.ui.editor.DefaultToolbar.addDefaultFormatOptions = function(button) { goog.ui.editor.ToolbarFactory.addFormatOptions(button, goog.ui.editor.DefaultToolbar.FORMAT_OPTIONS_); }; /** * Creates a {@link goog.ui.Toolbar} containing a default set of editor * toolbar buttons, and renders it into the given parent element. * @param {!Element} elem Toolbar parent element. * @param {boolean=} opt_isRightToLeft Whether the editor chrome is * right-to-left; defaults to the directionality of the toolbar parent * element. * @return {!goog.ui.Toolbar} Default editor toolbar, rendered into the given * parent element. * @see goog.ui.editor.DefaultToolbar.DEFAULT_BUTTONS */ goog.ui.editor.DefaultToolbar.makeDefaultToolbar = function(elem, opt_isRightToLeft) { var isRightToLeft = opt_isRightToLeft || goog.style.isRightToLeft(elem); var buttons = isRightToLeft ? goog.ui.editor.DefaultToolbar.DEFAULT_BUTTONS_RTL : goog.ui.editor.DefaultToolbar.DEFAULT_BUTTONS; return goog.ui.editor.DefaultToolbar.makeToolbar(buttons, elem, opt_isRightToLeft); }; /** * Creates a {@link goog.ui.Toolbar} containing the specified set of * toolbar buttons, and renders it into the given parent element. Each * item in the {@code items} array must either be a * {@link goog.editor.Command} (to create a built-in button) or a subclass * of {@link goog.ui.Control} (to create a custom control). * @param {!Array.<string|goog.ui.Control>} items Toolbar items; each must * be a {@link goog.editor.Command} or a {@link goog.ui.Control}. * @param {!Element} elem Toolbar parent element. * @param {boolean=} opt_isRightToLeft Whether the editor chrome is * right-to-left; defaults to the directionality of the toolbar parent * element. * @return {!goog.ui.Toolbar} Editor toolbar, rendered into the given parent * element. */ goog.ui.editor.DefaultToolbar.makeToolbar = function(items, elem, opt_isRightToLeft) { var domHelper = goog.dom.getDomHelper(elem); var controls = []; for (var i = 0, button; button = items[i]; i++) { if (goog.isString(button)) { button = goog.ui.editor.DefaultToolbar.makeBuiltInToolbarButton(button, domHelper); } if (button) { controls.push(button); } } return goog.ui.editor.ToolbarFactory.makeToolbar(controls, elem, opt_isRightToLeft); }; /** * Creates an instance of a subclass of {@link goog.ui.Button} for the given * {@link goog.editor.Command}, or null if no built-in button exists for the * command. Note that this function is only intended to create built-in * buttons; please don't try to hack it! * @param {string} command Editor command ID. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {goog.ui.Button} Toolbar button (null if no built-in button exists * for the command). */ goog.ui.editor.DefaultToolbar.makeBuiltInToolbarButton = function(command, opt_domHelper) { var button; var descriptor = goog.ui.editor.DefaultToolbar.buttons_[command]; if (descriptor) { // Default the factory method to makeToggleButton, since most built-in // toolbar buttons are toggle buttons. See also // goog.ui.editor.DefaultToolbar.BUTTONS_. var factory = descriptor.factory || goog.ui.editor.ToolbarFactory.makeToggleButton; var id = descriptor.command; var tooltip = descriptor.tooltip; var caption = descriptor.caption; var classNames = descriptor.classes; // Default the DOM helper to the one for the current document. var domHelper = opt_domHelper || goog.dom.getDomHelper(); // Instantiate the button based on the descriptor. button = factory(id, tooltip, caption, classNames, null, domHelper); // If this button's state should be queried when updating the toolbar, // set the button object's queryable property to true. if (descriptor.queryable) { button.queryable = true; } } return button; }; /** * A set of built-in buttons to display in the default editor toolbar. * @type {!Array.<string>} */ goog.ui.editor.DefaultToolbar.DEFAULT_BUTTONS = [ goog.editor.Command.IMAGE, goog.editor.Command.LINK, goog.editor.Command.BOLD, goog.editor.Command.ITALIC, goog.editor.Command.UNORDERED_LIST, goog.editor.Command.FONT_COLOR, goog.editor.Command.FONT_FACE, goog.editor.Command.FONT_SIZE, goog.editor.Command.JUSTIFY_LEFT, goog.editor.Command.JUSTIFY_CENTER, goog.editor.Command.JUSTIFY_RIGHT, goog.editor.Command.EDIT_HTML ]; /** * A set of built-in buttons to display in the default editor toolbar when * the editor chrome is right-to-left (BiDi mode only). * @type {!Array.<string>} */ goog.ui.editor.DefaultToolbar.DEFAULT_BUTTONS_RTL = [ goog.editor.Command.IMAGE, goog.editor.Command.LINK, goog.editor.Command.BOLD, goog.editor.Command.ITALIC, goog.editor.Command.UNORDERED_LIST, goog.editor.Command.FONT_COLOR, goog.editor.Command.FONT_FACE, goog.editor.Command.FONT_SIZE, goog.editor.Command.JUSTIFY_RIGHT, goog.editor.Command.JUSTIFY_CENTER, goog.editor.Command.JUSTIFY_LEFT, goog.editor.Command.DIR_RTL, goog.editor.Command.DIR_LTR, goog.editor.Command.EDIT_HTML ]; /** * Creates a toolbar button with the given ID, tooltip, and caption. Applies * any custom CSS class names to the button's caption element. This button * is designed to be used as the RTL button. * @param {string} id Button ID; must equal a {@link goog.editor.Command} for * built-in buttons, anything else for custom buttons. * @param {string} tooltip Tooltip to be shown on hover. * @param {goog.ui.ControlContent} caption Button caption. * @param {string=} opt_classNames CSS class name(s) to apply to the caption * element. * @param {goog.ui.ButtonRenderer=} opt_renderer Button renderer; defaults to * {@link goog.ui.ToolbarButtonRenderer} if unspecified. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {!goog.ui.Button} A toolbar button. * @private */ goog.ui.editor.DefaultToolbar.rtlButtonFactory_ = function(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper) { var button = goog.ui.editor.ToolbarFactory.makeToggleButton(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper); button.updateFromValue = function(value) { // Enable/disable right-to-left text editing mode in the toolbar. var isRtl = !!value; // Enable/disable a marker class on the toolbar's root element; the rest is // done using CSS scoping in editortoolbar.css. This changes // direction-senitive toolbar icons (like indent/outdent) goog.dom.classes.enable( button.getParent().getElement(), goog.getCssName('tr-rtl-mode'), isRtl); button.setChecked(isRtl); }; return button; }; /** * Creates a toolbar button with the given ID, tooltip, and caption. Applies * any custom CSS class names to the button's caption element. Designed to * be used to create undo and redo buttons. * @param {string} id Button ID; must equal a {@link goog.editor.Command} for * built-in buttons, anything else for custom buttons. * @param {string} tooltip Tooltip to be shown on hover. * @param {goog.ui.ControlContent} caption Button caption. * @param {string=} opt_classNames CSS class name(s) to apply to the caption * element. * @param {goog.ui.ButtonRenderer=} opt_renderer Button renderer; defaults to * {@link goog.ui.ToolbarButtonRenderer} if unspecified. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {!goog.ui.Button} A toolbar button. * @private */ goog.ui.editor.DefaultToolbar.undoRedoButtonFactory_ = function(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper) { var button = goog.ui.editor.ToolbarFactory.makeButton(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper); button.updateFromValue = function(value) { button.setEnabled(value); }; return button; }; /** * Creates a toolbar button with the given ID, tooltip, and caption. Applies * any custom CSS class names to the button's caption element. Used to create * a font face button, filled with default fonts. * @param {string} id Button ID; must equal a {@link goog.editor.Command} for * built-in buttons, anything else for custom buttons. * @param {string} tooltip Tooltip to be shown on hover. * @param {goog.ui.ControlContent} caption Button caption. * @param {string=} opt_classNames CSS class name(s) to apply to the caption * element. * @param {goog.ui.MenuButtonRenderer=} opt_renderer Button renderer; defaults * to {@link goog.ui.ToolbarMenuButtonRenderer} if unspecified. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {!goog.ui.Button} A toolbar button. * @private */ goog.ui.editor.DefaultToolbar.fontFaceFactory_ = function(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper) { var button = goog.ui.editor.ToolbarFactory.makeSelectButton(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper); goog.ui.editor.DefaultToolbar.addDefaultFonts(button); button.setDefaultCaption(goog.ui.editor.DefaultToolbar.MSG_FONT_NORMAL); // Font options don't have keyboard accelerators. goog.dom.classes.add(button.getMenu().getContentElement(), goog.getCssName('goog-menu-noaccel')); // How to update this button's state. button.updateFromValue = function(value) { // Normalize value to null or a non-empty string (sometimes we get // the empty string, sometimes we get false...), extract the substring // up to the first comma to get the primary font name, and normalize // to lowercase. This allows us to map a font spec like "Arial, // Helvetica, sans-serif" to a font menu item. // TODO (attila): Try to make this more robust. var item = null; if (value && value.length > 0) { item = /** @type {goog.ui.MenuItem} */ (button.getMenu().getChild( goog.ui.editor.ToolbarFactory.getPrimaryFont(value))); } var selectedItem = button.getSelectedItem(); if (item != selectedItem) { button.setSelectedItem(item); } }; return button; }; /** * Creates a toolbar button with the given ID, tooltip, and caption. Applies * any custom CSS class names to the button's caption element. Use to create a * font size button, filled with default font sizes. * @param {string} id Button ID; must equal a {@link goog.editor.Command} for * built-in buttons, anything else for custom buttons. * @param {string} tooltip Tooltip to be shown on hover. * @param {goog.ui.ControlContent} caption Button caption. * @param {string=} opt_classNames CSS class name(s) to apply to the caption * element. * @param {goog.ui.MenuButtonRenderer=} opt_renderer Button renderer; defaults * to {@link goog.ui.ToolbarMebuButtonRenderer} if unspecified. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {!goog.ui.Button} A toolbar button. * @private */ goog.ui.editor.DefaultToolbar.fontSizeFactory_ = function(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper) { var button = goog.ui.editor.ToolbarFactory.makeSelectButton(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper); goog.ui.editor.DefaultToolbar.addDefaultFontSizes(button); button.setDefaultCaption(goog.ui.editor.DefaultToolbar.MSG_FONT_SIZE_NORMAL); // Font size options don't have keyboard accelerators. goog.dom.classes.add(button.getMenu().getContentElement(), goog.getCssName('goog-menu-noaccel')); // How to update this button's state. button.updateFromValue = function(value) { // Webkit pre-534.7 returns a string like '32px' instead of the equivalent // integer, so normalize that first. // NOTE(user): Gecko returns "6" so can't just normalize all // strings, only ones ending in "px". if (goog.isString(value) && goog.style.getLengthUnits(value) == 'px') { value = goog.ui.editor.ToolbarFactory.getLegacySizeFromPx( parseInt(value, 10)); } // Normalize value to null or a positive integer (sometimes we get // the empty string, sometimes we get false, or -1 if the above // normalization didn't match to a particular 0-7 size) value = value > 0 ? value : null; if (value != button.getValue()) { button.setValue(value); } }; return button; }; /** * Function to update the state of a color menu button. * @param {goog.ui.ToolbarColorMenuButton} button The button to which the * color menu is attached. * @param {number} color Color value to update to. * @private */ goog.ui.editor.DefaultToolbar.colorUpdateFromValue_ = function(button, color) { var value = color; /** @preserveTry */ try { if (goog.userAgent.IE) { // IE returns a number that, converted to hex, is a BGR color. // Convert from decimal to BGR to RGB. var hex = '000000' + value.toString(16); var bgr = hex.substr(hex.length - 6, 6); value = '#' + bgr.substring(4, 6) + bgr.substring(2, 4) + bgr.substring(0, 2); } if (value != button.getValue()) { button.setValue(/** @type {string} */ (value)); } } catch (ex) { // TODO(attila): Find out when/why this happens. } }; /** * Creates a toolbar button with the given ID, tooltip, and caption. Applies * any custom CSS class names to the button's caption element. Use to create * a font color button. * @param {string} id Button ID; must equal a {@link goog.editor.Command} for * built-in buttons, anything else for custom buttons. * @param {string} tooltip Tooltip to be shown on hover. * @param {goog.ui.ControlContent} caption Button caption. * @param {string=} opt_classNames CSS class name(s) to apply to the caption * element. * @param {goog.ui.ColorMenuButtonRenderer=} opt_renderer Button renderer; * defaults to {@link goog.ui.ToolbarColorMenuButtonRenderer} if * unspecified. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {!goog.ui.Button} A toolbar button. * @private */ goog.ui.editor.DefaultToolbar.fontColorFactory_ = function(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper) { var button = goog.ui.editor.ToolbarFactory.makeColorMenuButton(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper); // Initialize default foreground color. button.setSelectedColor('#000'); button.updateFromValue = goog.partial( goog.ui.editor.DefaultToolbar.colorUpdateFromValue_, button); return button; }; /** * Creates a toolbar button with the given ID, tooltip, and caption. Applies * any custom CSS class names to the button's caption element. Use to create * a font background color button. * @param {string} id Button ID; must equal a {@link goog.editor.Command} for * built-in buttons, anything else for custom buttons. * @param {string} tooltip Tooltip to be shown on hover. * @param {goog.ui.ControlContent} caption Button caption. * @param {string=} opt_classNames CSS class name(s) to apply to the caption * element. * @param {goog.ui.ColorMenuButtonRenderer=} opt_renderer Button renderer; * defaults to {@link goog.ui.ToolbarColorMenuButtonRenderer} if * unspecified. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {!goog.ui.Button} A toolbar button. * @private */ goog.ui.editor.DefaultToolbar.backgroundColorFactory_ = function(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper) { var button = goog.ui.editor.ToolbarFactory.makeColorMenuButton(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper); // Initialize default background color. button.setSelectedColor('#FFF'); button.updateFromValue = goog.partial( goog.ui.editor.DefaultToolbar.colorUpdateFromValue_, button); return button; }; /** * Creates a toolbar button with the given ID, tooltip, and caption. Applies * any custom CSS class names to the button's caption element. Use to create * the format menu, prefilled with default formats. * @param {string} id Button ID; must equal a {@link goog.editor.Command} for * built-in buttons, anything else for custom buttons. * @param {string} tooltip Tooltip to be shown on hover. * @param {goog.ui.ControlContent} caption Button caption. * @param {string=} opt_classNames CSS class name(s) to apply to the caption * element. * @param {goog.ui.MenuButtonRenderer=} opt_renderer Button renderer; * defaults to * {@link goog.ui.ToolbarMenuButtonRenderer} if unspecified. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {!goog.ui.Button} A toolbar button. * @private */ goog.ui.editor.DefaultToolbar.formatBlockFactory_ = function(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper) { var button = goog.ui.editor.ToolbarFactory.makeSelectButton(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper); goog.ui.editor.DefaultToolbar.addDefaultFormatOptions(button); button.setDefaultCaption(goog.ui.editor.DefaultToolbar.MSG_FORMAT_NORMAL); // Format options don't have keyboard accelerators. goog.dom.classes.add(button.getMenu().getContentElement(), goog.getCssName('goog-menu-noaccel')); // How to update this button. button.updateFromValue = function(value) { // Normalize value to null or a nonempty string (sometimes we get // the empty string, sometimes we get false...) value = value && value.length > 0 ? value : null; if (value != button.getValue()) { button.setValue(value); } }; return button; }; // Messages used for tooltips and captions. /** @desc Format menu tooltip. */ goog.ui.editor.DefaultToolbar.MSG_FORMAT_BLOCK_TITLE = goog.getMsg('Format'); /** @desc Format menu caption. */ goog.ui.editor.DefaultToolbar.MSG_FORMAT_BLOCK_CAPTION = goog.getMsg('Format'); /** @desc Undo button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_UNDO_TITLE = goog.getMsg('Undo'); /** @desc Redo button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_REDO_TITLE = goog.getMsg('Redo'); /** @desc Font menu tooltip. */ goog.ui.editor.DefaultToolbar.MSG_FONT_FACE_TITLE = goog.getMsg('Font'); /** @desc Font size menu tooltip. */ goog.ui.editor.DefaultToolbar.MSG_FONT_SIZE_TITLE = goog.getMsg('Font size'); /** @desc Text foreground color menu tooltip. */ goog.ui.editor.DefaultToolbar.MSG_FONT_COLOR_TITLE = goog.getMsg('Text color'); /** @desc Bold button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_BOLD_TITLE = goog.getMsg('Bold'); /** @desc Italic button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_ITALIC_TITLE = goog.getMsg('Italic'); /** @desc Underline button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_UNDERLINE_TITLE = goog.getMsg('Underline'); /** @desc Text background color menu tooltip. */ goog.ui.editor.DefaultToolbar.MSG_BACKGROUND_COLOR_TITLE = goog.getMsg('Text background color'); /** @desc Link button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_LINK_TITLE = goog.getMsg('Add or remove link'); /** @desc Numbered list button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_ORDERED_LIST_TITLE = goog.getMsg('Numbered list'); /** @desc Bullet list button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_UNORDERED_LIST_TITLE = goog.getMsg('Bullet list'); /** @desc Outdent button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_OUTDENT_TITLE = goog.getMsg('Decrease indent'); /** @desc Indent button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_INDENT_TITLE = goog.getMsg('Increase indent'); /** @desc Align left button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_ALIGN_LEFT_TITLE = goog.getMsg('Align left'); /** @desc Align center button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_ALIGN_CENTER_TITLE = goog.getMsg('Align center'); /** @desc Align right button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_ALIGN_RIGHT_TITLE = goog.getMsg('Align right'); /** @desc Justify button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_JUSTIFY_TITLE = goog.getMsg('Justify'); /** @desc Remove formatting button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_REMOVE_FORMAT_TITLE = goog.getMsg('Remove formatting'); /** @desc Insert image button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_IMAGE_TITLE = goog.getMsg('Insert image'); /** @desc Strike through button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_STRIKE_THROUGH_TITLE = goog.getMsg('Strikethrough'); /** @desc Left-to-right button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_DIR_LTR_TITLE = goog.getMsg('Left-to-right'); /** @desc Right-to-left button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_DIR_RTL_TITLE = goog.getMsg('Right-to-left'); /** @desc Blockquote button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_BLOCKQUOTE_TITLE = goog.getMsg('Quote'); /** @desc Edit HTML button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_EDIT_HTML_TITLE = goog.getMsg('Edit HTML source'); /** @desc Subscript button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_SUBSCRIPT = goog.getMsg('Subscript'); /** @desc Superscript button tooltip. */ goog.ui.editor.DefaultToolbar.MSG_SUPERSCRIPT = goog.getMsg('Superscript'); /** @desc Edit HTML button caption. */ goog.ui.editor.DefaultToolbar.MSG_EDIT_HTML_CAPTION = goog.getMsg('Edit HTML'); /** * Map of {@code goog.editor.Command}s to toolbar button descriptor objects, * each of which has the following attributes: * <ul> * <li>{@code command} - The command corresponding to the * button (mandatory) * <li>{@code tooltip} - Tooltip text (optional); if unspecified, the button * has no hover text * <li>{@code caption} - Caption to display on the button (optional); if * unspecified, the button has no text caption * <li>{@code classes} - CSS class name(s) to be applied to the button's * element when rendered (optional); if unspecified, defaults to * 'tr-icon' * plus 'tr-' followed by the command ID, but without any leading '+' * character (e.g. if the command ID is '+undo', then {@code classes} * defaults to 'tr-icon tr-undo') * <li>{@code factory} - factory function used to create the button, which * must accept {@code id}, {@code tooltip}, {@code caption}, and * {@code classes} as arguments, and must return an instance of * {@link goog.ui.Button} or an appropriate subclass (optional); if * unspecified, defaults to * {@link goog.ui.editor.DefaultToolbar.makeToggleButton}, * since most built-in toolbar buttons are toggle buttons * <li>(@code queryable} - Whether the button's state should be queried * when updating the toolbar (optional). * </ul> * Note that this object is only used for creating toolbar buttons for * built-in editor commands; custom buttons aren't listed here. Please don't * try to hack this! * @type {Object.<!goog.ui.editor.ButtonDescriptor>}. * @private */ goog.ui.editor.DefaultToolbar.buttons_ = {}; /** * @typedef {{command: string, tooltip: ?string, * caption: ?goog.ui.ControlContent, classes: ?string, * factory: ?function(string, string, goog.ui.ControlContent, ?string, * goog.ui.ButtonRenderer, goog.dom.DomHelper):goog.ui.Button, * queryable:?boolean}} */ goog.ui.editor.ButtonDescriptor; /** * Built-in toolbar button descriptors. See * {@link goog.ui.editor.DefaultToolbar.buttons_} for details on button * descriptor objects. This array is processed at JS parse time; each item is * inserted into {@link goog.ui.editor.DefaultToolbar.buttons_}, and the array * itself is deleted and (hopefully) garbage-collected. * @type {Array.<!goog.ui.editor.ButtonDescriptor>}. * @private */ goog.ui.editor.DefaultToolbar.BUTTONS_ = [{ command: goog.editor.Command.UNDO, tooltip: goog.ui.editor.DefaultToolbar.MSG_UNDO_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-undo'), factory: goog.ui.editor.DefaultToolbar.undoRedoButtonFactory_, queryable: true }, { command: goog.editor.Command.REDO, tooltip: goog.ui.editor.DefaultToolbar.MSG_REDO_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-redo'), factory: goog.ui.editor.DefaultToolbar.undoRedoButtonFactory_, queryable: true }, { command: goog.editor.Command.FONT_FACE, tooltip: goog.ui.editor.DefaultToolbar.MSG_FONT_FACE_TITLE, classes: goog.getCssName('tr-fontName'), factory: goog.ui.editor.DefaultToolbar.fontFaceFactory_, queryable: true }, { command: goog.editor.Command.FONT_SIZE, tooltip: goog.ui.editor.DefaultToolbar.MSG_FONT_SIZE_TITLE, classes: goog.getCssName('tr-fontSize'), factory: goog.ui.editor.DefaultToolbar.fontSizeFactory_, queryable: true }, { command: goog.editor.Command.BOLD, tooltip: goog.ui.editor.DefaultToolbar.MSG_BOLD_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-bold'), queryable: true }, { command: goog.editor.Command.ITALIC, tooltip: goog.ui.editor.DefaultToolbar.MSG_ITALIC_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-italic'), queryable: true }, { command: goog.editor.Command.UNDERLINE, tooltip: goog.ui.editor.DefaultToolbar.MSG_UNDERLINE_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-underline'), queryable: true }, { command: goog.editor.Command.FONT_COLOR, tooltip: goog.ui.editor.DefaultToolbar.MSG_FONT_COLOR_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-foreColor'), factory: goog.ui.editor.DefaultToolbar.fontColorFactory_, queryable: true }, { command: goog.editor.Command.BACKGROUND_COLOR, tooltip: goog.ui.editor.DefaultToolbar.MSG_BACKGROUND_COLOR_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-backColor'), factory: goog.ui.editor.DefaultToolbar.backgroundColorFactory_, queryable: true }, { command: goog.editor.Command.LINK, tooltip: goog.ui.editor.DefaultToolbar.MSG_LINK_TITLE, caption: goog.ui.editor.messages.MSG_LINK_CAPTION, classes: goog.getCssName('tr-link'), queryable: true }, { command: goog.editor.Command.ORDERED_LIST, tooltip: goog.ui.editor.DefaultToolbar.MSG_ORDERED_LIST_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-insertOrderedList'), queryable: true }, { command: goog.editor.Command.UNORDERED_LIST, tooltip: goog.ui.editor.DefaultToolbar.MSG_UNORDERED_LIST_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-insertUnorderedList'), queryable: true }, { command: goog.editor.Command.OUTDENT, tooltip: goog.ui.editor.DefaultToolbar.MSG_OUTDENT_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-outdent'), factory: goog.ui.editor.ToolbarFactory.makeButton }, { command: goog.editor.Command.INDENT, tooltip: goog.ui.editor.DefaultToolbar.MSG_INDENT_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-indent'), factory: goog.ui.editor.ToolbarFactory.makeButton }, { command: goog.editor.Command.JUSTIFY_LEFT, tooltip: goog.ui.editor.DefaultToolbar.MSG_ALIGN_LEFT_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-justifyLeft'), queryable: true }, { command: goog.editor.Command.JUSTIFY_CENTER, tooltip: goog.ui.editor.DefaultToolbar.MSG_ALIGN_CENTER_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-justifyCenter'), queryable: true }, { command: goog.editor.Command.JUSTIFY_RIGHT, tooltip: goog.ui.editor.DefaultToolbar.MSG_ALIGN_RIGHT_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-justifyRight'), queryable: true }, { command: goog.editor.Command.JUSTIFY_FULL, tooltip: goog.ui.editor.DefaultToolbar.MSG_JUSTIFY_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-justifyFull'), queryable: true }, { command: goog.editor.Command.REMOVE_FORMAT, tooltip: goog.ui.editor.DefaultToolbar.MSG_REMOVE_FORMAT_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-removeFormat'), factory: goog.ui.editor.ToolbarFactory.makeButton }, { command: goog.editor.Command.IMAGE, tooltip: goog.ui.editor.DefaultToolbar.MSG_IMAGE_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-image'), factory: goog.ui.editor.ToolbarFactory.makeButton }, { command: goog.editor.Command.STRIKE_THROUGH, tooltip: goog.ui.editor.DefaultToolbar.MSG_STRIKE_THROUGH_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-strikeThrough'), queryable: true }, { command: goog.editor.Command.SUBSCRIPT, tooltip: goog.ui.editor.DefaultToolbar.MSG_SUBSCRIPT, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-subscript'), queryable: true } , { command: goog.editor.Command.SUPERSCRIPT, tooltip: goog.ui.editor.DefaultToolbar.MSG_SUPERSCRIPT, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-superscript'), queryable: true }, { command: goog.editor.Command.DIR_LTR, tooltip: goog.ui.editor.DefaultToolbar.MSG_DIR_LTR_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-ltr'), queryable: true }, { command: goog.editor.Command.DIR_RTL, tooltip: goog.ui.editor.DefaultToolbar.MSG_DIR_RTL_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-rtl'), factory: goog.ui.editor.DefaultToolbar.rtlButtonFactory_, queryable: true }, { command: goog.editor.Command.BLOCKQUOTE, tooltip: goog.ui.editor.DefaultToolbar.MSG_BLOCKQUOTE_TITLE, classes: goog.getCssName('tr-icon') + ' ' + goog.getCssName('tr-BLOCKQUOTE'), queryable: true }, { command: goog.editor.Command.FORMAT_BLOCK, tooltip: goog.ui.editor.DefaultToolbar.MSG_FORMAT_BLOCK_TITLE, caption: goog.ui.editor.DefaultToolbar.MSG_FORMAT_BLOCK_CAPTION, classes: goog.getCssName('tr-formatBlock'), factory: goog.ui.editor.DefaultToolbar.formatBlockFactory_, queryable: true }, { command: goog.editor.Command.EDIT_HTML, tooltip: goog.ui.editor.DefaultToolbar.MSG_EDIT_HTML_TITLE, caption: goog.ui.editor.DefaultToolbar.MSG_EDIT_HTML_CAPTION, classes: goog.getCssName('tr-editHtml'), factory: goog.ui.editor.ToolbarFactory.makeButton }]; (function() { // Create the goog.ui.editor.DefaultToolbar.buttons_ map from // goog.ui.editor.DefaultToolbar.BUTTONS_. for (var i = 0, button; button = goog.ui.editor.DefaultToolbar.BUTTONS_[i]; i++) { goog.ui.editor.DefaultToolbar.buttons_[button.command] = button; } // goog.ui.editor.DefaultToolbar.BUTTONS_ is no longer needed // once the map is ready. delete goog.ui.editor.DefaultToolbar.BUTTONS_; })();
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A dialog for editing/creating a link. * */ goog.provide('goog.ui.editor.LinkDialog'); goog.provide('goog.ui.editor.LinkDialog.BeforeTestLinkEvent'); goog.provide('goog.ui.editor.LinkDialog.EventType'); goog.provide('goog.ui.editor.LinkDialog.OkEvent'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.editor.BrowserFeature'); goog.require('goog.editor.Link'); goog.require('goog.editor.focus'); goog.require('goog.editor.node'); goog.require('goog.events.Event'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventType'); goog.require('goog.events.InputHandler'); goog.require('goog.string'); goog.require('goog.style'); goog.require('goog.ui.Button'); goog.require('goog.ui.Component'); goog.require('goog.ui.LinkButtonRenderer'); goog.require('goog.ui.editor.AbstractDialog'); goog.require('goog.ui.editor.TabPane'); goog.require('goog.ui.editor.messages'); goog.require('goog.userAgent'); goog.require('goog.window'); /** * A type of goog.ui.editor.AbstractDialog for editing/creating a link. * @param {goog.dom.DomHelper} domHelper DomHelper to be used to create the * dialog's dom structure. * @param {goog.editor.Link} link The target link. * @constructor * @extends {goog.ui.editor.AbstractDialog} */ goog.ui.editor.LinkDialog = function(domHelper, link) { goog.base(this, domHelper); this.targetLink_ = link; /** * The event handler for this dialog. * @type {goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); }; goog.inherits(goog.ui.editor.LinkDialog, goog.ui.editor.AbstractDialog); /** * Events specific to the link dialog. * @enum {string} */ goog.ui.editor.LinkDialog.EventType = { BEFORE_TEST_LINK: 'beforetestlink' }; /** * OK event object for the link dialog. * @param {string} linkText Text the user chose to display for the link. * @param {string} linkUrl Url the user chose for the link to point to. * @param {boolean} openInNewWindow Whether the link should open in a new window * when clicked. * @param {boolean} noFollow Whether the link should have 'rel=nofollow' * attribute. * @constructor * @extends {goog.events.Event} */ goog.ui.editor.LinkDialog.OkEvent = function( linkText, linkUrl, openInNewWindow, noFollow) { goog.base(this, goog.ui.editor.AbstractDialog.EventType.OK); /** * The text of the link edited in the dialog. * @type {string} */ this.linkText = linkText; /** * The url of the link edited in the dialog. * @type {string} */ this.linkUrl = linkUrl; /** * Whether the link should open in a new window when clicked. * @type {boolean} */ this.openInNewWindow = openInNewWindow; /** * Whether the link should have 'rel=nofollow' attribute. * @type {boolean} */ this.noFollow = noFollow; }; goog.inherits(goog.ui.editor.LinkDialog.OkEvent, goog.events.Event); /** * Event fired before testing a link by opening it in another window. * Calling preventDefault will stop the link from being opened. * @param {string} url Url of the link being tested. * @constructor * @extends {goog.events.Event} */ goog.ui.editor.LinkDialog.BeforeTestLinkEvent = function(url) { goog.base(this, goog.ui.editor.LinkDialog.EventType.BEFORE_TEST_LINK); /** * The url of the link being tested. * @type {string} */ this.url = url; }; goog.inherits(goog.ui.editor.LinkDialog.BeforeTestLinkEvent, goog.events.Event); /** * Optional warning to show about email addresses. * @type {string|undefined} * @private */ goog.ui.editor.LinkDialog.prototype.emailWarning_; /** * Whether to show a checkbox where the user can choose to have the link open in * a new window. * @type {boolean} * @private */ goog.ui.editor.LinkDialog.prototype.showOpenLinkInNewWindow_ = false; /** * Whether the "open link in new window" checkbox should be checked when the * dialog is shown, and also whether it was checked last time the dialog was * closed. * @type {boolean} * @private */ goog.ui.editor.LinkDialog.prototype.isOpenLinkInNewWindowChecked_ = false; /** * Whether to show a checkbox where the user can choose to have 'rel=nofollow' * attribute added to the link. * @type {boolean} * @private */ goog.ui.editor.LinkDialog.prototype.showRelNoFollow_ = false; /** * Sets the warning message to show to users about including email addresses on * public web pages. * @param {string} emailWarning Warning message to show users about including * email addresses on the web. */ goog.ui.editor.LinkDialog.prototype.setEmailWarning = function( emailWarning) { this.emailWarning_ = emailWarning; }; /** * Tells the dialog to show a checkbox where the user can choose to have the * link open in a new window. * @param {boolean} startChecked Whether to check the checkbox the first * time the dialog is shown. Subesquent times the checkbox will remember its * previous state. */ goog.ui.editor.LinkDialog.prototype.showOpenLinkInNewWindow = function( startChecked) { this.showOpenLinkInNewWindow_ = true; this.isOpenLinkInNewWindowChecked_ = startChecked; }; /** * Tells the dialog to show a checkbox where the user can choose to add * 'rel=nofollow' attribute to the link. */ goog.ui.editor.LinkDialog.prototype.showRelNoFollow = function() { this.showRelNoFollow_ = true; }; /** @override */ goog.ui.editor.LinkDialog.prototype.show = function() { goog.base(this, 'show'); this.selectAppropriateTab_(this.textToDisplayInput_.value, this.getTargetUrl_()); this.syncOkButton_(); if (this.showOpenLinkInNewWindow_) { if (!this.targetLink_.isNew()) { // If link is not new, checkbox should reflect current target. this.isOpenLinkInNewWindowChecked_ = this.targetLink_.getAnchor().target == '_blank'; } this.openInNewWindowCheckbox_.checked = this.isOpenLinkInNewWindowChecked_; } if (this.showRelNoFollow_) { this.relNoFollowCheckbox_.checked = goog.ui.editor.LinkDialog.hasNoFollow(this.targetLink_.getAnchor().rel); } }; /** @override */ goog.ui.editor.LinkDialog.prototype.hide = function() { this.disableAutogenFlag_(false); goog.base(this, 'hide'); }; /** * Tells the dialog whether to show the 'text to display' div. * When the target element of the dialog is an image, there is no link text * to modify. This function can be used for this kind of situations. * @param {boolean} visible Whether to make 'text to display' div visible. */ goog.ui.editor.LinkDialog.prototype.setTextToDisplayVisible = function( visible) { if (this.textToDisplayDiv_) { goog.style.setStyle(this.textToDisplayDiv_, 'display', visible ? 'block' : 'none'); } }; /** * Tells the plugin whether to stop leaking the page's url via the referrer * header when the "test this link" link is clicked. * @param {boolean} stop Whether to stop leaking the referrer. */ goog.ui.editor.LinkDialog.prototype.setStopReferrerLeaks = function(stop) { this.stopReferrerLeaks_ = stop; }; /** * Tells the dialog whether the autogeneration of text to display is to be * enabled. * @param {boolean} enable Whether to enable the feature. */ goog.ui.editor.LinkDialog.prototype.setAutogenFeatureEnabled = function( enable) { this.autogenFeatureEnabled_ = enable; }; /** * Checks if {@code str} contains {@code "nofollow"} as a separate word. * @param {string} str String to be tested. This is usually {@code rel} * attribute of an {@code HTMLAnchorElement} object. * @return {boolean} {@code true} if {@code str} contains {@code nofollow}. */ goog.ui.editor.LinkDialog.hasNoFollow = function(str) { return goog.ui.editor.LinkDialog.NO_FOLLOW_REGEX_.test(str); }; /** * Removes {@code "nofollow"} from {@code rel} if it's present as a separate * word. * @param {string} rel Input string. This is usually {@code rel} attribute of * an {@code HTMLAnchorElement} object. * @return {string} {@code rel} with any {@code "nofollow"} removed. */ goog.ui.editor.LinkDialog.removeNoFollow = function(rel) { return rel.replace(goog.ui.editor.LinkDialog.NO_FOLLOW_REGEX_, ''); }; // *** Protected interface ************************************************** // /** @override */ goog.ui.editor.LinkDialog.prototype.createDialogControl = function() { var builder = new goog.ui.editor.AbstractDialog.Builder(this); builder.setTitle(goog.ui.editor.messages.MSG_EDIT_LINK) .setContent(this.createDialogContent_()); return builder.build(); }; /** * Creates and returns the event object to be used when dispatching the OK * event to listeners based on which tab is currently selected and the contents * of the input fields of that tab. * @return {goog.ui.editor.LinkDialog.OkEvent} The event object to be used when * dispatching the OK event to listeners. * @protected * @override */ goog.ui.editor.LinkDialog.prototype.createOkEvent = function() { if (this.tabPane_.getCurrentTabId() == goog.ui.editor.LinkDialog.Id_.EMAIL_ADDRESS_TAB) { return this.createOkEventFromEmailTab_(); } else { return this.createOkEventFromWebTab_(); } }; /** @override */ goog.ui.editor.LinkDialog.prototype.disposeInternal = function() { this.eventHandler_.dispose(); this.eventHandler_ = null; this.tabPane_.dispose(); this.tabPane_ = null; this.urlInputHandler_.dispose(); this.urlInputHandler_ = null; this.emailInputHandler_.dispose(); this.emailInputHandler_ = null; goog.base(this, 'disposeInternal'); }; // *** Private implementation *********************************************** // /** * Regular expression that matches {@code nofollow} value in an * {@code * HTMLAnchorElement}'s {@code rel} element. * @type {RegExp} * @private */ goog.ui.editor.LinkDialog.NO_FOLLOW_REGEX_ = /\bnofollow\b/i; /** * The link being modified by this dialog. * @type {goog.editor.Link} * @private */ goog.ui.editor.LinkDialog.prototype.targetLink_; /** * EventHandler object that keeps track of all handlers set by this dialog. * @type {goog.events.EventHandler} * @private */ goog.ui.editor.LinkDialog.prototype.eventHandler_; /** * InputHandler object to listen for changes in the url input field. * @type {goog.events.InputHandler} * @private */ goog.ui.editor.LinkDialog.prototype.urlInputHandler_; /** * InputHandler object to listen for changes in the email input field. * @type {goog.events.InputHandler} * @private */ goog.ui.editor.LinkDialog.prototype.emailInputHandler_; /** * The tab bar where the url and email tabs are. * @type {goog.ui.editor.TabPane} * @private */ goog.ui.editor.LinkDialog.prototype.tabPane_; /** * The div element holding the link's display text input. * @type {HTMLDivElement} * @private */ goog.ui.editor.LinkDialog.prototype.textToDisplayDiv_; /** * The input element holding the link's display text. * @type {HTMLInputElement} * @private */ goog.ui.editor.LinkDialog.prototype.textToDisplayInput_; /** * Whether or not the feature of automatically generating the display text is * enabled. * @type {boolean} * @private */ goog.ui.editor.LinkDialog.prototype.autogenFeatureEnabled_ = true; /** * Whether or not we should automatically generate the display text. * @type {boolean} * @private */ goog.ui.editor.LinkDialog.prototype.autogenerateTextToDisplay_; /** * Whether or not automatic generation of the display text is disabled. * @type {boolean} * @private */ goog.ui.editor.LinkDialog.prototype.disableAutogen_; /** * The input element (checkbox) to indicate that the link should open in a new * window. * @type {HTMLInputElement} * @private */ goog.ui.editor.LinkDialog.prototype.openInNewWindowCheckbox_; /** * The input element (checkbox) to indicate that the link should have * 'rel=nofollow' attribute. * @type {HTMLInputElement} * @private */ goog.ui.editor.LinkDialog.prototype.relNoFollowCheckbox_; /** * Whether to stop leaking the page's url via the referrer header when the * "test this link" link is clicked. * @type {boolean} * @private */ goog.ui.editor.LinkDialog.prototype.stopReferrerLeaks_ = false; /** * Creates contents of this dialog. * @return {Element} Contents of the dialog as a DOM element. * @private */ goog.ui.editor.LinkDialog.prototype.createDialogContent_ = function() { this.textToDisplayDiv_ = /** @type {HTMLDivElement} */( this.buildTextToDisplayDiv_()); var content = this.dom.createDom(goog.dom.TagName.DIV, null, this.textToDisplayDiv_); this.tabPane_ = new goog.ui.editor.TabPane(this.dom, goog.ui.editor.messages.MSG_LINK_TO); this.tabPane_.addTab(goog.ui.editor.LinkDialog.Id_.ON_WEB_TAB, goog.ui.editor.messages.MSG_ON_THE_WEB, goog.ui.editor.messages.MSG_ON_THE_WEB_TIP, goog.ui.editor.LinkDialog.BUTTON_GROUP_, this.buildTabOnTheWeb_()); this.tabPane_.addTab(goog.ui.editor.LinkDialog.Id_.EMAIL_ADDRESS_TAB, goog.ui.editor.messages.MSG_EMAIL_ADDRESS, goog.ui.editor.messages.MSG_EMAIL_ADDRESS_TIP, goog.ui.editor.LinkDialog.BUTTON_GROUP_, this.buildTabEmailAddress_()); this.tabPane_.render(content); this.eventHandler_.listen(this.tabPane_, goog.ui.Component.EventType.SELECT, this.onChangeTab_); if (this.showOpenLinkInNewWindow_) { content.appendChild(this.buildOpenInNewWindowDiv_()); } if (this.showRelNoFollow_) { content.appendChild(this.buildRelNoFollowDiv_()); } return content; }; /** * Builds and returns the text to display section of the edit link dialog. * @return {Element} A div element to be appended into the dialog div. * @private */ goog.ui.editor.LinkDialog.prototype.buildTextToDisplayDiv_ = function() { var table = this.dom.createTable(1, 2); table.cellSpacing = '0'; table.cellPadding = '0'; table.style.fontSize = '10pt'; // Build the text to display input. var textToDisplayDiv = this.dom.createDom(goog.dom.TagName.DIV); table.rows[0].cells[0].innerHTML = '<span style="position: relative;' + ' bottom: 2px; padding-right: 1px; white-space: nowrap;">' + goog.ui.editor.messages.MSG_TEXT_TO_DISPLAY + '&nbsp;</span>'; this.textToDisplayInput_ = /** @type {HTMLInputElement} */( this.dom.createDom(goog.dom.TagName.INPUT, {id: goog.ui.editor.LinkDialog.Id_.TEXT_TO_DISPLAY})); var textInput = this.textToDisplayInput_; // 98% prevents scroll bars in standards mode. // TODO(robbyw): Is this necessary for quirks mode? goog.style.setStyle(textInput, 'width', '98%'); goog.style.setStyle(table.rows[0].cells[1], 'width', '100%'); goog.dom.appendChild(table.rows[0].cells[1], textInput); textInput.value = this.targetLink_.getCurrentText(); this.eventHandler_.listen(textInput, goog.events.EventType.KEYUP, goog.bind(this.onTextToDisplayEdit_, this)); goog.dom.appendChild(textToDisplayDiv, table); return textToDisplayDiv; }; /** * Builds and returns the "checkbox to open the link in a new window" section of * the edit link dialog. * @return {Element} A div element to be appended into the dialog div. * @private */ goog.ui.editor.LinkDialog.prototype.buildOpenInNewWindowDiv_ = function() { this.openInNewWindowCheckbox_ = /** @type {HTMLInputElement} */( this.dom.createDom(goog.dom.TagName.INPUT, {'type': 'checkbox'})); return this.dom.createDom(goog.dom.TagName.DIV, null, this.dom.createDom(goog.dom.TagName.LABEL, null, this.openInNewWindowCheckbox_, goog.ui.editor.messages.MSG_OPEN_IN_NEW_WINDOW)); }; /** * Creates a DIV with a checkbox for {@code rel=nofollow} option. * @return {Element} Newly created DIV element. * @private */ goog.ui.editor.LinkDialog.prototype.buildRelNoFollowDiv_ = function() { /** @desc Checkbox text for adding 'rel=nofollow' attribute to a link. */ var MSG_ADD_REL_NOFOLLOW_ATTR = goog.getMsg( "Add '{$relNoFollow}' attribute ({$linkStart}Learn more{$linkEnd})", { 'relNoFollow': 'rel=nofollow', 'linkStart': '<a href="http://support.google.com/webmasters/bin/' + 'answer.py?hl=en&answer=96569" target="_blank">', 'linkEnd': '</a>' }); this.relNoFollowCheckbox_ = /** @type {HTMLInputElement} */( this.dom.createDom(goog.dom.TagName.INPUT, {'type': 'checkbox'})); return this.dom.createDom(goog.dom.TagName.DIV, null, this.dom.createDom(goog.dom.TagName.LABEL, null, this.relNoFollowCheckbox_, goog.dom.htmlToDocumentFragment(MSG_ADD_REL_NOFOLLOW_ATTR))); }; /** * Builds and returns the div containing the tab "On the web". * @return {Element} The div element containing the tab. * @private */ goog.ui.editor.LinkDialog.prototype.buildTabOnTheWeb_ = function() { var onTheWebDiv = this.dom.createElement(goog.dom.TagName.DIV); var headingDiv = this.dom.createDom(goog.dom.TagName.DIV, {innerHTML: '<b>' + goog.ui.editor.messages.MSG_WHAT_URL + '</b>'}); var urlInput = this.dom.createDom(goog.dom.TagName.INPUT, { id: goog.ui.editor.LinkDialog.Id_.ON_WEB_INPUT, className: goog.ui.editor.LinkDialog.TARGET_INPUT_CLASSNAME_ }); // IE throws on unknown values for type. if (!goog.userAgent.IE) { // On browsers that support Web Forms 2.0, allow autocompletion of URLs. // (As of now, this is only supported by Opera 9) urlInput.type = 'url'; } if (goog.editor.BrowserFeature.NEEDS_99_WIDTH_IN_STANDARDS_MODE && goog.editor.node.isStandardsMode(urlInput)) { urlInput.style.width = '99%'; } var inputDiv = this.dom.createDom(goog.dom.TagName.DIV, null, urlInput); this.urlInputHandler_ = new goog.events.InputHandler(urlInput); this.eventHandler_.listen(this.urlInputHandler_, goog.events.InputHandler.EventType.INPUT, this.onUrlOrEmailInputChange_); var testLink = new goog.ui.Button(goog.ui.editor.messages.MSG_TEST_THIS_LINK, goog.ui.LinkButtonRenderer.getInstance(), this.dom); testLink.render(inputDiv); testLink.getElement().style.marginTop = '1em'; this.eventHandler_.listen(testLink, goog.ui.Component.EventType.ACTION, this.onWebTestLink_); // Build the "On the web" explanation text div. var explanationDiv = this.dom.createDom(goog.dom.TagName.DIV, { className: goog.ui.editor.LinkDialog.EXPLANATION_TEXT_CLASSNAME_, innerHTML: goog.ui.editor.messages.MSG_TR_LINK_EXPLANATION }); onTheWebDiv.appendChild(headingDiv); onTheWebDiv.appendChild(inputDiv); onTheWebDiv.appendChild(explanationDiv); return onTheWebDiv; }; /** * Builds and returns the div containing the tab "Email address". * @return {Element} the div element containing the tab. * @private */ goog.ui.editor.LinkDialog.prototype.buildTabEmailAddress_ = function() { var emailTab = this.dom.createDom(goog.dom.TagName.DIV); var headingDiv = this.dom.createDom(goog.dom.TagName.DIV, {innerHTML: '<b>' + goog.ui.editor.messages.MSG_WHAT_EMAIL + '</b>'}); goog.dom.appendChild(emailTab, headingDiv); var emailInput = this.dom.createDom(goog.dom.TagName.INPUT, { id: goog.ui.editor.LinkDialog.Id_.EMAIL_ADDRESS_INPUT, className: goog.ui.editor.LinkDialog.TARGET_INPUT_CLASSNAME_ }); if (goog.editor.BrowserFeature.NEEDS_99_WIDTH_IN_STANDARDS_MODE && goog.editor.node.isStandardsMode(emailInput)) { // Standards mode sizes this too large. emailInput.style.width = '99%'; } goog.dom.appendChild(emailTab, emailInput); this.emailInputHandler_ = new goog.events.InputHandler(emailInput); this.eventHandler_.listen(this.emailInputHandler_, goog.events.InputHandler.EventType.INPUT, this.onUrlOrEmailInputChange_); goog.dom.appendChild(emailTab, this.dom.createDom(goog.dom.TagName.DIV, { id: goog.ui.editor.LinkDialog.Id_.EMAIL_WARNING, className: goog.ui.editor.LinkDialog.EMAIL_WARNING_CLASSNAME_, style: 'visibility:hidden' }, goog.ui.editor.messages.MSG_INVALID_EMAIL)); if (this.emailWarning_) { var explanationDiv = this.dom.createDom(goog.dom.TagName.DIV, { className: goog.ui.editor.LinkDialog.EXPLANATION_TEXT_CLASSNAME_, innerHTML: this.emailWarning_ }); goog.dom.appendChild(emailTab, explanationDiv); } return emailTab; }; /** * Returns the url that the target points to. * @return {string} The url that the target points to. * @private */ goog.ui.editor.LinkDialog.prototype.getTargetUrl_ = function() { // Get the href-attribute through getAttribute() rather than the href property // because Google-Toolbar on Firefox with "Send with Gmail" turned on // modifies the href-property of 'mailto:' links but leaves the attribute // untouched. return this.targetLink_.getAnchor().getAttribute('href') || ''; }; /** * Selects the correct tab based on the URL, and fills in its inputs. * For new links, it suggests a url based on the link text. * @param {string} text The inner text of the link. * @param {string} url The href for the link. * @private */ goog.ui.editor.LinkDialog.prototype.selectAppropriateTab_ = function( text, url) { if (this.isNewLink_()) { // Newly created non-empty link: try to infer URL from the link text. this.guessUrlAndSelectTab_(text); } else if (goog.editor.Link.isMailto(url)) { // The link is for an email. this.tabPane_.setSelectedTabId( goog.ui.editor.LinkDialog.Id_.EMAIL_ADDRESS_TAB); this.dom.getElement(goog.ui.editor.LinkDialog.Id_.EMAIL_ADDRESS_INPUT) .value = url.substring(url.indexOf(':') + 1); this.setAutogenFlagFromCurInput_(); } else { // No specific tab was appropriate, default to on the web tab. this.tabPane_.setSelectedTabId(goog.ui.editor.LinkDialog.Id_.ON_WEB_TAB); this.dom.getElement(goog.ui.editor.LinkDialog.Id_.ON_WEB_INPUT) .value = this.isNewLink_() ? 'http://' : url; this.setAutogenFlagFromCurInput_(); } }; /** * Select a url/tab based on the link's text. This function is simply * the isNewLink_() == true case of selectAppropriateTab_(). * @param {string} text The inner text of the link. * @private */ goog.ui.editor.LinkDialog.prototype.guessUrlAndSelectTab_ = function(text) { if (goog.editor.Link.isLikelyEmailAddress(text)) { // The text is for an email address. this.tabPane_.setSelectedTabId( goog.ui.editor.LinkDialog.Id_.EMAIL_ADDRESS_TAB); this.dom.getElement(goog.ui.editor.LinkDialog.Id_.EMAIL_ADDRESS_INPUT) .value = text; this.setAutogenFlag_(true); // TODO(user): Why disable right after enabling? What bug are we // working around? this.disableAutogenFlag_(true); } else if (goog.editor.Link.isLikelyUrl(text)) { // The text is for a web URL. this.tabPane_.setSelectedTabId(goog.ui.editor.LinkDialog.Id_.ON_WEB_TAB); this.dom.getElement(goog.ui.editor.LinkDialog.Id_.ON_WEB_INPUT) .value = text; this.setAutogenFlag_(true); this.disableAutogenFlag_(true); } else { // No meaning could be deduced from text, choose a default tab. if (!this.targetLink_.getCurrentText()) { this.setAutogenFlag_(true); } this.tabPane_.setSelectedTabId(goog.ui.editor.LinkDialog.Id_.ON_WEB_TAB); } }; /** * Called on a change to the url or email input. If either one of those tabs * is active, sets the OK button to enabled/disabled accordingly. * @private */ goog.ui.editor.LinkDialog.prototype.syncOkButton_ = function() { var inputValue; if (this.tabPane_.getCurrentTabId() == goog.ui.editor.LinkDialog.Id_.EMAIL_ADDRESS_TAB) { inputValue = this.dom.getElement( goog.ui.editor.LinkDialog.Id_.EMAIL_ADDRESS_INPUT).value; this.toggleInvalidEmailWarning_(inputValue != '' && !goog.editor.Link.isLikelyEmailAddress(inputValue)); } else if (this.tabPane_.getCurrentTabId() == goog.ui.editor.LinkDialog.Id_.ON_WEB_TAB) { inputValue = this.dom.getElement( goog.ui.editor.LinkDialog.Id_.ON_WEB_INPUT).value; } else { return; } this.getOkButtonElement().disabled = goog.string.isEmpty(inputValue); }; /** * Show/hide the Invalid Email Address warning. * @param {boolean} on Whether to show the warning. * @private */ goog.ui.editor.LinkDialog.prototype.toggleInvalidEmailWarning_ = function(on) { this.dom.getElement(goog.ui.editor.LinkDialog.Id_.EMAIL_WARNING) .style.visibility = (on ? 'visible' : 'hidden'); }; /** * Changes the autogenerateTextToDisplay flag so that text to * display stops autogenerating. * @private */ goog.ui.editor.LinkDialog.prototype.onTextToDisplayEdit_ = function() { var inputEmpty = this.textToDisplayInput_.value == ''; if (inputEmpty) { this.setAutogenFlag_(true); } else { this.setAutogenFlagFromCurInput_(); } }; /** * The function called when hitting OK with the "On the web" tab current. * @return {goog.ui.editor.LinkDialog.OkEvent} The event object to be used when * dispatching the OK event to listeners. * @private */ goog.ui.editor.LinkDialog.prototype.createOkEventFromWebTab_ = function() { var input = /** @type {HTMLInputElement} */( this.dom.getElement(goog.ui.editor.LinkDialog.Id_.ON_WEB_INPUT)); var linkURL = input.value; if (goog.editor.Link.isLikelyEmailAddress(linkURL)) { // Make sure that if user types in an e-mail address, it becomes "mailto:". return this.createOkEventFromEmailTab_( goog.ui.editor.LinkDialog.Id_.ON_WEB_INPUT); } else { if (linkURL.search(/:/) < 0) { linkURL = 'http://' + goog.string.trimLeft(linkURL); } return this.createOkEventFromUrl_(linkURL); } }; /** * The function called when hitting OK with the "email address" tab current. * @param {string=} opt_inputId Id of an alternate input to check. * @return {goog.ui.editor.LinkDialog.OkEvent} The event object to be used when * dispatching the OK event to listeners. * @private */ goog.ui.editor.LinkDialog.prototype.createOkEventFromEmailTab_ = function( opt_inputId) { var linkURL = this.dom.getElement( opt_inputId || goog.ui.editor.LinkDialog.Id_.EMAIL_ADDRESS_INPUT).value; linkURL = 'mailto:' + linkURL; return this.createOkEventFromUrl_(linkURL); }; /** * Function to test a link from the on the web tab. * @private */ goog.ui.editor.LinkDialog.prototype.onWebTestLink_ = function() { var input = /** @type {HTMLInputElement} */( this.dom.getElement(goog.ui.editor.LinkDialog.Id_.ON_WEB_INPUT)); var url = input.value; if (url.search(/:/) < 0) { url = 'http://' + goog.string.trimLeft(url); } if (this.dispatchEvent( new goog.ui.editor.LinkDialog.BeforeTestLinkEvent(url))) { var win = this.dom.getWindow(); var size = goog.dom.getViewportSize(win); var openOptions = { target: '_blank', width: Math.max(size.width - 50, 50), height: Math.max(size.height - 50, 50), toolbar: true, scrollbars: true, location: true, statusbar: false, menubar: true, 'resizable': true, 'noreferrer': this.stopReferrerLeaks_ }; goog.window.open(url, openOptions, win); } }; /** * Called whenever the url or email input is edited. If the text to display * matches the text to display, turn on auto. Otherwise if auto is on, update * the text to display based on the url. * @private */ goog.ui.editor.LinkDialog.prototype.onUrlOrEmailInputChange_ = function() { if (this.autogenerateTextToDisplay_) { this.setTextToDisplayFromAuto_(); } else if (this.textToDisplayInput_.value == '') { this.setAutogenFlagFromCurInput_(); } this.syncOkButton_(); }; /** * Called when the currently selected tab changes. * @param {goog.events.Event} e The tab change event. * @private */ goog.ui.editor.LinkDialog.prototype.onChangeTab_ = function(e) { var tab = /** @type {goog.ui.Tab} */ (e.target); // Focus on the input field in the selected tab. var input = this.dom.getElement(tab.getId() + goog.ui.editor.LinkDialog.Id_.TAB_INPUT_SUFFIX); goog.editor.focus.focusInputField(input); // For some reason, IE does not fire onpropertychange events when the width // is specified as a percentage, which breaks the InputHandlers. input.style.width = ''; input.style.width = input.offsetWidth + 'px'; this.syncOkButton_(); this.setTextToDisplayFromAuto_(); }; /** * If autogen is turned on, set the value of text to display based on the * current selection or url. * @private */ goog.ui.editor.LinkDialog.prototype.setTextToDisplayFromAuto_ = function() { if (this.autogenFeatureEnabled_ && this.autogenerateTextToDisplay_) { var inputId = this.tabPane_.getCurrentTabId() + goog.ui.editor.LinkDialog.Id_.TAB_INPUT_SUFFIX; this.textToDisplayInput_.value = /** @type {HTMLInputElement} */(this.dom.getElement(inputId)).value; } }; /** * Turn on the autogenerate text to display flag, and set some sort of indicator * that autogen is on. * @param {boolean} val Boolean value to set autogenerate to. * @private */ goog.ui.editor.LinkDialog.prototype.setAutogenFlag_ = function(val) { // TODO(user): This whole autogen thing is very confusing. It needs // to be refactored and/or explained. this.autogenerateTextToDisplay_ = val; }; /** * Disables autogen so that onUrlOrEmailInputChange_ doesn't act in cases * that are undesirable. * @param {boolean} autogen Boolean value to set disableAutogen to. * @private */ goog.ui.editor.LinkDialog.prototype.disableAutogenFlag_ = function(autogen) { this.setAutogenFlag_(!autogen); this.disableAutogen_ = autogen; }; /** * Creates an OK event from the text to display input and the specified link. * If text to display input is empty, then generate the auto value for it. * @return {goog.ui.editor.LinkDialog.OkEvent} The event object to be used when * dispatching the OK event to listeners. * @param {string} url Url the target element should point to. * @private */ goog.ui.editor.LinkDialog.prototype.createOkEventFromUrl_ = function(url) { // Fill in the text to display input in case it is empty. this.setTextToDisplayFromAuto_(); if (this.showOpenLinkInNewWindow_) { // Save checkbox state for next time. this.isOpenLinkInNewWindowChecked_ = this.openInNewWindowCheckbox_.checked; } return new goog.ui.editor.LinkDialog.OkEvent(this.textToDisplayInput_.value, url, this.showOpenLinkInNewWindow_ && this.isOpenLinkInNewWindowChecked_, this.showRelNoFollow_ && this.relNoFollowCheckbox_.checked); }; /** * If an email or url is being edited, set autogenerate to on if the text to * display matches the url. * @private */ goog.ui.editor.LinkDialog.prototype.setAutogenFlagFromCurInput_ = function() { var autogen = false; if (!this.disableAutogen_) { var tabInput = this.dom.getElement(this.tabPane_.getCurrentTabId() + goog.ui.editor.LinkDialog.Id_.TAB_INPUT_SUFFIX); autogen = (tabInput.value == this.textToDisplayInput_.value); } this.setAutogenFlag_(autogen); }; /** * @return {boolean} Whether the link is new. * @private */ goog.ui.editor.LinkDialog.prototype.isNewLink_ = function() { return this.targetLink_.isNew(); }; /** * IDs for relevant DOM elements. * @enum {string} * @private */ goog.ui.editor.LinkDialog.Id_ = { TEXT_TO_DISPLAY: 'linkdialog-text', ON_WEB_TAB: 'linkdialog-onweb', ON_WEB_INPUT: 'linkdialog-onweb-tab-input', EMAIL_ADDRESS_TAB: 'linkdialog-email', EMAIL_ADDRESS_INPUT: 'linkdialog-email-tab-input', EMAIL_WARNING: 'linkdialog-email-warning', TAB_INPUT_SUFFIX: '-tab-input' }; /** * Base name for the radio buttons group. * @type {string} * @private */ goog.ui.editor.LinkDialog.BUTTON_GROUP_ = 'linkdialog-buttons'; /** * Class name for the url and email input elements. * @type {string} * @private */ goog.ui.editor.LinkDialog.TARGET_INPUT_CLASSNAME_ = goog.getCssName('tr-link-dialog-target-input'); /** * Class name for the email address warning element. * @type {string} * @private */ goog.ui.editor.LinkDialog.EMAIL_WARNING_CLASSNAME_ = goog.getCssName('tr-link-dialog-email-warning'); /** * Class name for the explanation text elements. * @type {string} * @private */ goog.ui.editor.LinkDialog.EXPLANATION_TEXT_CLASSNAME_ = goog.getCssName('tr-link-dialog-explanation-text');
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A class for managing the editor toolbar. * * @author attila@google.com (Attila Bodis) * @author jparent@google.com (Julie Parent) * @see ../../demos/editor/editor.html */ goog.provide('goog.ui.editor.ToolbarController'); goog.require('goog.editor.Field.EventType'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventTarget'); goog.require('goog.ui.Component.EventType'); /** * A class for managing the editor toolbar. Acts as a bridge between * a {@link goog.editor.Field} and a {@link goog.ui.Toolbar}. * * The {@code toolbar} argument must be an instance of {@link goog.ui.Toolbar} * or a subclass. This class doesn't care how the toolbar was created. As * long as one or more controls hosted in the toolbar have IDs that match * built-in {@link goog.editor.Command}s, they will function as expected. It is * the caller's responsibility to ensure that the toolbar is already rendered * or that it decorates an existing element. * * * @param {!goog.editor.Field} field Editable field to be controlled by the * toolbar. * @param {!goog.ui.Toolbar} toolbar Toolbar to control the editable field. * @constructor * @extends {goog.events.EventTarget} */ goog.ui.editor.ToolbarController = function(field, toolbar) { goog.events.EventTarget.call(this); /** * Event handler to listen for field events and user actions. * @type {!goog.events.EventHandler} * @private */ this.handler_ = new goog.events.EventHandler(this); /** * The field instance controlled by the toolbar. * @type {!goog.editor.Field} * @private */ this.field_ = field; /** * The toolbar that controls the field. * @type {!goog.ui.Toolbar} * @private */ this.toolbar_ = toolbar; /** * Editing commands whose state is to be queried when updating the toolbar. * @type {!Array.<string>} * @private */ this.queryCommands_ = []; // Iterate over all buttons, and find those which correspond to // queryable commands. Add them to the list of commands to query on // each COMMAND_VALUE_CHANGE event. this.toolbar_.forEachChild(function(button) { if (button.queryable) { this.queryCommands_.push(this.getComponentId(button.getId())); } }, this); // Make sure the toolbar doesn't steal keyboard focus. this.toolbar_.setFocusable(false); // Hook up handlers that update the toolbar in response to field events, // and to execute editor commands in response to toolbar events. this.handler_. listen(this.field_, goog.editor.Field.EventType.COMMAND_VALUE_CHANGE, this.updateToolbar). listen(this.toolbar_, goog.ui.Component.EventType.ACTION, this.handleAction); }; goog.inherits(goog.ui.editor.ToolbarController, goog.events.EventTarget); /** * Returns the Closure component ID of the control that corresponds to the * given {@link goog.editor.Command} constant. * Subclasses may override this method if they want to use a custom mapping * scheme from commands to controls. * @param {string} command Editor command. * @return {string} Closure component ID of the corresponding toolbar * control, if any. * @protected */ goog.ui.editor.ToolbarController.prototype.getComponentId = function(command) { // The default implementation assumes that the component ID is the same as // the command constant. return command; }; /** * Returns the {@link goog.editor.Command} constant * that corresponds to the given Closure component ID. Subclasses may override * this method if they want to use a custom mapping scheme from controls to * commands. * @param {string} id Closure component ID of a toolbar control. * @return {string} Editor command or dialog constant corresponding to the * toolbar control, if any. * @protected */ goog.ui.editor.ToolbarController.prototype.getCommand = function(id) { // The default implementation assumes that the component ID is the same as // the command constant. return id; }; /** * Returns the event handler object for the editor toolbar. Useful for classes * that extend {@code goog.ui.editor.ToolbarController}. * @return {!goog.events.EventHandler} The event handler object. * @protected */ goog.ui.editor.ToolbarController.prototype.getHandler = function() { return this.handler_; }; /** * Returns the field instance managed by the toolbar. Useful for * classes that extend {@code goog.ui.editor.ToolbarController}. * @return {!goog.editor.Field} The field managed by the toolbar. * @protected */ goog.ui.editor.ToolbarController.prototype.getField = function() { return this.field_; }; /** * Returns the toolbar UI component that manages the editor. Useful for * classes that extend {@code goog.ui.editor.ToolbarController}. * @return {!goog.ui.Toolbar} The toolbar UI component. */ goog.ui.editor.ToolbarController.prototype.getToolbar = function() { return this.toolbar_; }; /** * @return {boolean} Whether the toolbar is visible. */ goog.ui.editor.ToolbarController.prototype.isVisible = function() { return this.toolbar_.isVisible(); }; /** * Shows or hides the toolbar. * @param {boolean} visible Whether to show or hide the toolbar. */ goog.ui.editor.ToolbarController.prototype.setVisible = function(visible) { this.toolbar_.setVisible(visible); }; /** * @return {boolean} Whether the toolbar is enabled. */ goog.ui.editor.ToolbarController.prototype.isEnabled = function() { return this.toolbar_.isEnabled(); }; /** * Enables or disables the toolbar. * @param {boolean} enabled Whether to enable or disable the toolbar. */ goog.ui.editor.ToolbarController.prototype.setEnabled = function(enabled) { this.toolbar_.setEnabled(enabled); }; /** * Programmatically blurs the editor toolbar, un-highlighting the currently * highlighted item, and closing the currently open menu (if any). */ goog.ui.editor.ToolbarController.prototype.blur = function() { // We can't just call this.toolbar_.getElement().blur(), because the toolbar // element itself isn't focusable, so goog.ui.Container#handleBlur isn't // registered to handle blur events. this.toolbar_.handleBlur(null); }; /** @override */ goog.ui.editor.ToolbarController.prototype.disposeInternal = function() { goog.ui.editor.ToolbarController.superClass_.disposeInternal.call(this); if (this.handler_) { this.handler_.dispose(); delete this.handler_; } if (this.toolbar_) { this.toolbar_.dispose(); delete this.toolbar_; } delete this.field_; delete this.queryCommands_; }; /** * Updates the toolbar in response to editor events. Specifically, updates * button states based on {@code COMMAND_VALUE_CHANGE} events, reflecting the * effective formatting of the selection. * @param {goog.events.Event} e Editor event to handle. * @protected */ goog.ui.editor.ToolbarController.prototype.updateToolbar = function(e) { if (!this.toolbar_.isEnabled() || !this.dispatchEvent(goog.ui.Component.EventType.CHANGE)) { return; } var state; /** @preserveTry */ try { /** @type {Array.<string>} */ e.commands; // Added by dispatchEvent. // If the COMMAND_VALUE_CHANGE event specifies which commands changed // state, then we only need to update those ones, otherwise update all // commands. state = /** @type {Object} */ ( this.field_.queryCommandValue(e.commands || this.queryCommands_)); } catch (ex) { // TODO(attila): Find out when/why this happens. state = {}; } this.updateToolbarFromState(state); }; /** * Updates the toolbar to reflect a given state. * @param {Object} state Object mapping editor commands to values. */ goog.ui.editor.ToolbarController.prototype.updateToolbarFromState = function(state) { for (var command in state) { var button = this.toolbar_.getChild(this.getComponentId(command)); if (button) { var value = state[command]; if (button.updateFromValue) { button.updateFromValue(value); } else { button.setChecked(!!value); } } } }; /** * Handles {@code ACTION} events dispatched by toolbar buttons in response to * user actions by executing the corresponding field command. * @param {goog.events.Event} e Action event to handle. * @protected */ goog.ui.editor.ToolbarController.prototype.handleAction = function(e) { var command = this.getCommand(e.target.getId()); this.field_.execCommand(command, e.target.getValue()); };
JavaScript
// Copyright 2011 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('goog.ui.editor.EquationEditorOkEvent'); goog.require('goog.events.Event'); goog.require('goog.ui.editor.AbstractDialog'); /** * OK event object for the equation editor dialog. * @param {string} equationHtml html containing the equation to put in the * editable field. * @constructor * @extends {goog.events.Event} */ goog.ui.editor.EquationEditorOkEvent = function(equationHtml) { this.equationHtml = equationHtml; }; goog.inherits(goog.ui.editor.EquationEditorOkEvent, goog.events.Event); /** * Event type. * @type {goog.ui.editor.AbstractDialog.EventType} * @override */ goog.ui.editor.EquationEditorOkEvent.prototype.type = goog.ui.editor.AbstractDialog.EventType.OK; /** * HTML containing the equation to put in the editable field. * @type {string} */ goog.ui.editor.EquationEditorOkEvent.prototype.equationHtml;
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Generic factory functions for creating the building blocks for * an editor toolbar. * * @author attila@google.com (Attila Bodis) * @author jparent@google.com (Julie Parent) */ goog.provide('goog.ui.editor.ToolbarFactory'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.string'); goog.require('goog.string.Unicode'); goog.require('goog.style'); goog.require('goog.ui.Component.State'); goog.require('goog.ui.Container.Orientation'); goog.require('goog.ui.ControlContent'); goog.require('goog.ui.Option'); goog.require('goog.ui.Toolbar'); goog.require('goog.ui.ToolbarButton'); goog.require('goog.ui.ToolbarColorMenuButton'); goog.require('goog.ui.ToolbarMenuButton'); goog.require('goog.ui.ToolbarRenderer'); goog.require('goog.ui.ToolbarSelect'); goog.require('goog.userAgent'); /** * Takes a font spec (e.g. "Arial, Helvetica, sans-serif") and returns the * primary font name, normalized to lowercase (e.g. "arial"). * @param {string} fontSpec Font specification. * @return {string} The primary font name, in lowercase. */ goog.ui.editor.ToolbarFactory.getPrimaryFont = function(fontSpec) { var i = fontSpec.indexOf(','); var fontName = (i != -1 ? fontSpec.substring(0, i) : fontSpec).toLowerCase(); // Strip leading/trailing quotes from the font name (bug 1050118). return goog.string.stripQuotes(fontName, '"\''); }; /** * Bulk-adds fonts to the given font menu button. The argument must be an * array of font descriptor objects, each of which must have the following * attributes: * <ul> * <li>{@code caption} - Caption to show in the font menu (e.g. 'Tahoma') * <li>{@code value} - Value for the corresponding 'font-family' CSS style * (e.g. 'Tahoma, Arial, sans-serif') * </ul> * @param {!goog.ui.Select} button Font menu button. * @param {!Array.<{caption: string, value: string}>} fonts Array of * font descriptors. */ goog.ui.editor.ToolbarFactory.addFonts = function(button, fonts) { goog.array.forEach(fonts, function(font) { goog.ui.editor.ToolbarFactory.addFont(button, font.caption, font.value); }); }; /** * Adds a menu item to the given font menu button. The first font listed in * the {@code value} argument is considered the font ID, so adding two items * whose CSS style starts with the same font may lead to unpredictable results. * @param {!goog.ui.Select} button Font menu button. * @param {string} caption Caption to show for the font menu. * @param {string} value Value for the corresponding 'font-family' CSS style. */ goog.ui.editor.ToolbarFactory.addFont = function(button, caption, value) { // The font ID is the first font listed in the CSS style, normalized to // lowercase. var id = goog.ui.editor.ToolbarFactory.getPrimaryFont(value); // Construct the option, and add it to the button. var option = new goog.ui.Option(caption, value, button.getDomHelper()); option.setId(id); button.addItem(option); // Captions are shown in their own font. option.getContentElement().style.fontFamily = value; }; /** * Bulk-adds font sizes to the given font size menu button. The argument must * be an array of font size descriptor objects, each of which must have the * following attributes: * <ul> * <li>{@code caption} - Caption to show in the font size menu (e.g. 'Huge') * <li>{@code value} - Value for the corresponding HTML font size (e.g. 6) * </ul> * @param {!goog.ui.Select} button Font size menu button. * @param {!Array.<{caption: string, value:number}>} sizes Array of font * size descriptors. */ goog.ui.editor.ToolbarFactory.addFontSizes = function(button, sizes) { goog.array.forEach(sizes, function(size) { goog.ui.editor.ToolbarFactory.addFontSize(button, size.caption, size.value); }); }; /** * Adds a menu item to the given font size menu button. The {@code value} * argument must be a legacy HTML font size in the 0-7 range. * @param {!goog.ui.Select} button Font size menu button. * @param {string} caption Caption to show in the font size menu. * @param {number} value Value for the corresponding HTML font size. */ goog.ui.editor.ToolbarFactory.addFontSize = function(button, caption, value) { // Construct the option, and add it to the button. var option = new goog.ui.Option(caption, value, button.getDomHelper()); button.addItem(option); // Adjust the font size of the menu item and the height of the checkbox // element after they've been rendered by addItem(). Captions are shown in // the corresponding font size, and lining up the checkbox is tricky. var content = option.getContentElement(); content.style.fontSize = goog.ui.editor.ToolbarFactory.getPxFromLegacySize(value) + 'px'; content.firstChild.style.height = '1.1em'; }; /** * Converts a legacy font size specification into an equivalent pixel size. * For example, {@code &lt;font size="6"&gt;} is {@code font-size: 32px;}, etc. * @param {number} fontSize Legacy font size spec in the 0-7 range. * @return {number} Equivalent pixel size. */ goog.ui.editor.ToolbarFactory.getPxFromLegacySize = function(fontSize) { return goog.ui.editor.ToolbarFactory.LEGACY_SIZE_TO_PX_MAP_[fontSize] || 10; }; /** * Converts a pixel font size specification into an equivalent legacy size. * For example, {@code font-size: 32px;} is {@code &lt;font size="6"&gt;}, etc. * If the given pixel size doesn't exactly match one of the legacy sizes, -1 is * returned. * @param {number} px Pixel font size. * @return {number} Equivalent legacy size spec in the 0-7 range, or -1 if none * exists. */ goog.ui.editor.ToolbarFactory.getLegacySizeFromPx = function(px) { // Use lastIndexOf to get the largest legacy size matching the pixel size // (most notably returning 1 instead of 0 for 10px). return goog.array.lastIndexOf( goog.ui.editor.ToolbarFactory.LEGACY_SIZE_TO_PX_MAP_, px); }; /** * Map of legacy font sizes (0-7) to equivalent pixel sizes. * @type {Array.<number>} * @private */ goog.ui.editor.ToolbarFactory.LEGACY_SIZE_TO_PX_MAP_ = [10, 10, 13, 16, 18, 24, 32, 48]; /** * Bulk-adds format options to the given "Format block" menu button. The * argument must be an array of format option descriptor objects, each of * which must have the following attributes: * <ul> * <li>{@code caption} - Caption to show in the menu (e.g. 'Minor heading') * <li>{@code command} - Corresponding {@link goog.dom.TagName} (e.g. * 'H4') * </ul> * @param {!goog.ui.Select} button "Format block" menu button. * @param {!Array.<{caption: string, command: goog.dom.TagName}>} formats Array * of format option descriptors. */ goog.ui.editor.ToolbarFactory.addFormatOptions = function(button, formats) { goog.array.forEach(formats, function(format) { goog.ui.editor.ToolbarFactory.addFormatOption(button, format.caption, format.command); }); }; /** * Adds a menu item to the given "Format block" menu button. * @param {!goog.ui.Select} button "Format block" menu button. * @param {string} caption Caption to show in the menu. * @param {goog.dom.TagName} tag Corresponding block format tag. */ goog.ui.editor.ToolbarFactory.addFormatOption = function(button, caption, tag) { // Construct the option, and add it to the button. // TODO(attila): Create boring but functional menu item for now... var buttonDom = button.getDomHelper(); var option = new goog.ui.Option(buttonDom.createDom(goog.dom.TagName.DIV, null, caption), tag, buttonDom); option.setId(tag); button.addItem(option); }; /** * Creates a {@link goog.ui.Toolbar} containing the specified set of * toolbar buttons, and renders it into the given parent element. Each * item in the {@code items} array must a {@link goog.ui.Control}. * @param {!Array.<goog.ui.Control>} items Toolbar items; each must * be a {@link goog.ui.Control}. * @param {!Element} elem Toolbar parent element. * @param {boolean=} opt_isRightToLeft Whether the editor chrome is * right-to-left; defaults to the directionality of the toolbar parent * element. * @return {!goog.ui.Toolbar} Editor toolbar, rendered into the given parent * element. */ goog.ui.editor.ToolbarFactory.makeToolbar = function(items, elem, opt_isRightToLeft) { var domHelper = goog.dom.getDomHelper(elem); // Create an empty horizontal toolbar using the default renderer. var toolbar = new goog.ui.Toolbar(goog.ui.ToolbarRenderer.getInstance(), goog.ui.Container.Orientation.HORIZONTAL, domHelper); // Optimization: Explicitly test for the directionality of the parent // element here, so we can set it for both the toolbar and its children, // saving a lot of expensive calls to goog.style.isRightToLeft() during // rendering. var isRightToLeft = opt_isRightToLeft || goog.style.isRightToLeft(elem); toolbar.setRightToLeft(isRightToLeft); // Optimization: Set the toolbar to non-focusable before it is rendered, // to avoid creating unnecessary keyboard event handler objects. toolbar.setFocusable(false); for (var i = 0, button; button = items[i]; i++) { // Optimization: Set the button to non-focusable before it is rendered, // to avoid creating unnecessary keyboard event handler objects. Also set // the directionality of the button explicitly, to avoid expensive calls // to goog.style.isRightToLeft() during rendering. button.setSupportedState(goog.ui.Component.State.FOCUSED, false); button.setRightToLeft(isRightToLeft); toolbar.addChild(button, true); } toolbar.render(elem); return toolbar; }; /** * Creates a toolbar button with the given ID, tooltip, and caption. Applies * any custom CSS class names to the button's caption element. * @param {string} id Button ID; must equal a {@link goog.editor.Command} for * built-in buttons, anything else for custom buttons. * @param {string} tooltip Tooltip to be shown on hover. * @param {goog.ui.ControlContent} caption Button caption. * @param {string=} opt_classNames CSS class name(s) to apply to the caption * element. * @param {goog.ui.ButtonRenderer=} opt_renderer Button renderer; defaults to * {@link goog.ui.ToolbarButtonRenderer} if unspecified. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {!goog.ui.Button} A toolbar button. */ goog.ui.editor.ToolbarFactory.makeButton = function(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper) { var button = new goog.ui.ToolbarButton( goog.ui.editor.ToolbarFactory.createContent_(caption, opt_classNames, opt_domHelper), opt_renderer, opt_domHelper); button.setId(id); button.setTooltip(tooltip); return button; }; /** * Creates a toggle button with the given ID, tooltip, and caption. Applies * any custom CSS class names to the button's caption element. The button * returned has checkbox-like toggle semantics. * @param {string} id Button ID; must equal a {@link goog.editor.Command} for * built-in buttons, anything else for custom buttons. * @param {string} tooltip Tooltip to be shown on hover. * @param {goog.ui.ControlContent} caption Button caption. * @param {string=} opt_classNames CSS class name(s) to apply to the caption * element. * @param {goog.ui.ButtonRenderer=} opt_renderer Button renderer; defaults to * {@link goog.ui.ToolbarButtonRenderer} if unspecified. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {!goog.ui.Button} A toggle button. */ goog.ui.editor.ToolbarFactory.makeToggleButton = function(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper) { var button = goog.ui.editor.ToolbarFactory.makeButton(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper); button.setSupportedState(goog.ui.Component.State.CHECKED, true); return button; }; /** * Creates a menu button with the given ID, tooltip, and caption. Applies * any custom CSS class names to the button's caption element. The button * returned doesn't have an actual menu attached; use {@link * goog.ui.MenuButton#setMenu} to attach a {@link goog.ui.Menu} to the * button. * @param {string} id Button ID; must equal a {@link goog.editor.Command} for * built-in buttons, anything else for custom buttons. * @param {string} tooltip Tooltip to be shown on hover. * @param {goog.ui.ControlContent} caption Button caption. * @param {string=} opt_classNames CSS class name(s) to apply to the caption * element. * @param {goog.ui.ButtonRenderer=} opt_renderer Button renderer; defaults to * {@link goog.ui.ToolbarMenuButtonRenderer} if unspecified. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {!goog.ui.MenuButton} A menu button. */ goog.ui.editor.ToolbarFactory.makeMenuButton = function(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper) { var button = new goog.ui.ToolbarMenuButton( goog.ui.editor.ToolbarFactory.createContent_(caption, opt_classNames, opt_domHelper), null, opt_renderer, opt_domHelper); button.setId(id); button.setTooltip(tooltip); return button; }; /** * Creates a select button with the given ID, tooltip, and caption. Applies * any custom CSS class names to the button's root element. The button * returned doesn't have an actual menu attached; use {@link * goog.ui.Select#setMenu} to attach a {@link goog.ui.Menu} containing * {@link goog.ui.Option}s to the select button. * @param {string} id Button ID; must equal a {@link goog.editor.Command} for * built-in buttons, anything else for custom buttons. * @param {string} tooltip Tooltip to be shown on hover. * @param {goog.ui.ControlContent} caption Button caption; used as the * default caption when nothing is selected. * @param {string=} opt_classNames CSS class name(s) to apply to the button's * root element. * @param {goog.ui.MenuButtonRenderer=} opt_renderer Button renderer; * defaults to {@link goog.ui.ToolbarMenuButtonRenderer} if unspecified. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {!goog.ui.Select} A select button. */ goog.ui.editor.ToolbarFactory.makeSelectButton = function(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper) { var button = new goog.ui.ToolbarSelect(null, null, opt_renderer, opt_domHelper); if (opt_classNames) { // Unlike the other button types, for goog.ui.Select buttons we apply the // extra class names to the root element, because for select buttons the // caption isn't stable (as it changes each time the selection changes). goog.array.forEach(opt_classNames.split(/\s+/), button.addClassName, button); } button.addClassName(goog.getCssName('goog-toolbar-select')); button.setDefaultCaption(caption); button.setId(id); button.setTooltip(tooltip); return button; }; /** * Creates a color menu button with the given ID, tooltip, and caption. * Applies any custom CSS class names to the button's caption element. The * button is created with a default color menu containing standard color * palettes. * @param {string} id Button ID; must equal a {@link goog.editor.Command} for * built-in toolbar buttons, but can be anything else for custom buttons. * @param {string} tooltip Tooltip to be shown on hover. * @param {goog.ui.ControlContent} caption Button caption. * @param {string=} opt_classNames CSS class name(s) to apply to the caption * element. * @param {goog.ui.ColorMenuButtonRenderer=} opt_renderer Button renderer; * defaults to {@link goog.ui.ToolbarColorMenuButtonRenderer} * if unspecified. * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {!goog.ui.ColorMenuButton} A color menu button. */ goog.ui.editor.ToolbarFactory.makeColorMenuButton = function(id, tooltip, caption, opt_classNames, opt_renderer, opt_domHelper) { var button = new goog.ui.ToolbarColorMenuButton( goog.ui.editor.ToolbarFactory.createContent_(caption, opt_classNames, opt_domHelper), null, opt_renderer, opt_domHelper); button.setId(id); button.setTooltip(tooltip); return button; }; /** * Creates a new DIV that wraps a button caption, optionally applying CSS * class names to it. Used as a helper function in button factory methods. * @param {goog.ui.ControlContent} caption Button caption. * @param {string=} opt_classNames CSS class name(s) to apply to the DIV that * wraps the caption (if any). * @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for DOM * creation; defaults to the current document if unspecified. * @return {!Element} DIV that wraps the caption. * @private */ goog.ui.editor.ToolbarFactory.createContent_ = function(caption, opt_classNames, opt_domHelper) { // FF2 doesn't like empty DIVs, especially when rendered right-to-left. if ((!caption || caption == '') && goog.userAgent.GECKO && !goog.userAgent.isVersion('1.9a')) { caption = goog.string.Unicode.NBSP; } return (opt_domHelper || goog.dom.getDomHelper()).createDom( goog.dom.TagName.DIV, opt_classNames ? {'class' : opt_classNames} : null, caption); };
JavaScript
// Copyright 2005 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Bubble component - handles display, hiding, etc. of the * actual bubble UI. * * This is used exclusively by code within the editor package, and should not * be used directly. * * @author robbyw@google.com (Robby Walker) * @author tildahl@google.com (Michael Tildahl) */ goog.provide('goog.ui.editor.Bubble'); goog.require('goog.debug.Logger'); goog.require('goog.dom'); goog.require('goog.dom.ViewportSizeMonitor'); goog.require('goog.editor.style'); goog.require('goog.events'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventType'); goog.require('goog.math.Box'); goog.require('goog.positioning'); goog.require('goog.string'); goog.require('goog.style'); goog.require('goog.ui.Component.EventType'); goog.require('goog.ui.PopupBase'); goog.require('goog.ui.PopupBase.EventType'); goog.require('goog.userAgent'); /** * Property bubble UI element. * @param {Element} parent The parent element for this bubble. * @param {number} zIndex The z index to draw the bubble at. * @constructor * @extends {goog.events.EventTarget} */ goog.ui.editor.Bubble = function(parent, zIndex) { goog.base(this); /** * Dom helper for the document the bubble should be shown in. * @type {!goog.dom.DomHelper} * @private */ this.dom_ = goog.dom.getDomHelper(parent); /** * Event handler for this bubble. * @type {goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); /** * Object that monitors the application window for size changes. * @type {goog.dom.ViewportSizeMonitor} * @private */ this.viewPortSizeMonitor_ = new goog.dom.ViewportSizeMonitor( this.dom_.getWindow()); /** * Maps panel ids to panels. * @type {Object.<goog.ui.editor.Bubble.Panel_>} * @private */ this.panels_ = {}; /** * Container element for the entire bubble. This may contain elements related * to look and feel or styling of the bubble. * @type {Element} * @private */ this.bubbleContainer_ = this.dom_.createDom(goog.dom.TagName.DIV, {'className': goog.ui.editor.Bubble.BUBBLE_CLASSNAME}); goog.style.setElementShown(this.bubbleContainer_, false); goog.dom.appendChild(parent, this.bubbleContainer_); goog.style.setStyle(this.bubbleContainer_, 'zIndex', zIndex); /** * Container element for the bubble panels - this should be some inner element * within (or equal to) bubbleContainer. * @type {Element} * @private */ this.bubbleContents_ = this.createBubbleDom(this.dom_, this.bubbleContainer_); /** * Element showing the close box. * @type {!Element} * @private */ this.closeBox_ = this.dom_.createDom(goog.dom.TagName.DIV, { 'className': goog.getCssName('tr_bubble_closebox'), 'innerHTML': '&nbsp;' }); this.bubbleContents_.appendChild(this.closeBox_); // We make bubbles unselectable so that clicking on them does not steal focus // or move the cursor away from the element the bubble is attached to. goog.editor.style.makeUnselectable(this.bubbleContainer_, this.eventHandler_); /** * Popup that controls showing and hiding the bubble at the appropriate * position. * @type {goog.ui.PopupBase} * @private */ this.popup_ = new goog.ui.PopupBase(this.bubbleContainer_); }; goog.inherits(goog.ui.editor.Bubble, goog.events.EventTarget); /** * The css class name of the bubble container element. * @type {string} */ goog.ui.editor.Bubble.BUBBLE_CLASSNAME = goog.getCssName('tr_bubble'); /** * Creates and adds DOM for the bubble UI to the given container. This default * implementation just returns the container itself. * @param {!goog.dom.DomHelper} dom DOM helper to use. * @param {!Element} container Element to add the new elements to. * @return {!Element} The element where bubble content should be added. * @protected */ goog.ui.editor.Bubble.prototype.createBubbleDom = function(dom, container) { return container; }; /** * A logger for goog.ui.editor.Bubble. * @type {goog.debug.Logger} * @protected */ goog.ui.editor.Bubble.prototype.logger = goog.debug.Logger.getLogger('goog.ui.editor.Bubble'); /** @override */ goog.ui.editor.Bubble.prototype.disposeInternal = function() { goog.base(this, 'disposeInternal'); goog.dom.removeNode(this.bubbleContainer_); this.bubbleContainer_ = null; this.eventHandler_.dispose(); this.eventHandler_ = null; this.viewPortSizeMonitor_.dispose(); this.viewPortSizeMonitor_ = null; }; /** * @return {Element} The element that where the bubble's contents go. */ goog.ui.editor.Bubble.prototype.getContentElement = function() { return this.bubbleContents_; }; /** * @return {Element} The element that contains the bubble. * @protected */ goog.ui.editor.Bubble.prototype.getContainerElement = function() { return this.bubbleContainer_; }; /** * @return {goog.events.EventHandler} The event handler. * @protected */ goog.ui.editor.Bubble.prototype.getEventHandler = function() { return this.eventHandler_; }; /** * Handles user resizing of window. * @private */ goog.ui.editor.Bubble.prototype.handleWindowResize_ = function() { if (this.isVisible()) { this.reposition(); } }; /** * Returns whether there is already a panel of the given type. * @param {string} type Type of panel to check. * @return {boolean} Whether there is already a panel of the given type. */ goog.ui.editor.Bubble.prototype.hasPanelOfType = function(type) { return goog.object.some(this.panels_, function(panel) { return panel.type == type; }); }; /** * Adds a panel to the bubble. * @param {string} type The type of bubble panel this is. Should usually be * the same as the tagName of the targetElement. This ensures multiple * bubble panels don't appear for the same element. * @param {string} title The title of the panel. * @param {Element} targetElement The target element of the bubble. * @param {function(Element): void} contentFn Function that when called with * a container element, will add relevant panel content to it. * @param {boolean=} opt_preferTopPosition Whether to prefer placing the bubble * above the element instead of below it. Defaults to preferring below. * If any panel prefers the top position, the top position is used. * @return {string} The id of the panel. */ goog.ui.editor.Bubble.prototype.addPanel = function(type, title, targetElement, contentFn, opt_preferTopPosition) { var id = goog.string.createUniqueString(); var panel = new goog.ui.editor.Bubble.Panel_(this.dom_, id, type, title, targetElement, !opt_preferTopPosition); this.panels_[id] = panel; // Insert the panel in string order of type. Technically we could use binary // search here but n is really small (probably 0 - 2) so it's not worth it. // The last child of bubbleContents_ is the close box so we take care not // to treat it as a panel element, and we also ensure it stays as the last // element. The intention here is not to create any artificial order, but // just to ensure that it is always consistent. var nextElement; for (var i = 0, len = this.bubbleContents_.childNodes.length - 1; i < len; i++) { var otherChild = this.bubbleContents_.childNodes[i]; var otherPanel = this.panels_[otherChild.id]; if (otherPanel.type > type) { nextElement = otherChild; break; } } goog.dom.insertSiblingBefore(panel.element, nextElement || this.bubbleContents_.lastChild); contentFn(panel.getContentElement()); goog.editor.style.makeUnselectable(panel.element, this.eventHandler_); var numPanels = goog.object.getCount(this.panels_); if (numPanels == 1) { this.openBubble_(); } else if (numPanels == 2) { goog.dom.classes.add(this.bubbleContainer_, goog.getCssName('tr_multi_bubble')); } this.reposition(); return id; }; /** * Removes the panel with the given id. * @param {string} id The id of the panel. */ goog.ui.editor.Bubble.prototype.removePanel = function(id) { var panel = this.panels_[id]; goog.dom.removeNode(panel.element); delete this.panels_[id]; var numPanels = goog.object.getCount(this.panels_); if (numPanels <= 1) { goog.dom.classes.remove(this.bubbleContainer_, goog.getCssName('tr_multi_bubble')); } if (numPanels == 0) { this.closeBubble_(); } else { this.reposition(); } }; /** * Opens the bubble. * @private */ goog.ui.editor.Bubble.prototype.openBubble_ = function() { this.eventHandler_. listen(this.closeBox_, goog.events.EventType.CLICK, this.closeBubble_). listen(this.viewPortSizeMonitor_, goog.events.EventType.RESIZE, this.handleWindowResize_). listen(this.popup_, goog.ui.PopupBase.EventType.HIDE, this.handlePopupHide); this.popup_.setVisible(true); this.reposition(); }; /** * Closes the bubble. * @private */ goog.ui.editor.Bubble.prototype.closeBubble_ = function() { this.popup_.setVisible(false); }; /** * Handles the popup's hide event by removing all panels and dispatching a * HIDE event. * @protected */ goog.ui.editor.Bubble.prototype.handlePopupHide = function() { // Remove the panel elements. for (var panelId in this.panels_) { goog.dom.removeNode(this.panels_[panelId].element); } // Update the state to reflect no panels. this.panels_ = {}; goog.dom.classes.remove(this.bubbleContainer_, goog.getCssName('tr_multi_bubble')); this.eventHandler_.removeAll(); this.dispatchEvent(goog.ui.Component.EventType.HIDE); }; /** * Returns the visibility of the bubble. * @return {boolean} True if visible false if not. */ goog.ui.editor.Bubble.prototype.isVisible = function() { return this.popup_.isVisible(); }; /** * The vertical clearance in pixels between the bottom of the targetElement * and the edge of the bubble. * @type {number} * @private */ goog.ui.editor.Bubble.VERTICAL_CLEARANCE_ = goog.userAgent.IE ? 4 : 2; /** * Bubble's margin box to be passed to goog.positioning. * @type {goog.math.Box} * @private */ goog.ui.editor.Bubble.MARGIN_BOX_ = new goog.math.Box( goog.ui.editor.Bubble.VERTICAL_CLEARANCE_, 0, goog.ui.editor.Bubble.VERTICAL_CLEARANCE_, 0); /** * Positions and displays this bubble below its targetElement. Assumes that * the bubbleContainer is already contained in the document object it applies * to. */ goog.ui.editor.Bubble.prototype.reposition = function() { var targetElement = null; var preferBottomPosition = true; for (var panelId in this.panels_) { var panel = this.panels_[panelId]; // We don't care which targetElement we get, so we just take the last one. targetElement = panel.targetElement; preferBottomPosition = preferBottomPosition && panel.preferBottomPosition; } var status = goog.positioning.OverflowStatus.FAILED; // Fix for bug when bubbleContainer and targetElement have // opposite directionality, the bubble should anchor to the END of // the targetElement instead of START. var reverseLayout = (goog.style.isRightToLeft(this.bubbleContainer_) != goog.style.isRightToLeft(targetElement)); // Try to put the bubble at the bottom of the target unless the plugin has // requested otherwise. if (preferBottomPosition) { status = this.positionAtAnchor_(reverseLayout ? goog.positioning.Corner.BOTTOM_END : goog.positioning.Corner.BOTTOM_START, goog.positioning.Corner.TOP_START, goog.positioning.Overflow.ADJUST_X | goog.positioning.Overflow.FAIL_Y); } if (status & goog.positioning.OverflowStatus.FAILED) { // Try to put it at the top of the target if there is not enough // space at the bottom. status = this.positionAtAnchor_(reverseLayout ? goog.positioning.Corner.TOP_END : goog.positioning.Corner.TOP_START, goog.positioning.Corner.BOTTOM_START, goog.positioning.Overflow.ADJUST_X | goog.positioning.Overflow.FAIL_Y); } if (status & goog.positioning.OverflowStatus.FAILED) { // Put it at the bottom again with adjustment if there is no // enough space at the top. status = this.positionAtAnchor_(reverseLayout ? goog.positioning.Corner.BOTTOM_END : goog.positioning.Corner.BOTTOM_START, goog.positioning.Corner.TOP_START, goog.positioning.Overflow.ADJUST_X | goog.positioning.Overflow.ADJUST_Y); if (status & goog.positioning.OverflowStatus.FAILED) { this.logger.warning( 'reposition(): positionAtAnchor() failed with ' + status); } } }; /** * A helper for reposition() - positions the bubble in regards to the position * of the elements the bubble is attached to. * @param {goog.positioning.Corner} targetCorner The corner of * the target element. * @param {goog.positioning.Corner} bubbleCorner The corner of the bubble. * @param {number} overflow Overflow handling mode bitmap, * {@see goog.positioning.Overflow}. * @return {number} Status bitmap, {@see goog.positioning.OverflowStatus}. * @private */ goog.ui.editor.Bubble.prototype.positionAtAnchor_ = function( targetCorner, bubbleCorner, overflow) { var targetElement = null; for (var panelId in this.panels_) { // For now, we use the outermost element. This assumes the multiple // elements this panel is showing for contain each other - in the event // that is not generally the case this may need to be updated to pick // the lowest or highest element depending on targetCorner. var candidate = this.panels_[panelId].targetElement; if (!targetElement || goog.dom.contains(candidate, targetElement)) { targetElement = this.panels_[panelId].targetElement; } } return goog.positioning.positionAtAnchor( targetElement, targetCorner, this.bubbleContainer_, bubbleCorner, null, goog.ui.editor.Bubble.MARGIN_BOX_, overflow); }; /** * Private class used to describe a bubble panel. * @param {goog.dom.DomHelper} dom DOM helper used to create the panel. * @param {string} id ID of the panel. * @param {string} type Type of the panel. * @param {string} title Title of the panel. * @param {Element} targetElement Element the panel is showing for. * @param {boolean} preferBottomPosition Whether this panel prefers to show * below the target element. * @constructor * @private */ goog.ui.editor.Bubble.Panel_ = function(dom, id, type, title, targetElement, preferBottomPosition) { /** * The type of bubble panel. * @type {string} */ this.type = type; /** * The target element of this bubble panel. * @type {Element} */ this.targetElement = targetElement; /** * Whether the panel prefers to be placed below the target element. * @type {boolean} */ this.preferBottomPosition = preferBottomPosition; /** * The element containing this panel. */ this.element = dom.createDom(goog.dom.TagName.DIV, {className: goog.getCssName('tr_bubble_panel'), id: id}, dom.createDom(goog.dom.TagName.DIV, {className: goog.getCssName('tr_bubble_panel_title')}, title + ':'), // TODO(robbyw): Does this work properly in bidi? dom.createDom(goog.dom.TagName.DIV, {className: goog.getCssName('tr_bubble_panel_content')})); }; /** * @return {Element} The element in the panel where content should go. */ goog.ui.editor.Bubble.Panel_.prototype.getContentElement = function() { return /** @type {Element} */ (this.element.lastChild); };
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Tabbed pane with style and functionality specific to * Editor dialogs. * * @author robbyw@google.com (Robby Walker) */ goog.provide('goog.ui.editor.TabPane'); goog.require('goog.dom.TagName'); goog.require('goog.dom.classes'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventType'); goog.require('goog.style'); goog.require('goog.ui.Component'); goog.require('goog.ui.Control'); goog.require('goog.ui.Tab'); goog.require('goog.ui.TabBar'); /** * Creates a new Editor-style tab pane. * @param {goog.dom.DomHelper} dom The dom helper for the window to create this * tab pane in. * @param {string=} opt_caption Optional caption of the tab pane. * @constructor * @extends {goog.ui.Component} */ goog.ui.editor.TabPane = function(dom, opt_caption) { goog.base(this, dom); /** * The event handler used to register events. * @type {goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); this.registerDisposable(this.eventHandler_); /** * The tab bar used to render the tabs. * @type {goog.ui.TabBar} * @private */ this.tabBar_ = new goog.ui.TabBar(goog.ui.TabBar.Location.START, undefined, this.dom_); this.tabBar_.setFocusable(false); /** * The content element. * @private */ this.tabContent_ = this.dom_.createDom(goog.dom.TagName.DIV, {className: goog.getCssName('goog-tab-content')}); /** * The currently selected radio button. * @type {Element} * @private */ this.selectedRadio_ = null; /** * The currently visible tab content. * @type {Element} * @private */ this.visibleContent_ = null; // Add the caption as the first element in the tab bar. if (opt_caption) { var captionControl = new goog.ui.Control(opt_caption, undefined, this.dom_); captionControl.addClassName(goog.getCssName('tr-tabpane-caption')); captionControl.setEnabled(false); this.tabBar_.addChild(captionControl, true); } }; goog.inherits(goog.ui.editor.TabPane, goog.ui.Component); /** * @return {string} The ID of the content element for the current tab. */ goog.ui.editor.TabPane.prototype.getCurrentTabId = function() { return this.tabBar_.getSelectedTab().getId(); }; /** * Selects the tab with the given id. * @param {string} id Id of the tab to select. */ goog.ui.editor.TabPane.prototype.setSelectedTabId = function(id) { this.tabBar_.setSelectedTab(this.tabBar_.getChild(id)); }; /** * Adds a tab to the tab pane. * @param {string} id The id of the tab to add. * @param {string} caption The caption of the tab. * @param {string} tooltip The tooltip for the tab. * @param {string} groupName for the radio button group. * @param {Element} content The content element to show when this tab is * selected. */ goog.ui.editor.TabPane.prototype.addTab = function(id, caption, tooltip, groupName, content) { var radio = this.dom_.createDom(goog.dom.TagName.INPUT, { name: groupName, type: 'radio' }); var tab = new goog.ui.Tab([radio, this.dom_.createTextNode(caption)], undefined, this.dom_); tab.setId(id); tab.setTooltip(tooltip); this.tabBar_.addChild(tab, true); // When you navigate the radio buttons with TAB and then the Arrow keys on // Chrome and FF, you get a CLICK event on them, and the radio button // is selected. You don't get a SELECT at all. We listen for SELECT // nonetheless because it's possible that some browser will issue only // SELECT. this.eventHandler_.listen(radio, [goog.events.EventType.SELECT, goog.events.EventType.CLICK], goog.bind(this.tabBar_.setSelectedTab, this.tabBar_, tab)); content.id = id + '-tab'; this.tabContent_.appendChild(content); goog.style.setElementShown(content, false); }; /** @override */ goog.ui.editor.TabPane.prototype.enterDocument = function() { goog.base(this, 'enterDocument'); // Get the root element and add a class name to it. var root = this.getElement(); goog.dom.classes.add(root, goog.getCssName('tr-tabpane')); // Add the tabs. this.addChild(this.tabBar_, true); this.eventHandler_.listen(this.tabBar_, goog.ui.Component.EventType.SELECT, this.handleTabSelect_); // Add the tab content. root.appendChild(this.tabContent_); // Add an element to clear the tab float. root.appendChild( this.dom_.createDom(goog.dom.TagName.DIV, {className: goog.getCssName('goog-tab-bar-clear')})); }; /** * Handles a tab change. * @param {goog.events.Event} e The browser change event. * @private */ goog.ui.editor.TabPane.prototype.handleTabSelect_ = function(e) { var tab = /** @type {goog.ui.Tab} */ (e.target); // Show the tab content. if (this.visibleContent_) { goog.style.setElementShown(this.visibleContent_, false); } this.visibleContent_ = this.dom_.getElement(tab.getId() + '-tab'); goog.style.setElementShown(this.visibleContent_, true); // Select the appropriate radio button (and deselect the current one). if (this.selectedRadio_) { this.selectedRadio_.checked = false; } this.selectedRadio_ = tab.getElement().getElementsByTagName( goog.dom.TagName.INPUT)[0]; this.selectedRadio_.checked = true; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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.Path'); 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 * @override */ 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). * @override */ 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 * @override */ 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 * @override */ 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; } };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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.base(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_); }; /** * @return {HTMLInputElement} The user input element. May be null if the Prompt * has not been rendered. */ goog.ui.Prompt.prototype.getInputElement = function() { return this.userInputEl_; }; /** * 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. * @override */ 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. * @override */ goog.ui.Prompt.prototype.setVisible = function(visible) { goog.base(this, 'setVisible', 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() { goog.base(this, 'focus'); 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; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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. * @override */ goog.ui.FilteredMenu.prototype.handleKeyEventInternal = 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_.handleKeyEventInternal.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. * @override */ 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_(); };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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. * @override */ 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. * @override */ goog.ui.DrilldownRow.prototype.canDecorate = function(node) { return node.tagName == 'TR'; }; /** * Child drilldowns are rendered when needed. * * @param {goog.ui.Component} child New DrilldownRow child to be added. * @param {number} index position to be occupied by the child. * @param {boolean=} opt_render true to force immediate rendering. * @override */ 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. * @override */ 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;">' + '&nbsp;</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; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Utility for 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), '">'); };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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 {Node} node Node to test. * @return {boolean} Whether or not hovercard should be shown. * @private */ goog.ui.HoverCard.prototype.isAnchor_ = function(node) { return node.tagName in this.anchors_ && !!node.getAttribute(this.anchors_[node.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.setPosition(null); 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. * @override */ 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. * @override */ 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. * @override */ 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);
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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_, 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; };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Definition of the 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. * @override */ 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.setElementShown(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.setElementShown(el, false); } }; /** * 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;
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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.a11y.aria'); goog.require('goog.a11y.aria.State'); 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. * @override */ 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.Control} control goog.ui.DimensionPicker to decorate. * @param {Element} element The element to decorate. * @return {Element} The decorated element. * @override */ goog.ui.DimensionPickerRenderer.prototype.decorate = function(control, element) { var palette = /** @type {goog.ui.DimensionPicker} */ (control); 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'))); }; /** * Creates a div and adds the appropriate contents to it. * @param {goog.ui.Control} control Picker to render. * @return {Element} Root element for the palette. * @override */ goog.ui.DimensionPickerRenderer.prototype.createDom = function(control) { var palette = /** @type {goog.ui.DimensionPicker} */ (control); 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.Control} control Palette whose DOM is to be * initialized as it enters the document. * @override */ goog.ui.DimensionPickerRenderer.prototype.initializeDom = function( control) { var palette = /** @type {goog.ui.DimensionPicker} */ (control); goog.ui.DimensionPickerRenderer.superClass_.initializeDom.call(this, palette); // Make the displayed highlighted size match the dimension picker's value. var highlightedSize = palette.getValue(); this.setHighlightedSize(palette, highlightedSize.width, highlightedSize.height); 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. Does nothing if the palette hasn't been rendered. * @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(); // Can't update anything if DimensionPicker hasn't been rendered. if (!element) { return; } // 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 aria label. /** * @desc The dimension of the columns and rows currently selected in the * dimension picker, as text that can be spoken by a screen reader. */ var MSG_DIMENSION_PICKER_HIGHLIGHTED_DIMENSIONS = goog.getMsg( '{$numCols} by {$numRows}', {'numCols': columns, 'numRows': rows}); goog.a11y.aria.setState(element, goog.a11y.aria.State.LABEL, MSG_DIMENSION_PICKER_HIGHLIGHTED_DIMENSIONS); // 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. * @override */ 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'); } };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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'); 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 {*} value New button value; should be a color spec string. * @override */ goog.ui.ColorMenuButton.prototype.setValue = function(value) { var color = /** @type {?string} */ (value); 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. * @override */ 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); });
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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'); 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); });
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Gauge UI component, using browser vector graphics. * @see ../demos/gauge.html */ goog.provide('goog.ui.Gauge'); goog.provide('goog.ui.GaugeColoredRange'); goog.require('goog.a11y.aria'); goog.require('goog.asserts'); goog.require('goog.dom'); 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; var element = this.getElement(); if (element) { goog.a11y.aria.setState(element, '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; var element = this.getElement(); if (element) { goog.a11y.aria.setState(element, '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); } var element = this.getElement(); if (element) { goog.a11y.aria.setState(element, '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. * @override */ 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); // Move to outer point at "from" angle path.moveTo( cx + goog.math.angleDx(fromAngle, r), cy + goog.math.angleDy(fromAngle, r)); // Arc to outer point at "to" angle path.arcTo(r, r, fromAngle, toAngle - fromAngle); // Line to inner point at "to" angle path.lineTo( cx + goog.math.angleDx(toAngle, rBackgroundInternal), cy + goog.math.angleDy(toAngle, rBackgroundInternal)); // Arc to inner point at "from" angle path.arcTo( rBackgroundInternal, rBackgroundInternal, toAngle, fromAngle - toAngle); 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_(); }; /** @override */ goog.ui.Gauge.prototype.enterDocument = function() { goog.ui.Gauge.superClass_.enterDocument.call(this); // set roles and states var el = this.getElement(); goog.asserts.assert(el, 'The DOM element for the gauge cannot be null.'); goog.a11y.aria.setRole(el, 'progressbar'); goog.a11y.aria.setState(el, 'live', 'polite'); goog.a11y.aria.setState(el, 'valuemin', this.minValue_); goog.a11y.aria.setState(el, 'valuemax', this.maxValue_); goog.a11y.aria.setState(el, 'valuenow', this.value_); this.draw_(); }; /** @override */ 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); };
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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.provide('goog.ui.Textarea.EventType'); 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 helper, 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_; /** * Constants for event names. * @enum {string} */ goog.ui.Textarea.EventType = { RESIZE: 'resize' }; /** * @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 maximum 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() { goog.base(this, 'enterDocument'); 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(); var oldHeight = this.height_; 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_(); } if (oldHeight != this.height_) { this.dispatchEvent(goog.ui.Textarea.EventType.RESIZE); } }; /** * Resizes the textarea 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 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'; } } 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; } };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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_ = {};
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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(); };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A class for representing 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.a11y.aria'); goog.require('goog.asserts'); 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. * @override */ goog.ui.Separator.prototype.enterDocument = function() { goog.ui.Separator.superClass_.enterDocument.call(this); var element = this.getElement(); goog.asserts.assert(element, 'The DOM element for the separator cannot be null.'); goog.a11y.aria.setRole(element, 'separator'); }; // Register a decorator factory function for goog.ui.MenuSeparators. goog.ui.registry.setDecoratorByClassName( goog.ui.MenuSeparatorRenderer.CSS_CLASS, function() { // Separator defaults to using MenuSeparatorRenderer. return new goog.ui.Separator(); });
JavaScript
// Copyright 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); });
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Renderer for {@link goog.ui.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. * @override */ goog.ui.MenuHeaderRenderer.prototype.getCssClass = function() { return goog.ui.MenuHeaderRenderer.CSS_CLASS; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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);
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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.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. * @override */ 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.setElementShown(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.setElementShown(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.setElementShown(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; };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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.a11y.aria.Role'); 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.Control} control goog.ui.Button to render. * @return {Element} Root element for the button. * @override */ goog.ui.CustomButtonRenderer.prototype.createDom = function(control) { var button = /** @type {goog.ui.Button} */ (control); 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.a11y.aria.Role|undefined} ARIA role. * @override */ goog.ui.CustomButtonRenderer.prototype.getAriaRole = function() { return goog.a11y.aria.Role.BUTTON; }; /** * 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). * @override */ 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. * @override */ 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); var outerClassName = goog.getCssName(this.getCssClass(), 'outer-box'); if (outer && goog.dom.classes.has(outer, outerClassName)) { var inner = button.getDomHelper().getFirstElementChild(outer); var innerClassName = goog.getCssName(this.getCssClass(), 'inner-box'); if (inner && goog.dom.classes.has(inner, innerClassName)) { // 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.Control} control Button instance to decorate the element. * @param {Element} element Element to decorate. * @return {Element} Decorated element. * @override */ goog.ui.CustomButtonRenderer.prototype.decorate = function(control, element) { var button = /** @type {goog.ui.Button} */ (control); // 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. * @override */ 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; } } };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Base class for container renderers. * * @author attila@google.com (Attila Bodis) */ goog.provide('goog.ui.ContainerRenderer'); goog.require('goog.a11y.aria'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.classes'); goog.require('goog.string'); goog.require('goog.style'); 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(); goog.asserts.assert(elem, 'The container DOM element cannot be null.'); // 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.a11y.aria.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; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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. * @override */ 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 = '&nbsp;&nbsp;&nbsp;'; 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, 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; } };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Definition of the goog.ui.tree.TreeNode class. * * @author arv@google.com (Erik Arvidsson) * @author eae@google.com (Emil A Eklund) * @author jonp@google.com (Jon Perlow) * * This is a based on the webfx tree control. See file comment in * treecontrol.js. */ goog.provide('goog.ui.tree.TreeNode'); goog.require('goog.ui.tree.BaseNode'); /** * A single node in the tree. * @param {string} html The html content of the node label. * @param {Object=} opt_config The configuration for the tree. See * goog.ui.tree.TreeControl.defaultConfig. If not specified, a default config * will be used. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. * @constructor * @extends {goog.ui.tree.BaseNode} */ goog.ui.tree.TreeNode = function(html, opt_config, opt_domHelper) { goog.ui.tree.BaseNode.call(this, html, opt_config, opt_domHelper); }; goog.inherits(goog.ui.tree.TreeNode, goog.ui.tree.BaseNode); /** * The tree the item is in. Cached on demand from the parent. * @type {goog.ui.tree.TreeControl?} * @private */ goog.ui.tree.TreeNode.prototype.tree_ = null; /** * Returns the tree. * @return {goog.ui.tree.TreeControl?} The tree. * @override */ goog.ui.tree.TreeNode.prototype.getTree = function() { if (this.tree_) { return this.tree_; } var parent = this.getParent(); if (parent) { var tree = parent.getTree(); if (tree) { this.setTreeInternal(tree); return tree; } } return null; }; /** * Returns the source for the icon. * @return {string} Src for the icon. * @override */ goog.ui.tree.TreeNode.prototype.getCalculatedIconClass = function() { var expanded = this.getExpanded(); if (expanded && this.expandedIconClass_) { return this.expandedIconClass_; } if (!expanded && this.iconClass_) { return this.iconClass_; } // fall back on default icons var config = this.getConfig(); if (this.hasChildren()) { if (expanded && config.cssExpandedFolderIcon) { return config.cssTreeIcon + ' ' + config.cssExpandedFolderIcon; } else if (!expanded && config.cssCollapsedFolderIcon) { return config.cssTreeIcon + ' ' + config.cssCollapsedFolderIcon; } } else { if (config.cssFileIcon) { return config.cssTreeIcon + ' ' + config.cssFileIcon; } } return ''; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides the typeahead functionality for the tree class. * */ goog.provide('goog.ui.tree.TypeAhead'); goog.provide('goog.ui.tree.TypeAhead.Offset'); goog.require('goog.array'); goog.require('goog.events.KeyCodes'); goog.require('goog.string'); goog.require('goog.structs.Trie'); /** * Constructs a TypeAhead object. * @constructor */ goog.ui.tree.TypeAhead = function() { this.nodeMap_ = new goog.structs.Trie(); }; /** * Map of tree nodes to allow for quick access by characters in the label text. * @type {goog.structs.Trie} * @private */ goog.ui.tree.TypeAhead.prototype.nodeMap_; /** * Buffer for storing typeahead characters. * @type {string} * @private */ goog.ui.tree.TypeAhead.prototype.buffer_ = ''; /** * Matching labels from the latest typeahead search. * @type {Array.<string>?} * @private */ goog.ui.tree.TypeAhead.prototype.matchingLabels_ = null; /** * Matching nodes from the latest typeahead search. Used when more than * one node is present with the same label text. * @type {Array.<goog.ui.tree.BaseNode>?} * @private */ goog.ui.tree.TypeAhead.prototype.matchingNodes_ = null; /** * Specifies the current index of the label from the latest typeahead search. * @type {number} * @private */ goog.ui.tree.TypeAhead.prototype.matchingLabelIndex_ = 0; /** * Specifies the index into matching nodes when more than one node is found * with the same label. * @type {number} * @private */ goog.ui.tree.TypeAhead.prototype.matchingNodeIndex_ = 0; /** * Enum for offset values that are used for ctrl-key navigation among the * multiple matches of a given typeahead buffer. * * @enum {number} */ goog.ui.tree.TypeAhead.Offset = { DOWN: 1, UP: -1 }; /** * Handles navigation keys. * @param {goog.events.BrowserEvent} e The browser event. * @return {boolean} The handled value. */ goog.ui.tree.TypeAhead.prototype.handleNavigation = function(e) { var handled = false; switch (e.keyCode) { // Handle ctrl+down, ctrl+up to navigate within typeahead results. case goog.events.KeyCodes.DOWN: case goog.events.KeyCodes.UP: if (e.ctrlKey) { this.jumpTo_(e.keyCode == goog.events.KeyCodes.DOWN ? goog.ui.tree.TypeAhead.Offset.DOWN : goog.ui.tree.TypeAhead.Offset.UP); handled = true; } break; // Remove the last typeahead char. case goog.events.KeyCodes.BACKSPACE: var length = this.buffer_.length - 1; handled = true; if (length > 0) { this.buffer_ = this.buffer_.substring(0, length); this.jumpToLabel_(this.buffer_); } else if (length == 0) { // Clear the last character in typeahead. this.buffer_ = ''; } else { handled = false; } break; // Clear typeahead buffer. case goog.events.KeyCodes.ESC: this.buffer_ = ''; handled = true; break; } return handled; }; /** * Handles the character presses. * @param {goog.events.BrowserEvent} e The browser event. * Expected event type is goog.events.KeyHandler.EventType.KEY. * @return {boolean} The handled value. */ goog.ui.tree.TypeAhead.prototype.handleTypeAheadChar = function(e) { var handled = false; if (!e.ctrlKey && !e.altKey) { // Since goog.structs.Trie.getKeys compares characters during // lookup, we should use charCode instead of keyCode where possible. // Convert to lowercase, typeahead is case insensitive. var ch = String.fromCharCode(e.charCode || e.keyCode).toLowerCase(); if (goog.string.isUnicodeChar(ch) && (ch != ' ' || this.buffer_)) { this.buffer_ += ch; handled = this.jumpToLabel_(this.buffer_); } } return handled; }; /** * Adds or updates the given node in the nodemap. The label text is used as a * key and the node id is used as a value. In the case that the key already * exists, such as when more than one node exists with the same label, then this * function creates an array to hold the multiple nodes. * @param {goog.ui.tree.BaseNode} node Node to be added or updated. */ goog.ui.tree.TypeAhead.prototype.setNodeInMap = function(node) { var labelText = node.getText(); if (labelText && !goog.string.isEmptySafe(labelText)) { // Typeahead is case insensitive, convert to lowercase. labelText = labelText.toLowerCase(); var previousValue = this.nodeMap_.get(labelText); if (previousValue) { // Found a previously created array, add the given node. previousValue.push(node); } else { // Create a new array and set the array as value. var nodeList = [node]; this.nodeMap_.set(labelText, nodeList); } } }; /** * Removes the given node from the nodemap. * @param {goog.ui.tree.BaseNode} node Node to be removed. */ goog.ui.tree.TypeAhead.prototype.removeNodeFromMap = function(node) { var labelText = node.getText(); if (labelText && !goog.string.isEmptySafe(labelText)) { labelText = labelText.toLowerCase(); var nodeList = /** @type {Array} */ (this.nodeMap_.get(labelText)); if (nodeList) { // Remove the node from the array. goog.array.remove(nodeList, node); if (!!nodeList.length) { this.nodeMap_.remove(labelText); } } } }; /** * Select the first matching node for the given typeahead. * @param {string} typeAhead Typeahead characters to match. * @return {boolean} True iff a node is found. * @private */ goog.ui.tree.TypeAhead.prototype.jumpToLabel_ = function(typeAhead) { var handled = false; var labels = this.nodeMap_.getKeys(typeAhead); // Make sure we have at least one matching label. if (labels && labels.length) { this.matchingNodeIndex_ = 0; this.matchingLabelIndex_ = 0; var nodes = /** @type {Array} */ (this.nodeMap_.get(labels[0])); if ((handled = this.selectMatchingNode_(nodes))) { this.matchingLabels_ = labels; } } // TODO(user): beep when no node is found return handled; }; /** * Select the next or previous node based on the offset. * @param {goog.ui.tree.TypeAhead.Offset} offset DOWN or UP. * @return {boolean} Whether a node is found. * @private */ goog.ui.tree.TypeAhead.prototype.jumpTo_ = function(offset) { var handled = false; var labels = this.matchingLabels_; if (labels) { var nodes = null; var nodeIndexOutOfRange = false; // Navigate within the nodes array. if (this.matchingNodes_) { var newNodeIndex = this.matchingNodeIndex_ + offset; if (newNodeIndex >= 0 && newNodeIndex < this.matchingNodes_.length) { this.matchingNodeIndex_ = newNodeIndex; nodes = this.matchingNodes_; } else { nodeIndexOutOfRange = true; } } // Navigate to the next or previous label. if (!nodes) { var newLabelIndex = this.matchingLabelIndex_ + offset; if (newLabelIndex >= 0 && newLabelIndex < labels.length) { this.matchingLabelIndex_ = newLabelIndex; } if (labels.length > this.matchingLabelIndex_) { nodes = /** @type {Array} */ (this.nodeMap_.get( labels[this.matchingLabelIndex_])); } // Handle the case where we are moving beyond the available nodes, // while going UP select the last item of multiple nodes with same label // and while going DOWN select the first item of next set of nodes if (nodes && nodes.length && nodeIndexOutOfRange) { this.matchingNodeIndex_ = (offset == goog.ui.tree.TypeAhead.Offset.UP) ? nodes.length - 1 : 0; } } if ((handled = this.selectMatchingNode_(nodes))) { this.matchingLabels_ = labels; } } // TODO(user): beep when no node is found return handled; }; /** * Given a nodes array reveals and selects the node while using node index. * @param {Array.<goog.ui.tree.BaseNode>?} nodes Nodes array to select the * node from. * @return {boolean} Whether a matching node was found. * @private */ goog.ui.tree.TypeAhead.prototype.selectMatchingNode_ = function(nodes) { var node; if (nodes) { // Find the matching node. if (this.matchingNodeIndex_ < nodes.length) { node = nodes[this.matchingNodeIndex_]; this.matchingNodes_ = nodes; } if (node) { node.reveal(); node.select(); } } return !!node; }; /** * Clears the typeahead buffer. */ goog.ui.tree.TypeAhead.prototype.clear = function() { this.buffer_ = ''; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Definition of the goog.ui.tree.BaseNode class. * * @author arv@google.com (Erik Arvidsson) * @author eae@google.com (Emil A Eklund) * @author jonp@google.com (Jon Perlow) * * This is a based on the webfx tree control. It since been updated to add * typeahead support, as well as accessibility support using ARIA framework. * See file comment in treecontrol.js. */ goog.provide('goog.ui.tree.BaseNode'); goog.provide('goog.ui.tree.BaseNode.EventType'); goog.require('goog.Timer'); goog.require('goog.a11y.aria'); goog.require('goog.asserts'); goog.require('goog.events.KeyCodes'); goog.require('goog.string'); goog.require('goog.string.StringBuffer'); goog.require('goog.style'); goog.require('goog.ui.Component'); goog.require('goog.userAgent'); /** * An abstract base class for a node in the tree. * * @param {string} html The html content of the node label. * @param {Object=} opt_config The configuration for the tree. See * {@link goog.ui.tree.TreeControl.defaultConfig}. If not specified the * default config will be used. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. * @constructor * @extends {goog.ui.Component} */ goog.ui.tree.BaseNode = function(html, opt_config, opt_domHelper) { goog.ui.Component.call(this, opt_domHelper); /** * The configuration for the tree. * @type {Object} * @private */ this.config_ = opt_config || goog.ui.tree.TreeControl.defaultConfig; /** * HTML content of the node label. * @type {string} * @private */ this.html_ = html; }; goog.inherits(goog.ui.tree.BaseNode, goog.ui.Component); /** * The event types dispatched by this class. * @enum {string} */ goog.ui.tree.BaseNode.EventType = { BEFORE_EXPAND: 'beforeexpand', EXPAND: 'expand', BEFORE_COLLAPSE: 'beforecollapse', COLLAPSE: 'collapse' }; /** * Map of nodes in existence. Needed to route events to the appropriate nodes. * Nodes are added to the map at {@link #enterDocument} time and removed at * {@link #exitDocument} time. * @type {Object} * @protected */ goog.ui.tree.BaseNode.allNodes = {}; /** * Whether the tree item is selected. * @type {boolean} * @private */ goog.ui.tree.BaseNode.prototype.selected_ = false; /** * Whether the tree node is expanded. * @type {boolean} * @private */ goog.ui.tree.BaseNode.prototype.expanded_ = false; /** * Tooltip for the tree item * @type {?string} * @private */ goog.ui.tree.BaseNode.prototype.toolTip_ = null; /** * HTML that can appear after the label (so not inside the anchor). * @type {string} * @private */ goog.ui.tree.BaseNode.prototype.afterLabelHtml_ = ''; /** * Whether to allow user to collapse this node. * @type {boolean} * @private */ goog.ui.tree.BaseNode.prototype.isUserCollapsible_ = true; /** * Nesting depth of this node; cached result of computeDepth_. * -1 if value has not been cached. * @type {number} * @private */ goog.ui.tree.BaseNode.prototype.depth_ = -1; /** @override */ goog.ui.tree.BaseNode.prototype.disposeInternal = function() { goog.ui.tree.BaseNode.superClass_.disposeInternal.call(this); if (this.tree_) { this.tree_.removeNode(this); this.tree_ = null; } this.setElementInternal(null); }; /** * Adds roles and states. * @protected */ goog.ui.tree.BaseNode.prototype.initAccessibility = function() { var el = this.getElement(); if (el) { // Set an id for the label var label = this.getLabelElement(); if (label && !label.id) { label.id = this.getId() + '.label'; } goog.a11y.aria.setRole(el, 'treeitem'); goog.a11y.aria.setState(el, 'selected', false); goog.a11y.aria.setState(el, 'expanded', false); goog.a11y.aria.setState(el, 'level', this.getDepth()); if (label) { goog.a11y.aria.setState(el, 'labelledby', label.id); } var img = this.getIconElement(); if (img) { goog.a11y.aria.setRole(img, 'presentation'); } var ei = this.getExpandIconElement(); if (ei) { goog.a11y.aria.setRole(ei, 'presentation'); } var ce = this.getChildrenElement(); if (ce) { goog.a11y.aria.setRole(ce, 'group'); // In case the children will be created lazily. if (ce.hasChildNodes()) { // do setsize for each child var count = this.getChildCount(); for (var i = 1; i <= count; i++) { var child = this.getChildAt(i - 1).getElement(); goog.asserts.assert(child, 'The child element cannot be null'); goog.a11y.aria.setState(child, 'setsize', count); goog.a11y.aria.setState(child, 'posinset', i); } } } } }; /** @override */ goog.ui.tree.BaseNode.prototype.createDom = function() { var sb = new goog.string.StringBuffer(); this.toHtml(sb); var element = this.getDomHelper().htmlToDocumentFragment(sb.toString()); this.setElementInternal(/** @type {Element} */ (element)); }; /** @override */ goog.ui.tree.BaseNode.prototype.enterDocument = function() { goog.ui.tree.BaseNode.superClass_.enterDocument.call(this); goog.ui.tree.BaseNode.allNodes[this.getId()] = this; this.initAccessibility(); }; /** @override */ goog.ui.tree.BaseNode.prototype.exitDocument = function() { goog.ui.tree.BaseNode.superClass_.exitDocument.call(this); delete goog.ui.tree.BaseNode.allNodes[this.getId()]; }; /** * The method assumes that the child doesn't have parent node yet. * The {@code opt_render} argument is not used. If the parent node is expanded, * the child node's state will be the same as the parent's. Otherwise the * child's DOM tree won't be created. * @override */ goog.ui.tree.BaseNode.prototype.addChildAt = function(child, index, opt_render) { goog.asserts.assert(!child.getParent()); var prevNode = this.getChildAt(index - 1); var nextNode = this.getChildAt(index); goog.ui.tree.BaseNode.superClass_.addChildAt.call(this, child, index); child.previousSibling_ = prevNode; child.nextSibling_ = nextNode; if (prevNode) { prevNode.nextSibling_ = child; } else { this.firstChild_ = child; } if (nextNode) { nextNode.previousSibling_ = child; } else { this.lastChild_ = child; } var tree = this.getTree(); if (tree) { child.setTreeInternal(tree); } child.setDepth_(this.getDepth() + 1); if (this.getElement()) { this.updateExpandIcon(); if (this.getExpanded()) { var el = this.getChildrenElement(); if (!child.getElement()) { child.createDom(); } var childElement = child.getElement(); var nextElement = nextNode && nextNode.getElement(); el.insertBefore(childElement, nextElement); if (this.isInDocument()) { child.enterDocument(); } if (!nextNode) { if (prevNode) { prevNode.updateExpandIcon(); } else { goog.style.setElementShown(el, true); this.setExpanded(this.getExpanded()); } } } } }; /** * Adds a node as a child to the current node. * @param {goog.ui.tree.BaseNode} child The child to add. * @param {goog.ui.tree.BaseNode=} opt_before If specified, the new child is * added as a child before this one. If not specified, it's appended to the * end. * @return {goog.ui.tree.BaseNode} The added child. */ goog.ui.tree.BaseNode.prototype.add = function(child, opt_before) { goog.asserts.assert(!opt_before || opt_before.getParent() == this, 'Can only add nodes before siblings'); if (child.getParent()) { child.getParent().removeChild(child); } this.addChildAt(child, opt_before ? this.indexOfChild(opt_before) : this.getChildCount()); return child; }; /** * Removes a child. The caller is responsible for disposing the node. * @param {goog.ui.Component|string} childNode The child to remove. Must be a * {@link goog.ui.tree.BaseNode}. * @param {boolean=} opt_unrender Unused. The child will always be unrendered. * @return {goog.ui.tree.BaseNode} The child that was removed. * @override */ goog.ui.tree.BaseNode.prototype.removeChild = function(childNode, opt_unrender) { // In reality, this only accepts BaseNodes. var child = /** @type {goog.ui.tree.BaseNode} */ (childNode); // if we remove selected or tree with the selected we should select this var tree = this.getTree(); var selectedNode = tree ? tree.getSelectedItem() : null; if (selectedNode == child || child.contains(selectedNode)) { if (tree.hasFocus()) { this.select(); goog.Timer.callOnce(this.onTimeoutSelect_, 10, this); } else { this.select(); } } goog.ui.tree.BaseNode.superClass_.removeChild.call(this, child); if (this.lastChild_ == child) { this.lastChild_ = child.previousSibling_; } if (this.firstChild_ == child) { this.firstChild_ = child.nextSibling_; } if (child.previousSibling_) { child.previousSibling_.nextSibling_ = child.nextSibling_; } if (child.nextSibling_) { child.nextSibling_.previousSibling_ = child.previousSibling_; } var wasLast = child.isLastSibling(); child.tree_ = null; child.depth_ = -1; if (tree) { // Tell the tree control that this node is now removed. tree.removeNode(this); if (this.isInDocument()) { var el = this.getChildrenElement(); if (child.isInDocument()) { var childEl = child.getElement(); el.removeChild(childEl); child.exitDocument(); } if (wasLast) { var newLast = this.getLastChild(); if (newLast) { newLast.updateExpandIcon(); } } if (!this.hasChildren()) { el.style.display = 'none'; this.updateExpandIcon(); this.updateIcon_(); } } } return child; }; /** * @deprecated Use {@link #removeChild}. */ goog.ui.tree.BaseNode.prototype.remove = goog.ui.tree.BaseNode.prototype.removeChild; /** * Handler for setting focus asynchronously. * @private */ goog.ui.tree.BaseNode.prototype.onTimeoutSelect_ = function() { this.select(); }; /** * Returns the tree. */ goog.ui.tree.BaseNode.prototype.getTree = goog.abstractMethod; /** * Returns the depth of the node in the tree. Should not be overridden. * @return {number} The non-negative depth of this node (the root is zero). */ goog.ui.tree.BaseNode.prototype.getDepth = function() { var depth = this.depth_; if (depth < 0) { depth = this.computeDepth_(); this.setDepth_(depth); } return depth; }; /** * Computes the depth of the node in the tree. * Called only by getDepth, when the depth hasn't already been cached. * @return {number} The non-negative depth of this node (the root is zero). * @private */ goog.ui.tree.BaseNode.prototype.computeDepth_ = function() { var parent = this.getParent(); if (parent) { return parent.getDepth() + 1; } else { return 0; } }; /** * Changes the depth of a node (and all its descendants). * @param {number} depth The new nesting depth; must be non-negative. * @private */ goog.ui.tree.BaseNode.prototype.setDepth_ = function(depth) { if (depth != this.depth_) { this.depth_ = depth; var row = this.getRowElement(); if (row) { var indent = this.getPixelIndent_() + 'px'; if (this.isRightToLeft()) { row.style.paddingRight = indent; } else { row.style.paddingLeft = indent; } } this.forEachChild(function(child) { child.setDepth_(depth + 1); }); } }; /** * Returns true if the node is a descendant of this node * @param {goog.ui.tree.BaseNode} node The node to check. * @return {boolean} True if the node is a descendant of this node, false * otherwise. */ goog.ui.tree.BaseNode.prototype.contains = function(node) { var current = node; while (current) { if (current == this) { return true; } current = current.getParent(); } return false; }; /** * An array of empty children to return for nodes that have no children. * @type {!Array.<!goog.ui.tree.BaseNode>} * @private */ goog.ui.tree.BaseNode.EMPTY_CHILDREN_ = []; /** * @param {number} index 0-based index. * @return {goog.ui.tree.BaseNode} The child at the given index; null if none. */ goog.ui.tree.BaseNode.prototype.getChildAt; /** * Returns the children of this node. * @return {!Array.<!goog.ui.tree.BaseNode>} The children. */ goog.ui.tree.BaseNode.prototype.getChildren = function() { var children = []; this.forEachChild(function(child) { children.push(child); }); return children; }; /** * @return {goog.ui.tree.BaseNode} The first child of this node. */ goog.ui.tree.BaseNode.prototype.getFirstChild = function() { return this.getChildAt(0); }; /** * @return {goog.ui.tree.BaseNode} The last child of this node. */ goog.ui.tree.BaseNode.prototype.getLastChild = function() { return this.getChildAt(this.getChildCount() - 1); }; /** * @return {goog.ui.tree.BaseNode} The previous sibling of this node. */ goog.ui.tree.BaseNode.prototype.getPreviousSibling = function() { return this.previousSibling_; }; /** * @return {goog.ui.tree.BaseNode} The next sibling of this node. */ goog.ui.tree.BaseNode.prototype.getNextSibling = function() { return this.nextSibling_; }; /** * @return {boolean} Whether the node is the last sibling. */ goog.ui.tree.BaseNode.prototype.isLastSibling = function() { return !this.nextSibling_; }; /** * @return {boolean} Whether the node is selected. */ goog.ui.tree.BaseNode.prototype.isSelected = function() { return this.selected_; }; /** * Selects the node. */ goog.ui.tree.BaseNode.prototype.select = function() { var tree = this.getTree(); if (tree) { tree.setSelectedItem(this); } }; /** * Originally it was intended to deselect the node but never worked. * @deprecated Use {@code tree.setSelectedItem(null)}. */ goog.ui.tree.BaseNode.prototype.deselect = goog.nullFunction; /** * Called from the tree to instruct the node change its selection state. * @param {boolean} selected The new selection state. * @protected */ goog.ui.tree.BaseNode.prototype.setSelectedInternal = function(selected) { if (this.selected_ == selected) { return; } this.selected_ = selected; this.updateRow(); var el = this.getElement(); if (el) { goog.a11y.aria.setState(el, 'selected', selected); if (selected) { var treeElement = this.getTree().getElement(); goog.asserts.assert(treeElement, 'The DOM element for the tree cannot be null'); goog.a11y.aria.setState(treeElement, 'activedescendant', this.getId()); } } }; /** * @return {boolean} Whether the node is expanded. */ goog.ui.tree.BaseNode.prototype.getExpanded = function() { return this.expanded_; }; /** * Sets the node to be expanded internally, without state change events. * @param {boolean} expanded Whether to expand or close the node. */ goog.ui.tree.BaseNode.prototype.setExpandedInternal = function(expanded) { this.expanded_ = expanded; }; /** * Sets the node to be expanded. * @param {boolean} expanded Whether to expand or close the node. */ goog.ui.tree.BaseNode.prototype.setExpanded = function(expanded) { var isStateChange = expanded != this.expanded_; if (isStateChange) { // Only fire events if the expanded state has actually changed. var prevented = !this.dispatchEvent( expanded ? goog.ui.tree.BaseNode.EventType.BEFORE_EXPAND : goog.ui.tree.BaseNode.EventType.BEFORE_COLLAPSE); if (prevented) return; } var ce; this.expanded_ = expanded; var tree = this.getTree(); var el = this.getElement(); if (this.hasChildren()) { if (!expanded && tree && this.contains(tree.getSelectedItem())) { this.select(); } if (el) { ce = this.getChildrenElement(); if (ce) { goog.style.setElementShown(ce, expanded); // Make sure we have the HTML for the children here. if (expanded && this.isInDocument() && !ce.hasChildNodes()) { var sb = new goog.string.StringBuffer(); this.forEachChild(function(child) { child.toHtml(sb); }); ce.innerHTML = sb.toString(); this.forEachChild(function(child) { child.enterDocument(); }); } } this.updateExpandIcon(); } } else { ce = this.getChildrenElement(); if (ce) { goog.style.setElementShown(ce, false); } } if (el) { this.updateIcon_(); goog.a11y.aria.setState(el, 'expanded', expanded); } if (isStateChange) { this.dispatchEvent(expanded ? goog.ui.tree.BaseNode.EventType.EXPAND : goog.ui.tree.BaseNode.EventType.COLLAPSE); } }; /** * Toggles the expanded state of the node. */ goog.ui.tree.BaseNode.prototype.toggle = function() { this.setExpanded(!this.getExpanded()); }; /** * Expands the node. */ goog.ui.tree.BaseNode.prototype.expand = function() { this.setExpanded(true); }; /** * Collapses the node. */ goog.ui.tree.BaseNode.prototype.collapse = function() { this.setExpanded(false); }; /** * Collapses the children of the node. */ goog.ui.tree.BaseNode.prototype.collapseChildren = function() { this.forEachChild(function(child) { child.collapseAll(); }); }; /** * Collapses the children and the node. */ goog.ui.tree.BaseNode.prototype.collapseAll = function() { this.collapseChildren(); this.collapse(); }; /** * Expands the children of the node. */ goog.ui.tree.BaseNode.prototype.expandChildren = function() { this.forEachChild(function(child) { child.expandAll(); }); }; /** * Expands the children and the node. */ goog.ui.tree.BaseNode.prototype.expandAll = function() { this.expandChildren(); this.expand(); }; /** * Expands the parent chain of this node so that it is visible. */ goog.ui.tree.BaseNode.prototype.reveal = function() { var parent = this.getParent(); if (parent) { parent.setExpanded(true); parent.reveal(); } }; /** * Sets whether the node will allow the user to collapse it. * @param {boolean} isCollapsible Whether to allow node collapse. */ goog.ui.tree.BaseNode.prototype.setIsUserCollapsible = function(isCollapsible) { this.isUserCollapsible_ = isCollapsible; if (!this.isUserCollapsible_) { this.expand(); } if (this.getElement()) { this.updateExpandIcon(); } }; /** * @return {boolean} Whether the node is collapsible by user actions. */ goog.ui.tree.BaseNode.prototype.isUserCollapsible = function() { return this.isUserCollapsible_; }; /** * Returns the html for the node. * @param {goog.string.StringBuffer} sb A string buffer to append the HTML to. */ goog.ui.tree.BaseNode.prototype.toHtml = function(sb) { var tree = this.getTree(); var hideLines = !tree.getShowLines() || tree == this.getParent() && !tree.getShowRootLines(); var childClass = hideLines ? this.config_.cssChildrenNoLines : this.config_.cssChildren; var nonEmptyAndExpanded = this.getExpanded() && this.hasChildren(); sb.append('<div class="', this.config_.cssItem, '" id="', this.getId(), '">', this.getRowHtml(), '<div class="', childClass, '" style="', this.getLineStyle(), (nonEmptyAndExpanded ? '' : 'display:none;'), '">'); if (nonEmptyAndExpanded) { // children this.forEachChild(function(child) { child.toHtml(sb); }); } // and tags sb.append('</div></div>'); }; /** * @return {number} The pixel indent of the row. * @private */ goog.ui.tree.BaseNode.prototype.getPixelIndent_ = function() { return Math.max(0, (this.getDepth() - 1) * this.config_.indentWidth); }; /** * @return {string} The html for the row. * @protected */ goog.ui.tree.BaseNode.prototype.getRowHtml = function() { var sb = new goog.string.StringBuffer(); sb.append('<div class="', this.getRowClassName(), '" style="padding-', this.isRightToLeft() ? 'right:' : 'left:', this.getPixelIndent_(), 'px">', this.getExpandIconHtml(), this.getIconHtml(), this.getLabelHtml(), '</div>'); return sb.toString(); }; /** * @return {string} The class name for the row. * @protected */ goog.ui.tree.BaseNode.prototype.getRowClassName = function() { var selectedClass; if (this.isSelected()) { selectedClass = ' ' + this.config_.cssSelectedRow; } else { selectedClass = ''; } return this.config_.cssTreeRow + selectedClass; }; /** * @return {string} The html for the label. * @protected */ goog.ui.tree.BaseNode.prototype.getLabelHtml = function() { var toolTip = this.getToolTip(); var sb = new goog.string.StringBuffer(); sb.append('<span class="', this.config_.cssItemLabel, '"', (toolTip ? ' title="' + goog.string.htmlEscape(toolTip) + '"' : ''), '>', this.getHtml(), '</span>', '<span>', this.getAfterLabelHtml(), '</span>'); return sb.toString(); }; /** * Returns the html that appears after the label. This is useful if you want to * put extra UI on the row of the label but not inside the anchor tag. * @return {string} The html. */ goog.ui.tree.BaseNode.prototype.getAfterLabelHtml = function() { return this.afterLabelHtml_; }; /** * Sets the html that appears after the label. This is useful if you want to * put extra UI on the row of the label but not inside the anchor tag. * @param {string} html The html. */ goog.ui.tree.BaseNode.prototype.setAfterLabelHtml = function(html) { this.afterLabelHtml_ = html; var el = this.getAfterLabelElement(); if (el) { el.innerHTML = html; } }; /** * @return {string} The html for the icon. * @protected */ goog.ui.tree.BaseNode.prototype.getIconHtml = function() { return '<span style="display:inline-block" class="' + this.getCalculatedIconClass() + '"></span>'; }; /** * Gets the calculated icon class. * @protected */ goog.ui.tree.BaseNode.prototype.getCalculatedIconClass = goog.abstractMethod; /** * @return {string} The source for the icon. * @protected */ goog.ui.tree.BaseNode.prototype.getExpandIconHtml = function() { return '<span type="expand" style="display:inline-block" class="' + this.getExpandIconClass() + '"></span>'; }; /** * @return {string} The class names of the icon used for expanding the node. * @protected */ goog.ui.tree.BaseNode.prototype.getExpandIconClass = function() { var tree = this.getTree(); var hideLines = !tree.getShowLines() || tree == this.getParent() && !tree.getShowRootLines(); var config = this.config_; var sb = new goog.string.StringBuffer(); sb.append(config.cssTreeIcon, ' ', config.cssExpandTreeIcon, ' '); if (this.hasChildren()) { var bits = 0; /* Bitmap used to determine which icon to use 1 Plus 2 Minus 4 T Line 8 L Line */ if (tree.getShowExpandIcons() && this.isUserCollapsible_) { if (this.getExpanded()) { bits = 2; } else { bits = 1; } } if (!hideLines) { if (this.isLastSibling()) { bits += 4; } else { bits += 8; } } switch (bits) { case 1: sb.append(config.cssExpandTreeIconPlus); break; case 2: sb.append(config.cssExpandTreeIconMinus); break; case 4: sb.append(config.cssExpandTreeIconL); break; case 5: sb.append(config.cssExpandTreeIconLPlus); break; case 6: sb.append(config.cssExpandTreeIconLMinus); break; case 8: sb.append(config.cssExpandTreeIconT); break; case 9: sb.append(config.cssExpandTreeIconTPlus); break; case 10: sb.append(config.cssExpandTreeIconTMinus); break; default: // 0 sb.append(config.cssExpandTreeIconBlank); } } else { if (hideLines) { sb.append(config.cssExpandTreeIconBlank); } else if (this.isLastSibling()) { sb.append(config.cssExpandTreeIconL); } else { sb.append(config.cssExpandTreeIconT); } } return sb.toString(); }; /** * @return {string} The line style. */ goog.ui.tree.BaseNode.prototype.getLineStyle = function() { return 'background-position:' + this.getLineStyle2() + ';'; }; /** * @return {string} The line style. */ goog.ui.tree.BaseNode.prototype.getLineStyle2 = function() { return (this.isLastSibling() ? '-100' : (this.getDepth() - 1) * this.config_.indentWidth) + 'px 0'; }; /** * @return {Element} The element for the tree node. * @override */ goog.ui.tree.BaseNode.prototype.getElement = function() { var el = goog.ui.tree.BaseNode.superClass_.getElement.call(this); if (!el) { el = this.getDomHelper().getElement(this.getId()); this.setElementInternal(el); } return el; }; /** * @return {Element} The row is the div that is used to draw the node without * the children. */ goog.ui.tree.BaseNode.prototype.getRowElement = function() { var el = this.getElement(); return el ? /** @type {Element} */ (el.firstChild) : null; }; /** * @return {Element} The expanded icon element. * @protected */ goog.ui.tree.BaseNode.prototype.getExpandIconElement = function() { var el = this.getRowElement(); return el ? /** @type {Element} */ (el.firstChild) : null; }; /** * @return {Element} The icon element. * @protected */ goog.ui.tree.BaseNode.prototype.getIconElement = function() { var el = this.getRowElement(); return el ? /** @type {Element} */ (el.childNodes[1]) : null; }; /** * @return {Element} The label element. */ goog.ui.tree.BaseNode.prototype.getLabelElement = function() { var el = this.getRowElement(); // TODO: find/fix race condition that requires us to add // the lastChild check return el && el.lastChild ? /** @type {Element} */ (el.lastChild.previousSibling) : null; }; /** * @return {Element} The element after the label. */ goog.ui.tree.BaseNode.prototype.getAfterLabelElement = function() { var el = this.getRowElement(); return el ? /** @type {Element} */ (el.lastChild) : null; }; /** * @return {Element} The div containing the children. * @protected */ goog.ui.tree.BaseNode.prototype.getChildrenElement = function() { var el = this.getElement(); return el ? /** @type {Element} */ (el.lastChild) : null; }; /** * Sets the icon class for the node. * @param {string} s The icon class. */ goog.ui.tree.BaseNode.prototype.setIconClass = function(s) { this.iconClass_ = s; if (this.isInDocument()) { this.updateIcon_(); } }; /** * Gets the icon class for the node. * @return {string} s The icon source. */ goog.ui.tree.BaseNode.prototype.getIconClass = function() { return this.iconClass_; }; /** * Sets the icon class for when the node is expanded. * @param {string} s The expanded icon class. */ goog.ui.tree.BaseNode.prototype.setExpandedIconClass = function(s) { this.expandedIconClass_ = s; if (this.isInDocument()) { this.updateIcon_(); } }; /** * Gets the icon class for when the node is expanded. * @return {string} The class. */ goog.ui.tree.BaseNode.prototype.getExpandedIconClass = function() { return this.expandedIconClass_; }; /** * Sets the text of the label. * @param {string} s The plain text of the label. */ goog.ui.tree.BaseNode.prototype.setText = function(s) { this.setHtml(goog.string.htmlEscape(s)); }; /** * Returns the text of the label. If the text was originally set as HTML, the * return value is unspecified. * @return {string} The plain text of the label. */ goog.ui.tree.BaseNode.prototype.getText = function() { return goog.string.unescapeEntities(this.getHtml()); }; /** * Sets the html of the label. * @param {string} s The html string for the label. */ goog.ui.tree.BaseNode.prototype.setHtml = function(s) { this.html_ = s; var el = this.getLabelElement(); if (el) { el.innerHTML = s; } var tree = this.getTree(); if (tree) { // Tell the tree control about the updated label text. tree.setNode(this); } }; /** * Returns the html of the label. * @return {string} The html string of the label. */ goog.ui.tree.BaseNode.prototype.getHtml = function() { return this.html_; }; /** * Sets the text of the tooltip. * @param {string} s The tooltip text to set. */ goog.ui.tree.BaseNode.prototype.setToolTip = function(s) { this.toolTip_ = s; var el = this.getLabelElement(); if (el) { el.title = s; } }; /** * Returns the text of the tooltip. * @return {?string} The tooltip text. */ goog.ui.tree.BaseNode.prototype.getToolTip = function() { return this.toolTip_; }; /** * Updates the row styles. */ goog.ui.tree.BaseNode.prototype.updateRow = function() { var rowEl = this.getRowElement(); if (rowEl) { rowEl.className = this.getRowClassName(); } }; /** * Updates the expand icon of the node. */ goog.ui.tree.BaseNode.prototype.updateExpandIcon = function() { var img = this.getExpandIconElement(); if (img) { img.className = this.getExpandIconClass(); } var cel = this.getChildrenElement(); if (cel) { cel.style.backgroundPosition = this.getLineStyle2(); } }; /** * Updates the icon of the node. Assumes that this.getElement() is created. * @private */ goog.ui.tree.BaseNode.prototype.updateIcon_ = function() { this.getIconElement().className = this.getCalculatedIconClass(); }; /** * Handles mouse down event. * @param {!goog.events.BrowserEvent} e The browser event. * @protected */ goog.ui.tree.BaseNode.prototype.onMouseDown = function(e) { var el = e.target; // expand icon var type = el.getAttribute('type'); if (type == 'expand' && this.hasChildren()) { if (this.isUserCollapsible_) { this.toggle(); } return; } this.select(); this.updateRow(); }; /** * Handles a click event. * @param {!goog.events.BrowserEvent} e The browser event. * @protected * @suppress {underscore} */ goog.ui.tree.BaseNode.prototype.onClick_ = goog.events.Event.preventDefault; /** * Handles a double click event. * @param {!goog.events.BrowserEvent} e The browser event. * @protected * @suppress {underscore} */ goog.ui.tree.BaseNode.prototype.onDoubleClick_ = function(e) { var el = e.target; // expand icon var type = el.getAttribute('type'); if (type == 'expand' && this.hasChildren()) { return; } if (this.isUserCollapsible_) { this.toggle(); } }; /** * Handles a key down event. * @param {!goog.events.BrowserEvent} e The browser event. * @return {boolean} The handled value. * @protected */ goog.ui.tree.BaseNode.prototype.onKeyDown = function(e) { var handled = true; switch (e.keyCode) { case goog.events.KeyCodes.RIGHT: if (e.altKey) { break; } if (this.hasChildren()) { if (!this.getExpanded()) { this.setExpanded(true); } else { this.getFirstChild().select(); } } break; case goog.events.KeyCodes.LEFT: if (e.altKey) { break; } if (this.hasChildren() && this.getExpanded() && this.isUserCollapsible_) { this.setExpanded(false); } else { var parent = this.getParent(); var tree = this.getTree(); // don't go to root if hidden if (parent && (tree.getShowRootNode() || parent != tree)) { parent.select(); } } break; case goog.events.KeyCodes.DOWN: var nextNode = this.getNextShownNode(); if (nextNode) { nextNode.select(); } break; case goog.events.KeyCodes.UP: var previousNode = this.getPreviousShownNode(); if (previousNode) { previousNode.select(); } break; default: handled = false; } if (handled) { e.preventDefault(); var tree = this.getTree(); if (tree) { // clear type ahead buffer as user navigates with arrow keys tree.clearTypeAhead(); } } return handled; }; /** * Handles a key down event. * @param {!goog.events.BrowserEvent} e The browser event. * @private */ goog.ui.tree.BaseNode.prototype.onKeyPress_ = function(e) { if (!e.altKey && e.keyCode >= goog.events.KeyCodes.LEFT && e.keyCode <= goog.events.KeyCodes.DOWN) { e.preventDefault(); } }; /** * @return {goog.ui.tree.BaseNode} The last shown descendant. */ goog.ui.tree.BaseNode.prototype.getLastShownDescendant = function() { if (!this.getExpanded() || !this.hasChildren()) { return this; } // we know there is at least 1 child return this.getLastChild().getLastShownDescendant(); }; /** * @return {goog.ui.tree.BaseNode} The next node to show or null if there isn't * a next node to show. */ goog.ui.tree.BaseNode.prototype.getNextShownNode = function() { if (this.hasChildren() && this.getExpanded()) { return this.getFirstChild(); } else { var parent = this; var next; while (parent != this.getTree()) { next = parent.getNextSibling(); if (next != null) { return next; } parent = parent.getParent(); } return null; } }; /** * @return {goog.ui.tree.BaseNode} The previous node to show. */ goog.ui.tree.BaseNode.prototype.getPreviousShownNode = function() { var ps = this.getPreviousSibling(); if (ps != null) { return ps.getLastShownDescendant(); } var parent = this.getParent(); var tree = this.getTree(); if (!tree.getShowRootNode() && parent == tree) { return null; } return /** @type {goog.ui.tree.BaseNode} */ (parent); }; /** * @return {*} Data set by the client. * @deprecated Use {@link #getModel} instead. */ goog.ui.tree.BaseNode.prototype.getClientData = goog.ui.tree.BaseNode.prototype.getModel; /** * Sets client data to associate with the node. * @param {*} data The client data to associate with the node. * @deprecated Use {@link #setModel} instead. */ goog.ui.tree.BaseNode.prototype.setClientData = goog.ui.tree.BaseNode.prototype.setModel; /** * @return {Object} The configuration for the tree. */ goog.ui.tree.BaseNode.prototype.getConfig = function() { return this.config_; }; /** * Internal method that is used to set the tree control on the node. * @param {goog.ui.tree.TreeControl} tree The tree control. */ goog.ui.tree.BaseNode.prototype.setTreeInternal = function(tree) { if (this.tree_ != tree) { this.tree_ = tree; // Add new node to the type ahead node map. tree.setNode(this); this.forEachChild(function(child) { child.setTreeInternal(tree); }); } };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Definition of the goog.ui.tree.TreeControl class, which * provides a way to view a hierarchical set of data. * * @author arv@google.com (Erik Arvidsson) * @author eae@google.com (Emil A Eklund) * @author jonp@google.com (Jon Perlow) * @author annams@google.com (Srinivas Annam) * * This is a based on the webfx tree control. It since been updated to add * typeahead support, as well as accessibility support using ARIA framework. * * @see ../../demos/tree/demo.html */ goog.provide('goog.ui.tree.TreeControl'); goog.require('goog.a11y.aria'); goog.require('goog.asserts'); goog.require('goog.debug.Logger'); goog.require('goog.dom.classes'); goog.require('goog.events.EventType'); goog.require('goog.events.FocusHandler'); goog.require('goog.events.KeyHandler'); goog.require('goog.events.KeyHandler.EventType'); goog.require('goog.ui.tree.BaseNode'); goog.require('goog.ui.tree.TreeNode'); goog.require('goog.ui.tree.TypeAhead'); goog.require('goog.userAgent'); /** * This creates a TreeControl object. A tree control provides a way to * view a hierarchical set of data. * @param {string} html The HTML content of the node label. * @param {Object=} opt_config The configuration for the tree. See * goog.ui.tree.TreeControl.defaultConfig. If not specified, a default config * will be used. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. * @constructor * @extends {goog.ui.tree.BaseNode} */ goog.ui.tree.TreeControl = function(html, opt_config, opt_domHelper) { goog.ui.tree.BaseNode.call(this, html, opt_config, opt_domHelper); // The root is open and selected by default. this.setExpandedInternal(true); this.setSelectedInternal(true); this.selectedItem_ = this; /** * Used for typeahead support. * @type {!goog.ui.tree.TypeAhead} * @private */ this.typeAhead_ = new goog.ui.tree.TypeAhead(); if (goog.userAgent.IE) { /** @preserveTry */ try { // works since IE6SP1 document.execCommand('BackgroundImageCache', false, true); } catch (e) { this.logger_.warning('Failed to enable background image cache'); } } }; goog.inherits(goog.ui.tree.TreeControl, goog.ui.tree.BaseNode); /** * The object handling keyboard events. * @type {goog.events.KeyHandler} * @private */ goog.ui.tree.TreeControl.prototype.keyHandler_ = null; /** * The object handling focus events. * @type {goog.events.FocusHandler} * @private */ goog.ui.tree.TreeControl.prototype.focusHandler_ = null; /** * Logger * @type {goog.debug.Logger} * @private */ goog.ui.tree.TreeControl.prototype.logger_ = goog.debug.Logger.getLogger('goog.ui.tree.TreeControl'); /** * Whether the tree is focused. * @type {boolean} * @private */ goog.ui.tree.TreeControl.prototype.focused_ = false; /** * Child node that currently has focus. * @type {goog.ui.tree.BaseNode} * @private */ goog.ui.tree.TreeControl.prototype.focusedNode_ = null; /** * Whether to show lines. * @type {boolean} * @private */ goog.ui.tree.TreeControl.prototype.showLines_ = true; /** * Whether to show expanded lines. * @type {boolean} * @private */ goog.ui.tree.TreeControl.prototype.showExpandIcons_ = true; /** * Whether to show the root node. * @type {boolean} * @private */ goog.ui.tree.TreeControl.prototype.showRootNode_ = true; /** * Whether to show the root lines. * @type {boolean} * @private */ goog.ui.tree.TreeControl.prototype.showRootLines_ = true; /** @override */ goog.ui.tree.TreeControl.prototype.getTree = function() { return this; }; /** @override */ goog.ui.tree.TreeControl.prototype.getDepth = function() { return 0; }; /** * Expands the parent chain of this node so that it is visible. * @override */ goog.ui.tree.TreeControl.prototype.reveal = function() { // always expanded by default // needs to be overriden so that we don't try to reveal our parent // which is a generic component }; /** * Handles focus on the tree. * @param {!goog.events.BrowserEvent} e The browser event. * @private */ goog.ui.tree.TreeControl.prototype.handleFocus_ = function(e) { this.focused_ = true; goog.dom.classes.add(this.getElement(), 'focused'); if (this.selectedItem_) { this.selectedItem_.select(); } }; /** * Handles blur on the tree. * @param {!goog.events.BrowserEvent} e The browser event. * @private */ goog.ui.tree.TreeControl.prototype.handleBlur_ = function(e) { this.focused_ = false; goog.dom.classes.remove(this.getElement(), 'focused'); }; /** * @return {boolean} Whether the tree has keyboard focus. */ goog.ui.tree.TreeControl.prototype.hasFocus = function() { return this.focused_; }; /** @override */ goog.ui.tree.TreeControl.prototype.getExpanded = function() { return !this.showRootNode_ || goog.ui.tree.TreeControl.superClass_.getExpanded.call(this); }; /** @override */ goog.ui.tree.TreeControl.prototype.setExpanded = function(expanded) { if (!this.showRootNode_) { this.setExpandedInternal(expanded); } else { goog.ui.tree.TreeControl.superClass_.setExpanded.call(this, expanded); } }; /** @override */ goog.ui.tree.TreeControl.prototype.getExpandIconHtml = function() { // no expand icon for root element return ''; }; /** @override */ goog.ui.tree.TreeControl.prototype.getIconElement = function() { var el = this.getRowElement(); return el ? /** @type {Element} */ (el.firstChild) : null; }; /** @override */ goog.ui.tree.TreeControl.prototype.getExpandIconElement = function() { // no expand icon for root element return null; }; /** @override */ goog.ui.tree.TreeControl.prototype.updateExpandIcon = function() { // no expand icon }; /** @override */ goog.ui.tree.TreeControl.prototype.getRowClassName = function() { return goog.ui.tree.TreeControl.superClass_.getRowClassName.call(this) + (this.showRootNode_ ? '' : ' ' + this.getConfig().cssHideRoot); }; /** * Returns the source for the icon. * @return {string} Src for the icon. * @override */ goog.ui.tree.TreeControl.prototype.getCalculatedIconClass = function() { var expanded = this.getExpanded(); if (expanded && this.expandedIconClass_) { return this.expandedIconClass_; } if (!expanded && this.iconClass_) { return this.iconClass_; } // fall back on default icons var config = this.getConfig(); if (expanded && config.cssExpandedRootIcon) { return config.cssTreeIcon + ' ' + config.cssExpandedRootIcon; } else if (!expanded && config.cssCollapsedRootIcon) { return config.cssTreeIcon + ' ' + config.cssCollapsedRootIcon; } return ''; }; /** * Sets the selected item. * @param {goog.ui.tree.BaseNode} node The item to select. */ goog.ui.tree.TreeControl.prototype.setSelectedItem = function(node) { if (this.selectedItem_ == node) { return; } var hadFocus = false; if (this.selectedItem_) { hadFocus = this.selectedItem_ == this.focusedNode_; this.selectedItem_.setSelectedInternal(false); } this.selectedItem_ = node; if (node) { node.setSelectedInternal(true); if (hadFocus) { node.select(); } } this.dispatchEvent(goog.events.EventType.CHANGE); }; /** * Returns the selected item. * @return {goog.ui.tree.BaseNode} The currently selected item. */ goog.ui.tree.TreeControl.prototype.getSelectedItem = function() { return this.selectedItem_; }; /** * Sets whether to show lines. * @param {boolean} b Whether to show lines. */ goog.ui.tree.TreeControl.prototype.setShowLines = function(b) { if (this.showLines_ != b) { this.showLines_ = b; if (this.isInDocument()) { this.updateLinesAndExpandIcons_(); } } }; /** * @return {boolean} Whether to show lines. */ goog.ui.tree.TreeControl.prototype.getShowLines = function() { return this.showLines_; }; /** * Updates the lines after the tree has been drawn. * @private */ goog.ui.tree.TreeControl.prototype.updateLinesAndExpandIcons_ = function() { var tree = this; var showLines = tree.getShowLines(); var showRootLines = tree.getShowRootLines(); // Recursively walk through all nodes and update the class names of the // expand icon and the children element. function updateShowLines(node) { var childrenEl = node.getChildrenElement(); if (childrenEl) { var hideLines = !showLines || tree == node.getParent() && !showRootLines; var childClass = hideLines ? node.getConfig().cssChildrenNoLines : node.getConfig().cssChildren; childrenEl.className = childClass; var expandIconEl = node.getExpandIconElement(); if (expandIconEl) { expandIconEl.className = node.getExpandIconClass(); } } node.forEachChild(updateShowLines); } updateShowLines(this); }; /** * Sets whether to show root lines. * @param {boolean} b Whether to show root lines. */ goog.ui.tree.TreeControl.prototype.setShowRootLines = function(b) { if (this.showRootLines_ != b) { this.showRootLines_ = b; if (this.isInDocument()) { this.updateLinesAndExpandIcons_(); } } }; /** * @return {boolean} Whether to show root lines. */ goog.ui.tree.TreeControl.prototype.getShowRootLines = function() { return this.showRootLines_; }; /** * Sets whether to show expand icons. * @param {boolean} b Whether to show expand icons. */ goog.ui.tree.TreeControl.prototype.setShowExpandIcons = function(b) { if (this.showExpandIcons_ != b) { this.showExpandIcons_ = b; if (this.isInDocument()) { this.updateLinesAndExpandIcons_(); } } }; /** * @return {boolean} Whether to show expand icons. */ goog.ui.tree.TreeControl.prototype.getShowExpandIcons = function() { return this.showExpandIcons_; }; /** * Sets whether to show the root node. * @param {boolean} b Whether to show the root node. */ goog.ui.tree.TreeControl.prototype.setShowRootNode = function(b) { if (this.showRootNode_ != b) { this.showRootNode_ = b; if (this.isInDocument()) { var el = this.getRowElement(); if (el) { el.className = this.getRowClassName(); } } // Ensure that we do not hide the selected item. if (!b && this.getSelectedItem() == this && this.getFirstChild()) { this.setSelectedItem(this.getFirstChild()); } } }; /** * @return {boolean} Whether to show the root node. */ goog.ui.tree.TreeControl.prototype.getShowRootNode = function() { return this.showRootNode_; }; /** * Add roles and states. * @protected * @override */ goog.ui.tree.TreeControl.prototype.initAccessibility = function() { goog.ui.tree.TreeControl.superClass_.initAccessibility.call(this); var elt = this.getElement(); goog.asserts.assert(elt, 'The DOM element for the tree cannot be null.'); goog.a11y.aria.setRole(elt, 'tree'); goog.a11y.aria.setState(elt, 'labelledby', this.getLabelElement().id); }; /** @override */ goog.ui.tree.TreeControl.prototype.enterDocument = function() { goog.ui.tree.TreeControl.superClass_.enterDocument.call(this); var el = this.getElement(); el.className = this.getConfig().cssRoot; el.setAttribute('hideFocus', 'true'); this.attachEvents_(); this.initAccessibility(); }; /** @override */ goog.ui.tree.TreeControl.prototype.exitDocument = function() { goog.ui.tree.TreeControl.superClass_.exitDocument.call(this); this.detachEvents_(); }; /** * Adds the event listeners to the tree. * @private */ goog.ui.tree.TreeControl.prototype.attachEvents_ = function() { var el = this.getElement(); el.tabIndex = 0; var kh = this.keyHandler_ = new goog.events.KeyHandler(el); var fh = this.focusHandler_ = new goog.events.FocusHandler(el); this.getHandler(). listen(fh, goog.events.FocusHandler.EventType.FOCUSOUT, this.handleBlur_). listen(fh, goog.events.FocusHandler.EventType.FOCUSIN, this.handleFocus_). listen(kh, goog.events.KeyHandler.EventType.KEY, this.handleKeyEvent). listen(el, goog.events.EventType.MOUSEDOWN, this.handleMouseEvent_). listen(el, goog.events.EventType.CLICK, this.handleMouseEvent_). listen(el, goog.events.EventType.DBLCLICK, this.handleMouseEvent_); }; /** * Removes the event listeners from the tree. * @private */ goog.ui.tree.TreeControl.prototype.detachEvents_ = function() { this.keyHandler_.dispose(); this.keyHandler_ = null; this.focusHandler_.dispose(); this.focusHandler_ = null; }; /** * Handles mouse events. * @param {!goog.events.BrowserEvent} e The browser event. * @private */ goog.ui.tree.TreeControl.prototype.handleMouseEvent_ = function(e) { this.logger_.fine('Received event ' + e.type); var node = this.getNodeFromEvent_(e); if (node) { switch (e.type) { case goog.events.EventType.MOUSEDOWN: node.onMouseDown(e); break; case goog.events.EventType.CLICK: node.onClick_(e); break; case goog.events.EventType.DBLCLICK: node.onDoubleClick_(e); break; } } }; /** * Handles key down on the tree. * @param {!goog.events.BrowserEvent} e The browser event. * @return {boolean} The handled value. */ goog.ui.tree.TreeControl.prototype.handleKeyEvent = function(e) { var handled = false; // Handle typeahead and navigation keystrokes. handled = this.typeAhead_.handleNavigation(e) || (this.selectedItem_ && this.selectedItem_.onKeyDown(e)) || this.typeAhead_.handleTypeAheadChar(e); if (handled) { e.preventDefault(); } return handled; }; /** * Finds the containing node given an event. * @param {!goog.events.BrowserEvent} e The browser event. * @return {goog.ui.tree.BaseNode} The containing node or null if no node is * found. * @private */ goog.ui.tree.TreeControl.prototype.getNodeFromEvent_ = function(e) { // find the right node var node = null; var target = e.target; while (target != null) { var id = target.id; node = goog.ui.tree.BaseNode.allNodes[id]; if (node) { return node; } if (target == this.getElement()) { break; } target = target.parentNode; } return null; }; /** * Creates a new tree node using the same config as the root. * @param {string} html The html content of the node label. * @return {goog.ui.tree.TreeNode} The new item. */ goog.ui.tree.TreeControl.prototype.createNode = function(html) { // Some projects call createNode without arguments which causes failure. // See http://goto/misuse-createnode // TODO(user): Fix them and remove the html || '' workaround. return new goog.ui.tree.TreeNode(html || '', this.getConfig(), this.getDomHelper()); }; /** * Allows the caller to notify that the given node has been added or just had * been updated in the tree. * @param {goog.ui.tree.BaseNode} node New node being added or existing node * that just had been updated. */ goog.ui.tree.TreeControl.prototype.setNode = function(node) { this.typeAhead_.setNodeInMap(node); }; /** * Allows the caller to notify that the given node is being removed from the * tree. * @param {goog.ui.tree.BaseNode} node Node being removed. */ goog.ui.tree.TreeControl.prototype.removeNode = function(node) { this.typeAhead_.removeNodeFromMap(node); }; /** * Clear the typeahead buffer. */ goog.ui.tree.TreeControl.prototype.clearTypeAhead = function() { this.typeAhead_.clear(); }; /** * A default configuration for the tree. */ goog.ui.tree.TreeControl.defaultConfig = { indentWidth: 19, cssRoot: goog.getCssName('goog-tree-root') + ' ' + goog.getCssName('goog-tree-item'), cssHideRoot: goog.getCssName('goog-tree-hide-root'), cssItem: goog.getCssName('goog-tree-item'), cssChildren: goog.getCssName('goog-tree-children'), cssChildrenNoLines: goog.getCssName('goog-tree-children-nolines'), cssTreeRow: goog.getCssName('goog-tree-row'), cssItemLabel: goog.getCssName('goog-tree-item-label'), cssTreeIcon: goog.getCssName('goog-tree-icon'), cssExpandTreeIcon: goog.getCssName('goog-tree-expand-icon'), cssExpandTreeIconPlus: goog.getCssName('goog-tree-expand-icon-plus'), cssExpandTreeIconMinus: goog.getCssName('goog-tree-expand-icon-minus'), cssExpandTreeIconTPlus: goog.getCssName('goog-tree-expand-icon-tplus'), cssExpandTreeIconTMinus: goog.getCssName('goog-tree-expand-icon-tminus'), cssExpandTreeIconLPlus: goog.getCssName('goog-tree-expand-icon-lplus'), cssExpandTreeIconLMinus: goog.getCssName('goog-tree-expand-icon-lminus'), cssExpandTreeIconT: goog.getCssName('goog-tree-expand-icon-t'), cssExpandTreeIconL: goog.getCssName('goog-tree-expand-icon-l'), cssExpandTreeIconBlank: goog.getCssName('goog-tree-expand-icon-blank'), cssExpandedFolderIcon: goog.getCssName('goog-tree-expanded-folder-icon'), cssCollapsedFolderIcon: goog.getCssName('goog-tree-collapsed-folder-icon'), cssFileIcon: goog.getCssName('goog-tree-file-icon'), cssExpandedRootIcon: goog.getCssName('goog-tree-expanded-folder-icon'), cssCollapsedRootIcon: goog.getCssName('goog-tree-collapsed-folder-icon'), cssSelectedRow: goog.getCssName('selected') };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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.a11y.aria.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.a11y.aria.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.a11y.aria.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). * @override */ 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. * @override */ 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 (this.handleContextMenu != goog.nullFunction) { handler.listen(element, goog.events.EventType.CONTEXTMENU, this.handleContextMenu); } 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 (this.handleContextMenu != goog.nullFunction) { handler.unlisten(element, goog.events.EventType.CONTEXTMENU, this.handleContextMenu); } 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); } } }; /** * Handles contextmenu events. * @param {goog.events.BrowserEvent} e Event to handle. */ goog.ui.Control.prototype.handleContextMenu = goog.nullFunction; /** * 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); });
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Class for 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.a11y.aria'); goog.require('goog.a11y.aria.Role'); goog.require('goog.a11y.aria.State'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.TagName'); goog.require('goog.dom.classes'); goog.require('goog.events'); 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; /** * The dialog's preferred ARIA role. * @type {goog.a11y.aria.Role} * @private */ goog.ui.Dialog.prototype.preferredAriaRole_ = goog.a11y.aria.Role.DIALOG; /** @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_; }; /** * Returns the dialog's preferred ARIA role. This can be used to override the * default dialog role, e.g. with an ARIA role of ALERTDIALOG for a simple * warning or confirmation dialog. * @return {goog.a11y.aria.Role} This dialog's preferred ARIA role. */ goog.ui.Dialog.prototype.getPreferredAriaRole = function() { return this.preferredAriaRole_; }; /** * Sets the dialog's preferred ARIA role. This can be used to override the * default dialog role, e.g. with an ARIA role of ALERTDIALOG for a simple * warning or confirmation dialog. * @param {goog.a11y.aria.Role} role This dialog's preferred ARIA role. */ goog.ui.Dialog.prototype.setPreferredAriaRole = function(role) { this.preferredAriaRole_ = role; }; /** * 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. * @override */ 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. * @override */ 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.a11y.aria.setRole(element, this.getPreferredAriaRole()); goog.a11y.aria.setState(element, goog.a11y.aria.State.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.setElementShown(this.titleCloseEl_, this.hasTitleCloseButton_); // Render the buttons. if (this.buttons_) { this.buttons_.attachToElement(this.buttonEl_); } goog.style.setElementShown(this.buttonEl_, !!this.buttons_); this.setBackgroundElementOpacity(this.backgroundElementOpacity_); }; /** @override */ goog.ui.Dialog.prototype.decorateInternal = function(element) { goog.base(this, 'decorateInternal', element); var dialogElement = this.getElement(); goog.asserts.assert(dialogElement, 'The DOM element for dialog cannot be null.'); // Decorate or create the content element. var contentClass = goog.getCssName(this.class_, 'content'); this.contentEl_ = goog.dom.getElementsByTagNameAndClass( null, contentClass, dialogElement)[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_; } dialogElement.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, dialogElement)[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]; // Give the title an id if it doesn't already have one. if (!this.titleEl_.id) { this.titleEl_.id = this.getId(); } } 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', {'className': titleClass, 'id': this.getId()}); dialogElement.insertBefore(this.titleEl_, this.contentEl_); } this.titleId_ = this.titleEl_.id; // 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.a11y.aria.setState(dialogElement, goog.a11y.aria.State.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.setElementShown(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, dialogElement)[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); dialogElement.appendChild(this.buttonEl_); if (this.buttons_) { this.buttons_.attachToElement(this.buttonEl_); } goog.style.setElementShown(this.buttonEl_, !!this.buttons_); } this.setBackgroundElementOpacity(this.backgroundElementOpacity_); }; /** @override */ goog.ui.Dialog.prototype.enterDocument = function() { goog.base(this, 'enterDocument'); // Listen for keyboard 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_); // 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_); // 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_); var element = this.getElement(); goog.asserts.assert(element, 'The DOM element for dialog cannot be null'); goog.a11y.aria.setRole(element, this.getPreferredAriaRole()); if (this.titleTextEl_.id !== '') { goog.a11y.aria.setState(element, goog.a11y.aria.State.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. After this * method returns, isVisible() will always return the new state, even * if there is a transition. * @param {boolean} visible Whether the dialog should be visible. * @override */ 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); }; /** @override */ goog.ui.Dialog.prototype.onShow = function() { goog.base(this, 'onShow'); this.dispatchEvent(goog.ui.Dialog.EventType.AFTER_SHOW); }; /** @override */ goog.ui.Dialog.prototype.onHide = function() { goog.base(this, 'onHide'); 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. * @override */ 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 && !button.disabled) { 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.setElementShown(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.setElementShown(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. // Instead, set up a wrap in focus backward to the end of the dialog. this.setupBackwardTabWrap(); } } 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, SELECT or an A element. var isSpecialFormElement = (target.tagName == 'TEXTAREA' || target.tagName == 'SELECT' || target.tagName == 'A') && !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 {*} key Key used to identify the button in events. * @param {*} 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. * @override */ 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_ = /** @type {?string} */ (key); } if (opt_isCancel) { this.cancelButton_ = /** @type {?string} */ (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(); } })();
JavaScript
// Copyright 2010 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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.setElementShown(this.valueWarningElem_, false); } else { goog.style.setElementShown(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; };
JavaScript
// Copyright 2012 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Renderer for {@link goog.ui.menuBar}. * */ goog.provide('goog.ui.MenuBarRenderer'); goog.require('goog.a11y.aria.Role'); goog.require('goog.dom'); goog.require('goog.ui.ContainerRenderer'); /** * Default renderer for {@link goog.ui.menuBar}s, based on {@link * goog.ui.ContainerRenderer}. * @constructor * @extends {goog.ui.ContainerRenderer} */ goog.ui.MenuBarRenderer = function() { goog.base(this); }; goog.inherits(goog.ui.MenuBarRenderer, goog.ui.ContainerRenderer); goog.addSingletonGetter(goog.ui.MenuBarRenderer); /** * Default CSS class to be applied to the root element of elements rendered * by this renderer. * @type {string} */ goog.ui.MenuBarRenderer.CSS_CLASS = goog.getCssName('goog-menubar'); /** * @override */ goog.ui.MenuBarRenderer.prototype.getAriaRole = function() { return goog.a11y.aria.Role.MENUBAR; }; /** * @override */ goog.ui.MenuBarRenderer.prototype.getCssClass = function() { return goog.ui.MenuBarRenderer.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. * @override */ goog.ui.MenuBarRenderer.prototype.getDefaultOrientation = function() { return goog.ui.Container.Orientation.HORIZONTAL; };
JavaScript
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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.a11y.aria'); goog.require('goog.asserts'); goog.require('goog.date'); goog.require('goog.date.Date'); goog.require('goog.date.Interval'); goog.require('goog.dom'); goog.require('goog.dom.NodeType'); goog.require('goog.dom.classes'); goog.require('goog.events.Event'); goog.require('goog.events.EventType'); goog.require('goog.events.KeyHandler'); goog.require('goog.i18n.DateTimeFormat'); goog.require('goog.i18n.DateTimeSymbols'); goog.require('goog.style'); goog.require('goog.ui.Component'); goog.require('goog.ui.IdGenerator'); /** * 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; /** * Generator for unique table cell IDs. * @type {goog.ui.IdGenerator} * @private */ goog.ui.DatePicker.prototype.cellIdGenerator_ = goog.ui.IdGenerator.getInstance(); /** * 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.setElementShown(this.elToday_, this.showToday_); goog.style.setElementShown(this.elNone_, this.allowNone_); goog.style.setElementShown(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 active month displayed. */ goog.ui.DatePicker.prototype.getActiveMonth = function() { return this.activeMonth_.clone(); }; /** * @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.a11y.aria.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.a11y.aria.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_.STANDALONEMONTHS[i]); } this.createMenu_(this.elMonth_, list, this.handleMonthMenuClick_, this.symbols_.STANDALONEMONTHS[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_.STANDALONEMONTHS[date.getMonth()], date.getFullYear())); } if (this.elMonth_) { goog.dom.setTextContent(this.elMonth_, this.symbols_.STANDALONEMONTHS[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 = this.cellIdGenerator_.getNextUniqueId(); } goog.asserts.assert(el, 'The table DOM element cannot be null.'); goog.a11y.aria.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.asserts.assert(this.tableBody_, 'The table body DOM element cannot be null'); goog.a11y.aria.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.setElementShown(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.setElementShown(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);
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Renderer for {@link goog.ui.SubMenu}s. * */ goog.provide('goog.ui.SubMenuRenderer'); goog.require('goog.a11y.aria'); goog.require('goog.a11y.aria.State'); goog.require('goog.asserts'); goog.require('goog.dom'); 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.Control} control goog.ui.SubMenu to render. * @return {Element} Root element for the item. * @override */ goog.ui.SubMenuRenderer.prototype.createDom = function(control) { var subMenu = /** @type {goog.ui.SubMenu} */ (control); 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.Control} control goog.ui.SubMenu to render. * @param {Element} element Element to decorate. * @return {Element} Root element for the item. * @override */ goog.ui.SubMenuRenderer.prototype.decorate = function(control, element) { var subMenu = /** @type {goog.ui.SubMenu} */ (control); 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.setElementShown(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.Control} control goog.ui.SubMenu whose DOM is to be * initialized as it enters the document. * @override */ goog.ui.SubMenuRenderer.prototype.initializeDom = function(control) { var subMenu = /** @type {goog.ui.SubMenu} */ (control); 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); } var subMenuElement = subMenu.getElement(); goog.asserts.assert(subMenuElement, 'The sub menu DOM element cannot be null.'); goog.a11y.aria.setState(subMenuElement, goog.a11y.aria.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); } };
JavaScript
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview 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. * @override */ goog.ui.FilterObservingMenuItemRenderer.prototype.getCssClass = function() { return goog.ui.FilterObservingMenuItemRenderer.CSS_CLASS; };
JavaScript
// Copyright 2007 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A 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. * @override */ 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' ];
JavaScript