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 Plugin to handle enter keys.
*
*/
goog.provide('goog.editor.plugins.EnterHandler');
goog.require('goog.dom');
goog.require('goog.dom.AbstractRange');
goog.require('goog.dom.NodeOffset');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.TagName');
goog.require('goog.editor.BrowserFeature');
goog.require('goog.editor.Plugin');
goog.require('goog.editor.node');
goog.require('goog.editor.plugins.Blockquote');
goog.require('goog.editor.range');
goog.require('goog.editor.style');
goog.require('goog.events.KeyCodes');
goog.require('goog.string');
goog.require('goog.userAgent');
/**
* Plugin to handle enter keys. This does all the crazy to normalize (as much as
* is reasonable) what happens when you hit enter. This also handles the
* special casing of hitting enter in a blockquote.
*
* In IE, Webkit, and Opera, the resulting HTML uses one DIV tag per line. In
* Firefox, the resulting HTML uses BR tags at the end of each line.
*
* @constructor
* @extends {goog.editor.Plugin}
*/
goog.editor.plugins.EnterHandler = function() {
goog.editor.Plugin.call(this);
};
goog.inherits(goog.editor.plugins.EnterHandler, goog.editor.Plugin);
/**
* The type of block level tag to add on enter, for browsers that support
* specifying the default block-level tag. Can be overriden by subclasses; must
* be either DIV or P.
* @type {goog.dom.TagName}
* @protected
*/
goog.editor.plugins.EnterHandler.prototype.tag = goog.dom.TagName.DIV;
/** @override */
goog.editor.plugins.EnterHandler.prototype.getTrogClassId = function() {
return 'EnterHandler';
};
/** @override */
goog.editor.plugins.EnterHandler.prototype.enable = function(fieldObject) {
goog.base(this, 'enable', fieldObject);
if (goog.editor.BrowserFeature.SUPPORTS_OPERA_DEFAULTBLOCK_COMMAND &&
(this.tag == goog.dom.TagName.P || this.tag == goog.dom.TagName.DIV)) {
var doc = this.getFieldDomHelper().getDocument();
doc.execCommand('opera-defaultBlock', false, this.tag);
}
};
/**
* If the contents are empty, return the 'default' html for the field.
* The 'default' contents depend on the enter handling mode, so it
* makes the most sense in this plugin.
* @param {string} html The html to prepare.
* @return {string} The original HTML, or default contents if that
* html is empty.
* @override
*/
goog.editor.plugins.EnterHandler.prototype.prepareContentsHtml = function(
html) {
if (!html || goog.string.isBreakingWhitespace(html)) {
return goog.editor.BrowserFeature.COLLAPSES_EMPTY_NODES ?
this.getNonCollapsingBlankHtml() : '';
}
return html;
};
/**
* Gets HTML with no contents that won't collapse, for browsers that
* collapse the empty string.
* @return {string} Blank html.
* @protected
*/
goog.editor.plugins.EnterHandler.prototype.getNonCollapsingBlankHtml =
goog.functions.constant('<br>');
/**
* Internal backspace handler.
* @param {goog.events.Event} e The keypress event.
* @param {goog.dom.AbstractRange} range The closure range object.
* @protected
*/
goog.editor.plugins.EnterHandler.prototype.handleBackspaceInternal = function(e,
range) {
var field = this.getFieldObject().getElement();
var container = range && range.getStartNode();
if (field.firstChild == container && goog.editor.node.isEmpty(container)) {
e.preventDefault();
// TODO(user): I think we probably don't need to stopPropagation here
e.stopPropagation();
}
};
/**
* Fix paragraphs to be the correct type of node.
* @param {goog.events.Event} e The <enter> key event.
* @param {boolean} split Whether we already split up a blockquote by
* manually inserting elements.
* @protected
*/
goog.editor.plugins.EnterHandler.prototype.processParagraphTagsInternal =
function(e, split) {
// Force IE to turn the node we are leaving into a DIV. If we do turn
// it into a DIV, the node IE creates in response to ENTER will also be
// a DIV. If we don't, it will be a P. We handle that case
// in handleKeyUpIE_
if (goog.userAgent.IE || goog.userAgent.OPERA) {
this.ensureBlockIeOpera(goog.dom.TagName.DIV);
} else if (!split && goog.userAgent.WEBKIT) {
// WebKit duplicates a blockquote when the user hits enter. Let's cancel
// this and insert a BR instead, to make it more consistent with the other
// browsers.
var range = this.getFieldObject().getRange();
if (!range || !goog.editor.plugins.EnterHandler.isDirectlyInBlockquote(
range.getContainerElement())) {
return;
}
var dh = this.getFieldDomHelper();
var br = dh.createElement(goog.dom.TagName.BR);
range.insertNode(br, true);
// If the BR is at the end of a block element, Safari still thinks there is
// only one line instead of two, so we need to add another BR in that case.
if (goog.editor.node.isBlockTag(br.parentNode) &&
!goog.editor.node.skipEmptyTextNodes(br.nextSibling)) {
goog.dom.insertSiblingBefore(
dh.createElement(goog.dom.TagName.BR), br);
}
goog.editor.range.placeCursorNextTo(br, false);
e.preventDefault();
}
};
/**
* Determines whether the lowest containing block node is a blockquote.
* @param {Node} n The node.
* @return {boolean} Whether the deepest block ancestor of n is a blockquote.
*/
goog.editor.plugins.EnterHandler.isDirectlyInBlockquote = function(n) {
for (var current = n; current; current = current.parentNode) {
if (goog.editor.node.isBlockTag(current)) {
return current.tagName == goog.dom.TagName.BLOCKQUOTE;
}
}
return false;
};
/**
* Internal delete key handler.
* @param {goog.events.Event} e The keypress event.
* @protected
*/
goog.editor.plugins.EnterHandler.prototype.handleDeleteGecko = function(e) {
this.deleteBrGecko(e);
};
/**
* Deletes the element at the cursor if it is a BR node, and if it does, calls
* e.preventDefault to stop the browser from deleting. Only necessary in Gecko
* as a workaround for mozilla bug 205350 where deleting a BR that is followed
* by a block element doesn't work (the BR gets immediately replaced). We also
* need to account for an ill-formed cursor which occurs from us trying to
* stop the browser from deleting.
*
* @param {goog.events.Event} e The DELETE keypress event.
* @protected
*/
goog.editor.plugins.EnterHandler.prototype.deleteBrGecko = function(e) {
var range = this.getFieldObject().getRange();
if (range.isCollapsed()) {
var container = range.getEndNode();
if (container.nodeType == goog.dom.NodeType.ELEMENT) {
var nextNode = container.childNodes[range.getEndOffset()];
if (nextNode && nextNode.tagName == goog.dom.TagName.BR) {
// We want to retrieve the first non-whitespace previous sibling
// as we could have added an empty text node below and want to
// properly handle deleting a sequence of BR's.
var previousSibling = goog.editor.node.getPreviousSibling(nextNode);
var nextSibling = nextNode.nextSibling;
container.removeChild(nextNode);
e.preventDefault();
// When we delete a BR followed by a block level element, the cursor
// has a line-height which spans the height of the block level element.
// e.g. If we delete a BR followed by a UL, the resulting HTML will
// appear to the end user like:-
//
// | * one
// | * two
// | * three
//
// There are a couple of cases that we have to account for in order to
// properly conform to what the user expects when DELETE is pressed.
//
// 1. If the BR has a previous sibling and the previous sibling is
// not a block level element or a BR, we place the cursor at the
// end of that.
// 2. If the BR doesn't have a previous sibling or the previous sibling
// is a block level element or a BR, we place the cursor at the
// beginning of the leftmost leaf of its next sibling.
if (nextSibling && goog.editor.node.isBlockTag(nextSibling)) {
if (previousSibling &&
!(previousSibling.tagName == goog.dom.TagName.BR ||
goog.editor.node.isBlockTag(previousSibling))) {
goog.dom.Range.createCaret(
previousSibling,
goog.editor.node.getLength(previousSibling)).select();
} else {
var leftMostLeaf = goog.editor.node.getLeftMostLeaf(nextSibling);
goog.dom.Range.createCaret(leftMostLeaf, 0).select();
}
}
}
}
}
};
/** @override */
goog.editor.plugins.EnterHandler.prototype.handleKeyPress = function(e) {
// If a dialog doesn't have selectable field, Gecko grabs the event and
// performs actions in editor window. This solves that problem and allows
// the event to be passed on to proper handlers.
if (goog.userAgent.GECKO && this.getFieldObject().inModalMode()) {
return false;
}
// Firefox will allow the first node in an iframe to be deleted
// on a backspace. Disallow it if the node is empty.
if (e.keyCode == goog.events.KeyCodes.BACKSPACE) {
this.handleBackspaceInternal(e, this.getFieldObject().getRange());
} else if (e.keyCode == goog.events.KeyCodes.ENTER) {
if (goog.userAgent.GECKO) {
if (!e.shiftKey) {
// Behave similarly to IE's content editable return carriage:
// If the shift key is down or specified by the application, insert a
// BR, otherwise split paragraphs
this.handleEnterGecko_(e);
}
} else {
// In Gecko-based browsers, this is handled in the handleEnterGecko_
// method.
this.getFieldObject().dispatchBeforeChange();
var cursorPosition = this.deleteCursorSelection_();
var split = !!this.getFieldObject().execCommand(
goog.editor.plugins.Blockquote.SPLIT_COMMAND, cursorPosition);
if (split) {
// TODO(user): I think we probably don't need to stopPropagation here
e.preventDefault();
e.stopPropagation();
}
this.releasePositionObject_(cursorPosition);
if (goog.userAgent.WEBKIT) {
this.handleEnterWebkitInternal(e);
}
this.processParagraphTagsInternal(e, split);
this.getFieldObject().dispatchChange();
}
} else if (goog.userAgent.GECKO && e.keyCode == goog.events.KeyCodes.DELETE) {
this.handleDeleteGecko(e);
}
return false;
};
/** @override */
goog.editor.plugins.EnterHandler.prototype.handleKeyUp = function(e) {
// If a dialog doesn't have selectable field, Gecko grabs the event and
// performs actions in editor window. This solves that problem and allows
// the event to be passed on to proper handlers.
if (goog.userAgent.GECKO && this.getFieldObject().inModalMode()) {
return false;
}
this.handleKeyUpInternal(e);
return false;
};
/**
* Internal handler for keyup events.
* @param {goog.events.Event} e The key event.
* @protected
*/
goog.editor.plugins.EnterHandler.prototype.handleKeyUpInternal = function(e) {
if ((goog.userAgent.IE || goog.userAgent.OPERA) &&
e.keyCode == goog.events.KeyCodes.ENTER) {
this.ensureBlockIeOpera(goog.dom.TagName.DIV, true);
}
};
/**
* Handles an enter keypress event on fields in Gecko.
* @param {goog.events.BrowserEvent} e The key event.
* @private
*/
goog.editor.plugins.EnterHandler.prototype.handleEnterGecko_ = function(e) {
// Retrieve whether the selection is collapsed before we delete it.
var range = this.getFieldObject().getRange();
var wasCollapsed = !range || range.isCollapsed();
var cursorPosition = this.deleteCursorSelection_();
var handled = this.getFieldObject().execCommand(
goog.editor.plugins.Blockquote.SPLIT_COMMAND, cursorPosition);
if (handled) {
// TODO(user): I think we probably don't need to stopPropagation here
e.preventDefault();
e.stopPropagation();
}
this.releasePositionObject_(cursorPosition);
if (!handled) {
this.handleEnterAtCursorGeckoInternal(e, wasCollapsed, range);
}
};
/**
* Handle an enter key press in WebKit.
* @param {goog.events.BrowserEvent} e The key press event.
* @protected
*/
goog.editor.plugins.EnterHandler.prototype.handleEnterWebkitInternal =
goog.nullFunction;
/**
* Handle an enter key press on collapsed selection. handleEnterGecko_ ensures
* the selection is collapsed by deleting its contents if it is not. The
* default implementation does nothing.
* @param {goog.events.BrowserEvent} e The key press event.
* @param {boolean} wasCollapsed Whether the selection was collapsed before
* the key press. If it was not, code before this function has already
* cleared the contents of the selection.
* @param {goog.dom.AbstractRange} range Object representing the selection.
* @protected
*/
goog.editor.plugins.EnterHandler.prototype.handleEnterAtCursorGeckoInternal =
goog.nullFunction;
/**
* Names of all the nodes that we don't want to turn into block nodes in IE when
* the user hits enter.
* @type {Object}
* @private
*/
goog.editor.plugins.EnterHandler.DO_NOT_ENSURE_BLOCK_NODES_ =
goog.object.createSet(
goog.dom.TagName.LI, goog.dom.TagName.DIV, goog.dom.TagName.H1,
goog.dom.TagName.H2, goog.dom.TagName.H3, goog.dom.TagName.H4,
goog.dom.TagName.H5, goog.dom.TagName.H6);
/**
* Whether this is a node that contains a single BR tag and non-nbsp
* whitespace.
* @param {Node} node Node to check.
* @return {boolean} Whether this is an element that only contains a BR.
* @protected
*/
goog.editor.plugins.EnterHandler.isBrElem = function(node) {
return goog.editor.node.isEmpty(node) &&
node.getElementsByTagName(goog.dom.TagName.BR).length == 1;
};
/**
* Ensures all text in IE and Opera to be in the given tag in order to control
* Enter spacing. Call this when Enter is pressed if desired.
*
* We want to make sure the user is always inside of a block (or other nodes
* listed in goog.editor.plugins.EnterHandler.IGNORE_ENSURE_BLOCK_NODES_). We
* listen to keypress to force nodes that the user is leaving to turn into
* blocks, but we also need to listen to keyup to force nodes that the user is
* entering to turn into blocks.
* Example: html is: "<h2>foo[cursor]</h2>", and the user hits enter. We
* don't want to format the h2, but we do want to format the P that is
* created on enter. The P node is not available until keyup.
* @param {goog.dom.TagName} tag The tag name to convert to.
* @param {boolean=} opt_keyUp Whether the function is being called on key up.
* When called on key up, the cursor is in the newly created node, so the
* semantics for when to change it to a block are different. Specifically,
* if the resulting node contains only a BR, it is converted to <tag>.
* @protected
*/
goog.editor.plugins.EnterHandler.prototype.ensureBlockIeOpera = function(tag,
opt_keyUp) {
var range = this.getFieldObject().getRange();
var container = range.getContainer();
var field = this.getFieldObject().getElement();
var paragraph;
while (container && container != field) {
// We don't need to ensure a block if we are already in the same block, or
// in another block level node that we don't want to change the format of
// (unless we're handling keyUp and that block node just contains a BR).
var nodeName = container.nodeName;
// Due to @bug 2455389, the call to isBrElem needs to be inlined in the if
// instead of done before and saved in a variable, so that it can be
// short-circuited and avoid a weird IE edge case.
if (nodeName == tag ||
(goog.editor.plugins.EnterHandler.
DO_NOT_ENSURE_BLOCK_NODES_[nodeName] && !(opt_keyUp &&
goog.editor.plugins.EnterHandler.isBrElem(container)))) {
// Opera can create a <p> inside of a <div> in some situations,
// such as when breaking out of a list that is contained in a <div>.
if (goog.userAgent.OPERA && paragraph) {
if (nodeName == tag &&
paragraph == container.lastChild &&
goog.editor.node.isEmpty(paragraph)) {
goog.dom.insertSiblingAfter(paragraph, container);
goog.dom.Range.createFromNodeContents(paragraph).select();
}
break;
}
return;
}
if (goog.userAgent.OPERA && opt_keyUp && nodeName == goog.dom.TagName.P &&
nodeName != tag) {
paragraph = container;
}
container = container.parentNode;
}
if (goog.userAgent.IE && !goog.userAgent.isVersion(9)) {
// IE (before IE9) has a bug where if the cursor is directly before a block
// node (e.g., the content is "foo[cursor]<blockquote>bar</blockquote>"),
// the FormatBlock command actually formats the "bar" instead of the "foo".
// This is just wrong. To work-around this, we want to move the
// selection back one character, and then restore it to its prior position.
// NOTE: We use the following "range math" to detect this situation because
// using Closure ranges here triggers a bug in IE that causes a crash.
// parent2 != parent3 ensures moving the cursor forward one character
// crosses at least 1 element boundary, and therefore tests if the cursor is
// at such a boundary. The second check, parent3 != range.parentElement()
// weeds out some cases where the elements are siblings instead of cousins.
var needsHelp = false;
range = range.getBrowserRangeObject();
var range2 = range.duplicate();
range2.moveEnd('character', 1);
// In whitebox mode, when the cursor is at the end of the field, trying to
// move the end of the range will do nothing, and hence the range's text
// will be empty. In this case, the cursor clearly isn't sitting just
// before a block node, since it isn't before anything.
if (range2.text.length) {
var parent2 = range2.parentElement();
var range3 = range2.duplicate();
range3.collapse(false);
var parent3 = range3.parentElement();
if ((needsHelp = parent2 != parent3 &&
parent3 != range.parentElement())) {
range.move('character', -1);
range.select();
}
}
}
this.getFieldObject().getEditableDomHelper().getDocument().execCommand(
'FormatBlock', false, '<' + tag + '>');
if (needsHelp) {
range.move('character', 1);
range.select();
}
};
/**
* Deletes the content at the current cursor position.
* @return {Node|Object} Something representing the current cursor position.
* See deleteCursorSelectionIE_ and deleteCursorSelectionW3C_ for details.
* Should be passed to releasePositionObject_ when no longer in use.
* @private
*/
goog.editor.plugins.EnterHandler.prototype.deleteCursorSelection_ = function() {
return goog.editor.BrowserFeature.HAS_W3C_RANGES ?
this.deleteCursorSelectionW3C_() : this.deleteCursorSelectionIE_();
};
/**
* Releases the object returned by deleteCursorSelection_.
* @param {Node|Object} position The object returned by deleteCursorSelection_.
* @private
*/
goog.editor.plugins.EnterHandler.prototype.releasePositionObject_ =
function(position) {
if (!goog.editor.BrowserFeature.HAS_W3C_RANGES) {
(/** @type {Node} */ (position)).removeNode(true);
}
};
/**
* Delete the selection at the current cursor position, then returns a temporary
* node at the current position.
* @return {Node} A temporary node marking the current cursor position. This
* node should eventually be removed from the DOM.
* @private
*/
goog.editor.plugins.EnterHandler.prototype.deleteCursorSelectionIE_ =
function() {
var doc = this.getFieldDomHelper().getDocument();
var range = doc.selection.createRange();
var id = goog.string.createUniqueString();
range.pasteHTML('<span id="' + id + '"></span>');
var splitNode = doc.getElementById(id);
splitNode.id = '';
return splitNode;
};
/**
* Delete the selection at the current cursor position, then returns the node
* at the current position.
* @return {goog.editor.range.Point} The current cursor position. Note that
* unlike simulateEnterIE_, this should not be removed from the DOM.
* @private
*/
goog.editor.plugins.EnterHandler.prototype.deleteCursorSelectionW3C_ =
function() {
var range = this.getFieldObject().getRange();
// Delete the current selection if it's is non-collapsed.
// Although this is redundant in FF, it's necessary for Safari
if (!range.isCollapsed()) {
var shouldDelete = true;
// Opera selects the <br> in an empty block if there is no text node
// preceding it. To preserve inline formatting when pressing [enter] inside
// an empty block, don't delete the selection if it only selects a <br> at
// the end of the block.
// TODO(user): Move this into goog.dom.Range. It should detect this state
// when creating a range from the window selection and fix it in the created
// range.
if (goog.userAgent.OPERA) {
var startNode = range.getStartNode();
var startOffset = range.getStartOffset();
if (startNode == range.getEndNode() &&
// This weeds out cases where startNode is a text node.
startNode.lastChild &&
startNode.lastChild.tagName == goog.dom.TagName.BR &&
// If this check is true, then endOffset is implied to be
// startOffset + 1, because the selection is not collapsed and
// it starts and ends within the same element.
startOffset == startNode.childNodes.length - 1) {
shouldDelete = false;
}
}
if (shouldDelete) {
goog.editor.plugins.EnterHandler.deleteW3cRange_(range);
}
}
return goog.editor.range.getDeepEndPoint(range, true);
};
/**
* Deletes the contents of the selection from the DOM.
* @param {goog.dom.AbstractRange} range The range to remove contents from.
* @return {goog.dom.AbstractRange} The resulting range. Used for testing.
* @private
*/
goog.editor.plugins.EnterHandler.deleteW3cRange_ = function(range) {
if (range && !range.isCollapsed()) {
var reselect = true;
var baseNode = range.getContainerElement();
var nodeOffset = new goog.dom.NodeOffset(range.getStartNode(), baseNode);
var rangeOffset = range.getStartOffset();
// Whether the selection crosses no container boundaries.
var isInOneContainer =
goog.editor.plugins.EnterHandler.isInOneContainerW3c_(range);
// Whether the selection ends in a container it doesn't fully select.
var isPartialEnd = !isInOneContainer &&
goog.editor.plugins.EnterHandler.isPartialEndW3c_(range);
// Remove The range contents, and ensure the correct content stays selected.
range.removeContents();
var node = nodeOffset.findTargetNode(baseNode);
if (node) {
range = goog.dom.Range.createCaret(node, rangeOffset);
} else {
// This occurs when the node that would have been referenced has now been
// deleted and there are no other nodes in the baseNode. Thus need to
// set the caret to the end of the base node.
range =
goog.dom.Range.createCaret(baseNode, baseNode.childNodes.length);
reselect = false;
}
range.select();
// If we just deleted everything from the container, add an nbsp
// to the container, and leave the cursor inside of it
if (isInOneContainer) {
var container = goog.editor.style.getContainer(range.getStartNode());
if (goog.editor.node.isEmpty(container, true)) {
var html = ' ';
if (goog.userAgent.OPERA &&
container.tagName == goog.dom.TagName.LI) {
// Don't break Opera's native break-out-of-lists behavior.
html = '<br>';
}
goog.editor.node.replaceInnerHtml(container, html);
goog.editor.range.selectNodeStart(container.firstChild);
reselect = false;
}
}
if (isPartialEnd) {
/*
This code handles the following, where | is the cursor:
<div>a|b</div><div>c|d</div>
After removeContents, the remaining HTML is
<div>a</div><div>d</div>
which means the line break between the two divs remains. This block
moves children of the second div in to the first div to get the correct
result:
<div>ad</div>
TODO(robbyw): Should we wrap the second div's contents in a span if they
have inline style?
*/
var rangeStart = goog.editor.style.getContainer(range.getStartNode());
var redundantContainer = goog.editor.node.getNextSibling(rangeStart);
if (rangeStart && redundantContainer) {
goog.dom.append(rangeStart, redundantContainer.childNodes);
goog.dom.removeNode(redundantContainer);
}
}
if (reselect) {
// The contents of the original range are gone, so restore the cursor
// position at the start of where the range once was.
range = goog.dom.Range.createCaret(nodeOffset.findTargetNode(baseNode),
rangeOffset);
range.select();
}
}
return range;
};
/**
* Checks whether the whole range is in a single block-level element.
* @param {goog.dom.AbstractRange} range The range to check.
* @return {boolean} Whether the whole range is in a single block-level element.
* @private
*/
goog.editor.plugins.EnterHandler.isInOneContainerW3c_ = function(range) {
// Find the block element containing the start of the selection.
var startContainer = range.getStartNode();
if (goog.editor.style.isContainer(startContainer)) {
startContainer = startContainer.childNodes[range.getStartOffset()] ||
startContainer;
}
startContainer = goog.editor.style.getContainer(startContainer);
// Find the block element containing the end of the selection.
var endContainer = range.getEndNode();
if (goog.editor.style.isContainer(endContainer)) {
endContainer = endContainer.childNodes[range.getEndOffset()] ||
endContainer;
}
endContainer = goog.editor.style.getContainer(endContainer);
// Compare the two.
return startContainer == endContainer;
};
/**
* Checks whether the end of the range is not at the end of a block-level
* element.
* @param {goog.dom.AbstractRange} range The range to check.
* @return {boolean} Whether the end of the range is not at the end of a
* block-level element.
* @private
*/
goog.editor.plugins.EnterHandler.isPartialEndW3c_ = function(range) {
var endContainer = range.getEndNode();
var endOffset = range.getEndOffset();
var node = endContainer;
if (goog.editor.style.isContainer(node)) {
var child = node.childNodes[endOffset];
// Child is null when end offset is >= length, which indicates the entire
// container is selected. Otherwise, we also know the entire container
// is selected if the selection ends at a new container.
if (!child ||
child.nodeType == goog.dom.NodeType.ELEMENT &&
goog.editor.style.isContainer(child)) {
return false;
}
}
var container = goog.editor.style.getContainer(node);
while (container != node) {
if (goog.editor.node.getNextSibling(node)) {
return true;
}
node = node.parentNode;
}
return endOffset != goog.editor.node.getLength(endContainer);
};
| 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 TrogEdit plugin to handle enter keys by inserting the
* specified block level tag.
*
*/
goog.provide('goog.editor.plugins.TagOnEnterHandler');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.Range');
goog.require('goog.dom.TagName');
goog.require('goog.editor.Command');
goog.require('goog.editor.node');
goog.require('goog.editor.plugins.EnterHandler');
goog.require('goog.editor.range');
goog.require('goog.editor.style');
goog.require('goog.events.KeyCodes');
goog.require('goog.string');
goog.require('goog.style');
goog.require('goog.userAgent');
/**
* Plugin to handle enter keys. This subclass normalizes all browsers to use
* the given block tag on enter.
* @param {goog.dom.TagName} tag The type of tag to add on enter.
* @constructor
* @extends {goog.editor.plugins.EnterHandler}
*/
goog.editor.plugins.TagOnEnterHandler = function(tag) {
this.tag = tag;
goog.editor.plugins.EnterHandler.call(this);
};
goog.inherits(goog.editor.plugins.TagOnEnterHandler,
goog.editor.plugins.EnterHandler);
/** @override */
goog.editor.plugins.TagOnEnterHandler.prototype.getTrogClassId = function() {
return 'TagOnEnterHandler';
};
/** @override */
goog.editor.plugins.TagOnEnterHandler.prototype.getNonCollapsingBlankHtml =
function() {
if (this.tag == goog.dom.TagName.P) {
return '<p> </p>';
} else if (this.tag == goog.dom.TagName.DIV) {
return '<div><br></div>';
}
return '<br>';
};
/**
* This plugin is active on uneditable fields so it can provide a value for
* queryCommandValue calls asking for goog.editor.Command.BLOCKQUOTE.
* @return {boolean} True.
* @override
*/
goog.editor.plugins.TagOnEnterHandler.prototype.activeOnUneditableFields =
goog.functions.TRUE;
/** @override */
goog.editor.plugins.TagOnEnterHandler.prototype.isSupportedCommand = function(
command) {
return command == goog.editor.Command.DEFAULT_TAG;
};
/** @override */
goog.editor.plugins.TagOnEnterHandler.prototype.queryCommandValue = function(
command) {
return command == goog.editor.Command.DEFAULT_TAG ? this.tag : null;
};
/** @override */
goog.editor.plugins.TagOnEnterHandler.prototype.handleBackspaceInternal =
function(e, range) {
goog.editor.plugins.TagOnEnterHandler.superClass_.handleBackspaceInternal.
call(this, e, range);
if (goog.userAgent.GECKO) {
this.markBrToNotBeRemoved_(range, true);
}
};
/** @override */
goog.editor.plugins.TagOnEnterHandler.prototype.processParagraphTagsInternal =
function(e, split) {
if ((goog.userAgent.OPERA || goog.userAgent.IE) &&
this.tag != goog.dom.TagName.P) {
this.ensureBlockIeOpera(this.tag);
}
};
/** @override */
goog.editor.plugins.TagOnEnterHandler.prototype.handleDeleteGecko = function(
e) {
var range = this.getFieldObject().getRange();
var container = goog.editor.style.getContainer(
range && range.getContainerElement());
if (this.getFieldObject().getElement().lastChild == container &&
goog.editor.plugins.EnterHandler.isBrElem(container)) {
// Don't delete if it's the last node in the field and just has a BR.
e.preventDefault();
// TODO(user): I think we probably don't need to stopPropagation here
e.stopPropagation();
} else {
// Go ahead with deletion.
// Prevent an existing BR immediately following the selection being deleted
// from being removed in the keyup stage (as opposed to a BR added by FF
// after deletion, which we do remove).
this.markBrToNotBeRemoved_(range, false);
// Manually delete the selection if it's at a BR.
this.deleteBrGecko(e);
}
};
/** @override */
goog.editor.plugins.TagOnEnterHandler.prototype.handleKeyUpInternal = function(
e) {
if (goog.userAgent.GECKO) {
if (e.keyCode == goog.events.KeyCodes.DELETE) {
this.removeBrIfNecessary_(false);
} else if (e.keyCode == goog.events.KeyCodes.BACKSPACE) {
this.removeBrIfNecessary_(true);
}
} else if ((goog.userAgent.IE || goog.userAgent.OPERA) &&
e.keyCode == goog.events.KeyCodes.ENTER) {
this.ensureBlockIeOpera(this.tag, true);
}
// Safari uses DIVs by default.
};
/**
* String that matches a single BR tag or NBSP surrounded by non-breaking
* whitespace
* @type {string}
* @private
*/
goog.editor.plugins.TagOnEnterHandler.BrOrNbspSurroundedWithWhiteSpace_ =
'[\t\n\r ]*(<br[^>]*\/?>| )[\t\n\r ]*';
/**
* String that matches a single BR tag or NBSP surrounded by non-breaking
* whitespace
* @type {RegExp}
* @private
*/
goog.editor.plugins.TagOnEnterHandler.emptyLiRegExp_ = new RegExp('^' +
goog.editor.plugins.TagOnEnterHandler.BrOrNbspSurroundedWithWhiteSpace_ +
'$');
/**
* Ensures the current node is wrapped in the tag.
* @param {Node} node The node to ensure gets wrapped.
* @param {Element} container Element containing the selection.
* @return {Element} Element containing the selection, after the wrapping.
* @private
*/
goog.editor.plugins.TagOnEnterHandler.prototype.ensureNodeIsWrappedW3c_ =
function(node, container) {
if (container == this.getFieldObject().getElement()) {
// If the first block-level ancestor of cursor is the field,
// don't split the tree. Find all the text from the cursor
// to both block-level elements surrounding it (if they exist)
// and split the text into two elements.
// This is the IE contentEditable behavior.
// The easy way to do this is to wrap all the text in an element
// and then split the element as if the user had hit enter
// in the paragraph
// However, simply wrapping the text into an element creates problems
// if the text was already wrapped using some other element such as an
// anchor. For example, wrapping the text of
// <a href="">Text</a>
// would produce
// <a href=""><p>Text</p></a>
// which is not what we want. What we really want is
// <p><a href="">Text</a></p>
// So we need to search for an ancestor of position.node to be wrapped.
// We do this by iterating up the hierarchy of postiion.node until we've
// reached the node that's just under the container.
var isChildOfFn = function(child) {
return container == child.parentNode; };
var nodeToWrap = goog.dom.getAncestor(node, isChildOfFn, true);
container = goog.editor.plugins.TagOnEnterHandler.wrapInContainerW3c_(
this.tag, {node: nodeToWrap, offset: 0}, container);
}
return container;
};
/** @override */
goog.editor.plugins.TagOnEnterHandler.prototype.handleEnterWebkitInternal =
function(e) {
if (this.tag == goog.dom.TagName.DIV) {
var range = this.getFieldObject().getRange();
var container =
goog.editor.style.getContainer(range.getContainerElement());
var position = goog.editor.range.getDeepEndPoint(range, true);
container = this.ensureNodeIsWrappedW3c_(position.node, container);
goog.dom.Range.createCaret(position.node, position.offset).select();
}
};
/** @override */
goog.editor.plugins.TagOnEnterHandler.prototype.
handleEnterAtCursorGeckoInternal = function(e, wasCollapsed, range) {
// We use this because there are a few cases where FF default
// implementation doesn't follow IE's:
// -Inserts BRs into empty elements instead of NBSP which has nasty
// side effects w/ making/deleting selections
// -Hitting enter when your cursor is in the field itself. IE will
// create two elements. FF just inserts a BR.
// -Hitting enter inside an empty list-item doesn't create a block
// tag. It just splits the list and puts your cursor in the middle.
var li = null;
if (wasCollapsed) {
// Only break out of lists for collapsed selections.
li = goog.dom.getAncestorByTagNameAndClass(
range && range.getContainerElement(), goog.dom.TagName.LI);
}
var isEmptyLi = (li &&
li.innerHTML.match(
goog.editor.plugins.TagOnEnterHandler.emptyLiRegExp_));
var elementAfterCursor = isEmptyLi ?
this.breakOutOfEmptyListItemGecko_(li) :
this.handleRegularEnterGecko_();
// Move the cursor in front of "nodeAfterCursor", and make sure it
// is visible
this.scrollCursorIntoViewGecko_(elementAfterCursor);
// Fix for http://b/1991234 :
if (goog.editor.plugins.EnterHandler.isBrElem(elementAfterCursor)) {
// The first element in the new line is a line with just a BR and maybe some
// whitespace.
// Calling normalize() is needed because there might be empty text nodes
// before BR and empty text nodes cause the cursor position bug in Firefox.
// See http://b/5220858
elementAfterCursor.normalize();
var br = elementAfterCursor.getElementsByTagName(goog.dom.TagName.BR)[0];
if (br.previousSibling &&
br.previousSibling.nodeType == goog.dom.NodeType.TEXT) {
// If there is some whitespace before the BR, don't put the selection on
// the BR, put it in the text node that's there, otherwise when you type
// it will create adjacent text nodes.
elementAfterCursor = br.previousSibling;
}
}
goog.editor.range.selectNodeStart(elementAfterCursor);
e.preventDefault();
// TODO(user): I think we probably don't need to stopPropagation here
e.stopPropagation();
};
/**
* If The cursor is in an empty LI then break out of the list like in IE
* @param {Node} li LI to break out of.
* @return {Element} Element to put the cursor after.
* @private
*/
goog.editor.plugins.TagOnEnterHandler.prototype.breakOutOfEmptyListItemGecko_ =
function(li) {
// Do this as follows:
// 1. <ul>...<li> </li>...</ul>
// 2. <ul id='foo1'>...<li id='foo2'> </li>...</ul>
// 3. <ul id='foo1'>...</ul><p id='foo3'> </p><ul id='foo2'>...</ul>
// 4. <ul>...</ul><p> </p><ul>...</ul>
//
// There are a couple caveats to the above. If the UL is contained in
// a list, then the new node inserted is an LI, not a P.
// For an OL, it's all the same, except the tagname of course.
// Finally, it's possible that with the LI at the beginning or the end
// of the list that we'll end up with an empty list. So we special case
// those cases.
var listNode = li.parentNode;
var grandparent = listNode.parentNode;
var inSubList = grandparent.tagName == goog.dom.TagName.OL ||
grandparent.tagName == goog.dom.TagName.UL;
// TODO(robbyw): Should we apply the list or list item styles to the new node?
var newNode = goog.dom.getDomHelper(li).createElement(
inSubList ? goog.dom.TagName.LI : this.tag);
if (!li.previousSibling) {
goog.dom.insertSiblingBefore(newNode, listNode);
} else {
if (li.nextSibling) {
var listClone = listNode.cloneNode(false);
while (li.nextSibling) {
listClone.appendChild(li.nextSibling);
}
goog.dom.insertSiblingAfter(listClone, listNode);
}
goog.dom.insertSiblingAfter(newNode, listNode);
}
if (goog.editor.node.isEmpty(listNode)) {
goog.dom.removeNode(listNode);
}
goog.dom.removeNode(li);
newNode.innerHTML = ' ';
return newNode;
};
/**
* Wrap the text indicated by "position" in an HTML container of type
* "nodeName".
* @param {string} nodeName Type of container, e.g. "p" (paragraph).
* @param {Object} position The W3C cursor position object
* (from getCursorPositionW3c).
* @param {Node} container The field containing position.
* @return {Element} The container element that holds the contents from
* position.
* @private
*/
goog.editor.plugins.TagOnEnterHandler.wrapInContainerW3c_ = function(nodeName,
position, container) {
var start = position.node;
while (start.previousSibling &&
!goog.editor.style.isContainer(start.previousSibling)) {
start = start.previousSibling;
}
var end = position.node;
while (end.nextSibling &&
!goog.editor.style.isContainer(end.nextSibling)) {
end = end.nextSibling;
}
var para = container.ownerDocument.createElement(nodeName);
while (start != end) {
var newStart = start.nextSibling;
goog.dom.appendChild(para, start);
start = newStart;
}
var nextSibling = end.nextSibling;
goog.dom.appendChild(para, end);
container.insertBefore(para, nextSibling);
return para;
};
/**
* When we delete an element, FF inserts a BR. We want to strip that
* BR after the fact, but in the case where your cursor is at a character
* right before a BR and you delete that character, we don't want to
* strip it. So we detect this case on keydown and mark the BR as not needing
* removal.
* @param {goog.dom.AbstractRange} range The closure range object.
* @param {boolean} isBackspace Whether this is handling the backspace key.
* @private
*/
goog.editor.plugins.TagOnEnterHandler.prototype.markBrToNotBeRemoved_ =
function(range, isBackspace) {
var focusNode = range.getFocusNode();
var focusOffset = range.getFocusOffset();
var newEndOffset = isBackspace ? focusOffset : focusOffset + 1;
if (goog.editor.node.getLength(focusNode) == newEndOffset) {
var sibling = focusNode.nextSibling;
if (sibling && sibling.tagName == goog.dom.TagName.BR) {
this.brToKeep_ = sibling;
}
}
};
/**
* If we hit delete/backspace to merge elements, FF inserts a BR.
* We want to strip that BR. In markBrToNotBeRemoved, we detect if
* there was already a BR there before the delete/backspace so that
* we don't accidentally remove a user-inserted BR.
* @param {boolean} isBackSpace Whether this is handling the backspace key.
* @private
*/
goog.editor.plugins.TagOnEnterHandler.prototype.removeBrIfNecessary_ = function(
isBackSpace) {
var range = this.getFieldObject().getRange();
var focusNode = range.getFocusNode();
var focusOffset = range.getFocusOffset();
var sibling;
if (isBackSpace && focusNode.data == '') {
// nasty hack. sometimes firefox will backspace a paragraph and put
// the cursor before the BR. when it does this, the focusNode is
// an empty textnode.
sibling = focusNode.nextSibling;
} else if (isBackSpace && focusOffset == 0) {
var node = focusNode;
while (node && !node.previousSibling &&
node.parentNode != this.getFieldObject().getElement()) {
node = node.parentNode;
}
sibling = node.previousSibling;
} else if (focusNode.length == focusOffset) {
sibling = focusNode.nextSibling;
}
if (!sibling || sibling.tagName != goog.dom.TagName.BR ||
this.brToKeep_ == sibling) {
return;
}
goog.dom.removeNode(sibling);
if (focusNode.nodeType == goog.dom.NodeType.TEXT) {
// Sometimes firefox inserts extra whitespace. Do our best to deal.
// This is buggy though.
focusNode.data =
goog.editor.plugins.TagOnEnterHandler.trimTabsAndLineBreaks_(
focusNode.data);
// When we strip whitespace, make sure that our cursor is still at
// the end of the textnode.
goog.dom.Range.createCaret(focusNode,
Math.min(focusOffset, focusNode.length)).select();
}
};
/**
* Trim the tabs and line breaks from a string.
* @param {string} string String to trim.
* @return {string} Trimmed string.
* @private
*/
goog.editor.plugins.TagOnEnterHandler.trimTabsAndLineBreaks_ = function(
string) {
return string.replace(/^[\t\n\r]|[\t\n\r]$/g, '');
};
/**
* Called in response to a normal enter keystroke. It has the action of
* splitting elements.
* @return {Element} The node that the cursor should be before.
* @private
*/
goog.editor.plugins.TagOnEnterHandler.prototype.handleRegularEnterGecko_ =
function() {
var range = this.getFieldObject().getRange();
var container =
goog.editor.style.getContainer(range.getContainerElement());
var newNode;
if (goog.editor.plugins.EnterHandler.isBrElem(container)) {
if (container.tagName == goog.dom.TagName.BODY) {
// If the field contains only a single BR, this code ensures we don't
// try to clone the body tag.
container = this.ensureNodeIsWrappedW3c_(
container.getElementsByTagName(goog.dom.TagName.BR)[0],
container);
}
newNode = container.cloneNode(true);
goog.dom.insertSiblingAfter(newNode, container);
} else {
if (!container.firstChild) {
container.innerHTML = ' ';
}
var position = goog.editor.range.getDeepEndPoint(range, true);
container = this.ensureNodeIsWrappedW3c_(position.node, container);
newNode = goog.editor.plugins.TagOnEnterHandler.splitDomAndAppend_(
position.node, position.offset, container);
// If the left half and right half of the splitted node are anchors then
// that means the user pressed enter while the caret was inside
// an anchor tag and split it. The left half is the first anchor
// found while traversing the right branch of container. The right half
// is the first anchor found while traversing the left branch of newNode.
var leftAnchor =
goog.editor.plugins.TagOnEnterHandler.findAnchorInTraversal_(
container);
var rightAnchor =
goog.editor.plugins.TagOnEnterHandler.findAnchorInTraversal_(
newNode, true);
if (leftAnchor && rightAnchor &&
leftAnchor.tagName == goog.dom.TagName.A &&
rightAnchor.tagName == goog.dom.TagName.A) {
// If the original anchor (left anchor) is now empty, that means
// the user pressed [Enter] at the beginning of the anchor,
// in which case we we
// want to replace that anchor with its child nodes
// Otherwise, we take the second half of the splitted text and break
// it out of the anchor.
var anchorToRemove = goog.editor.node.isEmpty(leftAnchor, false) ?
leftAnchor : rightAnchor;
goog.dom.flattenElement(/** @type {Element} */ (anchorToRemove));
}
}
return /** @type {Element} */ (newNode);
};
/**
* Scroll the cursor into view, resulting from splitting the paragraph/adding
* a br. It behaves differently than scrollIntoView
* @param {Element} element The element immediately following the cursor. Will
* be used to determine how to scroll in order to make the cursor visible.
* CANNOT be a BR, as they do not have offsetHeight/offsetTop.
* @private
*/
goog.editor.plugins.TagOnEnterHandler.prototype.scrollCursorIntoViewGecko_ =
function(element) {
if (!this.getFieldObject().isFixedHeight()) {
return; // Only need to scroll fixed height fields.
}
var field = this.getFieldObject().getElement();
// Get the y position of the element we want to scroll to
var elementY = goog.style.getPageOffsetTop(element);
// Determine the height of that element, since we want the bottom of the
// element to be in view.
var bottomOfNode = elementY + element.offsetHeight;
var dom = this.getFieldDomHelper();
var win = this.getFieldDomHelper().getWindow();
var scrollY = dom.getDocumentScroll().y;
var viewportHeight = goog.dom.getViewportSize(win).height;
// If the botom of the element is outside the viewport, move it into view
if (bottomOfNode > viewportHeight + scrollY) {
// In standards mode, use the html element and not the body
if (field.tagName == goog.dom.TagName.BODY &&
goog.editor.node.isStandardsMode(field)) {
field = field.parentNode;
}
field.scrollTop = bottomOfNode - viewportHeight;
}
};
/**
* Splits the DOM tree around the given node and returns the node
* containing the second half of the tree. The first half of the tree
* is modified, but not removed from the DOM.
* @param {Node} positionNode Node to split at.
* @param {number} positionOffset Offset into positionNode to split at. If
* positionNode is a text node, this offset is an offset in to the text
* content of that node. Otherwise, positionOffset is an offset in to
* the childNodes array. All elements with child index of positionOffset
* or greater will be moved to the second half. If positionNode is an
* empty element, the dom will be split at that element, with positionNode
* ending up in the second half. positionOffset must be 0 in this case.
* @param {Node=} opt_root Node at which to stop splitting the dom (the root
* is also split).
* @return {Node} The node containing the second half of the tree.
* @private
*/
goog.editor.plugins.TagOnEnterHandler.splitDom_ = function(
positionNode, positionOffset, opt_root) {
if (!opt_root) opt_root = positionNode.ownerDocument.body;
// Split the node.
var textSplit = positionNode.nodeType == goog.dom.NodeType.TEXT;
var secondHalfOfSplitNode;
if (textSplit) {
if (goog.userAgent.IE &&
positionOffset == positionNode.nodeValue.length) {
// Since splitText fails in IE at the end of a node, we split it manually.
secondHalfOfSplitNode = goog.dom.getDomHelper(positionNode).
createTextNode('');
goog.dom.insertSiblingAfter(secondHalfOfSplitNode, positionNode);
} else {
secondHalfOfSplitNode = positionNode.splitText(positionOffset);
}
} else {
// Here we ensure positionNode is the last node in the first half of the
// resulting tree.
if (positionOffset) {
// Use offset as an index in to childNodes.
positionNode = positionNode.childNodes[positionOffset - 1];
} else {
// In this case, positionNode would be the last node in the first half
// of the tree, but we actually want to move it to the second half.
// Therefore we set secondHalfOfSplitNode to the same node.
positionNode = secondHalfOfSplitNode = positionNode.firstChild ||
positionNode;
}
}
// Create second half of the tree.
var secondHalf = goog.editor.node.splitDomTreeAt(
positionNode, secondHalfOfSplitNode, opt_root);
if (textSplit) {
// Join secondHalfOfSplitNode and its right text siblings together and
// then replace leading NonNbspWhiteSpace with a Nbsp. If
// secondHalfOfSplitNode has a right sibling that isn't a text node,
// then we can leave secondHalfOfSplitNode empty.
secondHalfOfSplitNode =
goog.editor.plugins.TagOnEnterHandler.joinTextNodes_(
secondHalfOfSplitNode, true);
goog.editor.plugins.TagOnEnterHandler.replaceWhiteSpaceWithNbsp_(
secondHalfOfSplitNode, true, !!secondHalfOfSplitNode.nextSibling);
// Join positionNode and its left text siblings together and then replace
// trailing NonNbspWhiteSpace with a Nbsp.
var firstHalf = goog.editor.plugins.TagOnEnterHandler.joinTextNodes_(
positionNode, false);
goog.editor.plugins.TagOnEnterHandler.replaceWhiteSpaceWithNbsp_(
firstHalf, false, false);
}
return secondHalf;
};
/**
* Splits the DOM tree around the given node and returns the node containing
* second half of the tree, which is appended after the old node. The first
* half of the tree is modified, but not removed from the DOM.
* @param {Node} positionNode Node to split at.
* @param {number} positionOffset Offset into positionNode to split at. If
* positionNode is a text node, this offset is an offset in to the text
* content of that node. Otherwise, positionOffset is an offset in to
* the childNodes array. All elements with child index of positionOffset
* or greater will be moved to the second half. If positionNode is an
* empty element, the dom will be split at that element, with positionNode
* ending up in the second half. positionOffset must be 0 in this case.
* @param {Node} node Node to split.
* @return {Node} The node containing the second half of the tree.
* @private
*/
goog.editor.plugins.TagOnEnterHandler.splitDomAndAppend_ = function(
positionNode, positionOffset, node) {
var newNode = goog.editor.plugins.TagOnEnterHandler.splitDom_(
positionNode, positionOffset, node);
goog.dom.insertSiblingAfter(newNode, node);
return newNode;
};
/**
* Joins node and its adjacent text nodes together.
* @param {Node} node The node to start joining.
* @param {boolean} moveForward Determines whether to join left siblings (false)
* or right siblings (true).
* @return {Node} The joined text node.
* @private
*/
goog.editor.plugins.TagOnEnterHandler.joinTextNodes_ = function(node,
moveForward) {
if (node && node.nodeName == '#text') {
var nextNodeFn = moveForward ? 'nextSibling' : 'previousSibling';
var prevNodeFn = moveForward ? 'previousSibling' : 'nextSibling';
var nodeValues = [node.nodeValue];
while (node[nextNodeFn] &&
node[nextNodeFn].nodeType == goog.dom.NodeType.TEXT) {
node = node[nextNodeFn];
nodeValues.push(node.nodeValue);
goog.dom.removeNode(node[prevNodeFn]);
}
if (!moveForward) {
nodeValues.reverse();
}
node.nodeValue = nodeValues.join('');
}
return node;
};
/**
* Replaces leading or trailing spaces of a text node to a single Nbsp.
* @param {Node} textNode The text node to search and replace white spaces.
* @param {boolean} fromStart Set to true to replace leading spaces, false to
* replace trailing spaces.
* @param {boolean} isLeaveEmpty Set to true to leave the node empty if the
* text node was empty in the first place, otherwise put a Nbsp into the
* text node.
* @private
*/
goog.editor.plugins.TagOnEnterHandler.replaceWhiteSpaceWithNbsp_ = function(
textNode, fromStart, isLeaveEmpty) {
var regExp = fromStart ? /^[ \t\r\n]+/ : /[ \t\r\n]+$/;
textNode.nodeValue = textNode.nodeValue.replace(regExp,
goog.string.Unicode.NBSP);
if (!isLeaveEmpty && textNode.nodeValue == '') {
textNode.nodeValue = goog.string.Unicode.NBSP;
}
};
/**
* Finds the first A element in a traversal from the input node. The input
* node itself is not included in the search.
* @param {Node} node The node to start searching from.
* @param {boolean=} opt_useFirstChild Whether to traverse along the first child
* (true) or last child (false).
* @return {Node} The first anchor node found in the search, or null if none
* was found.
* @private
*/
goog.editor.plugins.TagOnEnterHandler.findAnchorInTraversal_ = function(node,
opt_useFirstChild) {
while ((node = opt_useFirstChild ? node.firstChild : node.lastChild) &&
node.tagName != goog.dom.TagName.A) {
// Do nothing - advancement is handled in the condition.
}
return node;
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Code for managing series of undo-redo actions in the form of
* {@link goog.editor.plugins.UndoRedoState}s.
*
*/
goog.provide('goog.editor.plugins.UndoRedoManager');
goog.provide('goog.editor.plugins.UndoRedoManager.EventType');
goog.require('goog.editor.plugins.UndoRedoState');
goog.require('goog.events.EventTarget');
/**
* Manages undo and redo operations through a series of {@code UndoRedoState}s
* maintained on undo and redo stacks.
*
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.editor.plugins.UndoRedoManager = function() {
goog.events.EventTarget.call(this);
/**
* The maximum number of states on the undo stack at any time. Used to limit
* the memory footprint of the undo-redo stack.
* TODO(user) have a separate memory size based limit.
* @type {number}
* @private
*/
this.maxUndoDepth_ = 100;
/**
* The undo stack.
* @type {Array.<goog.editor.plugins.UndoRedoState>}
* @private
*/
this.undoStack_ = [];
/**
* The redo stack.
* @type {Array.<goog.editor.plugins.UndoRedoState>}
* @private
*/
this.redoStack_ = [];
/**
* A queue of pending undo or redo actions. Stored as objects with two
* properties: func and state. The func property stores the undo or redo
* function to be called, the state property stores the state that method
* came from.
* @type {Array.<Object>}
* @private
*/
this.pendingActions_ = [];
};
goog.inherits(goog.editor.plugins.UndoRedoManager, goog.events.EventTarget);
/**
* Event types for the events dispatched by undo-redo manager.
* @enum {string}
*/
goog.editor.plugins.UndoRedoManager.EventType = {
/**
* Signifies that he undo or redo stack transitioned between 0 and 1 states,
* meaning that the ability to peform undo or redo operations has changed.
*/
STATE_CHANGE: 'state_change',
/**
* Signifies that a state was just added to the undo stack. Events of this
* type will have a {@code state} property whose value is the state that
* was just added.
*/
STATE_ADDED: 'state_added',
/**
* Signifies that the undo method of a state is about to be called.
* Events of this type will have a {@code state} property whose value is the
* state whose undo action is about to be performed. If the event is cancelled
* the action does not proceed, but the state will still transition between
* stacks.
*/
BEFORE_UNDO: 'before_undo',
/**
* Signifies that the redo method of a state is about to be called.
* Events of this type will have a {@code state} property whose value is the
* state whose redo action is about to be performed. If the event is cancelled
* the action does not proceed, but the state will still transition between
* stacks.
*/
BEFORE_REDO: 'before_redo'
};
/**
* The key for the listener for the completion of the asynchronous state whose
* undo or redo action is in progress. Null if no action is in progress.
* @type {goog.events.Key}
* @private
*/
goog.editor.plugins.UndoRedoManager.prototype.inProgressActionKey_ = null;
/**
* Set the max undo stack depth (not the real memory usage).
* @param {number} depth Depth of the stack.
*/
goog.editor.plugins.UndoRedoManager.prototype.setMaxUndoDepth =
function(depth) {
this.maxUndoDepth_ = depth;
};
/**
* Add state to the undo stack. This clears the redo stack.
*
* @param {goog.editor.plugins.UndoRedoState} state The state to add to the undo
* stack.
*/
goog.editor.plugins.UndoRedoManager.prototype.addState = function(state) {
// TODO: is the state.equals check necessary?
if (this.undoStack_.length == 0 ||
!state.equals(this.undoStack_[this.undoStack_.length - 1])) {
this.undoStack_.push(state);
if (this.undoStack_.length > this.maxUndoDepth_) {
this.undoStack_.shift();
}
// Clobber the redo stack.
var redoLength = this.redoStack_.length;
this.redoStack_.length = 0;
this.dispatchEvent({
type: goog.editor.plugins.UndoRedoManager.EventType.STATE_ADDED,
state: state
});
// If the redo state had states on it, then clobbering the redo stack above
// has caused a state change.
if (this.undoStack_.length == 1 || redoLength) {
this.dispatchStateChange_();
}
}
};
/**
* Dispatches a STATE_CHANGE event with this manager as the target.
* @private
*/
goog.editor.plugins.UndoRedoManager.prototype.dispatchStateChange_ =
function() {
this.dispatchEvent(
goog.editor.plugins.UndoRedoManager.EventType.STATE_CHANGE);
};
/**
* Performs the undo operation of the state at the top of the undo stack, moving
* that state to the top of the redo stack. If the undo stack is empty, does
* nothing.
*/
goog.editor.plugins.UndoRedoManager.prototype.undo = function() {
this.shiftState_(this.undoStack_, this.redoStack_);
};
/**
* Performs the redo operation of the state at the top of the redo stack, moving
* that state to the top of the undo stack. If redo undo stack is empty, does
* nothing.
*/
goog.editor.plugins.UndoRedoManager.prototype.redo = function() {
this.shiftState_(this.redoStack_, this.undoStack_);
};
/**
* @return {boolean} Wether the undo stack has items on it, i.e., if it is
* possible to perform an undo operation.
*/
goog.editor.plugins.UndoRedoManager.prototype.hasUndoState = function() {
return this.undoStack_.length > 0;
};
/**
* @return {boolean} Wether the redo stack has items on it, i.e., if it is
* possible to perform a redo operation.
*/
goog.editor.plugins.UndoRedoManager.prototype.hasRedoState = function() {
return this.redoStack_.length > 0;
};
/**
* Move a state from one stack to the other, performing the appropriate undo
* or redo action.
*
* @param {Array.<goog.editor.plugins.UndoRedoState>} fromStack Stack to move
* the state from.
* @param {Array.<goog.editor.plugins.UndoRedoState>} toStack Stack to move
* the state to.
* @private
*/
goog.editor.plugins.UndoRedoManager.prototype.shiftState_ = function(
fromStack, toStack) {
if (fromStack.length) {
var state = fromStack.pop();
// Push the current state into the redo stack.
toStack.push(state);
this.addAction_({
type: fromStack == this.undoStack_ ?
goog.editor.plugins.UndoRedoManager.EventType.BEFORE_UNDO :
goog.editor.plugins.UndoRedoManager.EventType.BEFORE_REDO,
func: fromStack == this.undoStack_ ? state.undo : state.redo,
state: state
});
// If either stack transitioned between 0 and 1 in size then the ability
// to do an undo or redo has changed and we must dispatch a state change.
if (fromStack.length == 0 || toStack.length == 1) {
this.dispatchStateChange_();
}
}
};
/**
* Adds an action to the queue of pending undo or redo actions. If no actions
* are pending, immediately performs the action.
*
* @param {Object} action An undo or redo action. Stored as an object with two
* properties: func and state. The func property stores the undo or redo
* function to be called, the state property stores the state that method
* came from.
* @private
*/
goog.editor.plugins.UndoRedoManager.prototype.addAction_ = function(action) {
this.pendingActions_.push(action);
if (this.pendingActions_.length == 1) {
this.doAction_();
}
};
/**
* Executes the action at the front of the pending actions queue. If an action
* is already in progress or the queue is empty, does nothing.
* @private
*/
goog.editor.plugins.UndoRedoManager.prototype.doAction_ = function() {
if (this.inProgressActionKey_ || this.pendingActions_.length == 0) {
return;
}
var action = this.pendingActions_.shift();
var e = {
type: action.type,
state: action.state
};
if (this.dispatchEvent(e)) {
if (action.state.isAsynchronous()) {
this.inProgressActionKey_ = goog.events.listen(action.state,
goog.editor.plugins.UndoRedoState.ACTION_COMPLETED,
this.finishAction_, false, this);
action.func.call(action.state);
} else {
action.func.call(action.state);
this.doAction_();
}
}
};
/**
* Finishes processing the current in progress action, starting the next queued
* action if one exists.
* @private
*/
goog.editor.plugins.UndoRedoManager.prototype.finishAction_ = function() {
goog.events.unlistenByKey(/** @type {number} */ (this.inProgressActionKey_));
this.inProgressActionKey_ = null;
this.doAction_();
};
/**
* Clears the undo and redo stacks.
*/
goog.editor.plugins.UndoRedoManager.prototype.clearHistory = function() {
if (this.undoStack_.length > 0 || this.redoStack_.length > 0) {
this.undoStack_.length = 0;
this.redoStack_.length = 0;
this.dispatchStateChange_();
}
};
/**
* @return {goog.editor.plugins.UndoRedoState|undefined} The state at the top of
* the undo stack without removing it from the stack.
*/
goog.editor.plugins.UndoRedoManager.prototype.undoPeek = function() {
return this.undoStack_[this.undoStack_.length - 1];
};
/**
* @return {goog.editor.plugins.UndoRedoState|undefined} The state at the top of
* the redo stack without removing it from the stack.
*/
goog.editor.plugins.UndoRedoManager.prototype.redoPeek = function() {
return this.redoStack_[this.redoStack_.length - 1];
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A plugin that fills the field with lorem ipsum text when it's
* empty and does not have the focus. Applies to both editable and uneditable
* fields.
*
*/
goog.provide('goog.editor.plugins.LoremIpsum');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.editor.Command');
goog.require('goog.editor.Plugin');
goog.require('goog.editor.node');
goog.require('goog.functions');
/**
* A plugin that manages lorem ipsum state of editable fields.
* @param {string} message The lorem ipsum message.
* @constructor
* @extends {goog.editor.Plugin}
*/
goog.editor.plugins.LoremIpsum = function(message) {
goog.editor.Plugin.call(this);
/**
* The lorem ipsum message.
* @type {string}
* @private
*/
this.message_ = message;
};
goog.inherits(goog.editor.plugins.LoremIpsum, goog.editor.Plugin);
/** @override */
goog.editor.plugins.LoremIpsum.prototype.getTrogClassId =
goog.functions.constant('LoremIpsum');
/** @override */
goog.editor.plugins.LoremIpsum.prototype.activeOnUneditableFields =
goog.functions.TRUE;
/**
* Whether the field is currently filled with lorem ipsum text.
* @type {boolean}
* @private
*/
goog.editor.plugins.LoremIpsum.prototype.usingLorem_ = false;
/**
* Handles queryCommandValue.
* @param {string} command The command to query.
* @return {boolean} The result.
* @override
*/
goog.editor.plugins.LoremIpsum.prototype.queryCommandValue = function(command) {
return command == goog.editor.Command.USING_LOREM && this.usingLorem_;
};
/**
* Handles execCommand.
* @param {string} command The command to execute.
* Should be CLEAR_LOREM or UPDATE_LOREM.
* @param {*=} opt_placeCursor Whether to place the cursor in the field
* after clearing lorem. Should be a boolean.
* @override
*/
goog.editor.plugins.LoremIpsum.prototype.execCommand = function(command,
opt_placeCursor) {
if (command == goog.editor.Command.CLEAR_LOREM) {
this.clearLorem_(!!opt_placeCursor);
} else if (command == goog.editor.Command.UPDATE_LOREM) {
this.updateLorem_();
}
};
/** @override */
goog.editor.plugins.LoremIpsum.prototype.isSupportedCommand =
function(command) {
return command == goog.editor.Command.CLEAR_LOREM ||
command == goog.editor.Command.UPDATE_LOREM ||
command == goog.editor.Command.USING_LOREM;
};
/**
* Set the lorem ipsum text in a goog.editor.Field if needed.
* @private
*/
goog.editor.plugins.LoremIpsum.prototype.updateLorem_ = function() {
// Try to apply lorem ipsum if:
// 1) We have lorem ipsum text
// 2) There's not a dialog open, as that screws
// with the dialog's ability to properly restore the selection
// on dialog close (since the DOM nodes would get clobbered in FF)
// 3) We're not using lorem already
// 4) The field is not currently active (doesn't have focus).
var fieldObj = this.getFieldObject();
if (!this.usingLorem_ &&
!fieldObj.inModalMode() &&
goog.editor.Field.getActiveFieldId() != fieldObj.id) {
var field = fieldObj.getElement();
if (!field) {
// Fallback on the original element. This is needed by
// fields managed by click-to-edit.
field = fieldObj.getOriginalElement();
}
goog.asserts.assert(field);
if (goog.editor.node.isEmpty(field)) {
this.usingLorem_ = true;
// Save the old font style so it can be restored when we
// clear the lorem ipsum style.
this.oldFontStyle_ = field.style.fontStyle;
field.style.fontStyle = 'italic';
fieldObj.setHtml(true, this.message_, true);
}
}
};
/**
* Clear an EditableField's lorem ipsum and put in initial text if needed.
*
* If using click-to-edit mode (where Trogedit manages whether the field
* is editable), this works for both editable and uneditable fields.
*
* TODO(user): Is this really necessary? See TODO below.
* @param {boolean=} opt_placeCursor Whether to place the cursor in the field
* after clearing lorem.
* @private
*/
goog.editor.plugins.LoremIpsum.prototype.clearLorem_ = function(
opt_placeCursor) {
// Don't mess with lorem state when a dialog is open as that screws
// with the dialog's ability to properly restore the selection
// on dialog close (since the DOM nodes would get clobbered)
var fieldObj = this.getFieldObject();
if (this.usingLorem_ && !fieldObj.inModalMode()) {
var field = fieldObj.getElement();
if (!field) {
// Fallback on the original element. This is needed by
// fields managed by click-to-edit.
field = fieldObj.getOriginalElement();
}
goog.asserts.assert(field);
this.usingLorem_ = false;
field.style.fontStyle = this.oldFontStyle_;
fieldObj.setHtml(true, null, true);
// TODO(nicksantos): I'm pretty sure that this is a hack, but talk to
// Julie about why this is necessary and what to do with it. Really,
// we need to figure out where it's necessary and remove it where it's
// not. Safari never places the cursor on its own willpower.
if (opt_placeCursor && fieldObj.isLoaded()) {
if (goog.userAgent.WEBKIT) {
goog.dom.getOwnerDocument(fieldObj.getElement()).body.focus();
fieldObj.focusAndPlaceCursorAtStart();
} else if (goog.userAgent.OPERA) {
fieldObj.placeCursorAtStart();
}
}
}
};
| 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.
// All Rights Reserved.
/**
* @fileoverview Class to encapsulate an editable field. Always uses an
* iframe to contain the editable area, never inherits the style of the
* surrounding page, and is always a fixed height.
*
* @see ../demos/editor/editor.html
* @see ../demos/editor/field_basic.html
*/
goog.provide('goog.editor.Field');
goog.provide('goog.editor.Field.EventType');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.Role');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.async.Delay');
goog.require('goog.debug.Logger');
goog.require('goog.dom');
goog.require('goog.dom.Range');
goog.require('goog.dom.TagName');
goog.require('goog.editor.BrowserFeature');
goog.require('goog.editor.Command');
goog.require('goog.editor.Plugin');
goog.require('goog.editor.icontent');
goog.require('goog.editor.icontent.FieldFormatInfo');
goog.require('goog.editor.icontent.FieldStyleInfo');
goog.require('goog.editor.node');
goog.require('goog.editor.range');
goog.require('goog.events');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.functions');
goog.require('goog.string');
goog.require('goog.string.Unicode');
goog.require('goog.style');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');
/**
* This class encapsulates an editable field.
*
* event: load Fires when the field is loaded
* event: unload Fires when the field is unloaded (made not editable)
*
* event: beforechange Fires before the content of the field might change
*
* event: delayedchange Fires a short time after field has changed. If multiple
* change events happen really close to each other only
* the last one will trigger the delayedchange event.
*
* event: beforefocus Fires before the field becomes active
* event: focus Fires when the field becomes active. Fires after the blur event
* event: blur Fires when the field becomes inactive
*
* TODO: figure out if blur or beforefocus fires first in IE and make FF match
*
* @param {string} id An identifer for the field. This is used to find the
* field and the element associated with this field.
* @param {Document=} opt_doc The document that the element with the given
* id can be found in. If not provided, the default document is used.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.editor.Field = function(id, opt_doc) {
goog.events.EventTarget.call(this);
/**
* The id for this editable field, which must match the id of the element
* associated with this field.
* @type {string}
*/
this.id = id;
/**
* The hash code for this field. Should be equal to the id.
* @type {string}
* @private
*/
this.hashCode_ = id;
/**
* Dom helper for the editable node.
* @type {goog.dom.DomHelper}
* @protected
*/
this.editableDomHelper = null;
/**
* Map of class id to registered plugin.
* @type {Object}
* @private
*/
this.plugins_ = {};
/**
* Plugins registered on this field, indexed by the goog.editor.Plugin.Op
* that they support.
* @type {Object.<Array>}
* @private
*/
this.indexedPlugins_ = {};
for (var op in goog.editor.Plugin.OPCODE) {
this.indexedPlugins_[op] = [];
}
/**
* Additional styles to install for the editable field.
* @type {string}
* @protected
*/
this.cssStyles = '';
// The field will not listen to change events until it has finished loading
this.stoppedEvents_ = {};
this.stopEvent(goog.editor.Field.EventType.CHANGE);
this.stopEvent(goog.editor.Field.EventType.DELAYEDCHANGE);
this.isModified_ = false;
this.isEverModified_ = false;
this.delayedChangeTimer_ = new goog.async.Delay(this.dispatchDelayedChange_,
goog.editor.Field.DELAYED_CHANGE_FREQUENCY, this);
this.debouncedEvents_ = {};
for (var key in goog.editor.Field.EventType) {
this.debouncedEvents_[goog.editor.Field.EventType[key]] = 0;
}
if (goog.editor.BrowserFeature.USE_MUTATION_EVENTS) {
this.changeTimerGecko_ = new goog.async.Delay(this.handleChange,
goog.editor.Field.CHANGE_FREQUENCY, this);
}
/**
* @type {goog.events.EventHandler}
* @protected
*/
this.eventRegister = new goog.events.EventHandler(this);
// Wrappers around this field, to be disposed when the field is disposed.
this.wrappers_ = [];
this.loadState_ = goog.editor.Field.LoadState_.UNEDITABLE;
var doc = opt_doc || document;
/**
* @type {!goog.dom.DomHelper}
* @protected
*/
this.originalDomHelper = goog.dom.getDomHelper(doc);
/**
* @type {Element}
* @protected
*/
this.originalElement = this.originalDomHelper.getElement(this.id);
// Default to the same window as the field is in.
this.appWindow_ = this.originalDomHelper.getWindow();
};
goog.inherits(goog.editor.Field, goog.events.EventTarget);
/**
* The editable dom node.
* @type {Element}
* TODO(user): Make this private!
*/
goog.editor.Field.prototype.field = null;
/**
* The original node that is being made editable, or null if it has
* not yet been found.
* @type {Element}
* @protected
*/
goog.editor.Field.prototype.originalElement = null;
/**
* Logging object.
* @type {goog.debug.Logger}
* @protected
*/
goog.editor.Field.prototype.logger =
goog.debug.Logger.getLogger('goog.editor.Field');
/**
* Event types that can be stopped/started.
* @enum {string}
*/
goog.editor.Field.EventType = {
/**
* Dispatched when the command state of the selection may have changed. This
* event should be listened to for updating toolbar state.
*/
COMMAND_VALUE_CHANGE: 'cvc',
/**
* Dispatched when the field is loaded and ready to use.
*/
LOAD: 'load',
/**
* Dispatched when the field is fully unloaded and uneditable.
*/
UNLOAD: 'unload',
/**
* Dispatched before the field contents are changed.
*/
BEFORECHANGE: 'beforechange',
/**
* Dispatched when the field contents change, in FF only.
* Used for internal resizing, please do not use.
*/
CHANGE: 'change',
/**
* Dispatched on a slight delay after changes are made.
* Use for autosave, or other times your app needs to know
* that the field contents changed.
*/
DELAYEDCHANGE: 'delayedchange',
/**
* Dispatched before focus in moved into the field.
*/
BEFOREFOCUS: 'beforefocus',
/**
* Dispatched when focus is moved into the field.
*/
FOCUS: 'focus',
/**
* Dispatched when the field is blurred.
*/
BLUR: 'blur',
/**
* Dispatched before tab is handled by the field. This is a legacy way
* of controlling tab behavior. Use trog.plugins.AbstractTabHandler now.
*/
BEFORETAB: 'beforetab',
/**
* Dispatched after the iframe containing the field is resized, so that UI
* components which contain it can respond.
*/
IFRAME_RESIZED: 'ifrsz',
/**
* Dispatched when the selection changes.
* Use handleSelectionChange from plugin API instead of listening
* directly to this event.
*/
SELECTIONCHANGE: 'selectionchange'
};
/**
* The load state of the field.
* @enum {number}
* @private
*/
goog.editor.Field.LoadState_ = {
UNEDITABLE: 0,
LOADING: 1,
EDITABLE: 2
};
/**
* The amount of time that a debounce blocks an event.
* TODO(nicksantos): As of 9/30/07, this is only used for blocking
* a keyup event after a keydown. We might need to tweak this for other
* types of events. Maybe have a per-event debounce time?
* @type {number}
* @private
*/
goog.editor.Field.DEBOUNCE_TIME_MS_ = 500;
/**
* There is at most one "active" field at a time. By "active" field, we mean
* a field that has focus and is being used.
* @type {?string}
* @private
*/
goog.editor.Field.activeFieldId_ = null;
/**
* Whether this field is in "modal interaction" mode. This usually
* means that it's being edited by a dialog.
* @type {boolean}
* @private
*/
goog.editor.Field.prototype.inModalMode_ = false;
/**
* The window where dialogs and bubbles should be rendered.
* @type {!Window}
* @private
*/
goog.editor.Field.prototype.appWindow_;
/**
* The dom helper for the node to be made editable.
* @type {goog.dom.DomHelper}
* @protected
*/
goog.editor.Field.prototype.originalDomHelper;
/**
* Target node to be used when dispatching SELECTIONCHANGE asynchronously on
* mouseup (to avoid IE quirk). Should be set just before starting the timer and
* nulled right after consuming.
* @type {Node}
* @private
*/
goog.editor.Field.prototype.selectionChangeTarget_;
/**
* Flag controlling wether to capture mouse up events on the window or not.
* @type {boolean}
* @private
*/
goog.editor.Field.prototype.useWindowMouseUp_ = false;
/**
* FLag indicating the handling of a mouse event sequence.
* @type {boolean}
* @private
*/
goog.editor.Field.prototype.waitingForMouseUp_ = false;
/**
* Sets the active field id.
* @param {?string} fieldId The active field id.
*/
goog.editor.Field.setActiveFieldId = function(fieldId) {
goog.editor.Field.activeFieldId_ = fieldId;
};
/**
* @return {?string} The id of the active field.
*/
goog.editor.Field.getActiveFieldId = function() {
return goog.editor.Field.activeFieldId_;
};
/**
* Sets flag to control whether to use window mouse up after seeing
* a mouse down operation on the field.
* @param {boolean} flag True to track window mouse up.
*/
goog.editor.Field.prototype.setUseWindowMouseUp = function(flag) {
goog.asserts.assert(!flag || !this.usesIframe(),
'procssing window mouse up should only be enabled when not using iframe');
this.useWindowMouseUp_ = flag;
};
/**
* @return {boolean} Whether we're in modal interaction mode. When this
* returns true, another plugin is interacting with the field contents
* in a synchronous way, and expects you not to make changes to
* the field's DOM structure or selection.
*/
goog.editor.Field.prototype.inModalMode = function() {
return this.inModalMode_;
};
/**
* @param {boolean} inModalMode Sets whether we're in modal interaction mode.
*/
goog.editor.Field.prototype.setModalMode = function(inModalMode) {
this.inModalMode_ = inModalMode;
};
/**
* Returns a string usable as a hash code for this field. For field's
* that were created with an id, the hash code is guaranteed to be the id.
* TODO(user): I think we can get rid of this. Seems only used from editor.
* @return {string} The hash code for this editable field.
*/
goog.editor.Field.prototype.getHashCode = function() {
return this.hashCode_;
};
/**
* Returns the editable DOM element or null if this field
* is not editable.
* <p>On IE or Safari this is the element with contentEditable=true
* (in whitebox mode, the iFrame body).
* <p>On Gecko this is the iFrame body
* TODO(user): How do we word this for subclass version?
* @return {Element} The editable DOM element, defined as above.
*/
goog.editor.Field.prototype.getElement = function() {
return this.field;
};
/**
* Returns original DOM element that is being made editable by Trogedit or
* null if that element has not yet been found in the appropriate document.
* @return {Element} The original element.
*/
goog.editor.Field.prototype.getOriginalElement = function() {
return this.originalElement;
};
/**
* Registers a keyboard event listener on the field. This is necessary for
* Gecko since the fields are contained in an iFrame and there is no way to
* auto-propagate key events up to the main window.
* @param {string|Array.<string>} type Event type to listen for or array of
* event types, for example goog.events.EventType.KEYDOWN.
* @param {Function} listener Function to be used as the listener.
* @param {boolean=} opt_capture Whether to use capture phase (optional,
* defaults to false).
* @param {Object=} opt_handler Object in whose scope to call the listener.
*/
goog.editor.Field.prototype.addListener = function(type, listener, opt_capture,
opt_handler) {
var elem = this.getElement();
// On Gecko, keyboard events only reliably fire on the document element when
// using an iframe.
if (goog.editor.BrowserFeature.USE_DOCUMENT_FOR_KEY_EVENTS && elem &&
this.usesIframe()) {
elem = elem.ownerDocument;
}
this.eventRegister.listen(elem, type, listener, opt_capture, opt_handler);
};
/**
* Returns the registered plugin with the given classId.
* @param {string} classId classId of the plugin.
* @return {goog.editor.Plugin} Registered plugin with the given classId.
*/
goog.editor.Field.prototype.getPluginByClassId = function(classId) {
return this.plugins_[classId];
};
/**
* Registers the plugin with the editable field.
* @param {goog.editor.Plugin} plugin The plugin to register.
*/
goog.editor.Field.prototype.registerPlugin = function(plugin) {
var classId = plugin.getTrogClassId();
if (this.plugins_[classId]) {
this.logger.severe('Cannot register the same class of plugin twice.');
}
this.plugins_[classId] = plugin;
// Only key events and execute should have these has* functions with a custom
// handler array since they need to be very careful about performance.
// The rest of the plugin hooks should be event-based.
for (var op in goog.editor.Plugin.OPCODE) {
var opcode = goog.editor.Plugin.OPCODE[op];
if (plugin[opcode]) {
this.indexedPlugins_[op].push(plugin);
}
}
plugin.registerFieldObject(this);
// By default we enable all plugins for fields that are currently loaded.
if (this.isLoaded()) {
plugin.enable(this);
}
};
/**
* Unregisters the plugin with this field.
* @param {goog.editor.Plugin} plugin The plugin to unregister.
*/
goog.editor.Field.prototype.unregisterPlugin = function(plugin) {
var classId = plugin.getTrogClassId();
if (!this.plugins_[classId]) {
this.logger.severe('Cannot unregister a plugin that isn\'t registered.');
}
delete this.plugins_[classId];
for (var op in goog.editor.Plugin.OPCODE) {
var opcode = goog.editor.Plugin.OPCODE[op];
if (plugin[opcode]) {
goog.array.remove(this.indexedPlugins_[op], plugin);
}
}
plugin.unregisterFieldObject(this);
};
/**
* Sets the value that will replace the style attribute of this field's
* element when the field is made non-editable. This method is called with the
* current value of the style attribute when the field is made editable.
* @param {string} cssText The value of the style attribute.
*/
goog.editor.Field.prototype.setInitialStyle = function(cssText) {
this.cssText = cssText;
};
/**
* Reset the properties on the original field element to how it was before
* it was made editable.
*/
goog.editor.Field.prototype.resetOriginalElemProperties = function() {
var field = this.getOriginalElement();
field.removeAttribute('contentEditable');
field.removeAttribute('g_editable');
field.removeAttribute('role');
if (!this.id) {
field.removeAttribute('id');
} else {
field.id = this.id;
}
field.className = this.savedClassName_ || '';
var cssText = this.cssText;
if (!cssText) {
field.removeAttribute('style');
} else {
goog.dom.setProperties(field, {'style' : cssText});
}
if (goog.isString(this.originalFieldLineHeight_)) {
goog.style.setStyle(field, 'lineHeight', this.originalFieldLineHeight_);
this.originalFieldLineHeight_ = null;
}
};
/**
* Checks the modified state of the field.
* Note: Changes that take place while the goog.editor.Field.EventType.CHANGE
* event is stopped do not effect the modified state.
* @param {boolean=} opt_useIsEverModified Set to true to check if the field
* has ever been modified since it was created, otherwise checks if the field
* has been modified since the last goog.editor.Field.EventType.DELAYEDCHANGE
* event was dispatched.
* @return {boolean} Whether the field has been modified.
*/
goog.editor.Field.prototype.isModified = function(opt_useIsEverModified) {
return opt_useIsEverModified ? this.isEverModified_ : this.isModified_;
};
/**
* Number of milliseconds after a change when the change event should be fired.
* @type {number}
*/
goog.editor.Field.CHANGE_FREQUENCY = 15;
/**
* Number of milliseconds between delayed change events.
* @type {number}
*/
goog.editor.Field.DELAYED_CHANGE_FREQUENCY = 250;
/**
* @return {boolean} Whether the field is implemented as an iframe.
*/
goog.editor.Field.prototype.usesIframe = goog.functions.TRUE;
/**
* @return {boolean} Whether the field should be rendered with a fixed
* height, or should expand to fit its contents.
*/
goog.editor.Field.prototype.isFixedHeight = goog.functions.TRUE;
/**
* @return {boolean} Whether the field should be refocused on input.
* This is a workaround for the iOS bug that text input doesn't work
* when the main window listens touch events.
*/
goog.editor.Field.prototype.shouldRefocusOnInputMobileSafari =
goog.functions.FALSE;
/**
* Map of keyCodes (not charCodes) that cause changes in the field contents.
* @type {Object}
* @private
*/
goog.editor.Field.KEYS_CAUSING_CHANGES_ = {
46: true, // DEL
8: true // BACKSPACE
};
if (!goog.userAgent.IE) {
// Only IE doesn't change the field by default upon tab.
// TODO(user): This really isn't right now that we have tab plugins.
goog.editor.Field.KEYS_CAUSING_CHANGES_[9] = true; // TAB
}
/**
* Map of keyCodes (not charCodes) that when used in conjunction with the
* Ctrl key cause changes in the field contents. These are the keys that are
* not handled by basic formatting trogedit plugins.
* @type {Object}
* @private
*/
goog.editor.Field.CTRL_KEYS_CAUSING_CHANGES_ = {
86: true, // V
88: true // X
};
if (goog.userAgent.WINDOWS && !goog.userAgent.GECKO) {
// In IE and Webkit, input from IME (Input Method Editor) does not generate a
// keypress event so we have to rely on the keydown event. This way we have
// false positives while the user is using keyboard to select the
// character to input, but it is still better than the false negatives
// that ignores user's final input at all.
goog.editor.Field.KEYS_CAUSING_CHANGES_[229] = true; // from IME;
}
/**
* Returns true if the keypress generates a change in contents.
* @param {goog.events.BrowserEvent} e The event.
* @param {boolean} testAllKeys True to test for all types of generating keys.
* False to test for only the keys found in
* goog.editor.Field.KEYS_CAUSING_CHANGES_.
* @return {boolean} Whether the keypress generates a change in contents.
* @private
*/
goog.editor.Field.isGeneratingKey_ = function(e, testAllKeys) {
if (goog.editor.Field.isSpecialGeneratingKey_(e)) {
return true;
}
return !!(testAllKeys && !(e.ctrlKey || e.metaKey) &&
(!goog.userAgent.GECKO || e.charCode));
};
/**
* Returns true if the keypress generates a change in the contents.
* due to a special key listed in goog.editor.Field.KEYS_CAUSING_CHANGES_
* @param {goog.events.BrowserEvent} e The event.
* @return {boolean} Whether the keypress generated a change in the contents.
* @private
*/
goog.editor.Field.isSpecialGeneratingKey_ = function(e) {
var testCtrlKeys = (e.ctrlKey || e.metaKey) &&
e.keyCode in goog.editor.Field.CTRL_KEYS_CAUSING_CHANGES_;
var testRegularKeys = !(e.ctrlKey || e.metaKey) &&
e.keyCode in goog.editor.Field.KEYS_CAUSING_CHANGES_;
return testCtrlKeys || testRegularKeys;
};
/**
* Sets the application window.
* @param {!Window} appWindow The window where dialogs and bubbles should be
* rendered.
*/
goog.editor.Field.prototype.setAppWindow = function(appWindow) {
this.appWindow_ = appWindow;
};
/**
* Returns the "application" window, where dialogs and bubbles
* should be rendered.
* @return {!Window} The window.
*/
goog.editor.Field.prototype.getAppWindow = function() {
return this.appWindow_;
};
/**
* Sets the zIndex that the field should be based off of.
* TODO(user): Get rid of this completely. Here for Sites.
* Should this be set directly on UI plugins?
*
* @param {number} zindex The base zIndex of the editor.
*/
goog.editor.Field.prototype.setBaseZindex = function(zindex) {
this.baseZindex_ = zindex;
};
/**
* Returns the zindex of the base level of the field.
*
* @return {number} The base zindex of the editor.
*/
goog.editor.Field.prototype.getBaseZindex = function() {
return this.baseZindex_ || 0;
};
/**
* Sets up the field object and window util of this field, and enables this
* editable field with all registered plugins.
* This is essential to the initialization of the field.
* It must be called when the field becomes fully loaded and editable.
* @param {Element} field The field property.
* @protected
*/
goog.editor.Field.prototype.setupFieldObject = function(field) {
this.loadState_ = goog.editor.Field.LoadState_.EDITABLE;
this.field = field;
this.editableDomHelper = goog.dom.getDomHelper(field);
this.isModified_ = false;
this.isEverModified_ = false;
field.setAttribute('g_editable', 'true');
goog.a11y.aria.setRole(field, goog.a11y.aria.Role.TEXTBOX);
};
/**
* Help make the field not editable by setting internal data structures to null,
* and disabling this field with all registered plugins.
* @private
*/
goog.editor.Field.prototype.tearDownFieldObject_ = function() {
this.loadState_ = goog.editor.Field.LoadState_.UNEDITABLE;
for (var classId in this.plugins_) {
var plugin = this.plugins_[classId];
if (!plugin.activeOnUneditableFields()) {
plugin.disable(this);
}
}
this.field = null;
this.editableDomHelper = null;
};
/**
* Initialize listeners on the field.
* @private
*/
goog.editor.Field.prototype.setupChangeListeners_ = function() {
if ((goog.userAgent.product.IPHONE || goog.userAgent.product.IPAD) &&
this.usesIframe() && this.shouldRefocusOnInputMobileSafari()) {
// This is a workaround for the iOS bug that text input doesn't work
// when the main window listens touch events.
var editWindow = this.getEditableDomHelper().getWindow();
this.boundRefocusListenerMobileSafari_ =
goog.bind(editWindow.focus, editWindow);
editWindow.addEventListener(goog.events.EventType.KEYDOWN,
this.boundRefocusListenerMobileSafari_, false);
editWindow.addEventListener(goog.events.EventType.TOUCHEND,
this.boundRefocusListenerMobileSafari_, false);
}
if (goog.userAgent.OPERA && this.usesIframe()) {
// We can't use addListener here because we need to listen on the window,
// and removing listeners on window objects from the event register throws
// an exception if the window is closed.
this.boundFocusListenerOpera_ =
goog.bind(this.dispatchFocusAndBeforeFocus_, this);
this.boundBlurListenerOpera_ =
goog.bind(this.dispatchBlur, this);
var editWindow = this.getEditableDomHelper().getWindow();
editWindow.addEventListener(goog.events.EventType.FOCUS,
this.boundFocusListenerOpera_, false);
editWindow.addEventListener(goog.events.EventType.BLUR,
this.boundBlurListenerOpera_, false);
} else {
if (goog.editor.BrowserFeature.SUPPORTS_FOCUSIN) {
this.addListener(goog.events.EventType.FOCUS, this.dispatchFocus_);
this.addListener(goog.events.EventType.FOCUSIN,
this.dispatchBeforeFocus_);
} else {
this.addListener(goog.events.EventType.FOCUS,
this.dispatchFocusAndBeforeFocus_);
}
this.addListener(goog.events.EventType.BLUR, this.dispatchBlur,
goog.editor.BrowserFeature.USE_MUTATION_EVENTS);
}
if (goog.editor.BrowserFeature.USE_MUTATION_EVENTS) {
// Ways to detect changes in Mozilla:
//
// keypress - check event.charCode (only typable characters has a
// charCode), but also keyboard commands lile Ctrl+C will
// return a charCode.
// dragdrop - fires when the user drops something. This does not necessary
// lead to a change but we cannot detect if it will or not
//
// Known Issues: We cannot detect cut and paste using menus
// We cannot detect when someone moves something out of the
// field using drag and drop.
//
this.setupMutationEventHandlersGecko();
} else {
// Ways to detect that a change is about to happen in other browsers.
// (IE and Safari have these events. Opera appears to work, but we haven't
// researched it.)
//
// onbeforepaste
// onbeforecut
// ondrop - happens when the user drops something on the editable text
// field the value at this time does not contain the dropped text
// ondragleave - when the user drags something from the current document.
// This might not cause a change if the action was copy
// instead of move
// onkeypress - IE only fires keypress events if the key will generate
// output. It will not trigger for delete and backspace
// onkeydown - For delete and backspace
//
// known issues: IE triggers beforepaste just by opening the edit menu
// delete at the end should not cause beforechange
// backspace at the beginning should not cause beforechange
// see above in ondragleave
// TODO(user): Why don't we dispatchBeforeChange from the
// handleDrop event for all browsers?
this.addListener(['beforecut', 'beforepaste', 'drop', 'dragend'],
this.dispatchBeforeChange);
this.addListener(['cut', 'paste'],
goog.functions.lock(this.dispatchChange));
this.addListener('drop', this.handleDrop_);
}
// TODO(user): Figure out why we use dragend vs dragdrop and
// document this better.
var dropEventName = goog.userAgent.WEBKIT ? 'dragend' : 'dragdrop';
this.addListener(dropEventName, this.handleDrop_);
this.addListener(goog.events.EventType.KEYDOWN, this.handleKeyDown_);
this.addListener(goog.events.EventType.KEYPRESS, this.handleKeyPress_);
this.addListener(goog.events.EventType.KEYUP, this.handleKeyUp_);
this.selectionChangeTimer_ =
new goog.async.Delay(this.handleSelectionChangeTimer_,
goog.editor.Field.SELECTION_CHANGE_FREQUENCY_, this);
if (goog.editor.BrowserFeature.FOLLOWS_EDITABLE_LINKS) {
this.addListener(
goog.events.EventType.CLICK, goog.editor.Field.cancelLinkClick_);
}
this.addListener(goog.events.EventType.MOUSEDOWN, this.handleMouseDown_);
if (this.useWindowMouseUp_) {
this.eventRegister.listen(this.editableDomHelper.getDocument(),
goog.events.EventType.MOUSEUP, this.handleMouseUp_);
this.addListener(goog.events.EventType.DRAGSTART, this.handleDragStart_);
} else {
this.addListener(goog.events.EventType.MOUSEUP, this.handleMouseUp_);
}
};
/**
* Frequency to check for selection changes.
* @type {number}
* @private
*/
goog.editor.Field.SELECTION_CHANGE_FREQUENCY_ = 250;
/**
* Stops all listeners and timers.
* @protected
*/
goog.editor.Field.prototype.clearListeners = function() {
if (this.eventRegister) {
this.eventRegister.removeAll();
}
if ((goog.userAgent.product.IPHONE || goog.userAgent.product.IPAD) &&
this.usesIframe() && this.shouldRefocusOnInputMobileSafari()) {
try {
var editWindow = this.getEditableDomHelper().getWindow();
editWindow.removeEventListener(goog.events.EventType.KEYDOWN,
this.boundRefocusListenerMobileSafari_, false);
editWindow.removeEventListener(goog.events.EventType.TOUCHEND,
this.boundRefocusListenerMobileSafari_, false);
} catch (e) {
// The editWindow no longer exists, or has been navigated to a different-
// origin URL. Either way, the event listeners have already been removed
// for us.
}
delete this.boundRefocusListenerMobileSafari_;
}
if (goog.userAgent.OPERA && this.usesIframe()) {
try {
var editWindow = this.getEditableDomHelper().getWindow();
editWindow.removeEventListener(goog.events.EventType.FOCUS,
this.boundFocusListenerOpera_, false);
editWindow.removeEventListener(goog.events.EventType.BLUR,
this.boundBlurListenerOpera_, false);
} catch (e) {
// The editWindow no longer exists, or has been navigated to a different-
// origin URL. Either way, the event listeners have already been removed
// for us.
}
delete this.boundFocusListenerOpera_;
delete this.boundBlurListenerOpera_;
}
if (this.changeTimerGecko_) {
this.changeTimerGecko_.stop();
}
this.delayedChangeTimer_.stop();
};
/** @override */
goog.editor.Field.prototype.disposeInternal = function() {
if (this.isLoading() || this.isLoaded()) {
this.logger.warning('Disposing a field that is in use.');
}
if (this.getOriginalElement()) {
this.execCommand(goog.editor.Command.CLEAR_LOREM);
}
this.tearDownFieldObject_();
this.clearListeners();
this.clearFieldLoadListener_();
this.originalDomHelper = null;
if (this.eventRegister) {
this.eventRegister.dispose();
this.eventRegister = null;
}
this.removeAllWrappers();
if (goog.editor.Field.getActiveFieldId() == this.id) {
goog.editor.Field.setActiveFieldId(null);
}
for (var classId in this.plugins_) {
var plugin = this.plugins_[classId];
if (plugin.isAutoDispose()) {
plugin.dispose();
}
}
delete(this.plugins_);
goog.editor.Field.superClass_.disposeInternal.call(this);
};
/**
* Attach an wrapper to this field, to be thrown out when the field
* is disposed.
* @param {goog.Disposable} wrapper The wrapper to attach.
*/
goog.editor.Field.prototype.attachWrapper = function(wrapper) {
this.wrappers_.push(wrapper);
};
/**
* Removes all wrappers and destroys them.
*/
goog.editor.Field.prototype.removeAllWrappers = function() {
var wrapper;
while (wrapper = this.wrappers_.pop()) {
wrapper.dispose();
}
};
/**
* List of mutation events in Gecko browsers.
* @type {Array.<string>}
* @protected
*/
goog.editor.Field.MUTATION_EVENTS_GECKO = [
'DOMNodeInserted',
'DOMNodeRemoved',
'DOMNodeRemovedFromDocument',
'DOMNodeInsertedIntoDocument',
'DOMCharacterDataModified'
];
/**
* Mutation events tell us when something has changed for mozilla.
* @protected
*/
goog.editor.Field.prototype.setupMutationEventHandlersGecko = function() {
// Always use DOMSubtreeModified on Gecko when not using an iframe so that
// DOM mutations outside the Field do not trigger handleMutationEventGecko_.
if (goog.editor.BrowserFeature.HAS_DOM_SUBTREE_MODIFIED_EVENT ||
!this.usesIframe()) {
this.eventRegister.listen(this.getElement(), 'DOMSubtreeModified',
this.handleMutationEventGecko_);
} else {
var doc = this.getEditableDomHelper().getDocument();
this.eventRegister.listen(doc, goog.editor.Field.MUTATION_EVENTS_GECKO,
this.handleMutationEventGecko_, true);
// DOMAttrModified fires for a lot of events we want to ignore. This goes
// through a different handler so that we can ignore many of these.
this.eventRegister.listen(doc, 'DOMAttrModified',
goog.bind(this.handleDomAttrChange, this,
this.handleMutationEventGecko_),
true);
}
};
/**
* Handle before change key events and fire the beforetab event if appropriate.
* This needs to happen on keydown in IE and keypress in FF.
* @param {goog.events.BrowserEvent} e The browser event.
* @return {boolean} Whether to still perform the default key action. Only set
* to true if the actual event has already been canceled.
* @private
*/
goog.editor.Field.prototype.handleBeforeChangeKeyEvent_ = function(e) {
// There are two reasons to block a key:
var block =
// #1: to intercept a tab
// TODO: possibly don't allow clients to intercept tabs outside of LIs and
// maybe tables as well?
(e.keyCode == goog.events.KeyCodes.TAB && !this.dispatchBeforeTab_(e)) ||
// #2: to block a Firefox-specific bug where Macs try to navigate
// back a page when you hit command+left arrow or comamnd-right arrow.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=341886
// TODO(nicksantos): Get Firefox to fix this.
(goog.userAgent.GECKO && e.metaKey &&
(e.keyCode == goog.events.KeyCodes.LEFT ||
e.keyCode == goog.events.KeyCodes.RIGHT));
if (block) {
e.preventDefault();
return false;
} else {
// In Gecko we have both keyCode and charCode. charCode is for human
// readable characters like a, b and c. However pressing ctrl+c and so on
// also causes charCode to be set.
// TODO(arv): Del at end of field or backspace at beginning should be
// ignored.
this.gotGeneratingKey_ = e.charCode ||
goog.editor.Field.isGeneratingKey_(e, goog.userAgent.GECKO);
if (this.gotGeneratingKey_) {
this.dispatchBeforeChange();
// TODO(robbyw): Should we return the value of the above?
}
}
return true;
};
/**
* Keycodes that result in a selectionchange event (e.g. the cursor moving).
* @enum {number}
* @private
*/
goog.editor.Field.SELECTION_CHANGE_KEYCODES_ = {
8: 1, // backspace
9: 1, // tab
13: 1, // enter
33: 1, // page up
34: 1, // page down
35: 1, // end
36: 1, // home
37: 1, // left
38: 1, // up
39: 1, // right
40: 1, // down
46: 1 // delete
};
/**
* Map of keyCodes (not charCodes) that when used in conjunction with the
* Ctrl key cause selection changes in the field contents. These are the keys
* that are not handled by the basic formatting trogedit plugins. Note that
* combinations like Ctrl-left etc are already handled in
* SELECTION_CHANGE_KEYCODES_
* @type {Object}
* @private
*/
goog.editor.Field.CTRL_KEYS_CAUSING_SELECTION_CHANGES_ = {
65: true, // A
86: true, // V
88: true // X
};
/**
* Map of keyCodes (not charCodes) that might need to be handled as a keyboard
* shortcut (even when ctrl/meta key is not pressed) by some plugin. Currently
* it is a small list. If it grows too big we can optimize it by using ranges
* or extending it from SELECTION_CHANGE_KEYCODES_
* @type {Object}
* @private
*/
goog.editor.Field.POTENTIAL_SHORTCUT_KEYCODES_ = {
8: 1, // backspace
9: 1, // tab
13: 1, // enter
27: 1, // esc
33: 1, // page up
34: 1, // page down
37: 1, // left
38: 1, // up
39: 1, // right
40: 1 // down
};
/**
* Calls all the plugins of the given operation, in sequence, with the
* given arguments. This is short-circuiting: once one plugin cancels
* the event, no more plugins will be invoked.
* @param {goog.editor.Plugin.Op} op A plugin op.
* @param {...*} var_args The arguments to the plugin.
* @return {boolean} True if one of the plugins cancel the event, false
* otherwise.
* @private
*/
goog.editor.Field.prototype.invokeShortCircuitingOp_ = function(op, var_args) {
var plugins = this.indexedPlugins_[op];
var argList = goog.array.slice(arguments, 1);
for (var i = 0; i < plugins.length; ++i) {
// If the plugin returns true, that means it handled the event and
// we shouldn't propagate to the other plugins.
var plugin = plugins[i];
if ((plugin.isEnabled(this) ||
goog.editor.Plugin.IRREPRESSIBLE_OPS[op]) &&
plugin[goog.editor.Plugin.OPCODE[op]].apply(plugin, argList)) {
// Only one plugin is allowed to handle the event. If for some reason
// a plugin wants to handle it and still allow other plugins to handle
// it, it shouldn't return true.
return true;
}
}
return false;
};
/**
* Invoke this operation on all plugins with the given arguments.
* @param {goog.editor.Plugin.Op} op A plugin op.
* @param {...*} var_args The arguments to the plugin.
* @private
*/
goog.editor.Field.prototype.invokeOp_ = function(op, var_args) {
var plugins = this.indexedPlugins_[op];
var argList = goog.array.slice(arguments, 1);
for (var i = 0; i < plugins.length; ++i) {
var plugin = plugins[i];
if (plugin.isEnabled(this) ||
goog.editor.Plugin.IRREPRESSIBLE_OPS[op]) {
plugin[goog.editor.Plugin.OPCODE[op]].apply(plugin, argList);
}
}
};
/**
* Reduce this argument over all plugins. The result of each plugin invocation
* will be passed to the next plugin invocation. See goog.array.reduce.
* @param {goog.editor.Plugin.Op} op A plugin op.
* @param {string} arg The argument to reduce. For now, we assume it's a
* string, but we should widen this later if there are reducing
* plugins that don't operate on strings.
* @param {...*} var_args Any extra arguments to pass to the plugin. These args
* will not be reduced.
* @return {string} The reduced argument.
* @private
*/
goog.editor.Field.prototype.reduceOp_ = function(op, arg, var_args) {
var plugins = this.indexedPlugins_[op];
var argList = goog.array.slice(arguments, 1);
for (var i = 0; i < plugins.length; ++i) {
var plugin = plugins[i];
if (plugin.isEnabled(this) ||
goog.editor.Plugin.IRREPRESSIBLE_OPS[op]) {
argList[0] = plugin[goog.editor.Plugin.OPCODE[op]].apply(
plugin, argList);
}
}
return argList[0];
};
/**
* Prepare the given contents, then inject them into the editable field.
* @param {?string} contents The contents to prepare.
* @param {Element} field The field element.
* @protected
*/
goog.editor.Field.prototype.injectContents = function(contents, field) {
var styles = {};
var newHtml = this.getInjectableContents(contents, styles);
goog.style.setStyle(field, styles);
goog.editor.node.replaceInnerHtml(field, newHtml);
};
/**
* Returns prepared contents that can be injected into the editable field.
* @param {?string} contents The contents to prepare.
* @param {Object} styles A map that will be populated with styles that should
* be applied to the field element together with the contents.
* @return {string} The prepared contents.
*/
goog.editor.Field.prototype.getInjectableContents = function(contents, styles) {
return this.reduceOp_(
goog.editor.Plugin.Op.PREPARE_CONTENTS_HTML, contents || '', styles);
};
/**
* Handles keydown on the field.
* @param {goog.events.BrowserEvent} e The browser event.
* @private
*/
goog.editor.Field.prototype.handleKeyDown_ = function(e) {
if (!goog.editor.BrowserFeature.USE_MUTATION_EVENTS) {
if (!this.handleBeforeChangeKeyEvent_(e)) {
return;
}
}
if (!this.invokeShortCircuitingOp_(goog.editor.Plugin.Op.KEYDOWN, e) &&
goog.editor.BrowserFeature.USES_KEYDOWN) {
this.handleKeyboardShortcut_(e);
}
};
/**
* Handles keypress on the field.
* @param {goog.events.BrowserEvent} e The browser event.
* @private
*/
goog.editor.Field.prototype.handleKeyPress_ = function(e) {
if (goog.editor.BrowserFeature.USE_MUTATION_EVENTS) {
if (!this.handleBeforeChangeKeyEvent_(e)) {
return;
}
} else {
// In IE only keys that generate output trigger keypress
// In Mozilla charCode is set for keys generating content.
this.gotGeneratingKey_ = true;
this.dispatchBeforeChange();
}
if (!this.invokeShortCircuitingOp_(goog.editor.Plugin.Op.KEYPRESS, e) &&
!goog.editor.BrowserFeature.USES_KEYDOWN) {
this.handleKeyboardShortcut_(e);
}
};
/**
* Handles keyup on the field.
* @param {goog.events.BrowserEvent} e The browser event.
* @private
*/
goog.editor.Field.prototype.handleKeyUp_ = function(e) {
if (!goog.editor.BrowserFeature.USE_MUTATION_EVENTS &&
(this.gotGeneratingKey_ ||
goog.editor.Field.isSpecialGeneratingKey_(e))) {
// The special keys won't have set the gotGeneratingKey flag, so we check
// for them explicitly
this.handleChange();
}
this.invokeShortCircuitingOp_(goog.editor.Plugin.Op.KEYUP, e);
if (this.isEventStopped(goog.editor.Field.EventType.SELECTIONCHANGE)) {
return;
}
if (goog.editor.Field.SELECTION_CHANGE_KEYCODES_[e.keyCode] ||
((e.ctrlKey || e.metaKey) &&
goog.editor.Field.CTRL_KEYS_CAUSING_SELECTION_CHANGES_[e.keyCode])) {
this.selectionChangeTimer_.start();
}
};
/**
* Handles keyboard shortcuts on the field. Note that we bake this into our
* handleKeyPress/handleKeyDown rather than using goog.events.KeyHandler or
* goog.ui.KeyboardShortcutHandler for performance reasons. Since these
* are handled on every key stroke, we do not want to be going out to the
* event system every time.
* @param {goog.events.BrowserEvent} e The browser event.
* @private
*/
goog.editor.Field.prototype.handleKeyboardShortcut_ = function(e) {
// Alt key is used for i18n languages to enter certain characters. like
// control + alt + z (used for IMEs) and control + alt + s for Polish.
// So we don't invoke handleKeyboardShortcut at all for alt keys.
if (e.altKey) {
return;
}
var isModifierPressed = goog.userAgent.MAC ? e.metaKey : e.ctrlKey;
if (isModifierPressed ||
goog.editor.Field.POTENTIAL_SHORTCUT_KEYCODES_[e.keyCode]) {
// TODO(user): goog.events.KeyHandler uses much more complicated logic
// to determine key. Consider changing to what they do.
var key = e.charCode || e.keyCode;
if (key == 17) { // Ctrl key
// In IE and Webkit pressing Ctrl key itself results in this event.
return;
}
var stringKey = String.fromCharCode(key).toLowerCase();
if (this.invokeShortCircuitingOp_(goog.editor.Plugin.Op.SHORTCUT,
e, stringKey, isModifierPressed)) {
e.preventDefault();
// We don't call stopPropagation as some other handler outside of
// trogedit might need it.
}
}
};
/**
* Executes an editing command as per the registered plugins.
* @param {string} command The command to execute.
* @param {...*} var_args Any additional parameters needed to execute the
* command.
* @return {*} False if the command wasn't handled, otherwise, the result of
* the command.
*/
goog.editor.Field.prototype.execCommand = function(command, var_args) {
var args = arguments;
var result;
var plugins = this.indexedPlugins_[goog.editor.Plugin.Op.EXEC_COMMAND];
for (var i = 0; i < plugins.length; ++i) {
// If the plugin supports the command, that means it handled the
// event and we shouldn't propagate to the other plugins.
var plugin = plugins[i];
if (plugin.isEnabled(this) && plugin.isSupportedCommand(command)) {
result = plugin.execCommand.apply(plugin, args);
break;
}
}
return result;
};
/**
* Gets the value of command(s).
* @param {string|Array.<string>} commands String name(s) of the command.
* @return {*} Value of each command. Returns false (or array of falses)
* if designMode is off or the field is otherwise uneditable, and
* there are no activeOnUneditable plugins for the command.
*/
goog.editor.Field.prototype.queryCommandValue = function(commands) {
var isEditable = this.isLoaded() && this.isSelectionEditable();
if (goog.isString(commands)) {
return this.queryCommandValueInternal_(commands, isEditable);
} else {
var state = {};
for (var i = 0; i < commands.length; i++) {
state[commands[i]] = this.queryCommandValueInternal_(commands[i],
isEditable);
}
return state;
}
};
/**
* Gets the value of this command.
* @param {string} command The command to check.
* @param {boolean} isEditable Whether the field is currently editable.
* @return {*} The state of this command. Null if not handled.
* False if the field is uneditable and there are no handlers for
* uneditable commands.
* @private
*/
goog.editor.Field.prototype.queryCommandValueInternal_ = function(command,
isEditable) {
var plugins = this.indexedPlugins_[goog.editor.Plugin.Op.QUERY_COMMAND];
for (var i = 0; i < plugins.length; ++i) {
var plugin = plugins[i];
if (plugin.isEnabled(this) && plugin.isSupportedCommand(command) &&
(isEditable || plugin.activeOnUneditableFields())) {
return plugin.queryCommandValue(command);
}
}
return isEditable ? null : false;
};
/**
* Fires a change event only if the attribute change effects the editiable
* field. We ignore events that are internal browser events (ie scrollbar
* state change)
* @param {Function} handler The function to call if this is not an internal
* browser event.
* @param {goog.events.BrowserEvent} browserEvent The browser event.
* @protected
*/
goog.editor.Field.prototype.handleDomAttrChange =
function(handler, browserEvent) {
if (this.isEventStopped(goog.editor.Field.EventType.CHANGE)) {
return;
}
var e = browserEvent.getBrowserEvent();
// For XUL elements, since we don't care what they are doing
try {
if (e.originalTarget.prefix || e.originalTarget.nodeName == 'scrollbar') {
return;
}
} catch (ex1) {
// Some XUL nodes don't like you reading their properties. If we got
// the exception, this implies a XUL node so we can return.
return;
}
// Check if prev and new values are different, sometimes this fires when
// nothing has really changed.
if (e.prevValue == e.newValue) {
return;
}
handler.call(this, e);
};
/**
* Handle a mutation event.
* @param {goog.events.BrowserEvent|Event} e The browser event.
* @private
*/
goog.editor.Field.prototype.handleMutationEventGecko_ = function(e) {
if (this.isEventStopped(goog.editor.Field.EventType.CHANGE)) {
return;
}
e = e.getBrowserEvent ? e.getBrowserEvent() : e;
// For people with firebug, firebug sets this property on elements it is
// inserting into the dom.
if (e.target.firebugIgnore) {
return;
}
this.isModified_ = true;
this.isEverModified_ = true;
this.changeTimerGecko_.start();
};
/**
* Handle drop events. Deal with focus/selection issues and set the document
* as changed.
* @param {goog.events.BrowserEvent} e The browser event.
* @private
*/
goog.editor.Field.prototype.handleDrop_ = function(e) {
if (goog.userAgent.IE) {
// TODO(user): This should really be done in the loremipsum plugin.
this.execCommand(goog.editor.Command.CLEAR_LOREM, true);
}
// TODO(user): I just moved this code to this location, but I wonder why
// it is only done for this case. Investigate.
if (goog.editor.BrowserFeature.USE_MUTATION_EVENTS) {
this.dispatchFocusAndBeforeFocus_();
}
this.dispatchChange();
};
/**
* @return {HTMLIFrameElement} The iframe that's body is editable.
* @protected
*/
goog.editor.Field.prototype.getEditableIframe = function() {
var dh;
if (this.usesIframe() && (dh = this.getEditableDomHelper())) {
// If the iframe has been destroyed, the dh could still exist since the
// node may not be gc'ed, but fetching the window can fail.
var win = dh.getWindow();
return /** @type {HTMLIFrameElement} */ (win && win.frameElement);
}
return null;
};
/**
* @return {goog.dom.DomHelper?} The dom helper for the editable node.
*/
goog.editor.Field.prototype.getEditableDomHelper = function() {
return this.editableDomHelper;
};
/**
* @return {goog.dom.AbstractRange?} Closure range object wrapping the selection
* in this field or null if this field is not currently editable.
*/
goog.editor.Field.prototype.getRange = function() {
var win = this.editableDomHelper && this.editableDomHelper.getWindow();
return win && goog.dom.Range.createFromWindow(win);
};
/**
* Dispatch a selection change event, optionally caused by the given browser
* event or selecting the given target.
* @param {goog.events.BrowserEvent=} opt_e Optional browser event causing this
* event.
* @param {Node=} opt_target The node the selection changed to.
*/
goog.editor.Field.prototype.dispatchSelectionChangeEvent = function(
opt_e, opt_target) {
if (this.isEventStopped(goog.editor.Field.EventType.SELECTIONCHANGE)) {
return;
}
// The selection is editable only if the selection is inside the
// editable field.
var range = this.getRange();
var rangeContainer = range && range.getContainerElement();
this.isSelectionEditable_ = !!rangeContainer &&
goog.dom.contains(this.getElement(), rangeContainer);
this.dispatchCommandValueChange();
this.dispatchEvent({
type: goog.editor.Field.EventType.SELECTIONCHANGE,
originalType: opt_e && opt_e.type
});
this.invokeShortCircuitingOp_(goog.editor.Plugin.Op.SELECTION,
opt_e, opt_target);
};
/**
* Dispatch a selection change event using a browser event that was
* asynchronously saved earlier.
* @private
*/
goog.editor.Field.prototype.handleSelectionChangeTimer_ = function() {
var t = this.selectionChangeTarget_;
this.selectionChangeTarget_ = null;
this.dispatchSelectionChangeEvent(undefined, t);
};
/**
* This dispatches the beforechange event on the editable field
*/
goog.editor.Field.prototype.dispatchBeforeChange = function() {
if (this.isEventStopped(goog.editor.Field.EventType.BEFORECHANGE)) {
return;
}
this.dispatchEvent(goog.editor.Field.EventType.BEFORECHANGE);
};
/**
* This dispatches the beforetab event on the editable field. If this event is
* cancelled, then the default tab behavior is prevented.
* @param {goog.events.BrowserEvent} e The tab event.
* @private
* @return {boolean} The result of dispatchEvent.
*/
goog.editor.Field.prototype.dispatchBeforeTab_ = function(e) {
return this.dispatchEvent({
type: goog.editor.Field.EventType.BEFORETAB,
shiftKey: e.shiftKey,
altKey: e.altKey,
ctrlKey: e.ctrlKey
});
};
/**
* Temporarily ignore change events. If the time has already been set, it will
* fire immediately now. Further setting of the timer is stopped and
* dispatching of events is stopped until startChangeEvents is called.
* @param {boolean=} opt_stopChange Whether to ignore base change events.
* @param {boolean=} opt_stopDelayedChange Whether to ignore delayed change
* events.
*/
goog.editor.Field.prototype.stopChangeEvents = function(opt_stopChange,
opt_stopDelayedChange) {
if (opt_stopChange) {
if (this.changeTimerGecko_) {
this.changeTimerGecko_.fireIfActive();
}
this.stopEvent(goog.editor.Field.EventType.CHANGE);
}
if (opt_stopDelayedChange) {
this.clearDelayedChange();
this.stopEvent(goog.editor.Field.EventType.DELAYEDCHANGE);
}
};
/**
* Start change events again and fire once if desired.
* @param {boolean=} opt_fireChange Whether to fire the change event
* immediately.
* @param {boolean=} opt_fireDelayedChange Whether to fire the delayed change
* event immediately.
*/
goog.editor.Field.prototype.startChangeEvents = function(opt_fireChange,
opt_fireDelayedChange) {
if (!opt_fireChange && this.changeTimerGecko_) {
// In the case where change events were stopped and we're not firing
// them on start, the user was trying to suppress all change or delayed
// change events. Clear the change timer now while the events are still
// stopped so that its firing doesn't fire a stopped change event, or
// queue up a delayed change event that we were trying to stop.
this.changeTimerGecko_.fireIfActive();
}
this.startEvent(goog.editor.Field.EventType.CHANGE);
this.startEvent(goog.editor.Field.EventType.DELAYEDCHANGE);
if (opt_fireChange) {
this.handleChange();
}
if (opt_fireDelayedChange) {
this.dispatchDelayedChange_();
}
};
/**
* Stops the event of the given type from being dispatched.
* @param {goog.editor.Field.EventType} eventType type of event to stop.
*/
goog.editor.Field.prototype.stopEvent = function(eventType) {
this.stoppedEvents_[eventType] = 1;
};
/**
* Re-starts the event of the given type being dispatched, if it had
* previously been stopped with stopEvent().
* @param {goog.editor.Field.EventType} eventType type of event to start.
*/
goog.editor.Field.prototype.startEvent = function(eventType) {
// Toggling this bit on/off instead of deleting it/re-adding it
// saves array allocations.
this.stoppedEvents_[eventType] = 0;
};
/**
* Block an event for a short amount of time. Intended
* for the situation where an event pair fires in quick succession
* (e.g., mousedown/mouseup, keydown/keyup, focus/blur),
* and we want the second event in the pair to get "debounced."
*
* WARNING: This should never be used to solve race conditions or for
* mission-critical actions. It should only be used for UI improvements,
* where it's okay if the behavior is non-deterministic.
*
* @param {goog.editor.Field.EventType} eventType type of event to debounce.
*/
goog.editor.Field.prototype.debounceEvent = function(eventType) {
this.debouncedEvents_[eventType] = goog.now();
};
/**
* Checks if the event of the given type has stopped being dispatched
* @param {goog.editor.Field.EventType} eventType type of event to check.
* @return {boolean} true if the event has been stopped with stopEvent().
* @protected
*/
goog.editor.Field.prototype.isEventStopped = function(eventType) {
return !!this.stoppedEvents_[eventType] ||
(this.debouncedEvents_[eventType] &&
(goog.now() - this.debouncedEvents_[eventType] <=
goog.editor.Field.DEBOUNCE_TIME_MS_));
};
/**
* Calls a function to manipulate the dom of this field. This method should be
* used whenever Trogedit clients need to modify the dom of the field, so that
* delayed change events are handled appropriately. Extra delayed change events
* will cause undesired states to be added to the undo-redo stack. This method
* will always fire at most one delayed change event, depending on the value of
* {@code opt_preventDelayedChange}.
*
* @param {function()} func The function to call that will manipulate the dom.
* @param {boolean=} opt_preventDelayedChange Whether delayed change should be
* prevented after calling {@code func}. Defaults to always firing
* delayed change.
* @param {Object=} opt_handler Object in whose scope to call the listener.
*/
goog.editor.Field.prototype.manipulateDom = function(func,
opt_preventDelayedChange, opt_handler) {
this.stopChangeEvents(true, true);
// We don't want any problems with the passed in function permanently
// stopping change events. That would break Trogedit.
try {
func.call(opt_handler);
} finally {
// If the field isn't loaded then change and delayed change events will be
// started as part of the onload behavior.
if (this.isLoaded()) {
// We assume that func always modified the dom and so fire a single change
// event. Delayed change is only fired if not prevented by the user.
if (opt_preventDelayedChange) {
this.startEvent(goog.editor.Field.EventType.CHANGE);
this.handleChange();
this.startEvent(goog.editor.Field.EventType.DELAYEDCHANGE);
} else {
this.dispatchChange();
}
}
}
};
/**
* Dispatches a command value change event.
* @param {Array.<string>=} opt_commands Commands whose state has
* changed.
*/
goog.editor.Field.prototype.dispatchCommandValueChange =
function(opt_commands) {
if (opt_commands) {
this.dispatchEvent({
type: goog.editor.Field.EventType.COMMAND_VALUE_CHANGE,
commands: opt_commands
});
} else {
this.dispatchEvent(goog.editor.Field.EventType.COMMAND_VALUE_CHANGE);
}
};
/**
* Dispatches the appropriate set of change events. This only fires
* synchronous change events in blended-mode, iframe-using mozilla. It just
* starts the appropriate timer for goog.editor.Field.EventType.DELAYEDCHANGE.
* This also starts up change events again if they were stopped.
*
* @param {boolean=} opt_noDelay True if
* goog.editor.Field.EventType.DELAYEDCHANGE should be fired syncronously.
*/
goog.editor.Field.prototype.dispatchChange = function(opt_noDelay) {
this.startChangeEvents(true, opt_noDelay);
};
/**
* Handle a change in the Editable Field. Marks the field has modified,
* dispatches the change event on the editable field (moz only), starts the
* timer for the delayed change event. Note that these actions only occur if
* the proper events are not stopped.
*/
goog.editor.Field.prototype.handleChange = function() {
if (this.isEventStopped(goog.editor.Field.EventType.CHANGE)) {
return;
}
// Clear the changeTimerGecko_ if it's active, since any manual call to
// handle change is equiavlent to changeTimerGecko_.fire().
if (this.changeTimerGecko_) {
this.changeTimerGecko_.stop();
}
this.isModified_ = true;
this.isEverModified_ = true;
if (this.isEventStopped(goog.editor.Field.EventType.DELAYEDCHANGE)) {
return;
}
this.delayedChangeTimer_.start();
};
/**
* Dispatch a delayed change event.
* @private
*/
goog.editor.Field.prototype.dispatchDelayedChange_ = function() {
if (this.isEventStopped(goog.editor.Field.EventType.DELAYEDCHANGE)) {
return;
}
// Clear the delayedChangeTimer_ if it's active, since any manual call to
// dispatchDelayedChange_ is equivalent to delayedChangeTimer_.fire().
this.delayedChangeTimer_.stop();
this.isModified_ = false;
this.dispatchEvent(goog.editor.Field.EventType.DELAYEDCHANGE);
};
/**
* Don't wait for the timer and just fire the delayed change event if it's
* pending.
*/
goog.editor.Field.prototype.clearDelayedChange = function() {
// The changeTimerGecko_ will queue up a delayed change so to fully clear
// delayed change we must also clear this timer.
if (this.changeTimerGecko_) {
this.changeTimerGecko_.fireIfActive();
}
this.delayedChangeTimer_.fireIfActive();
};
/**
* Dispatch beforefocus and focus for FF. Note that both of these actually
* happen in the document's "focus" event. Unfortunately, we don't actually
* have a way of getting in before the focus event in FF (boo! hiss!).
* In IE, we use onfocusin for before focus and onfocus for focus.
* @private
*/
goog.editor.Field.prototype.dispatchFocusAndBeforeFocus_ = function() {
this.dispatchBeforeFocus_();
this.dispatchFocus_();
};
/**
* Dispatches a before focus event.
* @private
*/
goog.editor.Field.prototype.dispatchBeforeFocus_ = function() {
if (this.isEventStopped(goog.editor.Field.EventType.BEFOREFOCUS)) {
return;
}
this.execCommand(goog.editor.Command.CLEAR_LOREM, true);
this.dispatchEvent(goog.editor.Field.EventType.BEFOREFOCUS);
};
/**
* Dispatches a focus event.
* @private
*/
goog.editor.Field.prototype.dispatchFocus_ = function() {
if (this.isEventStopped(goog.editor.Field.EventType.FOCUS)) {
return;
}
goog.editor.Field.setActiveFieldId(this.id);
this.isSelectionEditable_ = true;
this.dispatchEvent(goog.editor.Field.EventType.FOCUS);
if (goog.editor.BrowserFeature.
PUTS_CURSOR_BEFORE_FIRST_BLOCK_ELEMENT_ON_FOCUS) {
// If the cursor is at the beginning of the field, make sure that it is
// in the first user-visible line break, e.g.,
// no selection: <div><p>...</p></div> --> <div><p>|cursor|...</p></div>
// <div>|cursor|<p>...</p></div> --> <div><p>|cursor|...</p></div>
// <body>|cursor|<p>...</p></body> --> <body><p>|cursor|...</p></body>
var field = this.getElement();
var range = this.getRange();
if (range) {
var focusNode = range.getFocusNode();
if (range.getFocusOffset() == 0 && (!focusNode || focusNode == field ||
focusNode.tagName == goog.dom.TagName.BODY)) {
goog.editor.range.selectNodeStart(field);
}
}
}
if (!goog.editor.BrowserFeature.CLEARS_SELECTION_WHEN_FOCUS_LEAVES &&
this.usesIframe()) {
var parent = this.getEditableDomHelper().getWindow().parent;
parent.getSelection().removeAllRanges();
}
};
/**
* Dispatches a blur event.
* @protected
*/
goog.editor.Field.prototype.dispatchBlur = function() {
if (this.isEventStopped(goog.editor.Field.EventType.BLUR)) {
return;
}
// Another field may have already been registered as active, so only
// clear out the active field id if we still think this field is active.
if (goog.editor.Field.getActiveFieldId() == this.id) {
goog.editor.Field.setActiveFieldId(null);
}
this.isSelectionEditable_ = false;
this.dispatchEvent(goog.editor.Field.EventType.BLUR);
};
/**
* @return {boolean} Whether the selection is editable.
*/
goog.editor.Field.prototype.isSelectionEditable = function() {
return this.isSelectionEditable_;
};
/**
* Event handler for clicks in browsers that will follow a link when the user
* clicks, even if it's editable. We stop the click manually
* @param {goog.events.BrowserEvent} e The event.
* @private
*/
goog.editor.Field.cancelLinkClick_ = function(e) {
if (goog.dom.getAncestorByTagNameAndClass(
/** @type {Node} */ (e.target), goog.dom.TagName.A)) {
e.preventDefault();
}
};
/**
* Handle mouse down inside the editable field.
* @param {goog.events.BrowserEvent} e The event.
* @private
*/
goog.editor.Field.prototype.handleMouseDown_ = function(e) {
goog.editor.Field.setActiveFieldId(this.id);
// Open links in a new window if the user control + clicks.
if (goog.userAgent.IE) {
var targetElement = e.target;
if (targetElement &&
targetElement.tagName == goog.dom.TagName.A && e.ctrlKey) {
this.originalDomHelper.getWindow().open(targetElement.href);
}
}
this.waitingForMouseUp_ = true;
};
/**
* Handle drag start. Needs to cancel listening for the mouse up event on the
* window.
* @param {goog.events.BrowserEvent} e The event.
* @private
*/
goog.editor.Field.prototype.handleDragStart_ = function(e) {
this.waitingForMouseUp_ = false;
};
/**
* Handle mouse up inside the editable field.
* @param {goog.events.BrowserEvent} e The event.
* @private
*/
goog.editor.Field.prototype.handleMouseUp_ = function(e) {
if (this.useWindowMouseUp_ && !this.waitingForMouseUp_) {
return;
}
this.waitingForMouseUp_ = false;
/*
* We fire a selection change event immediately for listeners that depend on
* the native browser event object (e). On IE, a listener that tries to
* retrieve the selection with goog.dom.Range may see an out-of-date
* selection range.
*/
this.dispatchSelectionChangeEvent(e);
if (goog.userAgent.IE) {
/*
* Fire a second selection change event for listeners that need an
* up-to-date selection range. Save the event's target to be sent with it
* (it's safer than saving a copy of the event itself).
*/
this.selectionChangeTarget_ = /** @type {Node} */ (e.target);
this.selectionChangeTimer_.start();
}
};
/**
* Retrieve the HTML contents of a field.
*
* Do NOT just get the innerHTML of a field directly--there's a lot of
* processing that needs to happen.
* @return {string} The scrubbed contents of the field.
*/
goog.editor.Field.prototype.getCleanContents = function() {
if (this.queryCommandValue(goog.editor.Command.USING_LOREM)) {
return goog.string.Unicode.NBSP;
}
if (!this.isLoaded()) {
// The field is uneditable, so it's ok to read contents directly.
var elem = this.getOriginalElement();
if (!elem) {
this.logger.shout("Couldn't get the field element to read the contents");
}
return elem.innerHTML;
}
var fieldCopy = this.getFieldCopy();
// Allow the plugins to handle their cleanup.
this.invokeOp_(goog.editor.Plugin.Op.CLEAN_CONTENTS_DOM, fieldCopy);
return this.reduceOp_(
goog.editor.Plugin.Op.CLEAN_CONTENTS_HTML, fieldCopy.innerHTML);
};
/**
* Get the copy of the editable field element, which has the innerHTML set
* correctly.
* @return {Element} The copy of the editable field.
* @protected
*/
goog.editor.Field.prototype.getFieldCopy = function() {
var field = this.getElement();
// Deep cloneNode strips some script tag contents in IE, so we do this.
var fieldCopy = /** @type {Element} */(field.cloneNode(false));
// For some reason, when IE sets innerHtml of the cloned node, it strips
// script tags that fall at the beginning of an element. Appending a
// non-breaking space prevents this.
var html = field.innerHTML;
if (goog.userAgent.IE && html.match(/^\s*<script/i)) {
html = goog.string.Unicode.NBSP + html;
}
fieldCopy.innerHTML = html;
return fieldCopy;
};
/**
* Sets the contents of the field.
* @param {boolean} addParas Boolean to specify whether to add paragraphs
* to long fields.
* @param {?string} html html to insert. If html=null, then this defaults
* to a nsbp for mozilla and an empty string for IE.
* @param {boolean=} opt_dontFireDelayedChange True to make this content change
* not fire a delayed change event.
* @param {boolean=} opt_applyLorem Whether to apply lorem ipsum styles.
*/
goog.editor.Field.prototype.setHtml = function(
addParas, html, opt_dontFireDelayedChange, opt_applyLorem) {
if (this.isLoading()) {
this.logger.severe("Can't set html while loading Trogedit");
return;
}
// Clear the lorem ipsum style, always.
if (opt_applyLorem) {
this.execCommand(goog.editor.Command.CLEAR_LOREM);
}
if (html && addParas) {
html = '<p>' + html + '</p>';
}
// If we don't want change events to fire, we have to turn off change events
// before setting the field contents, since that causes mutation events.
if (opt_dontFireDelayedChange) {
this.stopChangeEvents(false, true);
}
this.setInnerHtml_(html);
// Set the lorem ipsum style, if the element is empty.
if (opt_applyLorem) {
this.execCommand(goog.editor.Command.UPDATE_LOREM);
}
// TODO(user): This check should probably be moved to isEventStopped and
// startEvent.
if (this.isLoaded()) {
if (opt_dontFireDelayedChange) { // Turn back on change events
// We must fire change timer if necessary before restarting change events!
// Otherwise, the change timer firing after we restart events will cause
// the delayed change we were trying to stop. Flow:
// Stop delayed change
// setInnerHtml_, this starts the change timer
// start delayed change
// change timer fires
// starts delayed change timer since event was not stopped
// delayed change fires for the delayed change we tried to stop.
if (goog.editor.BrowserFeature.USE_MUTATION_EVENTS) {
this.changeTimerGecko_.fireIfActive();
}
this.startChangeEvents();
} else { // Mark the document as changed and fire change events.
this.dispatchChange();
}
}
};
/**
* Sets the inner HTML of the field. Works on both editable and
* uneditable fields.
* @param {?string} html The new inner HTML of the field.
* @private
*/
goog.editor.Field.prototype.setInnerHtml_ = function(html) {
var field = this.getElement();
if (field) {
// Safari will put <style> tags into *new* <head> elements. When setting
// HTML, we need to remove these spare <head>s to make sure there's a
// clean slate, but keep the first <head>.
// Note: We punt on this issue for the non iframe case since
// we don't want to screw with the main document.
if (this.usesIframe() && goog.editor.BrowserFeature.MOVES_STYLE_TO_HEAD) {
var heads = field.ownerDocument.getElementsByTagName('HEAD');
for (var i = heads.length - 1; i >= 1; --i) {
heads[i].parentNode.removeChild(heads[i]);
}
}
} else {
field = this.getOriginalElement();
}
if (field) {
this.injectContents(html, field);
}
};
/**
* Attemps to turn on designMode for a document. This function can fail under
* certain circumstances related to the load event, and will throw an exception.
* @protected
*/
goog.editor.Field.prototype.turnOnDesignModeGecko = function() {
var doc = this.getEditableDomHelper().getDocument();
// NOTE(nicksantos): This will fail under certain conditions, like
// when the node has display: none. It's up to clients to ensure that
// their fields are valid when they try to make them editable.
doc.designMode = 'on';
if (goog.editor.BrowserFeature.HAS_STYLE_WITH_CSS) {
doc.execCommand('styleWithCSS', false, false);
}
};
/**
* Installs styles if needed. Only writes styles when they can't be written
* inline directly into the field.
* @protected
*/
goog.editor.Field.prototype.installStyles = function() {
if (this.cssStyles && this.shouldLoadAsynchronously()) {
goog.style.installStyles(this.cssStyles, this.getElement());
}
};
/**
* Signal that the field is loaded and ready to use. Change events now are
* in effect.
* @private
*/
goog.editor.Field.prototype.dispatchLoadEvent_ = function() {
var field = this.getElement();
this.installStyles();
this.startChangeEvents();
this.logger.info('Dispatching load ' + this.id);
this.dispatchEvent(goog.editor.Field.EventType.LOAD);
};
/**
* @return {boolean} Whether the field is uneditable.
*/
goog.editor.Field.prototype.isUneditable = function() {
return this.loadState_ == goog.editor.Field.LoadState_.UNEDITABLE;
};
/**
* @return {boolean} Whether the field has finished loading.
*/
goog.editor.Field.prototype.isLoaded = function() {
return this.loadState_ == goog.editor.Field.LoadState_.EDITABLE;
};
/**
* @return {boolean} Whether the field is in the process of loading.
*/
goog.editor.Field.prototype.isLoading = function() {
return this.loadState_ == goog.editor.Field.LoadState_.LOADING;
};
/**
* Gives the field focus.
*/
goog.editor.Field.prototype.focus = function() {
if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE &&
this.usesIframe()) {
// In designMode, only the window itself can be focused; not the element.
this.getEditableDomHelper().getWindow().focus();
} else {
if (goog.userAgent.OPERA) {
// Opera will scroll to the bottom of the focused document, even
// if it is contained in an iframe that is scrolled to the top and
// the bottom flows past the end of it. To prevent this,
// save the scroll position of the document containing the editor
// iframe, then restore it after the focus.
var scrollX = this.appWindow_.pageXOffset;
var scrollY = this.appWindow_.pageYOffset;
}
this.getElement().focus();
if (goog.userAgent.OPERA) {
this.appWindow_.scrollTo(
/** @type {number} */ (scrollX), /** @type {number} */ (scrollY));
}
}
};
/**
* Gives the field focus and places the cursor at the start of the field.
*/
goog.editor.Field.prototype.focusAndPlaceCursorAtStart = function() {
// NOTE(user): Excluding Gecko to maintain existing behavior post refactoring
// placeCursorAtStart into its own method. In Gecko browsers that currently
// have a selection the existing selection will be restored, otherwise it
// will go to the start.
// TODO(user): Refactor the code using this and related methods. We should
// only mess with the selection in the case where there is not an existing
// selection in the field.
if (goog.editor.BrowserFeature.HAS_IE_RANGES || goog.userAgent.WEBKIT) {
this.placeCursorAtStart();
}
this.focus();
};
/**
* Place the cursor at the start of this field. It's recommended that you only
* use this method (and manipulate the selection in general) when there is not
* an existing selection in the field.
*/
goog.editor.Field.prototype.placeCursorAtStart = function() {
this.placeCursorAtStartOrEnd_(true);
};
/**
* Place the cursor at the start of this field. It's recommended that you only
* use this method (and manipulate the selection in general) when there is not
* an existing selection in the field.
*/
goog.editor.Field.prototype.placeCursorAtEnd = function() {
this.placeCursorAtStartOrEnd_(false);
};
/**
* Helper method to place the cursor at the start or end of this field.
* @param {boolean} isStart True for start, false for end.
* @private
*/
goog.editor.Field.prototype.placeCursorAtStartOrEnd_ = function(isStart) {
var field = this.getElement();
if (field) {
var cursorPosition = isStart ? goog.editor.node.getLeftMostLeaf(field) :
goog.editor.node.getRightMostLeaf(field);
if (field == cursorPosition) {
// The rightmost leaf we found was the field element itself (which likely
// means the field element is empty). We can't place the cursor next to
// the field element, so just place it at the beginning.
goog.dom.Range.createCaret(field, 0).select();
} else {
goog.editor.range.placeCursorNextTo(cursorPosition, isStart);
}
this.dispatchSelectionChangeEvent();
}
};
/**
* Restore a saved range, and set the focus on the field.
* If no range is specified, we simply set the focus.
* @param {goog.dom.SavedRange=} opt_range A previously saved selected range.
*/
goog.editor.Field.prototype.restoreSavedRange = function(opt_range) {
if (goog.userAgent.IE) {
this.focus();
}
if (opt_range) {
opt_range.restore();
}
if (!goog.userAgent.IE) {
this.focus();
}
};
/**
* Makes a field editable.
*
* @param {string=} opt_iframeSrc URL to set the iframe src to if necessary.
*/
goog.editor.Field.prototype.makeEditable = function(opt_iframeSrc) {
this.loadState_ = goog.editor.Field.LoadState_.LOADING;
var field = this.getOriginalElement();
// TODO: In the fieldObj, save the field's id, className, cssText
// in order to reset it on closeField. That way, we can muck with the field's
// css, id, class and restore to how it was at the end.
this.nodeName = field.nodeName;
this.savedClassName_ = field.className;
this.setInitialStyle(field.style.cssText);
field.className += ' editable';
this.makeEditableInternal(opt_iframeSrc);
};
/**
* Handles actually making something editable - creating necessary nodes,
* injecting content, etc.
* @param {string=} opt_iframeSrc URL to set the iframe src to if necessary.
* @protected
*/
goog.editor.Field.prototype.makeEditableInternal = function(opt_iframeSrc) {
this.makeIframeField_(opt_iframeSrc);
};
/**
* Handle the loading of the field (e.g. once the field is ready to setup).
* TODO(user): this should probably just be moved into dispatchLoadEvent_.
* @protected
*/
goog.editor.Field.prototype.handleFieldLoad = function() {
if (goog.userAgent.IE) {
// This sometimes fails if the selection is invalid. This can happen, for
// example, if you attach a CLICK handler to the field that causes the
// field to be removed from the DOM and replaced with an editor
// -- however, listening to another event like MOUSEDOWN does not have this
// issue since no mouse selection has happened at that time.
goog.dom.Range.clearSelection(this.editableDomHelper.getWindow());
}
if (goog.editor.Field.getActiveFieldId() != this.id) {
this.execCommand(goog.editor.Command.UPDATE_LOREM);
}
this.setupChangeListeners_();
this.dispatchLoadEvent_();
// Enabling plugins after we fire the load event so that clients have a
// chance to set initial field contents before we start mucking with
// everything.
for (var classId in this.plugins_) {
this.plugins_[classId].enable(this);
}
};
/**
* Closes the field and cancels all pending change timers. Note that this
* means that if a change event has not fired yet, it will not fire. Clients
* should check fieldOj.isModified() if they depend on the final change event.
* Throws an error if the field is already uneditable.
*
* @param {boolean=} opt_skipRestore True to prevent copying of editable field
* contents back into the original node.
*/
goog.editor.Field.prototype.makeUneditable = function(opt_skipRestore) {
if (this.isUneditable()) {
throw Error('makeUneditable: Field is already uneditable');
}
// Fire any events waiting on a timeout.
// Clearing delayed change also clears changeTimerGecko_.
this.clearDelayedChange();
this.selectionChangeTimer_.fireIfActive();
this.execCommand(goog.editor.Command.CLEAR_LOREM);
var html = null;
if (!opt_skipRestore && this.getElement()) {
// Rest of cleanup is simpler if field was never initialized.
html = this.getCleanContents();
}
// First clean up anything that happens in makeFieldEditable
// (i.e. anything that needs cleanup even if field has not loaded).
this.clearFieldLoadListener_();
var field = this.getOriginalElement();
if (goog.editor.Field.getActiveFieldId() == field.id) {
goog.editor.Field.setActiveFieldId(null);
}
// Clear all listeners before removing the nodes from the dom - if
// there are listeners on the iframe window, Firefox throws errors trying
// to unlisten once the iframe is no longer in the dom.
this.clearListeners();
// For fields that have loaded, clean up anything that happened in
// handleFieldOpen or later.
// If html is provided, copy it back and reset the properties on the field
// so that the original node will have the same properties as it did before
// it was made editable.
if (goog.isString(html)) {
goog.editor.node.replaceInnerHtml(field, html);
this.resetOriginalElemProperties();
}
this.restoreDom();
this.tearDownFieldObject_();
// On Safari, make sure to un-focus the field so that the
// native "current field" highlight style gets removed.
if (goog.userAgent.WEBKIT) {
field.blur();
}
this.execCommand(goog.editor.Command.UPDATE_LOREM);
this.dispatchEvent(goog.editor.Field.EventType.UNLOAD);
};
/**
* Restores the dom to how it was before being made editable.
* @protected
*/
goog.editor.Field.prototype.restoreDom = function() {
// TODO(user): Consider only removing the iframe if we are
// restoring the original node, aka, if opt_html.
var field = this.getOriginalElement();
// TODO(robbyw): Consider throwing an error if !field.
if (field) {
// If the field is in the process of loading when it starts getting torn
// up, the iframe will not exist.
var iframe = this.getEditableIframe();
if (iframe) {
goog.dom.replaceNode(field, iframe);
}
}
};
/**
* Returns true if the field needs to be loaded asynchrnously.
* @return {boolean} True if loads are async.
* @protected
*/
goog.editor.Field.prototype.shouldLoadAsynchronously = function() {
if (!goog.isDef(this.isHttps_)) {
this.isHttps_ = false;
if (goog.userAgent.IE && this.usesIframe()) {
// IE iframes need to load asynchronously if they are in https as we need
// to set an actual src on the iframe and wait for it to load.
// Find the top-most window we have access to and see if it's https.
// Technically this could fail if we have an http frame in an https frame
// on the same domain (or vice versa), but walking up the window heirarchy
// to find the first window that has an http* protocol seems like
// overkill.
var win = this.originalDomHelper.getWindow();
while (win != win.parent) {
try {
win = win.parent;
} catch (e) {
break;
}
}
var loc = win.location;
this.isHttps_ = loc.protocol == 'https:' &&
loc.search.indexOf('nocheckhttps') == -1;
}
}
return this.isHttps_;
};
/**
* Start the editable iframe creation process for Mozilla or IE whitebox.
* The iframes load asynchronously.
*
* @param {string=} opt_iframeSrc URL to set the iframe src to if necessary.
* @private
*/
goog.editor.Field.prototype.makeIframeField_ = function(opt_iframeSrc) {
var field = this.getOriginalElement();
// TODO(robbyw): Consider throwing an error if !field.
if (field) {
var html = field.innerHTML;
// Invoke prepareContentsHtml on all plugins to prepare html for editing.
// Make sure this is done before calling this.attachFrame which removes the
// original element from DOM tree. Plugins may assume that the original
// element is still in its original position in DOM.
var styles = {};
html = this.reduceOp_(goog.editor.Plugin.Op.PREPARE_CONTENTS_HTML,
html, styles);
var iframe = /** @type {HTMLIFrameElement} */(
this.originalDomHelper.createDom(goog.dom.TagName.IFRAME,
this.getIframeAttributes()));
// TODO(nicksantos): Figure out if this is ever needed in SAFARI?
// In IE over HTTPS we need to wait for a load event before we set up the
// iframe, this is to prevent a security prompt or access is denied
// errors.
// NOTE(user): This hasn't been confirmed. isHttps_ allows a query
// param, nocheckhttps, which we can use to ascertain if this is actually
// needed. It was originally thought to be needed for IE6 SP1, but
// errors have been seen in IE7 as well.
if (this.shouldLoadAsynchronously()) {
// onLoad is the function to call once the iframe is ready to continue
// loading.
var onLoad = goog.bind(this.iframeFieldLoadHandler, this, iframe,
html, styles);
this.fieldLoadListenerKey_ = goog.events.listen(iframe,
goog.events.EventType.LOAD, onLoad, true);
if (opt_iframeSrc) {
iframe.src = opt_iframeSrc;
}
}
this.attachIframe(iframe);
// Only continue if its not IE HTTPS in which case we're waiting for load.
if (!this.shouldLoadAsynchronously()) {
this.iframeFieldLoadHandler(iframe, html, styles);
}
}
};
/**
* Given the original field element, and the iframe that is destined to
* become the editable field, styles them appropriately and add the iframe
* to the dom.
*
* @param {HTMLIFrameElement} iframe The iframe element.
* @protected
*/
goog.editor.Field.prototype.attachIframe = function(iframe) {
var field = this.getOriginalElement();
// TODO(user): Why do we do these two lines .. and why whitebox only?
iframe.className = field.className;
iframe.id = field.id;
goog.dom.replaceNode(iframe, field);
};
/**
* @param {Object} extraStyles A map of extra styles.
* @return {goog.editor.icontent.FieldFormatInfo} The FieldFormatInfo object for
* this field's configuration.
* @protected
*/
goog.editor.Field.prototype.getFieldFormatInfo = function(extraStyles) {
var originalElement = this.getOriginalElement();
var isStandardsMode = goog.editor.node.isStandardsMode(originalElement);
return new goog.editor.icontent.FieldFormatInfo(
this.id,
isStandardsMode,
false,
false,
extraStyles);
};
/**
* Writes the html content into the iframe. Handles writing any aditional
* styling as well.
* @param {HTMLIFrameElement} iframe Iframe to write contents into.
* @param {string} innerHtml The html content to write into the iframe.
* @param {Object} extraStyles A map of extra style attributes.
* @protected
*/
goog.editor.Field.prototype.writeIframeContent = function(
iframe, innerHtml, extraStyles) {
var formatInfo = this.getFieldFormatInfo(extraStyles);
if (this.shouldLoadAsynchronously()) {
var doc = goog.dom.getFrameContentDocument(iframe);
goog.editor.icontent.writeHttpsInitialIframe(formatInfo, doc, innerHtml);
} else {
var styleInfo = new goog.editor.icontent.FieldStyleInfo(
this.getElement(), this.cssStyles);
goog.editor.icontent.writeNormalInitialIframe(formatInfo, innerHtml,
styleInfo, iframe);
}
};
/**
* The function to call when the editable iframe loads.
*
* @param {HTMLIFrameElement} iframe Iframe that just loaded.
* @param {string} innerHtml Html to put inside the body of the iframe.
* @param {Object} styles Property-value map of CSS styles to install on
* editable field.
* @protected
*/
goog.editor.Field.prototype.iframeFieldLoadHandler = function(iframe,
innerHtml, styles) {
this.clearFieldLoadListener_();
iframe.allowTransparency = 'true';
this.writeIframeContent(iframe, innerHtml, styles);
var doc = goog.dom.getFrameContentDocument(iframe);
// Make sure to get this pointer after the doc.write as the doc.write
// clobbers all the document contents.
var body = doc.body;
this.setupFieldObject(body);
if (!goog.editor.BrowserFeature.HAS_CONTENT_EDITABLE &&
this.usesIframe()) {
this.turnOnDesignModeGecko();
}
this.handleFieldLoad();
};
/**
* Clears fieldLoadListener for a field. Must be called even (especially?) if
* the field is not yet loaded and therefore not in this.fieldMap_
* @private
*/
goog.editor.Field.prototype.clearFieldLoadListener_ = function() {
if (this.fieldLoadListenerKey_) {
goog.events.unlistenByKey(this.fieldLoadListenerKey_);
this.fieldLoadListenerKey_ = null;
}
};
/**
* @return {Object} Get the HTML attributes for this field's iframe.
* @protected
*/
goog.editor.Field.prototype.getIframeAttributes = function() {
var iframeStyle = 'padding:0;' + this.getOriginalElement().style.cssText;
if (!goog.string.endsWith(iframeStyle, ';')) {
iframeStyle += ';';
}
iframeStyle += 'background-color:white;';
// Ensure that the iframe has default overflow styling. If overflow is
// set to auto, an IE rendering bug can occur when it tries to render a
// table at the very bottom of the field, such that the table would cause
// a scrollbar, that makes the entire field go blank.
if (goog.userAgent.IE) {
iframeStyle += 'overflow:visible;';
}
return { 'frameBorder': 0, 'style': iframeStyle };
};
| 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 Trogedit constants for browser features and quirks that should
* be used by the rich text editor.
*/
goog.provide('goog.editor.BrowserFeature');
goog.require('goog.editor.defines');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');
goog.require('goog.userAgent.product.isVersion');
/**
* Maps browser quirks to boolean values, detailing what the current
* browser supports.
* @type {Object}
*/
goog.editor.BrowserFeature = {
// Whether this browser uses the IE TextRange object.
HAS_IE_RANGES: goog.userAgent.IE && !goog.userAgent.isDocumentMode(9),
// Whether this browser uses the W3C standard Range object.
// Assumes IE higher versions will be compliance with W3C standard.
HAS_W3C_RANGES: goog.userAgent.GECKO || goog.userAgent.WEBKIT ||
goog.userAgent.OPERA ||
(goog.userAgent.IE && goog.userAgent.isDocumentMode(9)),
// Has the contentEditable attribute, which makes nodes editable.
//
// NOTE(nicksantos): FF3 has contentEditable, but there are 3 major reasons
// why we don't use it:
// 1) In FF3, we listen for key events on the document, and we'd have to
// filter them properly. See TR_Browser.USE_DOCUMENT_FOR_KEY_EVENTS.
// 2) In FF3, we listen for focus/blur events on the document, which
// simply doesn't make sense in contentEditable. focus/blur
// on contentEditable elements still has some quirks, which we're
// talking to Firefox-team about.
// 3) We currently use Mutation events in FF3 to detect changes,
// and these are dispatched on the document only.
// If we ever hope to support FF3/contentEditable, all 3 of these issues
// will need answers. Most just involve refactoring at our end.
HAS_CONTENT_EDITABLE: goog.userAgent.IE || goog.userAgent.WEBKIT ||
goog.userAgent.OPERA ||
(goog.editor.defines.USE_CONTENTEDITABLE_IN_FIREFOX_3 &&
goog.userAgent.GECKO && goog.userAgent.isVersion('1.9')),
// Whether to use mutation event types to detect changes
// in the field contents.
USE_MUTATION_EVENTS: goog.userAgent.GECKO,
// Whether the browser has a functional DOMSubtreeModified event.
// TODO(user): Enable for all FF3 once we're confident this event fires
// reliably. Currently it's only enabled if using contentEditable in FF as
// we have no other choice in that case but to use this event.
HAS_DOM_SUBTREE_MODIFIED_EVENT: goog.userAgent.WEBKIT ||
(goog.editor.defines.USE_CONTENTEDITABLE_IN_FIREFOX_3 &&
goog.userAgent.GECKO && goog.userAgent.isVersion('1.9')),
// Whether nodes can be copied from one document to another
HAS_DOCUMENT_INDEPENDENT_NODES: goog.userAgent.GECKO,
// Whether the cursor goes before or inside the first block element on
// focus, e.g., <body><p>foo</p></body>. FF will put the cursor before the
// paragraph on focus, which is wrong.
PUTS_CURSOR_BEFORE_FIRST_BLOCK_ELEMENT_ON_FOCUS: goog.userAgent.GECKO,
// Whether the selection of one frame is cleared when another frame
// is focused.
CLEARS_SELECTION_WHEN_FOCUS_LEAVES:
goog.userAgent.IE || goog.userAgent.WEBKIT || goog.userAgent.OPERA,
// Whether "unselectable" is supported as an element style.
HAS_UNSELECTABLE_STYLE: goog.userAgent.GECKO || goog.userAgent.WEBKIT,
// Whether this browser's "FormatBlock" command does not suck.
FORMAT_BLOCK_WORKS_FOR_BLOCKQUOTES: goog.userAgent.GECKO ||
goog.userAgent.WEBKIT || goog.userAgent.OPERA,
// Whether this browser's "FormatBlock" command may create multiple
// blockquotes.
CREATES_MULTIPLE_BLOCKQUOTES:
(goog.userAgent.WEBKIT && !goog.userAgent.isVersion('534.16')) ||
goog.userAgent.OPERA,
// Whether this browser's "FormatBlock" command will wrap blockquotes
// inside of divs, instead of replacing divs with blockquotes.
WRAPS_BLOCKQUOTE_IN_DIVS: goog.userAgent.OPERA,
// Whether the readystatechange event is more reliable than load.
PREFERS_READY_STATE_CHANGE_EVENT: goog.userAgent.IE,
// Whether hitting the tab key will fire a keypress event.
// see http://www.quirksmode.org/js/keys.html
TAB_FIRES_KEYPRESS: !goog.userAgent.IE,
// Has a standards mode quirk where width=100% doesn't do the right thing,
// but width=99% does.
// TODO(user|user): This should be fixable by less hacky means
NEEDS_99_WIDTH_IN_STANDARDS_MODE: goog.userAgent.IE,
// Whether keyboard events only reliably fire on the document.
// On Gecko without contentEditable, keyboard events only fire reliably on the
// document element. With contentEditable, the field itself is focusable,
// which means that it will fire key events. This does not apply if
// application is using ContentEditableField or otherwise overriding Field
// not to use an iframe.
USE_DOCUMENT_FOR_KEY_EVENTS: goog.userAgent.GECKO &&
!goog.editor.defines.USE_CONTENTEDITABLE_IN_FIREFOX_3,
// Whether this browser shows non-standard attributes in innerHTML.
SHOWS_CUSTOM_ATTRS_IN_INNER_HTML: goog.userAgent.IE,
// Whether this browser shrinks empty nodes away to nothing.
// (If so, we need to insert some space characters into nodes that
// shouldn't be collapsed)
COLLAPSES_EMPTY_NODES:
goog.userAgent.GECKO || goog.userAgent.WEBKIT || goog.userAgent.OPERA,
// Whether we must convert <strong> and <em> tags to <b>, <i>.
CONVERT_TO_B_AND_I_TAGS: goog.userAgent.GECKO || goog.userAgent.OPERA,
// Whether this browser likes to tab through images in contentEditable mode,
// and we like to disable this feature.
TABS_THROUGH_IMAGES: goog.userAgent.IE,
// Whether this browser unescapes urls when you extract it from the href tag.
UNESCAPES_URLS_WITHOUT_ASKING: goog.userAgent.IE &&
!goog.userAgent.isVersion('7.0'),
// Whether this browser supports execCommand("styleWithCSS") to toggle between
// inserting html tags or inline styling for things like bold, italic, etc.
HAS_STYLE_WITH_CSS:
goog.userAgent.GECKO && goog.userAgent.isVersion('1.8') ||
goog.userAgent.WEBKIT || goog.userAgent.OPERA,
// Whether clicking on an editable link will take you to that site.
FOLLOWS_EDITABLE_LINKS: goog.userAgent.WEBKIT ||
goog.userAgent.IE && goog.userAgent.isVersion('9'),
// Whether this browser has document.activeElement available.
HAS_ACTIVE_ELEMENT:
goog.userAgent.IE || goog.userAgent.OPERA ||
goog.userAgent.GECKO && goog.userAgent.isVersion('1.9'),
// Whether this browser supports the setCapture method on DOM elements.
HAS_SET_CAPTURE: goog.userAgent.IE,
// Whether this browser can't set background color when the selection
// is collapsed.
EATS_EMPTY_BACKGROUND_COLOR: goog.userAgent.GECKO ||
goog.userAgent.WEBKIT && !goog.userAgent.isVersion('527'),
// Whether this browser supports the "focusin" or "DOMFocusIn" event
// consistently.
// NOTE(nicksantos): FF supports DOMFocusIn, but doesn't seem to do so
// consistently.
SUPPORTS_FOCUSIN: goog.userAgent.IE || goog.userAgent.OPERA,
// Whether clicking on an image will cause the selection to move to the image.
// Note: Gecko moves the selection, but it won't always go to the image.
// For example, if the image is wrapped in a div, and you click on the img,
// anchorNode = focusNode = div, anchorOffset = 0, focusOffset = 1, so this
// is another way of "selecting" the image, but there are too many special
// cases like this so we will do the work manually.
SELECTS_IMAGES_ON_CLICK: goog.userAgent.IE || goog.userAgent.OPERA,
// Whether this browser moves <style> tags into new <head> elements.
MOVES_STYLE_TO_HEAD: goog.userAgent.WEBKIT,
// Whether this browser collapses the selection in a contenteditable when the
// mouse is pressed in a non-editable portion of the same frame, even if
// Event.preventDefault is called. This field is deprecated and unused -- only
// old versions of Opera have this bug.
COLLAPSES_SELECTION_ONMOUSEDOWN: false,
// Whether the user can actually create a selection in this browser with the
// caret in the MIDDLE of the selection by double-clicking.
CARET_INSIDE_SELECTION: goog.userAgent.OPERA,
// Whether the browser focuses <body contenteditable> automatically when
// the user clicks on <html>. This field is deprecated and unused -- only old
// versions of Opera don't have this behavior.
FOCUSES_EDITABLE_BODY_ON_HTML_CLICK: true,
// Whether to use keydown for key listening (uses keypress otherwise). Taken
// from goog.events.KeyHandler.
USES_KEYDOWN: goog.userAgent.IE ||
goog.userAgent.WEBKIT && goog.userAgent.isVersion('525'),
// Whether this browser converts spaces to non-breaking spaces when calling
// execCommand's RemoveFormat.
// See: https://bugs.webkit.org/show_bug.cgi?id=14062
ADDS_NBSPS_IN_REMOVE_FORMAT:
goog.userAgent.WEBKIT && !goog.userAgent.isVersion('531'),
// Whether the browser will get stuck inside a link. That is, if your cursor
// is after a link and you type, does your text go inside the link tag.
// Bug: http://bugs.webkit.org/show_bug.cgi?id=17697
GETS_STUCK_IN_LINKS:
goog.userAgent.WEBKIT && !goog.userAgent.isVersion('528'),
// Whether the browser corrupts empty text nodes in Node#normalize,
// removing them from the Document instead of merging them.
NORMALIZE_CORRUPTS_EMPTY_TEXT_NODES: goog.userAgent.GECKO &&
goog.userAgent.isVersion('1.9') || goog.userAgent.IE ||
goog.userAgent.OPERA ||
goog.userAgent.WEBKIT && goog.userAgent.isVersion('531'),
// Whether the browser corrupts all text nodes in Node#normalize,
// removing them from the Document instead of merging them.
NORMALIZE_CORRUPTS_ALL_TEXT_NODES: goog.userAgent.IE,
// Browsers where executing subscript then superscript (or vv) will cause both
// to be applied in a nested fashion instead of the first being overwritten by
// the second.
NESTS_SUBSCRIPT_SUPERSCRIPT: goog.userAgent.IE || goog.userAgent.GECKO ||
goog.userAgent.OPERA,
// Whether this browser can place a cursor in an empty element natively.
CAN_SELECT_EMPTY_ELEMENT: !goog.userAgent.IE && !goog.userAgent.WEBKIT,
FORGETS_FORMATTING_WHEN_LISTIFYING: goog.userAgent.GECKO ||
goog.userAgent.WEBKIT && !goog.userAgent.isVersion('526'),
LEAVES_P_WHEN_REMOVING_LISTS: goog.userAgent.IE || goog.userAgent.OPERA,
CAN_LISTIFY_BR: !goog.userAgent.IE && !goog.userAgent.OPERA,
// See bug 1286408. When somewhere inside your selection there is an element
// with a style attribute that sets the font size, if you change the font
// size, the browser creates a font tag, but the font size in the style attr
// overrides the font tag. Only webkit removes that font size from the style
// attr.
DOESNT_OVERRIDE_FONT_SIZE_IN_STYLE_ATTR: !goog.userAgent.WEBKIT,
// Implements this spec about dragging files from the filesystem to the
// browser: http://www.whatwg/org/specs/web-apps/current-work/#dnd
SUPPORTS_HTML5_FILE_DRAGGING: (goog.userAgent.product.CHROME &&
goog.userAgent.product.isVersion('4')) ||
(goog.userAgent.product.SAFARI && goog.userAgent.isVersion('533')) ||
(goog.userAgent.GECKO && goog.userAgent.isVersion('2.0')) ||
(goog.userAgent.IE && goog.userAgent.isVersion('10')),
// Version of Opera that supports the opera-defaultBlock execCommand to change
// the default block inserted when [return] is pressed. Note that this only is
// used if the caret is not already in a block that can be repeated.
// TODO(user): Link to public documentation of this feature if Opera puts
// something up about it.
SUPPORTS_OPERA_DEFAULTBLOCK_COMMAND:
goog.userAgent.OPERA && goog.userAgent.isVersion('11.10'),
SUPPORTS_FILE_PASTING: goog.userAgent.product.CHROME &&
goog.userAgent.product.isVersion('12')
};
| 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 Utilties for working with ranges.
*
* @author nicksantos@google.com (Nick Santos)
*/
goog.provide('goog.editor.range');
goog.provide('goog.editor.range.Point');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.Range');
goog.require('goog.dom.RangeEndpoint');
goog.require('goog.dom.SavedCaretRange');
goog.require('goog.editor.BrowserFeature');
goog.require('goog.editor.node');
goog.require('goog.editor.style');
goog.require('goog.iter');
/**
* Given a range and an element, create a narrower range that is limited to the
* boundaries of the element. If the range starts (or ends) outside the
* element, the narrowed range's start point (or end point) will be the
* leftmost (or rightmost) leaf of the element.
* @param {goog.dom.AbstractRange} range The range.
* @param {Element} el The element to limit the range to.
* @return {goog.dom.AbstractRange} A new narrowed range, or null if the
* element does not contain any part of the given range.
*/
goog.editor.range.narrow = function(range, el) {
var startContainer = range.getStartNode();
var endContainer = range.getEndNode();
if (startContainer && endContainer) {
var isElement = function(node) {
return node == el;
};
var hasStart = goog.dom.getAncestor(startContainer, isElement, true);
var hasEnd = goog.dom.getAncestor(endContainer, isElement, true);
if (hasStart && hasEnd) {
// The range is contained entirely within this element.
return range.clone();
} else if (hasStart) {
// The range starts inside the element, but ends outside it.
var leaf = goog.editor.node.getRightMostLeaf(el);
return goog.dom.Range.createFromNodes(
range.getStartNode(), range.getStartOffset(),
leaf, goog.editor.node.getLength(leaf));
} else if (hasEnd) {
// The range starts outside the element, but ends inside it.
return goog.dom.Range.createFromNodes(
goog.editor.node.getLeftMostLeaf(el), 0,
range.getEndNode(), range.getEndOffset());
}
}
// The selection starts and ends outside the element.
return null;
};
/**
* Given a range, expand the range to include outer tags if the full contents of
* those tags are entirely selected. This essentially changes the dom position,
* but not the visible position of the range.
* Ex. <li>foo</li> if "foo" is selected, instead of returning start and end
* nodes as the foo text node, return the li.
* @param {goog.dom.AbstractRange} range The range.
* @param {Node=} opt_stopNode Optional node to stop expanding past.
* @return {goog.dom.AbstractRange} The expanded range.
*/
goog.editor.range.expand = function(range, opt_stopNode) {
// Expand the start out to the common container.
var expandedRange = goog.editor.range.expandEndPointToContainer_(
range, goog.dom.RangeEndpoint.START, opt_stopNode);
// Expand the end out to the common container.
expandedRange = goog.editor.range.expandEndPointToContainer_(
expandedRange, goog.dom.RangeEndpoint.END, opt_stopNode);
var startNode = expandedRange.getStartNode();
var endNode = expandedRange.getEndNode();
var startOffset = expandedRange.getStartOffset();
var endOffset = expandedRange.getEndOffset();
// If we have reached a common container, now expand out.
if (startNode == endNode) {
while (endNode != opt_stopNode &&
startOffset == 0 &&
endOffset == goog.editor.node.getLength(endNode)) {
// Select the parent instead.
var parentNode = endNode.parentNode;
startOffset = goog.array.indexOf(parentNode.childNodes, endNode);
endOffset = startOffset + 1;
endNode = parentNode;
}
startNode = endNode;
}
return goog.dom.Range.createFromNodes(startNode, startOffset,
endNode, endOffset);
};
/**
* Given a range, expands the start or end points as far out towards the
* range's common container (or stopNode, if provided) as possible, while
* perserving the same visible position.
*
* @param {goog.dom.AbstractRange} range The range to expand.
* @param {goog.dom.RangeEndpoint} endpoint The endpoint to expand.
* @param {Node=} opt_stopNode Optional node to stop expanding past.
* @return {goog.dom.AbstractRange} The expanded range.
* @private
*/
goog.editor.range.expandEndPointToContainer_ = function(range, endpoint,
opt_stopNode) {
var expandStart = endpoint == goog.dom.RangeEndpoint.START;
var node = expandStart ? range.getStartNode() : range.getEndNode();
var offset = expandStart ? range.getStartOffset() : range.getEndOffset();
var container = range.getContainerElement();
// Expand the node out until we reach the container or the stop node.
while (node != container && node != opt_stopNode) {
// It is only valid to expand the start if we are at the start of a node
// (offset 0) or expand the end if we are at the end of a node
// (offset length).
if (expandStart && offset != 0 ||
!expandStart && offset != goog.editor.node.getLength(node)) {
break;
}
var parentNode = node.parentNode;
var index = goog.array.indexOf(parentNode.childNodes, node);
offset = expandStart ? index : index + 1;
node = parentNode;
}
return goog.dom.Range.createFromNodes(
expandStart ? node : range.getStartNode(),
expandStart ? offset : range.getStartOffset(),
expandStart ? range.getEndNode() : node,
expandStart ? range.getEndOffset() : offset);
};
/**
* Cause the window's selection to be the start of this node.
* @param {Node} node The node to select the start of.
*/
goog.editor.range.selectNodeStart = function(node) {
goog.dom.Range.createCaret(goog.editor.node.getLeftMostLeaf(node), 0).
select();
};
/**
* Position the cursor immediately to the left or right of "node".
* In Firefox, the selection parent is outside of "node", so the cursor can
* effectively be moved to the end of a link node, without being considered
* inside of it.
* Note: This does not always work in WebKit. In particular, if you try to
* place a cursor to the right of a link, typing still puts you in the link.
* Bug: http://bugs.webkit.org/show_bug.cgi?id=17697
* @param {Node} node The node to position the cursor relative to.
* @param {boolean} toLeft True to place it to the left, false to the right.
* @return {goog.dom.AbstractRange} The newly selected range.
*/
goog.editor.range.placeCursorNextTo = function(node, toLeft) {
var parent = node.parentNode;
var offset = goog.array.indexOf(parent.childNodes, node) +
(toLeft ? 0 : 1);
var point = goog.editor.range.Point.createDeepestPoint(
parent, offset, toLeft, true);
var range = goog.dom.Range.createCaret(point.node, point.offset);
range.select();
return range;
};
/**
* Normalizes the node, preserving the selection of the document.
*
* May also normalize things outside the node, if it is more efficient to do so.
*
* @param {Node} node The node to normalize.
*/
goog.editor.range.selectionPreservingNormalize = function(node) {
var doc = goog.dom.getOwnerDocument(node);
var selection = goog.dom.Range.createFromWindow(goog.dom.getWindow(doc));
var normalizedRange =
goog.editor.range.rangePreservingNormalize(node, selection);
if (normalizedRange) {
normalizedRange.select();
}
};
/**
* Manually normalizes the node in IE, since native normalize in IE causes
* transient problems.
* @param {Node} node The node to normalize.
* @private
*/
goog.editor.range.normalizeNodeIe_ = function(node) {
var lastText = null;
var child = node.firstChild;
while (child) {
var next = child.nextSibling;
if (child.nodeType == goog.dom.NodeType.TEXT) {
if (child.nodeValue == '') {
node.removeChild(child);
} else if (lastText) {
lastText.nodeValue += child.nodeValue;
node.removeChild(child);
} else {
lastText = child;
}
} else {
goog.editor.range.normalizeNodeIe_(child);
lastText = null;
}
child = next;
}
};
/**
* Normalizes the given node.
* @param {Node} node The node to normalize.
*/
goog.editor.range.normalizeNode = function(node) {
if (goog.userAgent.IE) {
goog.editor.range.normalizeNodeIe_(node);
} else {
node.normalize();
}
};
/**
* Normalizes the node, preserving a range of the document.
*
* May also normalize things outside the node, if it is more efficient to do so.
*
* @param {Node} node The node to normalize.
* @param {goog.dom.AbstractRange?} range The range to normalize.
* @return {goog.dom.AbstractRange?} The range, adjusted for normalization.
*/
goog.editor.range.rangePreservingNormalize = function(node, range) {
if (range) {
var rangeFactory = goog.editor.range.normalize(range);
// WebKit has broken selection affinity, so carets tend to jump out of the
// beginning of inline elements. This means that if we're doing the
// normalize as the result of a range that will later become the selection,
// we might not normalize something in the range after it is read back from
// the selection. We can't just normalize the parentNode here because WebKit
// can move the selection range out of multiple inline parents.
var container = goog.editor.style.getContainer(range.getContainerElement());
}
if (container) {
goog.editor.range.normalizeNode(
goog.dom.findCommonAncestor(container, node));
} else if (node) {
goog.editor.range.normalizeNode(node);
}
if (rangeFactory) {
return rangeFactory();
} else {
return null;
}
};
/**
* Get the deepest point in the DOM that's equivalent to the endpoint of the
* given range.
*
* @param {goog.dom.AbstractRange} range A range.
* @param {boolean} atStart True for the start point, false for the end point.
* @return {goog.editor.range.Point} The end point, expressed as a node
* and an offset.
*/
goog.editor.range.getDeepEndPoint = function(range, atStart) {
return atStart ?
goog.editor.range.Point.createDeepestPoint(
range.getStartNode(), range.getStartOffset()) :
goog.editor.range.Point.createDeepestPoint(
range.getEndNode(), range.getEndOffset());
};
/**
* Given a range in the current DOM, create a factory for a range that
* represents the same selection in a normalized DOM. The factory function
* should be invoked after the DOM is normalized.
*
* All browsers do a bad job preserving ranges across DOM normalization.
* The issue is best described in this 5-year-old bug report:
* https://bugzilla.mozilla.org/show_bug.cgi?id=191864
* For most applications, this isn't a problem. The browsers do a good job
* handling un-normalized text, so there's usually no reason to normalize.
*
* The exception to this rule is the rich text editing commands
* execCommand and queryCommandValue, which will fail often if there are
* un-normalized text nodes.
*
* The factory function creates new ranges so that we can normalize the DOM
* without problems. It must be created before any normalization happens,
* and invoked after normalization happens.
*
* @param {goog.dom.AbstractRange} range The range to normalize. It may
* become invalid after body.normalize() is called.
* @return {function(): goog.dom.AbstractRange} A factory for a normalized
* range. Should be called after body.normalize() is called.
*/
goog.editor.range.normalize = function(range) {
var startPoint = goog.editor.range.normalizePoint_(
goog.editor.range.getDeepEndPoint(range, true));
var startParent = startPoint.getParentPoint();
var startPreviousSibling = startPoint.node.previousSibling;
if (startPoint.node.nodeType == goog.dom.NodeType.TEXT) {
startPoint.node = null;
}
var endPoint = goog.editor.range.normalizePoint_(
goog.editor.range.getDeepEndPoint(range, false));
var endParent = endPoint.getParentPoint();
var endPreviousSibling = endPoint.node.previousSibling;
if (endPoint.node.nodeType == goog.dom.NodeType.TEXT) {
endPoint.node = null;
}
/** @return {goog.dom.AbstractRange} The normalized range. */
return function() {
if (!startPoint.node && startPreviousSibling) {
// If startPoint.node was previously an empty text node with no siblings,
// startPreviousSibling may not have a nextSibling since that node will no
// longer exist. Do our best and point to the end of the previous
// element.
startPoint.node = startPreviousSibling.nextSibling;
if (!startPoint.node) {
startPoint = goog.editor.range.Point.getPointAtEndOfNode(
startPreviousSibling);
}
}
if (!endPoint.node && endPreviousSibling) {
// If endPoint.node was previously an empty text node with no siblings,
// endPreviousSibling may not have a nextSibling since that node will no
// longer exist. Do our best and point to the end of the previous
// element.
endPoint.node = endPreviousSibling.nextSibling;
if (!endPoint.node) {
endPoint = goog.editor.range.Point.getPointAtEndOfNode(
endPreviousSibling);
}
}
return goog.dom.Range.createFromNodes(
startPoint.node || startParent.node.firstChild || startParent.node,
startPoint.offset,
endPoint.node || endParent.node.firstChild || endParent.node,
endPoint.offset);
};
};
/**
* Given a point in the current DOM, adjust it to represent the same point in
* a normalized DOM.
*
* See the comments on goog.editor.range.normalize for more context.
*
* @param {goog.editor.range.Point} point A point in the document.
* @return {goog.editor.range.Point} The same point, for easy chaining.
* @private
*/
goog.editor.range.normalizePoint_ = function(point) {
var previous;
if (point.node.nodeType == goog.dom.NodeType.TEXT) {
// If the cursor position is in a text node,
// look at all the previous text siblings of the text node,
// and set the offset relative to the earliest text sibling.
for (var current = point.node.previousSibling;
current && current.nodeType == goog.dom.NodeType.TEXT;
current = current.previousSibling) {
point.offset += goog.editor.node.getLength(current);
}
previous = current;
} else {
previous = point.node.previousSibling;
}
var parent = point.node.parentNode;
point.node = previous ? previous.nextSibling : parent.firstChild;
return point;
};
/**
* Checks if a range is completely inside an editable region.
* @param {goog.dom.AbstractRange} range The range to test.
* @return {boolean} Whether the range is completely inside an editable region.
*/
goog.editor.range.isEditable = function(range) {
var rangeContainer = range.getContainerElement();
// Closure's implementation of getContainerElement() is a little too
// smart in IE when exactly one element is contained in the range.
// It assumes that there's a user whose intent was actually to select
// all that element's children, so it returns the element itself as its
// own containing element.
// This little sanity check detects this condition so we can account for it.
var rangeContainerIsOutsideRange =
range.getStartNode() != rangeContainer.parentElement;
return (rangeContainerIsOutsideRange &&
goog.editor.node.isEditableContainer(rangeContainer)) ||
goog.editor.node.isEditable(rangeContainer);
};
/**
* Returns whether the given range intersects with any instance of the given
* tag.
* @param {goog.dom.AbstractRange} range The range to check.
* @param {goog.dom.TagName} tagName The name of the tag.
* @return {boolean} Whether the given range intersects with any instance of
* the given tag.
*/
goog.editor.range.intersectsTag = function(range, tagName) {
if (goog.dom.getAncestorByTagNameAndClass(range.getContainerElement(),
tagName)) {
return true;
}
return goog.iter.some(range, function(node) {
return node.tagName == tagName;
});
};
/**
* One endpoint of a range, represented as a Node and and offset.
* @param {Node} node The node containing the point.
* @param {number} offset The offset of the point into the node.
* @constructor
*/
goog.editor.range.Point = function(node, offset) {
/**
* The node containing the point.
* @type {Node}
*/
this.node = node;
/**
* The offset of the point into the node.
* @type {number}
*/
this.offset = offset;
};
/**
* Gets the point of this point's node in the DOM.
* @return {goog.editor.range.Point} The node's point.
*/
goog.editor.range.Point.prototype.getParentPoint = function() {
var parent = this.node.parentNode;
return new goog.editor.range.Point(
parent, goog.array.indexOf(parent.childNodes, this.node));
};
/**
* Construct the deepest possible point in the DOM that's equivalent
* to the given point, expressed as a node and an offset.
* @param {Node} node The node containing the point.
* @param {number} offset The offset of the point from the node.
* @param {boolean=} opt_trendLeft Notice that a (node, offset) pair may be
* equivalent to more than one descendent (node, offset) pair in the DOM.
* By default, we trend rightward. If this parameter is true, then we
* trend leftward. The tendency to fall rightward by default is for
* consistency with other range APIs (like placeCursorNextTo).
* @param {boolean=} opt_stopOnChildlessElement If true, and we encounter
* a Node which is an Element that cannot have children, we return a Point
* based on its parent rather than that Node itself.
* @return {goog.editor.range.Point} A new point.
*/
goog.editor.range.Point.createDeepestPoint =
function(node, offset, opt_trendLeft, opt_stopOnChildlessElement) {
while (node.nodeType == goog.dom.NodeType.ELEMENT) {
var child = node.childNodes[offset];
if (!child && !node.lastChild) {
break;
} else if (child) {
var prevSibling = child.previousSibling;
if (opt_trendLeft && prevSibling) {
if (opt_stopOnChildlessElement &&
goog.editor.range.Point.isTerminalElement_(prevSibling)) {
break;
}
node = prevSibling;
offset = goog.editor.node.getLength(node);
} else {
if (opt_stopOnChildlessElement &&
goog.editor.range.Point.isTerminalElement_(child)) {
break;
}
node = child;
offset = 0;
}
} else {
if (opt_stopOnChildlessElement &&
goog.editor.range.Point.isTerminalElement_(node.lastChild)) {
break;
}
node = node.lastChild;
offset = goog.editor.node.getLength(node);
}
}
return new goog.editor.range.Point(node, offset);
};
/**
* Return true if the specified node is an Element that is not expected to have
* children. The createDeepestPoint() method should not traverse into
* such elements.
* @param {Node} node .
* @return {boolean} True if the node is an Element that does not contain
* child nodes (e.g. BR, IMG).
* @private
*/
goog.editor.range.Point.isTerminalElement_ = function(node) {
return (node.nodeType == goog.dom.NodeType.ELEMENT &&
!goog.dom.canHaveChildren(node));
};
/**
* Construct a point at the very end of the given node.
* @param {Node} node The node to create a point for.
* @return {goog.editor.range.Point} A new point.
*/
goog.editor.range.Point.getPointAtEndOfNode = function(node) {
return new goog.editor.range.Point(node, goog.editor.node.getLength(node));
};
/**
* Saves the range by inserting carets into the HTML.
*
* Unlike the regular saveUsingCarets, this SavedRange normalizes text nodes.
* Browsers have other bugs where they don't handle split text nodes in
* contentEditable regions right.
*
* @param {goog.dom.AbstractRange} range The abstract range object.
* @return {goog.dom.SavedCaretRange} A saved caret range that normalizes
* text nodes.
*/
goog.editor.range.saveUsingNormalizedCarets = function(range) {
return new goog.editor.range.NormalizedCaretRange_(range);
};
/**
* Saves the range using carets, but normalizes text nodes when carets
* are removed.
* @see goog.editor.range.saveUsingNormalizedCarets
* @param {goog.dom.AbstractRange} range The range being saved.
* @constructor
* @extends {goog.dom.SavedCaretRange}
* @private
*/
goog.editor.range.NormalizedCaretRange_ = function(range) {
goog.dom.SavedCaretRange.call(this, range);
};
goog.inherits(goog.editor.range.NormalizedCaretRange_,
goog.dom.SavedCaretRange);
/**
* Normalizes text nodes whenever carets are removed from the document.
* @param {goog.dom.AbstractRange=} opt_range A range whose offsets have already
* been adjusted for caret removal; it will be adjusted and returned if it
* is also affected by post-removal operations, such as text node
* normalization.
* @return {goog.dom.AbstractRange|undefined} The adjusted range, if opt_range
* was provided.
* @override
*/
goog.editor.range.NormalizedCaretRange_.prototype.removeCarets =
function(opt_range) {
var startCaret = this.getCaret(true);
var endCaret = this.getCaret(false);
var node = startCaret && endCaret ?
goog.dom.findCommonAncestor(startCaret, endCaret) :
startCaret || endCaret;
goog.editor.range.NormalizedCaretRange_.superClass_.removeCarets.call(this);
if (opt_range) {
return goog.editor.range.rangePreservingNormalize(node, opt_range);
} else if (node) {
goog.editor.range.selectionPreservingNormalize(node);
}
};
| 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 Class to encapsulate an editable field that blends into the
* style of the page and never uses an iframe. The field's height can be
* controlled by CSS styles like min-height, max-height, and overflow. This is
* a goog.editor.Field, but overrides everything iframe related to use
* contentEditable divs. This is essentially a much lighter alternative to
* goog.editor.SeamlessField, but only works in Firefox 3+, and only works
* *well* in Firefox 12+ due to
* https://bugzilla.mozilla.org/show_bug.cgi?id=669026.
*
* @author gboyer@google.com (Garrett Boyer)
* @author jparent@google.com (Julie Parent)
* @author nicksantos@google.com (Nick Santos)
* @author ojan@google.com (Ojan Vafai)
*/
goog.provide('goog.editor.ContentEditableField');
goog.require('goog.asserts');
goog.require('goog.debug.Logger');
goog.require('goog.editor.Field');
/**
* This class encapsulates an editable field that is just a contentEditable
* div.
*
* To see events fired by this object, please see the base class.
*
* @param {string} id An identifer for the field. This is used to find the
* field and the element associated with this field.
* @param {Document=} opt_doc The document that the element with the given
* id can be found it.
* @constructor
* @extends {goog.editor.Field}
*/
goog.editor.ContentEditableField = function(id, opt_doc) {
goog.editor.Field.call(this, id, opt_doc);
};
goog.inherits(goog.editor.ContentEditableField, goog.editor.Field);
/**
* @override
*/
goog.editor.ContentEditableField.prototype.logger =
goog.debug.Logger.getLogger('goog.editor.ContentEditableField');
/** @override */
goog.editor.ContentEditableField.prototype.usesIframe = function() {
// Never uses an iframe in any browser.
return false;
};
// Overridden to improve dead code elimination only.
/** @override */
goog.editor.ContentEditableField.prototype.turnOnDesignModeGecko =
goog.nullFunction;
/** @override */
goog.editor.ContentEditableField.prototype.installStyles = function() {
goog.asserts.assert(!this.cssStyles, 'ContentEditableField does not support' +
' CSS styles; instead just write plain old CSS on the main page.');
};
/** @override */
goog.editor.ContentEditableField.prototype.makeEditableInternal = function(
opt_iframeSrc) {
var field = this.getOriginalElement();
if (field) {
this.setupFieldObject(field);
// TODO(gboyer): Allow clients/plugins to override with 'plaintext-only'
// for WebKit.
field.contentEditable = true;
this.injectContents(field.innerHTML, field);
this.handleFieldLoad();
}
};
/**
* @override
*
* ContentEditableField does not make any changes to the DOM when it is made
* editable other than setting contentEditable to true.
*/
goog.editor.ContentEditableField.prototype.restoreDom =
goog.nullFunction;
| 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 utility class for managing editable links.
*
* @author nicksantos@google.com (Nick Santos)
*/
goog.provide('goog.editor.Link');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.Range');
goog.require('goog.editor.BrowserFeature');
goog.require('goog.editor.Command');
goog.require('goog.editor.node');
goog.require('goog.editor.range');
goog.require('goog.string');
goog.require('goog.string.Unicode');
goog.require('goog.uri.utils');
goog.require('goog.uri.utils.ComponentIndex');
/**
* Wrap an editable link.
* @param {HTMLAnchorElement} anchor The anchor element.
* @param {boolean} isNew Whether this is a new link.
* @constructor
*/
goog.editor.Link = function(anchor, isNew) {
/**
* The link DOM element.
* @type {HTMLAnchorElement}
* @private
*/
this.anchor_ = anchor;
/**
* Whether this link represents a link just added to the document.
* @type {boolean}
* @private
*/
this.isNew_ = isNew;
/**
* Any extra anchors created by the browser from a selection in the same
* operation that created the primary link
* @type {!Array.<HTMLAnchorElement>}
* @private
*/
this.extraAnchors_ = [];
};
/**
* @return {HTMLAnchorElement} The anchor element.
*/
goog.editor.Link.prototype.getAnchor = function() {
return this.anchor_;
};
/**
* @return {!Array.<HTMLAnchorElement>} The extra anchor elements, if any,
* created by the browser from a selection.
*/
goog.editor.Link.prototype.getExtraAnchors = function() {
return this.extraAnchors_;
};
/**
* @return {string} The inner text for the anchor.
*/
goog.editor.Link.prototype.getCurrentText = function() {
if (!this.currentText_) {
this.currentText_ = goog.dom.getRawTextContent(this.getAnchor());
}
return this.currentText_;
};
/**
* @return {boolean} Whether the link is new.
*/
goog.editor.Link.prototype.isNew = function() {
return this.isNew_;
};
/**
* Set the url without affecting the isNew() status of the link.
* @param {string} url A URL.
*/
goog.editor.Link.prototype.initializeUrl = function(url) {
this.getAnchor().href = url;
};
/**
* Removes the link, leaving its contents in the document. Note that this
* object will no longer be usable/useful after this call.
*/
goog.editor.Link.prototype.removeLink = function() {
goog.dom.flattenElement(this.anchor_);
this.anchor_ = null;
while (this.extraAnchors_.length) {
goog.dom.flattenElement(/** @type {Element} */(this.extraAnchors_.pop()));
}
};
/**
* Change the link.
* @param {string} newText New text for the link. If the link contains all its
* text in one descendent, newText will only replace the text in that
* one node. Otherwise, we'll change the innerHTML of the whole
* link to newText.
* @param {string} newUrl A new URL.
*/
goog.editor.Link.prototype.setTextAndUrl = function(newText, newUrl) {
var anchor = this.getAnchor();
anchor.href = newUrl;
// If the text did not change, don't update link text.
var currentText = this.getCurrentText();
if (newText != currentText) {
var leaf = goog.editor.node.getLeftMostLeaf(anchor);
if (leaf.nodeType == goog.dom.NodeType.TEXT) {
leaf = leaf.parentNode;
}
if (goog.dom.getRawTextContent(leaf) != currentText) {
leaf = anchor;
}
goog.dom.removeChildren(leaf);
var domHelper = goog.dom.getDomHelper(leaf);
goog.dom.appendChild(leaf, domHelper.createTextNode(newText));
// The text changed, so force getCurrentText to recompute.
this.currentText_ = null;
}
this.isNew_ = false;
};
/**
* Places the cursor to the right of the anchor.
* Note that this is different from goog.editor.range's placeCursorNextTo
* in that it specifically handles the placement of a cursor in browsers
* that trap you in links, by adding a space when necessary and placing the
* cursor after that space.
*/
goog.editor.Link.prototype.placeCursorRightOf = function() {
var anchor = this.getAnchor();
// If the browser gets stuck in a link if we place the cursor next to it,
// we'll place the cursor after a space instead.
if (goog.editor.BrowserFeature.GETS_STUCK_IN_LINKS) {
var spaceNode;
var nextSibling = anchor.nextSibling;
// Check if there is already a space after the link. Only handle the
// simple case - the next node is a text node that starts with a space.
if (nextSibling &&
nextSibling.nodeType == goog.dom.NodeType.TEXT &&
(goog.string.startsWith(nextSibling.data, goog.string.Unicode.NBSP) ||
goog.string.startsWith(nextSibling.data, ' '))) {
spaceNode = nextSibling;
} else {
// If there isn't an obvious space to use, create one after the link.
var dh = goog.dom.getDomHelper(anchor);
spaceNode = dh.createTextNode(goog.string.Unicode.NBSP);
goog.dom.insertSiblingAfter(spaceNode, anchor);
}
// Move the selection after the space.
var range = goog.dom.Range.createCaret(spaceNode, 1);
range.select();
} else {
goog.editor.range.placeCursorNextTo(anchor, false);
}
};
/**
* Updates the cursor position and link bubble for this link.
* @param {goog.editor.Field} field The field in which the link is created.
* @param {string} url The link url.
* @private
*/
goog.editor.Link.prototype.updateLinkDisplay_ = function(field, url) {
this.initializeUrl(url);
this.placeCursorRightOf();
field.execCommand(goog.editor.Command.UPDATE_LINK_BUBBLE);
};
/**
* @return {string?} The modified string for the link if the link
* text appears to be a valid link. Returns null if this is not
* a valid link address.
*/
goog.editor.Link.prototype.getValidLinkFromText = function() {
var text = this.getCurrentText();
if (goog.editor.Link.isLikelyUrl(text)) {
if (text.search(/:/) < 0) {
return 'http://' + goog.string.trimLeft(text);
}
return text;
} else if (goog.editor.Link.isLikelyEmailAddress(text)) {
return 'mailto:' + text;
}
return null;
};
/**
* After link creation, finish creating the link depending on the type
* of link being created.
* @param {goog.editor.Field} field The field where this link is being created.
*/
goog.editor.Link.prototype.finishLinkCreation = function(field) {
var linkFromText = this.getValidLinkFromText();
if (linkFromText) {
this.updateLinkDisplay_(field, linkFromText);
} else {
field.execCommand(goog.editor.Command.MODAL_LINK_EDITOR, this);
}
};
/**
* Initialize a new link.
* @param {HTMLAnchorElement} anchor The anchor element.
* @param {string} url The initial URL.
* @param {string=} opt_target The target.
* @param {Array.<HTMLAnchorElement>=} opt_extraAnchors Extra anchors created
* by the browser when parsing a selection.
* @return {goog.editor.Link} The link.
*/
goog.editor.Link.createNewLink = function(anchor, url, opt_target,
opt_extraAnchors) {
var link = new goog.editor.Link(anchor, true);
link.initializeUrl(url);
if (opt_target) {
anchor.target = opt_target;
}
if (opt_extraAnchors) {
link.extraAnchors_ = opt_extraAnchors;
}
return link;
};
/**
* Returns true if str could be a URL, false otherwise
*
* Ex: TR_Util.isLikelyUrl_("http://www.google.com") == true
* TR_Util.isLikelyUrl_("www.google.com") == true
*
* @param {string} str String to check if it looks like a URL.
* @return {boolean} Whether str could be a URL.
*/
goog.editor.Link.isLikelyUrl = function(str) {
// Whitespace means this isn't a domain.
if (/\s/.test(str)) {
return false;
}
if (goog.editor.Link.isLikelyEmailAddress(str)) {
return false;
}
// Add a scheme if the url doesn't have one - this helps the parser.
var addedScheme = false;
if (!/^[^:\/?#.]+:/.test(str)) {
str = 'http://' + str;
addedScheme = true;
}
// Parse the domain.
var parts = goog.uri.utils.split(str);
// Relax the rules for special schemes.
var scheme = parts[goog.uri.utils.ComponentIndex.SCHEME];
if (goog.array.indexOf(['mailto', 'aim'], scheme) != -1) {
return true;
}
// Require domains to contain a '.', unless the domain is fully qualified and
// forbids domains from containing invalid characters.
var domain = parts[goog.uri.utils.ComponentIndex.DOMAIN];
if (!domain || (addedScheme && domain.indexOf('.') == -1) ||
(/[^\w\d\-\u0100-\uffff.%]/.test(domain))) {
return false;
}
// Require http and ftp paths to start with '/'.
var path = parts[goog.uri.utils.ComponentIndex.PATH];
return !path || path.indexOf('/') == 0;
};
/**
* Regular expression that matches strings that could be an email address.
* @type {RegExp}
* @private
*/
goog.editor.Link.LIKELY_EMAIL_ADDRESS_ = new RegExp(
'^' + // Test from start of string
'[\\w-]+(\\.[\\w-]+)*' + // Dot-delimited alphanumerics and dashes (name)
'\\@' + // @
'([\\w-]+\\.)+' + // Alphanumerics, dashes and dots (domain)
'(\\d+|\\w\\w+)$', // Domain ends in at least one number or 2 letters
'i');
/**
* Returns true if str could be an email address, false otherwise
*
* Ex: goog.editor.Link.isLikelyEmailAddress_("some word") == false
* goog.editor.Link.isLikelyEmailAddress_("foo@foo.com") == true
*
* @param {string} str String to test for being email address.
* @return {boolean} Whether "str" looks like an email address.
*/
goog.editor.Link.isLikelyEmailAddress = function(str) {
return goog.editor.Link.LIKELY_EMAIL_ADDRESS_.test(str);
};
/**
* Determines whether or not a url is an email link.
* @param {string} url A url.
* @return {boolean} Whether the url is a mailto link.
*/
goog.editor.Link.isMailto = function(url) {
return !!url && goog.string.startsWith(url, 'mailto:');
};
| 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 wrapper around a goog.editor.Field
* that listens to mouse events on the specified un-editable field, and makes
* the field editable if the user clicks on it. Clients are still responsible
* for determining when to make the field un-editable again.
*
* Clients can still determine when the field has loaded by listening to
* field's load event.
*
* @author nicksantos@google.com (Nick Santos)
*/
goog.provide('goog.editor.ClickToEditWrapper');
goog.require('goog.Disposable');
goog.require('goog.asserts');
goog.require('goog.debug.Logger');
goog.require('goog.dom');
goog.require('goog.dom.Range');
goog.require('goog.dom.TagName');
goog.require('goog.editor.BrowserFeature');
goog.require('goog.editor.Command');
goog.require('goog.editor.Field.EventType');
goog.require('goog.editor.range');
goog.require('goog.events.BrowserEvent.MouseButton');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventType');
/**
* Initialize the wrapper, and begin listening to mouse events immediately.
* @param {goog.editor.Field} fieldObj The editable field being wrapped.
* @constructor
* @extends {goog.Disposable}
*/
goog.editor.ClickToEditWrapper = function(fieldObj) {
goog.Disposable.call(this);
/**
* The field this wrapper interacts with.
* @type {goog.editor.Field}
* @private
*/
this.fieldObj_ = fieldObj;
/**
* DOM helper for the field's original element.
* @type {goog.dom.DomHelper}
* @private
*/
this.originalDomHelper_ = goog.dom.getDomHelper(
fieldObj.getOriginalElement());
/**
* @type {goog.dom.SavedCaretRange}
* @private
*/
this.savedCaretRange_ = null;
/**
* Event handler for field related events.
* @type {!goog.events.EventHandler}
* @private
*/
this.fieldEventHandler_ = new goog.events.EventHandler(this);
/**
* Bound version of the finishMouseUp method.
* @type {Function}
* @private
*/
this.finishMouseUpBound_ = goog.bind(this.finishMouseUp_, this);
/**
* Event handler for mouse events.
* @type {!goog.events.EventHandler}
* @private
*/
this.mouseEventHandler_ = new goog.events.EventHandler(this);
// Start listening to mouse events immediately if necessary.
if (!this.fieldObj_.isLoaded()) {
this.enterDocument();
}
this.fieldEventHandler_.
// Whenever the field is made editable, we need to check if there
// are any carets in it, and if so, use them to render the selection.
listen(
this.fieldObj_, goog.editor.Field.EventType.LOAD,
this.renderSelection_).
// Whenever the field is made uneditable, we need to set up
// the click-to-edit listeners.
listen(
this.fieldObj_, goog.editor.Field.EventType.UNLOAD,
this.enterDocument);
};
goog.inherits(goog.editor.ClickToEditWrapper, goog.Disposable);
/**
* The logger for this class.
* @type {goog.debug.Logger}
* @private
*/
goog.editor.ClickToEditWrapper.prototype.logger_ =
goog.debug.Logger.getLogger('goog.editor.ClickToEditWrapper');
/** @return {goog.editor.Field} The field. */
goog.editor.ClickToEditWrapper.prototype.getFieldObject = function() {
return this.fieldObj_;
};
/** @return {goog.dom.DomHelper} The dom helper of the uneditable element. */
goog.editor.ClickToEditWrapper.prototype.getOriginalDomHelper = function() {
return this.originalDomHelper_;
};
/** @override */
goog.editor.ClickToEditWrapper.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
this.exitDocument();
if (this.savedCaretRange_) {
this.savedCaretRange_.dispose();
}
this.fieldEventHandler_.dispose();
this.mouseEventHandler_.dispose();
this.savedCaretRange_ = null;
delete this.fieldEventHandler_;
delete this.mouseEventHandler_;
};
/**
* Initialize listeners when the uneditable field is added to the document.
* Also sets up lorem ipsum text.
*/
goog.editor.ClickToEditWrapper.prototype.enterDocument = function() {
if (this.isInDocument_) {
return;
}
this.isInDocument_ = true;
this.mouseEventTriggeredLoad_ = false;
var field = this.fieldObj_.getOriginalElement();
// To do artificial selection preservation, we have to listen to mouseup,
// get the current selection, and re-select the same text in the iframe.
//
// NOTE(nicksantos): Artificial selection preservation is needed in all cases
// where we set the field contents by setting innerHTML. There are a few
// rare cases where we don't need it. But these cases are highly
// implementation-specific, and computationally hard to detect (bidi
// and ig modules both set innerHTML), so we just do it in all cases.
this.savedAnchorClicked_ = null;
this.mouseEventHandler_.
listen(field, goog.events.EventType.MOUSEUP, this.handleMouseUp_).
listen(field, goog.events.EventType.CLICK, this.handleClick_);
// manage lorem ipsum text, if necessary
this.fieldObj_.execCommand(goog.editor.Command.UPDATE_LOREM);
};
/**
* Destroy listeners when the field is removed from the document.
*/
goog.editor.ClickToEditWrapper.prototype.exitDocument = function() {
this.mouseEventHandler_.removeAll();
this.isInDocument_ = false;
};
/**
* Returns the uneditable field element if the field is not yet editable
* (equivalent to EditableField.getOriginalElement()), and the editable DOM
* element if the field is currently editable (equivalent to
* EditableField.getElement()).
* @return {Element} The element containing the editable field contents.
*/
goog.editor.ClickToEditWrapper.prototype.getElement = function() {
return this.fieldObj_.isLoaded() ?
this.fieldObj_.getElement() : this.fieldObj_.getOriginalElement();
};
/**
* True if a mouse event should be handled, false if it should be ignored.
* @param {goog.events.BrowserEvent} e The mouse event.
* @return {boolean} Wether or not this mouse event should be handled.
* @private
*/
goog.editor.ClickToEditWrapper.prototype.shouldHandleMouseEvent_ = function(e) {
return e.isButton(goog.events.BrowserEvent.MouseButton.LEFT) &&
!(e.shiftKey || e.ctrlKey || e.altKey || e.metaKey);
};
/**
* Handle mouse click events on the field.
* @param {goog.events.BrowserEvent} e The click event.
* @private
*/
goog.editor.ClickToEditWrapper.prototype.handleClick_ = function(e) {
// If the user clicked on a link in an uneditable field,
// we want to cancel the click.
var anchorAncestor = goog.dom.getAncestorByTagNameAndClass(
/** @type {Node} */ (e.target),
goog.dom.TagName.A);
if (anchorAncestor) {
e.preventDefault();
if (!goog.editor.BrowserFeature.HAS_ACTIVE_ELEMENT) {
this.savedAnchorClicked_ = anchorAncestor;
}
}
};
/**
* Handle a mouse up event on the field.
* @param {goog.events.BrowserEvent} e The mouseup event.
* @private
*/
goog.editor.ClickToEditWrapper.prototype.handleMouseUp_ = function(e) {
// Only respond to the left mouse button.
if (this.shouldHandleMouseEvent_(e)) {
// We need to get the selection when the user mouses up, but the
// selection doesn't actually change until after the mouseup event has
// propagated. So we need to do this asynchronously.
this.originalDomHelper_.getWindow().setTimeout(this.finishMouseUpBound_, 0);
}
};
/**
* A helper function for handleMouseUp_ -- does the actual work
* when the event is finished propagating.
* @private
*/
goog.editor.ClickToEditWrapper.prototype.finishMouseUp_ = function() {
// Make sure that the field is still not editable.
if (!this.fieldObj_.isLoaded()) {
if (this.savedCaretRange_) {
this.savedCaretRange_.dispose();
this.savedCaretRange_ = null;
}
if (!this.fieldObj_.queryCommandValue(goog.editor.Command.USING_LOREM)) {
// We need carets (blank span nodes) to maintain the selection when
// the html is copied into an iframe. However, because our code
// clears the selection to make the behavior consistent, we need to do
// this even when we're not using an iframe.
this.insertCarets_();
}
this.ensureFieldEditable_();
}
this.exitDocument();
this.savedAnchorClicked_ = null;
};
/**
* Ensure that the field is editable. If the field is not editable,
* make it so, and record the fact that it was done by a user mouse event.
* @private
*/
goog.editor.ClickToEditWrapper.prototype.ensureFieldEditable_ = function() {
if (!this.fieldObj_.isLoaded()) {
this.mouseEventTriggeredLoad_ = true;
this.makeFieldEditable(this.fieldObj_);
}
};
/**
* Once the field has loaded in an iframe, re-create the selection
* as marked by the carets.
* @private
*/
goog.editor.ClickToEditWrapper.prototype.renderSelection_ = function() {
if (this.savedCaretRange_) {
// Make sure that the restoration document is inside the iframe
// if we're using one.
this.savedCaretRange_.setRestorationDocument(
this.fieldObj_.getEditableDomHelper().getDocument());
var startCaret = this.savedCaretRange_.getCaret(true);
var endCaret = this.savedCaretRange_.getCaret(false);
var hasCarets = startCaret && endCaret;
}
// There are two reasons why we might want to focus the field:
// 1) makeFieldEditable was triggered by the click-to-edit wrapper.
// In this case, the mouse event should have triggered a focus, but
// the editor might have taken the focus away to create lorem ipsum
// text or create an iframe for the field. So we make sure the focus
// is restored.
// 2) somebody placed carets, and we need to select those carets. The field
// needs focus to ensure that the selection appears.
if (this.mouseEventTriggeredLoad_ || hasCarets) {
this.focusOnFieldObj(this.fieldObj_);
}
if (hasCarets) {
var startCaretParent = startCaret.parentNode;
var endCaretParent = endCaret.parentNode;
this.savedCaretRange_.restore();
this.fieldObj_.dispatchSelectionChangeEvent();
// NOTE(nicksantos): Bubbles aren't actually enabled until the end
// if the load sequence, so if the user clicked on a link, the bubble
// will not pop up.
}
if (this.savedCaretRange_) {
this.savedCaretRange_.dispose();
this.savedCaretRange_ = null;
}
this.mouseEventTriggeredLoad_ = false;
};
/**
* Focus on the field object.
* @param {goog.editor.Field} field The field to focus.
* @protected
*/
goog.editor.ClickToEditWrapper.prototype.focusOnFieldObj = function(field) {
field.focusAndPlaceCursorAtStart();
};
/**
* Make the field object editable.
* @param {goog.editor.Field} field The field to make editable.
* @protected
*/
goog.editor.ClickToEditWrapper.prototype.makeFieldEditable = function(field) {
field.makeEditable();
};
//================================================================
// Caret-handling methods
/**
* Gets a saved caret range for the given range.
* @param {goog.dom.AbstractRange} range A range wrapper.
* @return {goog.dom.SavedCaretRange} The range, saved with carets, or null
* if the range wrapper was null.
* @private
*/
goog.editor.ClickToEditWrapper.createCaretRange_ = function(range) {
return range && goog.editor.range.saveUsingNormalizedCarets(range);
};
/**
* Inserts the carets, given the current selection.
*
* Note that for all practical purposes, a cursor position is just
* a selection with the start and end at the same point.
* @private
*/
goog.editor.ClickToEditWrapper.prototype.insertCarets_ = function() {
var fieldElement = this.fieldObj_.getOriginalElement();
this.savedCaretRange_ = null;
var originalWindow = this.originalDomHelper_.getWindow();
if (goog.dom.Range.hasSelection(originalWindow)) {
var range = goog.dom.Range.createFromWindow(originalWindow);
range = range && goog.editor.range.narrow(range, fieldElement);
this.savedCaretRange_ =
goog.editor.ClickToEditWrapper.createCaretRange_(range);
}
if (!this.savedCaretRange_) {
// We couldn't figure out where to put the carets.
// But in FF2/IE6+, this could mean that the user clicked on a
// 'special' node, (e.g., a link or an unselectable item). So the
// selection appears to be null or the full page, even though the user did
// click on something. In IE, we can determine the real selection via
// document.activeElement. In FF, we have to be more hacky.
var specialNodeClicked;
if (goog.editor.BrowserFeature.HAS_ACTIVE_ELEMENT) {
specialNodeClicked = goog.dom.getActiveElement(
this.originalDomHelper_.getDocument());
} else {
specialNodeClicked = this.savedAnchorClicked_;
}
var isFieldElement = function(node) {
return node == fieldElement;
};
if (specialNodeClicked &&
goog.dom.getAncestor(specialNodeClicked, isFieldElement, true)) {
// Insert the cursor at the beginning of the active element to be
// consistent with the behavior in FF1.5, where clicking on a
// link makes the current selection equal to the cursor position
// directly before that link.
//
// TODO(nicksantos): Is there a way to more accurately place the cursor?
this.savedCaretRange_ = goog.editor.ClickToEditWrapper.createCaretRange_(
goog.dom.Range.createFromNodes(
specialNodeClicked, 0, specialNodeClicked, 0));
}
}
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Support class for spell checker components.
*
* @author eae@google.com (Emil A Eklund)
*/
goog.provide('goog.spell.SpellCheck');
goog.provide('goog.spell.SpellCheck.WordChangedEvent');
goog.require('goog.Timer');
goog.require('goog.events.EventTarget');
goog.require('goog.structs.Set');
/**
* Support class for spell checker components. Provides basic functionality
* such as word lookup and caching.
*
* @param {Function=} opt_lookupFunction Function to use for word lookup. Must
* accept an array of words, an object reference and a callback function as
* parameters. It must also call the callback function (as a method on the
* object), once ready, with an array containing the original words, their
* spelling status and optionally an array of suggestions.
* @param {string=} opt_language Content language.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.spell.SpellCheck = function(opt_lookupFunction, opt_language) {
goog.events.EventTarget.call(this);
/**
* Function used to lookup spelling of words.
* @type {Function}
* @private
*/
this.lookupFunction_ = opt_lookupFunction || null;
/**
* Cache for words not yet checked with lookup function.
* @type {goog.structs.Set}
* @private
*/
this.unknownWords_ = new goog.structs.Set();
this.setLanguage(opt_language);
};
goog.inherits(goog.spell.SpellCheck, goog.events.EventTarget);
/**
* Delay, in ms, to wait for additional words to be entered before a lookup
* operation is triggered.
*
* @type {number}
* @private
*/
goog.spell.SpellCheck.LOOKUP_DELAY_ = 100;
/**
* Constants for event names
*
* @enum {string}
*/
goog.spell.SpellCheck.EventType = {
/**
* Fired when all pending words have been processed.
*/
READY: 'ready',
/**
* Fired when all lookup function failed.
*/
ERROR: 'error',
/**
* Fired when a word's status is changed.
*/
WORD_CHANGED: 'wordchanged'
};
/**
* Cache. Shared across all spell checker instances. Map with langauge as the
* key and a cache for that language as the value.
*
* @type {Object}
* @private
*/
goog.spell.SpellCheck.cache_ = {};
/**
* Content Language.
* @type {string}
* @private
*/
goog.spell.SpellCheck.prototype.language_ = '';
/**
* Cache for set language. Reference to the element corresponding to the set
* language in the static goog.spell.SpellCheck.cache_.
*
* @type {Object|undefined}
* @private
*/
goog.spell.SpellCheck.prototype.cache_;
/**
* Id for timer processing the pending queue.
*
* @type {number}
* @private
*/
goog.spell.SpellCheck.prototype.queueTimer_ = 0;
/**
* Whether a lookup operation is in progress.
*
* @type {boolean}
* @private
*/
goog.spell.SpellCheck.prototype.lookupInProgress_ = false;
/**
* Codes representing the status of an individual word.
*
* @enum {number}
*/
goog.spell.SpellCheck.WordStatus = {
UNKNOWN: 0,
VALID: 1,
INVALID: 2,
IGNORED: 3,
CORRECTED: 4 // Temporary status, not stored in cache
};
/**
* Fields for word array in cache.
*
* @enum {number}
*/
goog.spell.SpellCheck.CacheIndex = {
STATUS: 0,
SUGGESTIONS: 1
};
/**
* Regular expression for identifying word boundaries.
*
* @type {string}
*/
goog.spell.SpellCheck.WORD_BOUNDARY_CHARS =
'\t\r\n\u00A0 !\"#$%&()*+,\-.\/:;<=>?@\[\\\]^_`{|}~';
/**
* Regular expression for identifying word boundaries.
*
* @type {RegExp}
*/
goog.spell.SpellCheck.WORD_BOUNDARY_REGEX = new RegExp(
'[' + goog.spell.SpellCheck.WORD_BOUNDARY_CHARS + ']');
/**
* Regular expression for splitting a string into individual words and blocks of
* separators. Matches zero or one word followed by zero or more separators.
*
* @type {RegExp}
*/
goog.spell.SpellCheck.SPLIT_REGEX = new RegExp(
'([^' + goog.spell.SpellCheck.WORD_BOUNDARY_CHARS + ']*)' +
'([' + goog.spell.SpellCheck.WORD_BOUNDARY_CHARS + ']*)');
/**
* Sets the lookup function.
*
* @param {Function} f Function to use for word lookup. Must accept an array of
* words, an object reference and a callback function as parameters.
* It must also call the callback function (as a method on the object),
* once ready, with an array containing the original words, their
* spelling status and optionally an array of suggestions.
*/
goog.spell.SpellCheck.prototype.setLookupFunction = function(f) {
this.lookupFunction_ = f;
};
/**
* Sets language.
*
* @param {string=} opt_language Content language.
*/
goog.spell.SpellCheck.prototype.setLanguage = function(opt_language) {
this.language_ = opt_language || '';
if (!goog.spell.SpellCheck.cache_[this.language_]) {
goog.spell.SpellCheck.cache_[this.language_] = {};
}
this.cache_ = goog.spell.SpellCheck.cache_[this.language_];
};
/**
* Returns language.
*
* @return {string} Content language.
*/
goog.spell.SpellCheck.prototype.getLanguage = function() {
return this.language_;
};
/**
* Checks spelling for a block of text.
*
* @param {string} text Block of text to spell check.
*/
goog.spell.SpellCheck.prototype.checkBlock = function(text) {
var words = text.split(goog.spell.SpellCheck.WORD_BOUNDARY_REGEX);
var len = words.length;
for (var word, i = 0; i < len; i++) {
word = words[i];
this.checkWord_(word);
}
if (!this.queueTimer_ && !this.lookupInProgress_ &&
this.unknownWords_.getCount()) {
this.processPending_();
}
else if (this.unknownWords_.getCount() == 0) {
this.dispatchEvent(goog.spell.SpellCheck.EventType.READY);
}
};
/**
* Checks spelling for a single word. Returns the status of the supplied word,
* or UNKNOWN if it's not cached. If it's not cached the word is added to a
* queue and checked with the verification implementation with a short delay.
*
* @param {string} word Word to check spelling of.
* @return {goog.spell.SpellCheck.WordStatus} The status of the supplied word,
* or UNKNOWN if it's not cached.
*/
goog.spell.SpellCheck.prototype.checkWord = function(word) {
var status = this.checkWord_(word);
if (status == goog.spell.SpellCheck.WordStatus.UNKNOWN &&
!this.queueTimer_ && !this.lookupInProgress_) {
this.queueTimer_ = goog.Timer.callOnce(this.processPending_,
goog.spell.SpellCheck.LOOKUP_DELAY_, this);
}
return status;
};
/**
* Checks spelling for a single word. Returns the status of the supplied word,
* or UNKNOWN if it's not cached.
*
* @param {string} word Word to check spelling of.
* @return {goog.spell.SpellCheck.WordStatus} The status of the supplied word,
* or UNKNOWN if it's not cached.
* @private
*/
goog.spell.SpellCheck.prototype.checkWord_ = function(word) {
if (!word) {
return goog.spell.SpellCheck.WordStatus.INVALID;
}
var cacheEntry = this.cache_[word];
if (!cacheEntry) {
this.unknownWords_.add(word);
return goog.spell.SpellCheck.WordStatus.UNKNOWN;
}
return cacheEntry[goog.spell.SpellCheck.CacheIndex.STATUS];
};
/**
* Processes pending words unless a lookup operation has already been queued or
* is in progress.
*
* @throws {Error}
*/
goog.spell.SpellCheck.prototype.processPending = function() {
if (this.unknownWords_.getCount()) {
if (!this.queueTimer_ && !this.lookupInProgress_) {
this.processPending_();
}
} else {
this.dispatchEvent(goog.spell.SpellCheck.EventType.READY);
}
};
/**
* Processes pending words using the verification callback.
*
* @throws {Error}
* @private
*/
goog.spell.SpellCheck.prototype.processPending_ = function() {
if (!this.lookupFunction_) {
throw Error('No lookup function provided for spell checker.');
}
if (this.unknownWords_.getCount()) {
this.lookupInProgress_ = true;
var func = this.lookupFunction_;
func(this.unknownWords_.getValues(), this, this.lookupCallback_);
} else {
this.dispatchEvent(goog.spell.SpellCheck.EventType.READY);
}
this.queueTimer_ = 0;
};
/**
* Callback for lookup function.
*
* @param {Array.<Array>} data Data array. Each word is represented by an
* array containing the word, the status and optionally an array of
* suggestions. Passing null indicates that the operation failed.
* @private
*
* Example:
* obj.lookupCallback_([
* ['word', VALID],
* ['wrod', INVALID, ['word', 'wood', 'rod']]
* ]);
*/
goog.spell.SpellCheck.prototype.lookupCallback_ = function(data) {
// Lookup function failed; abort then dispatch error event.
if (data == null) {
if (this.queueTimer_) {
goog.Timer.clear(this.queueTimer_);
this.queueTimer_ = 0;
}
this.lookupInProgress_ = false;
this.dispatchEvent(goog.spell.SpellCheck.EventType.ERROR);
return;
}
for (var a, i = 0; a = data[i]; i++) {
this.setWordStatus_(a[0], a[1], a[2]);
}
this.lookupInProgress_ = false;
// Fire ready event if all pending words have been processed.
if (this.unknownWords_.getCount() == 0) {
this.dispatchEvent(goog.spell.SpellCheck.EventType.READY);
// Process pending
} else if (!this.queueTimer_) {
this.queueTimer_ = goog.Timer.callOnce(this.processPending_,
goog.spell.SpellCheck.LOOKUP_DELAY_, this);
}
};
/**
* Sets a words spelling status.
*
* @param {string} word Word to set status for.
* @param {goog.spell.SpellCheck.WordStatus} status Status of word.
* @param {Array.<string>=} opt_suggestions Suggestions.
*
* Example:
* obj.setWordStatus('word', VALID);
* obj.setWordStatus('wrod', INVALID, ['word', 'wood', 'rod']);.
*/
goog.spell.SpellCheck.prototype.setWordStatus =
function(word, status, opt_suggestions) {
this.setWordStatus_(word, status, opt_suggestions);
};
/**
* Sets a words spelling status.
*
* @param {string} word Word to set status for.
* @param {goog.spell.SpellCheck.WordStatus} status Status of word.
* @param {Array.<string>=} opt_suggestions Suggestions.
* @private
*/
goog.spell.SpellCheck.prototype.setWordStatus_ =
function(word, status, opt_suggestions) {
var suggestions = opt_suggestions || [];
this.cache_[word] = [status, suggestions];
this.unknownWords_.remove(word);
this.dispatchEvent(
new goog.spell.SpellCheck.WordChangedEvent(this, word, status));
};
/**
* Returns suggestions for the given word.
*
* @param {string} word Word to get suggestions for.
* @return {Array.<string>} An array of suggestions for the given word.
*/
goog.spell.SpellCheck.prototype.getSuggestions = function(word) {
var cacheEntry = this.cache_[word];
if (!cacheEntry) {
this.checkWord(word);
return [];
}
return cacheEntry[goog.spell.SpellCheck.CacheIndex.STATUS] ==
goog.spell.SpellCheck.WordStatus.INVALID ?
cacheEntry[goog.spell.SpellCheck.CacheIndex.SUGGESTIONS] : [];
};
/**
* Object representing a word changed event. Fired when the status of a word
* changes.
*
* @param {goog.spell.SpellCheck} target Spellcheck object initiating event.
* @param {string} word Word to set status for.
* @param {goog.spell.SpellCheck.WordStatus} status Status of word.
* @extends {goog.events.Event}
* @constructor
*/
goog.spell.SpellCheck.WordChangedEvent = function(target, word, status) {
goog.events.Event.call(this, goog.spell.SpellCheck.EventType.WORD_CHANGED,
target);
/**
* Word the status has changed for.
* @type {string}
*/
this.word = word;
/**
* New status
* @type {goog.spell.SpellCheck.WordStatus}
*/
this.status = status;
};
goog.inherits(goog.spell.SpellCheck.WordChangedEvent, goog.events.Event);
| 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.
/** @nocompile */
[
['apple',
{name: 'Fuji', url: 'http://www.google.com/images?q=fuji+apple'},
{name: 'Gala', url: 'http://www.google.com/images?q=gala+apple'},
{name: 'Golden Delicious',
url: 'http://www.google.com/images?q=golden delicious+apple'}
],
['citrus',
{name: 'Lemon', url: 'http://www.google.com/images?q=lemon+fruit'},
{name: 'Orange', url: 'http://www.google.com/images?q=orange+fruit'}
],
['berry',
{name: 'Strawberry', url: 'http://www.google.com/images?q=strawberry+fruit'},
{name: 'Blueberry', url: 'http://www.google.com/images?q=blueberry+fruit'},
{name: 'Blackberry', url: 'http://www.google.com/images?q=blackberry+fruit'}
]
]
| 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.
/** @nocompile */
['Big Table', 'Googlebot', 'Instant Indexing', 'Mustang', 'Page Rank',
'Proto 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 Contains application code for the XPC demo.
* This script is used in both the container page and the iframe.
*
*/
goog.require('goog.Uri');
goog.require('goog.debug.Logger');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.json');
goog.require('goog.net.xpc.CfgFields');
goog.require('goog.net.xpc.CrossPageChannel');
/**
* Namespace for the demo. We don't use goog.provide here because it's not a
* real module (cannot be required).
*/
var xpcdemo = {};
/**
* Global function to kick off initialization in the containing document.
*/
goog.global.initOuter = function() {
goog.events.listen(window, 'load', function() { xpcdemo.initOuter(); });
};
/**
* Global function to kick off initialization in the iframe.
*/
goog.global.initInner = function() {
goog.events.listen(window, 'load', function() { xpcdemo.initInner(); });
};
/**
* Initializes XPC in the containing page.
*/
xpcdemo.initOuter = function() {
// Build the configuration object.
var cfg = {};
var ownUri = new goog.Uri(window.location.href);
var relayUri = ownUri.resolve(new goog.Uri('relay.html'));
var pollUri = ownUri.resolve(new goog.Uri('blank.html'));
// Determine the peer domain. Uses the value of the URI-parameter
// 'peerdomain'. If that parameter is not present, it falls back to
// the own domain so that the demo will work out of the box (but
// communication will of course not cross domain-boundaries). For
// real cross-domain communication, the easiest way is to point two
// different host-names to the same webserver and then hit the
// following URI:
// http://host1.com/path/to/closure/demos/xpc/index.html?peerdomain=host2.com
var peerDomain = ownUri.getParameterValue('peerdomain') || ownUri.getDomain();
cfg[goog.net.xpc.CfgFields.LOCAL_RELAY_URI] = relayUri.toString();
cfg[goog.net.xpc.CfgFields.PEER_RELAY_URI] =
relayUri.setDomain(peerDomain).toString();
cfg[goog.net.xpc.CfgFields.LOCAL_POLL_URI] = pollUri.toString();
cfg[goog.net.xpc.CfgFields.PEER_POLL_URI] =
pollUri.setDomain(peerDomain).toString();
// Force transport to be used if tp-parameter is set.
var tp = ownUri.getParameterValue('tp');
if (tp) {
cfg[goog.net.xpc.CfgFields.TRANSPORT] = parseInt(tp, 10);
}
// Construct the URI of the peer page.
var peerUri = ownUri.resolve(
new goog.Uri('inner.html')).setDomain(peerDomain);
// Passthrough of verbose and compiled flags.
if (goog.isDef(ownUri.getParameterValue('verbose'))) {
peerUri.setParameterValue('verbose', '');
}
if (goog.isDef(ownUri.getParameterValue('compiled'))) {
peerUri.setParameterValue('compiled', '');
}
cfg[goog.net.xpc.CfgFields.PEER_URI] = peerUri;
// Instantiate the channel.
xpcdemo.channel = new goog.net.xpc.CrossPageChannel(cfg);
// Create the peer iframe.
xpcdemo.peerIframe = xpcdemo.channel.createPeerIframe(
goog.dom.getElement('iframeContainer'));
xpcdemo.initCommon_();
goog.dom.getElement('inactive').style.display = 'none';
goog.dom.getElement('active').style.display = '';
};
/**
* Initialization in the iframe.
*/
xpcdemo.initInner = function() {
// Get the channel configuration passed by the containing document.
var cfg = goog.json.parse(
(new goog.Uri(window.location.href)).getParameterValue('xpc'));
xpcdemo.channel = new goog.net.xpc.CrossPageChannel(cfg);
xpcdemo.initCommon_();
};
/**
* Initializes the demo.
* Registers service-handlers and connects the channel.
* @private
*/
xpcdemo.initCommon_ = function() {
var xpcLogger = goog.debug.Logger.getLogger('goog.net.xpc');
xpcLogger.addHandler(function(logRecord) {
xpcdemo.log('[XPC] ' + logRecord.getMessage());
});
xpcLogger.setLevel(window.location.href.match(/verbose/) ?
goog.debug.Logger.Level.ALL : goog.debug.Logger.Level.INFO);
// Register services.
xpcdemo.channel.registerService('log', xpcdemo.log);
xpcdemo.channel.registerService('ping', xpcdemo.pingHandler_);
xpcdemo.channel.registerService('events', xpcdemo.eventsMsgHandler_);
// Connect the channel.
xpcdemo.channel.connect(function() {
xpcdemo.channel.send('log', 'Hi from ' + window.location.host);
goog.events.listen(goog.dom.getElement('clickfwd'),
'click', xpcdemo.mouseEventHandler_);
});
};
/**
* Kills the peer iframe and the disposes the channel.
*/
xpcdemo.teardown = function() {
goog.events.unlisten(goog.dom.getElement('clickfwd'),
goog.events.EventType.CLICK, xpcdemo.mouseEventHandler_);
xpcdemo.channel.dispose();
delete xpcdemo.channel;
goog.dom.removeNode(xpcdemo.peerIframe);
xpcdemo.peerIframe = null;
goog.dom.getElement('inactive').style.display = '';
goog.dom.getElement('active').style.display = 'none';
};
/**
* Logging function. Inserts log-message into element with it id 'console'.
* @param {string} msgString The log-message.
*/
xpcdemo.log = function(msgString) {
xpcdemo.consoleElm || (xpcdemo.consoleElm = goog.dom.getElement('console'));
var msgElm = goog.dom.createDom('div');
msgElm.innerHTML = msgString;
xpcdemo.consoleElm.insertBefore(msgElm, xpcdemo.consoleElm.firstChild);
};
/**
* Sends a ping request to the peer.
*/
xpcdemo.ping = function() {
// send current time
xpcdemo.channel.send('ping', goog.now() + '');
};
/**
* The handler function for incoming pings (messages sent to the service
* called 'ping');
* @param {string} payload The message payload.
* @private
*/
xpcdemo.pingHandler_ = function(payload) {
// is the incoming message a response to a ping we sent?
if (payload.charAt(0) == '#') {
// calculate roundtrip time and log
var dt = goog.now() - parseInt(payload.substring(1), 10);
xpcdemo.log('roundtrip: ' + dt + 'ms');
} else {
// incoming message is a ping initiated from peer
// -> prepend with '#' and send back
xpcdemo.channel.send('ping', '#' + payload);
xpcdemo.log('ping reply sent');
}
};
/**
* Counter for mousemove events.
* @type {number}
* @private
*/
xpcdemo.mmCount_ = 0;
/**
* Holds timestamp when the last mousemove rate has been logged.
* @type {number}
* @private
*/
xpcdemo.mmLastRateOutput_ = 0;
/**
* Start mousemove event forwarding. Registers a listener on the document which
* sends them over the channel.
*/
xpcdemo.startMousemoveForwarding = function() {
goog.events.listen(document, goog.events.EventType.MOUSEMOVE,
xpcdemo.mouseEventHandler_);
xpcdemo.mmLastRateOutput_ = goog.now();
};
/**
* Stop mousemove event forwarding.
*/
xpcdemo.stopMousemoveForwarding = function() {
goog.events.unlisten(document, goog.events.EventType.MOUSEMOVE,
xpcdemo.mouseEventHandler_);
};
/**
* Function to be used as handler for mouse-events.
* @param {goog.events.BrowserEvent} e The mouse event.
* @private
*/
xpcdemo.mouseEventHandler_ = function(e) {
xpcdemo.channel.send('events',
[e.type, e.clientX, e.clientY, goog.now()].join(','));
};
/**
* Handler for the 'events' service.
* @param {string} payload The string returned from the xpcdemo.
* @private
*/
xpcdemo.eventsMsgHandler_ = function(payload) {
var now = goog.now();
var args = payload.split(',');
var type = args[0];
var pageX = args[1];
var pageY = args[2];
var time = parseInt(args[3], 10);
var msg = type + ': (' + pageX + ',' + pageY + '), latency: ' + (now - time);
xpcdemo.log(msg);
if (type == goog.events.EventType.MOUSEMOVE) {
xpcdemo.mmCount_++;
var dt = now - xpcdemo.mmLastRateOutput_;
if (dt > 1000) {
msg = 'RATE (mousemove/s): ' + (1000 * xpcdemo.mmCount_ / dt);
xpcdemo.log(msg);
xpcdemo.mmLastRateOutput_ = now;
xpcdemo.mmCount_ = 0;
}
}
};
/**
* Send multiple messages.
* @param {number} n The number of messages to send.
*/
xpcdemo.sendN = function(n) {
xpcdemo.count_ || (xpcdemo.count_ = 1);
for (var i = 0; i < n; i++) {
xpcdemo.channel.send('log', '' + xpcdemo.count_++);
}
};
| 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 example of how to write a dialog to be opened by a plugin.
*
*/
goog.provide('goog.demos.editor.HelloWorldDialog');
goog.provide('goog.demos.editor.HelloWorldDialog.OkEvent');
goog.require('goog.dom.TagName');
goog.require('goog.events.Event');
goog.require('goog.string');
goog.require('goog.ui.editor.AbstractDialog');
// *** Public interface ***************************************************** //
/**
* Creates a dialog to let the user enter a customized hello world message.
* @param {goog.dom.DomHelper} domHelper DomHelper to be used to create the
* dialog's dom structure.
* @constructor
* @extends {goog.ui.editor.AbstractDialog}
*/
goog.demos.editor.HelloWorldDialog = function(domHelper) {
goog.ui.editor.AbstractDialog.call(this, domHelper);
};
goog.inherits(goog.demos.editor.HelloWorldDialog,
goog.ui.editor.AbstractDialog);
// *** Event **************************************************************** //
/**
* OK event object for the hello world dialog.
* @param {string} message Customized hello world message chosen by the user.
* @constructor
* @extends {goog.events.Event}
*/
goog.demos.editor.HelloWorldDialog.OkEvent = function(message) {
this.message = message;
};
goog.inherits(goog.demos.editor.HelloWorldDialog.OkEvent, goog.events.Event);
/**
* Event type.
* @type {goog.ui.editor.AbstractDialog.EventType}
* @override
*/
goog.demos.editor.HelloWorldDialog.OkEvent.prototype.type =
goog.ui.editor.AbstractDialog.EventType.OK;
/**
* Customized hello world message chosen by the user.
* @type {string}
*/
goog.demos.editor.HelloWorldDialog.OkEvent.prototype.message;
// *** Protected interface ************************************************** //
/** @override */
goog.demos.editor.HelloWorldDialog.prototype.createDialogControl = function() {
var builder = new goog.ui.editor.AbstractDialog.Builder(this);
/** @desc Title of the hello world dialog. */
var MSG_HELLO_WORLD_DIALOG_TITLE = goog.getMsg('Add a Hello World message');
builder.setTitle(MSG_HELLO_WORLD_DIALOG_TITLE).
setContent(this.createContent_());
return builder.build();
};
/**
* 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.
* @param {goog.events.Event} e The event object dispatched by the wrapped
* dialog.
* @return {goog.demos.editor.HelloWorldDialog.OkEvent} The event object to be
* used when dispatching the OK event to listeners.
* @protected
* @override
*/
goog.demos.editor.HelloWorldDialog.prototype.createOkEvent = function(e) {
var message = this.getMessage_();
if (message &&
goog.demos.editor.HelloWorldDialog.isValidHelloWorld_(message)) {
return new goog.demos.editor.HelloWorldDialog.OkEvent(message);
} else {
/** @desc Error message telling the user why their message was rejected. */
var MSG_HELLO_WORLD_DIALOG_ERROR =
goog.getMsg('Your message must contain the words "hello" and "world".');
this.dom.getWindow().alert(MSG_HELLO_WORLD_DIALOG_ERROR);
return null; // Prevents the dialog from closing.
}
};
// *** Private implementation *********************************************** //
/**
* Input element where the user will type their hello world message.
* @type {Element}
* @private
*/
goog.demos.editor.HelloWorldDialog.prototype.input_;
/**
* Creates the DOM structure that makes up the dialog's content area.
* @return {Element} The DOM structure that makes up the dialog's content area.
* @private
*/
goog.demos.editor.HelloWorldDialog.prototype.createContent_ = function() {
/** @desc Sample hello world message to prepopulate the dialog with. */
var MSG_HELLO_WORLD_DIALOG_SAMPLE = goog.getMsg('Hello, world!');
this.input_ = this.dom.createDom(goog.dom.TagName.INPUT,
{size: 25, value: MSG_HELLO_WORLD_DIALOG_SAMPLE});
/** @desc Prompt telling the user to enter a hello world message. */
var MSG_HELLO_WORLD_DIALOG_PROMPT =
goog.getMsg('Enter your Hello World message');
return this.dom.createDom(goog.dom.TagName.DIV,
null,
[MSG_HELLO_WORLD_DIALOG_PROMPT, this.input_]);
};
/**
* Returns the hello world message currently typed into the dialog's input.
* @return {?string} The hello world message currently typed into the dialog's
* input, or null if called before the input is created.
* @private
*/
goog.demos.editor.HelloWorldDialog.prototype.getMessage_ = function() {
return this.input_ && this.input_.value;
};
/**
* Returns whether or not the given message contains the strings "hello" and
* "world". Case-insensitive and order doesn't matter.
* @param {string} message The message to be checked.
* @return {boolean} Whether or not the given message contains the strings
* "hello" and "world".
* @private
*/
goog.demos.editor.HelloWorldDialog.isValidHelloWorld_ = function(message) {
message = message.toLowerCase();
return goog.string.contains(message, 'hello') &&
goog.string.contains(message, 'world');
};
| 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.
//
// This file has been auto-generated by GenJsDeps, please do not edit.
goog.addDependency('demos/editor/equationeditor.js', ['goog.demos.editor.EquationEditor'], ['goog.ui.equation.EquationEditorDialog']);
goog.addDependency('demos/editor/helloworld.js', ['goog.demos.editor.HelloWorld'], ['goog.dom', 'goog.dom.TagName', 'goog.editor.Plugin']);
goog.addDependency('demos/editor/helloworlddialog.js', ['goog.demos.editor.HelloWorldDialog', 'goog.demos.editor.HelloWorldDialog.OkEvent'], ['goog.dom.TagName', 'goog.events.Event', 'goog.string', 'goog.ui.editor.AbstractDialog', 'goog.ui.editor.AbstractDialog.Builder', 'goog.ui.editor.AbstractDialog.EventType']);
goog.addDependency('demos/editor/helloworlddialogplugin.js', ['goog.demos.editor.HelloWorldDialogPlugin', 'goog.demos.editor.HelloWorldDialogPlugin.Command'], ['goog.demos.editor.HelloWorldDialog', 'goog.dom.TagName', 'goog.editor.plugins.AbstractDialogPlugin', 'goog.editor.range', 'goog.functions', 'goog.ui.editor.AbstractDialog.EventType']);
| 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 simple plugin that inserts 'Hello World!' on command. This
* plugin is intended to be an example of a very simple plugin for plugin
* developers.
*
* @author gak@google.com (Gregory Kick)
* @see helloworld.html
*/
goog.provide('goog.demos.editor.HelloWorld');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.editor.Plugin');
/**
* Plugin to insert 'Hello World!' into an editable field.
* @constructor
* @extends {goog.editor.Plugin}
*/
goog.demos.editor.HelloWorld = function() {
goog.editor.Plugin.call(this);
};
goog.inherits(goog.demos.editor.HelloWorld, goog.editor.Plugin);
/** @override */
goog.demos.editor.HelloWorld.prototype.getTrogClassId = function() {
return 'HelloWorld';
};
/**
* Commands implemented by this plugin.
* @enum {string}
*/
goog.demos.editor.HelloWorld.COMMAND = {
HELLO_WORLD: '+helloWorld'
};
/** @override */
goog.demos.editor.HelloWorld.prototype.isSupportedCommand = function(
command) {
return command == goog.demos.editor.HelloWorld.COMMAND.HELLO_WORLD;
};
/**
* Executes a command. Does not fire any BEFORECHANGE, CHANGE, or
* SELECTIONCHANGE events (these are handled by the super class implementation
* of {@code execCommand}.
* @param {string} command Command to execute.
* @override
* @protected
*/
goog.demos.editor.HelloWorld.prototype.execCommandInternal = function(
command) {
var domHelper = this.getFieldObject().getEditableDomHelper();
var range = this.getFieldObject().getRange();
range.removeContents();
var newNode =
domHelper.createDom(goog.dom.TagName.SPAN, null, 'Hello World!');
range.insertNode(newNode, 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.
/**
* @see equationeditor.html
*/
goog.provide('goog.demos.editor.EquationEditor');
goog.require('goog.ui.equation.EquationEditorDialog');
/**
* @constructor
*/
goog.demos.editor.EquationEditor = function() {
};
/**
* Creates a new editor and opens the dialog.
* @param {string} initialEquation The initial equation value to use.
*/
goog.demos.editor.EquationEditor.prototype.openEditor = function(
initialEquation) {
var editorDialog = new goog.ui.equation.EquationEditorDialog(initialEquation);
editorDialog.setVisible(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 An example of how to write a dialog plugin.
*
*/
goog.provide('goog.demos.editor.HelloWorldDialogPlugin');
goog.provide('goog.demos.editor.HelloWorldDialogPlugin.Command');
goog.require('goog.demos.editor.HelloWorldDialog');
goog.require('goog.dom.TagName');
goog.require('goog.editor.plugins.AbstractDialogPlugin');
goog.require('goog.editor.range');
goog.require('goog.functions');
goog.require('goog.ui.editor.AbstractDialog');
// *** Public interface ***************************************************** //
/**
* A plugin that opens the hello world dialog.
* @constructor
* @extends {goog.editor.plugins.AbstractDialogPlugin}
*/
goog.demos.editor.HelloWorldDialogPlugin = function() {
goog.editor.plugins.AbstractDialogPlugin.call(this,
goog.demos.editor.HelloWorldDialogPlugin.Command.HELLO_WORLD_DIALOG);
};
goog.inherits(goog.demos.editor.HelloWorldDialogPlugin,
goog.editor.plugins.AbstractDialogPlugin);
/**
* Commands implemented by this plugin.
* @enum {string}
*/
goog.demos.editor.HelloWorldDialogPlugin.Command = {
HELLO_WORLD_DIALOG: 'helloWorldDialog'
};
/** @override */
goog.demos.editor.HelloWorldDialogPlugin.prototype.getTrogClassId =
goog.functions.constant('HelloWorldDialog');
// *** Protected interface ************************************************** //
/**
* Creates a new instance of the dialog and registers for the relevant events.
* @param {goog.dom.DomHelper} dialogDomHelper The dom helper to be used to
* create the dialog.
* @return {goog.demos.editor.HelloWorldDialog} The dialog.
* @override
* @protected
*/
goog.demos.editor.HelloWorldDialogPlugin.prototype.createDialog = function(
dialogDomHelper) {
var dialog = new goog.demos.editor.HelloWorldDialog(dialogDomHelper);
dialog.addEventListener(goog.ui.editor.AbstractDialog.EventType.OK,
this.handleOk_,
false,
this);
return dialog;
};
// *** Private implementation *********************************************** //
/**
* Handles the OK event from the dialog by inserting the hello world message
* into the field.
* @param {goog.demos.editor.HelloWorldDialog.OkEvent} e OK event object.
* @private
*/
goog.demos.editor.HelloWorldDialogPlugin.prototype.handleOk_ = function(e) {
// First restore the selection so we can manipulate the field's content
// according to what was selected.
this.restoreOriginalSelection();
// Notify listeners that the field's contents are about to change.
this.getFieldObject().dispatchBeforeChange();
// Now we can clear out what was previously selected (if anything).
var range = this.getFieldObject().getRange();
range.removeContents();
// And replace it with a span containing our hello world message.
var createdNode = this.getFieldDomHelper().createDom(goog.dom.TagName.SPAN,
null,
e.message);
createdNode = range.insertNode(createdNode, false);
// Place the cursor at the end of the new text node (false == to the right).
goog.editor.range.placeCursorNextTo(createdNode, false);
// Notify listeners that the field's selection has changed.
this.getFieldObject().dispatchSelectionChangeEvent();
// Notify listeners that the field's contents have changed.
this.getFieldObject().dispatchChange();
};
| 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 simple, sample component.
*
*/
goog.provide('goog.demos.SampleComponent');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.events.KeyHandler');
goog.require('goog.events.KeyHandler.EventType');
goog.require('goog.ui.Component');
/**
* A simple box that changes colour when clicked. This class demonstrates the
* goog.ui.Component API, and is keyboard accessible, as per
* http://wiki/Main/ClosureKeyboardAccessible
*
* @param {string=} opt_label A label to display. Defaults to "Click Me" if none
* provided.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
*
* @extends {goog.ui.Component}
* @constructor
*/
goog.demos.SampleComponent = function(opt_label, opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
/**
* The label to display.
* @type {string}
* @private
*/
this.initialLabel_ = opt_label || 'Click Me';
/**
* The current color.
* @type {string}
* @private
*/
this.color_ = 'red';
/**
* Event handler for this object.
* @type {goog.events.EventHandler}
* @private
*/
this.eh_ = new goog.events.EventHandler(this);
/**
* Keyboard handler for this object. This object is created once the
* component's DOM element is known.
*
* @type {goog.events.KeyHandler?}
* @private
*/
this.kh_ = null;
};
goog.inherits(goog.demos.SampleComponent, goog.ui.Component);
/**
* Changes the color of the element.
* @private
*/
goog.demos.SampleComponent.prototype.changeColor_ = function() {
if (this.color_ == 'red') {
this.color_ = 'green';
} else if (this.color_ == 'green') {
this.color_ = 'blue';
} else {
this.color_ = 'red';
}
this.getElement().style.backgroundColor = this.color_;
};
/**
* Creates an initial DOM representation for the component.
*/
goog.demos.SampleComponent.prototype.createDom = function() {
this.decorateInternal(this.dom_.createElement('div'));
};
/**
* Decorates an existing HTML DIV element as a SampleComponent.
*
* @param {Element} element The DIV element to decorate. The element's
* text, if any will be used as the component's label.
*/
goog.demos.SampleComponent.prototype.decorateInternal = function(element) {
goog.demos.SampleComponent.superClass_.decorateInternal.call(this, element);
if (!this.getLabelText()) {
this.setLabelText(this.initialLabel_);
}
var elem = this.getElement();
goog.dom.classes.add(elem, goog.getCssName('goog-sample-component'));
elem.style.backgroundColor = this.color_;
elem.tabIndex = 0;
this.kh_ = new goog.events.KeyHandler(elem);
this.eh_.listen(this.kh_, goog.events.KeyHandler.EventType.KEY, this.onKey_);
};
/** @override */
goog.demos.SampleComponent.prototype.disposeInternal = function() {
goog.demos.SampleComponent.superClass_.disposeInternal.call(this);
this.eh_.dispose();
if (this.kh_) {
this.kh_.dispose();
}
};
/**
* Called when component's element is known to be in the document.
*/
goog.demos.SampleComponent.prototype.enterDocument = function() {
goog.demos.SampleComponent.superClass_.enterDocument.call(this);
this.eh_.listen(this.getElement(), goog.events.EventType.CLICK,
this.onDivClicked_);
};
/**
* Called when component's element is known to have been removed from the
* document.
*/
goog.demos.SampleComponent.prototype.exitDocument = function() {
goog.demos.SampleComponent.superClass_.exitDocument.call(this);
this.eh_.unlisten(this.getElement(), goog.events.EventType.CLICK,
this.onDivClicked_);
};
/**
* Gets the current label text.
*
* @return {string} The current text set into the label, or empty string if
* none set.
*/
goog.demos.SampleComponent.prototype.getLabelText = function() {
if (!this.getElement()) {
return '';
}
return goog.dom.getTextContent(this.getElement());
};
/**
* Handles DIV element clicks, causing the DIV's colour to change.
* @param {goog.events.Event} event The click event.
* @private
*/
goog.demos.SampleComponent.prototype.onDivClicked_ = function(event) {
this.changeColor_();
};
/**
* Fired when user presses a key while the DIV has focus. If the user presses
* space or enter, the color will be changed.
* @param {goog.events.Event} event The key event.
* @private
*/
goog.demos.SampleComponent.prototype.onKey_ = function(event) {
var keyCodes = goog.events.KeyCodes;
if (event.keyCode == keyCodes.SPACE || event.keyCode == keyCodes.ENTER) {
this.changeColor_();
}
};
/**
* Sets the current label text. Has no effect if component is not rendered.
*
* @param {string} text The text to set as the label.
*/
goog.demos.SampleComponent.prototype.setLabelText = function(text) {
if (this.getElement()) {
goog.dom.setTextContent(this.getElement(), text);
}
};
| 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.
var testData =
['Countries', [['A', [['Afghanistan'],
['Albania'],
['Algeria'],
['American Samoa'],
['Andorra'],
['Angola'],
['Anguilla'],
['Antarctica'],
['Antigua and Barbuda'],
['Argentina'],
['Armenia'],
['Aruba'],
['Australia'],
['Austria'],
['Azerbaijan']]],
['B', [['Bahamas'],
['Bahrain'],
['Bangladesh'],
['Barbados'],
['Belarus'],
['Belgium'],
['Belize'],
['Benin'],
['Bermuda'],
['Bhutan'],
['Bolivia'],
['Bosnia and Herzegovina'],
['Botswana'],
['Bouvet Island'],
['Brazil'],
['British Indian Ocean Territory'],
['Brunei Darussalam'],
['Bulgaria'],
['Burkina Faso'],
['Burundi']]],
['C', [['Cambodia'],
['Cameroon'],
['Canada'],
['Cape Verde'],
['Cayman Islands'],
['Central African Republic'],
['Chad'],
['Chile'],
['China'],
['Christmas Island'],
['Cocos (Keeling) Islands'],
['Colombia'],
['Comoros'],
['Congo'],
['Congo, the Democratic Republic of the'],
['Cook Islands'],
['Costa Rica'],
['Croatia'],
['Cuba'],
['Cyprus'],
['Czech Republic'],
['C\u00f4te d\u2019Ivoire']]],
['D', [['Denmark'],
['Djibouti'],
['Dominica'],
['Dominican Republic']]],
['E', [['Ecuador'],
['Egypt'],
['El Salvador'],
['Equatorial Guinea'],
['Eritrea'],
['Estonia'],
['Ethiopia']]],
['F', [['Falkland Islands (Malvinas)'],
['Faroe Islands'],
['Fiji'],
['Finland'],
['France'],
['French Guiana'],
['French Polynesia'],
['French Southern Territories']]],
['G', [['Gabon'],
['Gambia'],
['Georgia'],
['Germany'],
['Ghana'],
['Gibraltar'],
['Greece'],
['Greenland'],
['Grenada'],
['Guadeloupe'],
['Guam'],
['Guatemala'],
['Guernsey'],
['Guinea'],
['Guinea-Bissau'],
['Guyana']]],
['H', [['Haiti'],
['Heard Island and McDonald Islands'],
['Holy See (Vatican City State)'],
['Honduras'],
['Hong Kong'],
['Hungary']]],
['I', [['Iceland'],
['India'],
['Indonesia'],
['Iran, Islamic Republic of'],
['Iraq'],
['Ireland'],
['Isle of Man'],
['Israel'],
['Italy']]],
['J', [['Jamaica'],
['Japan'],
['Jersey'],
['Jordan']]],
['K', [['Kazakhstan'],
['Kenya'],
['Kiribati'],
['Korea, Democratic People\u2019s Republic of'],
['Korea, Republic of'],
['Kuwait'],
['Kyrgyzstan']]],
['L', [['Lao People\u2019s Democratic Republic'],
['Latvia'],
['Lebanon'],
['Lesotho'],
['Liberia'],
['Libyan Arab Jamahiriya'],
['Liechtenstein'],
['Lithuania'],
['Luxembourg']]],
['M', [['Macao'],
['Macedonia, the former Yugoslav Republic of'],
['Madagascar'],
['Malawi'],
['Malaysia'],
['Maldives'],
['Mali'],
['Malta'],
['Marshall Islands'],
['Martinique'],
['Mauritania'],
['Mauritius'],
['Mayotte'],
['Mexico'],
['Micronesia, Federated States of'],
['Moldova, Republic of'],
['Monaco'],
['Mongolia'],
['Montenegro'],
['Montserrat'],
['Morocco'],
['Mozambique'],
['Myanmar']]],
['N', [['Namibia'],
['Nauru'],
['Nepal'],
['Netherlands'],
['Netherlands Antilles'],
['New Caledonia'],
['New Zealand'],
['Nicaragua'],
['Niger'],
['Nigeria'],
['Niue'],
['Norfolk Island'],
['Northern Mariana Islands'],
['Norway']]],
['O', [['Oman']]],
['P', [['Pakistan'],
['Palau'],
['Palestinian Territory, Occupied'],
['Panama'],
['Papua New Guinea'],
['Paraguay'],
['Peru'],
['Philippines'],
['Pitcairn'],
['Poland'],
['Portugal'],
['Puerto Rico']]],
['Q', [['Qatar']]],
['R', [['Romania'],
['Russian Federation'],
['Rwanda'],
['R\u00e9union']]],
['S', [['Saint Barth\u00e9lemy'],
['Saint Helena'],
['Saint Kitts and Nevis'],
['Saint Lucia'],
['Saint Martin (French part)'],
['Saint Pierre and Miquelon'],
['Saint Vincent and the Grenadines'],
['Samoa'],
['San Marino'],
['Sao Tome and Principe'],
['Saudi Arabia'],
['Senegal'],
['Serbia'],
['Seychelles'],
['Sierra Leone'],
['Singapore'],
['Slovakia'],
['Slovenia'],
['Solomon Islands'],
['Somalia'],
['South Africa'],
['South Georgia and the South Sandwich Islands'],
['Spain'],
['Sri Lanka'],
['Sudan'],
['Suriname'],
['Svalbard and Jan Mayen'],
['Swaziland'],
['Sweden'],
['Switzerland'],
['Syrian Arab Republic']]],
['T', [['Taiwan, Province of China'],
['Tajikistan'],
['Tanzania, United Republic of'],
['Thailand'],
['Timor-Leste'],
['Togo'],
['Tokelau'],
['Tonga'],
['Trinidad and Tobago'],
['Tunisia'],
['Turkey'],
['Turkmenistan'],
['Turks and Caicos Islands'],
['Tuvalu']]],
['U', [['Uganda'],
['Ukraine'],
['United Arab Emirates'],
['United Kingdom'],
['United States'],
['United States Minor Outlying Islands'],
['Uruguay'],
['Uzbekistan']]],
['V', [['Vanuatu'],
['Venezuela'],
['Viet Nam'],
['Virgin Islands, British'],
['Virgin Islands, U.S.']]],
['W', [['Wallis and Futuna'],
['Western Sahara']]],
['Y', [['Yemen']]],
['Z', [['Zambia'],
['Zimbabwe']]],
['\u00c5', [['\u00c5land Islands']]]]]
| 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 This data is generated from an SVG image of a tiger.
*
* @author arv@google.com (Erik Arvidsson)
*/
var tigerData = [{f: '#fff', s: {c: '#000', w: 0.172},
p: [{t: 'M', p: [77.696, 284.285]},
{t: 'C', p: [77.696, 284.285, 77.797, 286.179, 76.973, 286.16]},
{t: 'C', p: [76.149, 286.141, 59.695, 238.066, 39.167, 240.309]},
{t: 'C', p: [39.167, 240.309, 56.95, 232.956, 77.696, 284.285]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.172},
p: [{t: 'M', p: [81.226, 281.262]},
{t: 'C', p: [81.226, 281.262, 80.677, 283.078, 79.908, 282.779]},
{t: 'C', p: [79.14, 282.481, 80.023, 231.675, 59.957, 226.801]},
{t: 'C', p: [59.957, 226.801, 79.18, 225.937, 81.226, 281.262]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.172},
p: [{t: 'M', p: [108.716, 323.59]},
{t: 'C', p: [108.716, 323.59, 110.352, 324.55, 109.882, 325.227]},
{t: 'C', p: [109.411, 325.904, 60.237, 313.102, 50.782, 331.459]},
{t: 'C', p: [50.782, 331.459, 54.461, 312.572, 108.716, 323.59]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.172},
p: [{t: 'M', p: [105.907, 333.801]},
{t: 'C', p: [105.907, 333.801, 107.763, 334.197, 107.529, 334.988]},
{t: 'C', p: [107.296, 335.779, 56.593, 339.121, 53.403, 359.522]},
{t: 'C', p: [53.403, 359.522, 50.945, 340.437, 105.907, 333.801]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.172},
p: [{t: 'M', p: [101.696, 328.276]},
{t: 'C', p: [101.696, 328.276, 103.474, 328.939, 103.128, 329.687]},
{t: 'C', p: [102.782, 330.435, 52.134, 326.346, 46.002, 346.064]},
{t: 'C', p: [46.002, 346.064, 46.354, 326.825, 101.696, 328.276]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.172},
p: [{t: 'M', p: [90.991, 310.072]},
{t: 'C', p: [90.991, 310.072, 92.299, 311.446, 91.66, 311.967]},
{t: 'C', p: [91.021, 312.488, 47.278, 286.634, 33.131, 301.676]},
{t: 'C', p: [33.131, 301.676, 41.872, 284.533, 90.991, 310.072]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.172},
p: [{t: 'M', p: [83.446, 314.263]},
{t: 'C', p: [83.446, 314.263, 84.902, 315.48, 84.326, 316.071]},
{t: 'C', p: [83.75, 316.661, 37.362, 295.922, 25.008, 312.469]},
{t: 'C', p: [25.008, 312.469, 31.753, 294.447, 83.446, 314.263]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.172},
p: [{t: 'M', p: [80.846, 318.335]},
{t: 'C', p: [80.846, 318.335, 82.454, 319.343, 81.964, 320.006]},
{t: 'C', p: [81.474, 320.669, 32.692, 306.446, 22.709, 324.522]},
{t: 'C', p: [22.709, 324.522, 26.934, 305.749, 80.846, 318.335]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.172},
p: [{t: 'M', p: [91.58, 318.949]},
{t: 'C', p: [91.58, 318.949, 92.702, 320.48, 92.001, 320.915]},
{t: 'C', p: [91.3, 321.35, 51.231, 290.102, 35.273, 303.207]},
{t: 'C', p: [35.273, 303.207, 46.138, 287.326, 91.58, 318.949]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.172},
p: [{t: 'M', p: [71.8, 290]},
{t: 'C', p: [71.8, 290, 72.4, 291.8, 71.6, 292]},
{t: 'C', p: [70.8, 292.2, 42.2, 250.2, 22.999, 257.8]},
{t: 'C', p: [22.999, 257.8, 38.2, 246, 71.8, 290]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.172},
p: [{t: 'M', p: [72.495, 296.979]},
{t: 'C', p: [72.495, 296.979, 73.47, 298.608, 72.731, 298.975]},
{t: 'C', p: [71.993, 299.343, 35.008, 264.499, 17.899, 276.061]},
{t: 'C', p: [17.899, 276.061, 30.196, 261.261, 72.495, 296.979]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.172},
p: [{t: 'M', p: [72.38, 301.349]},
{t: 'C', p: [72.38, 301.349, 73.502, 302.88, 72.801, 303.315]},
{t: 'C', p: [72.1, 303.749, 32.031, 272.502, 16.073, 285.607]},
{t: 'C', p: [16.073, 285.607, 26.938, 269.726, 72.38, 301.349]},
{t: 'z', p: []}]},
{f: '#fff', s: '#000', p: [{t: 'M', p: [70.17, 303.065]},
{t: 'C', p: [70.673, 309.113, 71.661, 315.682, 73.4, 318.801]},
{t: 'C', p: [73.4, 318.801, 69.8, 331.201, 78.6, 344.401]},
{t: 'C', p: [78.6, 344.401, 78.2, 351.601, 79.8, 354.801]},
{t: 'C', p: [79.8, 354.801, 83.8, 363.201, 88.6, 364.001]},
{t: 'C', p: [92.484, 364.648, 101.207, 367.717, 111.068, 369.121]},
{t: 'C', p: [111.068, 369.121, 128.2, 383.201, 125, 396.001]},
{t: 'C', p: [125, 396.001, 124.6, 412.401, 121, 414.001]},
{t: 'C', p: [121, 414.001, 132.6, 402.801, 123, 419.601]},
{t: 'L', p: [118.6, 438.401]},
{t: 'C', p: [118.6, 438.401, 144.2, 416.801, 128.6, 435.201]},
{t: 'L', p: [118.6, 461.201]},
{t: 'C', p: [118.6, 461.201, 138.2, 442.801, 131, 451.201]},
{t: 'L', p: [127.8, 460.001]},
{t: 'C', p: [127.8, 460.001, 171, 432.801, 140.2, 462.401]},
{t: 'C', p: [140.2, 462.401, 148.2, 458.801, 152.6, 461.601]},
{t: 'C', p: [152.6, 461.601, 159.4, 460.401, 158.6, 462.001]},
{t: 'C', p: [158.6, 462.001, 137.8, 472.401, 134.2, 490.801]},
{t: 'C', p: [134.2, 490.801, 142.6, 480.801, 139.4, 491.601]},
{t: 'L', p: [139.8, 503.201]},
{t: 'C', p: [139.8, 503.201, 143.8, 481.601, 143.4, 519.201]},
{t: 'C', p: [143.4, 519.201, 162.6, 501.201, 151, 522.001]},
{t: 'L', p: [151, 538.801]},
{t: 'C', p: [151, 538.801, 166.2, 522.401, 159.8, 535.201]},
{t: 'C', p: [159.8, 535.201, 169.8, 526.401, 165.8, 541.601]},
{t: 'C', p: [165.8, 541.601, 165, 552.001, 169.4, 540.801]},
{t: 'C', p: [169.4, 540.801, 185.4, 510.201, 179.4, 536.401]},
{t: 'C', p: [179.4, 536.401, 178.6, 555.601, 183.4, 540.801]},
{t: 'C', p: [183.4, 540.801, 183.8, 551.201, 193, 558.401]},
{t: 'C', p: [193, 558.401, 191.8, 507.601, 204.6, 543.601]},
{t: 'L', p: [208.6, 560.001]},
{t: 'C', p: [208.6, 560.001, 211.4, 550.801, 211, 545.601]},
{t: 'C', p: [211, 545.601, 225.8, 529.201, 219, 553.601]},
{t: 'C', p: [219, 553.601, 234.2, 530.801, 231, 544.001]},
{t: 'C', p: [231, 544.001, 223.4, 560.001, 225, 564.801]},
{t: 'C', p: [225, 564.801, 241.8, 530.001, 243, 528.401]},
{t: 'C', p: [243, 528.401, 241, 570.802, 251.8, 534.801]},
{t: 'C', p: [251.8, 534.801, 257.4, 546.801, 254.6, 551.201]},
{t: 'C', p: [254.6, 551.201, 262.6, 543.201, 261.8, 540.001]},
{t: 'C', p: [261.8, 540.001, 266.4, 531.801, 269.2, 545.401]},
{t: 'C', p: [269.2, 545.401, 271, 554.801, 272.6, 551.601]},
{t: 'C', p: [272.6, 551.601, 276.6, 575.602, 277.8, 552.801]},
{t: 'C', p: [277.8, 552.801, 279.4, 539.201, 272.2, 527.601]},
{t: 'C', p: [272.2, 527.601, 273, 524.401, 270.2, 520.401]},
{t: 'C', p: [270.2, 520.401, 283.8, 542.001, 276.6, 513.201]},
{t: 'C', p: [276.6, 513.201, 287.801, 521.201, 289.001, 521.201]},
{t: 'C', p: [289.001, 521.201, 275.4, 498.001, 284.2, 502.801]},
{t: 'C', p: [284.2, 502.801, 279, 492.401, 297.001, 504.401]},
{t: 'C', p: [297.001, 504.401, 281, 488.401, 298.601, 498.001]},
{t: 'C', p: [298.601, 498.001, 306.601, 504.401, 299.001, 494.401]},
{t: 'C', p: [299.001, 494.401, 284.6, 478.401, 306.601, 496.401]},
{t: 'C', p: [306.601, 496.401, 318.201, 512.801, 319.001, 515.601]},
{t: 'C', p: [319.001, 515.601, 309.001, 486.401, 304.601, 483.601]},
{t: 'C', p: [304.601, 483.601, 313.001, 447.201, 354.201, 462.801]},
{t: 'C', p: [354.201, 462.801, 361.001, 480.001, 365.401, 461.601]},
{t: 'C', p: [365.401, 461.601, 378.201, 455.201, 389.401, 482.801]},
{t: 'C', p: [389.401, 482.801, 393.401, 469.201, 392.601, 466.401]},
{t: 'C', p: [392.601, 466.401, 399.401, 467.601, 398.601, 466.401]},
{t: 'C', p: [398.601, 466.401, 411.801, 470.801, 413.001, 470.001]},
{t: 'C', p: [413.001, 470.001, 419.801, 476.801, 420.201, 473.201]},
{t: 'C', p: [420.201, 473.201, 429.401, 476.001, 427.401, 472.401]},
{t: 'C', p: [427.401, 472.401, 436.201, 488.001, 436.601, 491.601]},
{t: 'L', p: [439.001, 477.601]},
{t: 'L', p: [441.001, 480.401]},
{t: 'C', p: [441.001, 480.401, 442.601, 472.801, 441.801, 471.601]},
{t: 'C', p: [441.001, 470.401, 461.801, 478.401, 466.601, 499.201]},
{t: 'L', p: [468.601, 507.601]},
{t: 'C', p: [468.601, 507.601, 474.601, 492.801, 473.001, 488.801]},
{t: 'C', p: [473.001, 488.801, 478.201, 489.601, 478.601, 494.001]},
{t: 'C', p: [478.601, 494.001, 482.601, 470.801, 477.801, 464.801]},
{t: 'C', p: [477.801, 464.801, 482.201, 464.001, 483.401, 467.601]},
{t: 'L', p: [483.401, 460.401]},
{t: 'C', p: [483.401, 460.401, 490.601, 461.201, 490.601, 458.801]},
{t: 'C', p: [490.601, 458.801, 495.001, 454.801, 497.001, 459.601]},
{t: 'C', p: [497.001, 459.601, 484.601, 424.401, 503.001, 443.601]},
{t: 'C', p: [503.001, 443.601, 510.201, 454.401, 506.601, 435.601]},
{t: 'C', p: [503.001, 416.801, 499.001, 415.201, 503.801, 414.801]},
{t: 'C', p: [503.801, 414.801, 504.601, 411.201, 502.601, 409.601]},
{t: 'C', p: [500.601, 408.001, 503.801, 409.601, 503.801, 409.601]},
{t: 'C', p: [503.801, 409.601, 508.601, 413.601, 503.401, 391.601]},
{t: 'C', p: [503.401, 391.601, 509.801, 393.201, 497.801, 364.001]},
{t: 'C', p: [497.801, 364.001, 500.601, 361.601, 496.601, 353.201]},
{t: 'C', p: [496.601, 353.201, 504.601, 357.601, 507.401, 356.001]},
{t: 'C', p: [507.401, 356.001, 507.001, 354.401, 503.801, 350.401]},
{t: 'C', p: [503.801, 350.401, 482.201, 295.6, 502.601, 317.601]},
{t: 'C', p: [502.601, 317.601, 514.451, 331.151, 508.051, 308.351]},
{t: 'C', p: [508.051, 308.351, 498.94, 284.341, 499.717, 280.045]},
{t: 'L', p: [70.17, 303.065]},
{t: 'z', p: []}]},
{f: '#cc7226', s: '#000', p: [{t: 'M', p: [499.717, 280.245]},
{t: 'C', p: [500.345, 280.426, 502.551, 281.55, 503.801, 283.2]},
{t: 'C', p: [503.801, 283.2, 510.601, 294, 505.401, 275.6]},
{t: 'C', p: [505.401, 275.6, 496.201, 246.8, 505.001, 258]},
{t: 'C', p: [505.001, 258, 511.001, 265.2, 507.801, 251.6]},
{t: 'C', p: [503.936, 235.173, 501.401, 228.8, 501.401, 228.8]},
{t: 'C', p: [501.401, 228.8, 513.001, 233.6, 486.201, 194]},
{t: 'L', p: [495.001, 197.6]},
{t: 'C', p: [495.001, 197.6, 475.401, 158, 453.801, 152.8]},
{t: 'L', p: [445.801, 146.8]},
{t: 'C', p: [445.801, 146.8, 484.201, 108.8, 471.401, 72]},
{t: 'C', p: [471.401, 72, 464.601, 66.8, 455.001, 76]},
{t: 'C', p: [455.001, 76, 448.601, 80.8, 442.601, 79.2]},
{t: 'C', p: [442.601, 79.2, 411.801, 80.4, 409.801, 80.4]},
{t: 'C', p: [407.801, 80.4, 373.001, 43.2, 307.401, 60.8]},
{t: 'C', p: [307.401, 60.8, 302.201, 62.8, 297.801, 61.6]},
{t: 'C', p: [297.801, 61.6, 279.4, 45.6, 230.6, 68.4]},
{t: 'C', p: [230.6, 68.4, 220.6, 70.4, 219, 70.4]},
{t: 'C', p: [217.4, 70.4, 214.6, 70.4, 206.6, 76.8]},
{t: 'C', p: [198.6, 83.2, 198.2, 84, 196.2, 85.6]},
{t: 'C', p: [196.2, 85.6, 179.8, 96.8, 175, 97.6]},
{t: 'C', p: [175, 97.6, 163.4, 104, 159, 114]},
{t: 'L', p: [155.4, 115.2]},
{t: 'C', p: [155.4, 115.2, 153.8, 122.4, 153.4, 123.6]},
{t: 'C', p: [153.4, 123.6, 148.6, 127.2, 147.8, 132.8]},
{t: 'C', p: [147.8, 132.8, 139, 138.8, 139.4, 143.2]},
{t: 'C', p: [139.4, 143.2, 137.8, 148.4, 137, 153.2]},
{t: 'C', p: [137, 153.2, 129.8, 158, 130.6, 160.8]},
{t: 'C', p: [130.6, 160.8, 123, 174.8, 124.2, 181.6]},
{t: 'C', p: [124.2, 181.6, 117.8, 181.2, 115, 183.6]},
{t: 'C', p: [115, 183.6, 114.2, 188.4, 112.6, 188.8]},
{t: 'C', p: [112.6, 188.8, 109.8, 190, 112.2, 194]},
{t: 'C', p: [112.2, 194, 110.6, 196.8, 110.2, 198.4]},
{t: 'C', p: [110.2, 198.4, 111, 201.2, 106.6, 206.8]},
{t: 'C', p: [106.6, 206.8, 100.2, 225.6, 102.2, 230.8]},
{t: 'C', p: [102.2, 230.8, 102.6, 235.6, 99.8, 237.2]},
{t: 'C', p: [99.8, 237.2, 96.2, 236.8, 104.6, 248.8]},
{t: 'C', p: [104.6, 248.8, 105.4, 250, 102.2, 252.4]},
{t: 'C', p: [102.2, 252.4, 85, 256, 82.6, 272.4]},
{t: 'C', p: [82.6, 272.4, 69, 287.2, 69, 292.4]},
{t: 'C', p: [69, 294.705, 69.271, 297.852, 69.97, 302.465]},
{t: 'C', p: [69.97, 302.465, 69.4, 310.801, 97, 311.601]},
{t: 'C', p: [124.6, 312.401, 499.717, 280.245, 499.717, 280.245]},
{t: 'z', p: []}]},
{f: '#cc7226', s: null, p: [{t: 'M', p: [84.4, 302.6]},
{t: 'C', p: [59.4, 263.2, 73.8, 319.601, 73.8, 319.601]},
{t: 'C', p: [82.6, 354.001, 212.2, 316.401, 212.2, 316.401]},
{t: 'C', p: [212.2, 316.401, 381.001, 286, 392.201, 282]},
{t: 'C', p: [403.401, 278, 498.601, 284.4, 498.601, 284.4]},
{t: 'L', p: [493.001, 267.6]},
{t: 'C', p: [428.201, 221.2, 409.001, 244.4, 395.401, 240.4]},
{t: 'C', p: [381.801, 236.4, 384.201, 246, 381.001, 246.8]},
{t: 'C', p: [377.801, 247.6, 338.601, 222.8, 332.201, 223.6]},
{t: 'C', p: [325.801, 224.4, 300.459, 200.649, 315.401, 232.4]},
{t: 'C', p: [331.401, 266.4, 257, 271.6, 240.2, 260.4]},
{t: 'C', p: [223.4, 249.2, 247.4, 278.8, 247.4, 278.8]},
{t: 'C', p: [265.8, 298.8, 231.4, 282, 231.4, 282]},
{t: 'C', p: [197, 269.2, 173, 294.8, 169.8, 295.6]},
{t: 'C', p: [166.6, 296.4, 161.8, 299.6, 161, 293.2]},
{t: 'C', p: [160.2, 286.8, 152.69, 270.099, 121, 296.4]},
{t: 'C', p: [101, 313.001, 87.2, 291, 87.2, 291]},
{t: 'L', p: [84.4, 302.6]},
{t: 'z', p: []}]},
{f: '#e87f3a', s: null, p: [{t: 'M', p: [333.51, 225.346]},
{t: 'C', p: [327.11, 226.146, 301.743, 202.407, 316.71, 234.146]},
{t: 'C', p: [333.31, 269.346, 258.31, 273.346, 241.51, 262.146]},
{t: 'C', p: [224.709, 250.946, 248.71, 280.546, 248.71, 280.546]},
{t: 'C', p: [267.11, 300.546, 232.709, 283.746, 232.709, 283.746]},
{t: 'C', p: [198.309, 270.946, 174.309, 296.546, 171.109, 297.346]},
{t: 'C', p: [167.909, 298.146, 163.109, 301.346, 162.309, 294.946]},
{t: 'C', p: [161.509, 288.546, 154.13, 272.012, 122.309, 298.146]},
{t: 'C', p: [101.073, 315.492, 87.582, 294.037, 87.582, 294.037]},
{t: 'L', p: [84.382, 304.146]},
{t: 'C', p: [59.382, 264.346, 74.454, 322.655, 74.454, 322.655]},
{t: 'C', p: [83.255, 357.056, 213.509, 318.146, 213.509, 318.146]},
{t: 'C', p: [213.509, 318.146, 382.31, 287.746, 393.51, 283.746]},
{t: 'C', p: [404.71, 279.746, 499.038, 286.073, 499.038, 286.073]},
{t: 'L', p: [493.51, 268.764]},
{t: 'C', p: [428.71, 222.364, 410.31, 246.146, 396.71, 242.146]},
{t: 'C', p: [383.11, 238.146, 385.51, 247.746, 382.31, 248.546]},
{t: 'C', p: [379.11, 249.346, 339.91, 224.546, 333.51, 225.346]},
{t: 'z', p: []}]},
{f: '#ea8c4d', s: null, p: [{t: 'M', p: [334.819, 227.091]},
{t: 'C', p: [328.419, 227.891, 303.685, 203.862, 318.019, 235.891]},
{t: 'C', p: [334.219, 272.092, 259.619, 275.092, 242.819, 263.892]},
{t: 'C', p: [226.019, 252.692, 250.019, 282.292, 250.019, 282.292]},
{t: 'C', p: [268.419, 302.292, 234.019, 285.492, 234.019, 285.492]},
{t: 'C', p: [199.619, 272.692, 175.618, 298.292, 172.418, 299.092]},
{t: 'C', p: [169.218, 299.892, 164.418, 303.092, 163.618, 296.692]},
{t: 'C', p: [162.818, 290.292, 155.57, 273.925, 123.618, 299.892]},
{t: 'C', p: [101.145, 317.983, 87.964, 297.074, 87.964, 297.074]},
{t: 'L', p: [84.364, 305.692]},
{t: 'C', p: [60.564, 266.692, 75.109, 325.71, 75.109, 325.71]},
{t: 'C', p: [83.909, 360.11, 214.819, 319.892, 214.819, 319.892]},
{t: 'C', p: [214.819, 319.892, 383.619, 289.492, 394.819, 285.492]},
{t: 'C', p: [406.019, 281.492, 499.474, 287.746, 499.474, 287.746]},
{t: 'L', p: [494.02, 269.928]},
{t: 'C', p: [429.219, 223.528, 411.619, 247.891, 398.019, 243.891]},
{t: 'C', p: [384.419, 239.891, 386.819, 249.491, 383.619, 250.292]},
{t: 'C', p: [380.419, 251.092, 341.219, 226.291, 334.819, 227.091]},
{t: 'z', p: []}]},
{f: '#ec9961', s: null, p: [{t: 'M', p: [336.128, 228.837]},
{t: 'C', p: [329.728, 229.637, 304.999, 205.605, 319.328, 237.637]},
{t: 'C', p: [336.128, 275.193, 260.394, 276.482, 244.128, 265.637]},
{t: 'C', p: [227.328, 254.437, 251.328, 284.037, 251.328, 284.037]},
{t: 'C', p: [269.728, 304.037, 235.328, 287.237, 235.328, 287.237]},
{t: 'C', p: [200.928, 274.437, 176.928, 300.037, 173.728, 300.837]},
{t: 'C', p: [170.528, 301.637, 165.728, 304.837, 164.928, 298.437]},
{t: 'C', p: [164.128, 292.037, 157.011, 275.839, 124.927, 301.637]},
{t: 'C', p: [101.218, 320.474, 88.345, 300.11, 88.345, 300.11]},
{t: 'L', p: [84.345, 307.237]},
{t: 'C', p: [62.545, 270.437, 75.764, 328.765, 75.764, 328.765]},
{t: 'C', p: [84.564, 363.165, 216.128, 321.637, 216.128, 321.637]},
{t: 'C', p: [216.128, 321.637, 384.928, 291.237, 396.129, 287.237]},
{t: 'C', p: [407.329, 283.237, 499.911, 289.419, 499.911, 289.419]},
{t: 'L', p: [494.529, 271.092]},
{t: 'C', p: [429.729, 224.691, 412.929, 249.637, 399.329, 245.637]},
{t: 'C', p: [385.728, 241.637, 388.128, 251.237, 384.928, 252.037]},
{t: 'C', p: [381.728, 252.837, 342.528, 228.037, 336.128, 228.837]},
{t: 'z', p: []}]},
{f: '#eea575', s: null, p: [{t: 'M', p: [337.438, 230.583]},
{t: 'C', p: [331.037, 231.383, 306.814, 207.129, 320.637, 239.383]},
{t: 'C', p: [337.438, 278.583, 262.237, 278.583, 245.437, 267.383]},
{t: 'C', p: [228.637, 256.183, 252.637, 285.783, 252.637, 285.783]},
{t: 'C', p: [271.037, 305.783, 236.637, 288.983, 236.637, 288.983]},
{t: 'C', p: [202.237, 276.183, 178.237, 301.783, 175.037, 302.583]},
{t: 'C', p: [171.837, 303.383, 167.037, 306.583, 166.237, 300.183]},
{t: 'C', p: [165.437, 293.783, 158.452, 277.752, 126.237, 303.383]},
{t: 'C', p: [101.291, 322.965, 88.727, 303.146, 88.727, 303.146]},
{t: 'L', p: [84.327, 308.783]},
{t: 'C', p: [64.527, 273.982, 76.418, 331.819, 76.418, 331.819]},
{t: 'C', p: [85.218, 366.22, 217.437, 323.383, 217.437, 323.383]},
{t: 'C', p: [217.437, 323.383, 386.238, 292.983, 397.438, 288.983]},
{t: 'C', p: [408.638, 284.983, 500.347, 291.092, 500.347, 291.092]},
{t: 'L', p: [495.038, 272.255]},
{t: 'C', p: [430.238, 225.855, 414.238, 251.383, 400.638, 247.383]},
{t: 'C', p: [387.038, 243.383, 389.438, 252.983, 386.238, 253.783]},
{t: 'C', p: [383.038, 254.583, 343.838, 229.783, 337.438, 230.583]},
{t: 'z', p: []}]},
{f: '#f1b288', s: null, p: [{t: 'M', p: [338.747, 232.328]},
{t: 'C', p: [332.347, 233.128, 306.383, 209.677, 321.947, 241.128]},
{t: 'C', p: [341.147, 279.928, 263.546, 280.328, 246.746, 269.128]},
{t: 'C', p: [229.946, 257.928, 253.946, 287.528, 253.946, 287.528]},
{t: 'C', p: [272.346, 307.528, 237.946, 290.728, 237.946, 290.728]},
{t: 'C', p: [203.546, 277.928, 179.546, 303.528, 176.346, 304.328]},
{t: 'C', p: [173.146, 305.128, 168.346, 308.328, 167.546, 301.928]},
{t: 'C', p: [166.746, 295.528, 159.892, 279.665, 127.546, 305.128]},
{t: 'C', p: [101.364, 325.456, 89.109, 306.183, 89.109, 306.183]},
{t: 'L', p: [84.309, 310.328]},
{t: 'C', p: [66.309, 277.128, 77.073, 334.874, 77.073, 334.874]},
{t: 'C', p: [85.873, 369.274, 218.746, 325.128, 218.746, 325.128]},
{t: 'C', p: [218.746, 325.128, 387.547, 294.728, 398.747, 290.728]},
{t: 'C', p: [409.947, 286.728, 500.783, 292.764, 500.783, 292.764]},
{t: 'L', p: [495.547, 273.419]},
{t: 'C', p: [430.747, 227.019, 415.547, 253.128, 401.947, 249.128]},
{t: 'C', p: [388.347, 245.128, 390.747, 254.728, 387.547, 255.528]},
{t: 'C', p: [384.347, 256.328, 345.147, 231.528, 338.747, 232.328]},
{t: 'z', p: []}]},
{f: '#f3bf9c', s: null, p: [{t: 'M', p: [340.056, 234.073]},
{t: 'C', p: [333.655, 234.873, 307.313, 211.613, 323.255, 242.873]},
{t: 'C', p: [343.656, 282.874, 264.855, 282.074, 248.055, 270.874]},
{t: 'C', p: [231.255, 259.674, 255.255, 289.274, 255.255, 289.274]},
{t: 'C', p: [273.655, 309.274, 239.255, 292.474, 239.255, 292.474]},
{t: 'C', p: [204.855, 279.674, 180.855, 305.274, 177.655, 306.074]},
{t: 'C', p: [174.455, 306.874, 169.655, 310.074, 168.855, 303.674]},
{t: 'C', p: [168.055, 297.274, 161.332, 281.578, 128.855, 306.874]},
{t: 'C', p: [101.436, 327.947, 89.491, 309.219, 89.491, 309.219]},
{t: 'L', p: [84.291, 311.874]},
{t: 'C', p: [68.291, 281.674, 77.727, 337.929, 77.727, 337.929]},
{t: 'C', p: [86.527, 372.329, 220.055, 326.874, 220.055, 326.874]},
{t: 'C', p: [220.055, 326.874, 388.856, 296.474, 400.056, 292.474]},
{t: 'C', p: [411.256, 288.474, 501.22, 294.437, 501.22, 294.437]},
{t: 'L', p: [496.056, 274.583]},
{t: 'C', p: [431.256, 228.183, 416.856, 254.874, 403.256, 250.874]},
{t: 'C', p: [389.656, 246.873, 392.056, 256.474, 388.856, 257.274]},
{t: 'C', p: [385.656, 258.074, 346.456, 233.273, 340.056, 234.073]},
{t: 'z', p: []}]},
{f: '#f5ccb0', s: null, p: [{t: 'M', p: [341.365, 235.819]},
{t: 'C', p: [334.965, 236.619, 307.523, 213.944, 324.565, 244.619]},
{t: 'C', p: [346.565, 284.219, 266.164, 283.819, 249.364, 272.619]},
{t: 'C', p: [232.564, 261.419, 256.564, 291.019, 256.564, 291.019]},
{t: 'C', p: [274.964, 311.019, 240.564, 294.219, 240.564, 294.219]},
{t: 'C', p: [206.164, 281.419, 182.164, 307.019, 178.964, 307.819]},
{t: 'C', p: [175.764, 308.619, 170.964, 311.819, 170.164, 305.419]},
{t: 'C', p: [169.364, 299.019, 162.773, 283.492, 130.164, 308.619]},
{t: 'C', p: [101.509, 330.438, 89.873, 312.256, 89.873, 312.256]},
{t: 'L', p: [84.273, 313.419]},
{t: 'C', p: [69.872, 285.019, 78.382, 340.983, 78.382, 340.983]},
{t: 'C', p: [87.182, 375.384, 221.364, 328.619, 221.364, 328.619]},
{t: 'C', p: [221.364, 328.619, 390.165, 298.219, 401.365, 294.219]},
{t: 'C', p: [412.565, 290.219, 501.656, 296.11, 501.656, 296.11]},
{t: 'L', p: [496.565, 275.746]},
{t: 'C', p: [431.765, 229.346, 418.165, 256.619, 404.565, 252.619]},
{t: 'C', p: [390.965, 248.619, 393.365, 258.219, 390.165, 259.019]},
{t: 'C', p: [386.965, 259.819, 347.765, 235.019, 341.365, 235.819]},
{t: 'z', p: []}]},
{f: '#f8d8c4', s: null, p: [{t: 'M', p: [342.674, 237.565]},
{t: 'C', p: [336.274, 238.365, 308.832, 215.689, 325.874, 246.365]},
{t: 'C', p: [347.874, 285.965, 267.474, 285.565, 250.674, 274.365]},
{t: 'C', p: [233.874, 263.165, 257.874, 292.765, 257.874, 292.765]},
{t: 'C', p: [276.274, 312.765, 241.874, 295.965, 241.874, 295.965]},
{t: 'C', p: [207.473, 283.165, 183.473, 308.765, 180.273, 309.565]},
{t: 'C', p: [177.073, 310.365, 172.273, 313.565, 171.473, 307.165]},
{t: 'C', p: [170.673, 300.765, 164.214, 285.405, 131.473, 310.365]},
{t: 'C', p: [101.582, 332.929, 90.255, 315.293, 90.255, 315.293]},
{t: 'L', p: [84.255, 314.965]},
{t: 'C', p: [70.654, 288.564, 79.037, 344.038, 79.037, 344.038]},
{t: 'C', p: [87.837, 378.438, 222.673, 330.365, 222.673, 330.365]},
{t: 'C', p: [222.673, 330.365, 391.474, 299.965, 402.674, 295.965]},
{t: 'C', p: [413.874, 291.965, 502.093, 297.783, 502.093, 297.783]},
{t: 'L', p: [497.075, 276.91]},
{t: 'C', p: [432.274, 230.51, 419.474, 258.365, 405.874, 254.365]},
{t: 'C', p: [392.274, 250.365, 394.674, 259.965, 391.474, 260.765]},
{t: 'C', p: [388.274, 261.565, 349.074, 236.765, 342.674, 237.565]},
{t: 'z', p: []}]},
{f: '#fae5d7', s: null, p: [{t: 'M', p: [343.983, 239.31]},
{t: 'C', p: [337.583, 240.11, 310.529, 217.223, 327.183, 248.11]},
{t: 'C', p: [349.183, 288.91, 268.783, 287.31, 251.983, 276.11]},
{t: 'C', p: [235.183, 264.91, 259.183, 294.51, 259.183, 294.51]},
{t: 'C', p: [277.583, 314.51, 243.183, 297.71, 243.183, 297.71]},
{t: 'C', p: [208.783, 284.91, 184.783, 310.51, 181.583, 311.31]},
{t: 'C', p: [178.382, 312.11, 173.582, 315.31, 172.782, 308.91]},
{t: 'C', p: [171.982, 302.51, 165.654, 287.318, 132.782, 312.11]},
{t: 'C', p: [101.655, 335.42, 90.637, 318.329, 90.637, 318.329]},
{t: 'L', p: [84.236, 316.51]},
{t: 'C', p: [71.236, 292.51, 79.691, 347.093, 79.691, 347.093]},
{t: 'C', p: [88.491, 381.493, 223.983, 332.11, 223.983, 332.11]},
{t: 'C', p: [223.983, 332.11, 392.783, 301.71, 403.983, 297.71]},
{t: 'C', p: [415.183, 293.71, 502.529, 299.456, 502.529, 299.456]},
{t: 'L', p: [497.583, 278.074]},
{t: 'C', p: [432.783, 231.673, 420.783, 260.11, 407.183, 256.11]},
{t: 'C', p: [393.583, 252.11, 395.983, 261.71, 392.783, 262.51]},
{t: 'C', p: [389.583, 263.31, 350.383, 238.51, 343.983, 239.31]},
{t: 'z', p: []}]},
{f: '#fcf2eb', s: null, p: [{t: 'M', p: [345.292, 241.055]},
{t: 'C', p: [338.892, 241.855, 312.917, 218.411, 328.492, 249.855]},
{t: 'C', p: [349.692, 292.656, 270.092, 289.056, 253.292, 277.856]},
{t: 'C', p: [236.492, 266.656, 260.492, 296.256, 260.492, 296.256]},
{t: 'C', p: [278.892, 316.256, 244.492, 299.456, 244.492, 299.456]},
{t: 'C', p: [210.092, 286.656, 186.092, 312.256, 182.892, 313.056]},
{t: 'C', p: [179.692, 313.856, 174.892, 317.056, 174.092, 310.656]},
{t: 'C', p: [173.292, 304.256, 167.095, 289.232, 134.092, 313.856]},
{t: 'C', p: [101.727, 337.911, 91.018, 321.365, 91.018, 321.365]},
{t: 'L', p: [84.218, 318.056]},
{t: 'C', p: [71.418, 294.856, 80.346, 350.147, 80.346, 350.147]},
{t: 'C', p: [89.146, 384.547, 225.292, 333.856, 225.292, 333.856]},
{t: 'C', p: [225.292, 333.856, 394.093, 303.456, 405.293, 299.456]},
{t: 'C', p: [416.493, 295.456, 502.965, 301.128, 502.965, 301.128]},
{t: 'L', p: [498.093, 279.237]},
{t: 'C', p: [433.292, 232.837, 422.093, 261.856, 408.493, 257.856]},
{t: 'C', p: [394.893, 253.855, 397.293, 263.456, 394.093, 264.256]},
{t: 'C', p: [390.892, 265.056, 351.692, 240.255, 345.292, 241.055]},
{t: 'z', p: []}]},
{f: '#fff', s: null, p: [{t: 'M', p: [84.2, 319.601]},
{t: 'C', p: [71.4, 297.6, 81, 353.201, 81, 353.201]},
{t: 'C', p: [89.8, 387.601, 226.6, 335.601, 226.6, 335.601]},
{t: 'C', p: [226.6, 335.601, 395.401, 305.2, 406.601, 301.2]},
{t: 'C', p: [417.801, 297.2, 503.401, 302.8, 503.401, 302.8]},
{t: 'L', p: [498.601, 280.4]},
{t: 'C', p: [433.801, 234, 423.401, 263.6, 409.801, 259.6]},
{t: 'C', p: [396.201, 255.6, 398.601, 265.2, 395.401, 266]},
{t: 'C', p: [392.201, 266.8, 353.001, 242, 346.601, 242.8]},
{t: 'C', p: [340.201, 243.6, 314.981, 219.793, 329.801, 251.6]},
{t: 'C', p: [352.028, 299.307, 269.041, 289.227, 254.6, 279.6]},
{t: 'C', p: [237.8, 268.4, 261.8, 298, 261.8, 298]},
{t: 'C', p: [280.2, 318.001, 245.8, 301.2, 245.8, 301.2]},
{t: 'C', p: [211.4, 288.4, 187.4, 314.001, 184.2, 314.801]},
{t: 'C', p: [181, 315.601, 176.2, 318.801, 175.4, 312.401]},
{t: 'C', p: [174.6, 306, 168.535, 291.144, 135.4, 315.601]},
{t: 'C', p: [101.8, 340.401, 91.4, 324.401, 91.4, 324.401]},
{t: 'L', p: [84.2, 319.601]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [125.8, 349.601]},
{t: 'C', p: [125.8, 349.601, 118.6, 361.201, 139.4, 374.401]},
{t: 'C', p: [139.4, 374.401, 140.8, 375.801, 122.8, 371.601]},
{t: 'C', p: [122.8, 371.601, 116.6, 369.601, 115, 359.201]},
{t: 'C', p: [115, 359.201, 110.2, 354.801, 105.4, 349.201]},
{t: 'C', p: [100.6, 343.601, 125.8, 349.601, 125.8, 349.601]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [265.8, 302]},
{t: 'C', p: [265.8, 302, 283.498, 328.821, 282.9, 333.601]},
{t: 'C', p: [281.6, 344.001, 281.4, 353.601, 284.6, 357.601]},
{t: 'C', p: [287.801, 361.601, 296.601, 394.801, 296.601, 394.801]},
{t: 'C', p: [296.601, 394.801, 296.201, 396.001, 308.601, 358.001]},
{t: 'C', p: [308.601, 358.001, 320.201, 342.001, 300.201, 323.601]},
{t: 'C', p: [300.201, 323.601, 265, 294.8, 265.8, 302]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [145.8, 376.401]},
{t: 'C', p: [145.8, 376.401, 157, 383.601, 142.6, 414.801]},
{t: 'L', p: [149, 412.401]},
{t: 'C', p: [149, 412.401, 148.2, 423.601, 145, 426.001]},
{t: 'L', p: [152.2, 422.801]},
{t: 'C', p: [152.2, 422.801, 157, 430.801, 153, 435.601]},
{t: 'C', p: [153, 435.601, 169.8, 443.601, 169, 450.001]},
{t: 'C', p: [169, 450.001, 175.4, 442.001, 171.4, 435.601]},
{t: 'C', p: [167.4, 429.201, 160.2, 433.201, 161, 414.801]},
{t: 'L', p: [152.2, 418.001]},
{t: 'C', p: [152.2, 418.001, 157.8, 409.201, 157.8, 402.801]},
{t: 'L', p: [149.8, 405.201]},
{t: 'C', p: [149.8, 405.201, 165.269, 378.623, 154.6, 377.201]},
{t: 'C', p: [148.6, 376.401, 145.8, 376.401, 145.8, 376.401]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [178.2, 393.201]},
{t: 'C', p: [178.2, 393.201, 181, 388.801, 178.2, 389.601]},
{t: 'C', p: [175.4, 390.401, 144.2, 405.201, 138.2, 414.801]},
{t: 'C', p: [138.2, 414.801, 172.6, 390.401, 178.2, 393.201]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [188.6, 401.201]},
{t: 'C', p: [188.6, 401.201, 191.4, 396.801, 188.6, 397.601]},
{t: 'C', p: [185.8, 398.401, 154.6, 413.201, 148.6, 422.801]},
{t: 'C', p: [148.6, 422.801, 183, 398.401, 188.6, 401.201]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [201.8, 386.001]},
{t: 'C', p: [201.8, 386.001, 204.6, 381.601, 201.8, 382.401]},
{t: 'C', p: [199, 383.201, 167.8, 398.001, 161.8, 407.601]},
{t: 'C', p: [161.8, 407.601, 196.2, 383.201, 201.8, 386.001]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [178.6, 429.601]},
{t: 'C', p: [178.6, 429.601, 178.6, 423.601, 175.8, 424.401]},
{t: 'C', p: [173, 425.201, 137, 442.801, 131, 452.401]},
{t: 'C', p: [131, 452.401, 173, 426.801, 178.6, 429.601]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [179.8, 418.801]},
{t: 'C', p: [179.8, 418.801, 181, 414.001, 178.2, 414.801]},
{t: 'C', p: [176.2, 414.801, 149.8, 426.401, 143.8, 436.001]},
{t: 'C', p: [143.8, 436.001, 173.4, 414.401, 179.8, 418.801]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [165.4, 466.401]},
{t: 'L', p: [155.4, 474.001]},
{t: 'C', p: [155.4, 474.001, 165.8, 466.401, 169.4, 467.601]},
{t: 'C', p: [169.4, 467.601, 162.6, 478.801, 161.8, 484.001]},
{t: 'C', p: [161.8, 484.001, 172.2, 471.201, 177.8, 471.601]},
{t: 'C', p: [177.8, 471.601, 185.4, 472.001, 185.4, 482.801]},
{t: 'C', p: [185.4, 482.801, 191, 472.401, 194.2, 472.801]},
{t: 'C', p: [194.2, 472.801, 195.4, 479.201, 194.2, 486.001]},
{t: 'C', p: [194.2, 486.001, 198.2, 478.401, 202.2, 480.001]},
{t: 'C', p: [202.2, 480.001, 208.6, 478.001, 207.8, 489.601]},
{t: 'C', p: [207.8, 489.601, 207.8, 500.001, 207, 502.801]},
{t: 'C', p: [207, 502.801, 212.6, 476.401, 215, 476.001]},
{t: 'C', p: [215, 476.001, 223, 474.801, 227.8, 483.601]},
{t: 'C', p: [227.8, 483.601, 223.8, 476.001, 228.6, 478.001]},
{t: 'C', p: [228.6, 478.001, 239.4, 479.601, 242.6, 486.401]},
{t: 'C', p: [242.6, 486.401, 235.8, 474.401, 241.4, 477.601]},
{t: 'C', p: [241.4, 477.601, 248.2, 477.601, 249.4, 484.001]},
{t: 'C', p: [249.4, 484.001, 257.8, 505.201, 259.8, 506.801]},
{t: 'C', p: [259.8, 506.801, 252.2, 485.201, 253.8, 485.201]},
{t: 'C', p: [253.8, 485.201, 251.8, 473.201, 257, 488.001]},
{t: 'C', p: [257, 488.001, 253.8, 474.001, 259.4, 474.801]},
{t: 'C', p: [265, 475.601, 269.4, 485.601, 277.8, 483.201]},
{t: 'C', p: [277.8, 483.201, 287.401, 488.801, 289.401, 419.601]},
{t: 'L', p: [165.4, 466.401]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [170.2, 373.601]},
{t: 'C', p: [170.2, 373.601, 185, 367.601, 225, 373.601]},
{t: 'C', p: [225, 373.601, 232.2, 374.001, 239, 365.201]},
{t: 'C', p: [245.8, 356.401, 272.6, 349.201, 279, 351.201]},
{t: 'L', p: [288.601, 357.601]},
{t: 'L', p: [289.401, 358.801]},
{t: 'C', p: [289.401, 358.801, 301.801, 369.201, 302.201, 376.801]},
{t: 'C', p: [302.601, 384.401, 287.801, 432.401, 278.2, 448.401]},
{t: 'C', p: [268.6, 464.401, 259, 476.801, 239.8, 474.401]},
{t: 'C', p: [239.8, 474.401, 219, 470.401, 193.4, 474.401]},
{t: 'C', p: [193.4, 474.401, 164.2, 472.801, 161.4, 464.801]},
{t: 'C', p: [158.6, 456.801, 172.6, 441.601, 172.6, 441.601]},
{t: 'C', p: [172.6, 441.601, 177, 433.201, 175.8, 418.801]},
{t: 'C', p: [174.6, 404.401, 175, 376.401, 170.2, 373.601]},
{t: 'z', p: []}]},
{f: '#e5668c', s: null, p: [{t: 'M', p: [192.2, 375.601]},
{t: 'C', p: [200.6, 394.001, 171, 459.201, 171, 459.201]},
{t: 'C', p: [169, 460.801, 183.66, 466.846, 193.8, 464.401]},
{t: 'C', p: [204.746, 461.763, 245, 466.001, 245, 466.001]},
{t: 'C', p: [268.6, 450.401, 281.4, 406.001, 281.4, 406.001]},
{t: 'C', p: [281.4, 406.001, 291.801, 382.001, 274.2, 378.801]},
{t: 'C', p: [256.6, 375.601, 192.2, 375.601, 192.2, 375.601]},
{t: 'z', p: []}]},
{f: '#b23259', s: null, p: [{t: 'M', p: [190.169, 406.497]},
{t: 'C', p: [193.495, 393.707, 195.079, 381.906, 192.2, 375.601]},
{t: 'C', p: [192.2, 375.601, 254.6, 382.001, 265.8, 361.201]},
{t: 'C', p: [270.041, 353.326, 284.801, 384.001, 284.4, 393.601]},
{t: 'C', p: [284.4, 393.601, 221.4, 408.001, 206.6, 396.801]},
{t: 'L', p: [190.169, 406.497]},
{t: 'z', p: []}]},
{f: '#a5264c', s: null, p: [{t: 'M', p: [194.6, 422.801]},
{t: 'C', p: [194.6, 422.801, 196.6, 430.001, 194.2, 434.001]},
{t: 'C', p: [194.2, 434.001, 192.6, 434.801, 191.4, 435.201]},
{t: 'C', p: [191.4, 435.201, 192.6, 438.801, 198.6, 440.401]},
{t: 'C', p: [198.6, 440.401, 200.6, 444.801, 203, 445.201]},
{t: 'C', p: [205.4, 445.601, 210.2, 451.201, 214.2, 450.001]},
{t: 'C', p: [218.2, 448.801, 229.4, 444.801, 229.4, 444.801]},
{t: 'C', p: [229.4, 444.801, 235, 441.601, 243.8, 445.201]},
{t: 'C', p: [243.8, 445.201, 246.175, 444.399, 246.6, 440.401]},
{t: 'C', p: [247.1, 435.701, 250.2, 432.001, 252.2, 430.001]},
{t: 'C', p: [254.2, 428.001, 263.8, 415.201, 262.6, 414.801]},
{t: 'C', p: [261.4, 414.401, 194.6, 422.801, 194.6, 422.801]},
{t: 'z', p: []}]},
{f: '#ff727f', s: '#000', p: [{t: 'M', p: [190.2, 374.401]},
{t: 'C', p: [190.2, 374.401, 187.4, 396.801, 190.6, 405.201]},
{t: 'C', p: [193.8, 413.601, 193, 415.601, 192.2, 419.601]},
{t: 'C', p: [191.4, 423.601, 195.8, 433.601, 201.4, 439.601]},
{t: 'L', p: [213.4, 441.201]},
{t: 'C', p: [213.4, 441.201, 228.6, 437.601, 237.8, 440.401]},
{t: 'C', p: [237.8, 440.401, 246.794, 441.744, 250.2, 426.801]},
{t: 'C', p: [250.2, 426.801, 255, 420.401, 262.2, 417.601]},
{t: 'C', p: [269.4, 414.801, 276.6, 373.201, 272.6, 365.201]},
{t: 'C', p: [268.6, 357.201, 254.2, 352.801, 238.2, 368.401]},
{t: 'C', p: [222.2, 384.001, 220.2, 367.201, 190.2, 374.401]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [191.8, 449.201]},
{t: 'C', p: [191.8, 449.201, 191, 447.201, 186.6, 446.801]},
{t: 'C', p: [186.6, 446.801, 164.2, 443.201, 155.8, 430.801]},
{t: 'C', p: [155.8, 430.801, 149, 425.201, 153.4, 436.801]},
{t: 'C', p: [153.4, 436.801, 163.8, 457.201, 170.6, 460.001]},
{t: 'C', p: [170.6, 460.001, 187, 464.001, 191.8, 449.201]},
{t: 'z', p: []}]},
{f: '#cc3f4c', s: null, p: [{t: 'M', p: [271.742, 385.229]},
{t: 'C', p: [272.401, 377.323, 274.354, 368.709, 272.6, 365.201]},
{t: 'C', p: [266.154, 352.307, 249.181, 357.695, 238.2, 368.401]},
{t: 'C', p: [222.2, 384.001, 220.2, 367.201, 190.2, 374.401]},
{t: 'C', p: [190.2, 374.401, 188.455, 388.364, 189.295, 398.376]},
{t: 'C', p: [189.295, 398.376, 226.6, 386.801, 227.4, 392.401]},
{t: 'C', p: [227.4, 392.401, 229, 389.201, 238.2, 389.201]},
{t: 'C', p: [247.4, 389.201, 270.142, 388.029, 271.742, 385.229]},
{t: 'z', p: []}]},
{f: null, s: {c: '#a51926', w: 2},
p: [{t: 'M', p: [228.6, 375.201]},
{t: 'C', p: [228.6, 375.201, 233.4, 380.001, 229.8, 389.601]},
{t: 'C', p: [229.8, 389.601, 215.4, 405.601, 217.4, 419.601]}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [180.6, 460.001]},
{t: 'C', p: [180.6, 460.001, 176.2, 447.201, 185, 454.001]},
{t: 'C', p: [185, 454.001, 189.8, 456.001, 188.6, 457.601]},
{t: 'C', p: [187.4, 459.201, 181.8, 463.201, 180.6, 460.001]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [185.64, 461.201]},
{t: 'C', p: [185.64, 461.201, 182.12, 450.961, 189.16, 456.401]},
{t: 'C', p: [189.16, 456.401, 193.581, 458.849, 192.04, 459.281]},
{t: 'C', p: [187.48, 460.561, 192.04, 463.121, 185.64, 461.201]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [190.44, 461.201]},
{t: 'C', p: [190.44, 461.201, 186.92, 450.961, 193.96, 456.401]},
{t: 'C', p: [193.96, 456.401, 198.335, 458.711, 196.84, 459.281]},
{t: 'C', p: [193.48, 460.561, 196.84, 463.121, 190.44, 461.201]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [197.04, 461.401]},
{t: 'C', p: [197.04, 461.401, 193.52, 451.161, 200.56, 456.601]},
{t: 'C', p: [200.56, 456.601, 204.943, 458.933, 203.441, 459.481]},
{t: 'C', p: [200.48, 460.561, 203.441, 463.321, 197.04, 461.401]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [203.52, 461.321]},
{t: 'C', p: [203.52, 461.321, 200, 451.081, 207.041, 456.521]},
{t: 'C', p: [207.041, 456.521, 210.881, 458.121, 209.921, 459.401]},
{t: 'C', p: [208.961, 460.681, 209.921, 463.241, 203.52, 461.321]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [210.2, 462.001]},
{t: 'C', p: [210.2, 462.001, 205.4, 449.601, 214.6, 456.001]},
{t: 'C', p: [214.6, 456.001, 219.4, 458.001, 218.2, 459.601]},
{t: 'C', p: [217, 461.201, 218.2, 464.401, 210.2, 462.001]},
{t: 'z', p: []}]},
{f: null, s: {c: '#a5264c', w: 2},
p: [{t: 'M', p: [181.8, 444.801]},
{t: 'C', p: [181.8, 444.801, 195, 442.001, 201, 445.201]},
{t: 'C', p: [201, 445.201, 207, 446.401, 208.2, 446.001]},
{t: 'C', p: [209.4, 445.601, 212.6, 445.201, 212.6, 445.201]}]},
{f: null, s: {c: '#a5264c', w: 2},
p: [{t: 'M', p: [215.8, 453.601]},
{t: 'C', p: [215.8, 453.601, 227.8, 440.001, 239.8, 444.401]},
{t: 'C', p: [246.816, 446.974, 245.8, 443.601, 246.6, 440.801]},
{t: 'C', p: [247.4, 438.001, 247.6, 433.801, 252.6, 430.801]}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [233, 437.601]},
{t: 'C', p: [233, 437.601, 229, 426.801, 226.2, 439.601]},
{t: 'C', p: [223.4, 452.401, 220.2, 456.001, 218.6, 458.801]},
{t: 'C', p: [218.6, 458.801, 218.6, 464.001, 227, 463.601]},
{t: 'C', p: [227, 463.601, 237.8, 463.201, 238.2, 460.401]},
{t: 'C', p: [238.6, 457.601, 237, 446.001, 233, 437.601]},
{t: 'z', p: []}]},
{f: null, s: {c: '#a5264c', w: 2},
p: [{t: 'M', p: [247, 444.801]},
{t: 'C', p: [247, 444.801, 250.6, 442.401, 253, 443.601]}]},
{f: null, s: {c: '#a5264c', w: 2},
p: [{t: 'M', p: [253.5, 428.401]},
{t: 'C', p: [253.5, 428.401, 256.4, 423.501, 261.2, 422.701]}]},
{f: '#b2b2b2', s: null, p: [{t: 'M', p: [174.2, 465.201]},
{t: 'C', p: [174.2, 465.201, 192.2, 468.401, 196.6, 466.801]},
{t: 'C', p: [196.6, 466.801, 205.4, 466.801, 197, 468.801]},
{t: 'C', p: [197, 468.801, 184.2, 468.801, 176.2, 467.601]},
{t: 'C', p: [176.2, 467.601, 164.6, 462.001, 174.2, 465.201]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [188.2, 372.001]},
{t: 'C', p: [188.2, 372.001, 205.8, 372.001, 207.8, 372.801]},
{t: 'C', p: [207.8, 372.801, 215, 403.601, 211.4, 411.201]},
{t: 'C', p: [211.4, 411.201, 210.2, 414.001, 207.4, 408.401]},
{t: 'C', p: [207.4, 408.401, 189, 375.601, 185.8, 373.601]},
{t: 'C', p: [182.6, 371.601, 187, 372.001, 188.2, 372.001]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [111.1, 369.301]},
{t: 'C', p: [111.1, 369.301, 120, 371.001, 132.6, 373.601]},
{t: 'C', p: [132.6, 373.601, 137.4, 396.001, 140.6, 400.801]},
{t: 'C', p: [143.8, 405.601, 140.2, 405.601, 136.6, 402.801]},
{t: 'C', p: [133, 400.001, 118.2, 386.001, 116.2, 381.601]},
{t: 'C', p: [114.2, 377.201, 111.1, 369.301, 111.1, 369.301]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [132.961, 373.818]},
{t: 'C', p: [132.961, 373.818, 138.761, 375.366, 139.77, 377.581]},
{t: 'C', p: [140.778, 379.795, 138.568, 383.092, 138.568, 383.092]},
{t: 'C', p: [138.568, 383.092, 137.568, 386.397, 136.366, 384.235]},
{t: 'C', p: [135.164, 382.072, 132.292, 374.412, 132.961, 373.818]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [133, 373.601]},
{t: 'C', p: [133, 373.601, 136.6, 378.801, 140.2, 378.801]},
{t: 'C', p: [143.8, 378.801, 144.182, 378.388, 147, 379.001]},
{t: 'C', p: [151.6, 380.001, 151.2, 378.001, 157.8, 379.201]},
{t: 'C', p: [160.44, 379.681, 163, 378.801, 165.8, 380.001]},
{t: 'C', p: [168.6, 381.201, 171.8, 380.401, 173, 378.401]},
{t: 'C', p: [174.2, 376.401, 179, 372.201, 179, 372.201]},
{t: 'C', p: [179, 372.201, 166.2, 374.001, 163.4, 374.801]},
{t: 'C', p: [163.4, 374.801, 141, 376.001, 133, 373.601]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [177.6, 373.801]},
{t: 'C', p: [177.6, 373.801, 171.15, 377.301, 170.75, 379.701]},
{t: 'C', p: [170.35, 382.101, 176, 385.801, 176, 385.801]},
{t: 'C', p: [176, 385.801, 178.75, 390.401, 179.35, 388.001]},
{t: 'C', p: [179.95, 385.601, 178.4, 374.201, 177.6, 373.801]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [140.115, 379.265]},
{t: 'C', p: [140.115, 379.265, 147.122, 390.453, 147.339, 379.242]},
{t: 'C', p: [147.339, 379.242, 147.896, 377.984, 146.136, 377.962]},
{t: 'C', p: [140.061, 377.886, 141.582, 373.784, 140.115, 379.265]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [147.293, 379.514]},
{t: 'C', p: [147.293, 379.514, 155.214, 390.701, 154.578, 379.421]},
{t: 'C', p: [154.578, 379.421, 154.585, 379.089, 152.832, 378.936]},
{t: 'C', p: [148.085, 378.522, 148.43, 374.004, 147.293, 379.514]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [154.506, 379.522]},
{t: 'C', p: [154.506, 379.522, 162.466, 390.15, 161.797, 380.484]},
{t: 'C', p: [161.797, 380.484, 161.916, 379.251, 160.262, 378.95]},
{t: 'C', p: [156.37, 378.244, 156.159, 374.995, 154.506, 379.522]},
{t: 'z', p: []}]},
{f: '#ffc', s: {c: '#000', w: 0.5},
p: [{t: 'M', p: [161.382, 379.602]},
{t: 'C', p: [161.382, 379.602, 169.282, 391.163, 169.63, 381.382]},
{t: 'C', p: [169.63, 381.382, 171.274, 380.004, 169.528, 379.782]},
{t: 'C', p: [163.71, 379.042, 164.508, 374.588, 161.382, 379.602]},
{t: 'z', p: []}]},
{f: '#e5e5b2', s: null, p: [{t: 'M', p: [125.208, 383.132]},
{t: 'L', p: [117.55, 381.601]},
{t: 'C', p: [114.95, 376.601, 112.85, 370.451, 112.85, 370.451]},
{t: 'C', p: [112.85, 370.451, 119.2, 371.451, 131.7, 374.251]},
{t: 'C', p: [131.7, 374.251, 132.576, 377.569, 134.048, 383.364]},
{t: 'L', p: [125.208, 383.132]},
{t: 'z', p: []}]},
{f: '#e5e5b2', s: null, p: [{t: 'M', p: [190.276, 378.47]},
{t: 'C', p: [188.61, 375.964, 187.293, 374.206, 186.643, 373.8]},
{t: 'C', p: [183.63, 371.917, 187.773, 372.294, 188.902, 372.294]},
{t: 'C', p: [188.902, 372.294, 205.473, 372.294, 207.356, 373.047]},
{t: 'C', p: [207.356, 373.047, 207.88, 375.289, 208.564, 378.68]},
{t: 'C', p: [208.564, 378.68, 198.476, 376.67, 190.276, 378.47]},
{t: 'z', p: []}]},
{f: '#cc7226', s: null, p: [{t: 'M', p: [243.88, 240.321]},
{t: 'C', p: [271.601, 244.281, 297.121, 208.641, 298.881, 198.96]},
{t: 'C', p: [300.641, 189.28, 290.521, 177.4, 290.521, 177.4]},
{t: 'C', p: [291.841, 174.32, 287.001, 160.24, 281.721, 151]},
{t: 'C', p: [276.441, 141.76, 260.54, 142.734, 243, 141.76]},
{t: 'C', p: [227.16, 140.88, 208.68, 164.2, 207.36, 165.96]},
{t: 'C', p: [206.04, 167.72, 212.2, 206.001, 213.52, 211.721]},
{t: 'C', p: [214.84, 217.441, 212.2, 243.841, 212.2, 243.841]},
{t: 'C', p: [246.44, 234.741, 216.16, 236.361, 243.88, 240.321]},
{t: 'z', p: []}]},
{f: '#ea8e51', s: null, p: [{t: 'M', p: [208.088, 166.608]},
{t: 'C', p: [206.792, 168.336, 212.84, 205.921, 214.136, 211.537]},
{t: 'C', p: [215.432, 217.153, 212.84, 243.073, 212.84, 243.073]},
{t: 'C', p: [245.512, 234.193, 216.728, 235.729, 243.944, 239.617]},
{t: 'C', p: [271.161, 243.505, 296.217, 208.513, 297.945, 199.008]},
{t: 'C', p: [299.673, 189.504, 289.737, 177.84, 289.737, 177.84]},
{t: 'C', p: [291.033, 174.816, 286.281, 160.992, 281.097, 151.92]},
{t: 'C', p: [275.913, 142.848, 260.302, 143.805, 243.08, 142.848]},
{t: 'C', p: [227.528, 141.984, 209.384, 164.88, 208.088, 166.608]},
{t: 'z', p: []}]},
{f: '#efaa7c', s: null, p: [{t: 'M', p: [208.816, 167.256]},
{t: 'C', p: [207.544, 168.952, 213.48, 205.841, 214.752, 211.353]},
{t: 'C', p: [216.024, 216.865, 213.48, 242.305, 213.48, 242.305]},
{t: 'C', p: [244.884, 233.145, 217.296, 235.097, 244.008, 238.913]},
{t: 'C', p: [270.721, 242.729, 295.313, 208.385, 297.009, 199.056]},
{t: 'C', p: [298.705, 189.728, 288.953, 178.28, 288.953, 178.28]},
{t: 'C', p: [290.225, 175.312, 285.561, 161.744, 280.473, 152.84]},
{t: 'C', p: [275.385, 143.936, 260.063, 144.875, 243.16, 143.936]},
{t: 'C', p: [227.896, 143.088, 210.088, 165.56, 208.816, 167.256]},
{t: 'z', p: []}]},
{f: '#f4c6a8', s: null, p: [{t: 'M', p: [209.544, 167.904]},
{t: 'C', p: [208.296, 169.568, 214.12, 205.761, 215.368, 211.169]},
{t: 'C', p: [216.616, 216.577, 214.12, 241.537, 214.12, 241.537]},
{t: 'C', p: [243.556, 232.497, 217.864, 234.465, 244.072, 238.209]},
{t: 'C', p: [270.281, 241.953, 294.409, 208.257, 296.073, 199.105]},
{t: 'C', p: [297.737, 189.952, 288.169, 178.72, 288.169, 178.72]},
{t: 'C', p: [289.417, 175.808, 284.841, 162.496, 279.849, 153.76]},
{t: 'C', p: [274.857, 145.024, 259.824, 145.945, 243.24, 145.024]},
{t: 'C', p: [228.264, 144.192, 210.792, 166.24, 209.544, 167.904]},
{t: 'z', p: []}]},
{f: '#f9e2d3', s: null, p: [{t: 'M', p: [210.272, 168.552]},
{t: 'C', p: [209.048, 170.184, 214.76, 205.681, 215.984, 210.985]},
{t: 'C', p: [217.208, 216.289, 214.76, 240.769, 214.76, 240.769]},
{t: 'C', p: [242.628, 231.849, 218.432, 233.833, 244.136, 237.505]},
{t: 'C', p: [269.841, 241.177, 293.505, 208.129, 295.137, 199.152]},
{t: 'C', p: [296.769, 190.176, 287.385, 179.16, 287.385, 179.16]},
{t: 'C', p: [288.609, 176.304, 284.121, 163.248, 279.225, 154.68]},
{t: 'C', p: [274.329, 146.112, 259.585, 147.015, 243.32, 146.112]},
{t: 'C', p: [228.632, 145.296, 211.496, 166.92, 210.272, 168.552]},
{t: 'z', p: []}]},
{f: '#fff', s: null, p: [{t: 'M', p: [244.2, 236.8]},
{t: 'C', p: [269.4, 240.4, 292.601, 208, 294.201, 199.2]},
{t: 'C', p: [295.801, 190.4, 286.601, 179.6, 286.601, 179.6]},
{t: 'C', p: [287.801, 176.8, 283.4, 164, 278.6, 155.6]},
{t: 'C', p: [273.8, 147.2, 259.346, 148.086, 243.4, 147.2]},
{t: 'C', p: [229, 146.4, 212.2, 167.6, 211, 169.2]},
{t: 'C', p: [209.8, 170.8, 215.4, 205.6, 216.6, 210.8]},
{t: 'C', p: [217.8, 216, 215.4, 240, 215.4, 240]},
{t: 'C', p: [240.9, 231.4, 219, 233.2, 244.2, 236.8]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [290.601, 202.8]},
{t: 'C', p: [290.601, 202.8, 262.8, 210.4, 251.2, 208.8]},
{t: 'C', p: [251.2, 208.8, 235.4, 202.2, 226.6, 224]},
{t: 'C', p: [226.6, 224, 223, 231.2, 221, 233.2]},
{t: 'C', p: [219, 235.2, 290.601, 202.8, 290.601, 202.8]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [294.401, 200.6]},
{t: 'C', p: [294.401, 200.6, 265.4, 212.8, 255.4, 212.4]},
{t: 'C', p: [255.4, 212.4, 239, 207.8, 230.6, 222.4]},
{t: 'C', p: [230.6, 222.4, 222.2, 231.6, 219, 233.2]},
{t: 'C', p: [219, 233.2, 218.6, 234.8, 225, 230.8]},
{t: 'L', p: [235.4, 236]},
{t: 'C', p: [235.4, 236, 250.2, 245.6, 259.8, 229.6]},
{t: 'C', p: [259.8, 229.6, 263.8, 218.4, 263.8, 216.4]},
{t: 'C', p: [263.8, 214.4, 285, 208.8, 286.601, 208.4]},
{t: 'C', p: [288.201, 208, 294.801, 203.8, 294.401, 200.6]},
{t: 'z', p: []}]},
{f: '#99cc32', s: null, p: [{t: 'M', p: [247, 236.514]},
{t: 'C', p: [240.128, 236.514, 231.755, 232.649, 231.755, 226.4]},
{t: 'C', p: [231.755, 220.152, 240.128, 213.887, 247, 213.887]},
{t: 'C', p: [253.874, 213.887, 259.446, 218.952, 259.446, 225.2]},
{t: 'C', p: [259.446, 231.449, 253.874, 236.514, 247, 236.514]},
{t: 'z', p: []}]},
{f: '#659900', s: null, p: [{t: 'M', p: [243.377, 219.83]},
{t: 'C', p: [238.531, 220.552, 233.442, 222.055, 233.514, 221.839]},
{t: 'C', p: [235.054, 217.22, 241.415, 213.887, 247, 213.887]},
{t: 'C', p: [251.296, 213.887, 255.084, 215.865, 257.32, 218.875]},
{t: 'C', p: [257.32, 218.875, 252.004, 218.545, 243.377, 219.83]},
{t: 'z', p: []}]},
{f: '#fff', s: null, p: [{t: 'M', p: [255.4, 219.6]},
{t: 'C', p: [255.4, 219.6, 251, 216.4, 251, 218.6]},
{t: 'C', p: [251, 218.6, 254.6, 223, 255.4, 219.6]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [245.4, 227.726]},
{t: 'C', p: [242.901, 227.726, 240.875, 225.7, 240.875, 223.2]},
{t: 'C', p: [240.875, 220.701, 242.901, 218.675, 245.4, 218.675]},
{t: 'C', p: [247.9, 218.675, 249.926, 220.701, 249.926, 223.2]},
{t: 'C', p: [249.926, 225.7, 247.9, 227.726, 245.4, 227.726]},
{t: 'z', p: []}]},
{f: '#cc7226', s: null, p: [{t: 'M', p: [141.4, 214.4]},
{t: 'C', p: [141.4, 214.4, 138.2, 193.2, 140.6, 188.8]},
{t: 'C', p: [140.6, 188.8, 151.4, 178.8, 151, 175.2]},
{t: 'C', p: [151, 175.2, 150.6, 157.2, 149.4, 156.4]},
{t: 'C', p: [148.2, 155.6, 140.6, 149.6, 134.6, 156]},
{t: 'C', p: [134.6, 156, 124.2, 174, 125, 180.4]},
{t: 'L', p: [125, 182.4]},
{t: 'C', p: [125, 182.4, 117.4, 182, 115.8, 184]},
{t: 'C', p: [115.8, 184, 114.6, 189.2, 113.4, 189.6]},
{t: 'C', p: [113.4, 189.6, 110.6, 192, 112.6, 194.8]},
{t: 'C', p: [112.6, 194.8, 110.6, 197.2, 111, 201.2]},
{t: 'L', p: [118.6, 205.2]},
{t: 'C', p: [118.6, 205.2, 120.6, 219.6, 131.4, 224.8]},
{t: 'C', p: [136.236, 227.129, 139.4, 220.4, 141.4, 214.4]},
{t: 'z', p: []}]},
{f: '#fff', s: null, p: [{t: 'M', p: [140.4, 212.56]},
{t: 'C', p: [140.4, 212.56, 137.52, 193.48, 139.68, 189.52]},
{t: 'C', p: [139.68, 189.52, 149.4, 180.52, 149.04, 177.28]},
{t: 'C', p: [149.04, 177.28, 148.68, 161.08, 147.6, 160.36]},
{t: 'C', p: [146.52, 159.64, 139.68, 154.24, 134.28, 160]},
{t: 'C', p: [134.28, 160, 124.92, 176.2, 125.64, 181.96]},
{t: 'L', p: [125.64, 183.76]},
{t: 'C', p: [125.64, 183.76, 118.8, 183.4, 117.36, 185.2]},
{t: 'C', p: [117.36, 185.2, 116.28, 189.88, 115.2, 190.24]},
{t: 'C', p: [115.2, 190.24, 112.68, 192.4, 114.48, 194.92]},
{t: 'C', p: [114.48, 194.92, 112.68, 197.08, 113.04, 200.68]},
{t: 'L', p: [119.88, 204.28]},
{t: 'C', p: [119.88, 204.28, 121.68, 217.24, 131.4, 221.92]},
{t: 'C', p: [135.752, 224.015, 138.6, 217.96, 140.4, 212.56]},
{t: 'z', p: []}]},
{f: '#eb955c', s: null, p: [{t: 'M', p: [148.95, 157.39]},
{t: 'C', p: [147.86, 156.53, 140.37, 150.76, 134.52, 157]},
{t: 'C', p: [134.52, 157, 124.38, 174.55, 125.16, 180.79]},
{t: 'L', p: [125.16, 182.74]},
{t: 'C', p: [125.16, 182.74, 117.75, 182.35, 116.19, 184.3]},
{t: 'C', p: [116.19, 184.3, 115.02, 189.37, 113.85, 189.76]},
{t: 'C', p: [113.85, 189.76, 111.12, 192.1, 113.07, 194.83]},
{t: 'C', p: [113.07, 194.83, 111.12, 197.17, 111.51, 201.07]},
{t: 'L', p: [118.92, 204.97]},
{t: 'C', p: [118.92, 204.97, 120.87, 219.01, 131.4, 224.08]},
{t: 'C', p: [136.114, 226.35, 139.2, 219.79, 141.15, 213.94]},
{t: 'C', p: [141.15, 213.94, 138.03, 193.27, 140.37, 188.98]},
{t: 'C', p: [140.37, 188.98, 150.9, 179.23, 150.51, 175.72]},
{t: 'C', p: [150.51, 175.72, 150.12, 158.17, 148.95, 157.39]},
{t: 'z', p: []}]},
{f: '#f2b892', s: null, p: [{t: 'M', p: [148.5, 158.38]},
{t: 'C', p: [147.52, 157.46, 140.14, 151.92, 134.44, 158]},
{t: 'C', p: [134.44, 158, 124.56, 175.1, 125.32, 181.18]},
{t: 'L', p: [125.32, 183.08]},
{t: 'C', p: [125.32, 183.08, 118.1, 182.7, 116.58, 184.6]},
{t: 'C', p: [116.58, 184.6, 115.44, 189.54, 114.3, 189.92]},
{t: 'C', p: [114.3, 189.92, 111.64, 192.2, 113.54, 194.86]},
{t: 'C', p: [113.54, 194.86, 111.64, 197.14, 112.02, 200.94]},
{t: 'L', p: [119.24, 204.74]},
{t: 'C', p: [119.24, 204.74, 121.14, 218.42, 131.4, 223.36]},
{t: 'C', p: [135.994, 225.572, 139, 219.18, 140.9, 213.48]},
{t: 'C', p: [140.9, 213.48, 137.86, 193.34, 140.14, 189.16]},
{t: 'C', p: [140.14, 189.16, 150.4, 179.66, 150.02, 176.24]},
{t: 'C', p: [150.02, 176.24, 149.64, 159.14, 148.5, 158.38]},
{t: 'z', p: []}]},
{f: '#f8dcc8', s: null, p: [{t: 'M', p: [148.05, 159.37]},
{t: 'C', p: [147.18, 158.39, 139.91, 153.08, 134.36, 159]},
{t: 'C', p: [134.36, 159, 124.74, 175.65, 125.48, 181.57]},
{t: 'L', p: [125.48, 183.42]},
{t: 'C', p: [125.48, 183.42, 118.45, 183.05, 116.97, 184.9]},
{t: 'C', p: [116.97, 184.9, 115.86, 189.71, 114.75, 190.08]},
{t: 'C', p: [114.75, 190.08, 112.16, 192.3, 114.01, 194.89]},
{t: 'C', p: [114.01, 194.89, 112.16, 197.11, 112.53, 200.81]},
{t: 'L', p: [119.56, 204.51]},
{t: 'C', p: [119.56, 204.51, 121.41, 217.83, 131.4, 222.64]},
{t: 'C', p: [135.873, 224.794, 138.8, 218.57, 140.65, 213.02]},
{t: 'C', p: [140.65, 213.02, 137.69, 193.41, 139.91, 189.34]},
{t: 'C', p: [139.91, 189.34, 149.9, 180.09, 149.53, 176.76]},
{t: 'C', p: [149.53, 176.76, 149.16, 160.11, 148.05, 159.37]},
{t: 'z', p: []}]},
{f: '#fff', s: null, p: [{t: 'M', p: [140.4, 212.46]},
{t: 'C', p: [140.4, 212.46, 137.52, 193.48, 139.68, 189.52]},
{t: 'C', p: [139.68, 189.52, 149.4, 180.52, 149.04, 177.28]},
{t: 'C', p: [149.04, 177.28, 148.68, 161.08, 147.6, 160.36]},
{t: 'C', p: [146.84, 159.32, 139.68, 154.24, 134.28, 160]},
{t: 'C', p: [134.28, 160, 124.92, 176.2, 125.64, 181.96]},
{t: 'L', p: [125.64, 183.76]},
{t: 'C', p: [125.64, 183.76, 118.8, 183.4, 117.36, 185.2]},
{t: 'C', p: [117.36, 185.2, 116.28, 189.88, 115.2, 190.24]},
{t: 'C', p: [115.2, 190.24, 112.68, 192.4, 114.48, 194.92]},
{t: 'C', p: [114.48, 194.92, 112.68, 197.08, 113.04, 200.68]},
{t: 'L', p: [119.88, 204.28]},
{t: 'C', p: [119.88, 204.28, 121.68, 217.24, 131.4, 221.92]},
{t: 'C', p: [135.752, 224.015, 138.6, 217.86, 140.4, 212.46]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [137.3, 206.2]},
{t: 'C', p: [137.3, 206.2, 115.7, 196, 114.8, 195.2]},
{t: 'C', p: [114.8, 195.2, 123.9, 203.4, 124.7, 203.4]},
{t: 'C', p: [125.5, 203.4, 137.3, 206.2, 137.3, 206.2]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [120.2, 200]},
{t: 'C', p: [120.2, 200, 138.6, 203.6, 138.6, 208]},
{t: 'C', p: [138.6, 210.912, 138.357, 224.331, 133, 222.8]},
{t: 'C', p: [124.6, 220.4, 128.2, 206, 120.2, 200]},
{t: 'z', p: []}]},
{f: '#99cc32', s: null, p: [{t: 'M', p: [128.6, 203.8]},
{t: 'C', p: [128.6, 203.8, 137.578, 205.274, 138.6, 208]},
{t: 'C', p: [139.2, 209.6, 139.863, 217.908, 134.4, 219]},
{t: 'C', p: [129.848, 219.911, 127.618, 209.69, 128.6, 203.8]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [214.595, 246.349]},
{t: 'C', p: [214.098, 244.607, 215.409, 244.738, 217.2, 244.2]},
{t: 'C', p: [219.2, 243.6, 231.4, 239.8, 232.2, 237.2]},
{t: 'C', p: [233, 234.6, 246.2, 239, 246.2, 239]},
{t: 'C', p: [248, 239.8, 252.4, 242.4, 252.4, 242.4]},
{t: 'C', p: [257.2, 243.6, 263.8, 244, 263.8, 244]},
{t: 'C', p: [266.2, 245, 269.6, 247.8, 269.6, 247.8]},
{t: 'C', p: [284.2, 258, 296.601, 250.8, 296.601, 250.8]},
{t: 'C', p: [316.601, 244.2, 310.601, 227, 310.601, 227]},
{t: 'C', p: [307.601, 218, 310.801, 214.6, 310.801, 214.6]},
{t: 'C', p: [311.001, 210.8, 318.201, 217.2, 318.201, 217.2]},
{t: 'C', p: [320.801, 221.4, 321.601, 226.4, 321.601, 226.4]},
{t: 'C', p: [329.601, 237.6, 326.201, 219.8, 326.201, 219.8]},
{t: 'C', p: [326.401, 218.8, 323.601, 215.2, 323.601, 214]},
{t: 'C', p: [323.601, 212.8, 321.801, 209.4, 321.801, 209.4]},
{t: 'C', p: [318.801, 206, 321.201, 199, 321.201, 199]},
{t: 'C', p: [323.001, 185.2, 320.801, 187, 320.801, 187]},
{t: 'C', p: [319.601, 185.2, 310.401, 195.2, 310.401, 195.2]},
{t: 'C', p: [308.201, 198.6, 302.201, 200.2, 302.201, 200.2]},
{t: 'C', p: [299.401, 202, 296.001, 200.6, 296.001, 200.6]},
{t: 'C', p: [293.401, 200.2, 287.801, 207.2, 287.801, 207.2]},
{t: 'C', p: [290.601, 207, 293.001, 211.4, 295.401, 211.6]},
{t: 'C', p: [297.801, 211.8, 299.601, 209.2, 301.201, 208.6]},
{t: 'C', p: [302.801, 208, 305.601, 213.8, 305.601, 213.8]},
{t: 'C', p: [306.001, 216.4, 300.401, 221.2, 300.401, 221.2]},
{t: 'C', p: [300.001, 225.8, 298.401, 224.2, 298.401, 224.2]},
{t: 'C', p: [295.401, 223.6, 294.201, 227.4, 293.201, 232]},
{t: 'C', p: [292.201, 236.6, 288.001, 237, 288.001, 237]},
{t: 'C', p: [286.401, 244.4, 285.2, 241.4, 285.2, 241.4]},
{t: 'C', p: [285, 235.8, 279, 241.6, 279, 241.6]},
{t: 'C', p: [277.8, 243.6, 273.2, 241.4, 273.2, 241.4]},
{t: 'C', p: [266.4, 239.4, 268.8, 237.4, 268.8, 237.4]},
{t: 'C', p: [270.6, 235.2, 281.8, 237.4, 281.8, 237.4]},
{t: 'C', p: [284, 235.8, 276, 231.8, 276, 231.8]},
{t: 'C', p: [275.4, 230, 276.4, 225.6, 276.4, 225.6]},
{t: 'C', p: [277.6, 222.4, 284.4, 216.8, 284.4, 216.8]},
{t: 'C', p: [293.801, 215.6, 291.001, 214, 291.001, 214]},
{t: 'C', p: [284.801, 208.8, 279, 216.4, 279, 216.4]},
{t: 'C', p: [276.8, 222.6, 259.4, 237.6, 259.4, 237.6]},
{t: 'C', p: [254.6, 241, 257.2, 234.2, 253.2, 237.6]},
{t: 'C', p: [249.2, 241, 228.6, 232, 228.6, 232]},
{t: 'C', p: [217.038, 230.807, 214.306, 246.549, 210.777, 243.429]},
{t: 'C', p: [210.777, 243.429, 216.195, 251.949, 214.595, 246.349]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [409.401, 80]},
{t: 'C', p: [409.401, 80, 383.801, 88, 381.001, 106.8]},
{t: 'C', p: [381.001, 106.8, 378.601, 129.6, 399.001, 147.2]},
{t: 'C', p: [399.001, 147.2, 399.401, 153.6, 401.401, 156.8]},
{t: 'C', p: [401.401, 156.8, 399.801, 161.6, 418.601, 154]},
{t: 'L', p: [445.801, 145.6]},
{t: 'C', p: [445.801, 145.6, 452.201, 143.2, 457.401, 134.4]},
{t: 'C', p: [462.601, 125.6, 477.801, 106.8, 474.201, 81.6]},
{t: 'C', p: [474.201, 81.6, 475.401, 70.4, 469.401, 70]},
{t: 'C', p: [469.401, 70, 461.001, 68.4, 453.801, 76]},
{t: 'C', p: [453.801, 76, 447.001, 79.2, 444.601, 78.8]},
{t: 'L', p: [409.401, 80]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [464.022, 79.01]},
{t: 'C', p: [464.022, 79.01, 466.122, 70.08, 461.282, 74.92]},
{t: 'C', p: [461.282, 74.92, 454.242, 80.64, 446.761, 80.64]},
{t: 'C', p: [446.761, 80.64, 432.241, 82.84, 427.841, 96.04]},
{t: 'C', p: [427.841, 96.04, 423.881, 122.88, 431.801, 128.6]},
{t: 'C', p: [431.801, 128.6, 436.641, 136.08, 443.681, 129.48]},
{t: 'C', p: [450.722, 122.88, 466.222, 92.65, 464.022, 79.01]},
{t: 'z', p: []}]},
{f: '#323232', s: null, p: [{t: 'M', p: [463.648, 79.368]},
{t: 'C', p: [463.648, 79.368, 465.738, 70.624, 460.986, 75.376]},
{t: 'C', p: [460.986, 75.376, 454.074, 80.992, 446.729, 80.992]},
{t: 'C', p: [446.729, 80.992, 432.473, 83.152, 428.153, 96.112]},
{t: 'C', p: [428.153, 96.112, 424.265, 122.464, 432.041, 128.08]},
{t: 'C', p: [432.041, 128.08, 436.793, 135.424, 443.705, 128.944]},
{t: 'C', p: [450.618, 122.464, 465.808, 92.76, 463.648, 79.368]},
{t: 'z', p: []}]},
{f: '#666', s: null, p: [{t: 'M', p: [463.274, 79.726]},
{t: 'C', p: [463.274, 79.726, 465.354, 71.168, 460.69, 75.832]},
{t: 'C', p: [460.69, 75.832, 453.906, 81.344, 446.697, 81.344]},
{t: 'C', p: [446.697, 81.344, 432.705, 83.464, 428.465, 96.184]},
{t: 'C', p: [428.465, 96.184, 424.649, 122.048, 432.281, 127.56]},
{t: 'C', p: [432.281, 127.56, 436.945, 134.768, 443.729, 128.408]},
{t: 'C', p: [450.514, 122.048, 465.394, 92.87, 463.274, 79.726]},
{t: 'z', p: []}]},
{f: '#999', s: null, p: [{t: 'M', p: [462.9, 80.084]},
{t: 'C', p: [462.9, 80.084, 464.97, 71.712, 460.394, 76.288]},
{t: 'C', p: [460.394, 76.288, 453.738, 81.696, 446.665, 81.696]},
{t: 'C', p: [446.665, 81.696, 432.937, 83.776, 428.777, 96.256]},
{t: 'C', p: [428.777, 96.256, 425.033, 121.632, 432.521, 127.04]},
{t: 'C', p: [432.521, 127.04, 437.097, 134.112, 443.753, 127.872]},
{t: 'C', p: [450.41, 121.632, 464.98, 92.98, 462.9, 80.084]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [462.526, 80.442]},
{t: 'C', p: [462.526, 80.442, 464.586, 72.256, 460.098, 76.744]},
{t: 'C', p: [460.098, 76.744, 453.569, 82.048, 446.633, 82.048]},
{t: 'C', p: [446.633, 82.048, 433.169, 84.088, 429.089, 96.328]},
{t: 'C', p: [429.089, 96.328, 425.417, 121.216, 432.761, 126.52]},
{t: 'C', p: [432.761, 126.52, 437.249, 133.456, 443.777, 127.336]},
{t: 'C', p: [450.305, 121.216, 464.566, 93.09, 462.526, 80.442]},
{t: 'z', p: []}]},
{f: '#fff', s: null, p: [{t: 'M', p: [462.151, 80.8]},
{t: 'C', p: [462.151, 80.8, 464.201, 72.8, 459.801, 77.2]},
{t: 'C', p: [459.801, 77.2, 453.401, 82.4, 446.601, 82.4]},
{t: 'C', p: [446.601, 82.4, 433.401, 84.4, 429.401, 96.4]},
{t: 'C', p: [429.401, 96.4, 425.801, 120.8, 433.001, 126]},
{t: 'C', p: [433.001, 126, 437.401, 132.8, 443.801, 126.8]},
{t: 'C', p: [450.201, 120.8, 464.151, 93.2, 462.151, 80.8]},
{t: 'z', p: []}]},
{f: '#992600', s: null, p: [{t: 'M', p: [250.6, 284]},
{t: 'C', p: [250.6, 284, 230.2, 264.8, 222.2, 264]},
{t: 'C', p: [222.2, 264, 187.8, 260, 173, 278]},
{t: 'C', p: [173, 278, 190.6, 257.6, 218.2, 263.2]},
{t: 'C', p: [218.2, 263.2, 196.6, 258.8, 184.2, 262]},
{t: 'C', p: [184.2, 262, 167.4, 262, 157.8, 276]},
{t: 'L', p: [155, 280.8]},
{t: 'C', p: [155, 280.8, 159, 266, 177.4, 260]},
{t: 'C', p: [177.4, 260, 200.2, 255.2, 211, 260]},
{t: 'C', p: [211, 260, 189.4, 253.2, 179.4, 255.2]},
{t: 'C', p: [179.4, 255.2, 149, 252.8, 136.2, 279.2]},
{t: 'C', p: [136.2, 279.2, 140.2, 264.8, 155, 257.6]},
{t: 'C', p: [155, 257.6, 168.6, 248.8, 189, 251.6]},
{t: 'C', p: [189, 251.6, 203.4, 254.8, 208.6, 257.2]},
{t: 'C', p: [213.8, 259.6, 212.6, 256.8, 204.2, 252]},
{t: 'C', p: [204.2, 252, 198.6, 242, 184.6, 242.4]},
{t: 'C', p: [184.6, 242.4, 141.8, 246, 131.4, 258]},
{t: 'C', p: [131.4, 258, 145, 246.8, 155.4, 244]},
{t: 'C', p: [155.4, 244, 177.8, 236, 186.2, 236.8]},
{t: 'C', p: [186.2, 236.8, 211, 237.8, 218.6, 233.8]},
{t: 'C', p: [218.6, 233.8, 207.4, 238.8, 210.6, 242]},
{t: 'C', p: [213.8, 245.2, 220.6, 252.8, 220.6, 254]},
{t: 'C', p: [220.6, 255.2, 244.8, 277.3, 248.4, 281.7]},
{t: 'L', p: [250.6, 284]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [389, 478]},
{t: 'C', p: [389, 478, 373.5, 441.5, 361, 432]},
{t: 'C', p: [361, 432, 387, 448, 390.5, 466]},
{t: 'C', p: [390.5, 466, 390.5, 476, 389, 478]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [436, 485.5]},
{t: 'C', p: [436, 485.5, 409.5, 430.5, 391, 406.5]},
{t: 'C', p: [391, 406.5, 434.5, 444, 439.5, 470.5]},
{t: 'L', p: [440, 476]},
{t: 'L', p: [437, 473.5]},
{t: 'C', p: [437, 473.5, 436.5, 482.5, 436, 485.5]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [492.5, 437]},
{t: 'C', p: [492.5, 437, 430, 377.5, 428.5, 375]},
{t: 'C', p: [428.5, 375, 489, 441, 492, 448.5]},
{t: 'C', p: [492, 448.5, 490, 439.5, 492.5, 437]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [304, 480.5]},
{t: 'C', p: [304, 480.5, 323.5, 428.5, 342.5, 451]},
{t: 'C', p: [342.5, 451, 357.5, 461, 357, 464]},
{t: 'C', p: [357, 464, 353, 457.5, 335, 458]},
{t: 'C', p: [335, 458, 316, 455, 304, 480.5]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [494.5, 353]},
{t: 'C', p: [494.5, 353, 449.5, 324.5, 442, 323]},
{t: 'C', p: [430.193, 320.639, 491.5, 352, 496.5, 362.5]},
{t: 'C', p: [496.5, 362.5, 498.5, 360, 494.5, 353]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [343.801, 459.601]},
{t: 'C', p: [343.801, 459.601, 364.201, 457.601, 371.001, 450.801]},
{t: 'L', p: [375.401, 454.401]},
{t: 'L', p: [393.001, 416.001]},
{t: 'L', p: [396.601, 421.201]},
{t: 'C', p: [396.601, 421.201, 411.001, 406.401, 410.201, 398.401]},
{t: 'C', p: [409.401, 390.401, 423.001, 404.401, 423.001, 404.401]},
{t: 'C', p: [423.001, 404.401, 422.201, 392.801, 429.401, 399.601]},
{t: 'C', p: [429.401, 399.601, 427.001, 384.001, 435.401, 392.001]},
{t: 'C', p: [435.401, 392.001, 424.864, 361.844, 447.401, 387.601]},
{t: 'C', p: [453.001, 394.001, 448.601, 387.201, 448.601, 387.201]},
{t: 'C', p: [448.601, 387.201, 422.601, 339.201, 444.201, 353.601]},
{t: 'C', p: [444.201, 353.601, 446.201, 330.801, 445.001, 326.401]},
{t: 'C', p: [443.801, 322.001, 441.801, 299.6, 437.001, 294.4]},
{t: 'C', p: [432.201, 289.2, 437.401, 287.6, 443.001, 292.8]},
{t: 'C', p: [443.001, 292.8, 431.801, 268.8, 445.001, 280.8]},
{t: 'C', p: [445.001, 280.8, 441.401, 265.6, 437.001, 262.8]},
{t: 'C', p: [437.001, 262.8, 431.401, 245.6, 446.601, 256.4]},
{t: 'C', p: [446.601, 256.4, 442.201, 244, 439.001, 240.8]},
{t: 'C', p: [439.001, 240.8, 427.401, 213.2, 434.601, 218]},
{t: 'L', p: [439.001, 221.6]},
{t: 'C', p: [439.001, 221.6, 432.201, 207.6, 438.601, 212]},
{t: 'C', p: [445.001, 216.4, 445.001, 216, 445.001, 216]},
{t: 'C', p: [445.001, 216, 423.801, 182.8, 444.201, 200.4]},
{t: 'C', p: [444.201, 200.4, 436.042, 186.482, 432.601, 179.6]},
{t: 'C', p: [432.601, 179.6, 413.801, 159.2, 428.201, 165.6]},
{t: 'L', p: [433.001, 167.2]},
{t: 'C', p: [433.001, 167.2, 424.201, 157.2, 416.201, 155.6]},
{t: 'C', p: [408.201, 154, 418.601, 147.6, 425.001, 149.6]},
{t: 'C', p: [431.401, 151.6, 447.001, 159.2, 447.001, 159.2]},
{t: 'C', p: [447.001, 159.2, 459.801, 178, 463.801, 178.4]},
{t: 'C', p: [463.801, 178.4, 443.801, 170.8, 449.801, 178.8]},
{t: 'C', p: [449.801, 178.8, 464.201, 192.8, 457.001, 192.4]},
{t: 'C', p: [457.001, 192.4, 451.001, 199.6, 455.801, 208.4]},
{t: 'C', p: [455.801, 208.4, 437.342, 190.009, 452.201, 215.6]},
{t: 'L', p: [459.001, 232]},
{t: 'C', p: [459.001, 232, 434.601, 207.2, 445.801, 229.2]},
{t: 'C', p: [445.801, 229.2, 463.001, 252.8, 465.001, 253.2]},
{t: 'C', p: [467.001, 253.6, 471.401, 262.4, 471.401, 262.4]},
{t: 'L', p: [467.001, 260.4]},
{t: 'L', p: [472.201, 269.2]},
{t: 'C', p: [472.201, 269.2, 461.001, 257.2, 467.001, 270.4]},
{t: 'L', p: [472.601, 284.8]},
{t: 'C', p: [472.601, 284.8, 452.201, 262.8, 465.801, 292.4]},
{t: 'C', p: [465.801, 292.4, 449.401, 287.2, 458.201, 304.4]},
{t: 'C', p: [458.201, 304.4, 456.601, 320.401, 457.001, 325.601]},
{t: 'C', p: [457.401, 330.801, 458.601, 359.201, 454.201, 367.201]},
{t: 'C', p: [449.801, 375.201, 460.201, 394.401, 462.201, 398.401]},
{t: 'C', p: [464.201, 402.401, 467.801, 413.201, 459.001, 404.001]},
{t: 'C', p: [450.201, 394.801, 454.601, 400.401, 456.601, 409.201]},
{t: 'C', p: [458.601, 418.001, 464.601, 433.601, 463.801, 439.201]},
{t: 'C', p: [463.801, 439.201, 462.601, 440.401, 459.401, 436.801]},
{t: 'C', p: [459.401, 436.801, 444.601, 414.001, 446.201, 428.401]},
{t: 'C', p: [446.201, 428.401, 445.001, 436.401, 441.801, 445.201]},
{t: 'C', p: [441.801, 445.201, 438.601, 456.001, 438.601, 447.201]},
{t: 'C', p: [438.601, 447.201, 435.401, 430.401, 432.601, 438.001]},
{t: 'C', p: [429.801, 445.601, 426.201, 451.601, 423.401, 454.001]},
{t: 'C', p: [420.601, 456.401, 415.401, 433.601, 414.201, 444.001]},
{t: 'C', p: [414.201, 444.001, 402.201, 431.601, 397.401, 448.001]},
{t: 'L', p: [385.801, 464.401]},
{t: 'C', p: [385.801, 464.401, 385.401, 452.001, 384.201, 458.001]},
{t: 'C', p: [384.201, 458.001, 354.201, 464.001, 343.801, 459.601]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [309.401, 102.8]},
{t: 'C', p: [309.401, 102.8, 297.801, 94.8, 293.801, 95.2]},
{t: 'C', p: [289.801, 95.6, 321.401, 86.4, 362.601, 114]},
{t: 'C', p: [362.601, 114, 367.401, 116.8, 371.001, 116.4]},
{t: 'C', p: [371.001, 116.4, 374.201, 118.8, 371.401, 122.4]},
{t: 'C', p: [371.401, 122.4, 362.601, 132, 373.801, 143.2]},
{t: 'C', p: [373.801, 143.2, 392.201, 150, 386.601, 141.2]},
{t: 'C', p: [386.601, 141.2, 397.401, 145.2, 399.801, 149.2]},
{t: 'C', p: [402.201, 153.2, 401.001, 149.2, 401.001, 149.2]},
{t: 'C', p: [401.001, 149.2, 394.601, 142, 388.601, 136.8]},
{t: 'C', p: [388.601, 136.8, 383.401, 134.8, 380.601, 126.4]},
{t: 'C', p: [377.801, 118, 375.401, 108, 379.801, 104.8]},
{t: 'C', p: [379.801, 104.8, 375.801, 109.2, 376.601, 105.2]},
{t: 'C', p: [377.401, 101.2, 381.001, 97.6, 382.601, 97.2]},
{t: 'C', p: [384.201, 96.8, 400.601, 81, 407.401, 80.6]},
{t: 'C', p: [407.401, 80.6, 398.201, 82, 395.201, 81]},
{t: 'C', p: [392.201, 80, 365.601, 68.6, 359.601, 67.4]},
{t: 'C', p: [359.601, 67.4, 342.801, 60.8, 354.801, 62.8]},
{t: 'C', p: [354.801, 62.8, 390.601, 66.6, 408.801, 79.8]},
{t: 'C', p: [408.801, 79.8, 401.601, 71.4, 383.201, 64.4]},
{t: 'C', p: [383.201, 64.4, 361.001, 51.8, 325.801, 56.8]},
{t: 'C', p: [325.801, 56.8, 308.001, 60, 300.201, 61.8]},
{t: 'C', p: [300.201, 61.8, 297.601, 61.2, 297.001, 60.8]},
{t: 'C', p: [296.401, 60.4, 284.6, 51.4, 257, 58.4]},
{t: 'C', p: [257, 58.4, 240, 63, 231.4, 67.8]},
{t: 'C', p: [231.4, 67.8, 216.2, 69, 212.6, 72.2]},
{t: 'C', p: [212.6, 72.2, 194, 86.8, 192, 87.6]},
{t: 'C', p: [190, 88.4, 178.6, 96, 177.8, 96.4]},
{t: 'C', p: [177.8, 96.4, 202.4, 89.8, 204.8, 87.4]},
{t: 'C', p: [207.2, 85, 224.6, 82.4, 227, 83.8]},
{t: 'C', p: [229.4, 85.2, 237.8, 84.6, 228.2, 85.2]},
{t: 'C', p: [228.2, 85.2, 303.801, 100, 304.601, 102]},
{t: 'C', p: [305.401, 104, 309.401, 102.8, 309.401, 102.8]},
{t: 'z', p: []}]},
{f: '#cc7226', s: null, p: [{t: 'M', p: [380.801, 93.6]},
{t: 'C', p: [380.801, 93.6, 370.601, 86.2, 368.601, 86.2]},
{t: 'C', p: [366.601, 86.2, 354.201, 76, 350.001, 76.4]},
{t: 'C', p: [345.801, 76.8, 333.601, 66.8, 306.201, 75]},
{t: 'C', p: [306.201, 75, 305.601, 73, 309.201, 72.2]},
{t: 'C', p: [309.201, 72.2, 315.601, 70, 316.001, 69.4]},
{t: 'C', p: [316.001, 69.4, 336.201, 65.2, 343.401, 68.8]},
{t: 'C', p: [343.401, 68.8, 352.601, 71.4, 358.801, 77.6]},
{t: 'C', p: [358.801, 77.6, 370.001, 80.8, 373.201, 79.8]},
{t: 'C', p: [373.201, 79.8, 382.001, 82, 382.401, 83.8]},
{t: 'C', p: [382.401, 83.8, 388.201, 86.8, 386.401, 89.4]},
{t: 'C', p: [386.401, 89.4, 386.801, 91, 380.801, 93.6]},
{t: 'z', p: []}]},
{f: '#cc7226', s: null, p: [{t: 'M', p: [368.33, 91.491]},
{t: 'C', p: [369.137, 92.123, 370.156, 92.221, 370.761, 93.03]},
{t: 'C', p: [370.995, 93.344, 370.706, 93.67, 370.391, 93.767]},
{t: 'C', p: [369.348, 94.084, 368.292, 93.514, 367.15, 94.102]},
{t: 'C', p: [366.748, 94.309, 366.106, 94.127, 365.553, 93.978]},
{t: 'C', p: [363.921, 93.537, 362.092, 93.512, 360.401, 94.2]},
{t: 'C', p: [358.416, 93.071, 356.056, 93.655, 353.975, 92.654]},
{t: 'C', p: [353.917, 92.627, 353.695, 92.973, 353.621, 92.946]},
{t: 'C', p: [350.575, 91.801, 346.832, 92.084, 344.401, 89.8]},
{t: 'C', p: [341.973, 89.388, 339.616, 88.926, 337.188, 88.246]},
{t: 'C', p: [335.37, 87.737, 333.961, 86.748, 332.341, 85.916]},
{t: 'C', p: [330.964, 85.208, 329.507, 84.686, 327.973, 84.314]},
{t: 'C', p: [326.11, 83.862, 324.279, 83.974, 322.386, 83.454]},
{t: 'C', p: [322.293, 83.429, 322.101, 83.773, 322.019, 83.746]},
{t: 'C', p: [321.695, 83.638, 321.405, 83.055, 321.234, 83.108]},
{t: 'C', p: [319.553, 83.63, 318.065, 82.658, 316.401, 83]},
{t: 'C', p: [315.223, 81.776, 313.495, 82.021, 311.949, 81.579]},
{t: 'C', p: [308.985, 80.731, 305.831, 82.001, 302.801, 81]},
{t: 'C', p: [306.914, 79.158, 311.601, 80.39, 315.663, 78.321]},
{t: 'C', p: [317.991, 77.135, 320.653, 78.237, 323.223, 77.477]},
{t: 'C', p: [323.71, 77.333, 324.401, 77.131, 324.801, 77.8]},
{t: 'C', p: [324.935, 77.665, 325.117, 77.426, 325.175, 77.454]},
{t: 'C', p: [327.625, 78.611, 329.94, 79.885, 332.422, 80.951]},
{t: 'C', p: [332.763, 81.097, 333.295, 80.865, 333.547, 81.067]},
{t: 'C', p: [335.067, 82.283, 337.01, 82.18, 338.401, 83.4]},
{t: 'C', p: [340.099, 82.898, 341.892, 83.278, 343.621, 82.654]},
{t: 'C', p: [343.698, 82.627, 343.932, 82.968, 343.965, 82.946]},
{t: 'C', p: [345.095, 82.198, 346.25, 82.469, 347.142, 82.773]},
{t: 'C', p: [347.48, 82.888, 348.143, 83.135, 348.448, 83.209]},
{t: 'C', p: [349.574, 83.485, 350.43, 83.965, 351.609, 84.148]},
{t: 'C', p: [351.723, 84.166, 351.908, 83.826, 351.98, 83.854]},
{t: 'C', p: [353.103, 84.292, 354.145, 84.236, 354.801, 85.4]},
{t: 'C', p: [354.936, 85.265, 355.101, 85.027, 355.183, 85.054]},
{t: 'C', p: [356.21, 85.392, 356.859, 86.147, 357.96, 86.388]},
{t: 'C', p: [358.445, 86.494, 359.057, 87.12, 359.633, 87.296]},
{t: 'C', p: [362.025, 88.027, 363.868, 89.556, 366.062, 90.451]},
{t: 'C', p: [366.821, 90.761, 367.697, 90.995, 368.33, 91.491]},
{t: 'z', p: []}]},
{f: '#cc7226', s: null, p: [{t: 'M', p: [291.696, 77.261]},
{t: 'C', p: [289.178, 75.536, 286.81, 74.43, 284.368, 72.644]},
{t: 'C', p: [284.187, 72.511, 283.827, 72.681, 283.625, 72.559]},
{t: 'C', p: [282.618, 71.95, 281.73, 71.369, 280.748, 70.673]},
{t: 'C', p: [280.209, 70.291, 279.388, 70.302, 278.88, 70.044]},
{t: 'C', p: [276.336, 68.752, 273.707, 68.194, 271.2, 67]},
{t: 'C', p: [271.882, 66.362, 273.004, 66.606, 273.6, 65.8]},
{t: 'C', p: [273.795, 66.08, 274.033, 66.364, 274.386, 66.173]},
{t: 'C', p: [276.064, 65.269, 277.914, 65.116, 279.59, 65.206]},
{t: 'C', p: [281.294, 65.298, 283.014, 65.603, 284.789, 65.875]},
{t: 'C', p: [285.096, 65.922, 285.295, 66.445, 285.618, 66.542]},
{t: 'C', p: [287.846, 67.205, 290.235, 66.68, 292.354, 67.518]},
{t: 'C', p: [293.945, 68.147, 295.515, 68.97, 296.754, 70.245]},
{t: 'C', p: [297.006, 70.505, 296.681, 70.806, 296.401, 71]},
{t: 'C', p: [296.789, 70.891, 297.062, 71.097, 297.173, 71.41]},
{t: 'C', p: [297.257, 71.649, 297.257, 71.951, 297.173, 72.19]},
{t: 'C', p: [297.061, 72.502, 296.782, 72.603, 296.408, 72.654]},
{t: 'C', p: [295.001, 72.844, 296.773, 71.464, 296.073, 71.912]},
{t: 'C', p: [294.8, 72.726, 295.546, 74.132, 294.801, 75.4]},
{t: 'C', p: [294.521, 75.206, 294.291, 74.988, 294.401, 74.6]},
{t: 'C', p: [294.635, 75.122, 294.033, 75.412, 293.865, 75.728]},
{t: 'C', p: [293.48, 76.453, 292.581, 77.868, 291.696, 77.261]},
{t: 'z', p: []}]},
{f: '#cc7226', s: null, p: [{t: 'M', p: [259.198, 84.609]},
{t: 'C', p: [256.044, 83.815, 252.994, 83.93, 249.978, 82.654]},
{t: 'C', p: [249.911, 82.626, 249.688, 82.973, 249.624, 82.946]},
{t: 'C', p: [248.258, 82.352, 247.34, 81.386, 246.264, 80.34]},
{t: 'C', p: [245.351, 79.452, 243.693, 79.839, 242.419, 79.352]},
{t: 'C', p: [242.095, 79.228, 241.892, 78.716, 241.591, 78.677]},
{t: 'C', p: [240.372, 78.52, 239.445, 77.571, 238.4, 77]},
{t: 'C', p: [240.736, 76.205, 243.147, 76.236, 245.609, 75.852]},
{t: 'C', p: [245.722, 75.834, 245.867, 76.155, 246, 76.155]},
{t: 'C', p: [246.136, 76.155, 246.266, 75.934, 246.4, 75.8]},
{t: 'C', p: [246.595, 76.08, 246.897, 76.406, 247.154, 76.152]},
{t: 'C', p: [247.702, 75.612, 248.258, 75.802, 248.798, 75.842]},
{t: 'C', p: [248.942, 75.852, 249.067, 76.155, 249.2, 76.155]},
{t: 'C', p: [249.336, 76.155, 249.467, 75.844, 249.6, 75.844]},
{t: 'C', p: [249.736, 75.845, 249.867, 76.155, 250, 76.155]},
{t: 'C', p: [250.136, 76.155, 250.266, 75.934, 250.4, 75.8]},
{t: 'C', p: [251.092, 76.582, 251.977, 76.028, 252.799, 76.207]},
{t: 'C', p: [253.837, 76.434, 254.104, 77.582, 255.178, 77.88]},
{t: 'C', p: [259.893, 79.184, 264.03, 81.329, 268.393, 83.416]},
{t: 'C', p: [268.7, 83.563, 268.91, 83.811, 268.8, 84.2]},
{t: 'C', p: [269.067, 84.2, 269.38, 84.112, 269.57, 84.244]},
{t: 'C', p: [270.628, 84.976, 271.669, 85.524, 272.366, 86.622]},
{t: 'C', p: [272.582, 86.961, 272.253, 87.368, 272.02, 87.316]},
{t: 'C', p: [267.591, 86.321, 263.585, 85.713, 259.198, 84.609]},
{t: 'z', p: []}]},
{f: '#cc7226', s: null, p: [{t: 'M', p: [245.338, 128.821]},
{t: 'C', p: [243.746, 127.602, 243.162, 125.571, 242.034, 123.779]},
{t: 'C', p: [241.82, 123.439, 242.094, 123.125, 242.411, 123.036]},
{t: 'C', p: [242.971, 122.877, 243.514, 123.355, 243.923, 123.557]},
{t: 'C', p: [245.668, 124.419, 247.203, 125.661, 249.2, 125.8]},
{t: 'C', p: [251.19, 128.034, 255.45, 128.419, 255.457, 131.8]},
{t: 'C', p: [255.458, 132.659, 254.03, 131.741, 253.6, 132.6]},
{t: 'C', p: [251.149, 131.597, 248.76, 131.7, 246.38, 130.233]},
{t: 'C', p: [245.763, 129.852, 246.093, 129.399, 245.338, 128.821]},
{t: 'z', p: []}]},
{f: '#cc7226', s: null, p: [{t: 'M', p: [217.8, 76.244]},
{t: 'C', p: [217.935, 76.245, 224.966, 76.478, 224.949, 76.592]},
{t: 'C', p: [224.904, 76.901, 217.174, 77.95, 216.81, 77.78]},
{t: 'C', p: [216.646, 77.704, 209.134, 80.134, 209, 80]},
{t: 'C', p: [209.268, 79.865, 217.534, 76.244, 217.8, 76.244]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [233.2, 86]},
{t: 'C', p: [233.2, 86, 218.4, 87.8, 214, 89]},
{t: 'C', p: [209.6, 90.2, 191, 97.8, 188, 99.8]},
{t: 'C', p: [188, 99.8, 174.6, 105.2, 157.6, 125.2]},
{t: 'C', p: [157.6, 125.2, 165.2, 121.8, 167.4, 119]},
{t: 'C', p: [167.4, 119, 181, 106.4, 180.8, 109]},
{t: 'C', p: [180.8, 109, 193, 100.4, 192.4, 102.6]},
{t: 'C', p: [192.4, 102.6, 216.8, 91.4, 214.8, 94.6]},
{t: 'C', p: [214.8, 94.6, 236.4, 90, 235.4, 92]},
{t: 'C', p: [235.4, 92, 254.2, 96.4, 251.4, 96.6]},
{t: 'C', p: [251.4, 96.6, 245.6, 97.8, 252, 101.4]},
{t: 'C', p: [252, 101.4, 248.6, 105.8, 243.2, 101.8]},
{t: 'C', p: [237.8, 97.8, 240.8, 100, 235.8, 101]},
{t: 'C', p: [235.8, 101, 233.2, 101.8, 228.6, 97.8]},
{t: 'C', p: [228.6, 97.8, 223, 93.2, 214.2, 96.8]},
{t: 'C', p: [214.2, 96.8, 183.6, 109.4, 181.6, 110]},
{t: 'C', p: [181.6, 110, 178, 112.8, 175.6, 116.4]},
{t: 'C', p: [175.6, 116.4, 169.8, 120.8, 166.8, 122.2]},
{t: 'C', p: [166.8, 122.2, 154, 133.8, 152.8, 135.2]},
{t: 'C', p: [152.8, 135.2, 149.4, 140.4, 148.6, 140.8]},
{t: 'C', p: [148.6, 140.8, 155, 137, 157, 135]},
{t: 'C', p: [157, 135, 171, 125, 176.4, 124.2]},
{t: 'C', p: [176.4, 124.2, 180.8, 121.2, 181.6, 119.8]},
{t: 'C', p: [181.6, 119.8, 196, 110.6, 200.2, 110.6]},
{t: 'C', p: [200.2, 110.6, 209.4, 115.8, 211.8, 108.8]},
{t: 'C', p: [211.8, 108.8, 217.6, 107, 223.2, 108.2]},
{t: 'C', p: [223.2, 108.2, 226.4, 105.6, 225.6, 103.4]},
{t: 'C', p: [225.6, 103.4, 227.2, 101.6, 228.2, 105.4]},
{t: 'C', p: [228.2, 105.4, 231.6, 109, 236.4, 107]},
{t: 'C', p: [236.4, 107, 240.4, 106.8, 238.4, 109.2]},
{t: 'C', p: [238.4, 109.2, 234, 113, 222.2, 113.2]},
{t: 'C', p: [222.2, 113.2, 209.8, 113.8, 193.4, 121.4]},
{t: 'C', p: [193.4, 121.4, 163.6, 131.8, 154.4, 142.2]},
{t: 'C', p: [154.4, 142.2, 148, 151, 142.6, 152.2]},
{t: 'C', p: [142.6, 152.2, 136.8, 153, 130.8, 160.4]},
{t: 'C', p: [130.8, 160.4, 140.6, 154.6, 149.6, 154.6]},
{t: 'C', p: [149.6, 154.6, 153.6, 152.2, 149.8, 155.8]},
{t: 'C', p: [149.8, 155.8, 146.2, 163.4, 147.8, 168.8]},
{t: 'C', p: [147.8, 168.8, 147.2, 174, 146.4, 175.6]},
{t: 'C', p: [146.4, 175.6, 138.6, 188.4, 138.6, 190.8]},
{t: 'C', p: [138.6, 193.2, 139.8, 203, 140.2, 203.6]},
{t: 'C', p: [140.6, 204.2, 139.2, 202, 143, 204.4]},
{t: 'C', p: [146.8, 206.8, 149.6, 208.4, 150.4, 211.2]},
{t: 'C', p: [151.2, 214, 148.4, 205.8, 148.2, 204]},
{t: 'C', p: [148, 202.2, 143.8, 195, 144.6, 192.6]},
{t: 'C', p: [144.6, 192.6, 145.6, 193.6, 146.4, 195]},
{t: 'C', p: [146.4, 195, 145.8, 194.4, 146.4, 190.8]},
{t: 'C', p: [146.4, 190.8, 147.2, 185.6, 148.6, 182.4]},
{t: 'C', p: [150, 179.2, 152, 175.4, 152.4, 174.6]},
{t: 'C', p: [152.8, 173.8, 152.8, 168, 154.2, 170.6]},
{t: 'L', p: [157.6, 173.2]},
{t: 'C', p: [157.6, 173.2, 154.8, 170.6, 157, 168.4]},
{t: 'C', p: [157, 168.4, 156, 162.8, 157.8, 160.2]},
{t: 'C', p: [157.8, 160.2, 164.8, 151.8, 166.4, 150.8]},
{t: 'C', p: [168, 149.8, 166.6, 150.2, 166.6, 150.2]},
{t: 'C', p: [166.6, 150.2, 172.6, 146, 166.8, 147.6]},
{t: 'C', p: [166.8, 147.6, 162.8, 149.2, 159.8, 149.2]},
{t: 'C', p: [159.8, 149.2, 152.2, 151.2, 156.2, 147]},
{t: 'C', p: [160.2, 142.8, 170.2, 137.4, 174, 137.6]},
{t: 'L', p: [174.8, 139.2]},
{t: 'L', p: [186, 136.8]},
{t: 'L', p: [184.8, 137.6]},
{t: 'C', p: [184.8, 137.6, 184.6, 137.4, 188.8, 137]},
{t: 'C', p: [193, 136.6, 198.8, 138, 200.2, 136.2]},
{t: 'C', p: [201.6, 134.4, 205, 133.4, 204.6, 134.8]},
{t: 'C', p: [204.2, 136.2, 204, 138.2, 204, 138.2]},
{t: 'C', p: [204, 138.2, 209, 132.4, 208.4, 134.6]},
{t: 'C', p: [207.8, 136.8, 199.6, 142, 198.2, 148.2]},
{t: 'L', p: [208.6, 140]},
{t: 'L', p: [212.2, 137]},
{t: 'C', p: [212.2, 137, 215.8, 139.2, 216, 137.6]},
{t: 'C', p: [216.2, 136, 220.8, 130.2, 222, 130.4]},
{t: 'C', p: [223.2, 130.6, 225.2, 127.8, 225, 130.4]},
{t: 'C', p: [224.8, 133, 232.4, 138.4, 232.4, 138.4]},
{t: 'C', p: [232.4, 138.4, 235.6, 136.6, 237, 138]},
{t: 'C', p: [238.4, 139.4, 242.6, 118.2, 242.6, 118.2]},
{t: 'L', p: [267.6, 107.6]},
{t: 'L', p: [311.201, 104.2]},
{t: 'L', p: [294.201, 97.4]},
{t: 'L', p: [233.2, 86]},
{t: 'z', p: []}]},
{f: null, s: {c: '#4c0000', w: 2},
p: [{t: 'M', p: [251.4, 285]},
{t: 'C', p: [251.4, 285, 236.4, 268.2, 228, 265.6]},
{t: 'C', p: [228, 265.6, 214.6, 258.8, 190, 266.6]}]},
{f: null, s: {c: '#4c0000', w: 2},
p: [{t: 'M', p: [224.8, 264.2]},
{t: 'C', p: [224.8, 264.2, 199.6, 256.2, 184.2, 260.4]},
{t: 'C', p: [184.2, 260.4, 165.8, 262.4, 157.4, 276.2]}]},
{f: null, s: {c: '#4c0000', w: 2},
p: [{t: 'M', p: [221.2, 263]},
{t: 'C', p: [221.2, 263, 204.2, 255.8, 189.4, 253.6]},
{t: 'C', p: [189.4, 253.6, 172.8, 251, 156.2, 258.2]},
{t: 'C', p: [156.2, 258.2, 144, 264.2, 138.6, 274.4]}]},
{f: null, s: {c: '#4c0000', w: 2},
p: [{t: 'M', p: [222.2, 263.4]},
{t: 'C', p: [222.2, 263.4, 206.8, 252.4, 205.8, 251]},
{t: 'C', p: [205.8, 251, 198.8, 240, 185.8, 239.6]},
{t: 'C', p: [185.8, 239.6, 164.4, 240.4, 147.2, 248.4]}]},
{f: '#000', s: null, p: [{t: 'M', p: [220.895, 254.407]},
{t: 'C', p: [222.437, 255.87, 249.4, 284.8, 249.4, 284.8]},
{t: 'C', p: [284.6, 321.401, 256.6, 287.2, 256.6, 287.2]},
{t: 'C', p: [249, 282.4, 239.8, 263.6, 239.8, 263.6]},
{t: 'C', p: [238.6, 260.8, 253.8, 270.8, 253.8, 270.8]},
{t: 'C', p: [257.8, 271.6, 271.4, 290.8, 271.4, 290.8]},
{t: 'C', p: [264.6, 288.4, 269.4, 295.6, 269.4, 295.6]},
{t: 'C', p: [272.2, 297.6, 292.601, 313.201, 292.601, 313.201]},
{t: 'C', p: [296.201, 317.201, 300.201, 318.801, 300.201, 318.801]},
{t: 'C', p: [314.201, 313.601, 307.801, 326.801, 307.801, 326.801]},
{t: 'C', p: [310.201, 333.601, 315.801, 322.001, 315.801, 322.001]},
{t: 'C', p: [327.001, 305.2, 310.601, 307.601, 310.601, 307.601]},
{t: 'C', p: [280.6, 310.401, 273.8, 294.4, 273.8, 294.4]},
{t: 'C', p: [271.4, 292, 280.2, 294.4, 280.2, 294.4]},
{t: 'C', p: [288.601, 296.4, 273, 282, 273, 282]},
{t: 'C', p: [275.4, 282, 284.6, 288.8, 284.6, 288.8]},
{t: 'C', p: [295.001, 298, 297.001, 296, 297.001, 296]},
{t: 'C', p: [315.001, 287.2, 325.401, 294.8, 325.401, 294.8]},
{t: 'C', p: [327.401, 296.4, 321.801, 303.2, 323.401, 308.401]},
{t: 'C', p: [325.001, 313.601, 329.801, 326.001, 329.801, 326.001]},
{t: 'C', p: [327.401, 327.601, 327.801, 338.401, 327.801, 338.401]},
{t: 'C', p: [344.601, 361.601, 335.001, 359.601, 335.001, 359.601]},
{t: 'C', p: [319.401, 359.201, 334.201, 366.801, 334.201, 366.801]},
{t: 'C', p: [337.401, 368.801, 346.201, 376.001, 346.201, 376.001]},
{t: 'C', p: [343.401, 374.801, 341.801, 380.001, 341.801, 380.001]},
{t: 'C', p: [346.601, 384.001, 343.801, 388.801, 343.801, 388.801]},
{t: 'C', p: [337.801, 390.001, 336.601, 394.001, 336.601, 394.001]},
{t: 'C', p: [343.401, 402.001, 333.401, 402.401, 333.401, 402.401]},
{t: 'C', p: [337.001, 406.801, 332.201, 418.801, 332.201, 418.801]},
{t: 'C', p: [327.401, 418.801, 321.001, 424.401, 321.001, 424.401]},
{t: 'C', p: [323.401, 429.201, 313.001, 434.801, 313.001, 434.801]},
{t: 'C', p: [304.601, 436.401, 307.401, 443.201, 307.401, 443.201]},
{t: 'C', p: [299.401, 449.201, 297.001, 465.201, 297.001, 465.201]},
{t: 'C', p: [296.201, 475.601, 293.801, 478.801, 299.001, 476.801]},
{t: 'C', p: [304.201, 474.801, 303.401, 462.401, 303.401, 462.401]},
{t: 'C', p: [298.601, 446.801, 341.401, 430.801, 341.401, 430.801]},
{t: 'C', p: [345.401, 429.201, 346.201, 424.001, 346.201, 424.001]},
{t: 'C', p: [348.201, 424.401, 357.001, 432.001, 357.001, 432.001]},
{t: 'C', p: [364.601, 443.201, 365.001, 434.001, 365.001, 434.001]},
{t: 'C', p: [366.201, 430.401, 364.601, 424.401, 364.601, 424.401]},
{t: 'C', p: [370.601, 402.801, 356.601, 396.401, 356.601, 396.401]},
{t: 'C', p: [346.601, 362.801, 360.601, 371.201, 360.601, 371.201]},
{t: 'C', p: [363.401, 376.801, 374.201, 382.001, 374.201, 382.001]},
{t: 'L', p: [377.801, 379.601]},
{t: 'C', p: [376.201, 374.801, 384.601, 368.801, 384.601, 368.801]},
{t: 'C', p: [387.401, 375.201, 393.401, 367.201, 393.401, 367.201]},
{t: 'C', p: [397.001, 342.801, 409.401, 357.201, 409.401, 357.201]},
{t: 'C', p: [413.401, 358.401, 414.601, 351.601, 414.601, 351.601]},
{t: 'C', p: [418.201, 341.201, 414.601, 327.601, 414.601, 327.601]},
{t: 'C', p: [418.201, 327.201, 427.801, 333.201, 427.801, 333.201]},
{t: 'C', p: [430.601, 329.601, 421.401, 312.801, 425.401, 315.201]},
{t: 'C', p: [429.401, 317.601, 433.801, 319.201, 433.801, 319.201]},
{t: 'C', p: [434.601, 317.201, 424.601, 304.801, 424.601, 304.801]},
{t: 'C', p: [420.201, 302, 415.001, 281.6, 415.001, 281.6]},
{t: 'C', p: [422.201, 285.2, 412.201, 270, 412.201, 270]},
{t: 'C', p: [412.201, 266.8, 418.201, 255.6, 418.201, 255.6]},
{t: 'C', p: [417.401, 248.8, 418.201, 249.2, 418.201, 249.2]},
{t: 'C', p: [421.001, 250.4, 429.001, 252, 422.201, 245.6]},
{t: 'C', p: [415.401, 239.2, 423.001, 234.4, 423.001, 234.4]},
{t: 'C', p: [427.401, 231.6, 413.801, 232, 413.801, 232]},
{t: 'C', p: [408.601, 227.6, 409.001, 223.6, 409.001, 223.6]},
{t: 'C', p: [417.001, 225.6, 402.601, 211.2, 400.201, 207.6]},
{t: 'C', p: [397.801, 204, 407.401, 198.8, 407.401, 198.8]},
{t: 'C', p: [420.601, 195.2, 409.001, 192, 409.001, 192]},
{t: 'C', p: [389.401, 192.4, 400.201, 181.6, 400.201, 181.6]},
{t: 'C', p: [406.201, 182, 404.601, 179.6, 404.601, 179.6]},
{t: 'C', p: [399.401, 178.4, 389.801, 172, 389.801, 172]},
{t: 'C', p: [385.801, 168.4, 389.401, 169.2, 389.401, 169.2]},
{t: 'C', p: [406.201, 170.4, 377.401, 159.2, 377.401, 159.2]},
{t: 'C', p: [385.401, 159.2, 367.401, 148.8, 367.401, 148.8]},
{t: 'C', p: [365.401, 147.2, 362.201, 139.6, 362.201, 139.6]},
{t: 'C', p: [356.201, 134.4, 351.401, 127.6, 351.401, 127.6]},
{t: 'C', p: [351.001, 123.2, 346.201, 118.4, 346.201, 118.4]},
{t: 'C', p: [334.601, 104.8, 329.001, 105.2, 329.001, 105.2]},
{t: 'C', p: [314.201, 101.6, 309.001, 102.4, 309.001, 102.4]},
{t: 'L', p: [256.2, 106.8]},
{t: 'C', p: [229.8, 119.6, 237.6, 140.6, 237.6, 140.6]},
{t: 'C', p: [244, 149, 253.2, 145.2, 253.2, 145.2]},
{t: 'C', p: [257.8, 139, 269.4, 141.2, 269.4, 141.2]},
{t: 'C', p: [289.801, 144.4, 287.201, 140.8, 287.201, 140.8]},
{t: 'C', p: [284.801, 136.2, 268.6, 130, 268.4, 129.4]},
{t: 'C', p: [268.2, 128.8, 259.4, 125.4, 259.4, 125.4]},
{t: 'C', p: [256.4, 124.2, 252, 115, 252, 115]},
{t: 'C', p: [248.8, 111.6, 264.6, 117.4, 264.6, 117.4]},
{t: 'C', p: [263.4, 118.4, 270.8, 122.4, 270.8, 122.4]},
{t: 'C', p: [288.201, 121.4, 298.801, 132.2, 298.801, 132.2]},
{t: 'C', p: [309.601, 148.8, 309.801, 140.6, 309.801, 140.6]},
{t: 'C', p: [312.601, 131.2, 300.801, 110, 300.801, 110]},
{t: 'C', p: [301.201, 108, 309.401, 114.6, 309.401, 114.6]},
{t: 'C', p: [310.801, 112.6, 311.601, 118.4, 311.601, 118.4]},
{t: 'C', p: [311.801, 120.8, 315.601, 128.8, 315.601, 128.8]},
{t: 'C', p: [318.401, 141.8, 322.001, 134.4, 322.001, 134.4]},
{t: 'L', p: [326.601, 143.8]},
{t: 'C', p: [328.001, 146.4, 322.001, 154, 322.001, 154]},
{t: 'C', p: [321.801, 156.8, 322.601, 156.6, 317.001, 164.2]},
{t: 'C', p: [311.401, 171.8, 314.801, 176.2, 314.801, 176.2]},
{t: 'C', p: [313.401, 182.8, 322.201, 182.4, 322.201, 182.4]},
{t: 'C', p: [324.801, 184.6, 328.201, 184.6, 328.201, 184.6]},
{t: 'C', p: [330.001, 186.6, 332.401, 186, 332.401, 186]},
{t: 'C', p: [334.001, 182.2, 340.201, 184.2, 340.201, 184.2]},
{t: 'C', p: [341.601, 181.8, 349.801, 181.4, 349.801, 181.4]},
{t: 'C', p: [350.801, 178.8, 351.201, 177.2, 354.601, 176.6]},
{t: 'C', p: [358.001, 176, 333.401, 133, 333.401, 133]},
{t: 'C', p: [339.801, 132.2, 331.601, 119.8, 331.601, 119.8]},
{t: 'C', p: [329.401, 113.2, 340.801, 127.8, 343.001, 129.2]},
{t: 'C', p: [345.201, 130.6, 346.201, 132.8, 344.601, 132.6]},
{t: 'C', p: [343.001, 132.4, 341.201, 134.6, 342.601, 134.8]},
{t: 'C', p: [344.001, 135, 357.001, 150, 360.401, 160.2]},
{t: 'C', p: [363.801, 170.4, 369.801, 174.4, 376.001, 180.4]},
{t: 'C', p: [382.201, 186.4, 381.401, 210.6, 381.401, 210.6]},
{t: 'C', p: [381.001, 219.4, 387.001, 230, 387.001, 230]},
{t: 'C', p: [389.001, 233.8, 384.801, 252, 384.801, 252]},
{t: 'C', p: [382.801, 254.2, 384.201, 255, 384.201, 255]},
{t: 'C', p: [385.201, 256.2, 392.001, 269.4, 392.001, 269.4]},
{t: 'C', p: [390.201, 269.2, 393.801, 272.8, 393.801, 272.8]},
{t: 'C', p: [399.001, 278.8, 392.601, 275.8, 392.601, 275.8]},
{t: 'C', p: [386.601, 274.2, 393.601, 284, 393.601, 284]},
{t: 'C', p: [394.801, 285.8, 385.801, 281.2, 385.801, 281.2]},
{t: 'C', p: [376.601, 280.6, 388.201, 287.8, 388.201, 287.8]},
{t: 'C', p: [396.801, 295, 385.401, 290.6, 385.401, 290.6]},
{t: 'C', p: [380.801, 288.8, 384.001, 295.6, 384.001, 295.6]},
{t: 'C', p: [387.201, 297.2, 404.401, 304.2, 404.401, 304.2]},
{t: 'C', p: [404.801, 308.001, 401.801, 313.001, 401.801, 313.001]},
{t: 'C', p: [402.201, 317.001, 400.001, 320.401, 400.001, 320.401]},
{t: 'C', p: [398.801, 328.601, 398.201, 329.401, 398.201, 329.401]},
{t: 'C', p: [394.001, 329.601, 386.601, 343.401, 386.601, 343.401]},
{t: 'C', p: [384.801, 346.001, 374.601, 358.001, 374.601, 358.001]},
{t: 'C', p: [372.601, 365.001, 354.601, 357.801, 354.601, 357.801]},
{t: 'C', p: [348.001, 361.201, 350.001, 357.801, 350.001, 357.801]},
{t: 'C', p: [349.601, 355.601, 354.401, 349.601, 354.401, 349.601]},
{t: 'C', p: [361.401, 347.001, 358.801, 336.201, 358.801, 336.201]},
{t: 'C', p: [362.801, 334.801, 351.601, 332.001, 351.801, 330.801]},
{t: 'C', p: [352.001, 329.601, 357.801, 328.201, 357.801, 328.201]},
{t: 'C', p: [365.801, 326.201, 361.401, 323.801, 361.401, 323.801]},
{t: 'C', p: [360.801, 319.801, 363.801, 314.201, 363.801, 314.201]},
{t: 'C', p: [375.401, 313.401, 363.801, 297.2, 363.801, 297.2]},
{t: 'C', p: [353.001, 289.6, 352.001, 283.8, 352.001, 283.8]},
{t: 'C', p: [364.601, 275.6, 356.401, 263.2, 356.601, 259.6]},
{t: 'C', p: [356.801, 256, 358.001, 234.4, 358.001, 234.4]},
{t: 'C', p: [356.001, 228.2, 353.001, 214.6, 353.001, 214.6]},
{t: 'C', p: [355.201, 209.4, 362.601, 196.8, 362.601, 196.8]},
{t: 'C', p: [365.401, 192.6, 374.201, 187.8, 372.001, 184.8]},
{t: 'C', p: [369.801, 181.8, 362.001, 183.6, 362.001, 183.6]},
{t: 'C', p: [354.201, 182.2, 354.801, 187.4, 354.801, 187.4]},
{t: 'C', p: [353.201, 188.4, 352.401, 193.4, 352.401, 193.4]},
{t: 'C', p: [351.68, 201.333, 342.801, 207.6, 342.801, 207.6]},
{t: 'C', p: [331.601, 213.8, 340.801, 217.8, 340.801, 217.8]},
{t: 'C', p: [346.801, 224.4, 337.001, 224.6, 337.001, 224.6]},
{t: 'C', p: [326.001, 222.8, 334.201, 233, 334.201, 233]},
{t: 'C', p: [345.001, 245.8, 342.001, 248.6, 342.001, 248.6]},
{t: 'C', p: [331.801, 249.6, 344.401, 258.8, 344.401, 258.8]},
{t: 'C', p: [344.401, 258.8, 343.601, 256.8, 343.801, 258.6]},
{t: 'C', p: [344.001, 260.4, 347.001, 264.6, 347.801, 266.6]},
{t: 'C', p: [348.601, 268.6, 344.601, 268.8, 344.601, 268.8]},
{t: 'C', p: [345.201, 278.4, 329.801, 274.2, 329.801, 274.2]},
{t: 'C', p: [329.801, 274.2, 329.801, 274.2, 328.201, 274.4]},
{t: 'C', p: [326.601, 274.6, 315.401, 273.8, 309.601, 271.6]},
{t: 'C', p: [303.801, 269.4, 297.001, 269.4, 297.001, 269.4]},
{t: 'C', p: [297.001, 269.4, 293.001, 271.2, 285.4, 271]},
{t: 'C', p: [277.8, 270.8, 269.8, 273.6, 269.8, 273.6]},
{t: 'C', p: [265.4, 273.2, 274, 268.8, 274.2, 269]},
{t: 'C', p: [274.4, 269.2, 280, 263.6, 272, 264.2]},
{t: 'C', p: [250.203, 265.835, 239.4, 255.6, 239.4, 255.6]},
{t: 'C', p: [237.4, 254.2, 234.8, 251.4, 234.8, 251.4]},
{t: 'C', p: [224.8, 249.4, 236.2, 263.8, 236.2, 263.8]},
{t: 'C', p: [237.4, 265.2, 236, 266.2, 236, 266.2]},
{t: 'C', p: [235.2, 264.6, 227.4, 259.2, 227.4, 259.2]},
{t: 'C', p: [224.589, 258.227, 223.226, 256.893, 220.895, 254.407]},
{t: 'z', p: []}]},
{f: '#4c0000', s: null, p: [{t: 'M', p: [197, 242.8]},
{t: 'C', p: [197, 242.8, 208.6, 248.4, 211.2, 251.2]},
{t: 'C', p: [213.8, 254, 227.8, 265.4, 227.8, 265.4]},
{t: 'C', p: [227.8, 265.4, 222.4, 263.4, 219.8, 261.6]},
{t: 'C', p: [217.2, 259.8, 206.4, 251.6, 206.4, 251.6]},
{t: 'C', p: [206.4, 251.6, 202.6, 245.6, 197, 242.8]},
{t: 'z', p: []}]},
{f: '#99cc32', s: null, p: [{t: 'M', p: [138.991, 211.603]},
{t: 'C', p: [139.328, 211.455, 138.804, 208.743, 138.6, 208.2]},
{t: 'C', p: [137.578, 205.474, 128.6, 204, 128.6, 204]},
{t: 'C', p: [128.373, 205.365, 128.318, 206.961, 128.424, 208.599]},
{t: 'C', p: [128.424, 208.599, 133.292, 214.118, 138.991, 211.603]},
{t: 'z', p: []}]},
{f: '#659900', s: null, p: [{t: 'M', p: [138.991, 211.403]},
{t: 'C', p: [138.542, 211.561, 138.976, 208.669, 138.8, 208.2]},
{t: 'C', p: [137.778, 205.474, 128.6, 203.9, 128.6, 203.9]},
{t: 'C', p: [128.373, 205.265, 128.318, 206.861, 128.424, 208.499]},
{t: 'C', p: [128.424, 208.499, 132.692, 213.618, 138.991, 211.403]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [134.6, 211.546]},
{t: 'C', p: [133.975, 211.546, 133.469, 210.406, 133.469, 209]},
{t: 'C', p: [133.469, 207.595, 133.975, 206.455, 134.6, 206.455]},
{t: 'C', p: [135.225, 206.455, 135.732, 207.595, 135.732, 209]},
{t: 'C', p: [135.732, 210.406, 135.225, 211.546, 134.6, 211.546]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [134.6, 209]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [89, 309.601]},
{t: 'C', p: [89, 309.601, 83.4, 319.601, 108.2, 313.601]},
{t: 'C', p: [108.2, 313.601, 122.2, 312.401, 124.6, 310.001]},
{t: 'C', p: [125.8, 310.801, 134.166, 313.734, 137, 314.401]},
{t: 'C', p: [143.8, 316.001, 152.2, 306, 152.2, 306]},
{t: 'C', p: [152.2, 306, 156.8, 295.5, 159.6, 295.5]},
{t: 'C', p: [162.4, 295.5, 159.2, 297.1, 159.2, 297.1]},
{t: 'C', p: [159.2, 297.1, 152.6, 307.201, 153, 308.801]},
{t: 'C', p: [153, 308.801, 147.8, 328.801, 131.8, 329.601]},
{t: 'C', p: [131.8, 329.601, 115.65, 330.551, 117, 336.401]},
{t: 'C', p: [117, 336.401, 125.8, 334.001, 128.2, 336.401]},
{t: 'C', p: [128.2, 336.401, 139, 336.001, 131, 342.401]},
{t: 'L', p: [124.2, 354.001]},
{t: 'C', p: [124.2, 354.001, 124.34, 357.919, 114.2, 354.401]},
{t: 'C', p: [104.4, 351.001, 94.1, 338.101, 94.1, 338.101]},
{t: 'C', p: [94.1, 338.101, 78.15, 323.551, 89, 309.601]},
{t: 'z', p: []}]},
{f: '#e59999', s: null, p: [{t: 'M', p: [87.8, 313.601]},
{t: 'C', p: [87.8, 313.601, 85.8, 323.201, 122.6, 312.801]},
{t: 'C', p: [122.6, 312.801, 127, 312.801, 129.4, 313.601]},
{t: 'C', p: [131.8, 314.401, 143.8, 317.201, 145.8, 316.001]},
{t: 'C', p: [145.8, 316.001, 138.6, 329.601, 127, 328.001]},
{t: 'C', p: [127, 328.001, 113.8, 329.601, 114.2, 334.401]},
{t: 'C', p: [114.2, 334.401, 118.2, 341.601, 123, 344.001]},
{t: 'C', p: [123, 344.001, 125.8, 346.401, 125.4, 349.601]},
{t: 'C', p: [125, 352.801, 122.2, 354.401, 120.2, 355.201]},
{t: 'C', p: [118.2, 356.001, 115, 352.801, 113.4, 352.801]},
{t: 'C', p: [111.8, 352.801, 103.4, 346.401, 99, 341.601]},
{t: 'C', p: [94.6, 336.801, 86.2, 324.801, 86.6, 322.001]},
{t: 'C', p: [87, 319.201, 87.8, 313.601, 87.8, 313.601]},
{t: 'z', p: []}]},
{f: '#b26565', s: null, p: [{t: 'M', p: [91, 331.051]},
{t: 'C', p: [93.6, 335.001, 96.8, 339.201, 99, 341.601]},
{t: 'C', p: [103.4, 346.401, 111.8, 352.801, 113.4, 352.801]},
{t: 'C', p: [115, 352.801, 118.2, 356.001, 120.2, 355.201]},
{t: 'C', p: [122.2, 354.401, 125, 352.801, 125.4, 349.601]},
{t: 'C', p: [125.8, 346.401, 123, 344.001, 123, 344.001]},
{t: 'C', p: [119.934, 342.468, 117.194, 338.976, 115.615, 336.653]},
{t: 'C', p: [115.615, 336.653, 115.8, 339.201, 110.6, 338.401]},
{t: 'C', p: [105.4, 337.601, 100.2, 334.801, 98.6, 331.601]},
{t: 'C', p: [97, 328.401, 94.6, 326.001, 96.2, 329.601]},
{t: 'C', p: [97.8, 333.201, 100.2, 336.801, 101.8, 337.201]},
{t: 'C', p: [103.4, 337.601, 103, 338.801, 100.6, 338.401]},
{t: 'C', p: [98.2, 338.001, 95.4, 337.601, 91, 332.401]},
{t: 'z', p: []}]},
{f: '#992600', s: null, p: [{t: 'M', p: [88.4, 310.001]},
{t: 'C', p: [88.4, 310.001, 90.2, 296.4, 91.4, 292.4]},
{t: 'C', p: [91.4, 292.4, 90.6, 285.6, 93, 281.4]},
{t: 'C', p: [95.4, 277.2, 97.4, 271, 100.4, 265.6]},
{t: 'C', p: [103.4, 260.2, 103.6, 256.2, 107.6, 254.6]},
{t: 'C', p: [111.6, 253, 117.6, 244.4, 120.4, 243.4]},
{t: 'C', p: [123.2, 242.4, 123, 243.2, 123, 243.2]},
{t: 'C', p: [123, 243.2, 129.8, 228.4, 143.4, 232.4]},
{t: 'C', p: [143.4, 232.4, 127.2, 229.6, 143, 220.2]},
{t: 'C', p: [143, 220.2, 138.2, 221.3, 141.5, 214.3]},
{t: 'C', p: [143.701, 209.632, 143.2, 216.4, 132.2, 228.2]},
{t: 'C', p: [132.2, 228.2, 127.2, 236.8, 122, 239.8]},
{t: 'C', p: [116.8, 242.8, 104.8, 249.8, 103.6, 253.6]},
{t: 'C', p: [102.4, 257.4, 99.2, 263.2, 97.2, 264.8]},
{t: 'C', p: [95.2, 266.4, 92.4, 270.6, 92, 274]},
{t: 'C', p: [92, 274, 90.8, 278, 89.4, 279.2]},
{t: 'C', p: [88, 280.4, 87.8, 283.6, 87.8, 285.6]},
{t: 'C', p: [87.8, 287.6, 85.8, 290.4, 86, 292.8]},
{t: 'C', p: [86, 292.8, 86.8, 311.801, 86.4, 313.801]},
{t: 'L', p: [88.4, 310.001]},
{t: 'z', p: []}]},
{f: '#fff', s: null, p: [{t: 'M', p: [79.8, 314.601]},
{t: 'C', p: [79.8, 314.601, 77.8, 313.201, 73.4, 319.201]},
{t: 'C', p: [73.4, 319.201, 80.7, 352.201, 80.7, 353.601]},
{t: 'C', p: [80.7, 353.601, 81.8, 351.501, 80.5, 344.301]},
{t: 'C', p: [79.2, 337.101, 78.3, 324.401, 78.3, 324.401]},
{t: 'L', p: [79.8, 314.601]},
{t: 'z', p: []}]},
{f: '#992600', s: null, p: [{t: 'M', p: [101.4, 254]},
{t: 'C', p: [101.4, 254, 83.8, 257.2, 84.2, 286.4]},
{t: 'L', p: [83.4, 311.201]},
{t: 'C', p: [83.4, 311.201, 82.2, 285.6, 81, 284]},
{t: 'C', p: [79.8, 282.4, 83.8, 271.2, 80.6, 277.2]},
{t: 'C', p: [80.6, 277.2, 66.6, 291.2, 74.6, 312.401]},
{t: 'C', p: [74.6, 312.401, 76.1, 315.701, 73.1, 311.101]},
{t: 'C', p: [73.1, 311.101, 68.5, 298.5, 69.6, 292.1]},
{t: 'C', p: [69.6, 292.1, 69.8, 289.9, 71.7, 287.1]},
{t: 'C', p: [71.7, 287.1, 80.3, 275.4, 83, 273.1]},
{t: 'C', p: [83, 273.1, 84.8, 258.7, 100.2, 253.5]},
{t: 'C', p: [100.2, 253.5, 105.9, 251.2, 101.4, 254]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [240.8, 187.8]},
{t: 'C', p: [241.46, 187.446, 241.451, 186.476, 242.031, 186.303]},
{t: 'C', p: [243.18, 185.959, 243.344, 184.892, 243.862, 184.108]},
{t: 'C', p: [244.735, 182.789, 244.928, 181.256, 245.51, 179.765]},
{t: 'C', p: [245.782, 179.065, 245.809, 178.11, 245.496, 177.45]},
{t: 'C', p: [244.322, 174.969, 243.62, 172.52, 242.178, 170.094]},
{t: 'C', p: [241.91, 169.644, 241.648, 168.85, 241.447, 168.252]},
{t: 'C', p: [240.984, 166.868, 239.727, 165.877, 238.867, 164.557]},
{t: 'C', p: [238.579, 164.116, 239.104, 163.191, 238.388, 163.107]},
{t: 'C', p: [237.491, 163.002, 236.042, 162.422, 235.809, 163.448]},
{t: 'C', p: [235.221, 166.035, 236.232, 168.558, 237.2, 171]},
{t: 'C', p: [236.418, 171.692, 236.752, 172.613, 236.904, 173.38]},
{t: 'C', p: [237.614, 176.986, 236.416, 180.338, 235.655, 183.812]},
{t: 'C', p: [235.632, 183.916, 235.974, 184.114, 235.946, 184.176]},
{t: 'C', p: [234.724, 186.862, 233.272, 189.307, 231.453, 191.688]},
{t: 'C', p: [230.695, 192.68, 229.823, 193.596, 229.326, 194.659]},
{t: 'C', p: [228.958, 195.446, 228.55, 196.412, 228.8, 197.4]},
{t: 'C', p: [225.365, 200.18, 223.115, 204.025, 220.504, 207.871]},
{t: 'C', p: [220.042, 208.551, 220.333, 209.76, 220.884, 210.029]},
{t: 'C', p: [221.697, 210.427, 222.653, 209.403, 223.123, 208.557]},
{t: 'C', p: [223.512, 207.859, 223.865, 207.209, 224.356, 206.566]},
{t: 'C', p: [224.489, 206.391, 224.31, 205.972, 224.445, 205.851]},
{t: 'C', p: [227.078, 203.504, 228.747, 200.568, 231.2, 198.2]},
{t: 'C', p: [233.15, 197.871, 234.687, 196.873, 236.435, 195.86]},
{t: 'C', p: [236.743, 195.681, 237.267, 195.93, 237.557, 195.735]},
{t: 'C', p: [239.31, 194.558, 239.308, 192.522, 239.414, 190.612]},
{t: 'C', p: [239.464, 189.728, 239.66, 188.411, 240.8, 187.8]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [231.959, 183.334]},
{t: 'C', p: [232.083, 183.257, 231.928, 182.834, 232.037, 182.618]},
{t: 'C', p: [232.199, 182.294, 232.602, 182.106, 232.764, 181.782]},
{t: 'C', p: [232.873, 181.566, 232.71, 181.186, 232.846, 181.044]},
{t: 'C', p: [235.179, 178.597, 235.436, 175.573, 234.4, 172.6]},
{t: 'C', p: [235.424, 171.98, 235.485, 170.718, 235.06, 169.871]},
{t: 'C', p: [234.207, 168.171, 234.014, 166.245, 233.039, 164.702]},
{t: 'C', p: [232.237, 163.433, 230.659, 162.189, 229.288, 163.492]},
{t: 'C', p: [228.867, 163.892, 228.546, 164.679, 228.824, 165.391]},
{t: 'C', p: [228.888, 165.554, 229.173, 165.7, 229.146, 165.782]},
{t: 'C', p: [229.039, 166.106, 228.493, 166.33, 228.487, 166.602]},
{t: 'C', p: [228.457, 168.098, 227.503, 169.609, 228.133, 170.938]},
{t: 'C', p: [228.905, 172.567, 229.724, 174.424, 230.4, 176.2]},
{t: 'C', p: [229.166, 178.316, 230.199, 180.765, 228.446, 182.642]},
{t: 'C', p: [228.31, 182.788, 228.319, 183.174, 228.441, 183.376]},
{t: 'C', p: [228.733, 183.862, 229.139, 184.268, 229.625, 184.56]},
{t: 'C', p: [229.827, 184.681, 230.175, 184.683, 230.375, 184.559]},
{t: 'C', p: [230.953, 184.197, 231.351, 183.71, 231.959, 183.334]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [294.771, 173.023]},
{t: 'C', p: [296.16, 174.815, 296.45, 177.61, 294.401, 179]},
{t: 'C', p: [294.951, 182.309, 298.302, 180.33, 300.401, 179.8]},
{t: 'C', p: [300.292, 179.412, 300.519, 179.068, 300.802, 179.063]},
{t: 'C', p: [301.859, 179.048, 302.539, 178.016, 303.601, 178.2]},
{t: 'C', p: [304.035, 176.643, 305.673, 175.941, 306.317, 174.561]},
{t: 'C', p: [308.043, 170.866, 307.452, 166.593, 304.868, 163.347]},
{t: 'C', p: [304.666, 163.093, 304.883, 162.576, 304.759, 162.214]},
{t: 'C', p: [304.003, 160.003, 301.935, 159.688, 300.001, 159]},
{t: 'C', p: [298.824, 155.125, 298.163, 151.094, 296.401, 147.4]},
{t: 'C', p: [294.787, 147.15, 294.089, 145.411, 292.752, 144.691]},
{t: 'C', p: [291.419, 143.972, 290.851, 145.551, 290.892, 146.597]},
{t: 'C', p: [290.899, 146.802, 291.351, 147.026, 291.181, 147.391]},
{t: 'C', p: [291.105, 147.555, 290.845, 147.666, 290.845, 147.8]},
{t: 'C', p: [290.846, 147.935, 291.067, 148.066, 291.201, 148.2]},
{t: 'C', p: [290.283, 149.02, 288.86, 149.497, 288.565, 150.642]},
{t: 'C', p: [287.611, 154.352, 290.184, 157.477, 291.852, 160.678]},
{t: 'C', p: [292.443, 161.813, 291.707, 163.084, 290.947, 164.292]},
{t: 'C', p: [290.509, 164.987, 290.617, 166.114, 290.893, 166.97]},
{t: 'C', p: [291.645, 169.301, 293.236, 171.04, 294.771, 173.023]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [257.611, 191.409]},
{t: 'C', p: [256.124, 193.26, 252.712, 195.829, 255.629, 197.757]},
{t: 'C', p: [255.823, 197.886, 256.193, 197.89, 256.366, 197.756]},
{t: 'C', p: [258.387, 196.191, 260.39, 195.288, 262.826, 194.706]},
{t: 'C', p: [262.95, 194.677, 263.224, 195.144, 263.593, 194.983]},
{t: 'C', p: [265.206, 194.28, 267.216, 194.338, 268.4, 193]},
{t: 'C', p: [272.167, 193.224, 275.732, 192.108, 279.123, 190.8]},
{t: 'C', p: [280.284, 190.352, 281.554, 189.793, 282.755, 189.291]},
{t: 'C', p: [284.131, 188.715, 285.335, 187.787, 286.447, 186.646]},
{t: 'C', p: [286.58, 186.51, 286.934, 186.6, 287.201, 186.6]},
{t: 'C', p: [287.161, 185.737, 288.123, 185.61, 288.37, 184.988]},
{t: 'C', p: [288.462, 184.756, 288.312, 184.36, 288.445, 184.258]},
{t: 'C', p: [290.583, 182.628, 291.503, 180.61, 290.334, 178.233]},
{t: 'C', p: [290.049, 177.655, 289.8, 177.037, 289.234, 176.561]},
{t: 'C', p: [288.149, 175.65, 287.047, 176.504, 286, 176.2]},
{t: 'C', p: [285.841, 176.828, 285.112, 176.656, 284.726, 176.854]},
{t: 'C', p: [283.867, 177.293, 282.534, 176.708, 281.675, 177.146]},
{t: 'C', p: [280.313, 177.841, 279.072, 178.01, 277.65, 178.387]},
{t: 'C', p: [277.338, 178.469, 276.56, 178.373, 276.4, 179]},
{t: 'C', p: [276.266, 178.866, 276.118, 178.632, 276.012, 178.654]},
{t: 'C', p: [274.104, 179.05, 272.844, 179.264, 271.543, 180.956]},
{t: 'C', p: [271.44, 181.089, 270.998, 180.91, 270.839, 181.045]},
{t: 'C', p: [269.882, 181.853, 269.477, 183.087, 268.376, 183.759]},
{t: 'C', p: [268.175, 183.882, 267.823, 183.714, 267.629, 183.843]},
{t: 'C', p: [266.983, 184.274, 266.616, 184.915, 265.974, 185.362]},
{t: 'C', p: [265.645, 185.591, 265.245, 185.266, 265.277, 185.01]},
{t: 'C', p: [265.522, 183.063, 266.175, 181.276, 265.6, 179.4]},
{t: 'C', p: [267.677, 176.88, 270.194, 174.931, 272, 172.2]},
{t: 'C', p: [272.015, 170.034, 272.707, 167.888, 272.594, 165.811]},
{t: 'C', p: [272.584, 165.618, 272.296, 164.885, 272.17, 164.538]},
{t: 'C', p: [271.858, 163.684, 272.764, 162.618, 271.92, 161.894]},
{t: 'C', p: [270.516, 160.691, 269.224, 161.567, 268.4, 163]},
{t: 'C', p: [266.562, 163.39, 264.496, 164.083, 262.918, 162.849]},
{t: 'C', p: [261.911, 162.062, 261.333, 161.156, 260.534, 160.1]},
{t: 'C', p: [259.549, 158.798, 259.884, 157.362, 259.954, 155.798]},
{t: 'C', p: [259.96, 155.67, 259.645, 155.534, 259.645, 155.4]},
{t: 'C', p: [259.646, 155.265, 259.866, 155.134, 260, 155]},
{t: 'C', p: [259.294, 154.374, 259.019, 153.316, 258, 153]},
{t: 'C', p: [258.305, 151.908, 257.629, 151.024, 256.758, 150.722]},
{t: 'C', p: [254.763, 150.031, 253.086, 151.943, 251.194, 152.016]},
{t: 'C', p: [250.68, 152.035, 250.213, 150.997, 249.564, 150.672]},
{t: 'C', p: [249.132, 150.456, 248.428, 150.423, 248.066, 150.689]},
{t: 'C', p: [247.378, 151.193, 246.789, 151.307, 246.031, 151.512]},
{t: 'C', p: [244.414, 151.948, 243.136, 153.042, 241.656, 153.897]},
{t: 'C', p: [240.171, 154.754, 239.216, 156.191, 238.136, 157.511]},
{t: 'C', p: [237.195, 158.663, 237.059, 161.077, 238.479, 161.577]},
{t: 'C', p: [240.322, 162.227, 241.626, 159.524, 243.592, 159.85]},
{t: 'C', p: [243.904, 159.901, 244.11, 160.212, 244, 160.6]},
{t: 'C', p: [244.389, 160.709, 244.607, 160.48, 244.8, 160.2]},
{t: 'C', p: [245.658, 161.219, 246.822, 161.556, 247.76, 162.429]},
{t: 'C', p: [248.73, 163.333, 250.476, 162.915, 251.491, 163.912]},
{t: 'C', p: [253.02, 165.414, 252.461, 168.095, 254.4, 169.4]},
{t: 'C', p: [253.814, 170.713, 253.207, 171.99, 252.872, 173.417]},
{t: 'C', p: [252.59, 174.623, 253.584, 175.82, 254.795, 175.729]},
{t: 'C', p: [256.053, 175.635, 256.315, 174.876, 256.8, 173.8]},
{t: 'C', p: [257.067, 174.067, 257.536, 174.364, 257.495, 174.58]},
{t: 'C', p: [257.038, 176.967, 256.011, 178.96, 255.553, 181.391]},
{t: 'C', p: [255.494, 181.708, 255.189, 181.91, 254.8, 181.8]},
{t: 'C', p: [254.332, 185.949, 250.28, 188.343, 247.735, 191.508]},
{t: 'C', p: [247.332, 192.01, 247.328, 193.259, 247.737, 193.662]},
{t: 'C', p: [249.14, 195.049, 251.1, 193.503, 252.8, 193]},
{t: 'C', p: [253.013, 191.794, 253.872, 190.852, 255.204, 190.908]},
{t: 'C', p: [255.46, 190.918, 255.695, 190.376, 256.019, 190.246]},
{t: 'C', p: [256.367, 190.108, 256.869, 190.332, 257.155, 190.134]},
{t: 'C', p: [258.884, 188.939, 260.292, 187.833, 262.03, 186.644]},
{t: 'C', p: [262.222, 186.513, 262.566, 186.672, 262.782, 186.564]},
{t: 'C', p: [263.107, 186.402, 263.294, 186.015, 263.617, 185.83]},
{t: 'C', p: [263.965, 185.63, 264.207, 185.92, 264.4, 186.2]},
{t: 'C', p: [263.754, 186.549, 263.75, 187.506, 263.168, 187.708]},
{t: 'C', p: [262.393, 187.976, 261.832, 188.489, 261.158, 188.936]},
{t: 'C', p: [260.866, 189.129, 260.207, 188.881, 260.103, 189.06]},
{t: 'C', p: [259.505, 190.088, 258.321, 190.526, 257.611, 191.409]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [202.2, 142]},
{t: 'C', p: [202.2, 142, 192.962, 139.128, 181.8, 164.8]},
{t: 'C', p: [181.8, 164.8, 179.4, 170, 177, 172]},
{t: 'C', p: [174.6, 174, 163.4, 177.6, 161.4, 181.6]},
{t: 'L', p: [151, 197.6]},
{t: 'C', p: [151, 197.6, 165.8, 181.6, 169, 179.2]},
{t: 'C', p: [169, 179.2, 177, 170.8, 173.8, 177.6]},
{t: 'C', p: [173.8, 177.6, 159.8, 188.4, 161, 197.6]},
{t: 'C', p: [161, 197.6, 155.4, 212, 154.6, 214]},
{t: 'C', p: [154.6, 214, 170.6, 182, 173, 180.8]},
{t: 'C', p: [175.4, 179.6, 176.6, 179.6, 175.4, 183.2]},
{t: 'C', p: [174.2, 186.8, 173.8, 203.2, 171, 205.2]},
{t: 'C', p: [171, 205.2, 179, 184.8, 178.2, 181.6]},
{t: 'C', p: [178.2, 181.6, 181.4, 178, 183.8, 183.2]},
{t: 'L', p: [182.6, 199.2]},
{t: 'L', p: [187, 211.2]},
{t: 'C', p: [187, 211.2, 184.6, 200, 186.2, 184.4]},
{t: 'C', p: [186.2, 184.4, 184.2, 174, 188.2, 179.6]},
{t: 'C', p: [192.2, 185.2, 201.8, 191.2, 201.8, 196]},
{t: 'C', p: [201.8, 196, 196.6, 178.4, 187.4, 173.6]},
{t: 'L', p: [183.4, 179.6]},
{t: 'L', p: [182.2, 177.6]},
{t: 'C', p: [182.2, 177.6, 178.6, 176.8, 183, 170]},
{t: 'C', p: [187.4, 163.2, 187, 162.4, 187, 162.4]},
{t: 'C', p: [187, 162.4, 193.4, 169.6, 195, 169.6]},
{t: 'C', p: [195, 169.6, 208.2, 162, 209.4, 186.4]},
{t: 'C', p: [209.4, 186.4, 216.2, 172, 207, 165.2]},
{t: 'C', p: [207, 165.2, 192.2, 163.2, 193.4, 158]},
{t: 'L', p: [200.6, 145.6]},
{t: 'C', p: [204.2, 140.4, 202.6, 143.2, 202.6, 143.2]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [182.2, 158.4]},
{t: 'C', p: [182.2, 158.4, 169.4, 158.4, 166.2, 163.6]},
{t: 'L', p: [159, 173.2]},
{t: 'C', p: [159, 173.2, 176.2, 163.2, 180.2, 162]},
{t: 'C', p: [184.2, 160.8, 182.2, 158.4, 182.2, 158.4]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [142.2, 164.8]},
{t: 'C', p: [142.2, 164.8, 140.2, 166, 139.8, 168.8]},
{t: 'C', p: [139.4, 171.6, 137, 172, 137.8, 174.8]},
{t: 'C', p: [138.6, 177.6, 140.6, 180, 140.6, 176]},
{t: 'C', p: [140.6, 172, 142.2, 170, 143, 168.8]},
{t: 'C', p: [143.8, 167.6, 145.4, 163.2, 142.2, 164.8]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [133.4, 226]},
{t: 'C', p: [133.4, 226, 125, 222, 121.8, 218.4]},
{t: 'C', p: [118.6, 214.8, 119.052, 219.966, 114.2, 219.6]},
{t: 'C', p: [108.353, 219.159, 109.4, 203.2, 109.4, 203.2]},
{t: 'L', p: [105.4, 210.8]},
{t: 'C', p: [105.4, 210.8, 104.2, 225.2, 112.2, 222.8]},
{t: 'C', p: [116.107, 221.628, 117.4, 223.2, 115.8, 224]},
{t: 'C', p: [114.2, 224.8, 121.4, 225.2, 118.6, 226.8]},
{t: 'C', p: [115.8, 228.4, 130.2, 223.2, 127.8, 233.6]},
{t: 'L', p: [133.4, 226]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [120.8, 240.4]},
{t: 'C', p: [120.8, 240.4, 105.4, 244.8, 101.8, 235.2]},
{t: 'C', p: [101.8, 235.2, 97, 237.6, 99.2, 240.6]},
{t: 'C', p: [101.4, 243.6, 102.6, 244, 102.6, 244]},
{t: 'C', p: [102.6, 244, 108, 245.2, 107.4, 246]},
{t: 'C', p: [106.8, 246.8, 104.4, 250.2, 104.4, 250.2]},
{t: 'C', p: [104.4, 250.2, 114.6, 244.2, 120.8, 240.4]},
{t: 'z', p: []}]},
{f: '#fff', s: null, p: [{t: 'M', p: [349.201, 318.601]},
{t: 'C', p: [348.774, 320.735, 347.103, 321.536, 345.201, 322.201]},
{t: 'C', p: [343.284, 321.243, 340.686, 318.137, 338.801, 320.201]},
{t: 'C', p: [338.327, 319.721, 337.548, 319.661, 337.204, 318.999]},
{t: 'C', p: [336.739, 318.101, 337.011, 317.055, 336.669, 316.257]},
{t: 'C', p: [336.124, 314.985, 335.415, 313.619, 335.601, 312.201]},
{t: 'C', p: [337.407, 311.489, 338.002, 309.583, 337.528, 307.82]},
{t: 'C', p: [337.459, 307.563, 337.03, 307.366, 337.23, 307.017]},
{t: 'C', p: [337.416, 306.694, 337.734, 306.467, 338.001, 306.2]},
{t: 'C', p: [337.866, 306.335, 337.721, 306.568, 337.61, 306.548]},
{t: 'C', p: [337, 306.442, 337.124, 305.805, 337.254, 305.418]},
{t: 'C', p: [337.839, 303.672, 339.853, 303.408, 341.201, 304.6]},
{t: 'C', p: [341.457, 304.035, 341.966, 304.229, 342.401, 304.2]},
{t: 'C', p: [342.351, 303.621, 342.759, 303.094, 342.957, 302.674]},
{t: 'C', p: [343.475, 301.576, 345.104, 302.682, 345.901, 302.07]},
{t: 'C', p: [346.977, 301.245, 348.04, 300.546, 349.118, 301.149]},
{t: 'C', p: [350.927, 302.162, 352.636, 303.374, 353.835, 305.115]},
{t: 'C', p: [354.41, 305.949, 354.65, 307.23, 354.592, 308.188]},
{t: 'C', p: [354.554, 308.835, 353.173, 308.483, 352.83, 309.412]},
{t: 'C', p: [352.185, 311.16, 354.016, 311.679, 354.772, 313.017]},
{t: 'C', p: [354.97, 313.366, 354.706, 313.67, 354.391, 313.768]},
{t: 'C', p: [353.98, 313.896, 353.196, 313.707, 353.334, 314.16]},
{t: 'C', p: [354.306, 317.353, 351.55, 318.031, 349.201, 318.601]},
{t: 'z', p: []}]},
{f: '#fff', s: null, p: [{t: 'M', p: [339.6, 338.201]},
{t: 'C', p: [339.593, 336.463, 337.992, 334.707, 339.201, 333.001]},
{t: 'C', p: [339.336, 333.135, 339.467, 333.356, 339.601, 333.356]},
{t: 'C', p: [339.736, 333.356, 339.867, 333.135, 340.001, 333.001]},
{t: 'C', p: [341.496, 335.217, 345.148, 336.145, 345.006, 338.991]},
{t: 'C', p: [344.984, 339.438, 343.897, 340.356, 344.801, 341.001]},
{t: 'C', p: [342.988, 342.349, 342.933, 344.719, 342.001, 346.601]},
{t: 'C', p: [340.763, 346.315, 339.551, 345.952, 338.401, 345.401]},
{t: 'C', p: [338.753, 343.915, 338.636, 342.231, 339.456, 340.911]},
{t: 'C', p: [339.89, 340.213, 339.603, 339.134, 339.6, 338.201]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [173.4, 329.201]},
{t: 'C', p: [173.4, 329.201, 156.542, 339.337, 170.6, 324.001]},
{t: 'C', p: [179.4, 314.401, 189.4, 308.801, 189.4, 308.801]},
{t: 'C', p: [189.4, 308.801, 199.8, 304.4, 203.4, 303.2]},
{t: 'C', p: [207, 302, 222.2, 296.8, 225.4, 296.4]},
{t: 'C', p: [228.6, 296, 238.2, 292, 245, 296]},
{t: 'C', p: [251.8, 300, 259.8, 304.4, 259.8, 304.4]},
{t: 'C', p: [259.8, 304.4, 243.4, 296, 239.8, 298.4]},
{t: 'C', p: [236.2, 300.8, 229, 300.4, 223, 303.6]},
{t: 'C', p: [223, 303.6, 208.2, 308.001, 205, 310.001]},
{t: 'C', p: [201.8, 312.001, 191.4, 323.601, 189.8, 322.801]},
{t: 'C', p: [188.2, 322.001, 190.2, 321.601, 191.4, 318.801]},
{t: 'C', p: [192.6, 316.001, 190.6, 314.401, 182.6, 320.801]},
{t: 'C', p: [174.6, 327.201, 173.4, 329.201, 173.4, 329.201]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [180.805, 323.234]},
{t: 'C', p: [180.805, 323.234, 182.215, 310.194, 190.693, 311.859]},
{t: 'C', p: [190.693, 311.859, 198.919, 307.689, 201.641, 305.721]},
{t: 'C', p: [201.641, 305.721, 209.78, 304.019, 211.09, 303.402]},
{t: 'C', p: [229.569, 294.702, 244.288, 299.221, 244.835, 298.101]},
{t: 'C', p: [245.381, 296.982, 265.006, 304.099, 268.615, 308.185]},
{t: 'C', p: [269.006, 308.628, 258.384, 302.588, 248.686, 300.697]},
{t: 'C', p: [240.413, 299.083, 218.811, 300.944, 207.905, 306.48]},
{t: 'C', p: [204.932, 307.989, 195.987, 313.773, 193.456, 313.662]},
{t: 'C', p: [190.925, 313.55, 180.805, 323.234, 180.805, 323.234]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [177, 348.801]},
{t: 'C', p: [177, 348.801, 161.8, 346.401, 178.6, 344.801]},
{t: 'C', p: [178.6, 344.801, 196.6, 342.801, 200.6, 337.601]},
{t: 'C', p: [200.6, 337.601, 214.2, 328.401, 217, 328.001]},
{t: 'C', p: [219.8, 327.601, 249.8, 320.401, 250.2, 318.001]},
{t: 'C', p: [250.6, 315.601, 256.2, 315.601, 257.8, 316.401]},
{t: 'C', p: [259.4, 317.201, 258.6, 318.401, 255.8, 319.201]},
{t: 'C', p: [253, 320.001, 221.8, 336.401, 215.4, 337.601]},
{t: 'C', p: [209, 338.801, 197.4, 346.401, 192.6, 347.601]},
{t: 'C', p: [187.8, 348.801, 177, 348.801, 177, 348.801]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [196.52, 341.403]},
{t: 'C', p: [196.52, 341.403, 187.938, 340.574, 196.539, 339.755]},
{t: 'C', p: [196.539, 339.755, 205.355, 336.331, 207.403, 333.668]},
{t: 'C', p: [207.403, 333.668, 214.367, 328.957, 215.8, 328.753]},
{t: 'C', p: [217.234, 328.548, 231.194, 324.861, 231.399, 323.633]},
{t: 'C', p: [231.604, 322.404, 265.67, 309.823, 270.09, 313.013]},
{t: 'C', p: [273.001, 315.114, 263.1, 313.437, 253.466, 317.847]},
{t: 'C', p: [252.111, 318.467, 218.258, 333.054, 214.981, 333.668]},
{t: 'C', p: [211.704, 334.283, 205.765, 338.174, 203.307, 338.788]},
{t: 'C', p: [200.85, 339.403, 196.52, 341.403, 196.52, 341.403]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [188.6, 343.601]},
{t: 'C', p: [188.6, 343.601, 193.8, 343.201, 192.6, 344.801]},
{t: 'C', p: [191.4, 346.401, 189, 345.601, 189, 345.601]},
{t: 'L', p: [188.6, 343.601]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [181.4, 345.201]},
{t: 'C', p: [181.4, 345.201, 186.6, 344.801, 185.4, 346.401]},
{t: 'C', p: [184.2, 348.001, 181.8, 347.201, 181.8, 347.201]},
{t: 'L', p: [181.4, 345.201]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [171, 346.801]},
{t: 'C', p: [171, 346.801, 176.2, 346.401, 175, 348.001]},
{t: 'C', p: [173.8, 349.601, 171.4, 348.801, 171.4, 348.801]},
{t: 'L', p: [171, 346.801]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [163.4, 347.601]},
{t: 'C', p: [163.4, 347.601, 168.6, 347.201, 167.4, 348.801]},
{t: 'C', p: [166.2, 350.401, 163.8, 349.601, 163.8, 349.601]},
{t: 'L', p: [163.4, 347.601]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [201.8, 308.001]},
{t: 'C', p: [201.8, 308.001, 206.2, 308.001, 205, 309.601]},
{t: 'C', p: [203.8, 311.201, 200.6, 310.801, 200.6, 310.801]},
{t: 'L', p: [201.8, 308.001]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [191.8, 313.601]},
{t: 'C', p: [191.8, 313.601, 198.306, 311.46, 195.8, 314.801]},
{t: 'C', p: [194.6, 316.401, 192.2, 315.601, 192.2, 315.601]},
{t: 'L', p: [191.8, 313.601]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [180.6, 318.401]},
{t: 'C', p: [180.6, 318.401, 185.8, 318.001, 184.6, 319.601]},
{t: 'C', p: [183.4, 321.201, 181, 320.401, 181, 320.401]},
{t: 'L', p: [180.6, 318.401]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [173, 324.401]},
{t: 'C', p: [173, 324.401, 178.2, 324.001, 177, 325.601]},
{t: 'C', p: [175.8, 327.201, 173.4, 326.401, 173.4, 326.401]},
{t: 'L', p: [173, 324.401]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [166.2, 329.201]},
{t: 'C', p: [166.2, 329.201, 171.4, 328.801, 170.2, 330.401]},
{t: 'C', p: [169, 332.001, 166.6, 331.201, 166.6, 331.201]},
{t: 'L', p: [166.2, 329.201]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [205.282, 335.598]},
{t: 'C', p: [205.282, 335.598, 212.203, 335.066, 210.606, 337.195]},
{t: 'C', p: [209.009, 339.325, 205.814, 338.26, 205.814, 338.26]},
{t: 'L', p: [205.282, 335.598]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [215.682, 330.798]},
{t: 'C', p: [215.682, 330.798, 222.603, 330.266, 221.006, 332.395]},
{t: 'C', p: [219.409, 334.525, 216.214, 333.46, 216.214, 333.46]},
{t: 'L', p: [215.682, 330.798]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [226.482, 326.398]},
{t: 'C', p: [226.482, 326.398, 233.403, 325.866, 231.806, 327.995]},
{t: 'C', p: [230.209, 330.125, 227.014, 329.06, 227.014, 329.06]},
{t: 'L', p: [226.482, 326.398]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [236.882, 321.598]},
{t: 'C', p: [236.882, 321.598, 243.803, 321.066, 242.206, 323.195]},
{t: 'C', p: [240.609, 325.325, 237.414, 324.26, 237.414, 324.26]},
{t: 'L', p: [236.882, 321.598]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [209.282, 303.598]},
{t: 'C', p: [209.282, 303.598, 216.203, 303.066, 214.606, 305.195]},
{t: 'C', p: [213.009, 307.325, 209.014, 307.06, 209.014, 307.06]},
{t: 'L', p: [209.282, 303.598]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [219.282, 300.398]},
{t: 'C', p: [219.282, 300.398, 226.203, 299.866, 224.606, 301.995]},
{t: 'C', p: [223.009, 304.125, 218.614, 303.86, 218.614, 303.86]},
{t: 'L', p: [219.282, 300.398]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [196.6, 340.401]},
{t: 'C', p: [196.6, 340.401, 201.8, 340.001, 200.6, 341.601]},
{t: 'C', p: [199.4, 343.201, 197, 342.401, 197, 342.401]},
{t: 'L', p: [196.6, 340.401]},
{t: 'z', p: []}]},
{f: '#992600', s: null, p: [{t: 'M', p: [123.4, 241.2]},
{t: 'C', p: [123.4, 241.2, 119, 250, 118.6, 253.2]},
{t: 'C', p: [118.6, 253.2, 119.4, 244.4, 120.6, 242.4]},
{t: 'C', p: [121.8, 240.4, 123.4, 241.2, 123.4, 241.2]},
{t: 'z', p: []}]},
{f: '#992600', s: null, p: [{t: 'M', p: [105, 255.2]},
{t: 'C', p: [105, 255.2, 101.8, 269.6, 102.2, 272.4]},
{t: 'C', p: [102.2, 272.4, 101, 260.8, 101.4, 259.6]},
{t: 'C', p: [101.8, 258.4, 105, 255.2, 105, 255.2]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [125.8, 180.6]},
{t: 'L', p: [125.6, 183.8]},
{t: 'L', p: [123.4, 184]},
{t: 'C', p: [123.4, 184, 137.6, 196.6, 138.2, 204.2]},
{t: 'C', p: [138.2, 204.2, 139, 196, 125.8, 180.6]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [129.784, 181.865]},
{t: 'C', p: [129.353, 181.449, 129.572, 180.704, 129.164, 180.444]},
{t: 'C', p: [128.355, 179.928, 130.462, 179.871, 130.234, 179.155]},
{t: 'C', p: [129.851, 177.949, 130.038, 177.928, 129.916, 176.652]},
{t: 'C', p: [129.859, 176.054, 130.447, 174.514, 130.832, 174.074]},
{t: 'C', p: [132.278, 172.422, 130.954, 169.49, 132.594, 167.939]},
{t: 'C', p: [132.898, 167.65, 133.274, 167.098, 133.559, 166.68]},
{t: 'C', p: [134.218, 165.717, 135.402, 165.229, 136.352, 164.401]},
{t: 'C', p: [136.67, 164.125, 136.469, 163.298, 137.038, 163.39]},
{t: 'C', p: [137.752, 163.505, 138.993, 163.375, 138.948, 164.216]},
{t: 'C', p: [138.835, 166.336, 137.506, 168.056, 136.226, 169.724]},
{t: 'C', p: [136.677, 170.428, 136.219, 171.063, 135.935, 171.62]},
{t: 'C', p: [134.6, 174.24, 134.789, 177.081, 134.615, 179.921]},
{t: 'C', p: [134.61, 180.006, 134.303, 180.084, 134.311, 180.137]},
{t: 'C', p: [134.664, 182.472, 135.248, 184.671, 136.127, 186.9]},
{t: 'C', p: [136.493, 187.83, 136.964, 188.725, 137.114, 189.652]},
{t: 'C', p: [137.225, 190.338, 137.328, 191.171, 136.92, 191.876]},
{t: 'C', p: [138.955, 194.766, 137.646, 197.417, 138.815, 200.948]},
{t: 'C', p: [139.022, 201.573, 140.714, 203.487, 140.251, 203.326]},
{t: 'C', p: [137.738, 202.455, 137.626, 202.057, 137.449, 201.304]},
{t: 'C', p: [137.303, 200.681, 136.973, 199.304, 136.736, 198.702]},
{t: 'C', p: [136.672, 198.538, 136.501, 196.654, 136.423, 196.532]},
{t: 'C', p: [134.91, 194.15, 136.268, 194.326, 134.898, 191.968]},
{t: 'C', p: [133.47, 191.288, 132.504, 190.184, 131.381, 189.022]},
{t: 'C', p: [131.183, 188.818, 132.326, 188.094, 132.145, 187.881]},
{t: 'C', p: [131.053, 186.592, 129.9, 185.825, 130.236, 184.332]},
{t: 'C', p: [130.391, 183.642, 130.528, 182.585, 129.784, 181.865]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [126.2, 183.6]},
{t: 'C', p: [126.2, 183.6, 126.6, 190.4, 129, 192]},
{t: 'C', p: [131.4, 193.6, 130.2, 192.8, 127, 191.6]},
{t: 'C', p: [123.8, 190.4, 125, 189.6, 125, 189.6]},
{t: 'C', p: [125, 189.6, 122.2, 190, 124.6, 192]},
{t: 'C', p: [127, 194, 130.6, 196.4, 129, 196.4]},
{t: 'C', p: [127.4, 196.4, 119.8, 192.4, 119.8, 189.6]},
{t: 'C', p: [119.8, 186.8, 118.8, 182.7, 118.8, 182.7]},
{t: 'C', p: [118.8, 182.7, 119.9, 181.9, 124.7, 182]},
{t: 'C', p: [124.7, 182, 126.1, 182.7, 126.2, 183.6]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [125.4, 202.2]},
{t: 'C', p: [125.4, 202.2, 116.88, 199.409, 98.4, 202.8]},
{t: 'C', p: [98.4, 202.8, 107.431, 200.722, 126.2, 203]},
{t: 'C', p: [136.5, 204.25, 125.4, 202.2, 125.4, 202.2]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [127.498, 202.129]},
{t: 'C', p: [127.498, 202.129, 119.252, 198.611, 100.547, 200.392]},
{t: 'C', p: [100.547, 200.392, 109.725, 199.103, 128.226, 202.995]},
{t: 'C', p: [138.38, 205.131, 127.498, 202.129, 127.498, 202.129]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [129.286, 202.222]},
{t: 'C', p: [129.286, 202.222, 121.324, 198.101, 102.539, 198.486]},
{t: 'C', p: [102.539, 198.486, 111.787, 197.882, 129.948, 203.14]},
{t: 'C', p: [139.914, 206.025, 129.286, 202.222, 129.286, 202.222]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [130.556, 202.445]},
{t: 'C', p: [130.556, 202.445, 123.732, 198.138, 106.858, 197.04]},
{t: 'C', p: [106.858, 197.04, 115.197, 197.21, 131.078, 203.319]},
{t: 'C', p: [139.794, 206.672, 130.556, 202.445, 130.556, 202.445]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [245.84, 212.961]},
{t: 'C', p: [245.84, 212.961, 244.91, 213.605, 245.124, 212.424]},
{t: 'C', p: [245.339, 211.243, 273.547, 198.073, 277.161, 198.323]},
{t: 'C', p: [277.161, 198.323, 246.913, 211.529, 245.84, 212.961]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [242.446, 213.6]},
{t: 'C', p: [242.446, 213.6, 241.57, 214.315, 241.691, 213.121]},
{t: 'C', p: [241.812, 211.927, 268.899, 196.582, 272.521, 196.548]},
{t: 'C', p: [272.521, 196.548, 243.404, 212.089, 242.446, 213.6]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [239.16, 214.975]},
{t: 'C', p: [239.16, 214.975, 238.332, 215.747, 238.374, 214.547]},
{t: 'C', p: [238.416, 213.348, 258.233, 197.851, 268.045, 195.977]},
{t: 'C', p: [268.045, 195.977, 250.015, 204.104, 239.16, 214.975]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [236.284, 216.838]},
{t: 'C', p: [236.284, 216.838, 235.539, 217.532, 235.577, 216.453]},
{t: 'C', p: [235.615, 215.373, 253.449, 201.426, 262.28, 199.74]},
{t: 'C', p: [262.28, 199.74, 246.054, 207.054, 236.284, 216.838]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [204.6, 364.801]},
{t: 'C', p: [204.6, 364.801, 189.4, 362.401, 206.2, 360.801]},
{t: 'C', p: [206.2, 360.801, 224.2, 358.801, 228.2, 353.601]},
{t: 'C', p: [228.2, 353.601, 241.8, 344.401, 244.6, 344.001]},
{t: 'C', p: [247.4, 343.601, 263.8, 340.001, 264.2, 337.601]},
{t: 'C', p: [264.6, 335.201, 270.6, 332.801, 272.2, 333.601]},
{t: 'C', p: [273.8, 334.401, 273.8, 343.601, 271, 344.401]},
{t: 'C', p: [268.2, 345.201, 249.4, 352.401, 243, 353.601]},
{t: 'C', p: [236.6, 354.801, 225, 362.401, 220.2, 363.601]},
{t: 'C', p: [215.4, 364.801, 204.6, 364.801, 204.6, 364.801]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [277.6, 327.401]},
{t: 'C', p: [277.6, 327.401, 274.6, 329.001, 273.4, 331.601]},
{t: 'C', p: [273.4, 331.601, 267, 342.201, 252.8, 345.401]},
{t: 'C', p: [252.8, 345.401, 229.8, 354.401, 222, 356.401]},
{t: 'C', p: [222, 356.401, 208.6, 361.401, 201.2, 360.601]},
{t: 'C', p: [201.2, 360.601, 194.2, 360.801, 200.4, 362.401]},
{t: 'C', p: [200.4, 362.401, 220.6, 360.401, 224, 358.601]},
{t: 'C', p: [224, 358.601, 239.6, 353.401, 242.6, 350.801]},
{t: 'C', p: [245.6, 348.201, 263.8, 343.201, 266, 341.201]},
{t: 'C', p: [268.2, 339.201, 278, 330.801, 277.6, 327.401]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [218.882, 358.911]},
{t: 'C', p: [218.882, 358.911, 224.111, 358.685, 222.958, 360.234]},
{t: 'C', p: [221.805, 361.784, 219.357, 360.91, 219.357, 360.91]},
{t: 'L', p: [218.882, 358.911]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [211.68, 360.263]},
{t: 'C', p: [211.68, 360.263, 216.908, 360.037, 215.756, 361.586]},
{t: 'C', p: [214.603, 363.136, 212.155, 362.263, 212.155, 362.263]},
{t: 'L', p: [211.68, 360.263]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [201.251, 361.511]},
{t: 'C', p: [201.251, 361.511, 206.48, 361.284, 205.327, 362.834]},
{t: 'C', p: [204.174, 364.383, 201.726, 363.51, 201.726, 363.51]},
{t: 'L', p: [201.251, 361.511]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [193.617, 362.055]},
{t: 'C', p: [193.617, 362.055, 198.846, 361.829, 197.693, 363.378]},
{t: 'C', p: [196.54, 364.928, 194.092, 364.054, 194.092, 364.054]},
{t: 'L', p: [193.617, 362.055]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [235.415, 351.513]},
{t: 'C', p: [235.415, 351.513, 242.375, 351.212, 240.84, 353.274]},
{t: 'C', p: [239.306, 355.336, 236.047, 354.174, 236.047, 354.174]},
{t: 'L', p: [235.415, 351.513]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [245.73, 347.088]},
{t: 'C', p: [245.73, 347.088, 251.689, 343.787, 251.155, 348.849]},
{t: 'C', p: [250.885, 351.405, 246.362, 349.749, 246.362, 349.749]},
{t: 'L', p: [245.73, 347.088]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [254.862, 344.274]},
{t: 'C', p: [254.862, 344.274, 262.021, 340.573, 260.287, 346.035]},
{t: 'C', p: [259.509, 348.485, 255.493, 346.935, 255.493, 346.935]},
{t: 'L', p: [254.862, 344.274]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [264.376, 339.449]},
{t: 'C', p: [264.376, 339.449, 268.735, 334.548, 269.801, 341.21]},
{t: 'C', p: [270.207, 343.748, 265.008, 342.11, 265.008, 342.11]},
{t: 'L', p: [264.376, 339.449]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [226.834, 355.997]},
{t: 'C', p: [226.834, 355.997, 232.062, 355.77, 230.91, 357.32]},
{t: 'C', p: [229.757, 358.869, 227.308, 357.996, 227.308, 357.996]},
{t: 'L', p: [226.834, 355.997]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [262.434, 234.603]},
{t: 'C', p: [262.434, 234.603, 261.708, 235.268, 261.707, 234.197]},
{t: 'C', p: [261.707, 233.127, 279.191, 219.863, 288.034, 218.479]},
{t: 'C', p: [288.034, 218.479, 271.935, 225.208, 262.434, 234.603]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [265.4, 298.4]},
{t: 'C', p: [265.4, 298.4, 287.401, 320.801, 296.601, 324.401]},
{t: 'C', p: [296.601, 324.401, 305.801, 335.601, 301.801, 361.601]},
{t: 'C', p: [301.801, 361.601, 298.601, 369.201, 295.401, 348.401]},
{t: 'C', p: [295.401, 348.401, 298.601, 323.201, 287.401, 339.201]},
{t: 'C', p: [287.401, 339.201, 279, 329.301, 285.4, 329.601]},
{t: 'C', p: [285.4, 329.601, 288.601, 331.601, 289.001, 330.001]},
{t: 'C', p: [289.401, 328.401, 281.4, 314.801, 264.2, 300.4]},
{t: 'C', p: [247, 286, 265.4, 298.4, 265.4, 298.4]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [207, 337.201]},
{t: 'C', p: [207, 337.201, 206.8, 335.401, 208.6, 336.201]},
{t: 'C', p: [210.4, 337.001, 304.601, 343.201, 336.201, 367.201]},
{t: 'C', p: [336.201, 367.201, 291.001, 344.001, 207, 337.201]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [217.4, 332.801]},
{t: 'C', p: [217.4, 332.801, 217.2, 331.001, 219, 331.801]},
{t: 'C', p: [220.8, 332.601, 357.401, 331.601, 381.001, 364.001]},
{t: 'C', p: [381.001, 364.001, 359.001, 338.801, 217.4, 332.801]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [229, 328.801]},
{t: 'C', p: [229, 328.801, 228.8, 327.001, 230.6, 327.801]},
{t: 'C', p: [232.4, 328.601, 405.801, 315.601, 429.401, 348.001]},
{t: 'C', p: [429.401, 348.001, 419.801, 322.401, 229, 328.801]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [239, 324.001]},
{t: 'C', p: [239, 324.001, 238.8, 322.201, 240.6, 323.001]},
{t: 'C', p: [242.4, 323.801, 364.601, 285.2, 388.201, 317.601]},
{t: 'C', p: [388.201, 317.601, 374.801, 293, 239, 324.001]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [181, 346.801]},
{t: 'C', p: [181, 346.801, 180.8, 345.001, 182.6, 345.801]},
{t: 'C', p: [184.4, 346.601, 202.2, 348.801, 204.2, 387.601]},
{t: 'C', p: [204.2, 387.601, 197, 345.601, 181, 346.801]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [172.2, 348.401]},
{t: 'C', p: [172.2, 348.401, 172, 346.601, 173.8, 347.401]},
{t: 'C', p: [175.6, 348.201, 189.8, 343.601, 187, 382.401]},
{t: 'C', p: [187, 382.401, 188.2, 347.201, 172.2, 348.401]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [164.2, 348.801]},
{t: 'C', p: [164.2, 348.801, 164, 347.001, 165.8, 347.801]},
{t: 'C', p: [167.6, 348.601, 183, 349.201, 170.6, 371.601]},
{t: 'C', p: [170.6, 371.601, 180.2, 347.601, 164.2, 348.801]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [211.526, 304.465]},
{t: 'C', p: [211.526, 304.465, 211.082, 306.464, 212.631, 305.247]},
{t: 'C', p: [228.699, 292.622, 261.141, 233.72, 316.826, 228.086]},
{t: 'C', p: [316.826, 228.086, 278.518, 215.976, 211.526, 304.465]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [222.726, 302.665]},
{t: 'C', p: [222.726, 302.665, 221.363, 301.472, 223.231, 300.847]},
{t: 'C', p: [225.099, 300.222, 337.541, 227.72, 376.826, 235.686]},
{t: 'C', p: [376.826, 235.686, 349.719, 228.176, 222.726, 302.665]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [201.885, 308.767]},
{t: 'C', p: [201.885, 308.767, 201.376, 310.366, 203.087, 309.39]},
{t: 'C', p: [212.062, 304.27, 215.677, 247.059, 259.254, 245.804]},
{t: 'C', p: [259.254, 245.804, 226.843, 231.09, 201.885, 308.767]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [181.962, 319.793]},
{t: 'C', p: [181.962, 319.793, 180.885, 321.079, 182.838, 320.825]},
{t: 'C', p: [193.084, 319.493, 214.489, 278.222, 258.928, 283.301]},
{t: 'C', p: [258.928, 283.301, 226.962, 268.955, 181.962, 319.793]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [193.2, 313.667]},
{t: 'C', p: [193.2, 313.667, 192.389, 315.136, 194.258, 314.511]},
{t: 'C', p: [204.057, 311.237, 217.141, 266.625, 261.729, 263.078]},
{t: 'C', p: [261.729, 263.078, 227.603, 255.135, 193.2, 313.667]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [174.922, 324.912]},
{t: 'C', p: [174.922, 324.912, 174.049, 325.954, 175.631, 325.748]},
{t: 'C', p: [183.93, 324.669, 201.268, 291.24, 237.264, 295.354]},
{t: 'C', p: [237.264, 295.354, 211.371, 283.734, 174.922, 324.912]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [167.323, 330.821]},
{t: 'C', p: [167.323, 330.821, 166.318, 331.866, 167.909, 331.748]},
{t: 'C', p: [172.077, 331.439, 202.715, 298.36, 221.183, 313.862]},
{t: 'C', p: [221.183, 313.862, 209.168, 295.139, 167.323, 330.821]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [236.855, 298.898]},
{t: 'C', p: [236.855, 298.898, 235.654, 297.543, 237.586, 297.158]},
{t: 'C', p: [239.518, 296.774, 360.221, 239.061, 398.184, 251.927]},
{t: 'C', p: [398.184, 251.927, 372.243, 241.053, 236.855, 298.898]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [203.4, 363.201]},
{t: 'C', p: [203.4, 363.201, 203.2, 361.401, 205, 362.201]},
{t: 'C', p: [206.8, 363.001, 222.2, 363.601, 209.8, 386.001]},
{t: 'C', p: [209.8, 386.001, 219.4, 362.001, 203.4, 363.201]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [213.8, 361.601]},
{t: 'C', p: [213.8, 361.601, 213.6, 359.801, 215.4, 360.601]},
{t: 'C', p: [217.2, 361.401, 235, 363.601, 237, 402.401]},
{t: 'C', p: [237, 402.401, 229.8, 360.401, 213.8, 361.601]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [220.6, 360.001]},
{t: 'C', p: [220.6, 360.001, 220.4, 358.201, 222.2, 359.001]},
{t: 'C', p: [224, 359.801, 248.6, 363.201, 272.2, 395.601]},
{t: 'C', p: [272.2, 395.601, 236.6, 358.801, 220.6, 360.001]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [228.225, 357.972]},
{t: 'C', p: [228.225, 357.972, 227.788, 356.214, 229.678, 356.768]},
{t: 'C', p: [231.568, 357.322, 252.002, 355.423, 290.099, 389.599]},
{t: 'C', p: [290.099, 389.599, 243.924, 354.656, 228.225, 357.972]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [238.625, 353.572]},
{t: 'C', p: [238.625, 353.572, 238.188, 351.814, 240.078, 352.368]},
{t: 'C', p: [241.968, 352.922, 276.802, 357.423, 328.499, 392.399]},
{t: 'C', p: [328.499, 392.399, 254.324, 350.256, 238.625, 353.572]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [198.2, 342.001]},
{t: 'C', p: [198.2, 342.001, 198, 340.201, 199.8, 341.001]},
{t: 'C', p: [201.6, 341.801, 255, 344.401, 285.4, 371.201]},
{t: 'C', p: [285.4, 371.201, 250.499, 346.426, 198.2, 342.001]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [188.2, 346.001]},
{t: 'C', p: [188.2, 346.001, 188, 344.201, 189.8, 345.001]},
{t: 'C', p: [191.6, 345.801, 216.2, 349.201, 239.8, 381.601]},
{t: 'C', p: [239.8, 381.601, 204.2, 344.801, 188.2, 346.001]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [249.503, 348.962]},
{t: 'C', p: [249.503, 348.962, 248.938, 347.241, 250.864, 347.655]},
{t: 'C', p: [252.79, 348.068, 287.86, 350.004, 341.981, 381.098]},
{t: 'C', p: [341.981, 381.098, 264.317, 346.704, 249.503, 348.962]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [257.903, 346.562]},
{t: 'C', p: [257.903, 346.562, 257.338, 344.841, 259.264, 345.255]},
{t: 'C', p: [261.19, 345.668, 296.26, 347.604, 350.381, 378.698]},
{t: 'C', p: [350.381, 378.698, 273.317, 343.904, 257.903, 346.562]},
{t: 'z', p: []}]},
{f: '#fff', s: {c: '#000', w: 0.1},
p: [{t: 'M', p: [267.503, 341.562]},
{t: 'C', p: [267.503, 341.562, 266.938, 339.841, 268.864, 340.255]},
{t: 'C', p: [270.79, 340.668, 313.86, 345.004, 403.582, 379.298]},
{t: 'C', p: [403.582, 379.298, 282.917, 338.904, 267.503, 341.562]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [156.2, 348.401]},
{t: 'C', p: [156.2, 348.401, 161.4, 348.001, 160.2, 349.601]},
{t: 'C', p: [159, 351.201, 156.6, 350.401, 156.6, 350.401]},
{t: 'L', p: [156.2, 348.401]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [187, 362.401]},
{t: 'C', p: [187, 362.401, 192.2, 362.001, 191, 363.601]},
{t: 'C', p: [189.8, 365.201, 187.4, 364.401, 187.4, 364.401]},
{t: 'L', p: [187, 362.401]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [178.2, 362.001]},
{t: 'C', p: [178.2, 362.001, 183.4, 361.601, 182.2, 363.201]},
{t: 'C', p: [181, 364.801, 178.6, 364.001, 178.6, 364.001]},
{t: 'L', p: [178.2, 362.001]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [82.831, 350.182]},
{t: 'C', p: [82.831, 350.182, 87.876, 351.505, 86.218, 352.624]},
{t: 'C', p: [84.561, 353.744, 82.554, 352.202, 82.554, 352.202]},
{t: 'L', p: [82.831, 350.182]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [84.831, 340.582]},
{t: 'C', p: [84.831, 340.582, 89.876, 341.905, 88.218, 343.024]},
{t: 'C', p: [86.561, 344.144, 84.554, 342.602, 84.554, 342.602]},
{t: 'L', p: [84.831, 340.582]},
{t: 'z', p: []}]},
{f: '#000', s: null, p: [{t: 'M', p: [77.631, 336.182]},
{t: 'C', p: [77.631, 336.182, 82.676, 337.505, 81.018, 338.624]},
{t: 'C', p: [79.361, 339.744, 77.354, 338.202, 77.354, 338.202]},
{t: 'L', p: [77.631, 336.182]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [157.4, 411.201]},
{t: 'C', p: [157.4, 411.201, 155.8, 411.201, 151.8, 413.201]},
{t: 'C', p: [149.8, 413.201, 138.6, 416.801, 133, 426.801]},
{t: 'C', p: [133, 426.801, 145.4, 417.201, 157.4, 411.201]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [245.116, 503.847]},
{t: 'C', p: [245.257, 504.105, 245.312, 504.525, 245.604, 504.542]},
{t: 'C', p: [246.262, 504.582, 247.495, 504.883, 247.37, 504.247]},
{t: 'C', p: [246.522, 499.941, 245.648, 495.004, 241.515, 493.197]},
{t: 'C', p: [240.876, 492.918, 239.434, 493.331, 239.36, 494.215]},
{t: 'C', p: [239.233, 495.739, 239.116, 497.088, 239.425, 498.554]},
{t: 'C', p: [239.725, 499.975, 241.883, 499.985, 242.8, 498.601]},
{t: 'C', p: [243.736, 500.273, 244.168, 502.116, 245.116, 503.847]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [234.038, 508.581]},
{t: 'C', p: [234.786, 509.994, 234.659, 511.853, 236.074, 512.416]},
{t: 'C', p: [236.814, 512.71, 238.664, 511.735, 238.246, 510.661]},
{t: 'C', p: [237.444, 508.6, 237.056, 506.361, 235.667, 504.55]},
{t: 'C', p: [235.467, 504.288, 235.707, 503.755, 235.547, 503.427]},
{t: 'C', p: [234.953, 502.207, 233.808, 501.472, 232.4, 501.801]},
{t: 'C', p: [231.285, 504.004, 232.433, 506.133, 233.955, 507.842]},
{t: 'C', p: [234.091, 507.994, 233.925, 508.37, 234.038, 508.581]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [194.436, 503.391]},
{t: 'C', p: [194.328, 503.014, 194.29, 502.551, 194.455, 502.23]},
{t: 'C', p: [194.986, 501.197, 195.779, 500.075, 195.442, 499.053]},
{t: 'C', p: [195.094, 497.997, 193.978, 498.179, 193.328, 498.748]},
{t: 'C', p: [192.193, 499.742, 192.144, 501.568, 191.453, 502.927]},
{t: 'C', p: [191.257, 503.313, 191.308, 503.886, 190.867, 504.277]},
{t: 'C', p: [190.393, 504.698, 189.953, 506.222, 190.049, 506.793]},
{t: 'C', p: [190.102, 507.106, 189.919, 517.014, 190.141, 516.751]},
{t: 'C', p: [190.76, 516.018, 193.81, 506.284, 193.879, 505.392]},
{t: 'C', p: [193.936, 504.661, 194.668, 504.196, 194.436, 503.391]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [168.798, 496.599]},
{t: 'C', p: [171.432, 494.1, 174.222, 491.139, 173.78, 487.427]},
{t: 'C', p: [173.664, 486.451, 171.889, 486.978, 171.702, 487.824]},
{t: 'C', p: [170.9, 491.449, 168.861, 494.11, 166.293, 496.502]},
{t: 'C', p: [164.097, 498.549, 162.235, 504.893, 162, 505.401]},
{t: 'C', p: [165.697, 500.145, 167.954, 497.399, 168.798, 496.599]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [155.224, 490.635]},
{t: 'C', p: [155.747, 490.265, 155.445, 489.774, 155.662, 489.442]},
{t: 'C', p: [156.615, 487.984, 157.916, 486.738, 157.934, 485]},
{t: 'C', p: [157.937, 484.723, 157.559, 484.414, 157.224, 484.638]},
{t: 'C', p: [156.947, 484.822, 156.605, 484.952, 156.497, 485.082]},
{t: 'C', p: [154.467, 487.531, 153.067, 490.202, 151.624, 493.014]},
{t: 'C', p: [151.441, 493.371, 150.297, 497.862, 150.61, 497.973]},
{t: 'C', p: [150.849, 498.058, 152.569, 493.877, 152.779, 493.763]},
{t: 'C', p: [154.042, 493.077, 154.054, 491.462, 155.224, 490.635]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [171.957, 510.179]},
{t: 'C', p: [172.401, 509.31, 173.977, 508.108, 173.864, 507.219]},
{t: 'C', p: [173.746, 506.291, 174.214, 504.848, 173.302, 505.536]},
{t: 'C', p: [172.045, 506.484, 168.596, 507.833, 168.326, 513.641]},
{t: 'C', p: [168.3, 514.212, 171.274, 511.519, 171.957, 510.179]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [186.4, 493.001]},
{t: 'C', p: [186.8, 492.333, 187.508, 492.806, 187.967, 492.543]},
{t: 'C', p: [188.615, 492.171, 189.226, 491.613, 189.518, 490.964]},
{t: 'C', p: [190.488, 488.815, 192.257, 486.995, 192.4, 484.601]},
{t: 'C', p: [190.909, 483.196, 190.23, 485.236, 189.6, 486.201]},
{t: 'C', p: [188.277, 484.554, 187.278, 486.428, 185.978, 486.947]},
{t: 'C', p: [185.908, 486.975, 185.695, 486.628, 185.62, 486.655]},
{t: 'C', p: [184.443, 487.095, 183.763, 488.176, 182.765, 488.957]},
{t: 'C', p: [182.594, 489.091, 182.189, 488.911, 182.042, 489.047]},
{t: 'C', p: [181.39, 489.65, 180.417, 489.975, 180.137, 490.657]},
{t: 'C', p: [179.027, 493.364, 175.887, 495.459, 174, 503.001]},
{t: 'C', p: [174.381, 503.91, 178.512, 496.359, 178.999, 495.661]},
{t: 'C', p: [179.835, 494.465, 179.953, 497.322, 181.229, 496.656]},
{t: 'C', p: [181.28, 496.629, 181.466, 496.867, 181.6, 497.001]},
{t: 'C', p: [181.794, 496.721, 182.012, 496.492, 182.4, 496.601]},
{t: 'C', p: [182.4, 496.201, 182.266, 495.645, 182.467, 495.486]},
{t: 'C', p: [183.704, 494.509, 183.62, 493.441, 184.4, 492.201]},
{t: 'C', p: [184.858, 492.99, 185.919, 492.271, 186.4, 493.001]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [246.2, 547.401]},
{t: 'C', p: [246.2, 547.401, 253.6, 527.001, 249.2, 515.801]},
{t: 'C', p: [249.2, 515.801, 260.6, 537.401, 256, 548.601]},
{t: 'C', p: [256, 548.601, 255.6, 538.201, 251.6, 533.201]},
{t: 'C', p: [251.6, 533.201, 247.6, 546.001, 246.2, 547.401]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [231.4, 544.801]},
{t: 'C', p: [231.4, 544.801, 236.8, 536.001, 228.8, 517.601]},
{t: 'C', p: [228.8, 517.601, 228, 538.001, 221.2, 549.001]},
{t: 'C', p: [221.2, 549.001, 235.4, 528.801, 231.4, 544.801]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [221.4, 542.801]},
{t: 'C', p: [221.4, 542.801, 221.2, 522.801, 221.6, 519.801]},
{t: 'C', p: [221.6, 519.801, 217.8, 536.401, 207.6, 546.001]},
{t: 'C', p: [207.6, 546.001, 222, 534.001, 221.4, 542.801]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [211.8, 510.801]},
{t: 'C', p: [211.8, 510.801, 217.8, 524.401, 207.8, 542.801]},
{t: 'C', p: [207.8, 542.801, 214.2, 530.601, 209.4, 523.601]},
{t: 'C', p: [209.4, 523.601, 212, 520.201, 211.8, 510.801]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [192.6, 542.401]},
{t: 'C', p: [192.6, 542.401, 191.6, 526.801, 193.4, 524.601]},
{t: 'C', p: [193.4, 524.601, 193.6, 518.201, 193.2, 517.201]},
{t: 'C', p: [193.2, 517.201, 197.2, 511.001, 197.4, 518.401]},
{t: 'C', p: [197.4, 518.401, 198.8, 526.201, 201.6, 530.801]},
{t: 'C', p: [201.6, 530.801, 205.2, 536.201, 205, 542.601]},
{t: 'C', p: [205, 542.601, 195, 512.401, 192.6, 542.401]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [189, 514.801]},
{t: 'C', p: [189, 514.801, 182.4, 525.601, 180.6, 544.601]},
{t: 'C', p: [180.6, 544.601, 179.2, 538.401, 183, 524.001]},
{t: 'C', p: [183, 524.001, 187.2, 508.601, 189, 514.801]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [167.2, 534.601]},
{t: 'C', p: [167.2, 534.601, 172.2, 529.201, 173.6, 524.201]},
{t: 'C', p: [173.6, 524.201, 177.2, 508.401, 170.8, 517.001]},
{t: 'C', p: [170.8, 517.001, 171, 525.001, 162.8, 532.401]},
{t: 'C', p: [162.8, 532.401, 167.6, 530.001, 167.2, 534.601]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [161.4, 529.601]},
{t: 'C', p: [161.4, 529.601, 164.8, 512.201, 165.6, 511.401]},
{t: 'C', p: [165.6, 511.401, 167.4, 508.001, 164.6, 511.201]},
{t: 'C', p: [164.6, 511.201, 155.8, 530.401, 151.8, 537.001]},
{t: 'C', p: [151.8, 537.001, 159.8, 527.801, 161.4, 529.601]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [155.6, 513.001]},
{t: 'C', p: [155.6, 513.001, 167.2, 490.601, 145.4, 516.401]},
{t: 'C', p: [145.4, 516.401, 156.4, 506.601, 155.6, 513.001]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [140.2, 498.401]},
{t: 'C', p: [140.2, 498.401, 145, 479.601, 147.6, 479.801]},
{t: 'C', p: [147.6, 479.801, 155.8, 470.801, 149.2, 481.401]},
{t: 'C', p: [149.2, 481.401, 143.2, 491.001, 143.8, 500.801]},
{t: 'C', p: [143.8, 500.801, 143.2, 491.201, 140.2, 498.401]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [470.5, 487]},
{t: 'C', p: [470.5, 487, 458.5, 477, 456, 473.5]},
{t: 'C', p: [456, 473.5, 469.5, 492, 469.5, 499]},
{t: 'C', p: [469.5, 499, 472, 491.5, 470.5, 487]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [476, 465]},
{t: 'C', p: [476, 465, 455, 450, 451.5, 442.5]},
{t: 'C', p: [451.5, 442.5, 478, 472, 478, 476.5]},
{t: 'C', p: [478, 476.5, 478.5, 467.5, 476, 465]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [493, 311]},
{t: 'C', p: [493, 311, 481, 303, 479.5, 305]},
{t: 'C', p: [479.5, 305, 490, 311.5, 492.5, 320]},
{t: 'C', p: [492.5, 320, 491, 311, 493, 311]},
{t: 'z', p: []}]},
{f: '#ccc', s: null, p: [{t: 'M', p: [501.5, 391.5]},
{t: 'L', p: [484, 379.5]},
{t: 'C', p: [484, 379.5, 503, 396.5, 503.5, 400.5]},
{t: 'L', p: [501.5, 391.5]},
{t: 'z', p: []}]},
{f: null, s: '#000', p: [{t: 'M', p: [110.75, 369]},
{t: 'L', p: [132.75, 373.75]}]},
{f: null, s: '#000', p: [{t: 'M', p: [161, 531]},
{t: 'C', p: [161, 531, 160.5, 527.5, 151.5, 538]}]},
{f: null, s: '#000', p: [{t: 'M', p: [166.5, 536]},
{t: 'C', p: [166.5, 536, 168.5, 529.5, 162, 534]}]},
{f: null, s: '#000', p: [{t: 'M', p: [220.5, 544.5]},
{t: 'C', p: [220.5, 544.5, 222, 533.5, 210.5, 546.5]}]}]
| 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 Newer versions of iPhoto include a Safari plugin which allows
* the browser to detect if iPhoto is installed. Adapted from detection code
* built into the Mac.com Gallery RSS feeds.
* @author brenneman@google.com (Shawn Brenneman)
* @see ../demos/useragent.html
*/
goog.provide('goog.userAgent.iphoto');
goog.require('goog.string');
goog.require('goog.userAgent');
(function() {
var hasIphoto = false;
var version = '';
/**
* The plugin description string contains the version number as in the form
* 'iPhoto 700'. This returns just the version number as a dotted string,
* e.g., '7.0.0', compatible with {@code goog.string.compareVersions}.
* @param {string} desc The version string.
* @return {string} The dotted version.
*/
function getIphotoVersion(desc) {
var matches = desc.match(/\d/g);
return matches.join('.');
}
if (goog.userAgent.WEBKIT &&
navigator.mimeTypes &&
navigator.mimeTypes.length > 0) {
var iphoto = navigator.mimeTypes['application/photo'];
if (iphoto) {
hasIphoto = true;
var description = iphoto['description'];
if (description) {
version = getIphotoVersion(description);
}
}
}
/**
* Whether we can detect that the user has iPhoto installed.
* @type {boolean}
*/
goog.userAgent.iphoto.HAS_IPHOTO = hasIphoto;
/**
* The version of iPhoto installed if found.
* @type {string}
*/
goog.userAgent.iphoto.VERSION = version;
})();
/**
* Whether the installed version of iPhoto is as new or newer than a given
* version.
* @param {string} version The version to check.
* @return {boolean} Whether the installed version of iPhoto is as new or newer
* than a given version.
*/
goog.userAgent.iphoto.isVersion = function(version) {
return goog.string.compareVersions(
goog.userAgent.iphoto.VERSION, version) >= 0;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Detection for whether the user has Picasa installed.
* Only Picasa versions 2 and later can be detected, and only from Firefox or
* Internet Explorer. Picasa for Linux cannot be detected.
*
* In the future, Picasa may provide access to the installed version number,
* but until then we can only detect that Picasa 2 or later is present.
*
* To check for Picasa on Internet Explorer requires using document.write, so
* this file must be included at page rendering time and cannot be imported
* later as part of a dynamically loaded module.
*
* @author brenneman@google.com (Shawn Brenneman)
* @see ../demos/useragent.html
*/
goog.provide('goog.userAgent.picasa');
goog.require('goog.string');
goog.require('goog.userAgent');
/**
* Variable name used to temporarily save the Picasa state in the global object
* in Internet Explorer.
* @type {string}
* @private
*/
goog.userAgent.picasa.IE_HAS_PICASA_ = 'hasPicasa';
(function() {
var hasPicasa = false;
if (goog.userAgent.IE) {
// In Internet Explorer, Picasa 2 can be detected using conditional comments
// due to some nice registry magic. The precise version number is not
// available, only the major version. This may be updated for Picasa 3. This
// check must pollute the global namespace.
goog.global[goog.userAgent.picasa.IE_HAS_PICASA_] = hasPicasa;
// NOTE(user): Some browsers do not like seeing
// slash-script anywhere in the text even if it's inside a string
// and escaped with a backslash, make a string in a way that
// avoids problems.
document.write(goog.string.subs(
'<!--[if gte Picasa 2]>' +
'<%s>' +
'this.%s=true;' +
'</%s>' +
'<![endif]-->',
'script', goog.userAgent.picasa.IE_HAS_PICASA_, 'script'));
hasPicasa = goog.global[goog.userAgent.picasa.IE_HAS_PICASA_];
// Unset the variable in a crude attempt to leave no trace.
goog.global[goog.userAgent.picasa.IE_HAS_PICASA_] = undefined;
} else if (navigator.mimeTypes &&
navigator.mimeTypes['application/x-picasa-detect']) {
// Picasa 2.x registers a file handler for the MIME-type
// 'application/x-picasa-detect' for detection in Firefox. Future versions
// may make precise version detection possible.
hasPicasa = true;
}
/**
* Whether we detect the user has Picasa installed.
* @type {boolean}
*/
goog.userAgent.picasa.HAS_PICASA = hasPicasa;
/**
* The installed version of Picasa. If Picasa is detected, this means it is
* version 2 or later. The precise version number is not yet available to the
* browser, this is a placeholder for later versions of Picasa.
* @type {string}
*/
goog.userAgent.picasa.VERSION = hasPicasa ? '2' : '';
})();
/**
* Whether the installed Picasa version is as new or newer than a given version.
* This is not yet relevant, we can't detect the true Picasa version number yet,
* but this may be possible in future Picasa releases.
* @param {string} version The version to check.
* @return {boolean} Whether the installed Picasa version is as new or newer
* than a given version.
*/
goog.userAgent.picasa.isVersion = function(version) {
return goog.string.compareVersions(
goog.userAgent.picasa.VERSION, version) >= 0;
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Functions for understanding the version of the browser.
* This is pulled out of product.js to ensure that only builds that need
* this functionality actually get it, without having to rely on the compiler
* to strip out unneeded pieces.
*
* TODO(nnaze): Move to more appropriate filename/namespace.
*
*/
goog.provide('goog.userAgent.product.isVersion');
goog.require('goog.userAgent.product');
/**
* @return {string} The string that describes the version number of the user
* agent product. This is a string rather than a number because it may
* contain 'b', 'a', and so on.
* @private
*/
goog.userAgent.product.determineVersion_ = function() {
// All browsers have different ways to detect the version and they all have
// different naming schemes.
if (goog.userAgent.product.FIREFOX) {
// Firefox/2.0.0.1 or Firefox/3.5.3
return goog.userAgent.product.getFirstRegExpGroup_(/Firefox\/([0-9.]+)/);
}
if (goog.userAgent.product.IE || goog.userAgent.product.OPERA) {
return goog.userAgent.VERSION;
}
if (goog.userAgent.product.CHROME) {
// Chrome/4.0.223.1
return goog.userAgent.product.getFirstRegExpGroup_(/Chrome\/([0-9.]+)/);
}
if (goog.userAgent.product.SAFARI) {
// Version/5.0.3
//
// NOTE: Before version 3, Safari did not report a product version number.
// The product version number for these browsers will be the empty string.
// They may be differentiated by WebKit version number in goog.userAgent.
return goog.userAgent.product.getFirstRegExpGroup_(/Version\/([0-9.]+)/);
}
if (goog.userAgent.product.IPHONE || goog.userAgent.product.IPAD) {
// Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1
// (KHTML, like Gecko) Version/3.0 Mobile/3A100a Safari/419.3
// Version is the browser version, Mobile is the build number. We combine
// the version string with the build number: 3.0.3A100a for the example.
var arr = goog.userAgent.product.execRegExp_(
/Version\/(\S+).*Mobile\/(\S+)/);
if (arr) {
return arr[1] + '.' + arr[2];
}
} else if (goog.userAgent.product.ANDROID) {
// Mozilla/5.0 (Linux; U; Android 0.5; en-us) AppleWebKit/522+
// (KHTML, like Gecko) Safari/419.3
//
// Mozilla/5.0 (Linux; U; Android 1.0; en-us; dream) AppleWebKit/525.10+
// (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2
//
// Prefer Version number if present, else make do with the OS number
var version = goog.userAgent.product.getFirstRegExpGroup_(
/Android\s+([0-9.]+)/);
if (version) {
return version;
}
return goog.userAgent.product.getFirstRegExpGroup_(/Version\/([0-9.]+)/);
} else if (goog.userAgent.product.CAMINO) {
return goog.userAgent.product.getFirstRegExpGroup_(/Camino\/([0-9.]+)/);
}
return '';
};
/**
* Return the first group of the given regex.
* @param {!RegExp} re Regular expression with at least one group.
* @return {string} Contents of the first group or an empty string if no match.
* @private
*/
goog.userAgent.product.getFirstRegExpGroup_ = function(re) {
var arr = goog.userAgent.product.execRegExp_(re);
return arr ? arr[1] : '';
};
/**
* Run regexp's exec() on the userAgent string.
* @param {!RegExp} re Regular expression.
* @return {Array} A result array, or null for no match.
* @private
*/
goog.userAgent.product.execRegExp_ = function(re) {
return re.exec(goog.userAgent.getUserAgentString());
};
/**
* The version of the user agent. This is a string because it might contain
* 'b' (as in beta) as well as multiple dots.
* @type {string}
*/
goog.userAgent.product.VERSION = goog.userAgent.product.determineVersion_();
/**
* Whether the user agent product version is higher or the same as the given
* version.
*
* @param {string|number} version The version to check.
* @return {boolean} Whether the user agent product version is higher or the
* same as the given version.
*/
goog.userAgent.product.isVersion = function(version) {
return goog.string.compareVersions(
goog.userAgent.product.VERSION, version) >= 0;
};
| 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 Detects the Adobe Reader PDF browser plugin.
*
* @author chrisn@google.com (Chris Nokleberg)
* @see ../demos/useragent.html
*/
/** @suppress {extraProvide} */
goog.provide('goog.userAgent.adobeReader');
goog.require('goog.string');
goog.require('goog.userAgent');
(function() {
var version = '';
if (goog.userAgent.IE) {
var detectOnIe = function(classId) {
/** @preserveTry */
try {
new ActiveXObject(classId);
return true;
} catch (ex) {
return false;
}
};
if (detectOnIe('AcroPDF.PDF.1')) {
version = '7';
} else if (detectOnIe('PDF.PdfCtrl.6')) {
version = '6';
}
// TODO(chrisn): Add detection for previous versions if anyone needs them.
} else {
if (navigator.mimeTypes && navigator.mimeTypes.length > 0) {
var mimeType = navigator.mimeTypes['application/pdf'];
if (mimeType && mimeType.enabledPlugin) {
var description = mimeType.enabledPlugin.description;
if (description && description.indexOf('Adobe') != -1) {
// Newer plugins do not include the version in the description, so we
// default to 7.
version = description.indexOf('Version') != -1 ?
description.split('Version')[1] : '7';
}
}
}
}
/**
* Whether we detect the user has the Adobe Reader browser plugin installed.
* @type {boolean}
*/
goog.userAgent.adobeReader.HAS_READER = !!version;
/**
* The version of the installed Adobe Reader plugin. Versions after 7
* will all be reported as '7'.
* @type {string}
*/
goog.userAgent.adobeReader.VERSION = version;
/**
* On certain combinations of platform/browser/plugin, a print dialog
* can be shown for PDF files without a download dialog or making the
* PDF visible to the user, by loading the PDF into a hidden iframe.
*
* Currently this variable is true if Adobe Reader version 6 or later
* is detected on Windows.
*
* @type {boolean}
*/
goog.userAgent.adobeReader.SILENT_PRINT = goog.userAgent.WINDOWS &&
goog.string.compareVersions(version, '6') >= 0;
})();
| 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 Rendering engine detection.
* @see <a href="http://www.useragentstring.com/">User agent strings</a>
* For information on the browser brand (such as Safari versus Chrome), see
* goog.userAgent.product.
* @see ../demos/useragent.html
*/
goog.provide('goog.userAgent');
goog.require('goog.string');
/**
* @define {boolean} Whether we know at compile-time that the browser is IE.
*/
goog.userAgent.ASSUME_IE = false;
/**
* @define {boolean} Whether we know at compile-time that the browser is GECKO.
*/
goog.userAgent.ASSUME_GECKO = false;
/**
* @define {boolean} Whether we know at compile-time that the browser is WEBKIT.
*/
goog.userAgent.ASSUME_WEBKIT = false;
/**
* @define {boolean} Whether we know at compile-time that the browser is a
* mobile device running WebKit e.g. iPhone or Android.
*/
goog.userAgent.ASSUME_MOBILE_WEBKIT = false;
/**
* @define {boolean} Whether we know at compile-time that the browser is OPERA.
*/
goog.userAgent.ASSUME_OPERA = false;
/**
* @define {boolean} Whether the {@code goog.userAgent.isVersion} function will
* return true for any version.
*/
goog.userAgent.ASSUME_ANY_VERSION = false;
/**
* Whether we know the browser engine at compile-time.
* @type {boolean}
* @private
*/
goog.userAgent.BROWSER_KNOWN_ =
goog.userAgent.ASSUME_IE ||
goog.userAgent.ASSUME_GECKO ||
goog.userAgent.ASSUME_MOBILE_WEBKIT ||
goog.userAgent.ASSUME_WEBKIT ||
goog.userAgent.ASSUME_OPERA;
/**
* Returns the userAgent string for the current browser.
* Some user agents (I'm thinking of you, Gears WorkerPool) do not expose a
* navigator object off the global scope. In that case we return null.
*
* @return {?string} The userAgent string or null if there is none.
*/
goog.userAgent.getUserAgentString = function() {
return goog.global['navigator'] ? goog.global['navigator'].userAgent : null;
};
/**
* @return {Object} The native navigator object.
*/
goog.userAgent.getNavigator = function() {
// Need a local navigator reference instead of using the global one,
// to avoid the rare case where they reference different objects.
// (in a WorkerPool, for example).
return goog.global['navigator'];
};
/**
* Initializer for goog.userAgent.
*
* This is a named function so that it can be stripped via the jscompiler
* option for stripping types.
* @private
*/
goog.userAgent.init_ = function() {
/**
* Whether the user agent string denotes Opera.
* @type {boolean}
* @private
*/
goog.userAgent.detectedOpera_ = false;
/**
* Whether the user agent string denotes Internet Explorer. This includes
* other browsers using Trident as its rendering engine. For example AOL
* and Netscape 8
* @type {boolean}
* @private
*/
goog.userAgent.detectedIe_ = false;
/**
* Whether the user agent string denotes WebKit. WebKit is the rendering
* engine that Safari, Android and others use.
* @type {boolean}
* @private
*/
goog.userAgent.detectedWebkit_ = false;
/**
* Whether the user agent string denotes a mobile device.
* @type {boolean}
* @private
*/
goog.userAgent.detectedMobile_ = false;
/**
* Whether the user agent string denotes Gecko. Gecko is the rendering
* engine used by Mozilla, Mozilla Firefox, Camino and many more.
* @type {boolean}
* @private
*/
goog.userAgent.detectedGecko_ = false;
var ua;
if (!goog.userAgent.BROWSER_KNOWN_ &&
(ua = goog.userAgent.getUserAgentString())) {
var navigator = goog.userAgent.getNavigator();
goog.userAgent.detectedOpera_ = ua.indexOf('Opera') == 0;
goog.userAgent.detectedIe_ = !goog.userAgent.detectedOpera_ &&
ua.indexOf('MSIE') != -1;
goog.userAgent.detectedWebkit_ = !goog.userAgent.detectedOpera_ &&
ua.indexOf('WebKit') != -1;
// WebKit also gives navigator.product string equal to 'Gecko'.
goog.userAgent.detectedMobile_ = goog.userAgent.detectedWebkit_ &&
ua.indexOf('Mobile') != -1;
goog.userAgent.detectedGecko_ = !goog.userAgent.detectedOpera_ &&
!goog.userAgent.detectedWebkit_ && navigator.product == 'Gecko';
}
};
if (!goog.userAgent.BROWSER_KNOWN_) {
goog.userAgent.init_();
}
/**
* Whether the user agent is Opera.
* @type {boolean}
*/
goog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ?
goog.userAgent.ASSUME_OPERA : goog.userAgent.detectedOpera_;
/**
* Whether the user agent is Internet Explorer. This includes other browsers
* using Trident as its rendering engine. For example AOL and Netscape 8
* @type {boolean}
*/
goog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ?
goog.userAgent.ASSUME_IE : goog.userAgent.detectedIe_;
/**
* Whether the user agent is Gecko. Gecko is the rendering engine used by
* Mozilla, Mozilla Firefox, Camino and many more.
* @type {boolean}
*/
goog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ?
goog.userAgent.ASSUME_GECKO :
goog.userAgent.detectedGecko_;
/**
* Whether the user agent is WebKit. WebKit is the rendering engine that
* Safari, Android and others use.
* @type {boolean}
*/
goog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ?
goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT :
goog.userAgent.detectedWebkit_;
/**
* Whether the user agent is running on a mobile device.
* @type {boolean}
*/
goog.userAgent.MOBILE = goog.userAgent.ASSUME_MOBILE_WEBKIT ||
goog.userAgent.detectedMobile_;
/**
* Used while transitioning code to use WEBKIT instead.
* @type {boolean}
* @deprecated Use {@link goog.userAgent.product.SAFARI} instead.
* TODO(nicksantos): Delete this from goog.userAgent.
*/
goog.userAgent.SAFARI = goog.userAgent.WEBKIT;
/**
* @return {string} the platform (operating system) the user agent is running
* on. Default to empty string because navigator.platform may not be defined
* (on Rhino, for example).
* @private
*/
goog.userAgent.determinePlatform_ = function() {
var navigator = goog.userAgent.getNavigator();
return navigator && navigator.platform || '';
};
/**
* The platform (operating system) the user agent is running on. Default to
* empty string because navigator.platform may not be defined (on Rhino, for
* example).
* @type {string}
*/
goog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();
/**
* @define {boolean} Whether the user agent is running on a Macintosh operating
* system.
*/
goog.userAgent.ASSUME_MAC = false;
/**
* @define {boolean} Whether the user agent is running on a Windows operating
* system.
*/
goog.userAgent.ASSUME_WINDOWS = false;
/**
* @define {boolean} Whether the user agent is running on a Linux operating
* system.
*/
goog.userAgent.ASSUME_LINUX = false;
/**
* @define {boolean} Whether the user agent is running on a X11 windowing
* system.
*/
goog.userAgent.ASSUME_X11 = false;
/**
* @define {boolean} Whether the user agent is running on Android.
*/
goog.userAgent.ASSUME_ANDROID = false;
/**
* @define {boolean} Whether the user agent is running on an iPhone.
*/
goog.userAgent.ASSUME_IPHONE = false;
/**
* @define {boolean} Whether the user agent is running on an iPad.
*/
goog.userAgent.ASSUME_IPAD = false;
/**
* @type {boolean}
* @private
*/
goog.userAgent.PLATFORM_KNOWN_ =
goog.userAgent.ASSUME_MAC ||
goog.userAgent.ASSUME_WINDOWS ||
goog.userAgent.ASSUME_LINUX ||
goog.userAgent.ASSUME_X11 ||
goog.userAgent.ASSUME_ANDROID ||
goog.userAgent.ASSUME_IPHONE ||
goog.userAgent.ASSUME_IPAD;
/**
* Initialize the goog.userAgent constants that define which platform the user
* agent is running on.
* @private
*/
goog.userAgent.initPlatform_ = function() {
/**
* Whether the user agent is running on a Macintosh operating system.
* @type {boolean}
* @private
*/
goog.userAgent.detectedMac_ = goog.string.contains(goog.userAgent.PLATFORM,
'Mac');
/**
* Whether the user agent is running on a Windows operating system.
* @type {boolean}
* @private
*/
goog.userAgent.detectedWindows_ = goog.string.contains(
goog.userAgent.PLATFORM, 'Win');
/**
* Whether the user agent is running on a Linux operating system.
* @type {boolean}
* @private
*/
goog.userAgent.detectedLinux_ = goog.string.contains(goog.userAgent.PLATFORM,
'Linux');
/**
* Whether the user agent is running on a X11 windowing system.
* @type {boolean}
* @private
*/
goog.userAgent.detectedX11_ = !!goog.userAgent.getNavigator() &&
goog.string.contains(goog.userAgent.getNavigator()['appVersion'] || '',
'X11');
// Need user agent string for Android/IOS detection
var ua = goog.userAgent.getUserAgentString();
/**
* Whether the user agent is running on Android.
* @type {boolean}
* @private
*/
goog.userAgent.detectedAndroid_ = !!ua && ua.indexOf('Android') >= 0;
/**
* Whether the user agent is running on an iPhone.
* @type {boolean}
* @private
*/
goog.userAgent.detectedIPhone_ = !!ua && ua.indexOf('iPhone') >= 0;
/**
* Whether the user agent is running on an iPad.
* @type {boolean}
* @private
*/
goog.userAgent.detectedIPad_ = !!ua && ua.indexOf('iPad') >= 0;
};
if (!goog.userAgent.PLATFORM_KNOWN_) {
goog.userAgent.initPlatform_();
}
/**
* Whether the user agent is running on a Macintosh operating system.
* @type {boolean}
*/
goog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_MAC : goog.userAgent.detectedMac_;
/**
* Whether the user agent is running on a Windows operating system.
* @type {boolean}
*/
goog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_WINDOWS : goog.userAgent.detectedWindows_;
/**
* Whether the user agent is running on a Linux operating system.
* @type {boolean}
*/
goog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_LINUX : goog.userAgent.detectedLinux_;
/**
* Whether the user agent is running on a X11 windowing system.
* @type {boolean}
*/
goog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_X11 : goog.userAgent.detectedX11_;
/**
* Whether the user agent is running on Android.
* @type {boolean}
*/
goog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_ANDROID : goog.userAgent.detectedAndroid_;
/**
* Whether the user agent is running on an iPhone.
* @type {boolean}
*/
goog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_IPHONE : goog.userAgent.detectedIPhone_;
/**
* Whether the user agent is running on an iPad.
* @type {boolean}
*/
goog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_IPAD : goog.userAgent.detectedIPad_;
/**
* @return {string} The string that describes the version number of the user
* agent.
* @private
*/
goog.userAgent.determineVersion_ = function() {
// All browsers have different ways to detect the version and they all have
// different naming schemes.
// version is a string rather than a number because it may contain 'b', 'a',
// and so on.
var version = '', re;
if (goog.userAgent.OPERA && goog.global['opera']) {
var operaVersion = goog.global['opera'].version;
version = typeof operaVersion == 'function' ? operaVersion() : operaVersion;
} else {
if (goog.userAgent.GECKO) {
re = /rv\:([^\);]+)(\)|;)/;
} else if (goog.userAgent.IE) {
re = /MSIE\s+([^\);]+)(\)|;)/;
} else if (goog.userAgent.WEBKIT) {
// WebKit/125.4
re = /WebKit\/(\S+)/;
}
if (re) {
var arr = re.exec(goog.userAgent.getUserAgentString());
version = arr ? arr[1] : '';
}
}
if (goog.userAgent.IE) {
// IE9 can be in document mode 9 but be reporting an inconsistent user agent
// version. If it is identifying as a version lower than 9 we take the
// documentMode as the version instead. IE8 has similar behavior.
// It is recommended to set the X-UA-Compatible header to ensure that IE9
// uses documentMode 9.
var docMode = goog.userAgent.getDocumentMode_();
if (docMode > parseFloat(version)) {
return String(docMode);
}
}
return version;
};
/**
* @return {number|undefined} Returns the document mode (for testing).
* @private
*/
goog.userAgent.getDocumentMode_ = function() {
// NOTE(user): goog.userAgent may be used in context where there is no DOM.
var doc = goog.global['document'];
return doc ? doc['documentMode'] : undefined;
};
/**
* The version of the user agent. This is a string because it might contain
* 'b' (as in beta) as well as multiple dots.
* @type {string}
*/
goog.userAgent.VERSION = goog.userAgent.determineVersion_();
/**
* Compares two version numbers.
*
* @param {string} v1 Version of first item.
* @param {string} v2 Version of second item.
*
* @return {number} 1 if first argument is higher
* 0 if arguments are equal
* -1 if second argument is higher.
* @deprecated Use goog.string.compareVersions.
*/
goog.userAgent.compare = function(v1, v2) {
return goog.string.compareVersions(v1, v2);
};
/**
* Cache for {@link goog.userAgent.isVersion}. Calls to compareVersions are
* surprisingly expensive and as a browsers version number is unlikely to change
* during a session we cache the results.
* @type {Object}
* @private
*/
goog.userAgent.isVersionCache_ = {};
/**
* Whether the user agent version is higher or the same as the given version.
* NOTE: When checking the version numbers for Firefox and Safari, be sure to
* use the engine's version, not the browser's version number. For example,
* Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11.
* Opera and Internet Explorer versions match the product release number.<br>
* @see <a href="http://en.wikipedia.org/wiki/Safari_version_history">
* Webkit</a>
* @see <a href="http://en.wikipedia.org/wiki/Gecko_engine">Gecko</a>
*
* @param {string|number} version The version to check.
* @return {boolean} Whether the user agent version is higher or the same as
* the given version.
*/
goog.userAgent.isVersion = function(version) {
return goog.userAgent.ASSUME_ANY_VERSION ||
goog.userAgent.isVersionCache_[version] ||
(goog.userAgent.isVersionCache_[version] =
goog.string.compareVersions(goog.userAgent.VERSION, version) >= 0);
};
/**
* Whether the IE effective document mode is higher or the same as the given
* document mode version.
* NOTE: Only for IE, return false for another browser.
*
* @param {number} documentMode The document mode version to check.
* @return {boolean} Whether the IE effective document mode is higher or the
* same as the given version.
*/
goog.userAgent.isDocumentMode = function(documentMode) {
return goog.userAgent.IE && goog.userAgent.DOCUMENT_MODE >= documentMode;
};
/**
* For IE version < 7, documentMode is undefined, so attempt to use the
* CSS1Compat property to see if we are in standards mode. If we are in
* standards mode, treat the browser version as the document mode. Otherwise,
* IE is emulating version 5.
* @type {number|undefined}
* @const
*/
goog.userAgent.DOCUMENT_MODE = (function() {
var doc = goog.global['document'];
if (!doc || !goog.userAgent.IE) {
return undefined;
}
var mode = goog.userAgent.getDocumentMode_();
return mode || (doc['compatMode'] == 'CSS1Compat' ?
parseInt(goog.userAgent.VERSION, 10) : 5);
})();
| 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 Flash detection.
* @see ../demos/useragent.html
*/
goog.provide('goog.userAgent.flash');
goog.require('goog.string');
/**
* @define {boolean} Whether we know at compile-time that the browser doesn't
* have flash.
*/
goog.userAgent.flash.ASSUME_NO_FLASH = false;
/**
* Whether we can detect that the browser has flash
* @type {boolean}
* @private
*/
goog.userAgent.flash.detectedFlash_ = false;
/**
* Full version information of flash installed, in form 7.0.61
* @type {string}
* @private
*/
goog.userAgent.flash.detectedFlashVersion_ = '';
/**
* Initializer for goog.userAgent.flash
*
* This is a named function so that it can be stripped via the jscompiler if
* goog.userAgent.flash.ASSUME_NO_FLASH is true.
* @private
*/
goog.userAgent.flash.init_ = function() {
if (navigator.plugins && navigator.plugins.length) {
var plugin = navigator.plugins['Shockwave Flash'];
if (plugin) {
goog.userAgent.flash.detectedFlash_ = true;
if (plugin.description) {
goog.userAgent.flash.detectedFlashVersion_ =
goog.userAgent.flash.getVersion_(plugin.description);
}
}
if (navigator.plugins['Shockwave Flash 2.0']) {
goog.userAgent.flash.detectedFlash_ = true;
goog.userAgent.flash.detectedFlashVersion_ = '2.0.0.11';
}
} else if (navigator.mimeTypes && navigator.mimeTypes.length) {
var mimeType = navigator.mimeTypes['application/x-shockwave-flash'];
goog.userAgent.flash.detectedFlash_ = mimeType && mimeType.enabledPlugin;
if (goog.userAgent.flash.detectedFlash_) {
goog.userAgent.flash.detectedFlashVersion_ =
goog.userAgent.flash.getVersion_(mimeType.enabledPlugin.description);
}
} else {
/** @preserveTry */
try {
// Try 7 first, since we know we can use GetVariable with it
var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.7');
goog.userAgent.flash.detectedFlash_ = true;
goog.userAgent.flash.detectedFlashVersion_ =
goog.userAgent.flash.getVersion_(ax.GetVariable('$version'));
} catch (e) {
// Try 6 next, some versions are known to crash with GetVariable calls
/** @preserveTry */
try {
var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
goog.userAgent.flash.detectedFlash_ = true;
// First public version of Flash 6
goog.userAgent.flash.detectedFlashVersion_ = '6.0.21';
} catch (e2) {
/** @preserveTry */
try {
// Try the default activeX
var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
goog.userAgent.flash.detectedFlash_ = true;
goog.userAgent.flash.detectedFlashVersion_ =
goog.userAgent.flash.getVersion_(ax.GetVariable('$version'));
} catch (e3) {
// No flash
}
}
}
}
};
/**
* Derived from Apple's suggested sniffer.
* @param {string} desc e.g. Shockwave Flash 7.0 r61.
* @return {string} 7.0.61.
* @private
*/
goog.userAgent.flash.getVersion_ = function(desc) {
var matches = desc.match(/[\d]+/g);
matches.length = 3; // To standardize IE vs FF
return matches.join('.');
};
if (!goog.userAgent.flash.ASSUME_NO_FLASH) {
goog.userAgent.flash.init_();
}
/**
* Whether we can detect that the browser has flash
* @type {boolean}
*/
goog.userAgent.flash.HAS_FLASH = goog.userAgent.flash.detectedFlash_;
/**
* Full version information of flash installed, in form 7.0.61
* @type {string}
*/
goog.userAgent.flash.VERSION = goog.userAgent.flash.detectedFlashVersion_;
/**
* Whether the installed flash version is as new or newer than a given version.
* @param {string} version The version to check.
* @return {boolean} Whether the installed flash version is as new or newer
* than a given version.
*/
goog.userAgent.flash.isVersion = function(version) {
return goog.string.compareVersions(goog.userAgent.flash.VERSION,
version) >= 0;
};
| 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 Utilities for getting details about the user's platform.
*/
goog.provide('goog.userAgent.platform');
goog.require('goog.userAgent');
/**
* Detects the version of Windows or Mac OS that is running.
*
* @private
* @return {string} The platform version.
*/
goog.userAgent.platform.determineVersion_ = function() {
var version = '', re;
if (goog.userAgent.WINDOWS) {
re = /Windows NT ([0-9.]+)/;
var match = re.exec(goog.userAgent.getUserAgentString());
if (match) {
return match[1];
} else {
return '0';
}
} else if (goog.userAgent.MAC) {
re = /10[_.][0-9_.]+/;
var match = re.exec(goog.userAgent.getUserAgentString());
// Note: some old versions of Camino do not report an OSX version.
// Default to 10.
return match ? match[0].replace(/_/g, '.') : '10';
} else if (goog.userAgent.ANDROID) {
re = /Android\s+([^\);]+)(\)|;)/;
var match = re.exec(goog.userAgent.getUserAgentString());
return match ? match[1] : '';
} else if (goog.userAgent.IPHONE || goog.userAgent.IPAD) {
re = /(?:iPhone|CPU)\s+OS\s+(\S+)/;
var match = re.exec(goog.userAgent.getUserAgentString());
// Report the version as x.y.z and not x_y_z
return match ? match[1].replace(/_/g, '.') : '';
}
return '';
};
/**
* The version of the platform. We only determine the version for Windows and
* Mac, since it doesn't make much sense on Linux. For Windows, we only look at
* the NT version. Non-NT-based versions (e.g. 95, 98, etc.) are given version
* 0.0
* @type {string}
*/
goog.userAgent.platform.VERSION = goog.userAgent.platform.determineVersion_();
/**
* Whether the user agent platform version is higher or the same as the given
* version.
*
* @param {string|number} version The version to check.
* @return {boolean} Whether the user agent platform version is higher or the
* same as the given version.
*/
goog.userAgent.platform.isVersion = function(version) {
return goog.string.compareVersions(
goog.userAgent.platform.VERSION, version) >= 0;
};
| 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 Detects the specific browser and not just the rendering engine.
*
*/
goog.provide('goog.userAgent.product');
goog.require('goog.userAgent');
/**
* @define {boolean} Whether the code is running on the Firefox web browser.
*/
goog.userAgent.product.ASSUME_FIREFOX = false;
/**
* @define {boolean} Whether the code is running on the Camino web browser.
*/
goog.userAgent.product.ASSUME_CAMINO = false;
/**
* @define {boolean} Whether we know at compile-time that the product is an
* iPhone.
*/
goog.userAgent.product.ASSUME_IPHONE = false;
/**
* @define {boolean} Whether we know at compile-time that the product is an
* iPad.
*/
goog.userAgent.product.ASSUME_IPAD = false;
/**
* @define {boolean} Whether we know at compile-time that the product is an
* Android phone.
*/
goog.userAgent.product.ASSUME_ANDROID = false;
/**
* @define {boolean} Whether the code is running on the Chrome web browser.
*/
goog.userAgent.product.ASSUME_CHROME = false;
/**
* @define {boolean} Whether the code is running on the Safari web browser.
*/
goog.userAgent.product.ASSUME_SAFARI = false;
/**
* Whether we know the product type at compile-time.
* @type {boolean}
* @private
*/
goog.userAgent.product.PRODUCT_KNOWN_ =
goog.userAgent.ASSUME_IE ||
goog.userAgent.ASSUME_OPERA ||
goog.userAgent.product.ASSUME_FIREFOX ||
goog.userAgent.product.ASSUME_CAMINO ||
goog.userAgent.product.ASSUME_IPHONE ||
goog.userAgent.product.ASSUME_IPAD ||
goog.userAgent.product.ASSUME_ANDROID ||
goog.userAgent.product.ASSUME_CHROME ||
goog.userAgent.product.ASSUME_SAFARI;
/**
* Right now we just focus on Tier 1-3 browsers at:
* http://wiki/Nonconf/ProductPlatformGuidelines
* As well as the YUI grade A browsers at:
* http://developer.yahoo.com/yui/articles/gbs/
*
* @private
*/
goog.userAgent.product.init_ = function() {
/**
* Whether the code is running on the Firefox web browser.
* @type {boolean}
* @private
*/
goog.userAgent.product.detectedFirefox_ = false;
/**
* Whether the code is running on the Camino web browser.
* @type {boolean}
* @private
*/
goog.userAgent.product.detectedCamino_ = false;
/**
* Whether the code is running on an iPhone or iPod touch.
* @type {boolean}
* @private
*/
goog.userAgent.product.detectedIphone_ = false;
/**
* Whether the code is running on an iPad
* @type {boolean}
* @private
*/
goog.userAgent.product.detectedIpad_ = false;
/**
* Whether the code is running on the default browser on an Android phone.
* @type {boolean}
* @private
*/
goog.userAgent.product.detectedAndroid_ = false;
/**
* Whether the code is running on the Chrome web browser.
* @type {boolean}
* @private
*/
goog.userAgent.product.detectedChrome_ = false;
/**
* Whether the code is running on the Safari web browser.
* @type {boolean}
* @private
*/
goog.userAgent.product.detectedSafari_ = false;
var ua = goog.userAgent.getUserAgentString();
if (!ua) {
return;
}
// The order of the if-statements in the following code is important.
// For example, in the WebKit section, we put Chrome in front of Safari
// because the string 'Safari' is present on both of those browsers'
// userAgent strings as well as the string we are looking for.
// The idea is to prevent accidental detection of more than one client.
if (ua.indexOf('Firefox') != -1) {
goog.userAgent.product.detectedFirefox_ = true;
} else if (ua.indexOf('Camino') != -1) {
goog.userAgent.product.detectedCamino_ = true;
} else if (ua.indexOf('iPhone') != -1 || ua.indexOf('iPod') != -1) {
goog.userAgent.product.detectedIphone_ = true;
} else if (ua.indexOf('iPad') != -1) {
goog.userAgent.product.detectedIpad_ = true;
} else if (ua.indexOf('Android') != -1) {
goog.userAgent.product.detectedAndroid_ = true;
} else if (ua.indexOf('Chrome') != -1) {
goog.userAgent.product.detectedChrome_ = true;
} else if (ua.indexOf('Safari') != -1) {
goog.userAgent.product.detectedSafari_ = true;
}
};
if (!goog.userAgent.product.PRODUCT_KNOWN_) {
goog.userAgent.product.init_();
}
/**
* Whether the code is running on the Opera web browser.
* @type {boolean}
*/
goog.userAgent.product.OPERA = goog.userAgent.OPERA;
/**
* Whether the code is running on an IE web browser.
* @type {boolean}
*/
goog.userAgent.product.IE = goog.userAgent.IE;
/**
* Whether the code is running on the Firefox web browser.
* @type {boolean}
*/
goog.userAgent.product.FIREFOX = goog.userAgent.product.PRODUCT_KNOWN_ ?
goog.userAgent.product.ASSUME_FIREFOX :
goog.userAgent.product.detectedFirefox_;
/**
* Whether the code is running on the Camino web browser.
* @type {boolean}
*/
goog.userAgent.product.CAMINO = goog.userAgent.product.PRODUCT_KNOWN_ ?
goog.userAgent.product.ASSUME_CAMINO :
goog.userAgent.product.detectedCamino_;
/**
* Whether the code is running on an iPhone or iPod touch.
* @type {boolean}
*/
goog.userAgent.product.IPHONE = goog.userAgent.product.PRODUCT_KNOWN_ ?
goog.userAgent.product.ASSUME_IPHONE :
goog.userAgent.product.detectedIphone_;
/**
* Whether the code is running on an iPad.
* @type {boolean}
*/
goog.userAgent.product.IPAD = goog.userAgent.product.PRODUCT_KNOWN_ ?
goog.userAgent.product.ASSUME_IPAD :
goog.userAgent.product.detectedIpad_;
/**
* Whether the code is running on the default browser on an Android phone.
* @type {boolean}
*/
goog.userAgent.product.ANDROID = goog.userAgent.product.PRODUCT_KNOWN_ ?
goog.userAgent.product.ASSUME_ANDROID :
goog.userAgent.product.detectedAndroid_;
/**
* Whether the code is running on the Chrome web browser.
* @type {boolean}
*/
goog.userAgent.product.CHROME = goog.userAgent.product.PRODUCT_KNOWN_ ?
goog.userAgent.product.ASSUME_CHROME :
goog.userAgent.product.detectedChrome_;
/**
* Whether the code is running on the Safari web browser.
* @type {boolean}
*/
goog.userAgent.product.SAFARI = goog.userAgent.product.PRODUCT_KNOWN_ ?
goog.userAgent.product.ASSUME_SAFARI :
goog.userAgent.product.detectedSafari_;
| 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 Detection of JScript version.
*
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.userAgent.jscript');
goog.require('goog.string');
/**
* @define {boolean} True if it is known at compile time that the runtime
* environment will not be using JScript.
*/
goog.userAgent.jscript.ASSUME_NO_JSCRIPT = false;
/**
* Initializer for goog.userAgent.jscript. Detects if the user agent is using
* Microsoft JScript and which version of it.
*
* This is a named function so that it can be stripped via the jscompiler
* option for stripping types.
* @private
*/
goog.userAgent.jscript.init_ = function() {
var hasScriptEngine = 'ScriptEngine' in goog.global;
/**
* @type {boolean}
* @private
*/
goog.userAgent.jscript.DETECTED_HAS_JSCRIPT_ =
hasScriptEngine && goog.global['ScriptEngine']() == 'JScript';
/**
* @type {string}
* @private
*/
goog.userAgent.jscript.DETECTED_VERSION_ =
goog.userAgent.jscript.DETECTED_HAS_JSCRIPT_ ?
(goog.global['ScriptEngineMajorVersion']() + '.' +
goog.global['ScriptEngineMinorVersion']() + '.' +
goog.global['ScriptEngineBuildVersion']()) :
'0';
};
if (!goog.userAgent.jscript.ASSUME_NO_JSCRIPT) {
goog.userAgent.jscript.init_();
}
/**
* Whether we detect that the user agent is using Microsoft JScript.
* @type {boolean}
*/
goog.userAgent.jscript.HAS_JSCRIPT = goog.userAgent.jscript.ASSUME_NO_JSCRIPT ?
false : goog.userAgent.jscript.DETECTED_HAS_JSCRIPT_;
/**
* The installed version of JScript.
* @type {string}
*/
goog.userAgent.jscript.VERSION = goog.userAgent.jscript.ASSUME_NO_JSCRIPT ?
'0' : goog.userAgent.jscript.DETECTED_VERSION_;
/**
* Whether the installed version of JScript is as new or newer than a given
* version.
* @param {string} version The version to check.
* @return {boolean} Whether the installed version of JScript is as new or
* newer than the given version.
*/
goog.userAgent.jscript.isVersion = function(version) {
return goog.string.compareVersions(goog.userAgent.jscript.VERSION,
version) >= 0;
};
| 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 Provides a function to schedule running a function as soon
* as possible after the current JS execution stops and yields to the event
* loop.
*
*/
goog.provide('goog.async.nextTick');
/**
* Fires the provided callbacks as soon as possible after the current JS
* execution context. setTimeout(…, 0) always takes at least 5ms for legacy
* reasons.
* @param {function()} callback Callback function to fire as soon as possible.
* @param {Object=} opt_context Object in whose scope to call the listener.
*/
goog.async.nextTick = function(callback, opt_context) {
var cb = callback;
if (opt_context) {
cb = goog.bind(callback, opt_context);
}
if (!goog.async.nextTick.setImmediate_) {
goog.async.nextTick.setImmediate_ = goog.async.nextTick.getSetImmediate_();
}
goog.async.nextTick.setImmediate_(cb);
};
/**
* Cache for the setImmediate implementation.
* @type {function(function())}
* @private
*/
goog.async.nextTick.setImmediate_;
/**
* Determines the best possible implementation to run a function as soon as
* the JS event loop is idle.
* @return {function(function())} The "setImmediate" implementation.
* @private
*/
goog.async.nextTick.getSetImmediate_ = function() {
// Introduced and currently only supported by IE10.
if (typeof goog.global.setImmediate === 'function') {
return /** @type {function(function())} */ (
goog.bind(goog.global.setImmediate, goog.global));
}
// Create a private message channel and use it to postMessage empty messages
// to ourselves.
var Channel = goog.global['MessageChannel'];
// If MessageChannel is not available and we are in a browser, implement
// an iframe based polyfill in browsers that have postMessage and
// document.addEventListener. The latter excludes IE8 because it has a
// synchronous postMessage implementation.
if (typeof Channel === 'undefined' && typeof window !== 'undefined' &&
window.postMessage && window.addEventListener) {
/** @constructor */
Channel = function() {
// Make an empty, invisible iframe.
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = '';
document.body.appendChild(iframe);
var win = iframe.contentWindow;
var doc = win.document;
doc.open();
doc.write('');
doc.close();
var message = 'callImmediate' + Math.random();
var origin = win.location.protocol + '//' + win.location.host;
var onmessage = goog.bind(function(e) {
// Validate origin and message to make sure that this message was
// intended for us.
if (e.origin != origin && e.data != message) {
return;
}
this['port1'].onmessage();
}, this);
win.addEventListener('message', onmessage, false);
this['port1'] = {};
this['port2'] = {
postMessage: function() {
win.postMessage(message, origin);
}
};
};
}
if (typeof Channel !== 'undefined') {
var channel = new Channel();
// Use a fifo linked list to call callbacks in the right order.
var head = {};
var tail = head;
channel['port1'].onmessage = function() {
head = head.next;
var cb = head.cb;
head.cb = null;
cb();
};
return function(cb) {
tail.next = {
cb: cb
};
tail = tail.next;
channel['port2'].postMessage(0);
};
}
// Implementation for IE6-8: Script elements fire an asynchronous
// onreadystatechange event when inserted into the DOM.
if (typeof document !== 'undefined' && 'onreadystatechange' in
document.createElement('script')) {
return function(cb) {
var script = document.createElement('script');
script.onreadystatechange = function() {
// Clean up and call the callback.
script.onreadystatechange = null;
script.parentNode.removeChild(script);
script = null;
cb();
cb = null;
};
document.documentElement.appendChild(script);
};
}
// Fall back to setTimeout with 0. In browsers this creates a delay of 5ms
// or more.
return function(cb) {
goog.global.setTimeout(cb, 0);
};
};
| 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 Defines a class useful for handling functions that must be
* invoked later when some condition holds. Examples include deferred function
* calls that return a boolean flag whether it succedeed or not.
*
* Example:
*
* function deferred() {
* var succeeded = false;
* // ... custom code
* return succeeded;
* }
*
* var deferredCall = new goog.async.ConditionalDelay(deferred);
* deferredCall.onSuccess = function() {
* alert('Success: The deferred function has been successfully executed.');
* }
* deferredCall.onFailure = function() {
* alert('Failure: Time limit exceeded.');
* }
*
* // Call the deferred() every 100 msec until it returns true,
* // or 5 seconds pass.
* deferredCall.start(100, 5000);
*
* // Stop the deferred function call (does nothing if it's not active).
* deferredCall.stop();
*
*/
goog.provide('goog.async.ConditionalDelay');
goog.require('goog.Disposable');
goog.require('goog.async.Delay');
/**
* A ConditionalDelay object invokes the associated function after a specified
* interval delay and checks its return value. If the function returns
* {@code true} the conditional delay is cancelled and {@see #onSuccess}
* is called. Otherwise this object keeps to invoke the deferred function until
* either it returns {@code true} or the timeout is exceeded. In the latter case
* the {@see #onFailure} method will be called.
*
* The interval duration and timeout can be specified each time the delay is
* started. Calling start on an active delay will reset the timer.
*
* @param {function():boolean} listener Function to call when the delay
* completes. Should return a value that type-converts to {@code true} if
* the call succeeded and this delay should be stopped.
* @param {Object=} opt_handler The object scope to invoke the function in.
* @constructor
* @extends {goog.Disposable}
*/
goog.async.ConditionalDelay = function(listener, opt_handler) {
goog.Disposable.call(this);
/**
* The function that will be invoked after a delay.
* @type {function():boolean}
* @private
*/
this.listener_ = listener;
/**
* The object context to invoke the callback in.
* @type {Object|undefined}
* @private
*/
this.handler_ = opt_handler;
/**
* The underlying goog.async.Delay delegate object.
* @type {goog.async.Delay}
* @private
*/
this.delay_ = new goog.async.Delay(
goog.bind(this.onTick_, this), 0 /*interval*/, this /*scope*/);
};
goog.inherits(goog.async.ConditionalDelay, goog.Disposable);
/**
* The delay interval in milliseconds to between the calls to the callback.
* Note, that the callback may be invoked earlier than this interval if the
* timeout is exceeded.
* @type {number}
* @private
*/
goog.async.ConditionalDelay.prototype.interval_ = 0;
/**
* The timeout timestamp until which the delay is to be executed.
* A negative value means no timeout.
* @type {number}
* @private
*/
goog.async.ConditionalDelay.prototype.runUntil_ = 0;
/**
* True if the listener has been executed, and it returned {@code true}.
* @type {boolean}
* @private
*/
goog.async.ConditionalDelay.prototype.isDone_ = false;
/** @override */
goog.async.ConditionalDelay.prototype.disposeInternal = function() {
this.delay_.dispose();
delete this.listener_;
delete this.handler_;
goog.async.ConditionalDelay.superClass_.disposeInternal.call(this);
};
/**
* Starts the delay timer. The provided listener function will be called
* repeatedly after the specified interval until the function returns
* {@code true} or the timeout is exceeded. Calling start on an active timer
* will stop the timer first.
* @param {number=} opt_interval The time interval between the function
* invocations (in milliseconds). Default is 0.
* @param {number=} opt_timeout The timeout interval (in milliseconds). Takes
* precedence over the {@code opt_interval}, i.e. if the timeout is less
* than the invocation interval, the function will be called when the
* timeout is exceeded. A negative value means no timeout. Default is 0.
*/
goog.async.ConditionalDelay.prototype.start = function(opt_interval,
opt_timeout) {
this.stop();
this.isDone_ = false;
var timeout = opt_timeout || 0;
this.interval_ = Math.max(opt_interval || 0, 0);
this.runUntil_ = timeout < 0 ? -1 : (goog.now() + timeout);
this.delay_.start(
timeout < 0 ? this.interval_ : Math.min(this.interval_, timeout));
};
/**
* Stops the delay timer if it is active. No action is taken if the timer is not
* in use.
*/
goog.async.ConditionalDelay.prototype.stop = function() {
this.delay_.stop();
};
/**
* @return {boolean} True if the delay is currently active, false otherwise.
*/
goog.async.ConditionalDelay.prototype.isActive = function() {
return this.delay_.isActive();
};
/**
* @return {boolean} True if the listener has been executed and returned
* {@code true} since the last call to {@see #start}.
*/
goog.async.ConditionalDelay.prototype.isDone = function() {
return this.isDone_;
};
/**
* Called when the listener has been successfully executed and returned
* {@code true}. The {@see #isDone} method should return {@code true} by now.
* Designed for inheritance, should be overridden by subclasses or on the
* instances if they care.
*/
goog.async.ConditionalDelay.prototype.onSuccess = function() {
// Do nothing by default.
};
/**
* Called when this delayed call is cancelled because the timeout has been
* exceeded, and the listener has never returned {@code true}.
* Designed for inheritance, should be overridden by subclasses or on the
* instances if they care.
*/
goog.async.ConditionalDelay.prototype.onFailure = function() {
// Do nothing by default.
};
/**
* A callback function for the underlying {@code goog.async.Delay} object. When
* executed the listener function is called, and if it returns {@code true}
* the delay is stopped and the {@see #onSuccess} method is invoked.
* If the timeout is exceeded the delay is stopped and the
* {@see #onFailure} method is called.
* @private
*/
goog.async.ConditionalDelay.prototype.onTick_ = function() {
var successful = this.listener_.call(this.handler_);
if (successful) {
this.isDone_ = true;
this.onSuccess();
} else {
// Try to reschedule the task.
if (this.runUntil_ < 0) {
// No timeout.
this.delay_.start(this.interval_);
} else {
var timeLeft = this.runUntil_ - goog.now();
if (timeLeft <= 0) {
this.onFailure();
} else {
this.delay_.start(Math.min(this.interval_, timeLeft));
}
}
}
};
| 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.async.Throttle class.
*
* @see ../demos/timers.html
*/
goog.provide('goog.Throttle');
goog.provide('goog.async.Throttle');
goog.require('goog.Disposable');
goog.require('goog.Timer');
/**
* Throttle will perform an action that is passed in no more than once
* per interval (specified in milliseconds). If it gets multiple signals
* to perform the action while it is waiting, it will only perform the action
* once at the end of the interval.
* @param {Function} listener Function to callback when the action is triggered.
* @param {number} interval Interval over which to throttle. The handler can
* only be called once per interval.
* @param {Object=} opt_handler Object in whose scope to call the listener.
* @constructor
* @extends {goog.Disposable}
*/
goog.async.Throttle = function(listener, interval, opt_handler) {
goog.Disposable.call(this);
/**
* Function to callback
* @type {Function}
* @private
*/
this.listener_ = listener;
/**
* Interval for the throttle time
* @type {number}
* @private
*/
this.interval_ = interval;
/**
* "this" context for the listener
* @type {Object|undefined}
* @private
*/
this.handler_ = opt_handler;
/**
* Cached callback function invoked after the throttle timeout completes
* @type {Function}
* @private
*/
this.callback_ = goog.bind(this.onTimer_, this);
};
goog.inherits(goog.async.Throttle, goog.Disposable);
/**
* A deprecated alias.
* @deprecated Use goog.async.Throttle instead.
* @constructor
*/
goog.Throttle = goog.async.Throttle;
/**
* Indicates that the action is pending and needs to be fired.
* @type {boolean}
* @private
*/
goog.async.Throttle.prototype.shouldFire_ = false;
/**
* Indicates the count of nested pauses currently in effect on the throttle.
* When this count is not zero, fired actions will be postponed until the
* throttle is resumed enough times to drop the pause count to zero.
* @type {number}
* @private
*/
goog.async.Throttle.prototype.pauseCount_ = 0;
/**
* Timer for scheduling the next callback
* @type {?number}
* @private
*/
goog.async.Throttle.prototype.timer_ = null;
/**
* Notifies the throttle that the action has happened. It will throttle the call
* so that the callback is not called too often according to the interval
* parameter passed to the constructor.
*/
goog.async.Throttle.prototype.fire = function() {
if (!this.timer_ && !this.pauseCount_) {
this.doAction_();
} else {
this.shouldFire_ = true;
}
};
/**
* Cancels any pending action callback. The throttle can be restarted by
* calling {@link #fire}.
*/
goog.async.Throttle.prototype.stop = function() {
if (this.timer_) {
goog.Timer.clear(this.timer_);
this.timer_ = null;
this.shouldFire_ = false;
}
};
/**
* Pauses the throttle. All pending and future action callbacks will be
* delayed until the throttle is resumed. Pauses can be nested.
*/
goog.async.Throttle.prototype.pause = function() {
this.pauseCount_++;
};
/**
* Resumes the throttle. If doing so drops the pausing count to zero, pending
* action callbacks will be executed as soon as possible, but still no sooner
* than an interval's delay after the previous call. Future action callbacks
* will be executed as normal.
*/
goog.async.Throttle.prototype.resume = function() {
this.pauseCount_--;
if (!this.pauseCount_ && this.shouldFire_ && !this.timer_) {
this.shouldFire_ = false;
this.doAction_();
}
};
/** @override */
goog.async.Throttle.prototype.disposeInternal = function() {
goog.async.Throttle.superClass_.disposeInternal.call(this);
this.stop();
};
/**
* Handler for the timer to fire the throttle
* @private
*/
goog.async.Throttle.prototype.onTimer_ = function() {
this.timer_ = null;
if (this.shouldFire_ && !this.pauseCount_) {
this.shouldFire_ = false;
this.doAction_();
}
};
/**
* Calls the callback
* @private
*/
goog.async.Throttle.prototype.doAction_ = function() {
this.timer_ = goog.Timer.callOnce(this.callback_, this.interval_);
this.listener_.call(this.handler_);
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A delayed callback that pegs to the next animation frame
* instead of a user-configurable timeout.
*
*/
goog.provide('goog.async.AnimationDelay');
goog.require('goog.Disposable');
goog.require('goog.events');
goog.require('goog.functions');
// TODO(nicksantos): Should we factor out the common code between this and
// goog.async.Delay? I'm not sure if there's enough code for this to really
// make sense. Subclassing seems like the wrong approach for a variety of
// reasons. Maybe there should be a common interface?
/**
* A delayed callback that pegs to the next animation frame
* instead of a user configurable timeout. By design, this should have
* the same interface as goog.async.Delay.
*
* Uses requestAnimationFrame and friends when available, but falls
* back to a timeout of goog.async.AnimationDelay.TIMEOUT.
*
* For more on requestAnimationFrame and how you can use it to create smoother
* animations, see:
* @see http://paulirish.com/2011/requestanimationframe-for-smart-animating/
*
* @param {function(number)} listener Function to call when the delay completes.
* Will be passed the timestamp when it's called, in unix ms.
* @param {Window=} opt_window The window object to execute the delay in.
* Defaults to the global object.
* @param {Object=} opt_handler The object scope to invoke the function in.
* @constructor
* @extends {goog.Disposable}
*/
goog.async.AnimationDelay = function(listener, opt_window, opt_handler) {
goog.base(this);
/**
* The function that will be invoked after a delay.
* @type {function(number)}
* @private
*/
this.listener_ = listener;
/**
* The object context to invoke the callback in.
* @type {Object|undefined}
* @private
*/
this.handler_ = opt_handler;
/**
* @type {Window}
* @private
*/
this.win_ = opt_window || window;
/**
* Cached callback function invoked when the delay finishes.
* @type {function()}
* @private
*/
this.callback_ = goog.bind(this.doAction_, this);
};
goog.inherits(goog.async.AnimationDelay, goog.Disposable);
/**
* Identifier of the active delay timeout, or event listener,
* or null when inactive.
* @type {goog.events.Key|number|null}
* @private
*/
goog.async.AnimationDelay.prototype.id_ = null;
/**
* If we're using dom listeners.
* @type {?boolean}
* @private
*/
goog.async.AnimationDelay.prototype.usingListeners_ = false;
/**
* Default wait timeout for animations (in milliseconds). Only used for timed
* animation, which uses a timer (setTimeout) to schedule animation.
*
* @type {number}
* @const
*/
goog.async.AnimationDelay.TIMEOUT = 20;
/**
* Name of event received from the requestAnimationFrame in Firefox.
*
* @type {string}
* @const
* @private
*/
goog.async.AnimationDelay.MOZ_BEFORE_PAINT_EVENT_ = 'MozBeforePaint';
/**
* Starts the delay timer. The provided listener function will be called
* before the next animation frame.
*/
goog.async.AnimationDelay.prototype.start = function() {
this.stop();
this.usingListeners_ = false;
var raf = this.getRaf_();
var cancelRaf = this.getCancelRaf_();
if (raf && !cancelRaf && this.win_.mozRequestAnimationFrame) {
// Because Firefox (Gecko) runs animation in separate threads, it also saves
// time by running the requestAnimationFrame callbacks in that same thread.
// Sadly this breaks the assumption of implicit thread-safety in JS, and can
// thus create thread-based inconsistencies on counters etc.
//
// Calling cycleAnimations_ using the MozBeforePaint event instead of as
// callback fixes this.
//
// Trigger this condition only if the mozRequestAnimationFrame is available,
// but not the W3C requestAnimationFrame function (as in draft) or the
// equivalent cancel functions.
this.id_ = goog.events.listen(
this.win_,
goog.async.AnimationDelay.MOZ_BEFORE_PAINT_EVENT_,
this.callback_);
this.win_.mozRequestAnimationFrame(null);
this.usingListeners_ = true;
} else if (raf && cancelRaf) {
this.id_ = raf.call(this.win_, this.callback_);
} else {
this.id_ = this.win_.setTimeout(
// Prior to Firefox 13, Gecko passed a non-standard parameter
// to the callback that we want to ignore.
goog.functions.lock(this.callback_),
goog.async.AnimationDelay.TIMEOUT);
}
};
/**
* Stops the delay timer if it is active. No action is taken if the timer is not
* in use.
*/
goog.async.AnimationDelay.prototype.stop = function() {
if (this.isActive()) {
var raf = this.getRaf_();
var cancelRaf = this.getCancelRaf_();
if (raf && !cancelRaf && this.win_.mozRequestAnimationFrame) {
goog.events.unlistenByKey(this.id_);
} else if (raf && cancelRaf) {
cancelRaf.call(this.win_, /** @type {number} */ (this.id_));
} else {
this.win_.clearTimeout(/** @type {number} */ (this.id_));
}
}
this.id_ = null;
};
/**
* Fires delay's action even if timer has already gone off or has not been
* started yet; guarantees action firing. Stops the delay timer.
*/
goog.async.AnimationDelay.prototype.fire = function() {
this.stop();
this.doAction_();
};
/**
* Fires delay's action only if timer is currently active. Stops the delay
* timer.
*/
goog.async.AnimationDelay.prototype.fireIfActive = function() {
if (this.isActive()) {
this.fire();
}
};
/**
* @return {boolean} True if the delay is currently active, false otherwise.
*/
goog.async.AnimationDelay.prototype.isActive = function() {
return this.id_ != null;
};
/**
* Invokes the callback function after the delay successfully completes.
* @private
*/
goog.async.AnimationDelay.prototype.doAction_ = function() {
if (this.usingListeners_ && this.id_) {
goog.events.unlistenByKey(this.id_);
}
this.id_ = null;
// We are not using the timestamp returned by requestAnimationFrame
// because it may be either a Date.now-style time or a
// high-resolution time (depending on browser implementation). Using
// goog.now() will ensure that the timestamp used is consistent and
// compatible with goog.fx.Animation.
this.listener_.call(this.handler_, goog.now());
};
/** @override */
goog.async.AnimationDelay.prototype.disposeInternal = function() {
this.stop();
goog.base(this, 'disposeInternal');
};
/**
* @return {?function(function(number)): number} The requestAnimationFrame
* function, or null if not available on this browser.
* @private
*/
goog.async.AnimationDelay.prototype.getRaf_ = function() {
var win = this.win_;
return win.requestAnimationFrame ||
win.webkitRequestAnimationFrame ||
win.mozRequestAnimationFrame ||
win.oRequestAnimationFrame ||
win.msRequestAnimationFrame ||
null;
};
/**
* @return {?function(number): number} The cancelAnimationFrame function,
* or null if not available on this browser.
* @private
*/
goog.async.AnimationDelay.prototype.getCancelRaf_ = function() {
var win = this.win_;
return win.cancelRequestAnimationFrame ||
win.webkitCancelRequestAnimationFrame ||
win.mozCancelRequestAnimationFrame ||
win.oCancelRequestAnimationFrame ||
win.msCancelRequestAnimationFrame ||
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 Defines a class useful for handling functions that must be
* invoked after a delay, especially when that delay is frequently restarted.
* Examples include delaying before displaying a tooltip, menu hysteresis,
* idle timers, etc.
* @author brenneman@google.com (Shawn Brenneman)
* @see ../demos/timers.html
*/
goog.provide('goog.Delay');
goog.provide('goog.async.Delay');
goog.require('goog.Disposable');
goog.require('goog.Timer');
/**
* A Delay object invokes the associated function after a specified delay. The
* interval duration can be specified once in the constructor, or can be defined
* each time the delay is started. Calling start on an active delay will reset
* the timer.
*
* @param {Function} listener Function to call when the delay completes.
* @param {number=} opt_interval The default length of the invocation delay (in
* milliseconds).
* @param {Object=} opt_handler The object scope to invoke the function in.
* @constructor
* @extends {goog.Disposable}
*/
goog.async.Delay = function(listener, opt_interval, opt_handler) {
goog.Disposable.call(this);
/**
* The function that will be invoked after a delay.
* @type {Function}
* @private
*/
this.listener_ = listener;
/**
* The default amount of time to delay before invoking the callback.
* @type {number}
* @private
*/
this.interval_ = opt_interval || 0;
/**
* The object context to invoke the callback in.
* @type {Object|undefined}
* @private
*/
this.handler_ = opt_handler;
/**
* Cached callback function invoked when the delay finishes.
* @type {Function}
* @private
*/
this.callback_ = goog.bind(this.doAction_, this);
};
goog.inherits(goog.async.Delay, goog.Disposable);
/**
* A deprecated alias.
* @deprecated Use goog.async.Delay instead.
* @constructor
*/
goog.Delay = goog.async.Delay;
/**
* Identifier of the active delay timeout, or 0 when inactive.
* @type {number}
* @private
*/
goog.async.Delay.prototype.id_ = 0;
/**
* Disposes of the object, cancelling the timeout if it is still outstanding and
* removing all object references.
* @override
* @protected
*/
goog.async.Delay.prototype.disposeInternal = function() {
goog.async.Delay.superClass_.disposeInternal.call(this);
this.stop();
delete this.listener_;
delete this.handler_;
};
/**
* Starts the delay timer. The provided listener function will be called after
* the specified interval. Calling start on an active timer will reset the
* delay interval.
* @param {number=} opt_interval If specified, overrides the object's default
* interval with this one (in milliseconds).
*/
goog.async.Delay.prototype.start = function(opt_interval) {
this.stop();
this.id_ = goog.Timer.callOnce(
this.callback_,
goog.isDef(opt_interval) ? opt_interval : this.interval_);
};
/**
* Stops the delay timer if it is active. No action is taken if the timer is not
* in use.
*/
goog.async.Delay.prototype.stop = function() {
if (this.isActive()) {
goog.Timer.clear(this.id_);
}
this.id_ = 0;
};
/**
* Fires delay's action even if timer has already gone off or has not been
* started yet; guarantees action firing. Stops the delay timer.
*/
goog.async.Delay.prototype.fire = function() {
this.stop();
this.doAction_();
};
/**
* Fires delay's action only if timer is currently active. Stops the delay
* timer.
*/
goog.async.Delay.prototype.fireIfActive = function() {
if (this.isActive()) {
this.fire();
}
};
/**
* @return {boolean} True if the delay is currently active, false otherwise.
*/
goog.async.Delay.prototype.isActive = function() {
return this.id_ != 0;
};
/**
* Invokes the callback function after the delay successfully completes.
* @private
*/
goog.async.Delay.prototype.doAction_ = function() {
this.id_ = 0;
if (this.listener_) {
this.listener_.call(this.handler_);
}
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Utilities for manipulating objects/maps/hashes.
*/
goog.provide('goog.object');
/**
* Calls a function for each element in an object/map/hash.
*
* @param {Object.<K,V>} obj The object over which to iterate.
* @param {function(this:T,V,?,Object.<K,V>):?} f The function to call
* for every element. This function takes 3 arguments (the element, the
* index and the object) and the return value is ignored.
* @param {T=} opt_obj This is used as the 'this' object within f.
* @template T,K,V
*/
goog.object.forEach = function(obj, f, opt_obj) {
for (var key in obj) {
f.call(opt_obj, obj[key], key, obj);
}
};
/**
* Calls a function for each element in an object/map/hash. If that call returns
* true, adds the element to a new object.
*
* @param {Object.<K,V>} obj The object over which to iterate.
* @param {function(this:T,V,?,Object.<K,V>):boolean} f The function to call
* for every element. This
* function takes 3 arguments (the element, the index and the object)
* and should return a boolean. If the return value is true the
* element is added to the result object. If it is false the
* element is not included.
* @param {T=} opt_obj This is used as the 'this' object within f.
* @return {!Object.<K,V>} a new object in which only elements that passed the
* test are present.
* @template T,K,V
*/
goog.object.filter = function(obj, f, opt_obj) {
var res = {};
for (var key in obj) {
if (f.call(opt_obj, obj[key], key, obj)) {
res[key] = obj[key];
}
}
return res;
};
/**
* For every element in an object/map/hash calls a function and inserts the
* result into a new object.
*
* @param {Object.<K,V>} obj The object over which to iterate.
* @param {function(this:T,V,?,Object.<K,V>):R} f The function to call
* for every element. This function
* takes 3 arguments (the element, the index and the object)
* and should return something. The result will be inserted
* into a new object.
* @param {T=} opt_obj This is used as the 'this' object within f.
* @return {!Object.<K,R>} a new object with the results from f.
* @template T,K,V,R
*/
goog.object.map = function(obj, f, opt_obj) {
var res = {};
for (var key in obj) {
res[key] = f.call(opt_obj, obj[key], key, obj);
}
return res;
};
/**
* Calls a function for each element in an object/map/hash. If any
* call returns true, returns true (without checking the rest). If
* all calls return false, returns false.
*
* @param {Object.<K,V>} obj The object to check.
* @param {function(this:T,V,?,Object.<K,V>):boolean} f The function to
* call for every element. This function
* takes 3 arguments (the element, the index and the object) and should
* return a boolean.
* @param {T=} opt_obj This is used as the 'this' object within f.
* @return {boolean} true if any element passes the test.
* @template T,K,V
*/
goog.object.some = function(obj, f, opt_obj) {
for (var key in obj) {
if (f.call(opt_obj, obj[key], key, obj)) {
return true;
}
}
return false;
};
/**
* Calls a function for each element in an object/map/hash. If
* all calls return true, returns true. If any call returns false, returns
* false at this point and does not continue to check the remaining elements.
*
* @param {Object.<K,V>} obj The object to check.
* @param {?function(this:T,V,?,Object.<K,V>):boolean} f The function to
* call for every element. This function
* takes 3 arguments (the element, the index and the object) and should
* return a boolean.
* @param {T=} opt_obj This is used as the 'this' object within f.
* @return {boolean} false if any element fails the test.
* @template T,K,V
*/
goog.object.every = function(obj, f, opt_obj) {
for (var key in obj) {
if (!f.call(opt_obj, obj[key], key, obj)) {
return false;
}
}
return true;
};
/**
* Returns the number of key-value pairs in the object map.
*
* @param {Object} obj The object for which to get the number of key-value
* pairs.
* @return {number} The number of key-value pairs in the object map.
*/
goog.object.getCount = function(obj) {
// JS1.5 has __count__ but it has been deprecated so it raises a warning...
// in other words do not use. Also __count__ only includes the fields on the
// actual object and not in the prototype chain.
var rv = 0;
for (var key in obj) {
rv++;
}
return rv;
};
/**
* Returns one key from the object map, if any exists.
* For map literals the returned key will be the first one in most of the
* browsers (a know exception is Konqueror).
*
* @param {Object} obj The object to pick a key from.
* @return {string|undefined} The key or undefined if the object is empty.
*/
goog.object.getAnyKey = function(obj) {
for (var key in obj) {
return key;
}
};
/**
* Returns one value from the object map, if any exists.
* For map literals the returned value will be the first one in most of the
* browsers (a know exception is Konqueror).
*
* @param {Object.<K,V>} obj The object to pick a value from.
* @return {V|undefined} The value or undefined if the object is empty.
* @template K,V
*/
goog.object.getAnyValue = function(obj) {
for (var key in obj) {
return obj[key];
}
};
/**
* Whether the object/hash/map contains the given object as a value.
* An alias for goog.object.containsValue(obj, val).
*
* @param {Object.<K,V>} obj The object in which to look for val.
* @param {V} val The object for which to check.
* @return {boolean} true if val is present.
* @template K,V
*/
goog.object.contains = function(obj, val) {
return goog.object.containsValue(obj, val);
};
/**
* Returns the values of the object/map/hash.
*
* @param {Object.<K,V>} obj The object from which to get the values.
* @return {!Array.<V>} The values in the object/map/hash.
* @template K,V
*/
goog.object.getValues = function(obj) {
var res = [];
var i = 0;
for (var key in obj) {
res[i++] = obj[key];
}
return res;
};
/**
* Returns the keys of the object/map/hash.
*
* @param {Object} obj The object from which to get the keys.
* @return {!Array.<string>} Array of property keys.
*/
goog.object.getKeys = function(obj) {
var res = [];
var i = 0;
for (var key in obj) {
res[i++] = key;
}
return res;
};
/**
* Get a value from an object multiple levels deep. This is useful for
* pulling values from deeply nested objects, such as JSON responses.
* Example usage: getValueByKeys(jsonObj, 'foo', 'entries', 3)
*
* @param {!Object} obj An object to get the value from. Can be array-like.
* @param {...(string|number|!Array.<number|string>)} var_args A number of keys
* (as strings, or numbers, for array-like objects). Can also be
* specified as a single array of keys.
* @return {*} The resulting value. If, at any point, the value for a key
* is undefined, returns undefined.
*/
goog.object.getValueByKeys = function(obj, var_args) {
var isArrayLike = goog.isArrayLike(var_args);
var keys = isArrayLike ? var_args : arguments;
// Start with the 2nd parameter for the variable parameters syntax.
for (var i = isArrayLike ? 0 : 1; i < keys.length; i++) {
obj = obj[keys[i]];
if (!goog.isDef(obj)) {
break;
}
}
return obj;
};
/**
* Whether the object/map/hash contains the given key.
*
* @param {Object} obj The object in which to look for key.
* @param {*} key The key for which to check.
* @return {boolean} true If the map contains the key.
*/
goog.object.containsKey = function(obj, key) {
return key in obj;
};
/**
* Whether the object/map/hash contains the given value. This is O(n).
*
* @param {Object.<K,V>} obj The object in which to look for val.
* @param {V} val The value for which to check.
* @return {boolean} true If the map contains the value.
* @template K,V
*/
goog.object.containsValue = function(obj, val) {
for (var key in obj) {
if (obj[key] == val) {
return true;
}
}
return false;
};
/**
* Searches an object for an element that satisfies the given condition and
* returns its key.
* @param {Object.<K,V>} obj The object to search in.
* @param {function(this:T,V,string,Object.<K,V>):boolean} f The
* function to call for every element. Takes 3 arguments (the value,
* the key and the object) and should return a boolean.
* @param {T=} opt_this An optional "this" context for the function.
* @return {string|undefined} The key of an element for which the function
* returns true or undefined if no such element is found.
* @template T,K,V
*/
goog.object.findKey = function(obj, f, opt_this) {
for (var key in obj) {
if (f.call(opt_this, obj[key], key, obj)) {
return key;
}
}
return undefined;
};
/**
* Searches an object for an element that satisfies the given condition and
* returns its value.
* @param {Object.<K,V>} obj The object to search in.
* @param {function(this:T,V,string,Object.<K,V>):boolean} f The function
* to call for every element. Takes 3 arguments (the value, the key
* and the object) and should return a boolean.
* @param {T=} opt_this An optional "this" context for the function.
* @return {V} The value of an element for which the function returns true or
* undefined if no such element is found.
* @template T,K,V
*/
goog.object.findValue = function(obj, f, opt_this) {
var key = goog.object.findKey(obj, f, opt_this);
return key && obj[key];
};
/**
* Whether the object/map/hash is empty.
*
* @param {Object} obj The object to test.
* @return {boolean} true if obj is empty.
*/
goog.object.isEmpty = function(obj) {
for (var key in obj) {
return false;
}
return true;
};
/**
* Removes all key value pairs from the object/map/hash.
*
* @param {Object} obj The object to clear.
*/
goog.object.clear = function(obj) {
for (var i in obj) {
delete obj[i];
}
};
/**
* Removes a key-value pair based on the key.
*
* @param {Object} obj The object from which to remove the key.
* @param {*} key The key to remove.
* @return {boolean} Whether an element was removed.
*/
goog.object.remove = function(obj, key) {
var rv;
if ((rv = key in obj)) {
delete obj[key];
}
return rv;
};
/**
* Adds a key-value pair to the object. Throws an exception if the key is
* already in use. Use set if you want to change an existing pair.
*
* @param {Object.<K,V>} obj The object to which to add the key-value pair.
* @param {string} key The key to add.
* @param {V} val The value to add.
* @template K,V
*/
goog.object.add = function(obj, key, val) {
if (key in obj) {
throw Error('The object already contains the key "' + key + '"');
}
goog.object.set(obj, key, val);
};
/**
* Returns the value for the given key.
*
* @param {Object.<K,V>} obj The object from which to get the value.
* @param {string} key The key for which to get the value.
* @param {R=} opt_val The value to return if no item is found for the given
* key (default is undefined).
* @return {V|R|undefined} The value for the given key.
* @template K,V,R
*/
goog.object.get = function(obj, key, opt_val) {
if (key in obj) {
return obj[key];
}
return opt_val;
};
/**
* Adds a key-value pair to the object/map/hash.
*
* @param {Object.<K,V>} obj The object to which to add the key-value pair.
* @param {string} key The key to add.
* @param {K} value The value to add.
* @template K,V
*/
goog.object.set = function(obj, key, value) {
obj[key] = value;
};
/**
* Adds a key-value pair to the object/map/hash if it doesn't exist yet.
*
* @param {Object.<K,V>} obj The object to which to add the key-value pair.
* @param {string} key The key to add.
* @param {V} value The value to add if the key wasn't present.
* @return {V} The value of the entry at the end of the function.
* @template K,V
*/
goog.object.setIfUndefined = function(obj, key, value) {
return key in obj ? obj[key] : (obj[key] = value);
};
/**
* Does a flat clone of the object.
*
* @param {Object.<K,V>} obj Object to clone.
* @return {!Object.<K,V>} Clone of the input object.
* @template K,V
*/
goog.object.clone = function(obj) {
// We cannot use the prototype trick because a lot of methods depend on where
// the actual key is set.
var res = {};
for (var key in obj) {
res[key] = obj[key];
}
return res;
// We could also use goog.mixin but I wanted this to be independent from that.
};
/**
* Clones a value. The input may be an Object, Array, or basic type. Objects and
* arrays will be cloned recursively.
*
* WARNINGS:
* <code>goog.object.unsafeClone</code> does not detect reference loops. Objects
* that refer to themselves will cause infinite recursion.
*
* <code>goog.object.unsafeClone</code> is unaware of unique identifiers, and
* copies UIDs created by <code>getUid</code> into cloned results.
*
* @param {*} obj The value to clone.
* @return {*} A clone of the input value.
*/
goog.object.unsafeClone = function(obj) {
var type = goog.typeOf(obj);
if (type == 'object' || type == 'array') {
if (obj.clone) {
return obj.clone();
}
var clone = type == 'array' ? [] : {};
for (var key in obj) {
clone[key] = goog.object.unsafeClone(obj[key]);
}
return clone;
}
return obj;
};
/**
* Returns a new object in which all the keys and values are interchanged
* (keys become values and values become keys). If multiple keys map to the
* same value, the chosen transposed value is implementation-dependent.
*
* @param {Object} obj The object to transpose.
* @return {!Object} The transposed object.
*/
goog.object.transpose = function(obj) {
var transposed = {};
for (var key in obj) {
transposed[obj[key]] = key;
}
return transposed;
};
/**
* The names of the fields that are defined on Object.prototype.
* @type {Array.<string>}
* @private
*/
goog.object.PROTOTYPE_FIELDS_ = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
/**
* Extends an object with another object.
* This operates 'in-place'; it does not create a new Object.
*
* Example:
* var o = {};
* goog.object.extend(o, {a: 0, b: 1});
* o; // {a: 0, b: 1}
* goog.object.extend(o, {c: 2});
* o; // {a: 0, b: 1, c: 2}
*
* @param {Object} target The object to modify.
* @param {...Object} var_args The objects from which values will be copied.
*/
goog.object.extend = function(target, var_args) {
var key, source;
for (var i = 1; i < arguments.length; i++) {
source = arguments[i];
for (key in source) {
target[key] = source[key];
}
// For IE the for-in-loop does not contain any properties that are not
// enumerable on the prototype object (for example isPrototypeOf from
// Object.prototype) and it will also not include 'replace' on objects that
// extend String and change 'replace' (not that it is common for anyone to
// extend anything except Object).
for (var j = 0; j < goog.object.PROTOTYPE_FIELDS_.length; j++) {
key = goog.object.PROTOTYPE_FIELDS_[j];
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
};
/**
* Creates a new object built from the key-value pairs provided as arguments.
* @param {...*} var_args If only one argument is provided and it is an array
* then this is used as the arguments, otherwise even arguments are used as
* the property names and odd arguments are used as the property values.
* @return {!Object} The new object.
* @throws {Error} If there are uneven number of arguments or there is only one
* non array argument.
*/
goog.object.create = function(var_args) {
var argLength = arguments.length;
if (argLength == 1 && goog.isArray(arguments[0])) {
return goog.object.create.apply(null, arguments[0]);
}
if (argLength % 2) {
throw Error('Uneven number of arguments');
}
var rv = {};
for (var i = 0; i < argLength; i += 2) {
rv[arguments[i]] = arguments[i + 1];
}
return rv;
};
/**
* Creates a new object where the property names come from the arguments but
* the value is always set to true
* @param {...*} var_args If only one argument is provided and it is an array
* then this is used as the arguments, otherwise the arguments are used
* as the property names.
* @return {!Object} The new object.
*/
goog.object.createSet = function(var_args) {
var argLength = arguments.length;
if (argLength == 1 && goog.isArray(arguments[0])) {
return goog.object.createSet.apply(null, arguments[0]);
}
var rv = {};
for (var i = 0; i < argLength; i++) {
rv[arguments[i]] = true;
}
return rv;
};
/**
* Creates an immutable view of the underlying object, if the browser
* supports immutable objects.
*
* In default mode, writes to this view will fail silently. In strict mode,
* they will throw an error.
*
* @param {!Object.<K,V>} obj An object.
* @return {!Object.<K,V>} An immutable view of that object, or the
* original object if this browser does not support immutables.
* @template K,V
*/
goog.object.createImmutableView = function(obj) {
var result = obj;
if (Object.isFrozen && !Object.isFrozen(obj)) {
result = Object.create(obj);
Object.freeze(result);
}
return result;
};
/**
* @param {!Object} obj An object.
* @return {boolean} Whether this is an immutable view of the object.
*/
goog.object.isImmutableView = function(obj) {
return !!Object.isFrozen && Object.isFrozen(obj);
};
| 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 Unit tests for goog.position.
*
* @author eae@google.com (Emil A Eklund)
*/
/** @suppress {extraProvide} */
goog.provide('goog.positioningTest');
goog.require('goog.dom');
goog.require('goog.dom.DomHelper');
goog.require('goog.math.Box');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Size');
goog.require('goog.positioning');
goog.require('goog.positioning.Corner');
goog.require('goog.positioning.Overflow');
goog.require('goog.positioning.OverflowStatus');
goog.require('goog.style');
goog.require('goog.testing.ExpectedFailures');
goog.require('goog.testing.jsunit');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');
goog.setTestOnly('goog.positioningTest');
// Allow positions to be off by one in gecko as it reports scrolling
// offsets in steps of 2.
var ALLOWED_OFFSET = goog.userAgent.GECKO ? 1 : 0;
// Error bar for positions since some browsers are not super accurate
// in reporting them.
var EPSILON = 2;
var expectedFailures = new goog.testing.ExpectedFailures();
var corner = goog.positioning.Corner;
var overflow = goog.positioning.Overflow;
var testArea;
function setUp() {
window.scrollTo(0, 0);
var viewportSize = goog.dom.getViewportSize();
// Some tests need enough size viewport.
if (viewportSize.width < 600 || viewportSize.height < 600) {
window.moveTo(0, 0);
window.resizeTo(640, 640);
}
testArea = goog.dom.getElement('test-area');
}
function tearDown() {
expectedFailures.handleTearDown();
testArea.setAttribute('style', '');
testArea.innerHTML = '';
}
/**
* This is used to round pixel values on FF3 Mac.
*/
function assertRoundedEquals(a, b, c) {
function round(x) {
return goog.userAgent.GECKO && (goog.userAgent.MAC || goog.userAgent.X11) &&
goog.userAgent.isVersion('1.9') ? Math.round(x) : x;
}
if (arguments.length == 3) {
assertRoughlyEquals(a, round(b), round(c), ALLOWED_OFFSET);
} else {
assertRoughlyEquals(round(a), round(b), ALLOWED_OFFSET);
}
}
function testPositionAtAnchorLeftToRight() {
var anchor = document.getElementById('anchor1');
var popup = document.getElementById('popup1');
// Anchor top left to top left.
goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_LEFT);
var anchorRect = goog.style.getBounds(anchor);
var popupRect = goog.style.getBounds(popup);
assertRoundedEquals('Left edge of popup should line up with left edge ' +
'of anchor.',
anchorRect.left,
popupRect.left);
assertRoundedEquals('Popup should have the same y position as the anchor.',
anchorRect.top,
popupRect.top);
// Anchor top left to bottom left.
goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_LEFT,
popup, corner.TOP_LEFT);
anchorRect = goog.style.getBounds(anchor);
popupRect = goog.style.getBounds(popup);
assertRoundedEquals('Left edge of popup should line up with left edge ' +
'of anchor.',
anchorRect.left,
popupRect.left);
assertRoundedEquals('Popup should be positioned just below the anchor.',
anchorRect.top + anchorRect.height,
popupRect.top);
// Anchor top left to top right.
goog.positioning.positionAtAnchor(anchor, corner.TOP_RIGHT,
popup, corner.TOP_LEFT);
anchorRect = goog.style.getBounds(anchor);
popupRect = goog.style.getBounds(popup);
assertRoundedEquals('Popup should be positioned just right of the anchor.',
anchorRect.left + anchorRect.width,
popupRect.left);
assertRoundedEquals('Popup should have the same y position as the anchor.',
anchorRect.top,
popupRect.top);
// Anchor top right to bottom right.
goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT,
popup, corner.TOP_RIGHT);
anchorRect = goog.style.getBounds(anchor);
popupRect = goog.style.getBounds(popup);
assertRoundedEquals('Right edge of popup should line up with right edge ' +
'of anchor.',
anchorRect.left + anchorRect.width,
popupRect.left + popupRect.width);
assertRoundedEquals('Popup should be positioned just below the anchor.',
anchorRect.top + anchorRect.height,
popupRect.top);
// Anchor top start to bottom start.
goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_START,
popup, corner.TOP_START);
anchorRect = goog.style.getBounds(anchor);
popupRect = goog.style.getBounds(popup);
assertRoundedEquals('Left edge of popup should line up with left edge ' +
'of anchor.',
anchorRect.left,
popupRect.left);
assertRoundedEquals('Popup should be positioned just below the anchor.',
anchorRect.top + anchorRect.height,
popupRect.top);
}
function testPositionAtAnchorWithOffset() {
var anchor = document.getElementById('anchor1');
var popup = document.getElementById('popup1');
// Anchor top left to top left with an offset moving the popup away from the
// anchor.
goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_LEFT,
newCoord(-15, -20));
var anchorRect = goog.style.getBounds(anchor);
var popupRect = goog.style.getBounds(popup);
assertRoundedEquals('Left edge of popup should be fifteen pixels from ' +
'anchor.',
anchorRect.left,
popupRect.left + 15);
assertRoundedEquals('Top edge of popup should be twenty pixels from anchor.',
anchorRect.top,
popupRect.top + 20);
// Anchor top left to top left with an offset moving the popup towards the
// anchor.
goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_LEFT,
newCoord(3, 1));
anchorRect = goog.style.getBounds(anchor);
popupRect = goog.style.getBounds(popup);
assertRoundedEquals('Left edge of popup should be three pixels right of ' +
'the anchor\'s left edge',
anchorRect.left,
popupRect.left - 3);
assertRoundedEquals('Top edge of popup should be one pixel below of the ' +
'anchor\'s top edge',
anchorRect.top,
popupRect.top - 1);
}
function testPositionAtAnchorOverflowLeftEdgeRightToLeft() {
var anchor = document.getElementById('anchor5');
var popup = document.getElementById('popup5');
var status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_RIGHT,
undefined, undefined,
overflow.FAIL_X);
assertFalse('Positioning operation should have failed.',
(status & goog.positioning.OverflowStatus.FAILED) == 0);
// Change overflow strategy to ADJUST.
status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_RIGHT,
undefined, undefined,
overflow.ADJUST_X);
// Fails in Chrome because of infrastructure issues, temporarily disabled.
// See b/4274723.
expectedFailures.expectFailureFor(goog.userAgent.product.CHROME);
try {
assertTrue('Positioning operation should have been successful.',
(status & goog.positioning.OverflowStatus.FAILED) == 0);
assertTrue('Positioning operation should have been adjusted.',
(status & goog.positioning.OverflowStatus.ADJUSTED_X) != 0);
} catch (e) {
expectedFailures.handleException(e);
}
var anchorRect = goog.style.getBounds(anchor);
var popupRect = goog.style.getBounds(popup);
var parentRect = goog.style.getBounds(anchor.parentNode);
assertTrue('Position should have been adjusted so that the left edge of ' +
'the popup is left of the anchor but still within the bounding ' +
'box of the parent container.',
anchorRect.left <= popupRect.left <= parentRect.left);
}
function testPositionAtAnchorWithMargin() {
var anchor = document.getElementById('anchor1');
var popup = document.getElementById('popup1');
// Anchor top left to top left.
goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_LEFT, undefined,
new goog.math.Box(1, 2, 3, 4));
var anchorRect = goog.style.getBounds(anchor);
var popupRect = goog.style.getBounds(popup);
assertRoundedEquals('Left edge of popup should be four pixels from anchor.',
anchorRect.left,
popupRect.left - 4);
assertRoundedEquals('Top edge of popup should be one pixels from anchor.',
anchorRect.top,
popupRect.top - 1);
// Anchor top right to bottom right.
goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT,
popup, corner.TOP_RIGHT, undefined,
new goog.math.Box(1, 2, 3, 4));
anchorRect = goog.style.getBounds(anchor);
popupRect = goog.style.getBounds(popup);
var visibleAnchorRect = goog.positioning.getVisiblePart_(anchor);
assertRoundedEquals('Right edge of popup should line up with right edge ' +
'of anchor.',
visibleAnchorRect.left + visibleAnchorRect.width,
popupRect.left + popupRect.width + 2);
assertRoundedEquals('Popup should be positioned just below the anchor.',
visibleAnchorRect.top + visibleAnchorRect.height,
popupRect.top - 1);
}
function testPositionAtAnchorRightToLeft() {
if (goog.userAgent.IE && goog.userAgent.isVersion('6')) {
// These tests fails with IE6.
// TODO(user): Investigate the reason.
return;
}
var anchor = document.getElementById('anchor2');
var popup = document.getElementById('popup2');
// Anchor top left to top left.
goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_LEFT);
var anchorRect = goog.style.getBounds(anchor);
var popupRect = goog.style.getBounds(popup);
assertRoundedEquals('Left edge of popup should line up with left edge ' +
'of anchor.',
anchorRect.left,
popupRect.left);
assertRoundedEquals('Popup should have the same y position as the anchor.',
anchorRect.top,
popupRect.top);
// Anchor top start to bottom start.
goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_START,
popup, corner.TOP_START);
anchorRect = goog.style.getBounds(anchor);
popupRect = goog.style.getBounds(popup);
assertRoundedEquals('Right edge of popup should line up with right edge ' +
'of anchor.',
anchorRect.left + anchorRect.width,
popupRect.left + popupRect.width);
assertRoundedEquals('Popup should be positioned just below the anchor.',
anchorRect.top + anchorRect.height,
popupRect.top);
}
function testPositionAtAnchorRightToLeftWithScroll() {
if (goog.userAgent.IE && goog.userAgent.isVersion('6')) {
// These tests fails with IE6.
// TODO(user): Investigate the reason.
return;
}
var anchor = document.getElementById('anchor8');
var popup = document.getElementById('popup8');
// Anchor top left to top left.
goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_LEFT);
var anchorRect = goog.style.getBounds(anchor);
var popupRect = goog.style.getBounds(popup);
assertRoundedEquals('Left edge of popup should line up with left edge ' +
'of anchor.',
anchorRect.left,
popupRect.left);
assertRoundedEquals('Popup should have the same y position as the anchor.',
anchorRect.top,
popupRect.top);
// Anchor top start to bottom start.
goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_START,
popup, corner.TOP_START);
anchorRect = goog.style.getBounds(anchor);
popupRect = goog.style.getBounds(popup);
var visibleAnchorRect = goog.positioning.getVisiblePart_(anchor);
var visibleAnchorBox = visibleAnchorRect.toBox();
assertRoundedEquals('Right edge of popup should line up with right edge ' +
'of anchor.',
anchorRect.left + anchorRect.width,
popupRect.left + popupRect.width);
assertRoundedEquals('Popup should be positioned just below the anchor.',
visibleAnchorBox.bottom,
popupRect.top);
}
function testPositionAtAnchorBodyViewport() {
var anchor = document.getElementById('anchor1');
var popup = document.getElementById('popup3');
// Anchor top left to top left.
goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_LEFT);
var anchorRect = goog.style.getBounds(anchor);
var popupRect = goog.style.getBounds(popup);
assertEquals('Left edge of popup should line up with left edge of anchor.',
anchorRect.left,
popupRect.left);
assertRoughlyEquals('Popup should have the same y position as the anchor.',
anchorRect.top,
popupRect.top,
1);
// Anchor top start to bottom right.
goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT,
popup, corner.TOP_RIGHT);
anchorRect = goog.style.getBounds(anchor);
popupRect = goog.style.getBounds(popup);
assertEquals('Right edge of popup should line up with right edge of anchor.',
anchorRect.left + anchorRect.width,
popupRect.left + popupRect.width);
assertRoughlyEquals('Popup should be positioned just below the anchor.',
anchorRect.top + anchorRect.height,
popupRect.top,
1);
// Anchor top right to top left.
goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_RIGHT);
anchorRect = goog.style.getBounds(anchor);
popupRect = goog.style.getBounds(popup);
assertEquals('Right edge of popup should line up with left edge of anchor.',
anchorRect.left,
popupRect.left + popupRect.width);
assertRoughlyEquals('Popup should have the same y position as the anchor.',
anchorRect.top,
popupRect.top,
1);
}
function testPositionAtAnchorSpecificViewport() {
var anchor = document.getElementById('anchor1');
var popup = document.getElementById('popup3');
// Anchor top right to top left within outerbox.
var status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_RIGHT,
undefined, undefined,
overflow.FAIL_X);
anchorRect = goog.style.getBounds(anchor);
popupRect = goog.style.getBounds(popup);
assertTrue('Positioning operation should have been successful.',
(status & goog.positioning.OverflowStatus.FAILED) == 0);
assertTrue('X position should not have been adjusted.',
(status & goog.positioning.OverflowStatus.ADJUSTED_X) == 0);
assertTrue('Y position should not have been adjusted.',
(status & goog.positioning.OverflowStatus.ADJUSTED_Y) == 0);
assertEquals('Right edge of popup should line up with left edge of anchor.',
anchorRect.left,
popupRect.left + popupRect.width);
assertRoughlyEquals('Popup should have the same y position as the anchor.',
anchorRect.top,
popupRect.top,
1);
// position again within box1.
var box = document.getElementById('box1');
var viewport = goog.style.getBounds(box);
status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_RIGHT,
undefined, undefined,
overflow.FAIL_X, undefined,
viewport);
assertFalse('Positioning operation should have failed.',
(status & goog.positioning.OverflowStatus.FAILED) == 0);
// Change overflow strategy to adjust.
status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_RIGHT,
undefined, undefined,
overflow.ADJUST_X, undefined,
viewport);
anchorRect = goog.style.getBounds(anchor);
popupRect = goog.style.getBounds(popup);
assertTrue('Positioning operation should have been successful.',
(status & goog.positioning.OverflowStatus.FAILED) == 0);
assertFalse('X position should have been adjusted.',
(status & goog.positioning.OverflowStatus.ADJUSTED_X) == 0);
assertTrue('Y position should not have been adjusted.',
(status & goog.positioning.OverflowStatus.ADJUSTED_Y) == 0);
assertRoughlyEquals(
'Left edge of popup should line up with left edge of viewport.',
viewport.left, popupRect.left, EPSILON);
assertRoughlyEquals('Popup should have the same y position as the anchor.',
anchorRect.top,
popupRect.top,
1);
}
function testPositionAtAnchorOutsideViewport() {
var anchor = document.getElementById('anchor4');
var popup = document.getElementById('popup1');
var status = goog.positioning.positionAtAnchor(anchor, corner.TOP_LEFT,
popup, corner.TOP_RIGHT);
var anchorRect = goog.style.getBounds(anchor);
var popupRect = goog.style.getBounds(popup);
assertTrue('Positioning operation should have been successful.',
(status & goog.positioning.OverflowStatus.FAILED) == 0);
assertTrue('X position should not have been adjusted.',
(status & goog.positioning.OverflowStatus.ADJUSTED_X) == 0);
assertTrue('Y position should not have been adjusted.',
(status & goog.positioning.OverflowStatus.ADJUSTED_Y) == 0);
assertEquals('Right edge of popup should line up with left edge of anchor.',
anchorRect.left,
popupRect.left + popupRect.width);
// Change overflow strategy to fail.
status = goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT,
popup, corner.TOP_RIGHT,
undefined, undefined,
overflow.FAIL_X);
assertFalse('Positioning operation should have failed.',
(status & goog.positioning.OverflowStatus.FAILED) == 0);
// Change overflow strategy to adjust.
status = goog.positioning.positionAtAnchor(anchor, corner.BOTTOM_RIGHT,
popup, corner.TOP_RIGHT,
undefined, undefined,
overflow.ADJUST_X);
anchorRect = goog.style.getBounds(anchor);
popupRect = goog.style.getBounds(popup);
assertTrue('Positioning operation should have been successful.',
(status & goog.positioning.OverflowStatus.FAILED) == 0);
assertFalse('X position should have been adjusted.',
(status & goog.positioning.OverflowStatus.ADJUSTED_X) == 0);
assertTrue('Y position should not have been adjusted.',
(status & goog.positioning.OverflowStatus.ADJUSTED_Y) == 0);
assertRoughlyEquals(
'Left edge of popup should line up with left edge of viewport.',
0, popupRect.left, EPSILON);
assertEquals('Popup should be positioned just below the anchor.',
anchorRect.top + anchorRect.height,
popupRect.top);
}
function testAdjustForViewportFailIgnore() {
var f = goog.positioning.adjustForViewport_;
var viewport = new goog.math.Box(100, 200, 200, 100);
var overflow = goog.positioning.Overflow.IGNORE;
var pos = newCoord(150, 150);
var size = newSize(50, 50);
assertEquals('Viewport overflow should be ignored.',
goog.positioning.OverflowStatus.NONE,
f(pos, size, viewport, overflow));
pos = newCoord(150, 150);
size = newSize(100, 50);
assertEquals('Viewport overflow should be ignored.',
goog.positioning.OverflowStatus.NONE,
f(pos, size, viewport, overflow));
pos = newCoord(50, 50);
size = newSize(50, 50);
assertEquals('Viewport overflow should be ignored.',
goog.positioning.OverflowStatus.NONE,
f(pos, size, viewport, overflow));
}
function testAdjustForViewportFailXY() {
var f = goog.positioning.adjustForViewport_;
var viewport = new goog.math.Box(100, 200, 200, 100);
var overflow = goog.positioning.Overflow.FAIL_X |
goog.positioning.Overflow.FAIL_Y;
var pos = newCoord(150, 150);
var size = newSize(50, 50);
assertEquals('Element should not overflow viewport.',
goog.positioning.OverflowStatus.NONE,
f(pos, size, viewport, overflow));
pos = newCoord(150, 150);
size = newSize(100, 50);
assertEquals('Element should overflow the right edge of viewport.',
goog.positioning.OverflowStatus.FAILED_RIGHT,
f(pos, size, viewport, overflow));
pos = newCoord(150, 150);
size = newSize(50, 100);
assertEquals('Element should overflow the bottom edge of viewport.',
goog.positioning.OverflowStatus.FAILED_BOTTOM,
f(pos, size, viewport, overflow));
pos = newCoord(50, 150);
size = newSize(50, 50);
assertEquals('Element should overflow the left edge of viewport.',
goog.positioning.OverflowStatus.FAILED_LEFT,
f(pos, size, viewport, overflow));
pos = newCoord(150, 50);
size = newSize(50, 50);
assertEquals('Element should overflow the top edge of viewport.',
goog.positioning.OverflowStatus.FAILED_TOP,
f(pos, size, viewport, overflow));
pos = newCoord(50, 50);
size = newSize(50, 50);
assertEquals('Element should overflow the left & top edges of viewport.',
goog.positioning.OverflowStatus.FAILED_LEFT |
goog.positioning.OverflowStatus.FAILED_TOP,
f(pos, size, viewport, overflow));
}
function testAdjustForViewportAdjustXFailY() {
var f = goog.positioning.adjustForViewport_;
var viewport = new goog.math.Box(100, 200, 200, 100);
var overflow = goog.positioning.Overflow.ADJUST_X |
goog.positioning.Overflow.FAIL_Y;
var pos = newCoord(150, 150);
var size = newSize(50, 50);
assertEquals('Element should not overflow viewport.',
goog.positioning.OverflowStatus.NONE,
f(pos, size, viewport, overflow));
assertEquals('X Position should not have been changed.', 150, pos.x);
assertEquals('Y Position should not have been changed.', 150, pos.y);
pos = newCoord(150, 150);
size = newSize(100, 50);
assertEquals('Element position should be adjusted not to overflow right ' +
'edge of viewport.',
goog.positioning.OverflowStatus.ADJUSTED_X,
f(pos, size, viewport, overflow));
assertEquals('X Position should be adjusted to 100.', 100, pos.x);
assertEquals('Y Position should not have been changed.', 150, pos.y);
pos = newCoord(50, 150);
size = newSize(100, 50);
assertEquals('Element position should be adjusted not to overflow left ' +
'edge of viewport.',
goog.positioning.OverflowStatus.ADJUSTED_X,
f(pos, size, viewport, overflow));
assertEquals('X Position should be adjusted to 100.', 100, pos.x);
assertEquals('Y Position should not have been changed.', 150, pos.y);
pos = newCoord(50, 50);
size = newSize(100, 50);
assertEquals('Element position should be adjusted not to overflow left ' +
'edge of viewport, should overflow bottom edge.',
goog.positioning.OverflowStatus.ADJUSTED_X |
goog.positioning.OverflowStatus.FAILED_TOP,
f(pos, size, viewport, overflow));
assertEquals('X Position should be adjusted to 100.', 100, pos.x);
assertEquals('Y Position should not have been changed.', 50, pos.y);
}
function testAdjustForViewportResizeHeight() {
var f = goog.positioning.adjustForViewport_;
var viewport = new goog.math.Box(0, 200, 200, 0);
var overflow = goog.positioning.Overflow.RESIZE_HEIGHT;
var pos = newCoord(150, 150);
var size = newSize(25, 100);
assertEquals('Viewport height should be resized.',
goog.positioning.OverflowStatus.HEIGHT_ADJUSTED,
f(pos, size, viewport, overflow));
assertEquals('Height should be resized to 50.',
50, size.height);
var pos = newCoord(0, 0);
var size = newSize(50, 250);
assertEquals('Viewport height should be resized.',
goog.positioning.OverflowStatus.HEIGHT_ADJUSTED,
f(pos, size, viewport, overflow));
assertEquals('Height should be resized to 200.',
200, size.height);
var pos = newCoord(0, -50);
var size = newSize(50, 240);
assertEquals('Viewport height should be resized.',
goog.positioning.OverflowStatus.HEIGHT_ADJUSTED,
f(pos, size, viewport, overflow));
assertEquals('Height should be resized to 190.',
190, size.height);
pos = newCoord(150, 150);
size = newSize(50, 50);
assertEquals('No Viewport overflow.',
goog.positioning.OverflowStatus.NONE,
f(pos, size, viewport, overflow));
}
function testPositionAtCoordinateResizeHeight() {
var f = goog.positioning.positionAtCoordinate;
var viewport = new goog.math.Box(0, 50, 50, 0);
var overflow = goog.positioning.Overflow.RESIZE_HEIGHT |
goog.positioning.Overflow.ADJUST_Y;
var popup = document.getElementById('popup1');
var corner = goog.positioning.Corner.BOTTOM_LEFT;
var pos = newCoord(100, 100);
assertEquals('Viewport height should be resized.',
goog.positioning.OverflowStatus.HEIGHT_ADJUSTED |
goog.positioning.OverflowStatus.ADJUSTED_Y,
f(pos, popup, corner, undefined, viewport, overflow));
var bounds = goog.style.getSize(popup);
assertEquals('Height should be resized to the size of the viewport.',
50, bounds.height);
}
function testGetEffectiveCornerLeftToRight() {
var f = goog.positioning.getEffectiveCorner;
var el = document.getElementById('ltr');
assertEquals('TOP_LEFT should be unchanged for ltr.',
corner.TOP_LEFT,
f(el, corner.TOP_LEFT));
assertEquals('TOP_RIGHT should be unchanged for ltr.',
corner.TOP_RIGHT,
f(el, corner.TOP_RIGHT));
assertEquals('BOTTOM_LEFT should be unchanged for ltr.',
corner.BOTTOM_LEFT,
f(el, corner.BOTTOM_LEFT));
assertEquals('BOTTOM_RIGHT should be unchanged for ltr.',
corner.BOTTOM_RIGHT,
f(el, corner.BOTTOM_RIGHT));
assertEquals('TOP_START should be TOP_LEFT for ltr.',
corner.TOP_LEFT,
f(el, corner.TOP_START));
assertEquals('TOP_END should be TOP_RIGHT for ltr.',
corner.TOP_RIGHT,
f(el, corner.TOP_END));
assertEquals('BOTTOM_START should be BOTTOM_LEFT for ltr.',
corner.BOTTOM_LEFT,
f(el, corner.BOTTOM_START));
assertEquals('BOTTOM_END should be BOTTOM_RIGHT for ltr.',
corner.BOTTOM_RIGHT,
f(el, corner.BOTTOM_END));
}
function testGetEffectiveCornerRightToLeft() {
var f = goog.positioning.getEffectiveCorner;
var el = document.getElementById('rtl');
assertEquals('TOP_LEFT should be unchanged for rtl.',
corner.TOP_LEFT,
f(el, corner.TOP_LEFT));
assertEquals('TOP_RIGHT should be unchanged for rtl.',
corner.TOP_RIGHT,
f(el, corner.TOP_RIGHT));
assertEquals('BOTTOM_LEFT should be unchanged for rtl.',
corner.BOTTOM_LEFT,
f(el, corner.BOTTOM_LEFT));
assertEquals('BOTTOM_RIGHT should be unchanged for rtl.',
corner.BOTTOM_RIGHT,
f(el, corner.BOTTOM_RIGHT));
assertEquals('TOP_START should be TOP_RIGHT for rtl.',
corner.TOP_RIGHT,
f(el, corner.TOP_START));
assertEquals('TOP_END should be TOP_LEFT for rtl.',
corner.TOP_LEFT,
f(el, corner.TOP_END));
assertEquals('BOTTOM_START should be BOTTOM_RIGHT for rtl.',
corner.BOTTOM_RIGHT,
f(el, corner.BOTTOM_START));
assertEquals('BOTTOM_END should be BOTTOM_LEFT for rtl.',
corner.BOTTOM_LEFT,
f(el, corner.BOTTOM_END));
}
function testFlipCornerHorizontal() {
var f = goog.positioning.flipCornerHorizontal;
assertEquals('TOP_LEFT should be flipped to TOP_RIGHT.',
corner.TOP_RIGHT,
f(corner.TOP_LEFT));
assertEquals('TOP_RIGHT should be flipped to TOP_LEFT.',
corner.TOP_LEFT,
f(corner.TOP_RIGHT));
assertEquals('BOTTOM_LEFT should be flipped to BOTTOM_RIGHT.',
corner.BOTTOM_RIGHT,
f(corner.BOTTOM_LEFT));
assertEquals('BOTTOM_RIGHT should be flipped to BOTTOM_LEFT.',
corner.BOTTOM_LEFT,
f(corner.BOTTOM_RIGHT));
assertEquals('TOP_START should be flipped to TOP_END.',
corner.TOP_END,
f(corner.TOP_START));
assertEquals('TOP_END should be flipped to TOP_START.',
corner.TOP_START,
f(corner.TOP_END));
assertEquals('BOTTOM_START should be flipped to BOTTOM_END.',
corner.BOTTOM_END,
f(corner.BOTTOM_START));
assertEquals('BOTTOM_END should be flipped to BOTTOM_START.',
corner.BOTTOM_START,
f(corner.BOTTOM_END));
}
function testFlipCornerVertical() {
var f = goog.positioning.flipCornerVertical;
assertEquals('TOP_LEFT should be flipped to BOTTOM_LEFT.',
corner.BOTTOM_LEFT,
f(corner.TOP_LEFT));
assertEquals('TOP_RIGHT should be flipped to BOTTOM_RIGHT.',
corner.BOTTOM_RIGHT,
f(corner.TOP_RIGHT));
assertEquals('BOTTOM_LEFT should be flipped to TOP_LEFT.',
corner.TOP_LEFT,
f(corner.BOTTOM_LEFT));
assertEquals('BOTTOM_RIGHT should be flipped to TOP_RIGHT.',
corner.TOP_RIGHT,
f(corner.BOTTOM_RIGHT));
assertEquals('TOP_START should be flipped to BOTTOM_START.',
corner.BOTTOM_START,
f(corner.TOP_START));
assertEquals('TOP_END should be flipped to BOTTOM_END.',
corner.BOTTOM_END,
f(corner.TOP_END));
assertEquals('BOTTOM_START should be flipped to TOP_START.',
corner.TOP_START,
f(corner.BOTTOM_START));
assertEquals('BOTTOM_END should be flipped to TOP_END.',
corner.TOP_END,
f(corner.BOTTOM_END));
}
function testFlipCorner() {
var f = goog.positioning.flipCorner;
assertEquals('TOP_LEFT should be flipped to BOTTOM_RIGHT.',
corner.BOTTOM_RIGHT,
f(corner.TOP_LEFT));
assertEquals('TOP_RIGHT should be flipped to BOTTOM_LEFT.',
corner.BOTTOM_LEFT,
f(corner.TOP_RIGHT));
assertEquals('BOTTOM_LEFT should be flipped to TOP_RIGHT.',
corner.TOP_RIGHT,
f(corner.BOTTOM_LEFT));
assertEquals('BOTTOM_RIGHT should be flipped to TOP_LEFT.',
corner.TOP_LEFT,
f(corner.BOTTOM_RIGHT));
assertEquals('TOP_START should be flipped to BOTTOM_END.',
corner.BOTTOM_END,
f(corner.TOP_START));
assertEquals('TOP_END should be flipped to BOTTOM_START.',
corner.BOTTOM_START,
f(corner.TOP_END));
assertEquals('BOTTOM_START should be flipped to TOP_END.',
corner.TOP_END,
f(corner.BOTTOM_START));
assertEquals('BOTTOM_END should be flipped to TOP_START.',
corner.TOP_START,
f(corner.BOTTOM_END));
}
function testPositionAtAnchorFrameViewportStandard() {
var iframe = document.getElementById('iframe-standard');
var iframeDoc = goog.dom.getFrameContentDocument(iframe);
assertTrue(new goog.dom.DomHelper(iframeDoc).isCss1CompatMode());
new goog.dom.DomHelper(iframeDoc).getDocumentScrollElement().scrollTop = 100;
var anchor = iframeDoc.getElementById('anchor1');
var popup = document.getElementById('popup6');
var status = goog.positioning.positionAtAnchor(
anchor, corner.TOP_RIGHT, popup, corner.BOTTOM_RIGHT);
var iframeRect = goog.style.getBounds(iframe);
var popupRect = goog.style.getBounds(popup);
assertEquals('Status should not have any ADJUSTED and FAILED.',
goog.positioning.OverflowStatus.NONE, status);
assertRoundedEquals('Popup should be positioned just above the iframe, ' +
'not above the anchor element inside the iframe',
iframeRect.top,
popupRect.top + popupRect.height);
}
function testPositionAtAnchorFrameViewportQuirk() {
var iframe = document.getElementById('iframe-quirk');
var iframeDoc = goog.dom.getFrameContentDocument(iframe);
assertFalse(new goog.dom.DomHelper(iframeDoc).isCss1CompatMode());
window.scrollTo(0, 100);
new goog.dom.DomHelper(iframeDoc).getDocumentScrollElement().scrollTop = 100;
var anchor = iframeDoc.getElementById('anchor1');
var popup = document.getElementById('popup6');
var status = goog.positioning.positionAtAnchor(
anchor, corner.TOP_RIGHT, popup, corner.BOTTOM_RIGHT);
var iframeRect = goog.style.getBounds(iframe);
var popupRect = goog.style.getBounds(popup);
assertEquals('Status should not have any ADJUSTED and FAILED.',
goog.positioning.OverflowStatus.NONE, status);
assertRoundedEquals('Popup should be positioned just above the iframe, ' +
'not above the anchor element inside the iframe',
iframeRect.top,
popupRect.top + popupRect.height);
}
function testPositionAtAnchorFrameViewportWithPopupInScroller() {
var iframe = document.getElementById('iframe-standard');
var iframeDoc = goog.dom.getFrameContentDocument(iframe);
new goog.dom.DomHelper(iframeDoc).getDocumentScrollElement().scrollTop = 100;
var anchor = iframeDoc.getElementById('anchor1');
var popup = document.getElementById('popup7');
popup.offsetParent.scrollTop = 50;
var status = goog.positioning.positionAtAnchor(
anchor, corner.TOP_RIGHT, popup, corner.BOTTOM_RIGHT);
var iframeRect = goog.style.getBounds(iframe);
var popupRect = goog.style.getBounds(popup);
assertEquals('Status should not have any ADJUSTED and FAILED.',
goog.positioning.OverflowStatus.NONE, status);
assertRoughlyEquals('Popup should be positioned just above the iframe, ' +
'not above the anchor element inside the iframe',
iframeRect.top,
popupRect.top + popupRect.height,
ALLOWED_OFFSET);
}
function testPositionAtAnchorNestedFrames() {
var outerIframe = document.getElementById('nested-outer');
var outerDoc = goog.dom.getFrameContentDocument(outerIframe);
var popup = outerDoc.getElementById('popup1');
var innerIframe = outerDoc.getElementById('inner-frame');
var innerDoc = goog.dom.getFrameContentDocument(innerIframe);
var anchor = innerDoc.getElementById('anchor1');
var status = goog.positioning.positionAtAnchor(
anchor, corner.TOP_LEFT, popup, corner.BOTTOM_LEFT);
assertEquals('Status should not have any ADJUSTED and FAILED.',
goog.positioning.OverflowStatus.NONE, status);
var innerIframeRect = goog.style.getBounds(innerIframe);
var popupRect = goog.style.getBounds(popup);
assertRoundedEquals('Top of frame should align with bottom of the popup',
innerIframeRect.top, popupRect.top + popupRect.height);
// The anchor is scrolled up by 10px.
// Popup position should be the same as above.
goog.dom.getWindow(innerDoc).scrollTo(0, 10);
status = goog.positioning.positionAtAnchor(
anchor, corner.TOP_LEFT, popup, corner.BOTTOM_LEFT);
assertEquals('Status should not have any ADJUSTED and FAILED.',
goog.positioning.OverflowStatus.NONE, status);
innerIframeRect = goog.style.getBounds(innerIframe);
popupRect = goog.style.getBounds(popup);
assertRoundedEquals('Top of frame should align with bottom of the popup',
innerIframeRect.top, popupRect.top + popupRect.height);
}
function testPositionAtAnchorOffscreen() {
var offset = 0;
var anchor = goog.dom.getElement('offscreen-anchor');
var popup = goog.dom.getElement('popup3');
goog.positioning.positionAtAnchor(
anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, null, null,
overflow.ADJUST_X | overflow.ADJUST_Y);
assertObjectEquals(
newCoord(offset, offset), goog.style.getPageOffset(popup));
goog.positioning.positionAtAnchor(
anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, null, null,
overflow.ADJUST_X_EXCEPT_OFFSCREEN | overflow.ADJUST_Y);
assertObjectEquals(
newCoord(-1000, offset), goog.style.getPageOffset(popup));
goog.positioning.positionAtAnchor(
anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, null, null,
overflow.ADJUST_X | overflow.ADJUST_Y_EXCEPT_OFFSCREEN);
assertObjectEquals(
newCoord(offset, -1000), goog.style.getPageOffset(popup));
goog.positioning.positionAtAnchor(
anchor, corner.TOP_LEFT, popup, corner.TOP_LEFT, null, null,
overflow.ADJUST_X_EXCEPT_OFFSCREEN | overflow.ADJUST_Y_EXCEPT_OFFSCREEN);
assertObjectEquals(
newCoord(-1000, -1000),
goog.style.getPageOffset(popup));
}
function testPositionAtAnchorWithOverflowScrollOffsetParent() {
var testAreaOffset = goog.style.getPageOffset(testArea);
var scrollbarWidth = goog.style.getScrollbarWidth();
window.scrollTo(testAreaOffset.x, testAreaOffset.y);
var overflowDiv = goog.dom.createElement('div');
overflowDiv.style.overflow = 'scroll';
overflowDiv.style.position = 'relative';
goog.style.setSize(overflowDiv, 200 /* width */, 100 /* height */);
var anchor = goog.dom.createElement('div');
anchor.style.position = 'absolute';
goog.style.setSize(anchor, 50 /* width */, 50 /* height */);
goog.style.setPosition(anchor, 300 /* left */, 300 /* top */);
var popup = createPopupDiv(75 /* width */, 50 /* height */);
goog.dom.append(testArea, overflowDiv, anchor);
goog.dom.append(overflowDiv, popup);
// Popup should always be positioned within the overflowDiv
goog.style.setPosition(overflowDiv, 0 /* left */, 0 /* top */);
goog.positioning.positionAtAnchor(
anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, null, null,
overflow.ADJUST_X | overflow.ADJUST_Y);
assertObjectRoughlyEquals(
new goog.math.Coordinate(
testAreaOffset.x + 200 - 75 - scrollbarWidth,
testAreaOffset.y + 100 - 50 - scrollbarWidth),
goog.style.getPageOffset(popup),
1);
goog.style.setPosition(overflowDiv, 400 /* left */, 0 /* top */);
goog.positioning.positionAtAnchor(
anchor, corner.TOP_RIGHT, popup, corner.TOP_LEFT, null, null,
overflow.ADJUST_X | overflow.ADJUST_Y);
assertObjectRoughlyEquals(
new goog.math.Coordinate(
testAreaOffset.x + 400, testAreaOffset.y + 100 - 50 - scrollbarWidth),
goog.style.getPageOffset(popup),
1);
goog.style.setPosition(overflowDiv, 0 /* left */, 400 /* top */);
goog.positioning.positionAtAnchor(
anchor, corner.BOTTOM_LEFT, popup, corner.BOTTOM_RIGHT, null, null,
overflow.ADJUST_X | overflow.ADJUST_Y);
assertObjectRoughlyEquals(
new goog.math.Coordinate(
testAreaOffset.x + 200 - 75 - scrollbarWidth, testAreaOffset.y + 400),
goog.style.getPageOffset(popup),
1);
goog.style.setPosition(overflowDiv, 400 /* left */, 400 /* top */);
goog.positioning.positionAtAnchor(
anchor, corner.BOTTOM_RIGHT, popup, corner.BOTTOM_LEFT, null, null,
overflow.ADJUST_X | overflow.ADJUST_Y);
assertObjectRoughlyEquals(
new goog.math.Coordinate(
testAreaOffset.x + 400, testAreaOffset.y + 400),
goog.style.getPageOffset(popup),
1);
// No overflow.
goog.style.setPosition(overflowDiv, 300 - 50 /* left */, 300 /* top */);
goog.positioning.positionAtAnchor(
anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, null, null,
overflow.ADJUST_X | overflow.ADJUST_Y);
assertObjectRoughlyEquals(
new goog.math.Coordinate(
testAreaOffset.x + 300 - 50, testAreaOffset.y + 300),
goog.style.getPageOffset(popup),
1);
}
function testPositionAtAnchorWithOverflowHiddenParent() {
var testAreaOffset = goog.style.getPageOffset(testArea);
window.scrollTo(testAreaOffset.x, testAreaOffset.y);
var overflowDiv = goog.dom.createElement('div');
overflowDiv.style.overflow = 'hidden';
overflowDiv.style.position = 'relative';
goog.style.setSize(overflowDiv, 200 /* width */, 100 /* height */);
var anchor = goog.dom.createElement('div');
anchor.style.position = 'absolute';
goog.style.setSize(anchor, 50 /* width */, 50 /* height */);
goog.style.setPosition(anchor, 300 /* left */, 300 /* top */);
var popup = createPopupDiv(75 /* width */, 50 /* height */);
goog.dom.append(testArea, overflowDiv, anchor);
goog.dom.append(overflowDiv, popup);
// Popup should always be positioned within the overflowDiv
goog.style.setPosition(overflowDiv, 0 /* left */, 0 /* top */);
goog.positioning.positionAtAnchor(
anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, null, null,
overflow.ADJUST_X | overflow.ADJUST_Y);
assertObjectRoughlyEquals(
new goog.math.Coordinate(
testAreaOffset.x + 200 - 75, testAreaOffset.y + 100 - 50),
goog.style.getPageOffset(popup),
1);
goog.style.setPosition(overflowDiv, 400 /* left */, 0 /* top */);
goog.positioning.positionAtAnchor(
anchor, corner.TOP_RIGHT, popup, corner.TOP_LEFT, null, null,
overflow.ADJUST_X | overflow.ADJUST_Y);
assertObjectRoughlyEquals(
new goog.math.Coordinate(
testAreaOffset.x + 400, testAreaOffset.y + 100 - 50),
goog.style.getPageOffset(popup),
1);
goog.style.setPosition(overflowDiv, 0 /* left */, 400 /* top */);
goog.positioning.positionAtAnchor(
anchor, corner.BOTTOM_LEFT, popup, corner.BOTTOM_RIGHT, null, null,
overflow.ADJUST_X | overflow.ADJUST_Y);
assertObjectRoughlyEquals(
new goog.math.Coordinate(
testAreaOffset.x + 200 - 75, testAreaOffset.y + 400),
goog.style.getPageOffset(popup),
1);
goog.style.setPosition(overflowDiv, 400 /* left */, 400 /* top */);
goog.positioning.positionAtAnchor(
anchor, corner.BOTTOM_RIGHT, popup, corner.BOTTOM_LEFT, null, null,
overflow.ADJUST_X | overflow.ADJUST_Y);
assertObjectRoughlyEquals(
new goog.math.Coordinate(
testAreaOffset.x + 400, testAreaOffset.y + 400),
goog.style.getPageOffset(popup),
1);
// No overflow.
goog.style.setPosition(overflowDiv, 300 - 50 /* left */, 300 /* top */);
goog.positioning.positionAtAnchor(
anchor, corner.TOP_LEFT, popup, corner.TOP_RIGHT, null, null,
overflow.ADJUST_X | overflow.ADJUST_Y);
assertObjectRoughlyEquals(
new goog.math.Coordinate(
testAreaOffset.x + 300 - 50, testAreaOffset.y + 300),
goog.style.getPageOffset(popup),
1);
}
function createPopupDiv(width, height) {
var popupDiv = goog.dom.createElement('div');
popupDiv.style.position = 'absolute';
goog.style.setSize(popupDiv, width, height);
goog.style.setPosition(popupDiv, 0 /* left */, 250 /* top */);
return popupDiv;
}
function newCoord(x, y) {
return new goog.math.Coordinate(x, y);
}
function newSize(w, h) {
return new goog.math.Size(w, h);
}
| 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 Client viewport positioning class.
*
* @author robbyw@google.com (Robert Walker)
* @author eae@google.com (Emil A Eklund)
*/
goog.provide('goog.positioning.ViewportClientPosition');
goog.require('goog.math.Box');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Size');
goog.require('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.positioning.ClientPosition}
*/
goog.positioning.ViewportClientPosition = function(arg1, opt_arg2) {
goog.positioning.ClientPosition.call(this, arg1, opt_arg2);
};
goog.inherits(goog.positioning.ViewportClientPosition,
goog.positioning.ClientPosition);
/**
* The last-resort overflow strategy, if the popup fails to fit.
* @type {number}
* @private
*/
goog.positioning.ViewportClientPosition.prototype.lastResortOverflow_ = 0;
/**
* Set the last-resort overflow strategy, if the popup fails to fit.
* @param {number} overflow A bitmask of goog.positioning.Overflow strategies.
*/
goog.positioning.ViewportClientPosition.prototype.setLastResortOverflow =
function(overflow) {
this.lastResortOverflow_ = overflow;
};
/**
* Repositions the popup according to the current state.
*
* @param {Element} element The DOM element of the popup.
* @param {goog.positioning.Corner} popupCorner The corner of the popup
* element that that should be positioned adjacent to the anchorElement.
* One of the goog.positioning.Corner constants.
* @param {goog.math.Box=} opt_margin A margin specified in pixels.
* @param {goog.math.Size=} opt_preferredSize Preferred size fo the element.
* @override
*/
goog.positioning.ViewportClientPosition.prototype.reposition = function(
element, popupCorner, opt_margin, opt_preferredSize) {
var viewportElt = goog.style.getClientViewportElement(element);
var viewport = goog.style.getVisibleRectForElement(viewportElt);
var scrollEl = goog.dom.getDomHelper(element).getDocumentScrollElement();
var clientPos = new goog.math.Coordinate(
this.coordinate.x + scrollEl.scrollLeft,
this.coordinate.y + scrollEl.scrollTop);
var failXY = goog.positioning.Overflow.FAIL_X |
goog.positioning.Overflow.FAIL_Y;
var corner = popupCorner;
// Try the requested position.
var status = goog.positioning.positionAtCoordinate(clientPos, element, corner,
opt_margin, viewport, failXY, opt_preferredSize);
if ((status & goog.positioning.OverflowStatus.FAILED) == 0) {
return;
}
// Outside left or right edge of viewport, try try to flip it horizontally.
if (status & goog.positioning.OverflowStatus.FAILED_LEFT ||
status & goog.positioning.OverflowStatus.FAILED_RIGHT) {
corner = goog.positioning.flipCornerHorizontal(corner);
}
// Outside top or bottom edge of viewport, try try to flip it vertically.
if (status & goog.positioning.OverflowStatus.FAILED_TOP ||
status & goog.positioning.OverflowStatus.FAILED_BOTTOM) {
corner = goog.positioning.flipCornerVertical(corner);
}
// Try flipped position.
status = goog.positioning.positionAtCoordinate(clientPos, element, corner,
opt_margin, viewport, failXY, opt_preferredSize);
if ((status & goog.positioning.OverflowStatus.FAILED) == 0) {
return;
}
// If that failed, the viewport is simply too small to contain the popup.
// Revert to the original position.
goog.positioning.positionAtCoordinate(
clientPos, element, popupCorner, opt_margin, viewport,
this.lastResortOverflow_, opt_preferredSize);
};
| 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 Client positioning class.
*
*/
goog.provide('goog.positioning.ViewportPosition');
goog.require('goog.math.Box');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Size');
goog.require('goog.positioning.AbstractPosition');
/**
* Encapsulates a popup position where the popup is positioned according to
* coordinates relative to the element's viewport (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.positioning.AbstractPosition}
*/
goog.positioning.ViewportPosition = function(arg1, opt_arg2) {
this.coordinate = arg1 instanceof goog.math.Coordinate ? arg1 :
new goog.math.Coordinate(/** @type {number} */ (arg1), opt_arg2);
};
goog.inherits(goog.positioning.ViewportPosition,
goog.positioning.AbstractPosition);
/**
* Repositions the popup according to the current state
*
* @param {Element} element The DOM element of the popup.
* @param {goog.positioning.Corner} popupCorner The corner of the popup
* element that that should be positioned adjacent to the anchorElement.
* @param {goog.math.Box=} opt_margin A margin specified in pixels.
* @param {goog.math.Size=} opt_preferredSize Preferred size of the element.
* @override
*/
goog.positioning.ViewportPosition.prototype.reposition = function(
element, popupCorner, opt_margin, opt_preferredSize) {
goog.positioning.positionAtAnchor(
goog.style.getClientViewportElement(element),
goog.positioning.Corner.TOP_LEFT, element, popupCorner,
this.coordinate, opt_margin, null, opt_preferredSize);
};
| 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 Anchored viewport positioning class with both adjust and
* resize options for the popup.
*
* @author eae@google.com (Emil A Eklund)
* @author tildahl@google.com (Michael Tildahl)
*/
goog.provide('goog.positioning.MenuAnchoredPosition');
goog.require('goog.math.Box');
goog.require('goog.math.Size');
goog.require('goog.positioning');
goog.require('goog.positioning.AnchoredViewportPosition');
goog.require('goog.positioning.Corner');
goog.require('goog.positioning.Overflow');
/**
* Encapsulates a popup position where the popup is anchored at a corner of
* an element. The positioning behavior changes based on the values of
* opt_adjust and opt_resize.
*
* When using this positioning object it's recommended that the movable element
* be absolutely positioned.
*
* @param {Element} anchorElement Element the movable element should be
* anchored against.
* @param {goog.positioning.Corner} corner Corner of anchored element the
* movable element should be positioned 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.
* @param {boolean=} opt_resize Whether the positioning should be adjusted until
* the element fits inside the viewport on the X axis and its height is
* resized so if fits in the viewport. This take precedence over opt_adjust.
* @constructor
* @extends {goog.positioning.AnchoredViewportPosition}
*/
goog.positioning.MenuAnchoredPosition = function(anchorElement,
corner,
opt_adjust,
opt_resize) {
goog.positioning.AnchoredViewportPosition.call(this, anchorElement, corner,
opt_adjust || opt_resize);
if (opt_adjust || opt_resize) {
var overflowX = goog.positioning.Overflow.ADJUST_X_EXCEPT_OFFSCREEN;
var overflowY = opt_resize ?
goog.positioning.Overflow.RESIZE_HEIGHT :
goog.positioning.Overflow.ADJUST_Y_EXCEPT_OFFSCREEN;
this.setLastResortOverflow(overflowX | overflowY);
}
};
goog.inherits(goog.positioning.MenuAnchoredPosition,
goog.positioning.AnchoredViewportPosition);
| 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 Client viewport positioning class.
*
*/
goog.provide('goog.positioning.AbsolutePosition');
goog.require('goog.math.Box');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Size');
goog.require('goog.positioning');
goog.require('goog.positioning.AbstractPosition');
/**
* 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}
*/
goog.positioning.AbsolutePosition = function(arg1, opt_arg2) {
/**
* Coordinate to position popup at.
* @type {goog.math.Coordinate}
*/
this.coordinate = arg1 instanceof goog.math.Coordinate ? arg1 :
new goog.math.Coordinate(/** @type {number} */ (arg1), opt_arg2);
};
goog.inherits(goog.positioning.AbsolutePosition,
goog.positioning.AbstractPosition);
/**
* Repositions the popup according to the current state.
*
* @param {Element} movableElement The DOM element to position.
* @param {goog.positioning.Corner} movableCorner The corner of the movable
* element that should be positioned at the specified position.
* @param {goog.math.Box=} opt_margin A margin specified in pixels.
* @param {goog.math.Size=} opt_preferredSize Prefered size of the
* movableElement.
* @override
*/
goog.positioning.AbsolutePosition.prototype.reposition = function(
movableElement, movableCorner, opt_margin, opt_preferredSize) {
goog.positioning.positionAtCoordinate(this.coordinate,
movableElement,
movableCorner,
opt_margin,
null,
null,
opt_preferredSize);
};
| 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.
/**
* Tests for {@code goog.positioning.ClientPosition}
*/
goog.provide('goog.positioning.clientPositionTest');
goog.setTestOnly('goog.positioning.clientPositionTest');
goog.require('goog.dom');
goog.require('goog.positioning.ClientPosition');
goog.require('goog.style');
goog.require('goog.testing.jsunit');
/**
* Prefabricated popup element for convenient. This is created during
* setUp and is not attached to the document at the beginning of the
* test.
* @type {Element}
*/
var popupElement;
var testArea;
var POPUP_HEIGHT = 100;
var POPUP_WIDTH = 150;
function setUp() {
testArea = goog.dom.getElement('test-area');
// Enlarges the test area to 5000x5000px so that we can be confident
// that scrolling the document to some small (x,y) value would work.
goog.style.setSize(testArea, 5000, 5000);
window.scrollTo(0, 0);
popupElement = goog.dom.createDom('div');
goog.style.setSize(popupElement, POPUP_WIDTH, POPUP_HEIGHT);
popupElement.style.position = 'absolute';
// For ease of debugging.
popupElement.style.background = 'blue';
}
function tearDown() {
popupElement = null;
testArea.innerHTML = '';
testArea.setAttribute('style', '');
}
function testClientPositionWithZeroViewportOffset() {
goog.dom.appendChild(testArea, popupElement);
var x = 300;
var y = 200;
var pos = new goog.positioning.ClientPosition(x, y);
pos.reposition(popupElement, goog.positioning.Corner.TOP_LEFT);
assertPageOffset(x, y, popupElement);
pos.reposition(popupElement, goog.positioning.Corner.TOP_RIGHT);
assertPageOffset(x - POPUP_WIDTH, y, popupElement);
pos.reposition(popupElement, goog.positioning.Corner.BOTTOM_LEFT);
assertPageOffset(x, y - POPUP_HEIGHT, popupElement);
pos.reposition(popupElement, goog.positioning.Corner.BOTTOM_RIGHT);
assertPageOffset(x - POPUP_WIDTH, y - POPUP_HEIGHT, popupElement);
}
function testClientPositionWithSomeViewportOffset() {
goog.dom.appendChild(testArea, popupElement);
var x = 300;
var y = 200;
var scrollX = 135;
var scrollY = 270;
window.scrollTo(scrollX, scrollY);
var pos = new goog.positioning.ClientPosition(x, y);
pos.reposition(popupElement, goog.positioning.Corner.TOP_LEFT);
assertPageOffset(scrollX + x, scrollY + y, popupElement);
}
function testClientPositionWithPositionContext() {
var contextAbsoluteX = 90;
var contextAbsoluteY = 110;
var x = 300;
var y = 200;
var contextElement = goog.dom.createDom('div', undefined, popupElement);
goog.style.setPosition(contextElement, contextAbsoluteX, contextAbsoluteY);
contextElement.style.position = 'absolute';
goog.dom.appendChild(testArea, contextElement);
var pos = new goog.positioning.ClientPosition(x, y);
pos.reposition(popupElement, goog.positioning.Corner.TOP_LEFT);
assertPageOffset(x, y, popupElement);
}
function assertPageOffset(expectedX, expectedY, el) {
var offsetCoordinate = goog.style.getPageOffset(el);
assertEquals('x-coord page offset is wrong.', expectedX, offsetCoordinate.x);
assertEquals('y-coord page offset is wrong.', expectedY, offsetCoordinate.y);
}
| 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 Anchored viewport positioning class.
*
* @author eae@google.com (Emil A Eklund)
*/
goog.provide('goog.positioning.AnchoredViewportPosition');
goog.require('goog.math.Box');
goog.require('goog.positioning');
goog.require('goog.positioning.AnchoredPosition');
goog.require('goog.positioning.Corner');
goog.require('goog.positioning.Overflow');
goog.require('goog.positioning.OverflowStatus');
/**
* 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 this positioning object it's recommended that the movable element
* be absolutely positioned.
*
* @param {Element} anchorElement Element the movable element should be
* anchored against.
* @param {goog.positioning.Corner} corner Corner of anchored element the
* movable element should be positioned 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.
* @param {goog.math.Box=} opt_overflowConstraint Box object describing the
* dimensions in which the movable element could be shown.
* @constructor
* @extends {goog.positioning.AnchoredPosition}
*/
goog.positioning.AnchoredViewportPosition = function(anchorElement,
corner,
opt_adjust,
opt_overflowConstraint) {
goog.positioning.AnchoredPosition.call(this, anchorElement, corner);
/**
* The last resort algorithm to use if the algorithm can't fit inside
* the viewport.
*
* IGNORE = do nothing, just display at the preferred position.
*
* ADJUST_X | ADJUST_Y = Adjust until the element fits, even if that means
* that the anchored corners are ignored.
*
* @type {number}
* @private
*/
this.lastResortOverflow_ = opt_adjust ?
(goog.positioning.Overflow.ADJUST_X |
goog.positioning.Overflow.ADJUST_Y) :
goog.positioning.Overflow.IGNORE;
/**
* The dimensions in which the movable element could be shown.
* @type {goog.math.Box|undefined}
* @private
*/
this.overflowConstraint_ = opt_overflowConstraint || undefined;
};
goog.inherits(goog.positioning.AnchoredViewportPosition,
goog.positioning.AnchoredPosition);
/**
* @return {number} A bitmask for the "last resort" overflow.
*/
goog.positioning.AnchoredViewportPosition.prototype.getLastResortOverflow =
function() {
return this.lastResortOverflow_;
};
/**
* @param {number} lastResortOverflow A bitmask for the "last resort" overflow,
* if we fail to fit the element on-screen.
*/
goog.positioning.AnchoredViewportPosition.prototype.setLastResortOverflow =
function(lastResortOverflow) {
this.lastResortOverflow_ = lastResortOverflow;
};
/**
* Repositions the movable element.
*
* @param {Element} movableElement Element to position.
* @param {goog.positioning.Corner} movableCorner Corner of the movable element
* that should be positioned adjacent to the anchored element.
* @param {goog.math.Box=} opt_margin A margin specified in pixels.
* @param {goog.math.Size=} opt_preferredSize The preferred size of the
* movableElement.
* @override
*/
goog.positioning.AnchoredViewportPosition.prototype.reposition = function(
movableElement, movableCorner, opt_margin, opt_preferredSize) {
var status = goog.positioning.positionAtAnchor(this.element, this.corner,
movableElement, movableCorner, null, opt_margin,
goog.positioning.Overflow.FAIL_X | goog.positioning.Overflow.FAIL_Y,
opt_preferredSize, this.overflowConstraint_);
// If the desired position is outside the viewport try mirroring the corners
// horizontally or vertically.
if (status & goog.positioning.OverflowStatus.FAILED) {
var cornerFallback = this.adjustCorner(status, this.corner);
var movableCornerFallback = this.adjustCorner(status, movableCorner);
status = goog.positioning.positionAtAnchor(this.element, cornerFallback,
movableElement, movableCornerFallback, null, opt_margin,
goog.positioning.Overflow.FAIL_X | goog.positioning.Overflow.FAIL_Y,
opt_preferredSize, this.overflowConstraint_);
if (status & goog.positioning.OverflowStatus.FAILED) {
// If that also fails, pick the best corner from the two tries,
// and adjust the position until it fits.
cornerFallback = this.adjustCorner(status, cornerFallback);
movableCornerFallback = this.adjustCorner(
status, movableCornerFallback);
goog.positioning.positionAtAnchor(this.element, cornerFallback,
movableElement, movableCornerFallback, null, opt_margin,
this.getLastResortOverflow(), opt_preferredSize,
this.overflowConstraint_);
}
}
};
/**
* Adjusts the corner if X or Y positioning failed.
* @param {number} status The status of the last positionAtAnchor call.
* @param {goog.positioning.Corner} corner The corner to adjust.
* @return {goog.positioning.Corner} The adjusted corner.
* @protected
*/
goog.positioning.AnchoredViewportPosition.prototype.adjustCorner = function(
status, corner) {
if (status & goog.positioning.OverflowStatus.FAILED_HORIZONTAL) {
corner = goog.positioning.flipCornerHorizontal(corner);
}
if (status & goog.positioning.OverflowStatus.FAILED_VERTICAL) {
corner = goog.positioning.flipCornerVertical(corner);
}
return corner;
};
| 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 Abstract base class for positioning implementations.
*
* @author eae@google.com (Emil A Eklund)
*/
goog.provide('goog.positioning.AbstractPosition');
goog.require('goog.math.Box');
goog.require('goog.math.Size');
goog.require('goog.positioning.Corner');
/**
* Abstract position object. Encapsulates position and overflow handling.
*
* @constructor
*/
goog.positioning.AbstractPosition = function() {};
/**
* Repositions the element. Abstract method, should be overloaded.
*
* @param {Element} movableElement Element to position.
* @param {goog.positioning.Corner} corner Corner of the movable element that
* should be positioned adjacent to the anchored element.
* @param {goog.math.Box=} opt_margin A margin specified in pixels.
* @param {goog.math.Size=} opt_preferredSize PreferredSize of the
* movableElement.
*/
goog.positioning.AbstractPosition.prototype.reposition =
function(movableElement, corner, opt_margin, opt_preferredSize) { };
| JavaScript |
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Common positioning code.
*
*/
goog.provide('goog.positioning');
goog.provide('goog.positioning.Corner');
goog.provide('goog.positioning.CornerBit');
goog.provide('goog.positioning.Overflow');
goog.provide('goog.positioning.OverflowStatus');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.math.Box');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Size');
goog.require('goog.style');
goog.require('goog.style.bidi');
/**
* Enum for representing an element corner for positioning the popup.
*
* The START constants map to LEFT if element directionality is left
* to right and RIGHT if the directionality is right to left.
* Likewise END maps to RIGHT or LEFT depending on the directionality.
*
* @enum {number}
*/
goog.positioning.Corner = {
TOP_LEFT: 0,
TOP_RIGHT: 2,
BOTTOM_LEFT: 1,
BOTTOM_RIGHT: 3,
TOP_START: 4,
TOP_END: 6,
BOTTOM_START: 5,
BOTTOM_END: 7
};
/**
* Enum for bits in the {@see goog.positioning.Corner) bitmap.
*
* @enum {number}
*/
goog.positioning.CornerBit = {
BOTTOM: 1,
RIGHT: 2,
FLIP_RTL: 4
};
/**
* Enum for representing position handling in cases where the element would be
* positioned outside the viewport.
*
* @enum {number}
*/
goog.positioning.Overflow = {
/** Ignore overflow */
IGNORE: 0,
/** Try to fit horizontally in the viewport at all costs. */
ADJUST_X: 1,
/** If the element can't fit horizontally, report positioning failure. */
FAIL_X: 2,
/** Try to fit vertically in the viewport at all costs. */
ADJUST_Y: 4,
/** If the element can't fit vertically, report positioning failure. */
FAIL_Y: 8,
/** Resize the element's width to fit in the viewport. */
RESIZE_WIDTH: 16,
/** Resize the element's height to fit in the viewport. */
RESIZE_HEIGHT: 32,
/**
* If the anchor goes off-screen in the x-direction, position the movable
* element off-screen. Otherwise, try to fit horizontally in the viewport.
*/
ADJUST_X_EXCEPT_OFFSCREEN: 64 | 1,
/**
* If the anchor goes off-screen in the y-direction, position the movable
* element off-screen. Otherwise, try to fit vertically in the viewport.
*/
ADJUST_Y_EXCEPT_OFFSCREEN: 128 | 4
};
/**
* Enum for representing the outcome of a positioning call.
*
* @enum {number}
*/
goog.positioning.OverflowStatus = {
NONE: 0,
ADJUSTED_X: 1,
ADJUSTED_Y: 2,
WIDTH_ADJUSTED: 4,
HEIGHT_ADJUSTED: 8,
FAILED_LEFT: 16,
FAILED_RIGHT: 32,
FAILED_TOP: 64,
FAILED_BOTTOM: 128,
FAILED_OUTSIDE_VIEWPORT: 256
};
/**
* Shorthand to check if a status code contains any fail code.
* @type {number}
*/
goog.positioning.OverflowStatus.FAILED =
goog.positioning.OverflowStatus.FAILED_LEFT |
goog.positioning.OverflowStatus.FAILED_RIGHT |
goog.positioning.OverflowStatus.FAILED_TOP |
goog.positioning.OverflowStatus.FAILED_BOTTOM |
goog.positioning.OverflowStatus.FAILED_OUTSIDE_VIEWPORT;
/**
* Shorthand to check if horizontal positioning failed.
* @type {number}
*/
goog.positioning.OverflowStatus.FAILED_HORIZONTAL =
goog.positioning.OverflowStatus.FAILED_LEFT |
goog.positioning.OverflowStatus.FAILED_RIGHT;
/**
* Shorthand to check if vertical positioning failed.
* @type {number}
*/
goog.positioning.OverflowStatus.FAILED_VERTICAL =
goog.positioning.OverflowStatus.FAILED_TOP |
goog.positioning.OverflowStatus.FAILED_BOTTOM;
/**
* Positions a movable element relative to an anchor element. The caller
* specifies the corners that should touch. This functions then moves the
* movable element accordingly.
*
* @param {Element} anchorElement The element that is the anchor for where
* the movable element should position itself.
* @param {goog.positioning.Corner} anchorElementCorner The corner of the
* anchorElement for positioning the movable element.
* @param {Element} movableElement The element to move.
* @param {goog.positioning.Corner} movableElementCorner The corner of the
* movableElement that that should be positioned adjacent to the anchor
* element.
* @param {goog.math.Coordinate=} opt_offset An offset specified in pixels.
* After the normal positioning algorithm is applied, the offset is then
* applied. Positive coordinates move the popup closer to the center of the
* anchor element. Negative coordinates move the popup away from the center
* of the anchor element.
* @param {goog.math.Box=} opt_margin A margin specified in pixels.
* After the normal positioning algorithm is applied and any offset, the
* margin is then applied. Positive coordinates move the popup away from the
* spot it was positioned towards its center. Negative coordinates move it
* towards the spot it was positioned away from its center.
* @param {?number=} opt_overflow Overflow handling mode. Defaults to IGNORE if
* not specified. Bitmap, {@see goog.positioning.Overflow}.
* @param {goog.math.Size=} opt_preferredSize The preferred size of the
* movableElement.
* @param {goog.math.Box=} opt_viewport Box object describing the dimensions of
* the viewport. The viewport is specified relative to offsetParent of
* {@code movableElement}. In other words, the viewport can be thought of as
* describing a "position: absolute" element contained in the offsetParent.
* It defaults to visible area of nearest scrollable ancestor of
* {@code movableElement} (see {@code goog.style.getVisibleRectForElement}).
* @return {goog.positioning.OverflowStatus} Status bitmap,
* {@see goog.positioning.OverflowStatus}.
*/
goog.positioning.positionAtAnchor = function(anchorElement,
anchorElementCorner,
movableElement,
movableElementCorner,
opt_offset,
opt_margin,
opt_overflow,
opt_preferredSize,
opt_viewport) {
goog.asserts.assert(movableElement);
var movableParentTopLeft =
goog.positioning.getOffsetParentPageOffset(movableElement);
// Get the visible part of the anchor element. anchorRect is
// relative to anchorElement's page.
var anchorRect = goog.positioning.getVisiblePart_(anchorElement);
// Translate anchorRect to be relative to movableElement's page.
goog.style.translateRectForAnotherFrame(
anchorRect,
goog.dom.getDomHelper(anchorElement),
goog.dom.getDomHelper(movableElement));
// Offset based on which corner of the element we want to position against.
var corner = goog.positioning.getEffectiveCorner(anchorElement,
anchorElementCorner);
// absolutePos is a candidate position relative to the
// movableElement's window.
var absolutePos = new goog.math.Coordinate(
corner & goog.positioning.CornerBit.RIGHT ?
anchorRect.left + anchorRect.width : anchorRect.left,
corner & goog.positioning.CornerBit.BOTTOM ?
anchorRect.top + anchorRect.height : anchorRect.top);
// Translate absolutePos to be relative to the offsetParent.
absolutePos =
goog.math.Coordinate.difference(absolutePos, movableParentTopLeft);
// Apply offset, if specified
if (opt_offset) {
absolutePos.x += (corner & goog.positioning.CornerBit.RIGHT ? -1 : 1) *
opt_offset.x;
absolutePos.y += (corner & goog.positioning.CornerBit.BOTTOM ? -1 : 1) *
opt_offset.y;
}
// Determine dimension of viewport.
var viewport;
if (opt_overflow) {
if (opt_viewport) {
viewport = opt_viewport;
} else {
viewport = goog.style.getVisibleRectForElement(movableElement);
if (viewport) {
viewport.top -= movableParentTopLeft.y;
viewport.right -= movableParentTopLeft.x;
viewport.bottom -= movableParentTopLeft.y;
viewport.left -= movableParentTopLeft.x;
}
}
}
return goog.positioning.positionAtCoordinate(absolutePos,
movableElement,
movableElementCorner,
opt_margin,
viewport,
opt_overflow,
opt_preferredSize);
};
/**
* Calculates the page offset of the given element's
* offsetParent. This value can be used to translate any x- and
* y-offset relative to the page to an offset relative to the
* offsetParent, which can then be used directly with as position
* coordinate for {@code positionWithCoordinate}.
* @param {!Element} movableElement The element to calculate.
* @return {!goog.math.Coordinate} The page offset, may be (0, 0).
*/
goog.positioning.getOffsetParentPageOffset = function(movableElement) {
// Ignore offset for the BODY element unless its position is non-static.
// For cases where the offset parent is HTML rather than the BODY (such as in
// IE strict mode) there's no need to get the position of the BODY as it
// doesn't affect the page offset.
var movableParentTopLeft;
var parent = movableElement.offsetParent;
if (parent) {
var isBody = parent.tagName == goog.dom.TagName.HTML ||
parent.tagName == goog.dom.TagName.BODY;
if (!isBody ||
goog.style.getComputedPosition(parent) != 'static') {
// Get the top-left corner of the parent, in page coordinates.
movableParentTopLeft = goog.style.getPageOffset(parent);
if (!isBody) {
movableParentTopLeft = goog.math.Coordinate.difference(
movableParentTopLeft,
new goog.math.Coordinate(goog.style.bidi.getScrollLeft(parent),
parent.scrollTop));
}
}
}
return movableParentTopLeft || new goog.math.Coordinate();
};
/**
* Returns intersection of the specified element and
* goog.style.getVisibleRectForElement for it.
*
* @param {Element} el The target element.
* @return {goog.math.Rect} Intersection of getVisibleRectForElement
* and the current bounding rectangle of the element. If the
* intersection is empty, returns the bounding rectangle.
* @private
*/
goog.positioning.getVisiblePart_ = function(el) {
var rect = goog.style.getBounds(el);
var visibleBox = goog.style.getVisibleRectForElement(el);
if (visibleBox) {
rect.intersection(goog.math.Rect.createFromBox(visibleBox));
}
return rect;
};
/**
* Positions the specified corner of the movable element at the
* specified coordinate.
*
* @param {goog.math.Coordinate} absolutePos The coordinate to position the
* element at.
* @param {Element} movableElement The element to be positioned.
* @param {goog.positioning.Corner} movableElementCorner The corner of the
* movableElement that that should be positioned.
* @param {goog.math.Box=} opt_margin A margin specified in pixels.
* After the normal positioning algorithm is applied and any offset, the
* margin is then applied. Positive coordinates move the popup away from the
* spot it was positioned towards its center. Negative coordinates move it
* towards the spot it was positioned away from its center.
* @param {goog.math.Box=} opt_viewport Box object describing the dimensions of
* the viewport. Required if opt_overflow is specified.
* @param {?number=} opt_overflow Overflow handling mode. Defaults to IGNORE if
* not specified, {@see goog.positioning.Overflow}.
* @param {goog.math.Size=} opt_preferredSize The preferred size of the
* movableElement. Defaults to the current size.
* @return {goog.positioning.OverflowStatus} Status bitmap.
*/
goog.positioning.positionAtCoordinate = function(absolutePos,
movableElement,
movableElementCorner,
opt_margin,
opt_viewport,
opt_overflow,
opt_preferredSize) {
absolutePos = absolutePos.clone();
var status = goog.positioning.OverflowStatus.NONE;
// Offset based on attached corner and desired margin.
var corner = goog.positioning.getEffectiveCorner(movableElement,
movableElementCorner);
var elementSize = goog.style.getSize(movableElement);
var size = opt_preferredSize ? opt_preferredSize.clone() :
elementSize.clone();
if (opt_margin || corner != goog.positioning.Corner.TOP_LEFT) {
if (corner & goog.positioning.CornerBit.RIGHT) {
absolutePos.x -= size.width + (opt_margin ? opt_margin.right : 0);
} else if (opt_margin) {
absolutePos.x += opt_margin.left;
}
if (corner & goog.positioning.CornerBit.BOTTOM) {
absolutePos.y -= size.height + (opt_margin ? opt_margin.bottom : 0);
} else if (opt_margin) {
absolutePos.y += opt_margin.top;
}
}
// Adjust position to fit inside viewport.
if (opt_overflow) {
status = opt_viewport ?
goog.positioning.adjustForViewport_(
absolutePos, size, opt_viewport, opt_overflow) :
goog.positioning.OverflowStatus.FAILED_OUTSIDE_VIEWPORT;
if (status & goog.positioning.OverflowStatus.FAILED) {
return status;
}
}
goog.style.setPosition(movableElement, absolutePos);
if (!goog.math.Size.equals(elementSize, size)) {
goog.style.setBorderBoxSize(movableElement, size);
}
return status;
};
/**
* Adjusts the position and/or size of an element, identified by its position
* and size, to fit inside the viewport. If the position or size of the element
* is adjusted the pos or size objects, respectively, are modified.
*
* @param {goog.math.Coordinate} pos Position of element, updated if the
* position is adjusted.
* @param {goog.math.Size} size Size of element, updated if the size is
* adjusted.
* @param {goog.math.Box} viewport Bounding box describing the viewport.
* @param {number} overflow Overflow handling mode,
* {@see goog.positioning.Overflow}.
* @return {goog.positioning.OverflowStatus} Status bitmap,
* {@see goog.positioning.OverflowStatus}.
* @private
*/
goog.positioning.adjustForViewport_ = function(pos, size, viewport, overflow) {
var status = goog.positioning.OverflowStatus.NONE;
var ADJUST_X_EXCEPT_OFFSCREEN =
goog.positioning.Overflow.ADJUST_X_EXCEPT_OFFSCREEN;
var ADJUST_Y_EXCEPT_OFFSCREEN =
goog.positioning.Overflow.ADJUST_Y_EXCEPT_OFFSCREEN;
if ((overflow & ADJUST_X_EXCEPT_OFFSCREEN) == ADJUST_X_EXCEPT_OFFSCREEN &&
(pos.x < viewport.left || pos.x >= viewport.right)) {
overflow &= ~goog.positioning.Overflow.ADJUST_X;
}
if ((overflow & ADJUST_Y_EXCEPT_OFFSCREEN) == ADJUST_Y_EXCEPT_OFFSCREEN &&
(pos.y < viewport.top || pos.y >= viewport.bottom)) {
overflow &= ~goog.positioning.Overflow.ADJUST_Y;
}
// Left edge outside viewport, try to move it.
if (pos.x < viewport.left && overflow & goog.positioning.Overflow.ADJUST_X) {
pos.x = viewport.left;
status |= goog.positioning.OverflowStatus.ADJUSTED_X;
}
// Left edge inside and right edge outside viewport, try to resize it.
if (pos.x < viewport.left &&
pos.x + size.width > viewport.right &&
overflow & goog.positioning.Overflow.RESIZE_WIDTH) {
size.width = Math.max(
size.width - ((pos.x + size.width) - viewport.right), 0);
status |= goog.positioning.OverflowStatus.WIDTH_ADJUSTED;
}
// Right edge outside viewport, try to move it.
if (pos.x + size.width > viewport.right &&
overflow & goog.positioning.Overflow.ADJUST_X) {
pos.x = Math.max(viewport.right - size.width, viewport.left);
status |= goog.positioning.OverflowStatus.ADJUSTED_X;
}
// Left or right edge still outside viewport, fail if the FAIL_X option was
// specified, ignore it otherwise.
if (overflow & goog.positioning.Overflow.FAIL_X) {
status |= (pos.x < viewport.left ?
goog.positioning.OverflowStatus.FAILED_LEFT : 0) |
(pos.x + size.width > viewport.right ?
goog.positioning.OverflowStatus.FAILED_RIGHT : 0);
}
// Top edge outside viewport, try to move it.
if (pos.y < viewport.top && overflow & goog.positioning.Overflow.ADJUST_Y) {
pos.y = viewport.top;
status |= goog.positioning.OverflowStatus.ADJUSTED_Y;
}
// Bottom edge inside and top edge outside viewport, try to resize it.
if (pos.y <= viewport.top &&
pos.y + size.height < viewport.bottom &&
overflow & goog.positioning.Overflow.RESIZE_HEIGHT) {
size.height = Math.max(size.height - (viewport.top - pos.y), 0);
pos.y = 0;
status |= goog.positioning.OverflowStatus.HEIGHT_ADJUSTED;
}
// Top edge inside and bottom edge outside viewport, try to resize it.
if (pos.y >= viewport.top &&
pos.y + size.height > viewport.bottom &&
overflow & goog.positioning.Overflow.RESIZE_HEIGHT) {
size.height = Math.max(
size.height - ((pos.y + size.height) - viewport.bottom), 0);
status |= goog.positioning.OverflowStatus.HEIGHT_ADJUSTED;
}
// Bottom edge outside viewport, try to move it.
if (pos.y + size.height > viewport.bottom &&
overflow & goog.positioning.Overflow.ADJUST_Y) {
pos.y = Math.max(viewport.bottom - size.height, viewport.top);
status |= goog.positioning.OverflowStatus.ADJUSTED_Y;
}
// Top or bottom edge still outside viewport, fail if the FAIL_Y option was
// specified, ignore it otherwise.
if (overflow & goog.positioning.Overflow.FAIL_Y) {
status |= (pos.y < viewport.top ?
goog.positioning.OverflowStatus.FAILED_TOP : 0) |
(pos.y + size.height > viewport.bottom ?
goog.positioning.OverflowStatus.FAILED_BOTTOM : 0);
}
return status;
};
/**
* Returns an absolute corner (top/bottom left/right) given an absolute
* or relative (top/bottom start/end) corner and the direction of an element.
* Absolute corners remain unchanged.
* @param {Element} element DOM element to test for RTL direction.
* @param {goog.positioning.Corner} corner The popup corner used for
* positioning.
* @return {goog.positioning.Corner} Effective corner.
*/
goog.positioning.getEffectiveCorner = function(element, corner) {
return /** @type {goog.positioning.Corner} */ (
(corner & goog.positioning.CornerBit.FLIP_RTL &&
goog.style.isRightToLeft(element) ?
corner ^ goog.positioning.CornerBit.RIGHT :
corner
) & ~goog.positioning.CornerBit.FLIP_RTL);
};
/**
* Returns the corner opposite the given one horizontally.
* @param {goog.positioning.Corner} corner The popup corner used to flip.
* @return {goog.positioning.Corner} The opposite corner horizontally.
*/
goog.positioning.flipCornerHorizontal = function(corner) {
return /** @type {goog.positioning.Corner} */ (corner ^
goog.positioning.CornerBit.RIGHT);
};
/**
* Returns the corner opposite the given one vertically.
* @param {goog.positioning.Corner} corner The popup corner used to flip.
* @return {goog.positioning.Corner} The opposite corner vertically.
*/
goog.positioning.flipCornerVertical = function(corner) {
return /** @type {goog.positioning.Corner} */ (corner ^
goog.positioning.CornerBit.BOTTOM);
};
/**
* Returns the corner opposite the given one horizontally and vertically.
* @param {goog.positioning.Corner} corner The popup corner used to flip.
* @return {goog.positioning.Corner} The opposite corner horizontally and
* vertically.
*/
goog.positioning.flipCorner = function(corner) {
return /** @type {goog.positioning.Corner} */ (corner ^
goog.positioning.CornerBit.BOTTOM ^
goog.positioning.CornerBit.RIGHT);
};
| 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 Client positioning class.
*
*/
goog.provide('goog.positioning.AnchoredPosition');
goog.require('goog.math.Box');
goog.require('goog.positioning');
goog.require('goog.positioning.AbstractPosition');
/**
* 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} anchorElement Element the movable element should be
* anchored against.
* @param {goog.positioning.Corner} corner Corner of anchored element the
* movable element should be positioned at.
* @param {number=} opt_overflow Overflow handling mode. Defaults to IGNORE if
* not specified. Bitmap, {@see goog.positioning.Overflow}.
* @constructor
* @extends {goog.positioning.AbstractPosition}
*/
goog.positioning.AnchoredPosition = function(anchorElement,
corner,
opt_overflow) {
/**
* Element the movable element should be anchored against.
* @type {Element}
*/
this.element = anchorElement;
/**
* Corner of anchored element the movable element should be positioned at.
* @type {goog.positioning.Corner}
*/
this.corner = corner;
/**
* Overflow handling mode. Defaults to IGNORE if not specified.
* Bitmap, {@see goog.positioning.Overflow}.
* @type {number|undefined}
* @private
*/
this.overflow_ = opt_overflow;
};
goog.inherits(goog.positioning.AnchoredPosition,
goog.positioning.AbstractPosition);
/**
* Repositions the movable element.
*
* @param {Element} movableElement Element to position.
* @param {goog.positioning.Corner} movableCorner Corner of the movable element
* that should be positioned adjacent to the anchored element.
* @param {goog.math.Box=} opt_margin A margin specifin pixels.
* @param {goog.math.Size=} opt_preferredSize PreferredSize of the
* movableElement (unused in this class).
* @override
*/
goog.positioning.AnchoredPosition.prototype.reposition = function(
movableElement, movableCorner, opt_margin, opt_preferredSize) {
goog.positioning.positionAtAnchor(this.element,
this.corner,
movableElement,
movableCorner,
undefined,
opt_margin,
this.overflow_);
};
| 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 Client positioning class.
*
*/
goog.provide('goog.positioning.ClientPosition');
goog.require('goog.asserts');
goog.require('goog.math.Box');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Size');
goog.require('goog.positioning');
goog.require('goog.positioning.AbstractPosition');
goog.require('goog.style');
/**
* 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.positioning.AbstractPosition}
*/
goog.positioning.ClientPosition = function(arg1, opt_arg2) {
/**
* Coordinate to position popup at.
* @type {goog.math.Coordinate}
*/
this.coordinate = arg1 instanceof goog.math.Coordinate ? arg1 :
new goog.math.Coordinate(/** @type {number} */ (arg1), opt_arg2);
};
goog.inherits(goog.positioning.ClientPosition,
goog.positioning.AbstractPosition);
/**
* Repositions the popup according to the current state
*
* @param {Element} movableElement The DOM element of the popup.
* @param {goog.positioning.Corner} movableElementCorner The corner of
* the popup element that that should be positioned adjacent to
* the anchorElement. One of the goog.positioning.Corner
* constants.
* @param {goog.math.Box=} opt_margin A margin specified in pixels.
* @param {goog.math.Size=} opt_preferredSize Preferred size of the element.
* @override
*/
goog.positioning.ClientPosition.prototype.reposition = function(
movableElement, movableElementCorner, opt_margin, opt_preferredSize) {
goog.asserts.assert(movableElement);
// Translates the coordinate to be relative to the page.
var viewportOffset = goog.style.getViewportPageOffset(
goog.dom.getOwnerDocument(movableElement));
var x = this.coordinate.x + viewportOffset.x;
var y = this.coordinate.y + viewportOffset.y;
// Translates the coordinate to be relative to the offset parent.
var movableParentTopLeft =
goog.positioning.getOffsetParentPageOffset(movableElement);
x -= movableParentTopLeft.x;
y -= movableParentTopLeft.y;
goog.positioning.positionAtCoordinate(
new goog.math.Coordinate(x, y), movableElement, movableElementCorner,
opt_margin, null, null, opt_preferredSize);
};
| 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 file contains functions for using Gears.
*/
// TODO(arv): The Gears team is planning to inject the Gears factory as
// google.gears.factory in the main thread as well. Currently it is only
// injected in the worker threads.
goog.provide('goog.gears');
goog.require('goog.string');
/**
* Returns a new Gears factory object.
* @return {Object} the Gears factory object if available or null otherwise.
*/
goog.gears.getFactory = function() {
if (goog.gears.factory_ != undefined) {
return goog.gears.factory_;
}
// In the worker threads Gears injects google.gears.factory. They also plan
// to do this in the main thread.
var factory = goog.getObjectByName('google.gears.factory');
if (factory) {
return goog.gears.factory_ = factory;
}
// Mozilla
/** @preserveTry */
try {
var gearsFactory = /** @type {Function} */
(goog.getObjectByName('GearsFactory'));
return goog.gears.factory_ = new gearsFactory;
} catch (ex) {
// fall through
}
// MSIE
/** @preserveTry */
try {
factory = new ActiveXObject('Gears.Factory');
var buildInfo = factory.getBuildInfo();
if (buildInfo.indexOf('ie_mobile') != -1) {
factory.privateSetGlobalObject(goog.global);
}
return goog.gears.factory_ = factory;
} catch (ex) {
// fall through
}
return goog.gears.factory_ = goog.gears.tryGearsObject_();
};
/**
* Attempt to create a factory by adding an object element to the DOM.
* This covers the case for safari.
* @return {Function} The factory, or null.
* @private
*/
goog.gears.tryGearsObject_ = function() {
// HACK(arv): Use square bracket notation so this can compile in an
// environment without a DOM.
var win = goog.getObjectByName('window');
// Safari
if (win && win['navigator']['mimeTypes']['application/x-googlegears']) {
/** @preserveTry */
try {
var doc = win['document'];
var factory = doc['getElementById']('gears-factory');
// If missing, create a place for it
if (!factory) {
factory = doc['createElement']('object');
factory['style']['display'] = 'none';
factory['width'] = '0';
factory['height'] = '0';
factory['type'] = 'application/x-googlegears';
factory['id'] = 'gears-factory';
doc['documentElement']['appendChild'](factory);
}
// Even if Gears failed to get created we get an object element. Make
// sure that it has a create method before assuming it is a Gears factory.
if (typeof factory.create != 'undefined') {
return factory;
}
} catch (ex) {
// fall through
}
}
return null;
};
/**
* Cached result of getFactory
* @type {Object|undefined}
* @private
*/
goog.gears.factory_ = undefined;
/**
* Whether we can create a Gears factory object. This does not cache the
* result.
* @return {boolean} true if we can create a Gears factory object.
*/
goog.gears.hasFactory = function() {
if (goog.gears.hasFactory_ != undefined) return goog.gears.hasFactory_;
// Use [] notation so we don't have to put this in externs
var factory = goog.getObjectByName('google.gears.factory');
if (factory || goog.getObjectByName('GearsFactory')) {
return goog.gears.hasFactory_ = true;
}
// Try ActiveXObject for IE
if (typeof ActiveXObject != 'undefined') {
/** @preserveTry */
try {
new ActiveXObject('Gears.Factory');
return goog.gears.hasFactory_ = true;
} catch (ex) {
return goog.gears.hasFactory_ = false;
}
}
// NOTE(user): For safari we have to actually create an object element
// in the DOM. We have to do it in hasFactory so we can reliably know whether
// there actually is a factory, else we can get into a situation, e.g. in
// FF 3.5.3 where the Gears add-on is disabled because it's incompatible
// with FF but application/x-googlegears is still in the mimeTypes object.
//
// HACK(arv): Use object by name so this can compile in an environment without
// a DOM.
var mimeTypes = goog.getObjectByName('navigator.mimeTypes');
if (mimeTypes && mimeTypes['application/x-googlegears']) {
factory = goog.gears.tryGearsObject_();
if (factory) {
// Might as well cache it while we have it.
goog.gears.factory_ = factory;
return goog.gears.hasFactory_ = true;
}
}
return goog.gears.hasFactory_ = false;
};
/**
* Cached result of hasFactory.
* @type {boolean|undefined}
* @private
*/
goog.gears.hasFactory_ = undefined;
/**
* Maximum file name length.
* @type {number}
* @private
*/
goog.gears.MAX_FILE_NAME_LENGTH_ = 64;
/**
* Allow 10 characters for hash (#goog.string.hashCode).
* @type {number}
* @private
*/
goog.gears.MAX_FILE_NAME_PREFIX_LENGTH_ = goog.gears.MAX_FILE_NAME_LENGTH_ - 10;
/**
* Gears only allows file names up to 64 characters, so this function shortens
* file names to fit in this limit. #goog.string.hashCode is used to compress
* the name. This also removes invalid characters.
* @param {string} originalFileName Original (potentially unsafe) file name.
* @return {string} Safe file name. If originalFileName null or empty,
* return originalFileName.
* @throws {Error} If originalFileName is null, empty or contains only
* invalid characters.
*/
goog.gears.makeSafeFileName = function(originalFileName) {
if (!originalFileName) {
throw Error('file name empty');
}
// Safety measure since Gears behaves very badly if it gets an unexpected
// data type.
originalFileName = String(originalFileName);
// TODO(user): This should be removed when the Gears code
// gets fixed to allow for any id to be passed in. Right now
// it fails to create a user specific database if the characters
// sent in are non alphanumeric.
var sanitizedFileName = originalFileName.replace(/[^a-zA-Z0-9\.\-@_]/g, '');
if (!sanitizedFileName) {
throw Error('file name invalid: ' + originalFileName);
}
if (sanitizedFileName.length <= goog.gears.MAX_FILE_NAME_LENGTH_) {
return sanitizedFileName;
}
// Keep as many characters in original as we can, then hash the rest.
var prefix = sanitizedFileName.substring(
0, goog.gears.MAX_FILE_NAME_PREFIX_LENGTH_);
return prefix + String(goog.string.hashCode(originalFileName));
};
| 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 This file contains functions for setting up the standard
* goog.net.XmlHttp factory (and, therefore, goog.net.XhrIo) to work using
* the HttpRequest object Gears provides.
*
*/
goog.provide('goog.gears.HttpRequest');
goog.require('goog.Timer');
goog.require('goog.gears');
goog.require('goog.net.WrapperXmlHttpFactory');
goog.require('goog.net.XmlHttp');
/**
* Sets up the Gears HttpRequest's to be the default HttpRequest's used via
* the goog.net.XmlHttp factory.
*/
goog.gears.HttpRequest.setup = function() {
// Set the XmlHttp factory.
goog.net.XmlHttp.setGlobalFactory(
new goog.net.WrapperXmlHttpFactory(
goog.gears.HttpRequest.factory_,
goog.gears.HttpRequest.optionsFactory_));
// Use the Gears timer as the default timer object to ensure that the XhrIo
// timeouts function in the Workers.
goog.Timer.defaultTimerObject = goog.gears.getFactory().create(
'beta.timer', '1.0');
};
/**
* The factory for creating Gears HttpRequest's.
* @return {!(GearsHttpRequest|XMLHttpRequest)} The request object.
* @private
*/
goog.gears.HttpRequest.factory_ = function() {
return goog.gears.getFactory().create('beta.httprequest', '1.0');
};
/**
* The options object for the Gears HttpRequest.
* @type {!Object}
* @private
*/
goog.gears.HttpRequest.options_ = {};
// As of Gears API v.2 (build version 0.1.56.0), setting onreadystatechange to
// null in FF will cause the browser to crash.
goog.gears.HttpRequest.options_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] =
true;
/**
* The factory for creating the options object for Gears HttpRequest's.
* @return {!Object} The options.
* @private
*/
goog.gears.HttpRequest.optionsFactory_ = function() {
return goog.gears.HttpRequest.options_;
};
| 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 This file implements a wrapper around the Gears WorkerPool
* with some extra features.
*
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.gears.WorkerPool');
goog.provide('goog.gears.WorkerPool.Event');
goog.provide('goog.gears.WorkerPool.EventType');
goog.require('goog.events.Event');
goog.require('goog.events.EventTarget');
goog.require('goog.gears');
goog.require('goog.gears.Worker');
/**
* This class implements a wrapper around the Gears Worker Pool.
*
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.gears.WorkerPool = function() {
goog.events.EventTarget.call(this);
/**
* Map from thread id to worker object
* @type {Object}
* @private
*/
this.workers_ = {};
// If we are in a worker thread we get the global google.gears.workerPool,
// otherwise we create a new Gears WorkerPool using the factory
var workerPool = /** @type {GearsWorkerPool} */
(goog.getObjectByName('google.gears.workerPool'));
if (workerPool) {
this.workerPool_ = workerPool;
} else {
// use a protected method to let the sub class override
this.workerPool_ = this.getGearsWorkerPool();
}
this.workerPool_.onmessage = goog.bind(this.handleMessage_, this);
};
goog.inherits(goog.gears.WorkerPool, goog.events.EventTarget);
/**
* Enum for event types fired by the WorkerPool.
* @enum {string}
*/
goog.gears.WorkerPool.EventType = {
UNKNOWN_WORKER: 'uknown_worker'
};
/**
* The Gears WorkerPool object.
* @type {GearsWorkerPool}
* @private
*/
goog.gears.WorkerPool.prototype.workerPool_ = null;
/**
* @return {GearsWorkerPool} A Gears WorkerPool object.
* @protected
*/
goog.gears.WorkerPool.prototype.getGearsWorkerPool = function() {
var factory = goog.gears.getFactory();
return factory.create('beta.workerpool');
};
/**
* Sets a last-chance error handler for a worker pool.
* WARNING: This will only succeed from inside a worker thread. In main thread,
* use window.onerror handler.
* @param {function(!GearsErrorObject):boolean} fn An error handler function
* that gets passed an error object with message and line number attributes.
* Returns whether the error was handled. If true stops propagation.
* @param {Object=} opt_handler This object for the function.
*/
goog.gears.WorkerPool.prototype.setErrorHandler = function(fn, opt_handler) {
this.workerPool_.onerror = goog.bind(fn, opt_handler);
};
/**
* Creates a new worker.
* @param {string} code The code to execute inside the worker.
* @return {goog.gears.Worker} The worker that was just created.
*/
goog.gears.WorkerPool.prototype.createWorker = function(code) {
var workerId = this.workerPool_.createWorker(code);
var worker = new goog.gears.Worker(this, workerId);
this.registerWorker(worker);
return worker;
};
/**
* Creates a new worker from a URL.
* @param {string} url URL from which to get the code to execute inside the
* worker.
* @return {goog.gears.Worker} The worker that was just created.
*/
goog.gears.WorkerPool.prototype.createWorkerFromUrl = function(url) {
var workerId = this.workerPool_.createWorkerFromUrl(url);
var worker = new goog.gears.Worker(this, workerId);
this.registerWorker(worker);
return worker;
};
/**
* Allows the worker who calls this to be used cross origin.
*/
goog.gears.WorkerPool.prototype.allowCrossOrigin = function() {
this.workerPool_.allowCrossOrigin();
};
/**
* Sends a message to a given worker.
* @param {*} message The message to send to the worker.
* @param {goog.gears.Worker} worker The worker to send the message to.
*/
goog.gears.WorkerPool.prototype.sendMessage = function(message, worker) {
this.workerPool_.sendMessage(message, worker.getId());
};
/**
* Callback when this worker recieves a message.
* @param {string} message The message that was sent.
* @param {number} senderId The ID of the worker that sent the message.
* @param {GearsMessageObject} messageObject An object containing all
* information about the message.
* @private
*/
goog.gears.WorkerPool.prototype.handleMessage_ = function(message,
senderId,
messageObject) {
if (!this.isDisposed()) {
var workers = this.workers_;
if (!workers[senderId]) {
// If the worker is unknown, dispatch an event giving users of the class
// the change to register the worker.
this.dispatchEvent(new goog.gears.WorkerPool.Event(
goog.gears.WorkerPool.EventType.UNKNOWN_WORKER,
senderId,
messageObject));
}
var worker = workers[senderId];
if (worker) {
worker.handleMessage(messageObject);
}
}
};
/**
* Registers a worker object.
* @param {goog.gears.Worker} worker The worker to register.
*/
goog.gears.WorkerPool.prototype.registerWorker = function(worker) {
this.workers_[worker.getId()] = worker;
};
/**
* Unregisters a worker object.
* @param {goog.gears.Worker} worker The worker to unregister.
*/
goog.gears.WorkerPool.prototype.unregisterWorker = function(worker) {
delete this.workers_[worker.getId()];
};
/** @override */
goog.gears.WorkerPool.prototype.disposeInternal = function() {
goog.gears.WorkerPool.superClass_.disposeInternal.call(this);
this.workerPool_ = null;
delete this.workers_;
};
/**
* Event used when the workerpool recieves a message
* @param {string} type The type of event.
* @param {number} senderId The id of the sender of the message.
* @param {GearsMessageObject} messageObject The message object.
*
* @constructor
* @extends {goog.events.Event}
*/
goog.gears.WorkerPool.Event = function(
type, senderId, messageObject) {
goog.events.Event.call(this, type);
/**
* The id of the sender of the message.
* @type {number}
*/
this.senderId = senderId;
/**
* The message sent from the worker. This is the same as the
* messageObject.body field and is here for convenience.
* @type {*}
*/
this.message = messageObject.body;
/**
* The object containing all information about the message.
* @type {GearsMessageObject}
*/
this.messageObject = messageObject;
};
goog.inherits(goog.gears.WorkerPool.Event, goog.events.Event);
| 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 Simple wrapper around a Gears ManagedResourceStore.
*
*/
goog.provide('goog.gears.ManagedResourceStore');
goog.provide('goog.gears.ManagedResourceStore.EventType');
goog.provide('goog.gears.ManagedResourceStore.UpdateStatus');
goog.provide('goog.gears.ManagedResourceStoreEvent');
goog.require('goog.debug.Logger');
goog.require('goog.events.Event');
goog.require('goog.events.EventTarget');
goog.require('goog.gears');
goog.require('goog.string');
/**
* Creates a ManagedResourceStore with the specified name and update. This
* follows the Closure event model so the COMPLETE event will fire both for
* SUCCESS and for ERROR. You can use {@code isSuccess} in UPDATE to see if the
* capture was successful or you can just listen to the different events.
*
* This supports PROGRESS events, which are fired any time {@code filesComplete}
* or {@code filesTotal} changes. If the Gears version is 0.3.6 or newer this
* will reflect the numbers returned by the underlying Gears MRS but for older
* Gears versions this will just be {@code 0} or {@code 1}.
*
* NOTE: This relies on at least the 0.2 version of gears (for timer).
*
* @param {string} name The name of the managed store.
* @param {?string} requiredCookie A cookie that must be present for the
* managed store to be active. Should have the form "foo=bar". Can be null
* if not required.
* @param {GearsLocalServer=} opt_localServer Gears local server -- if not set,
* create a new one internally.
*
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.gears.ManagedResourceStore = function(name, requiredCookie,
opt_localServer) {
goog.base(this);
this.localServer_ = opt_localServer ||
goog.gears.getFactory().create('beta.localserver', '1.0');
this.name_ = goog.gears.makeSafeFileName(name);
if (name != this.name_) {
this.logger_.info(
'managed resource store name ' + name + '->' + this.name_);
}
this.requiredCookie_ = requiredCookie ? String(requiredCookie) : null;
// Whether Gears natively has "events" on the MRS. If it does not we treat
// the progress as 0 to 1
this.supportsEvents_ = goog.string.compareVersions(
goog.gears.getFactory().version, '0.3.6') >= 0;
};
goog.inherits(goog.gears.ManagedResourceStore, goog.events.EventTarget);
/**
* The amount of time between status checks during an update
* @type {number}
*/
goog.gears.ManagedResourceStore.UPDATE_INTERVAL_MS = 500;
/**
* Enum for possible values of Gears ManagedResourceStore.updatedStatus
* @enum
*/
goog.gears.ManagedResourceStore.UpdateStatus = {
OK: 0,
CHECKING: 1,
DOWNLOADING: 2,
FAILURE: 3
};
/**
* Logger.
* @type {goog.debug.Logger}
* @private
*/
goog.gears.ManagedResourceStore.prototype.logger_ =
goog.debug.Logger.getLogger('goog.gears.ManagedResourceStore');
/**
* The Gears local server object.
* @type {GearsLocalServer}
* @private
*/
goog.gears.ManagedResourceStore.prototype.localServer_;
/**
* The name of the managed store.
* @type {?string}
* @private
*/
goog.gears.ManagedResourceStore.prototype.name_;
/**
* A cookie that must be present for the managed store to be active.
* Should have the form "foo=bar". String cast is a safety measure since
* Gears behaves very badly when it gets an unexpected data type.
* @type {?string}
* @private
*/
goog.gears.ManagedResourceStore.prototype.requiredCookie_;
/**
* The required cookie, if any, for the managed store.
* @type {boolean}
* @private
*/
goog.gears.ManagedResourceStore.prototype.supportsEvents_;
/**
* The Gears ManagedResourceStore instance we are wrapping.
* @type {GearsManagedResourceStore}
* @private
*/
goog.gears.ManagedResourceStore.prototype.gearsStore_;
/**
* The id of the check status timer.
* @type {?number}
* @private
*/
goog.gears.ManagedResourceStore.prototype.timerId_ = null;
/**
* The check status timer.
* @type {Object}
* @private
*/
goog.gears.ManagedResourceStore.prototype.timer_ = null;
/**
* Whether we already have an active update check.
* @type {boolean}
* @private
*/
goog.gears.ManagedResourceStore.prototype.active_ = false;
/**
* Number of files completed. This is 0 or 1 if the Gears version does not
* support progress events. If the Gears version supports progress events
* this will reflect the number of files that have been completed.
* @type {number}
* @private
*/
goog.gears.ManagedResourceStore.prototype.filesComplete_ = 0;
/**
* Number of total files to load. This is 1 if the Gears version does not
* support progress events. If the Gears version supports progress events
* this will reflect the number of files that needs to be loaded.
* @type {number}
* @private
*/
goog.gears.ManagedResourceStore.prototype.filesTotal_ = 0;
/**
* @return {boolean} Whether there is an active request.
*/
goog.gears.ManagedResourceStore.prototype.isActive = function() {
return this.active_;
};
/**
* @return {boolean} Whether the update has completed.
*/
goog.gears.ManagedResourceStore.prototype.isComplete = function() {
return this.filesComplete_ == this.filesTotal_;
};
/**
* @return {boolean} Whether the update completed with a success.
*/
goog.gears.ManagedResourceStore.prototype.isSuccess = function() {
return this.getStatus() == goog.gears.ManagedResourceStore.UpdateStatus.OK;
};
/**
* Number of total files to load. This is always 1 if the Gears version does
* not support progress events. If the Gears version supports progress events
* this will reflect the number of files that needs to be loaded.
* @return {number} The number of files to load.
*/
goog.gears.ManagedResourceStore.prototype.getFilesTotal = function() {
return this.filesTotal_;
};
/**
* Get the last error message.
* @return {string} Last error message.
*/
goog.gears.ManagedResourceStore.prototype.getLastError = function() {
return this.gearsStore_ ? this.gearsStore_.lastErrorMessage : '';
};
/**
* Number of files completed. This is 0 or 1 if the Gears version does not
* support progress events. If the Gears version supports progress events
* this will reflect the number of files that have been completed.
* @return {number} The number of completed files.
*/
goog.gears.ManagedResourceStore.prototype.getFilesComplete = function() {
return this.filesComplete_;
};
/**
* Sets the filesComplete and the filesTotal and dispathces an event when
* either changes.
* @param {number} complete The count of the downloaded files.
* @param {number} total The total number of files.
* @private
*/
goog.gears.ManagedResourceStore.prototype.setFilesCounts_ = function(complete,
total) {
if (this.filesComplete_ != complete || this.filesTotal_ != total) {
this.filesComplete_ = complete;
this.filesTotal_ = total;
this.dispatchEvent(goog.gears.ManagedResourceStore.EventType.PROGRESS);
}
};
/**
* Determine if the ManagedResourceStore has been created in Gears yet
* @return {boolean} true if it has been created.
*/
goog.gears.ManagedResourceStore.prototype.exists = function() {
if (!this.gearsStore_) {
this.gearsStore_ = this.localServer_.openManagedStore(
this.name_, this.requiredCookie_);
}
return !!this.gearsStore_;
};
/**
* Throws an error if the store has not yet been created via create().
* @private
*/
goog.gears.ManagedResourceStore.prototype.assertExists_ = function() {
if (!this.exists()) {
throw Error('Store not yet created');
}
};
/**
* Throws an error if the store has already been created via create().
* @private
*/
goog.gears.ManagedResourceStore.prototype.assertNotExists_ = function() {
if (this.exists()) {
throw Error('Store already created');
}
};
/**
* Create the ManagedResourceStore in gears
* @param {string=} opt_manifestUrl The url of the manifest to associate.
*/
goog.gears.ManagedResourceStore.prototype.create = function(opt_manifestUrl) {
if (!this.exists()) {
this.gearsStore_ = this.localServer_.createManagedStore(
this.name_, this.requiredCookie_);
this.assertExists_();
}
if (opt_manifestUrl) {
// String cast is a safety measure since Gears behaves very badly if it
// gets an unexpected data type (e.g., goog.Uri).
this.gearsStore_.manifestUrl = String(opt_manifestUrl);
}
};
/**
* Starts an asynchronous process to update the ManagedResourcStore
*/
goog.gears.ManagedResourceStore.prototype.update = function() {
if (this.active_) {
// Update already in progress.
return;
}
this.assertExists_();
if (this.supportsEvents_) {
this.gearsStore_.onprogress = goog.bind(this.handleProgress_, this);
this.gearsStore_.oncomplete = goog.bind(this.handleComplete_, this);
this.gearsStore_.onerror = goog.bind(this.handleError_, this);
} else {
this.timer_ = goog.gears.getFactory().create('beta.timer', '1.0');
this.timerId_ = this.timer_.setInterval(
goog.bind(this.checkUpdateStatus_, this),
goog.gears.ManagedResourceStore.UPDATE_INTERVAL_MS);
this.setFilesCounts_(0, 1);
}
this.gearsStore_.checkForUpdate();
this.active_ = true;
};
/**
* @return {string} Store's current manifest URL.
*/
goog.gears.ManagedResourceStore.prototype.getManifestUrl = function() {
this.assertExists_();
return this.gearsStore_.manifestUrl;
};
/**
* @param {string} url Store's new manifest URL.
*/
goog.gears.ManagedResourceStore.prototype.setManifestUrl = function(url) {
this.assertExists_();
// Safety measure since Gears behaves very badly if it gets an unexpected
// data type (e.g., goog.Uri).
this.gearsStore_.manifestUrl = String(url);
};
/**
* @return {?string} The version of the managed store that is currently being
* served.
*/
goog.gears.ManagedResourceStore.prototype.getVersion = function() {
return this.exists() ? this.gearsStore_.currentVersion : null;
};
/**
* @return {goog.gears.ManagedResourceStore.UpdateStatus} The current update
* status.
*/
goog.gears.ManagedResourceStore.prototype.getStatus = function() {
this.assertExists_();
return /** @type {goog.gears.ManagedResourceStore.UpdateStatus} */ (
this.gearsStore_.updateStatus);
};
/**
* @return {boolean} Whether the store is currently enabled to serve local
* content.
*/
goog.gears.ManagedResourceStore.prototype.isEnabled = function() {
this.assertExists_();
return this.gearsStore_.enabled;
};
/**
* Sets whether the store is currently enabled to serve local content.
* @param {boolean} isEnabled True if the store is enabled and false otherwise.
*/
goog.gears.ManagedResourceStore.prototype.setEnabled = function(isEnabled) {
this.assertExists_();
// !! is a safety measure since Gears behaves very badly if it gets an
// unexpected data type.
this.gearsStore_.enabled = !!isEnabled;
};
/**
* Remove managed store.
*/
goog.gears.ManagedResourceStore.prototype.remove = function() {
this.assertExists_();
this.localServer_.removeManagedStore(this.name_, this.requiredCookie_);
this.gearsStore_ = null;
this.assertNotExists_();
};
/**
* Called periodically as the update proceeds. If it has completed, fire an
* approproiate event and cancel further checks.
* @private
*/
goog.gears.ManagedResourceStore.prototype.checkUpdateStatus_ = function() {
var e;
if (this.gearsStore_.updateStatus ==
goog.gears.ManagedResourceStore.UpdateStatus.FAILURE) {
e = new goog.gears.ManagedResourceStoreEvent(
goog.gears.ManagedResourceStore.EventType.ERROR,
this.gearsStore_.lastErrorMessage);
this.setFilesCounts_(0, 1);
} else if (this.gearsStore_.updateStatus ==
goog.gears.ManagedResourceStore.UpdateStatus.OK) {
e = new goog.gears.ManagedResourceStoreEvent(
goog.gears.ManagedResourceStore.EventType.SUCCESS);
this.setFilesCounts_(1, 1);
}
if (e) {
this.cancelStatusCheck_();
this.dispatchEvent(e);
// Fire complete after both error and success
this.dispatchEvent(goog.gears.ManagedResourceStore.EventType.COMPLETE);
this.active_ = false;
}
};
/**
* Cancel periodic status checks.
* @private
*/
goog.gears.ManagedResourceStore.prototype.cancelStatusCheck_ = function() {
if (!this.supportsEvents_ && this.timerId_ != null) {
this.timer_.clearInterval(this.timerId_);
this.timerId_ = null;
this.timer_ = null;
}
};
/**
* Callback for when the Gears managed resource store fires a progress event.
* @param {Object} details An object containg two fields, {@code filesComplete}
* and {@code filesTotal}.
* @private
*/
goog.gears.ManagedResourceStore.prototype.handleProgress_ = function(details) {
// setFilesCounts_ will dispatch the progress event as needed
this.setFilesCounts_(details['filesComplete'], details['filesTotal']);
};
/**
* Callback for when the Gears managed resource store fires a complete event.
* @param {Object} details An object containg one field called
* {@code newVersion}.
* @private
*/
goog.gears.ManagedResourceStore.prototype.handleComplete_ = function(details) {
this.dispatchEvent(goog.gears.ManagedResourceStore.EventType.SUCCESS);
this.dispatchEvent(goog.gears.ManagedResourceStore.EventType.COMPLETE);
this.active_ = false;
};
/**
* Callback for when the Gears managed resource store fires an error event.
* @param {Object} error An object containg one field called
* {@code message}.
* @private
*/
goog.gears.ManagedResourceStore.prototype.handleError_ = function(error) {
this.dispatchEvent(new goog.gears.ManagedResourceStoreEvent(
goog.gears.ManagedResourceStore.EventType.ERROR, error.message));
this.dispatchEvent(goog.gears.ManagedResourceStore.EventType.COMPLETE);
this.active_ = false;
};
/** @override */
goog.gears.ManagedResourceStore.prototype.disposeInternal = function() {
goog.gears.ManagedResourceStore.superClass_.disposeInternal.call(this);
if (this.supportsEvents_ && this.gearsStore_) {
this.gearsStore_.onprogress = null;
this.gearsStore_.oncomplete = null;
this.gearsStore_.onerror = null;
}
this.cancelStatusCheck_();
this.localServer_ = null;
this.gearsStore_ = null;
};
/**
* Enum for event types fired by ManagedResourceStore.
* @enum {string}
*/
goog.gears.ManagedResourceStore.EventType = {
COMPLETE: 'complete',
ERROR: 'error',
PROGRESS: 'progress',
SUCCESS: 'success'
};
/**
* Event used when a ManagedResourceStore update is complete
* @param {string} type The type of the event.
* @param {string=} opt_errorMessage The error message if failure.
* @constructor
* @extends {goog.events.Event}
*/
goog.gears.ManagedResourceStoreEvent = function(type, opt_errorMessage) {
goog.events.Event.call(this, type);
if (opt_errorMessage) {
this.errorMessage = opt_errorMessage;
}
};
goog.inherits(goog.gears.ManagedResourceStoreEvent, goog.events.Event);
/**
* Error message in the case of a failure event.
* @type {?string}
*/
goog.gears.ManagedResourceStoreEvent.prototype.errorMessage = 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 This file contains functions for using the Gears database.
*/
goog.provide('goog.gears.Database');
goog.provide('goog.gears.Database.EventType');
goog.provide('goog.gears.Database.TransactionEvent');
goog.require('goog.array');
goog.require('goog.debug');
goog.require('goog.debug.Logger');
goog.require('goog.events.Event');
goog.require('goog.events.EventTarget');
goog.require('goog.gears');
goog.require('goog.json');
/**
* Class that for accessing a Gears database
*
* @constructor
* @extends {goog.events.EventTarget}
* @param {string} userId the id token for this user.
* @param {string} appName the name of the application creating this database.
*/
goog.gears.Database = function(userId, appName) {
goog.events.EventTarget.call(this);
var factory = goog.gears.getFactory();
try {
/**
* The pointer to the Gears database object
* @private
*/
this.database_ = factory.create('beta.database', '1.0');
} catch (ex) {
// We will fail here if we cannot get a version of the database that is
// compatible with the JS code.
throw Error('Could not create the database. ' + ex.message);
}
if (this.database_ != null) {
var dbId = userId + '-' + appName;
var safeDbId = goog.gears.makeSafeFileName(dbId);
if (dbId != safeDbId) {
this.logger_.info('database name ' + dbId + '->' + safeDbId);
}
this.safeDbId_ = safeDbId;
this.database_.open(safeDbId);
} else {
throw Error('Could not create the database');
}
};
goog.inherits(goog.gears.Database, goog.events.EventTarget);
/**
* Constants for transaction event names.
* @enum {string}
*/
goog.gears.Database.EventType = {
BEFOREBEGIN: 'beforebegin',
BEGIN: 'begin',
BEFORECOMMIT: 'beforecommit',
COMMIT: 'commit',
BEFOREROLLBACK: 'beforerollback',
ROLLBACK: 'rollback'
};
/**
* Event info for transaction events.
* @extends {goog.events.Event}
* @constructor
* @param {goog.gears.Database.EventType} eventType The type of event.
*/
goog.gears.Database.TransactionEvent = function(eventType) {
goog.events.Event.call(this, eventType);
};
goog.inherits(goog.gears.Database.TransactionEvent, goog.events.Event);
/**
* Logger object
* @type {goog.debug.Logger}
* @private
*/
goog.gears.Database.prototype.logger_ =
goog.debug.Logger.getLogger('goog.gears.Database');
/**
* The safe name of the database.
* @type {string}
* @private
*/
goog.gears.Database.prototype.safeDbId_;
/**
* True if the database will be using transactions
* @private
* @type {boolean}
*/
goog.gears.Database.prototype.useTransactions_ = true;
/**
* Number of currently openned transactions. Use this to allow
* for nested Begin/Commit transactions. Will only do the real
* commit when this equals 0
* @private
* @type {number}
*/
goog.gears.Database.prototype.openTransactions_ = 0;
/**
* True if the outstanding opened transactions need to be rolled back
* @private
* @type {boolean}
*/
goog.gears.Database.prototype.needsRollback_ = false;
/**
* The default type of begin statement to use.
* @type {string}
* @private
*/
goog.gears.Database.prototype.defaultBeginType_ = 'IMMEDIATE';
/**
* Indicaton of the level of the begin. This is used to make sure
* nested begins do not elivate the level of the begin.
* @enum {number}
* @private
*/
goog.gears.Database.BeginLevels_ = {
'DEFERRED': 0,
'IMMEDIATE': 1,
'EXCLUSIVE': 2
};
/**
* The begin level of the currently opened transaction
* @type {goog.gears.Database.BeginLevels_}
* @private
*/
goog.gears.Database.prototype.currentBeginLevel_ =
goog.gears.Database.BeginLevels_['DEFERRED'];
/**
* Returns an array of arrays, where each sub array contains the selected
* values for each row in the result set.
* result values
*
* @param {GearsResultSet} rs the result set returned by execute.
* @return {Array} An array of arrays. Returns an empty array if
* there are no matching rows.
*/
goog.gears.Database.resultSetToArrays = function(rs) {
var rv = [];
if (rs) {
var cols = rs['fieldCount']();
while (rs['isValidRow']()) {
var row = new Array(cols);
for (var i = 0; i < cols; i++) {
row[i] = rs['field'](i);
}
rv.push(row);
rs['next']();
}
}
return rv;
};
/**
* Returns a array of hash objects, one per row in the result set,
* where the column names in the query are used as the members of
* the object.
*
* @param {GearsResultSet} rs the result set returned by execute.
* @return {Array.<Object>} An array containing hashes. Returns an empty
* array if there are no matching rows.
*/
goog.gears.Database.resultSetToObjectArray = function(rs) {
var rv = [];
if (rs) {
var cols = rs['fieldCount']();
var colNames = [];
for (var i = 0; i < cols; i++) {
colNames.push(rs['fieldName'](i));
}
while (rs['isValidRow']()) {
var h = {};
for (var i = 0; i < cols; i++) {
h[colNames[i]] = rs['field'](i);
}
rv.push(h);
rs['next']();
}
}
return rv;
};
/**
* Returns an array containing the first item of each row in a result set.
* This is useful for query that returns one column
*
* @param {GearsResultSet} rs the result set returned by execute.
* @return {Array.<Object>} An array containing the values in the first column
* Returns an empty array if there are no matching rows.
*/
goog.gears.Database.resultSetToValueArray = function(rs) {
var rv = [];
if (rs) {
while (rs['isValidRow']()) {
rv.push(rs['field'](0));
rs['next']();
}
}
return rv;
};
/**
* Returns a single value from the results (first column in first row).
*
* @param {GearsResultSet} rs the result set returned by execute.
* @return {(number,string,null)} The first item in the first row of the
* result set. Returns null if there are no matching rows.
*/
goog.gears.Database.resultSetToValue = function(rs) {
if (rs && rs['isValidRow']()) {
return rs['field'](0);
} else {
return null;
}
};
/**
* Returns a single hashed object from the result set (the first row),
* where the column names in the query are used as the members of
* the object.
*
* @param {GearsResultSet} rs the result set returned by execute.
* @return {Object} a hash map with the key-value-pairs from the first row.
* Returns null is there are no matching rows.
*/
goog.gears.Database.resultSetToObject = function(rs) {
if (rs && rs['isValidRow']()) {
var rv = {};
var cols = rs['fieldCount']();
for (var i = 0; i < cols; i++) {
rv[rs['fieldName'](i)] = rs['field'](i);
}
return rv;
} else {
return null;
}
};
/**
* Returns an array of the first row in the result set
*
* @param {GearsResultSet} rs the result set returned by execute.
* @return {Array} An array containing the values in the
* first result set. Returns an empty array if there no
* matching rows.
*/
goog.gears.Database.resultSetToArray = function(rs) {
var rv = [];
if (rs && rs['isValidRow']()) {
var cols = rs['fieldCount']();
for (var i = 0; i < cols; i++) {
rv[i] = rs['field'](i);
}
}
return rv;
};
/**
* Execute a sql statement with a set of arguments
*
* @param {string} sql The sql statement to execute.
* @param {...*} var_args The arguments to execute, either as a single
* array argument or as var_args.
* @return {GearsResultSet} The results.
*/
goog.gears.Database.prototype.execute = function(sql, var_args) {
this.logger_.finer('Executing SQL: ' + sql);
// TODO(user): Remove when Gears adds more rubust type handling.
// Safety measure since Gears behaves very badly if it gets an unexpected
// data type.
sql = String(sql);
var args;
try {
if (arguments.length == 1) {
return this.database_.execute(sql);
}
if (arguments.length == 2 && goog.isArray(arguments[1])) {
args = arguments[1];
} else {
args = goog.array.slice(arguments, 1);
}
this.logger_.finest('SQL arguments: ' + args);
// TODO(user): Type safety checking for args?
return this.database_.execute(sql, args);
} catch (e) {
if (args) {
sql += ': ' + goog.json.serialize(args);
}
throw goog.debug.enhanceError(e, sql);
}
};
/**
* This is useful to remove all the arguments juggling from inside the
* different helper functions.
*
* @private
* @param {string} sql The SQL statement.
* @param {Object} params An Array or arguments Object containing the query
* params. If the element at startIndex is an array, it will be used as
* the arguments passed to the execute method.
* @param {number} startIndex Where to start getting the query params from
* params.
* @return {GearsResultSet} The results of the command.
*/
goog.gears.Database.prototype.executeVarArgs_ = function(sql, params,
startIndex) {
if (params.length == 0 || startIndex >= params.length) {
return this.execute(sql);
} else {
if (goog.isArray(params[startIndex])) {
return this.execute(sql, params[startIndex]);
}
var args = Array.prototype.slice.call(
/** @type {{length:number}} */ (params), startIndex);
return this.execute(sql, args);
}
};
/**
* Helper methods for queryArrays, queryObjectArray, queryValueArray,
* queryValue, queryObject.
*
* @private
* @param {string} sql The SQL statement.
* @param {Function} f The function to call on the result set.
* @param {Object} params query params as an Array or an arguments object. If
* the element at startIndex is an array, it will be used as the arguments
* passed to the execute method.
* @param {number} startIndex Where to start getting the query params from
* params.
* @return {(Object,number,string,boolean,undefined,null)} whatever 'f'
* returns, which could be any type.
*/
goog.gears.Database.prototype.queryObject_ = function(sql,
f, params, startIndex) {
var rs = this.executeVarArgs_(sql, params, startIndex);
try {
return f(rs);
} finally {
if (rs) {
rs.close();
}
}
};
/**
* This calls query on the database and builds a two dimensional array
* containing the result.
*
* @param {string} sql The SQL statement.
* @param {...*} var_args Query params. An array or multiple arguments.
* @return {Array} An array of arrays containing the results of the query.
*/
goog.gears.Database.prototype.queryArrays = function(sql, var_args) {
return /** @type {Array} */ (this.queryObject_(sql,
goog.gears.Database.resultSetToArrays,
arguments,
1));
};
/**
* This calls query on the database and builds an array containing hashes
*
* @param {string} sql Ths SQL statement.
* @param {...*} var_args query params. An array or multiple arguments.
* @return {Array} An array of hashes containing the results of the query.
*/
goog.gears.Database.prototype.queryObjectArray = function(sql, var_args) {
return /** @type {Array} */ (this.queryObject_(sql,
goog.gears.Database.resultSetToObjectArray,
arguments,
1));
};
/**
* This calls query on the database and returns an array containing the values
* in the first column. This is useful if the result set only contains one
* column.
*
* @param {string} sql SQL statement.
* @param {...*} var_args query params. An array or multiple arguments.
* @return {Array} The values in the first column.
*/
goog.gears.Database.prototype.queryValueArray = function(sql, var_args) {
return /** @type {Array} */ (this.queryObject_(sql,
goog.gears.Database.resultSetToValueArray,
arguments,
1));
};
/**
* This calls query on the database and returns the first value in the first
* row.
*
* @param {string} sql SQL statement.
* @param {...*} var_args query params. An array or multiple arguments.
* @return {(number,string,null)} The first value in
* the first row.
*/
goog.gears.Database.prototype.queryValue = function(sql, var_args) {
return /** @type {(number,string,null)} */ (this.queryObject_(sql,
goog.gears.Database.resultSetToValue,
arguments,
1));
};
/**
* This calls query on the database and returns the first row as a hash map
* where the keys are the column names.
*
* @param {string} sql SQL statement.
* @param {...*} var_args query params. An array or multiple arguments.
* @return {Object} The first row as a hash map.
*/
goog.gears.Database.prototype.queryObject = function(sql, var_args) {
return /** @type {Object} */ (this.queryObject_(sql,
goog.gears.Database.resultSetToObject,
arguments,
1));
};
/**
* This calls query on the database and returns the first row as an array
*
* @param {string} sql SQL statement.
* @param {...*} var_args query params. An array or multiple arguments.
* @return {Array} The first row as an array.
*/
goog.gears.Database.prototype.queryArray = function(sql, var_args) {
return /** @type {Array} */ (this.queryObject_(sql,
goog.gears.Database.resultSetToArray,
arguments,
1));
};
/**
* For each value in the result set f will be called with the following
* parameters; value, rowIndex, columnIndex, columnName. Values will continue
* being processed as long as f returns true.
*
* @param {string} sql The SQL statement to execute.
* @param {Function} f Function to call for each value.
* @param {Object=} opt_this If present f will be called using this object as
* 'this'.
* @param {...*} var_args query params. An array or multiple arguments.
*/
goog.gears.Database.prototype.forEachValue = function(sql,
f, opt_this, var_args) {
var rs = this.executeVarArgs_(sql, arguments, 3);
try {
var rowIndex = 0;
var cols = rs['fieldCount']();
var colNames = [];
for (var i = 0; i < cols; i++) {
colNames.push(rs['fieldName'](i));
}
mainLoop: while (rs['isValidRow']()) {
for (var i = 0; i < cols; i++) {
if (!f.call(opt_this, rs['field'](i), rowIndex, i, colNames[i])) {
break mainLoop;
}
}
rs['next']();
rowIndex++;
}
} finally {
rs.close();
}
};
/**
* For each row in the result set f will be called with the following
* parameters: row (array of values), rowIndex and columnNames. Rows will
* continue being processed as long as f returns true.
*
* @param {string} sql The SQL statement to execute.
* @param {Function} f Function to call for each row.
* @param {Object=} opt_this If present f will be called using this
* object as 'this'.
* @param {...*} var_args query params. An array or multiple arguments.
*/
goog.gears.Database.prototype.forEachRow = function(sql,
f, opt_this, var_args) {
var rs = this.executeVarArgs_(sql, arguments, 3);
try {
var rowIndex = 0;
var cols = rs['fieldCount']();
var colNames = [];
for (var i = 0; i < cols; i++) {
colNames.push(rs['fieldName'](i));
}
var row;
while (rs['isValidRow']()) {
row = [];
for (var i = 0; i < cols; i++) {
row.push(rs['field'](i));
}
if (!f.call(opt_this, row, rowIndex, colNames)) {
break;
}
rs['next']();
rowIndex++;
}
} finally {
rs.close();
}
};
/**
* Executes a function transactionally.
*
* @param {Function} func the function to execute transactionally.
* Takes no params.
* @return {Object|number|boolean|string|null|undefined} the return value
* of 'func()'.
*/
goog.gears.Database.prototype.transact = function(func) {
this.begin();
try {
var result = func();
this.commit();
} catch (e) {
this.rollback(e);
throw e;
}
return result;
};
/**
* Helper that performs either a COMMIT or ROLLBACK command and dispatches
* pre/post commit/rollback events.
*
* @private
*
* @param {boolean} rollback Whether to rollback or commit.
* @return {boolean} True if the transaction was closed, false otherwise.
*/
goog.gears.Database.prototype.closeTransaction_ = function(rollback) {
// Send before rollback/commit event
var cmd;
var eventType;
cmd = rollback ? 'ROLLBACK' : 'COMMIT';
eventType = rollback ? goog.gears.Database.EventType.BEFOREROLLBACK :
goog.gears.Database.EventType.BEFORECOMMIT;
var event = new goog.gears.Database.TransactionEvent(eventType);
var returnValue = this.dispatchEvent(event);
// Only commit/rollback and send events if none of the event listeners
// called preventDefault().
if (returnValue) {
this.database_.execute(cmd);
this.openTransactions_ = 0;
eventType = rollback ? goog.gears.Database.EventType.ROLLBACK :
goog.gears.Database.EventType.COMMIT;
this.dispatchEvent(new goog.gears.Database.TransactionEvent(eventType));
}
return returnValue;
};
/**
* Whether transactions are used for the database
*
* @param {boolean} b Whether to use transactions or not.
*/
goog.gears.Database.prototype.setUseTransactions = function(b) {
this.useTransactions_ = b;
};
/**
* Whether transactions are used for the database
*
* @return {boolean} true if transactions should be used.
*/
goog.gears.Database.prototype.getUseTransactions = function() {
return this.useTransactions_;
};
/**
* Sets the default begin type.
*
* @param {string} beginType The default begin type.
*/
goog.gears.Database.prototype.setDefaultBeginType = function(beginType) {
if (beginType in goog.gears.Database.BeginLevels_) {
this.defaultBeginType_ = beginType;
}
};
/**
* Marks the beginning of a database transaction. Does a real BEGIN operation
* if useTransactions is true for this database and the this is the first
* opened transaction
* @private
*
* @param {string} beginType the type of begin comand.
* @return {boolean} true if the BEGIN has been executed.
*/
goog.gears.Database.prototype.beginTransaction_ = function(beginType) {
if (this.useTransactions_) {
if (this.openTransactions_ == 0) {
this.needsRollback_ = false;
this.dispatchEvent(
new goog.gears.Database.TransactionEvent(
goog.gears.Database.EventType.BEFOREBEGIN));
this.database_.execute('BEGIN ' + beginType);
this.currentBeginLevel_ =
goog.gears.Database.BeginLevels_[beginType];
this.openTransactions_ = 1;
try {
this.dispatchEvent(
new goog.gears.Database.TransactionEvent(
goog.gears.Database.EventType.BEGIN));
} catch (e) {
this.database_.execute('ROLLBACK');
this.openTransactions_ = 0;
throw e;
}
return true;
} else if (this.needsRollback_) {
throw Error(
'Cannot begin a transaction with a rollback pending');
} else if (goog.gears.Database.BeginLevels_[beginType] >
this.currentBeginLevel_) {
throw Error(
'Cannot elevate the level within a nested begin');
} else {
this.openTransactions_++;
}
}
return false;
};
/**
* Marks the beginning of a database transaction using the default begin
* type. Does a real BEGIN operation if useTransactions is true for this
* database and this is the first opened transaction. This will throw
* an exception if this is a nested begin and is trying to elevate the
* begin type from the original BEGIN that was processed.
*
* @return {boolean} true if the BEGIN has been executed.
*/
goog.gears.Database.prototype.begin = function() {
return this.beginTransaction_(this.defaultBeginType_);
};
/**
* Marks the beginning of a deferred database transaction.
* Does a real BEGIN operation if useTransactions is true for this
* database and this is the first opened transaction.
*
* @return {boolean} true if the BEGIN has been executed.
*/
goog.gears.Database.prototype.beginDeferred = function() {
return this.beginTransaction_('DEFERRED');
};
/**
* Marks the beginning of an immediate database transaction.
* Does a real BEGIN operation if useTransactions is true for this
* database and this is the first opened transaction. This will throw
* an exception if this is a nested begin and is trying to elevate the
* begin type from the original BEGIN that was processed.
*
* @return {boolean} true if the BEGIN has been executed.
*/
goog.gears.Database.prototype.beginImmediate = function() {
return this.beginTransaction_('IMMEDIATE');
};
/**
* Marks the beginning of an exclusive database transaction.
* Does a real BEGIN operation if useTransactions is true for this
* database and this is the first opened transaction. This will throw
* an exception if this is a nested begin and is trying to elevate the
* begin type from the original BEGIN that was processed.
*
* @return {boolean} true if the BEGIN has been executed.
*/
goog.gears.Database.prototype.beginExclusive = function() {
return this.beginTransaction_('EXCLUSIVE');
};
/**
* Marks the end of a successful transaction. Will do a real COMMIT
* if this the last outstanding transaction unless a nested transaction
* was closed with a ROLLBACK in which case a real ROLLBACK will be performed.
*
* @return {boolean} true if the COMMIT has been executed.
*/
goog.gears.Database.prototype.commit = function() {
if (this.useTransactions_) {
if (this.openTransactions_ <= 0) {
throw Error('Unbalanced transaction');
}
// Only one left.
if (this.openTransactions_ == 1) {
var closed = this.closeTransaction_(this.needsRollback_);
return !this.needsRollback_ && closed;
} else {
this.openTransactions_--;
}
}
return false;
};
/**
* Marks the end of an unsuccessful transaction. Will do a real ROLLBACK
* if this the last outstanding transaction, otherwise the real ROLLBACK will
* be deferred until the last outstanding transaction is closed.
*
* @param {Error=} opt_e the exception that caused this rollback. If it
* is provided then that exception is rethown if
* the rollback does not take place.
* @return {boolean} true if the ROLLBACK has been executed or if we are not
* using transactions.
*/
goog.gears.Database.prototype.rollback = function(opt_e) {
var closed = true;
if (this.useTransactions_) {
if (this.openTransactions_ <= 0) {
throw Error('Unbalanced transaction');
}
// Only one left.
if (this.openTransactions_ == 1) {
closed = this.closeTransaction_(true);
} else {
this.openTransactions_--;
this.needsRollback_ = true;
if (opt_e) {
throw opt_e;
}
return false;
}
}
return closed;
};
/**
* Returns whether or not we're in a transaction.
*
* @return {boolean} true if a transaction has been started and is not yet
* complete.
*/
goog.gears.Database.prototype.isInTransaction = function() {
return this.useTransactions_ && this.openTransactions_ > 0;
};
/**
* Ensures there is no open transaction upon return. An existing open
* transaction is rolled back.
*
* @param {string=} opt_logMsgPrefix a prefix to the message that is logged when
* an unexpected open transaction is found.
*/
goog.gears.Database.prototype.ensureNoTransaction = function(opt_logMsgPrefix) {
if (this.isInTransaction()) {
this.logger_.warning((opt_logMsgPrefix || 'ensureNoTransaction') +
' - rolling back unexpected transaction');
do {
this.rollback();
} while (this.isInTransaction());
}
};
/**
* Returns whether or not the current transaction has a pending rollback.
* Returns false if there is no current transaction.
*
* @return {boolean} Whether a started transaction has a rollback pending.
*/
goog.gears.Database.prototype.needsRollback = function() {
return this.useTransactions_ &&
this.openTransactions_ > 0 &&
this.needsRollback_;
};
/**
* Returns the time in Ms that database operations have currently
* consumed. This only exists in debug builds, but it still may be useful
* for goog.gears.Trace.
*
* @return {number} The time in Ms that database operations have currently
* consumed.
*/
goog.gears.Database.prototype.getExecutionTime = function() {
return this.database_['executeMsec'] || 0;
};
/**
* @return {number} The id of the last inserted row.
*/
goog.gears.Database.prototype.getLastInsertRowId = function() {
return this.database_['lastInsertRowId'];
};
/**
* Opens the database.
*/
goog.gears.Database.prototype.open = function() {
if (this.database_ && this.safeDbId_) {
this.database_.open(this.safeDbId_);
} else {
throw Error('Could not open the database');
}
};
/**
* Closes the database.
*/
goog.gears.Database.prototype.close = function() {
if (this.database_) {
this.database_.close();
}
};
/** @override */
goog.gears.Database.prototype.disposeInternal = function() {
goog.gears.Database.superClass_.disposeInternal.call(this);
this.database_ = null;
};
/**
* Determines if the exception is a locking error.
* @param {Error|string} ex The exception object or error string.
* @return {boolean} Whether this is a database locked exception.
*/
goog.gears.Database.isLockedException = function(ex) {
// TODO(user): change the test when gears provides a reasonable
// error code to check.
var message = goog.isString(ex) ? ex : ex.message;
return !!message && message.indexOf('database is locked') >= 0;
};
/**
* Removes the database.
* @throws {Error} This requires Gears 0.5 or newer and will throw an error if
* called on a too old version of Gears.
*/
goog.gears.Database.prototype.remove = function() {
this.database_.remove();
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file implements a store for goog.debug.Logger data.
*/
goog.provide('goog.gears.LogStore');
goog.provide('goog.gears.LogStore.Query');
goog.require('goog.async.Delay');
goog.require('goog.debug.LogManager');
goog.require('goog.debug.LogRecord');
goog.require('goog.debug.Logger');
goog.require('goog.debug.Logger.Level');
goog.require('goog.gears.BaseStore');
goog.require('goog.gears.BaseStore.SchemaType');
goog.require('goog.json');
/**
* Implements a store for goog.debug.Logger data.
* @param {goog.gears.Database} database Database.
* @param {?string=} opt_tableName Name of logging table to use.
* @extends {goog.gears.BaseStore}
* @constructor
*/
goog.gears.LogStore = function(database, opt_tableName) {
goog.gears.BaseStore.call(this, database);
/**
* Name of log table.
* @type {string}
*/
var tableName = opt_tableName || goog.gears.LogStore.DEFAULT_TABLE_NAME_;
this.tableName_ = tableName;
// Override BaseStore schema attribute.
this.schema = [
{
type: goog.gears.BaseStore.SchemaType.TABLE,
name: tableName,
columns: [
// Unique ID.
'id INTEGER PRIMARY KEY AUTOINCREMENT',
// Timestamp.
'millis BIGINT',
// #goog.debug.Logger.Level value.
'level INTEGER',
// Message.
'msg TEXT',
// Name of logger object.
'logger TEXT',
// Serialized error object.
'exception TEXT',
// Full exception text.
'exceptionText TEXT'
]
},
{
type: goog.gears.BaseStore.SchemaType.INDEX,
name: tableName + 'MillisIndex',
isUnique: false,
tableName: tableName,
columns: ['millis']
},
{
type: goog.gears.BaseStore.SchemaType.INDEX,
name: tableName + 'LevelIndex',
isUnique: false,
tableName: tableName,
columns: ['level']
}
];
/**
* Buffered log records not yet flushed to DB.
* @type {Array.<goog.debug.LogRecord>}
* @private
*/
this.records_ = [];
/**
* Save the publish handler so it can be removed.
* @type {Function}
* @private
*/
this.publishHandler_ = goog.bind(this.addLogRecord, this);
};
goog.inherits(goog.gears.LogStore, goog.gears.BaseStore);
/** @override */
goog.gears.LogStore.prototype.version = 1;
/**
* Whether we are currently capturing logger output.
* @type {boolean}
* @private
*/
goog.gears.LogStore.prototype.isCapturing_ = false;
/**
* Size of buffered log data messages.
* @type {number}
* @private
*/
goog.gears.LogStore.prototype.bufferSize_ = 0;
/**
* Scheduler for pruning action.
* @type {goog.async.Delay?}
* @private
*/
goog.gears.LogStore.prototype.delay_ = null;
/**
* Use this to protect against recursive flushing.
* @type {boolean}
* @private
*/
goog.gears.LogStore.prototype.isFlushing_ = false;
/**
* Logger.
* @type {goog.debug.Logger}
* @private
*/
goog.gears.LogStore.prototype.logger_ =
goog.debug.Logger.getLogger('goog.gears.LogStore');
/**
* Default value for how many records we keep when pruning.
* @type {number}
* @private
*/
goog.gears.LogStore.DEFAULT_PRUNE_KEEPER_COUNT_ = 1000;
/**
* Default value for how often to auto-prune (10 minutes).
* @type {number}
* @private
*/
goog.gears.LogStore.DEFAULT_AUTOPRUNE_INTERVAL_MILLIS_ = 10 * 60 * 1000;
/**
* The name for the log table.
* @type {string}
* @private
*/
goog.gears.LogStore.DEFAULT_TABLE_NAME_ = 'GoogGearsDebugLogStore';
/**
* Max message bytes to buffer before flushing to database.
* @type {number}
* @private
*/
goog.gears.LogStore.MAX_BUFFER_BYTES_ = 200000;
/**
* Flush buffered log records.
*/
goog.gears.LogStore.prototype.flush = function() {
if (this.isFlushing_ || !this.getDatabaseInternal()) {
return;
}
this.isFlushing_ = true;
// Grab local copy of records so database can log during this process.
this.logger_.info('flushing ' + this.records_.length + ' records');
var records = this.records_;
this.records_ = [];
for (var i = 0; i < records.length; i++) {
var record = records[i];
var exception = record.getException();
var serializedException = exception ? goog.json.serialize(exception) : '';
var statement = 'INSERT INTO ' + this.tableName_ +
' (millis, level, msg, logger, exception, exceptionText)' +
' VALUES (?, ?, ?, ?, ?, ?)';
this.getDatabaseInternal().execute(statement,
record.getMillis(), record.getLevel().value, record.getMessage(),
record.getLoggerName(), serializedException,
record.getExceptionText() || '');
}
this.isFlushing_ = false;
};
/**
* Create new delay object for auto-pruning. Does not stop or
* start auto-pruning, call #startAutoPrune and #startAutoPrune for that.
* @param {?number=} opt_count Number of records of recent hitory to keep.
* @param {?number=} opt_interval Milliseconds to wait before next pruning.
*/
goog.gears.LogStore.prototype.createAutoPruneDelay = function(
opt_count, opt_interval) {
if (this.delay_) {
this.delay_.dispose();
this.delay_ = null;
}
var interval = typeof opt_interval == 'number' ?
opt_interval : goog.gears.LogStore.DEFAULT_AUTOPRUNE_INTERVAL_MILLIS_;
var listener = goog.bind(this.autoPrune_, this, opt_count);
this.delay_ = new goog.async.Delay(listener, interval);
};
/**
* Enable periodic pruning. As a side effect, this also flushes the memory
* buffer.
*/
goog.gears.LogStore.prototype.startAutoPrune = function() {
if (!this.delay_) {
this.createAutoPruneDelay(
goog.gears.LogStore.DEFAULT_PRUNE_KEEPER_COUNT_,
goog.gears.LogStore.DEFAULT_AUTOPRUNE_INTERVAL_MILLIS_);
}
this.delay_.fire();
};
/**
* Disable scheduled pruning.
*/
goog.gears.LogStore.prototype.stopAutoPrune = function() {
if (this.delay_) {
this.delay_.stop();
}
};
/**
* @return {boolean} True iff auto prune timer is active.
*/
goog.gears.LogStore.prototype.isAutoPruneActive = function() {
return !!this.delay_ && this.delay_.isActive();
};
/**
* Prune, and schedule next pruning.
* @param {?number=} opt_count Number of records of recent hitory to keep.
* @private
*/
goog.gears.LogStore.prototype.autoPrune_ = function(opt_count) {
this.pruneBeforeCount(opt_count);
this.delay_.start();
};
/**
* Keep some number of most recent log records and delete all older ones.
* @param {?number=} opt_count Number of records of recent history to keep. If
* unspecified, we use #goog.gears.LogStore.DEFAULT_PRUNE_KEEPER_COUNT_.
* Pass in 0 to delete all log records.
*/
goog.gears.LogStore.prototype.pruneBeforeCount = function(opt_count) {
if (!this.getDatabaseInternal()) {
return;
}
var count = typeof opt_count == 'number' ?
opt_count : goog.gears.LogStore.DEFAULT_PRUNE_KEEPER_COUNT_;
this.logger_.info('pruning before ' + count + ' records ago');
this.flush();
this.getDatabaseInternal().execute('DELETE FROM ' + this.tableName_ +
' WHERE id <= ((SELECT MAX(id) FROM ' + this.tableName_ + ') - ?)',
count);
};
/**
* Delete log record #id and all older records.
* @param {number} sequenceNumber ID before which we delete all records.
*/
goog.gears.LogStore.prototype.pruneBeforeSequenceNumber =
function(sequenceNumber) {
if (!this.getDatabaseInternal()) {
return;
}
this.logger_.info('pruning before sequence number ' + sequenceNumber);
this.flush();
this.getDatabaseInternal().execute(
'DELETE FROM ' + this.tableName_ + ' WHERE id <= ?',
sequenceNumber);
};
/**
* Whether we are currently capturing logger output.
* @return {boolean} Whether we are currently capturing logger output.
*/
goog.gears.LogStore.prototype.isCapturing = function() {
return this.isCapturing_;
};
/**
* Sets whether we are currently capturing logger output.
* @param {boolean} capturing Whether to capture logger output.
*/
goog.gears.LogStore.prototype.setCapturing = function(capturing) {
if (capturing != this.isCapturing_) {
this.isCapturing_ = capturing;
// Attach or detach handler from the root logger.
var rootLogger = goog.debug.LogManager.getRoot();
if (capturing) {
rootLogger.addHandler(this.publishHandler_);
this.logger_.info('enabled');
} else {
this.logger_.info('disabling');
rootLogger.removeHandler(this.publishHandler_);
}
}
};
/**
* Adds a log record.
* @param {goog.debug.LogRecord} logRecord the LogRecord.
*/
goog.gears.LogStore.prototype.addLogRecord = function(logRecord) {
this.records_.push(logRecord);
this.bufferSize_ += logRecord.getMessage().length;
var exceptionText = logRecord.getExceptionText();
if (exceptionText) {
this.bufferSize_ += exceptionText.length;
}
if (this.bufferSize_ >= goog.gears.LogStore.MAX_BUFFER_BYTES_) {
this.flush();
}
};
/**
* Select log records.
* @param {goog.gears.LogStore.Query} query Query object.
* @return {Array.<goog.debug.LogRecord>} Selected logs in descending
* order of creation time.
*/
goog.gears.LogStore.prototype.select = function(query) {
if (!this.getDatabaseInternal()) {
// This should only occur if we've been disposed.
return [];
}
this.flush();
// TODO(user) Perhaps have Query object build this SQL string so we can
// omit unneeded WHERE clauses.
var statement =
'SELECT id, millis, level, msg, logger, exception, exceptionText' +
' FROM ' + this.tableName_ +
' WHERE level >= ? AND millis >= ? AND millis <= ?' +
' AND msg like ? and logger like ?' +
' ORDER BY id DESC LIMIT ?';
var rows = this.getDatabaseInternal().queryObjectArray(statement,
query.level.value, query.minMillis, query.maxMillis,
query.msgLike, query.loggerLike, query.limit);
var result = Array(rows.length);
for (var i = rows.length - 1; i >= 0; i--) {
var row = rows[i];
// Parse fields, allowing for invalid values.
var sequenceNumber = Number(row['id']) || 0;
var level = goog.debug.Logger.Level.getPredefinedLevelByValue(
Number(row['level']) || 0);
var msg = row['msg'] || '';
var loggerName = row['logger'] || '';
var millis = Number(row['millis']) || 0;
var serializedException = row['exception'];
var exception = serializedException ?
goog.json.parse(serializedException) : null;
var exceptionText = row['exceptionText'] || '';
// Create record.
var record = new goog.debug.LogRecord(level, msg, loggerName,
millis, sequenceNumber);
if (exception) {
record.setException(exception);
record.setExceptionText(exceptionText);
}
result[i] = record;
}
return result;
};
/** @override */
goog.gears.LogStore.prototype.disposeInternal = function() {
this.flush();
goog.gears.LogStore.superClass_.disposeInternal.call(this);
if (this.delay_) {
this.delay_.dispose();
this.delay_ = null;
}
};
/**
* Query to select log records.
* @constructor
*/
goog.gears.LogStore.Query = function() {
};
/**
* Minimum logging level.
* @type {goog.debug.Logger.Level}
*/
goog.gears.LogStore.Query.prototype.level = goog.debug.Logger.Level.ALL;
/**
* Minimum timestamp, inclusive.
* @type {number}
*/
goog.gears.LogStore.Query.prototype.minMillis = -1;
/**
* Maximum timestamp, inclusive.
* @type {number}
*/
goog.gears.LogStore.Query.prototype.maxMillis = Infinity;
/**
* Message 'like' pattern.
* See http://www.sqlite.org/lang_expr.html#likeFunc for 'like' syntax.
* @type {string}
*/
goog.gears.LogStore.Query.prototype.msgLike = '%';
/**
* Logger name 'like' pattern.
* See http://www.sqlite.org/lang_expr.html#likeFunc for 'like' syntax.
* @type {string}
*/
goog.gears.LogStore.Query.prototype.loggerLike = '%';
/**
* Max # recent records to return. -1 means no limit.
* @type {number}
*/
goog.gears.LogStore.Query.prototype.limit = -1;
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This represents a Gears worker (background process).
*
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.gears.Worker');
goog.provide('goog.gears.Worker.EventType');
goog.provide('goog.gears.WorkerEvent');
goog.require('goog.events.Event');
goog.require('goog.events.EventTarget');
/**
* This is an absctraction of workers that can be used with Gears WorkerPool.
* @constructor
* @param {goog.gears.WorkerPool} workerPool WorkerPool object.
* @param {number=} opt_id The id of the worker this represents.
*
* @extends {goog.events.EventTarget}
*/
goog.gears.Worker = function(workerPool, opt_id) {
goog.events.EventTarget.call(this);
/**
* Reference to the worker pool.
* @type {goog.gears.WorkerPool}
* @private
*/
this.workerPool_ = workerPool;
if (opt_id != null) {
this.init(opt_id);
}
};
goog.inherits(goog.gears.Worker, goog.events.EventTarget);
/**
* Called when we receive a message from this worker. The message will
* first be dispatched as a WorkerEvent with type {@code EventType.MESSAGE} and
* then a {@code EventType.COMMAND}. An EventTarget may call
* {@code WorkerEvent.preventDefault()} to stop further dispatches.
* @param {GearsMessageObject} messageObject An object containing all
* information about the message.
*/
goog.gears.Worker.prototype.handleMessage = function(messageObject) {
// First dispatch a message event.
var messageEvent = new goog.gears.WorkerEvent(
goog.gears.Worker.EventType.MESSAGE,
messageObject);
// Allow the user to call prevent default to not process the COMMAND.
if (this.dispatchEvent(messageEvent)) {
if (goog.gears.Worker.isCommandLike(messageObject.body)) {
this.dispatchEvent(new goog.gears.WorkerEvent(
goog.gears.Worker.EventType.COMMAND,
messageObject));
}
}
};
/**
* The ID of the worker we are communicating with.
* @type {?number}
* @private
*/
goog.gears.Worker.prototype.id_ = null;
/**
* Initializes the worker object with a worker id.
* @param {number} id The id of the worker this represents.
*/
goog.gears.Worker.prototype.init = function(id) {
if (this.id_ != null) {
throw Error('Can only set the worker id once');
}
this.id_ = id;
this.workerPool_.registerWorker(this);
};
/**
* Sends a command to the worker.
* @param {number} commandId The ID of the command to
* send.
* @param {Object} params An object to send as the parameters. This object
* must be something that Gears can serialize. This includes JSON as well
* as Gears blobs.
*/
goog.gears.Worker.prototype.sendCommand = function(commandId, params) {
this.sendMessage([commandId, params]);
};
/**
* Sends a message to the worker.
* @param {*} message The message to send to the target worker.
*/
goog.gears.Worker.prototype.sendMessage = function(message) {
this.workerPool_.sendMessage(message, this);
};
/**
* Gets an ID that uniquely identifies this worker. The ID is unique among all
* worker from the same WorkerPool.
*
* @return {number} The ID of the worker. This might be null if the
* worker has not been initialized yet.
*/
goog.gears.Worker.prototype.getId = function() {
if (this.id_ == null) {
throw Error('The worker has not yet been initialized');
}
return this.id_;
};
/**
* Whether an object looks like a command. A command is an array with length 2
* where the first element is a number.
* @param {*} obj The object to test.
* @return {boolean} true if the object looks like a command.
*/
goog.gears.Worker.isCommandLike = function(obj) {
return goog.isArray(obj) && obj.length == 2 &&
goog.isNumber(/** @type {Array} */ (obj)[0]);
};
/** @override */
goog.gears.Worker.prototype.disposeInternal = function() {
goog.gears.Worker.superClass_.disposeInternal.call(this);
this.workerPool_.unregisterWorker(this);
this.workerPool_ = null;
};
/**
* Enum for event types fired by the worker.
* @enum {string}
*/
goog.gears.Worker.EventType = {
MESSAGE: 'message',
COMMAND: 'command'
};
/**
* Event used when the worker recieves a message
* @param {string} type The type of event.
* @param {GearsMessageObject} messageObject The message object.
*
* @constructor
* @extends {goog.events.Event}
*/
goog.gears.WorkerEvent = function(type, messageObject) {
goog.events.Event.call(this, type);
/**
* The message sent from the worker.
* @type {*}
*/
this.message = messageObject.body;
/**
* The JSON object sent from the worker.
* @type {*}
* @deprecated Use message instead.
*/
this.json = this.message;
/**
* The object containing all information about the message.
* @type {GearsMessageObject}
*/
this.messageObject = messageObject;
};
goog.inherits(goog.gears.WorkerEvent, 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 Definition of goog.gears.BaseStore which
* is a base class for the various database stores. It provides
* the basic structure for creating, updating and removing the store, as well
* as versioning. It also provides ways to interconnect stores.
*
*/
goog.provide('goog.gears.BaseStore');
goog.provide('goog.gears.BaseStore.SchemaType');
goog.require('goog.Disposable');
/**
* This class implements the common store functionality
*
* @param {goog.gears.Database} database The data base to store the data in.
* @constructor
* @extends {goog.Disposable}
*/
goog.gears.BaseStore = function(database) {
goog.Disposable.call(this);
/**
* The underlying database that holds the message store.
* @private
* @type {goog.gears.Database}
*/
this.database_ = database;
};
goog.inherits(goog.gears.BaseStore, goog.Disposable);
/**
* Schema definition types
* @enum {number}
*/
goog.gears.BaseStore.SchemaType = {
TABLE: 1,
VIRTUAL_TABLE: 2,
INDEX: 3,
BEFORE_INSERT_TRIGGER: 4,
AFTER_INSERT_TRIGGER: 5,
BEFORE_UPDATE_TRIGGER: 6,
AFTER_UPDATE_TRIGGER: 7,
BEFORE_DELETE_TRIGGER: 8,
AFTER_DELETE_TRIGGER: 9
};
/**
* The name of the store. Subclasses should override and choose their own
* name. That name is used for the maintaining the version string
* @protected
* @type {string}
*/
goog.gears.BaseStore.prototype.name = 'Base';
/**
* The version number of the database schema. It is used to determine whether
* the store's portion of the database needs to be updated. Subclassses should
* override this value.
* @protected
* @type {number}
*/
goog.gears.BaseStore.prototype.version = 1;
/**
* The database schema for the store. This is an array of objects, where each
* object describes a database object (table, index, trigger). Documentation
* about the object's fields can be found in the #createSchema documentation.
* This is in the prototype so that it can be overriden by the subclass. This
* field is read only.
* @protected
* @type {Array.<Object>}
*/
goog.gears.BaseStore.prototype.schema = [];
/**
* Gets the underlying database.
* @return {goog.gears.Database}
* @protected
*/
goog.gears.BaseStore.prototype.getDatabaseInternal = function() {
return this.database_;
};
/**
* Updates the tables for the message store in the case where
* they are out of date.
*
* @protected
* @param {number} persistedVersion the current version of the tables in the
* database.
*/
goog.gears.BaseStore.prototype.updateStore = function(persistedVersion) {
// TODO(user): Need to figure out how to handle updates
// where to store the version number and is it globale or per unit.
};
/**
* Preloads any applicable data into the tables.
*
* @protected
*/
goog.gears.BaseStore.prototype.loadData = function() {
};
/**
* Creates in memory cache of data that is stored in the tables.
*
* @protected
*/
goog.gears.BaseStore.prototype.getCachedData = function() {
};
/**
* Informs other stores that this store exists .
*
* @protected
*/
goog.gears.BaseStore.prototype.informOtherStores = function() {
};
/**
* Makes sure that tables needed for the store exist and are up to date.
*/
goog.gears.BaseStore.prototype.ensureStoreExists = function() {
var persistedVersion = this.getStoreVersion();
if (persistedVersion) {
if (persistedVersion != this.version) {
// update
this.database_.begin();
try {
this.updateStore(persistedVersion);
this.setStoreVersion_(this.version);
this.database_.commit();
} catch (ex) {
this.database_.rollback(ex);
throw Error('Could not update the ' + this.name + ' schema ' +
' from version ' + persistedVersion + ' to ' + this.version +
': ' + (ex.message || 'unknown exception'));
}
}
} else {
// create
this.database_.begin();
try {
// This is rarely necessary, but it's possible if we rolled back a
// release and dropped the schema on version n-1 before installing
// again on version n.
this.dropSchema(this.schema);
this.createSchema(this.schema);
// Ensure that the version info schema exists.
this.createSchema([{
type: goog.gears.BaseStore.SchemaType.TABLE,
name: 'StoreVersionInfo',
columns: [
'StoreName TEXT NOT NULL PRIMARY KEY',
'Version INTEGER NOT NULL'
]}], true);
this.loadData();
this.setStoreVersion_(this.version);
this.database_.commit();
} catch (ex) {
this.database_.rollback(ex);
throw Error('Could not create the ' + this.name + ' schema' +
': ' + (ex.message || 'unknown exception'));
}
}
this.getCachedData();
this.informOtherStores();
};
/**
* Removes the tables for the MessageStore
*/
goog.gears.BaseStore.prototype.removeStore = function() {
this.database_.begin();
try {
this.removeStoreVersion();
this.dropSchema(this.schema);
this.database_.commit();
} catch (ex) {
this.database_.rollback(ex);
throw Error('Could not remove the ' + this.name + ' schema' +
': ' + (ex.message || 'unknown exception'));
}
};
/**
* Returns the name of the store.
*
* @return {string} The name of the store.
*/
goog.gears.BaseStore.prototype.getName = function() {
return this.name;
};
/**
* Returns the version number for the specified store
*
* @return {number} The version number of the store. Returns 0 if the
* store does not exist.
*/
goog.gears.BaseStore.prototype.getStoreVersion = function() {
try {
return /** @type {number} */ (this.database_.queryValue(
'SELECT Version FROM StoreVersionInfo WHERE StoreName=?',
this.name)) || 0;
} catch (ex) {
return 0;
}
};
/**
* Sets the version number for the specified store
*
* @param {number} version The version number for the store.
* @private
*/
goog.gears.BaseStore.prototype.setStoreVersion_ = function(version) {
// TODO(user): Need to determine if we should enforce the fact
// that store versions are monotonically increasing.
this.database_.execute(
'INSERT OR REPLACE INTO StoreVersionInfo ' +
'(StoreName, Version) VALUES(?,?)',
this.name,
version);
};
/**
* Removes the version number for the specified store
*/
goog.gears.BaseStore.prototype.removeStoreVersion = function() {
try {
this.database_.execute(
'DELETE FROM StoreVersionInfo WHERE StoreName=?',
this.name);
} catch (ex) {
// Ignore error - part of bootstrap process.
}
};
/**
* Generates an SQLITE CREATE TRIGGER statement from a definition array.
* @param {string} onStr the type of trigger to create.
* @param {Object} def a schema statement definition.
* @param {string} notExistsStr string to be included in the create
* indicating what to do.
* @return {string} the statement.
* @private
*/
goog.gears.BaseStore.prototype.getCreateTriggerStatement_ =
function(onStr, def, notExistsStr) {
return 'CREATE TRIGGER ' + notExistsStr + def.name + ' ' +
onStr + ' ON ' + def.tableName +
(def.when ? (' WHEN ' + def.when) : '') +
' BEGIN ' + def.actions.join('; ') + '; END';
};
/**
* Generates an SQLITE CREATE statement from a definition object.
* @param {Object} def a schema statement definition.
* @param {boolean=} opt_ifNotExists true if the table or index should be
* created only if it does not exist. Otherwise trying to create a table
* or index that already exists will result in an exception being thrown.
* @return {string} the statement.
* @private
*/
goog.gears.BaseStore.prototype.getCreateStatement_ =
function(def, opt_ifNotExists) {
var notExists = opt_ifNotExists ? 'IF NOT EXISTS ' : '';
switch (def.type) {
case goog.gears.BaseStore.SchemaType.TABLE:
return 'CREATE TABLE ' + notExists + def.name + ' (\n' +
def.columns.join(',\n ') +
')';
case goog.gears.BaseStore.SchemaType.VIRTUAL_TABLE:
return 'CREATE VIRTUAL TABLE ' + notExists + def.name +
' USING FTS2 (\n' + def.columns.join(',\n ') + ')';
case goog.gears.BaseStore.SchemaType.INDEX:
return 'CREATE' + (def.isUnique ? ' UNIQUE' : '') +
' INDEX ' + notExists + def.name + ' ON ' +
def.tableName + ' (\n' + def.columns.join(',\n ') + ')';
case goog.gears.BaseStore.SchemaType.BEFORE_INSERT_TRIGGER:
return this.getCreateTriggerStatement_('BEFORE INSERT', def, notExists);
case goog.gears.BaseStore.SchemaType.AFTER_INSERT_TRIGGER:
return this.getCreateTriggerStatement_('AFTER INSERT', def, notExists);
case goog.gears.BaseStore.SchemaType.BEFORE_UPDATE_TRIGGER:
return this.getCreateTriggerStatement_('BEFORE UPDATE', def, notExists);
case goog.gears.BaseStore.SchemaType.AFTER_UPDATE_TRIGGER:
return this.getCreateTriggerStatement_('AFTER UPDATE', def, notExists);
case goog.gears.BaseStore.SchemaType.BEFORE_DELETE_TRIGGER:
return this.getCreateTriggerStatement_('BEFORE DELETE', def, notExists);
case goog.gears.BaseStore.SchemaType.AFTER_DELETE_TRIGGER:
return this.getCreateTriggerStatement_('AFTER DELETE', def, notExists);
}
return '';
};
/**
* Generates an SQLITE DROP statement from a definition array.
* @param {Object} def a schema statement definition.
* @return {string} the statement.
* @private
*/
goog.gears.BaseStore.prototype.getDropStatement_ = function(def) {
switch (def.type) {
case goog.gears.BaseStore.SchemaType.TABLE:
case goog.gears.BaseStore.SchemaType.VIRTUAL_TABLE:
return 'DROP TABLE IF EXISTS ' + def.name;
case goog.gears.BaseStore.SchemaType.INDEX:
return 'DROP INDEX IF EXISTS ' + def.name;
case goog.gears.BaseStore.SchemaType.BEFORE_INSERT_TRIGGER:
case goog.gears.BaseStore.SchemaType.AFTER_INSERT_TRIGGER:
case goog.gears.BaseStore.SchemaType.BEFORE_UPDATE_TRIGGER:
case goog.gears.BaseStore.SchemaType.AFTER_UPDATE_TRIGGER:
case goog.gears.BaseStore.SchemaType.BEFORE_DELETE_TRIGGER:
case goog.gears.BaseStore.SchemaType.AFTER_DELETE_TRIGGER:
return 'DROP TRIGGER IF EXISTS ' + def.name;
}
return '';
};
/**
* Creates tables and indicies in the target database.
*
* @param {Array} defs definition arrays. This is an array of objects
* where each object describes a database object to create and drop.
* each object contains a 'type' field which of type
* goog.gears.BaseStore.SchemaType. Each object also contains a
* 'name' which contains the name of the object to create.
* A table object contains a 'columns' field which is an array
* that contains the column definitions for the table.
* A virtual table object contains c 'columns' field which contains
* the name of the columns. They are assumed to be of type text.
* An index object contains a 'tableName' field which is the name
* of the table that the index is on. It contains an 'isUnique'
* field which is a boolean indicating whether the index is
* unqiue or not. It also contains a 'columns' field which is
* an array that contains the columns names (possibly along with the
* ordering) that form the index.
* The trigger objects contain a 'tableName' field indicating the
* table the trigger is on. The type indicates the type of trigger.
* The trigger object may include a 'when' field which contains
* the when clause for the trigger. The trigger object also contains
* an 'actions' field which is an array of strings containing
* the actions for this trigger.
* @param {boolean=} opt_ifNotExists true if the table or index should be
* created only if it does not exist. Otherwise trying to create a table
* or index that already exists will result in an exception being thrown.
*/
goog.gears.BaseStore.prototype.createSchema = function(defs, opt_ifNotExists) {
this.database_.begin();
try {
for (var i = 0; i < defs.length; ++i) {
var sql = this.getCreateStatement_(defs[i], opt_ifNotExists);
this.database_.execute(sql);
}
this.database_.commit();
} catch (ex) {
this.database_.rollback(ex);
}
};
/**
* Drops tables and indicies in a target database.
*
* @param {Array} defs Definition arrays.
*/
goog.gears.BaseStore.prototype.dropSchema = function(defs) {
this.database_.begin();
try {
for (var i = defs.length - 1; i >= 0; --i) {
this.database_.execute(this.getDropStatement_(defs[i]));
}
this.database_.commit();
} catch (ex) {
this.database_.rollback(ex);
}
};
/**
* Creates triggers specified in definitions. Will first attempt
* to drop the trigger with this name first.
*
* @param {Array} defs Definition arrays.
*/
goog.gears.BaseStore.prototype.createTriggers = function(defs) {
this.database_.begin();
try {
for (var i = 0; i < defs.length; i++) {
var def = defs[i];
switch (def.type) {
case goog.gears.BaseStore.SchemaType.BEFORE_INSERT_TRIGGER:
case goog.gears.BaseStore.SchemaType.AFTER_INSERT_TRIGGER:
case goog.gears.BaseStore.SchemaType.BEFORE_UPDATE_TRIGGER:
case goog.gears.BaseStore.SchemaType.AFTER_UPDATE_TRIGGER:
case goog.gears.BaseStore.SchemaType.BEFORE_DELETE_TRIGGER:
case goog.gears.BaseStore.SchemaType.AFTER_DELETE_TRIGGER:
this.database_.execute('DROP TRIGGER IF EXISTS ' + def.name);
this.database_.execute(this.getCreateStatement_(def));
break;
}
}
this.database_.commit();
} catch (ex) {
this.database_.rollback(ex);
}
};
/**
* Returns true if the table exists in the database
*
* @param {string} name The table name.
* @return {boolean} Whether the table exists in the database.
*/
goog.gears.BaseStore.prototype.hasTable = function(name) {
return this.hasInSchema_('table', name);
};
/**
* Returns true if the index exists in the database
*
* @param {string} name The index name.
* @return {boolean} Whether the index exists in the database.
*/
goog.gears.BaseStore.prototype.hasIndex = function(name) {
return this.hasInSchema_('index', name);
};
/**
* @param {string} name The name of the trigger.
* @return {boolean} Whether the schema contains a trigger with the given name.
*/
goog.gears.BaseStore.prototype.hasTrigger = function(name) {
return this.hasInSchema_('trigger', name);
};
/**
* Returns true if the database contains the index or table
*
* @private
* @param {string} type The type of object to test for, 'table' or 'index'.
* @param {string} name The table or index name.
* @return {boolean} Whether the database contains the index or table.
*/
goog.gears.BaseStore.prototype.hasInSchema_ = function(type, name) {
return this.database_.queryValue('SELECT 1 FROM SQLITE_MASTER ' +
'WHERE TYPE=? AND NAME=?',
type,
name) != null;
};
/** @override */
goog.gears.BaseStore.prototype.disposeInternal = function() {
goog.gears.BaseStore.superClass_.disposeInternal.call(this);
this.database_ = null;
};
/**
* HACK(arv): The JSCompiler check for undefined properties sees that these
* fields are never set and raises warnings.
* @type {Array.<Object>}
* @private
*/
goog.gears.schemaDefDummy_ = [
{
type: '',
name: '',
when: '',
tableName: '',
actions: [],
isUnique: 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 This class provides a builder for building multipart form data
* that is to be usef with Gears BlobBuilder and GearsHttpRequest.
*
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.gears.MultipartFormData');
goog.require('goog.asserts');
goog.require('goog.gears');
goog.require('goog.string');
/**
* Creates a new multipart form data builder.
* @constructor
*/
goog.gears.MultipartFormData = function() {
/**
* The blob builder used to build the blob.
* @type {GearsBlobBuilder}
* @private
*/
this.blobBuilder_ = goog.gears.getFactory().create('beta.blobbuilder');
/**
* The boundary. This should be something that does not occurr in the values.
* @type {string}
* @private
*/
this.boundary_ = '----' + goog.string.getRandomString();
};
/**
* Constant for a carriage return followed by a new line.
* @type {string}
* @private
*/
goog.gears.MultipartFormData.CRLF_ = '\r\n';
/**
* Constant containing two dashes.
* @type {string}
* @private
*/
goog.gears.MultipartFormData.DASHES_ = '--';
/**
* Whether the builder has been closed.
* @type {boolean}
* @private
*/
goog.gears.MultipartFormData.prototype.closed_;
/**
* Whether the builder has any content.
* @type {boolean}
* @private
*/
goog.gears.MultipartFormData.prototype.hasContent_;
/**
* Adds a Gears file to the multipart.
* @param {string} name The name of the value.
* @param {GearsFile} gearsFile The Gears file as returned from openFiles etc.
* @return {goog.gears.MultipartFormData} The form builder itself.
*/
goog.gears.MultipartFormData.prototype.addFile = function(name, gearsFile) {
return this.addBlob(name, gearsFile.name, gearsFile.blob);
};
/**
* Adds some text to the multipart.
* @param {string} name The name of the value.
* @param {*} value The value. This will use toString on the value.
* @return {goog.gears.MultipartFormData} The form builder itself.
*/
goog.gears.MultipartFormData.prototype.addText = function(name, value) {
this.assertNotClosed_();
// Also assert that the value does not contain the boundary.
this.assertNoBoundary_(value);
this.hasContent_ = true;
this.blobBuilder_.append(
goog.gears.MultipartFormData.DASHES_ + this.boundary_ +
goog.gears.MultipartFormData.CRLF_ +
'Content-Disposition: form-data; name="' + name + '"' +
goog.gears.MultipartFormData.CRLF_ +
// The BlobBuilder uses UTF-8 so ensure that we use that at all times.
'Content-Type: text/plain; charset=UTF-8' +
goog.gears.MultipartFormData.CRLF_ +
goog.gears.MultipartFormData.CRLF_ +
value +
goog.gears.MultipartFormData.CRLF_);
return this;
};
/**
* Adds a Gears blob as a file to the multipart.
* @param {string} name The name of the value.
* @param {string} fileName The name of the file.
* @param {GearsBlob} blob The blob to add.
* @return {goog.gears.MultipartFormData} The form builder itself.
*/
goog.gears.MultipartFormData.prototype.addBlob = function(name, fileName,
blob) {
this.assertNotClosed_();
this.hasContent_ = true;
this.blobBuilder_.append(
goog.gears.MultipartFormData.DASHES_ + this.boundary_ +
goog.gears.MultipartFormData.CRLF_ +
'Content-Disposition: form-data; name="' + name + '"' +
'; filename="' + fileName + '"' +
goog.gears.MultipartFormData.CRLF_ +
'Content-Type: application/octet-stream' +
goog.gears.MultipartFormData.CRLF_ +
goog.gears.MultipartFormData.CRLF_);
this.blobBuilder_.append(blob);
this.blobBuilder_.append(goog.gears.MultipartFormData.CRLF_);
return this;
};
/**
* The content type to set on the GearsHttpRequest.
*
* var builder = new MultipartFormData;
* ...
* ghr.setRequestHeader('Content-Type', builder.getContentType());
* ghr.send(builder.getAsBlob());
*
* @return {string} The content type string to be used when posting this with
* a GearsHttpRequest.
*/
goog.gears.MultipartFormData.prototype.getContentType = function() {
return 'multipart/form-data; boundary=' + this.boundary_;
};
/**
* @return {GearsBlob} The blob to use in the send method of the
* GearsHttpRequest.
*/
goog.gears.MultipartFormData.prototype.getAsBlob = function() {
if (!this.closed_ && this.hasContent_) {
this.blobBuilder_.append(
goog.gears.MultipartFormData.DASHES_ +
this.boundary_ +
goog.gears.MultipartFormData.DASHES_ +
goog.gears.MultipartFormData.CRLF_);
this.closed_ = true;
}
return this.blobBuilder_.getAsBlob();
};
/**
* Asserts that we do not try to add any more data to a closed multipart form
* builder.
* @throws {Error} If the multipart form data has already been closed.
* @private
*/
goog.gears.MultipartFormData.prototype.assertNotClosed_ = function() {
goog.asserts.assert(!this.closed_, 'The multipart form builder has been ' +
'closed and no more data can be added to it');
};
/**
* Asserts that the value does not contain the boundary.
* @param {*} v The value to ensure that the string representation does not
* contain the boundary token.
* @throws {Error} If the value contains the boundary.
* @private
*/
goog.gears.MultipartFormData.prototype.assertNoBoundary_ = function(v) {
goog.asserts.assert(String(v).indexOf(this.boundary_) == -1,
'The value cannot contain the boundary');
};
| 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 An enum that contains the possible status type's of the Gears
* feature of an application.
*
*/
goog.provide('goog.gears.StatusType');
/**
* The possible status type's for Gears.
* @enum {string}
*/
goog.gears.StatusType = {
NOT_INSTALLED: 'ni',
INSTALLED: 'i',
PAUSED: 'p',
OFFLINE: 'off',
ONLINE: 'on',
SYNCING: 's',
CAPTURING: 'c',
ERROR: 'e'
};
| 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 message channel between Gears workers. This is meant to work
* even when the Gears worker has other message listeners. GearsWorkerChannel
* adds a specific prefix to its messages, and handles messages with that
* prefix.
*
*/
goog.provide('goog.gears.WorkerChannel');
goog.require('goog.Disposable');
goog.require('goog.debug');
goog.require('goog.debug.Logger');
goog.require('goog.events');
goog.require('goog.gears.Worker');
goog.require('goog.gears.Worker.EventType');
goog.require('goog.gears.WorkerEvent');
goog.require('goog.json');
goog.require('goog.messaging.AbstractChannel');
/**
* Creates a message channel for the given Gears worker.
*
* @param {goog.gears.Worker} worker The Gears worker to communicate with. This
* should already be initialized.
* @constructor
* @extends {goog.messaging.AbstractChannel}
*/
goog.gears.WorkerChannel = function(worker) {
goog.base(this);
/**
* The Gears worker to communicate with.
* @type {goog.gears.Worker}
* @private
*/
this.worker_ = worker;
goog.events.listen(this.worker_, goog.gears.Worker.EventType.MESSAGE,
this.deliver_, false, this);
};
goog.inherits(goog.gears.WorkerChannel, goog.messaging.AbstractChannel);
/**
* The flag added to messages that are sent by a GearsWorkerChannel, and are
* meant to be handled by one on the other side.
* @type {string}
*/
goog.gears.WorkerChannel.FLAG = '--goog.gears.WorkerChannel';
/**
* The expected origin of the other end of the worker channel, represented as a
* string of the form SCHEME://DOMAIN[:PORT]. The port may be omitted for
* standard ports (http port 80, https port 443).
*
* If this is set, all GearsWorkerChannel messages are validated to come from
* this origin, and ignored (with a warning) if they don't. Messages that aren't
* in the GearsWorkerChannel format are not validated.
*
* If more complex origin validation is required, the checkMessageOrigin method
* can be overridden.
*
* @type {?string}
*/
goog.gears.WorkerChannel.prototype.peerOrigin;
/**
* Logger for this class.
* @type {goog.debug.Logger}
* @protected
* @override
*/
goog.gears.WorkerChannel.prototype.logger =
goog.debug.Logger.getLogger('goog.gears.WorkerChannel');
/**
* @override
*/
goog.gears.WorkerChannel.prototype.send =
function(serviceName, payload) {
var message = {'serviceName': serviceName, 'payload': payload};
message[goog.gears.WorkerChannel.FLAG] = true;
this.worker_.sendMessage(message);
};
/** @override */
goog.gears.WorkerChannel.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
this.worker_.dispose();
};
/**
* Delivers a message to the appropriate service handler. If this message isn't
* a GearsWorkerChannel message, it's ignored and passed on to other handlers.
*
* @param {goog.gears.WorkerEvent} e The event.
* @private
*/
goog.gears.WorkerChannel.prototype.deliver_ = function(e) {
var messageObject = e.messageObject || {};
var body = messageObject.body;
if (!goog.isObject(body) || !body[goog.gears.WorkerChannel.FLAG]) {
return;
}
if (!this.checkMessageOrigin(messageObject.origin)) {
return;
}
if (this.validateMessage_(body)) {
this.deliver(body['serviceName'], body['payload']);
}
e.preventDefault();
e.stopPropagation();
};
/**
* Checks whether the message is invalid in some way.
*
* @param {Object} body The contents of the message.
* @return {boolean} True if the message is valid, false otherwise.
* @private
*/
goog.gears.WorkerChannel.prototype.validateMessage_ = function(body) {
if (!('serviceName' in body)) {
this.logger.warning('GearsWorkerChannel::deliver_(): ' +
'Message object doesn\'t contain service name: ' +
goog.debug.deepExpose(body));
return false;
}
if (!('payload' in body)) {
this.logger.warning('GearsWorkerChannel::deliver_(): ' +
'Message object doesn\'t contain payload: ' +
goog.debug.deepExpose(body));
return false;
}
return true;
};
/**
* Checks whether the origin for a given message is the expected origin. If it's
* not, a warning is logged and the message is ignored.
*
* This checks that the origin matches the peerOrigin property. It can be
* overridden if more complex origin detection is necessary.
*
* @param {string} messageOrigin The origin of the message, of the form
* SCHEME://HOST[:PORT]. The port is omitted for standard ports (http port
* 80, https port 443).
* @return {boolean} True if the origin is acceptable, false otherwise.
* @protected
*/
goog.gears.WorkerChannel.prototype.checkMessageOrigin = function(
messageOrigin) {
if (!this.peerOrigin) {
return true;
}
// Gears doesn't include standard port numbers, but we want to let the user
// include them, so we'll just edit them out.
var peerOrigin = this.peerOrigin;
if (/^http:/.test(peerOrigin)) {
peerOrigin = peerOrigin.replace(/\:80$/, '');
} else if (/^https:/.test(peerOrigin)) {
peerOrigin = peerOrigin.replace(/\:443$/, '');
}
if (messageOrigin === peerOrigin) {
return true;
}
this.logger.warning('Message from unexpected origin "' + messageOrigin +
'"; expected only messages from origin "' + peerOrigin +
'"');
return false;
};
| 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 This class lives on a worker thread and it intercepts the
* goog.debug.Logger objects and sends a LOGGER command to the main thread
* instead.
*
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.gears.LoggerClient');
goog.require('goog.Disposable');
goog.require('goog.debug');
goog.require('goog.debug.Logger');
/**
* Singleton class that overrides the goog.debug.Logger to send log commands
* to the main thread.
* @param {goog.gears.Worker} mainThread The main thread that has the
* logger server running.
* @param {number} logCommandId The command id used for logging.
* @param {string=} opt_workerName This, if present, is added to the error
* object when serializing it.
* @constructor
* @extends {goog.Disposable}
*/
goog.gears.LoggerClient = function(mainThread, logCommandId, opt_workerName) {
if (goog.gears.LoggerClient.instance_) {
return goog.gears.LoggerClient.instance_;
}
goog.Disposable.call(this);
/**
* The main thread object.
* @type {goog.gears.Worker}
* @private
*/
this.mainThread_ = mainThread;
/**
* The command id to use to send log commands to the main thread.
* @type {number}
* @private
*/
this.logCommandId_ = logCommandId;
/**
* The name of the worker thread.
* @type {string}
* @private
*/
this.workerName_ = opt_workerName || '';
var loggerClient = this;
// Override the log method
goog.debug.Logger.prototype.doLogRecord_ = function(logRecord) {
var name = this.getName();
loggerClient.sendLog_(
name, logRecord.getLevel(), logRecord.getMessage(),
logRecord.getException());
};
goog.gears.LoggerClient.instance_ = this;
};
goog.inherits(goog.gears.LoggerClient, goog.Disposable);
/**
* The singleton instance if any.
* @type {goog.gears.LoggerClient?}
* @private
*/
goog.gears.LoggerClient.instance_ = null;
/**
* Sends a log message to the main thread.
* @param {string} name The name of the logger.
* @param {goog.debug.Logger.Level} level One of the level identifiers.
* @param {string} msg The string message.
* @param {Object=} opt_exception An exception associated with the message.
* @private
*/
goog.gears.LoggerClient.prototype.sendLog_ = function(name,
level,
msg,
opt_exception) {
var exception;
if (opt_exception) {
var prefix = this.workerName_ ? this.workerName_ + ': ' : '';
exception = {
message: prefix + opt_exception.message,
stack: opt_exception.stack ||
goog.debug.getStacktrace(goog.debug.Logger.prototype.log)
};
// Add messageN to the exception in case it was added using
// goog.debug.enhanceError.
for (var i = 0; 'message' + i in opt_exception; i++) {
exception['message' + i] = String(opt_exception['message' + i]);
}
}
this.mainThread_.sendCommand(
this.logCommandId_,
[name, level.value, msg, exception]);
};
/** @override */
goog.gears.LoggerClient.prototype.disposeInternal = function() {
goog.gears.LoggerClient.superClass_.disposeInternal.call(this);
this.mainThread_ = null;
goog.gears.LoggerClient.instance_ = 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 This class lives on the main thread and takes care of incoming
* logger commands from a worker thread.
*
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.gears.LoggerServer');
goog.require('goog.Disposable');
goog.require('goog.debug.Logger');
goog.require('goog.debug.Logger.Level');
goog.require('goog.gears.Worker.EventType');
/**
* Creates an object that listens to incoming LOG commands and forwards them
* to a goog.debug.Logger
* @param {goog.gears.Worker} worker The worker thread that
* we are managing the loggers on.
* @param {number} logCommandId The command id used for logging.
* @param {string=} opt_workerName The name of the worker. If present then this
* is added to the log records and to exceptions as {@code workerName}.
* @constructor
* @extends {goog.Disposable}
*/
goog.gears.LoggerServer = function(worker, logCommandId, opt_workerName) {
goog.Disposable.call(this);
/**
* The command id to use to receive log commands from the workers.
* @type {number}
* @private
*/
this.logCommandId_ = logCommandId;
/**
* The worker thread object.
* @type {goog.gears.Worker}
* @private
*/
this.worker_ = worker;
/**
* The name of the worker.
* @type {string}
* @private
*/
this.workerName_ = opt_workerName || '';
/**
* Message prefix containing worker ID.
* @type {string}
* @private
*/
this.msgPrefix_ = '[' + worker.getId() + '] ';
// Listen for command's from the worker to handle the log command.
worker.addEventListener(goog.gears.Worker.EventType.COMMAND,
this.onCommand_, false, this);
};
goog.inherits(goog.gears.LoggerServer, goog.Disposable);
/**
* Whether to show the ID of the worker as a prefix to the shown message.
* @type {boolean}
* @private
*/
goog.gears.LoggerServer.prototype.useMessagePrefix_ = true;
/**
* @return {boolean} * Whether to show the ID of the worker as a prefix to the
* shown message.
*/
goog.gears.LoggerServer.prototype.getUseMessagePrefix = function() {
return this.useMessagePrefix_;
};
/**
* Whether to prefix the message text with the worker ID.
* @param {boolean} b True to prefix the messages.
*/
goog.gears.LoggerServer.prototype.setUseMessagePrefix = function(b) {
this.useMessagePrefix_ = b;
};
/**
* Event handler for the command event of the thread.
* @param {goog.gears.WorkerEvent} e The command event sent by the the
* worker thread.
* @private
*/
goog.gears.LoggerServer.prototype.onCommand_ = function(e) {
var message = /** @type {Array} */ (e.message);
var commandId = message[0];
if (commandId == this.logCommandId_) {
var params = message[1];
var i = 0;
var name = params[i++];
// The old version sent the level name as well. We no longer need it so
// we just step over it.
if (params.length == 5) {
i++;
}
var levelValue = params[i++];
var level = goog.debug.Logger.Level.getPredefinedLevelByValue(levelValue);
if (level) {
var msg = (this.useMessagePrefix_ ? this.msgPrefix_ : '') + params[i++];
var exception = params[i++];
var logger = goog.debug.Logger.getLogger(name);
var logRecord = logger.getLogRecord(level, msg, exception);
if (this.workerName_) {
logRecord.workerName = this.workerName_;
// Note that we happen to know that getLogRecord just references the
// exception object so we can continue to modify it as needed.
if (exception) {
exception.workerName = this.workerName_;
}
}
logger.logRecord(logRecord);
}
// ignore others for now
}
};
/** @override */
goog.gears.LoggerServer.prototype.disposeInternal = function() {
goog.gears.LoggerServer.superClass_.disposeInternal.call(this);
// Remove the event listener.
this.worker_.removeEventListener(
goog.gears.Worker.EventType.COMMAND, this.onCommand_, false, this);
this.worker_ = 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 Interface for capturing URLs to a ResourceStore on the
* LocalServer.
*
*/
goog.provide('goog.gears.UrlCapture');
goog.provide('goog.gears.UrlCapture.Event');
goog.provide('goog.gears.UrlCapture.EventType');
goog.require('goog.Uri');
goog.require('goog.debug.Logger');
goog.require('goog.events.Event');
goog.require('goog.events.EventTarget');
goog.require('goog.gears');
/**
* Class capture URLs to a ResourceStore on the LocalServer.
* @constructor
* @extends {goog.events.EventTarget}
* @param {string} name The name of the ResourceStore to capture the URLs to.
* @param {?string} requiredCookie A cookie that must be present for the
* managed store to be active. Should have the form "foo=bar".
* @param {GearsResourceStore=} opt_localServer The LocalServer for gears.
*/
goog.gears.UrlCapture = function(name, requiredCookie, opt_localServer) {
goog.events.EventTarget.call(this);
/**
* Name of resource store.
* @type {string}
* @private
*/
this.storeName_ = goog.gears.makeSafeFileName(name);
if (name != this.storeName_) {
this.logger_.info(
'local store name ' + name + '->' + this.storeName_);
}
/**
* A cookie that must be present for the store to be active.
* Should have the form "foo=bar". String cast is a safety measure since
* Gears behaves very badly when it gets an unexpected data type.
* @type {?string}
* @private
*/
this.requiredCookie_ = requiredCookie ? String(requiredCookie) : null;
/**
* The LocalServer for Gears.
* @type {GearsLocalServer}
* @private
*/
this.localServer_ = opt_localServer ||
goog.gears.getFactory().create('beta.localserver', '1.0');
/**
* Object mapping list of URIs to capture to capture id.
* @type {Object}
* @private
*/
this.uris_ = {};
/**
* Object mapping list of URIs that had errors in the capture to capture id.
* @type {Object}
* @private
*/
this.errorUris_ = {};
/**
* Object mapping number of URLs completed to capture id.
* @type {Object}
* @private
*/
this.numCompleted_ = {};
};
goog.inherits(goog.gears.UrlCapture, goog.events.EventTarget);
/**
* Logger.
* @type {goog.debug.Logger}
* @private
*/
goog.gears.UrlCapture.prototype.logger_ =
goog.debug.Logger.getLogger('goog.gears.UrlCapture');
/**
* The ResourceStore for gears, used to capture URLs.
* @type {GearsResourceStore}
* @private
*/
goog.gears.UrlCapture.prototype.resourceStore_ = null;
/**
* Events fired during URL capture
* @enum {string}
*/
goog.gears.UrlCapture.EventType = {
URL_SUCCESS: 'url_success',
URL_ERROR: 'url_error',
COMPLETE: 'complete',
ABORT: 'abort'
};
/**
* Lazy initializer for resource store.
* @return {GearsResourceStore} Gears resource store.
* @private
*/
goog.gears.UrlCapture.prototype.getResourceStore_ = function() {
if (!this.resourceStore_) {
this.logger_.info('creating resource store: ' + this.storeName_);
this.resourceStore_ = this.localServer_['createStore'](
this.storeName_, this.requiredCookie_);
}
return this.resourceStore_;
};
/**
* Determine if the UrlCapture has been created.
* @return {boolean} True if it has been created.
*/
goog.gears.UrlCapture.prototype.exists = function() {
if (!this.resourceStore_) {
this.logger_.info('opening resource store: ' + this.storeName_);
this.resourceStore_ = this.localServer_['openStore'](
this.storeName_, this.requiredCookie_);
}
return !!this.resourceStore_;
};
/**
* Remove this resource store.
*/
goog.gears.UrlCapture.prototype.removeStore = function() {
this.logger_.info('removing resource store: ' + this.storeName_);
this.localServer_['removeStore'](this.storeName_, this.requiredCookie_);
this.resourceStore_ = null;
};
/**
* Renames a Url that's been captured.
* @param {string|goog.Uri} srcUri The source Uri.
* @param {string|goog.Uri} dstUri The destination Uri.
*/
goog.gears.UrlCapture.prototype.rename = function(srcUri, dstUri) {
this.getResourceStore_()['rename'](srcUri.toString(), dstUri.toString());
};
/**
* Copies a Url that's been captured.
* @param {string|goog.Uri} srcUri The source Uri.
* @param {string|goog.Uri} dstUri The destination Uri.
*/
goog.gears.UrlCapture.prototype.copy = function(srcUri, dstUri) {
this.getResourceStore_()['copy'](srcUri.toString(), dstUri.toString());
};
/**
* Starts the capture of the given URLs. Returns immediately, and fires events
* on success and error.
* @param {Array.<string|goog.Uri>} uris URIs to capture.
* @return {number} The id of the ResourceStore capture. Can be used to
* abort, or identify events.
*/
goog.gears.UrlCapture.prototype.capture = function(uris) {
var count = uris.length;
this.logger_.fine('capture: count==' + count);
if (!count) {
throw Error('No URIs to capture');
}
// Convert goog.Uri objects to strings since Gears will throw an exception
// for non-strings.
var captureStrings = [];
for (var i = 0; i < count; i++) {
captureStrings.push(uris[i].toString());
}
var id = this.getResourceStore_()['capture'](
captureStrings, goog.bind(this.captureCallback_, this));
this.logger_.fine('capture started: ' + id);
this.uris_[id] = uris;
this.errorUris_[id] = [];
this.numCompleted_[id] = 0;
return id;
};
/**
* Aborts the capture with the given id. Dispatches abort event.
* @param {number} captureId The id of the capture to abort, from #capture.
*/
goog.gears.UrlCapture.prototype.abort = function(captureId) {
this.logger_.fine('abort: ' + captureId);
// TODO(user) Remove when Gears adds more rubust type handling.
// Safety measure since Gears behaves very badly if it gets an unexpected
// data type.
if (typeof captureId != 'number') {
throw Error('bad capture ID: ' + captureId);
}
// Only need to abort if the capture is still in progress.
if (this.uris_[captureId] || this.numCompleted_[captureId]) {
this.logger_.info('aborting capture: ' + captureId);
this.getResourceStore_()['abortCapture'](captureId);
this.cleanupCapture_(captureId);
this.dispatchEvent(new goog.gears.UrlCapture.Event(
goog.gears.UrlCapture.EventType.ABORT, captureId));
}
};
/**
* Checks if a URL is captured.
* @param {string|goog.Uri} uri The URL to check.
* @return {boolean} true if captured, false otherwise.
*/
goog.gears.UrlCapture.prototype.isCaptured = function(uri) {
this.logger_.fine('isCaptured: ' + uri);
return this.getResourceStore_()['isCaptured'](uri.toString());
};
/**
* Removes the given URI from the store.
* @param {string|goog.Uri} uri The URI to remove from the store.
*/
goog.gears.UrlCapture.prototype.remove = function(uri) {
this.logger_.fine('remove: ' + uri);
this.getResourceStore_()['remove'](uri.toString());
};
/**
* This is the callback passed into ResourceStore.capture. It gets called
* each time a URL is captured.
* @param {string} url The url from gears, always a string.
* @param {boolean} success True if capture succeeded, false otherwise.
* @param {number} captureId The id of the capture.
* @private
*/
goog.gears.UrlCapture.prototype.captureCallback_ = function(
url, success, captureId) {
this.logger_.fine('captureCallback_: ' + captureId);
if (!this.uris_[captureId] && !this.numCompleted_[captureId]) {
// This probably means we were aborted and then a capture event came in.
this.cleanupCapture_(captureId);
return;
}
// Dispatch success/error event for the URL
var eventUri = this.usesGoogUri_(captureId) ? new goog.Uri(url) : url;
var eventType = null;
if (success) {
eventType = goog.gears.UrlCapture.EventType.URL_SUCCESS;
} else {
eventType = goog.gears.UrlCapture.EventType.URL_ERROR;
this.errorUris_[captureId].push(eventUri);
}
this.dispatchEvent(new goog.gears.UrlCapture.Event(
eventType, captureId, eventUri));
// Dispatch complete event for the entire capture, if necessary
this.numCompleted_[captureId]++;
if (this.numCompleted_[captureId] == this.uris_[captureId].length) {
this.dispatchEvent(new goog.gears.UrlCapture.Event(
goog.gears.UrlCapture.EventType.COMPLETE, captureId, null,
this.errorUris_[captureId]));
this.cleanupCapture_(captureId);
}
};
/**
* Helper function to cleanup after a capture completes or is aborted.
* @private
* @param {number} captureId The id of the capture to clean up.
*/
goog.gears.UrlCapture.prototype.cleanupCapture_ = function(captureId) {
this.logger_.fine('cleanupCapture_: ' + captureId);
delete this.uris_[captureId];
delete this.numCompleted_[captureId];
delete this.errorUris_[captureId];
};
/**
* Helper function to check whether a certain capture is using URIs of type
* String or type goog.Uri
* @private
* @param {number} captureId The id of the capture to check.
* @return {boolean} True if the capture uses goog.Uri, false if it uses string
* or there are no URIs associated with the capture.
*/
goog.gears.UrlCapture.prototype.usesGoogUri_ = function(captureId) {
if (this.uris_[captureId] &&
this.uris_[captureId].length > 0 &&
this.uris_[captureId][0] instanceof goog.Uri) {
return true;
}
return false;
};
/**
* An event dispatched by UrlCapture
* @constructor
* @extends {goog.events.Event}
* @param {goog.gears.UrlCapture.EventType} type Type of event to dispatch.
* @param {number} captureId The id of the capture that fired this event.
* @param {string|goog.Uri=} opt_uri The URI for the event.
* @param {Array.<string|goog.Uri>=} opt_errorUris The URIs that failed to load
* correctly.
*/
goog.gears.UrlCapture.Event = function(type, captureId, opt_uri,
opt_errorUris) {
goog.events.Event.call(this, type);
/**
* The id of the capture to dispatch the event for. This id is returned from
* goog.gears.UrlCapture#capture
* @type {number}
*/
this.captureId = captureId;
/**
* The URI the event concerns. Valid for URL_SUCCESS and URL_ERROR events.
* @type {string|goog.Uri|null}
*/
this.uri = opt_uri || null;
/**
* A list of all the URIs that failed to load correctly. Valid for
* COMPLETE event.
* @type {Array.<string|goog.Uri>}
*/
this.errorUris = opt_errorUris || [];
};
goog.inherits(goog.gears.UrlCapture.Event, 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 Definition of the goog.ui.ItemEvent class.
*
*/
goog.provide('goog.ui.ItemEvent');
goog.require('goog.events.Event');
/**
* Generic ui event class for events that take a single item like a menu click
* event.
*
* @constructor
* @extends {goog.events.Event}
* @param {string} type Event Type.
* @param {Object} target Reference to the object that is the target
* of this event.
* @param {Object} item The item that was clicked.
*/
goog.ui.ItemEvent = function(type, target, item) {
goog.events.Event.call(this, type, target);
/**
* Item for the event. The type of this object is specific to the type
* of event. For a menu, it would be the menu item that was clicked. For a
* listbox selection, it would be the listitem that was selected.
*
* @type {Object}
*/
this.item = item;
};
goog.inherits(goog.ui.ItemEvent, goog.events.Event);
| 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 representing menu items that open a submenu.
* @see goog.ui.Menu
*
* @see ../demos/submenus.html
* @see ../demos/submenus2.html
*/
goog.provide('goog.ui.SubMenu');
goog.require('goog.Timer');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.events.KeyCodes');
goog.require('goog.positioning.AnchoredViewportPosition');
goog.require('goog.positioning.Corner');
goog.require('goog.style');
goog.require('goog.ui.Component');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.Component.State');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.Menu');
goog.require('goog.ui.MenuItem');
goog.require('goog.ui.SubMenuRenderer');
goog.require('goog.ui.registry');
/**
* Class representing a submenu that can be added as an item to other menus.
*
* @param {goog.ui.ControlContent} content Text caption or DOM structure to
* display as the content of the submenu (use to add icons or styling to
* menus).
* @param {*=} opt_model Data/model associated with the menu item.
* @param {goog.dom.DomHelper=} opt_domHelper Optional dom helper used for dom
* interactions.
* @param {goog.ui.MenuItemRenderer=} opt_renderer Renderer used to render or
* decorate the component; defaults to {@link goog.ui.SubMenuRenderer}.
* @constructor
* @extends {goog.ui.MenuItem}
*/
goog.ui.SubMenu = function(content, opt_model, opt_domHelper, opt_renderer) {
goog.ui.MenuItem.call(this, content, opt_model, opt_domHelper,
opt_renderer || goog.ui.SubMenuRenderer.getInstance());
};
goog.inherits(goog.ui.SubMenu, goog.ui.MenuItem);
/**
* The delay before opening the sub menu in milliseconds.
* @type {number}
*/
goog.ui.SubMenu.MENU_DELAY_MS = 218;
/**
* Timer used to dismiss the submenu when the item becomes unhighlighted.
* @type {?number}
* @private
*/
goog.ui.SubMenu.prototype.dismissTimer_ = null;
/**
* Timer used to show the submenu on mouseover.
* @type {?number}
* @private
*/
goog.ui.SubMenu.prototype.showTimer_ = null;
/**
* Flag used to determine if the submenu has control of the keyevents.
* @type {boolean}
* @private
*/
goog.ui.SubMenu.prototype.hasKeyboardControl_ = false;
/**
* The lazily created sub menu.
* @type {goog.ui.Menu?}
* @private
*/
goog.ui.SubMenu.prototype.subMenu_ = null;
/**
* Whether or not the sub-menu was set explicitly.
* @type {boolean}
* @private
*/
goog.ui.SubMenu.prototype.externalSubMenu_ = false;
/**
* Whether or not to align the submenu at the end of the parent menu.
* If true, the menu expands to the right in LTR languages and to the left
* in RTL langauges.
* @type {boolean}
* @private
*/
goog.ui.SubMenu.prototype.alignToEnd_ = true;
/**
* Whether the position of this submenu may be adjusted to fit
* the visible area, as in {@link goog.ui.Popup.positionAtCoordinate}.
* @type {boolean}
* @private
*/
goog.ui.SubMenu.prototype.isPositionAdjustable_ = false;
/** @override */
goog.ui.SubMenu.prototype.enterDocument = function() {
goog.ui.SubMenu.superClass_.enterDocument.call(this);
this.getHandler().listen(this.getParent(), goog.ui.Component.EventType.HIDE,
this.onParentHidden_);
if (this.subMenu_) {
this.setMenuListenersEnabled_(this.subMenu_, true);
}
};
/** @override */
goog.ui.SubMenu.prototype.exitDocument = function() {
this.getHandler().unlisten(this.getParent(), goog.ui.Component.EventType.HIDE,
this.onParentHidden_);
if (this.subMenu_) {
this.setMenuListenersEnabled_(this.subMenu_, false);
if (!this.externalSubMenu_) {
this.subMenu_.exitDocument();
goog.dom.removeNode(this.subMenu_.getElement());
}
}
goog.ui.SubMenu.superClass_.exitDocument.call(this);
};
/** @override */
goog.ui.SubMenu.prototype.disposeInternal = function() {
if (this.subMenu_ && !this.externalSubMenu_) {
this.subMenu_.dispose();
}
this.subMenu_ = null;
goog.ui.SubMenu.superClass_.disposeInternal.call(this);
};
/**
* @override
* Dismisses the submenu on a delay, with the result that the user needs less
* accuracy when moving to submenus. Alternate implementations could use
* geometry instead of a timer.
* @param {boolean} highlight Whether item should be highlighted.
* @param {boolean=} opt_btnPressed Whether the mouse button is held down.
*/
goog.ui.SubMenu.prototype.setHighlighted = function(highlight,
opt_btnPressed) {
goog.ui.SubMenu.superClass_.setHighlighted.call(this, highlight);
if (opt_btnPressed) {
this.getMenu().setMouseButtonPressed(true);
}
if (!highlight) {
if (this.dismissTimer_) {
goog.Timer.clear(this.dismissTimer_);
}
this.dismissTimer_ = goog.Timer.callOnce(
this.dismissSubMenu, goog.ui.SubMenu.MENU_DELAY_MS, this);
}
};
/**
* Show the submenu and ensure that all siblings are hidden.
*/
goog.ui.SubMenu.prototype.showSubMenu = function() {
// Only show the menu if this item is still selected. This is called on a
// timeout, so make sure our parent still exists.
var parent = this.getParent();
if (parent && parent.getHighlighted() == this) {
this.setSubMenuVisible_(true);
this.dismissSiblings_();
this.keyboardSetFocus_ = false;
}
};
/**
* Dismisses the menu and all further submenus.
*/
goog.ui.SubMenu.prototype.dismissSubMenu = function() {
// Because setHighlighted calls this function on a timeout, we need to make
// sure that the sub menu hasn't been disposed when we come back.
var subMenu = this.subMenu_;
if (subMenu && subMenu.getParent() == this) {
this.setSubMenuVisible_(false);
subMenu.forEachChild(function(child) {
if (typeof child.dismissSubMenu == 'function') {
child.dismissSubMenu();
}
});
}
};
/**
* Clears the show and hide timers for the sub menu.
*/
goog.ui.SubMenu.prototype.clearTimers = function() {
if (this.dismissTimer_) {
goog.Timer.clear(this.dismissTimer_);
}
if (this.showTimer_) {
goog.Timer.clear(this.showTimer_);
}
};
/**
* Sets the menu item to be visible or invisible.
* @param {boolean} visible Whether to show or hide the component.
* @param {boolean=} opt_force If true, doesn't check whether the component
* already has the requested visibility, and doesn't dispatch any events.
* @return {boolean} Whether the visibility was changed.
* @override
*/
goog.ui.SubMenu.prototype.setVisible = function(visible, opt_force) {
var visibilityChanged = goog.ui.SubMenu.superClass_.setVisible.call(this,
visible, opt_force);
// For menus that allow menu items to be hidden (i.e. ComboBox) ensure that
// the submenu is hidden.
if (visibilityChanged && !this.isVisible()) {
this.dismissSubMenu();
}
return visibilityChanged;
};
/**
* Dismiss all the sub menus of sibling menu items.
* @private
*/
goog.ui.SubMenu.prototype.dismissSiblings_ = function() {
this.getParent().forEachChild(function(child) {
if (child != this && typeof child.dismissSubMenu == 'function') {
child.dismissSubMenu();
child.clearTimers();
}
}, this);
};
/**
* Handles a key event that is passed to the menu item from its parent because
* it is highlighted. If the right key is pressed the sub menu takes control
* and delegates further key events to its menu until it is dismissed OR the
* left key is pressed.
* @param {goog.events.KeyEvent} e A key event.
* @return {boolean} Whether the event was handled.
* @override
*/
goog.ui.SubMenu.prototype.handleKeyEvent = function(e) {
var keyCode = e.keyCode;
var openKeyCode = this.isRightToLeft() ? goog.events.KeyCodes.LEFT :
goog.events.KeyCodes.RIGHT;
var closeKeyCode = this.isRightToLeft() ? goog.events.KeyCodes.RIGHT :
goog.events.KeyCodes.LEFT;
if (!this.hasKeyboardControl_) {
// Menu item doesn't have keyboard control and the right key was pressed.
// So open take keyboard control and open the sub menu.
if (this.isEnabled() &&
(keyCode == openKeyCode || keyCode == this.getMnemonic())) {
this.showSubMenu();
this.getMenu().highlightFirst();
this.clearTimers();
// The menu item doesn't currently care about the key events so let the
// parent menu handle them accordingly .
} else {
return false;
}
// Menu item has control, so let its menu try to handle the keys (this may
// in turn be handled by sub-sub menus).
} else if (this.getMenu().handleKeyEvent(e)) {
// Nothing to do
// The menu has control and the key hasn't yet been handled, on left arrow
// we turn off key control.
} else if (keyCode == closeKeyCode) {
this.dismissSubMenu();
} else {
// Submenu didn't handle the key so let the parent decide what to do.
return false;
}
e.preventDefault();
return true;
};
/**
* Listens to the sub menus items and ensures that this menu item is selected
* while dismissing the others. This handles the case when the user mouses
* over other items on their way to the sub menu.
* @param {goog.events.Event} e Highlight event to handle.
* @private
*/
goog.ui.SubMenu.prototype.onChildHighlight_ = function(e) {
if (this.subMenu_.getParent() == this) {
this.clearTimers();
this.getParentEventTarget().setHighlighted(this);
this.dismissSiblings_();
}
};
/**
* Listens to the parent menu's hide event and ensures that all submenus are
* hidden at the same time.
* @param {goog.events.Event} e The event.
* @private
*/
goog.ui.SubMenu.prototype.onParentHidden_ = function(e) {
// Ignore propagated events
if (e.target == this.getParentEventTarget()) {
// TODO(user): Using an event for this is expensive. Consider having a
// generalized interface that the parent menu calls on its children when
// it is hidden.
this.dismissSubMenu();
this.clearTimers();
}
};
/**
* @override
* Sets a timer to show the submenu and then dispatches an ENTER event to the
* parent menu.
* @param {goog.events.BrowserEvent} e Mouse event to handle.
* @protected
*/
goog.ui.SubMenu.prototype.handleMouseOver = function(e) {
if (this.isEnabled()) {
this.clearTimers();
this.showTimer_ = goog.Timer.callOnce(
this.showSubMenu, goog.ui.SubMenu.MENU_DELAY_MS, this);
}
goog.ui.SubMenu.superClass_.handleMouseOver.call(this, e);
};
/**
* Overrides the default mouseup event handler, so that the ACTION isn't
* dispatched for the submenu itself, instead the submenu is shown instantly.
* @param {goog.events.Event} e The browser event.
* @return {boolean} True if the action was allowed to proceed, false otherwise.
* @override
*/
goog.ui.SubMenu.prototype.performActionInternal = function(e) {
this.clearTimers();
var shouldHandleClick = this.isSupportedState(
goog.ui.Component.State.SELECTED);
if (shouldHandleClick) {
return goog.ui.SubMenu.superClass_.performActionInternal.call(this, e);
} else {
this.showSubMenu();
return true;
}
};
/**
* Sets the visiblility of the sub menu.
* @param {boolean} visible Whether to show menu.
* @private
*/
goog.ui.SubMenu.prototype.setSubMenuVisible_ = function(visible) {
// Dispatch OPEN event before calling getMenu(), so we can create the menu
// lazily on first access.
this.dispatchEvent(goog.ui.Component.getStateTransitionEvent(
goog.ui.Component.State.OPENED, visible));
var subMenu = this.getMenu();
if (visible != subMenu.isVisible()) {
if (visible) {
// Lazy-render menu when first shown, if needed.
if (!subMenu.isInDocument()) {
subMenu.render();
}
subMenu.setHighlightedIndex(-1);
}
this.hasKeyboardControl_ = visible;
goog.dom.classes.enable(this.getElement(),
goog.getCssName('goog-submenu-open'), visible);
subMenu.setVisible(visible);
// We must position after the menu is visible, otherwise positioning logic
// breaks in RTL.
if (visible) {
this.positionSubMenu();
}
}
};
/**
* Attaches or detaches menu event listeners to/from the given menu. Called
* each time a menu is attached to or detached from the submenu.
* @param {goog.ui.Menu} menu Menu on which to listen for events.
* @param {boolean} attach Whether to attach or detach event listeners.
* @private
*/
goog.ui.SubMenu.prototype.setMenuListenersEnabled_ = function(menu, attach) {
var handler = this.getHandler();
var method = attach ? handler.listen : handler.unlisten;
method.call(handler, menu, goog.ui.Component.EventType.HIGHLIGHT,
this.onChildHighlight_);
};
/**
* Sets whether the submenu is aligned at the end of the parent menu.
* @param {boolean} alignToEnd True to align to end, false to align to start.
*/
goog.ui.SubMenu.prototype.setAlignToEnd = function(alignToEnd) {
if (alignToEnd != this.alignToEnd_) {
this.alignToEnd_ = alignToEnd;
if (this.isInDocument()) {
// Completely re-render the widget.
var oldElement = this.getElement();
this.exitDocument();
if (oldElement.nextSibling) {
this.renderBefore(/** @type {!Element} */ (oldElement.nextSibling));
} else {
this.render(/** @type {Element} */ (oldElement.parentNode));
}
}
}
};
/**
* Determines whether the submenu is aligned at the end of the parent menu.
* @return {boolean} True if aligned to the end (the default), false if
* aligned to the start.
*/
goog.ui.SubMenu.prototype.isAlignedToEnd = function() {
return this.alignToEnd_;
};
/**
* Positions the submenu. This method should be called if the sub menu is
* opened and the menu element's size changes (e.g., when adding/removing items
* to an opened sub menu).
*/
goog.ui.SubMenu.prototype.positionSubMenu = function() {
var position = new goog.positioning.AnchoredViewportPosition(
this.getElement(), this.isAlignedToEnd() ?
goog.positioning.Corner.TOP_END : goog.positioning.Corner.TOP_START,
this.isPositionAdjustable_);
// TODO(user): Clean up popup code and have this be a one line call
var subMenu = this.getMenu();
var el = subMenu.getElement();
if (!subMenu.isVisible()) {
el.style.visibility = 'hidden';
goog.style.setElementShown(el, true);
}
position.reposition(
el, this.isAlignedToEnd() ?
goog.positioning.Corner.TOP_START : goog.positioning.Corner.TOP_END);
if (!subMenu.isVisible()) {
goog.style.setElementShown(el, false);
el.style.visibility = 'visible';
}
};
// Methods delegated to sub-menu but accessible here for convinience
/**
* Adds a new menu item at the end of the menu.
* @param {goog.ui.MenuHeader|goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu
* item to add to the menu.
*/
goog.ui.SubMenu.prototype.addItem = function(item) {
this.getMenu().addChild(item, true);
};
/**
* Adds a new menu item at a specific index in the menu.
* @param {goog.ui.MenuHeader|goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu
* item to add to the menu.
* @param {number} n Index at which to insert the menu item.
*/
goog.ui.SubMenu.prototype.addItemAt = function(item, n) {
this.getMenu().addChildAt(item, n, true);
};
/**
* Removes an item from the menu and disposes it.
* @param {goog.ui.MenuItem} item The menu item to remove.
*/
goog.ui.SubMenu.prototype.removeItem = function(item) {
var child = this.getMenu().removeChild(item, true);
if (child) {
child.dispose();
}
};
/**
* Removes a menu item at a given index in the menu and disposes it.
* @param {number} n Index of item.
*/
goog.ui.SubMenu.prototype.removeItemAt = function(n) {
var child = this.getMenu().removeChildAt(n, true);
if (child) {
child.dispose();
}
};
/**
* Returns a reference to the menu item at a given index.
* @param {number} n Index of menu item.
* @return {goog.ui.Component} Reference to the menu item.
*/
goog.ui.SubMenu.prototype.getItemAt = function(n) {
return this.getMenu().getChildAt(n);
};
/**
* Returns the number of items in the sub menu (including separators).
* @return {number} The number of items in the menu.
*/
goog.ui.SubMenu.prototype.getItemCount = function() {
return this.getMenu().getChildCount();
};
/**
* Returns the menu items contained in the sub menu.
* @return {Array.<goog.ui.MenuItem>} An array of menu items.
* @deprecated Use getItemAt/getItemCount instead.
*/
goog.ui.SubMenu.prototype.getItems = function() {
return this.getMenu().getItems();
};
/**
* Gets a reference to the submenu's actual menu.
* @return {goog.ui.Menu} Reference to the object representing the sub menu.
*/
goog.ui.SubMenu.prototype.getMenu = function() {
if (!this.subMenu_) {
this.setMenu(
new goog.ui.Menu(this.getDomHelper()), /* opt_internal */ true);
} else if (this.externalSubMenu_ && this.subMenu_.getParent() != this) {
// Since it is possible for the same popup menu to be attached to multiple
// submenus, we need to ensure that it has the correct parent event target.
this.subMenu_.setParent(this);
}
// Always create the menu DOM, for backward compatibility.
if (!this.subMenu_.getElement()) {
this.subMenu_.createDom();
}
return this.subMenu_;
};
/**
* Sets the submenu to a specific menu.
* @param {goog.ui.Menu} menu The menu to show when this item is selected.
* @param {boolean=} opt_internal Whether this menu is an "internal" menu, and
* should be disposed of when this object is disposed of.
*/
goog.ui.SubMenu.prototype.setMenu = function(menu, opt_internal) {
var oldMenu = this.subMenu_;
if (menu != oldMenu) {
if (oldMenu) {
this.dismissSubMenu();
if (this.isInDocument()) {
this.setMenuListenersEnabled_(oldMenu, false);
}
}
this.subMenu_ = menu;
this.externalSubMenu_ = !opt_internal;
if (menu) {
menu.setParent(this);
// There's no need to dispatch a HIDE event during submenu construction.
menu.setVisible(false, /* opt_force */ true);
menu.setAllowAutoFocus(false);
menu.setFocusable(false);
if (this.isInDocument()) {
this.setMenuListenersEnabled_(menu, true);
}
}
}
};
/**
* Returns true if the provided element is to be considered inside the menu for
* purposes such as dismissing the menu on an event. This is so submenus can
* make use of elements outside their own DOM.
* @param {Element} element The element to test for.
* @return {boolean} Whether or not the provided element is contained.
*/
goog.ui.SubMenu.prototype.containsElement = function(element) {
return this.getMenu().containsElement(element);
};
/**
* @param {boolean} isAdjustable Whether this submenu is adjustable.
*/
goog.ui.SubMenu.prototype.setPositionAdjustable = function(isAdjustable) {
this.isPositionAdjustable_ = !!isAdjustable;
};
/**
* @return {boolean} Whether this submenu is adjustable.
*/
goog.ui.SubMenu.prototype.isPositionAdjustable = function() {
return this.isPositionAdjustable_;
};
// Register a decorator factory function for goog.ui.SubMenus.
goog.ui.registry.setDecoratorByClassName(goog.getCssName('goog-submenu'),
function() {
return new goog.ui.SubMenu(null);
});
| 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 select control.
*
* @author attila@google.com (Attila Bodis)
* @author ssaviano@google.com (Steven Saviano)
*/
goog.provide('goog.ui.ToolbarSelect');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.Select');
goog.require('goog.ui.ToolbarMenuButtonRenderer');
goog.require('goog.ui.registry');
/**
* A select control for a toolbar.
*
* @param {goog.ui.ControlContent} caption Default caption or existing DOM
* structure to display as the button's caption when nothing is selected.
* @param {goog.ui.Menu=} opt_menu Menu containing selection options.
* @param {goog.ui.MenuButtonRenderer=} opt_renderer Renderer used to
* render or decorate the control; defaults to
* {@link goog.ui.ToolbarMenuButtonRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
* document interaction.
* @constructor
* @extends {goog.ui.Select}
*/
goog.ui.ToolbarSelect = function(
caption, opt_menu, opt_renderer, opt_domHelper) {
goog.ui.Select.call(this, caption, opt_menu, opt_renderer ||
goog.ui.ToolbarMenuButtonRenderer.getInstance(), opt_domHelper);
};
goog.inherits(goog.ui.ToolbarSelect, goog.ui.Select);
// Registers a decorator factory function for select controls used in toolbars.
goog.ui.registry.setDecoratorByClassName(goog.getCssName('goog-toolbar-select'),
function() {
return new goog.ui.ToolbarSelect(null);
});
| 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 HSVA (hue/saturation/value/alpha) color palette/picker
* implementation.
* Without the styles from the demo css file, only a hex color label and input
* field show up.
*
* @see ../demos/hsvapalette.html
*/
goog.provide('goog.ui.HsvaPalette');
goog.require('goog.array');
goog.require('goog.color');
goog.require('goog.color.alpha');
goog.require('goog.events.EventType');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.HsvPalette');
/**
* Creates an HSVA palette. Allows a user to select the hue, saturation,
* value/brightness and alpha/opacity.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @param {string=} opt_color Optional initial color, without alpha (default is
* red).
* @param {number=} opt_alpha Optional initial alpha (default is 1).
* @param {string=} opt_class Optional base for creating classnames (default is
* 'goog-hsva-palette').
* @extends {goog.ui.HsvPalette}
* @constructor
*/
goog.ui.HsvaPalette = function(opt_domHelper, opt_color, opt_alpha, opt_class) {
goog.base(this, opt_domHelper, opt_color, opt_class);
/**
* Alpha transparency of the currently selected color, in [0, 1]. When
* undefined, the palette will behave as a non-transparent HSV palette,
* assuming full opacity.
* @type {number}
* @private
*/
this.alpha_ = goog.isDef(opt_alpha) ? opt_alpha : 1;
/**
* @override
*/
this.className = opt_class || goog.getCssName('goog-hsva-palette');
/**
* The document which is being listened to.
* type {HTMLDocument}
* @private
*/
this.document_ = opt_domHelper ? opt_domHelper.getDocument() :
goog.dom.getDomHelper().getDocument();
};
goog.inherits(goog.ui.HsvaPalette, goog.ui.HsvPalette);
/**
* DOM element representing the alpha background image.
* @type {Element}
* @private
*/
goog.ui.HsvaPalette.prototype.aImageEl_;
/**
* DOM element representing the alpha handle.
* @type {Element}
* @private
*/
goog.ui.HsvaPalette.prototype.aHandleEl_;
/**
* DOM element representing the swatch backdrop image.
* @type {Element}
* @private
*/
goog.ui.HsvaPalette.prototype.swatchBackdropEl_;
/** @override */
goog.ui.HsvaPalette.prototype.getAlpha = function() {
return this.alpha_;
};
/**
* Sets which color is selected and update the UI. The passed color should be
* in #rrggbb format. The alpha value will be set to 1.
* @param {number} alpha The selected alpha value, in [0, 1].
*/
goog.ui.HsvaPalette.prototype.setAlpha = function(alpha) {
this.setColorAlphaHelper_(this.color_, alpha);
};
/**
* Sets which color is selected and update the UI. The passed color should be
* in #rrggbb format. The alpha value will be set to 1.
* @param {string} color The selected color.
* @override
*/
goog.ui.HsvaPalette.prototype.setColor = function(color) {
this.setColorAlphaHelper_(color, 1);
};
/**
* Gets the color that is currently selected in this color picker, in #rrggbbaa
* format.
* @return {string} The string of the selected color with alpha.
*/
goog.ui.HsvaPalette.prototype.getColorRgbaHex = function() {
var alphaHex = Math.floor(this.alpha_ * 255).toString(16);
return this.color_ + (alphaHex.length == 1 ? '0' + alphaHex : alphaHex);
};
/**
* Sets which color is selected and update the UI. The passed color should be
* in #rrggbbaa format. The alpha value will be set to 1.
* @param {string} color The selected color with alpha.
*/
goog.ui.HsvaPalette.prototype.setColorRgbaHex = function(color) {
var parsed = goog.ui.HsvaPalette.parseColorRgbaHex_(color);
this.setColorAlphaHelper_(parsed[0], parsed[1]);
};
/**
* Sets which color and alpha value are selected and update the UI. The passed
* color should be in #rrggbb format.
* @param {string} color The selected color in #rrggbb format.
* @param {number} alpha The selected alpha value, in [0, 1].
* @private
*/
goog.ui.HsvaPalette.prototype.setColorAlphaHelper_ = function(color, alpha) {
var colorChange = this.color_ != color;
var alphaChange = this.alpha_ != alpha;
this.alpha_ = alpha;
this.color_ = color;
if (colorChange) {
// This is to prevent multiple event dispatches.
goog.ui.HsvaPalette.superClass_.setColor_.call(this, color);
}
if (colorChange || alphaChange) {
this.updateUi();
this.dispatchEvent(goog.ui.Component.EventType.ACTION);
}
};
/** @override */
goog.ui.HsvaPalette.prototype.createDom = function() {
goog.ui.HsvaPalette.superClass_.createDom.call(this);
var dom = this.getDomHelper();
this.aImageEl_ = dom.createDom(
goog.dom.TagName.DIV, goog.getCssName(this.className, 'a-image'));
this.aHandleEl_ = dom.createDom(
goog.dom.TagName.DIV, goog.getCssName(this.className, 'a-handle'));
this.swatchBackdropEl_ = dom.createDom(
goog.dom.TagName.DIV, goog.getCssName(this.className, 'swatch-backdrop'));
dom.appendChild(this.element_, this.aImageEl_);
dom.appendChild(this.element_, this.aHandleEl_);
dom.appendChild(this.element_, this.swatchBackdropEl_);
};
/** @override */
goog.ui.HsvaPalette.prototype.disposeInternal = function() {
goog.ui.HsvaPalette.superClass_.disposeInternal.call(this);
delete this.aImageEl_;
delete this.aHandleEl_;
delete this.swatchBackdropEl_;
};
/** @override */
goog.ui.HsvaPalette.prototype.updateUi = function() {
goog.base(this, 'updateUi');
if (this.isInDocument()) {
var a = this.alpha_ * 255;
var top = this.aImageEl_.offsetTop -
Math.floor(this.aHandleEl_.offsetHeight / 2) +
this.aImageEl_.offsetHeight * ((255 - a) / 255);
this.aHandleEl_.style.top = top + 'px';
this.aImageEl_.style.backgroundColor = this.color_;
goog.style.setOpacity(this.swatchElement, a / 255);
}
};
/** @override */
goog.ui.HsvaPalette.prototype.updateInput = function() {
if (!goog.array.equals([this.color_, this.alpha_],
goog.ui.HsvaPalette.parseUserInput_(this.inputElement.value))) {
this.inputElement.value = this.getColorRgbaHex();
}
};
/** @override */
goog.ui.HsvaPalette.prototype.handleMouseDown = function(e) {
goog.base(this, 'handleMouseDown', e);
if (e.target == this.aImageEl_ || e.target == this.aHandleEl_) {
// Setup value change listeners
var b = goog.style.getBounds(this.valueBackgroundImageElement);
this.handleMouseMoveA_(b, e);
this.mouseMoveListener_ = goog.events.listen(this.document_,
goog.events.EventType.MOUSEMOVE,
goog.bind(this.handleMouseMoveA_, this, b));
this.mouseUpListener_ = goog.events.listen(this.document_,
goog.events.EventType.MOUSEUP, this.handleMouseUp, false, this);
}
};
/**
* Handles mousemove events on the document once a drag operation on the alpha
* slider has started.
* @param {goog.math.Rect} b Boundaries of the value slider object at the start
* of the drag operation.
* @param {goog.events.Event} e Event object.
* @private
*/
goog.ui.HsvaPalette.prototype.handleMouseMoveA_ = function(b, e) {
e.preventDefault();
var vportPos = this.getDomHelper().getDocumentScroll();
var newA = (b.top + b.height - Math.min(
Math.max(vportPos.y + e.clientY, b.top),
b.top + b.height)) / b.height;
this.setAlpha(newA);
};
/** @override */
goog.ui.HsvaPalette.prototype.handleInput = function(e) {
var parsed = goog.ui.HsvaPalette.parseUserInput_(this.inputElement.value);
if (parsed) {
this.setColorAlphaHelper_(parsed[0], parsed[1]);
}
};
/**
* Parses an #rrggbb or #rrggbbaa color string.
* @param {string} value User-entered color value.
* @return {Array} A two element array [color, alpha], where color is #rrggbb
* and alpha is in [0, 1]. Null if the argument was invalid.
* @private
*/
goog.ui.HsvaPalette.parseUserInput_ = function(value) {
if (/^#[0-9a-f]{8}$/i.test(value)) {
return goog.ui.HsvaPalette.parseColorRgbaHex_(value);
} else if (/^#[0-9a-f]{6}$/i.test(value)) {
return [value, 1];
}
return null;
};
/**
* Parses a #rrggbbaa color string.
* @param {string} color The color and alpha in #rrggbbaa format.
* @return {Array} A two element array [color, alpha], where color is #rrggbb
* and alpha is in [0, 1].
* @private
*/
goog.ui.HsvaPalette.parseColorRgbaHex_ = function(color) {
var hex = goog.color.alpha.parse(color).hex;
return [
goog.color.alpha.extractHexColor(hex),
parseInt(goog.color.alpha.extractAlpha(hex), 16) / 255
];
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Component for generating chart PNGs using Google Chart Server.
*
* @see ../demos/serverchart.html
*/
/**
* Namespace for chart functions
*/
goog.provide('goog.ui.ServerChart');
goog.provide('goog.ui.ServerChart.AxisDisplayType');
goog.provide('goog.ui.ServerChart.ChartType');
goog.provide('goog.ui.ServerChart.EncodingType');
goog.provide('goog.ui.ServerChart.Event');
goog.provide('goog.ui.ServerChart.LegendPosition');
goog.provide('goog.ui.ServerChart.MaximumValue');
goog.provide('goog.ui.ServerChart.MultiAxisAlignment');
goog.provide('goog.ui.ServerChart.MultiAxisType');
goog.provide('goog.ui.ServerChart.UriParam');
goog.provide('goog.ui.ServerChart.UriTooLongEvent');
goog.require('goog.Uri');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.events.Event');
goog.require('goog.string');
goog.require('goog.ui.Component');
/**
* Will construct a chart using Google's chartserver.
*
* @param {goog.ui.ServerChart.ChartType} type The chart type.
* @param {number=} opt_width The width of the chart.
* @param {number=} opt_height The height of the chart.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM Helper.
* @param {string=} opt_uri Optional uri used to connect to the chart server, if
* different than goog.ui.ServerChart.CHART_SERVER_SCHEME_INDEPENDENT_URI.
* @constructor
* @extends {goog.ui.Component}
*/
goog.ui.ServerChart = function(type, opt_width, opt_height, opt_domHelper,
opt_uri) {
goog.ui.Component.call(this, opt_domHelper);
/**
* Image URI.
* @type {goog.Uri}
* @private
*/
this.uri_ = new goog.Uri(
opt_uri || goog.ui.ServerChart.CHART_SERVER_SCHEME_INDEPENDENT_URI);
/**
* Encoding method for the URI data format.
* @type {goog.ui.ServerChart.EncodingType}
* @private
*/
this.encodingType_ = goog.ui.ServerChart.EncodingType.AUTOMATIC;
/**
* Two-dimensional array of the data sets on the chart.
* @type {Array.<Array.<number>>}
* @private
*/
this.dataSets_ = [];
/**
* Colors for each data set.
* @type {Array.<string>}
* @private
*/
this.setColors_ = [];
/**
* Legend texts for each data set.
* @type {Array.<string>}
* @private
*/
this.setLegendTexts_ = [];
/**
* Labels on the X-axis.
* @type {Array.<string>}
* @private
*/
this.xLabels_ = [];
/**
* Labels on the left along the Y-axis.
* @type {Array.<string>}
* @private
*/
this.leftLabels_ = [];
/**
* Labels on the right along the Y-axis.
* @type {Array.<string>}
* @private
*/
this.rightLabels_ = [];
/**
* Axis type for each multi-axis in the chart. The indices into this array
* also work as the reference index for all other multi-axis properties.
* @type {Array.<goog.ui.ServerChart.MultiAxisType>}
* @private
*/
this.multiAxisType_ = [];
/**
* Axis text for each multi-axis in the chart, indexed by the indices from
* multiAxisType_ in a sparse array.
* @type {Object}
* @private
*/
this.multiAxisLabelText_ = {};
/**
* Axis position for each multi-axis in the chart, indexed by the indices
* from multiAxisType_ in a sparse array.
* @type {Object}
* @private
*/
this.multiAxisLabelPosition_ = {};
/**
* Axis range for each multi-axis in the chart, indexed by the indices from
* multiAxisType_ in a sparse array.
* @type {Object}
* @private
*/
this.multiAxisRange_ = {};
/**
* Axis style for each multi-axis in the chart, indexed by the indices from
* multiAxisType_ in a sparse array.
* @type {Object}
* @private
*/
this.multiAxisLabelStyle_ = {};
this.setType(type);
this.setSize(opt_width, opt_height);
/**
* Minimum value for the chart (used for normalization). By default,
* this is set to infinity, and is eventually updated to the lowest given
* value in the data. The minimum value is then subtracted from all other
* values. For a pie chart, subtracting the minimum value does not make
* sense, so minValue_ is set to zero because 0 is the additive identity.
* @type {number}
* @private
*/
this.minValue_ = this.isPieChart() ? 0 : Infinity;
};
goog.inherits(goog.ui.ServerChart, goog.ui.Component);
/**
* Base scheme-independent URI for the chart renderer.
* @type {string}
*/
goog.ui.ServerChart.CHART_SERVER_SCHEME_INDEPENDENT_URI =
'//chart.googleapis.com/chart';
/**
* Base HTTP URI for the chart renderer.
* @type {string}
*/
goog.ui.ServerChart.CHART_SERVER_HTTP_URI =
'http://chart.googleapis.com/chart';
/**
* Base HTTPS URI for the chart renderer.
* @type {string}
*/
goog.ui.ServerChart.CHART_SERVER_HTTPS_URI =
'https://chart.googleapis.com/chart';
/**
* Base URI for the chart renderer.
* @type {string}
* @deprecated Use
* {@link goog.ui.ServerChart.CHART_SERVER_SCHEME_INDEPENDENT_URI},
* {@link goog.ui.ServerChart.CHART_SERVER_HTTP_URI} or
* {@link goog.ui.ServerChart.CHART_SERVER_HTTPS_URI} instead.
*/
goog.ui.ServerChart.CHART_SERVER_URI =
goog.ui.ServerChart.CHART_SERVER_HTTP_URI;
/**
* The 0 - 1.0 ("fraction of the range") value to use when getMinValue() ==
* getMaxValue(). This determines, for example, the vertical position
* of the line in a flat line-chart.
* @type {number}
*/
goog.ui.ServerChart.DEFAULT_NORMALIZATION = 0.5;
/**
* The upper limit on the length of the chart image URI, after encoding.
* If the URI's length equals or exceeds it, goog.ui.ServerChart.UriTooLongEvent
* is dispatched on the goog.ui.ServerChart object.
* @type {number}
* @private
*/
goog.ui.ServerChart.prototype.uriLengthLimit_ = 2048;
/**
* Number of gridlines along the X-axis.
* @type {number}
* @private
*/
goog.ui.ServerChart.prototype.gridX_ = 0;
/**
* Number of gridlines along the Y-axis.
* @type {number}
* @private
*/
goog.ui.ServerChart.prototype.gridY_ = 0;
/**
* Maximum value for the chart (used for normalization). The minimum is
* declared in the constructor.
* @type {number}
* @private
*/
goog.ui.ServerChart.prototype.maxValue_ = -Infinity;
/**
* Chart title.
* @type {?string}
* @private
*/
goog.ui.ServerChart.prototype.title_ = null;
/**
* Chart title size.
* @type {number}
* @private
*/
goog.ui.ServerChart.prototype.titleSize_ = 13.5;
/**
* Chart title color.
* @type {string}
* @private
*/
goog.ui.ServerChart.prototype.titleColor_ = '333333';
/**
* Chart legend.
* @type {Array.<string>?}
* @private
*/
goog.ui.ServerChart.prototype.legend_ = null;
/**
* ChartServer supports using data sets to position markers. A data set
* that is being used for positioning only can be made "invisible", in other
* words, the caller can indicate to ChartServer that ordinary chart elements
* (e.g. bars in a bar chart) should not be drawn on the data points of the
* invisible data set. Such data sets must be provided at the end of the
* chd parameter, and if invisible data sets are being used, the chd
* parameter must indicate the number of visible data sets.
* @type {?number}
* @private
*/
goog.ui.ServerChart.prototype.numVisibleDataSets_ = null;
/**
* Creates the DOM node (image) needed for the Chart
* @override
*/
goog.ui.ServerChart.prototype.createDom = function() {
var size = this.getSize();
this.setElementInternal(this.getDomHelper().createDom(
'img', {'src': this.getUri(),
'class': goog.getCssName('goog-serverchart-image'),
'width': size[0], 'height': size[1]}));
};
/**
* Decorate an image already in the DOM.
* Expects the following structure:
* <pre>
* - img
* </pre>
*
* @param {Element} img Image to decorate.
* @override
*/
goog.ui.ServerChart.prototype.decorateInternal = function(img) {
img.src = this.getUri();
this.setElementInternal(img);
};
/**
* Updates the image if any of the data or settings have changed.
*/
goog.ui.ServerChart.prototype.updateChart = function() {
if (this.getElement()) {
this.getElement().src = this.getUri();
}
};
/**
* Sets the URI of the chart.
*
* @param {goog.Uri} uri The chart URI.
*/
goog.ui.ServerChart.prototype.setUri = function(uri) {
this.uri_ = uri;
};
/**
* Returns the URI of the chart.
*
* @return {goog.Uri} The chart URI.
*/
goog.ui.ServerChart.prototype.getUri = function() {
this.computeDataString_();
return this.uri_;
};
/**
* Returns the upper limit on the length of the chart image URI, after encoding.
* If the URI's length equals or exceeds it, goog.ui.ServerChart.UriTooLongEvent
* is dispatched on the goog.ui.ServerChart object.
*
* @return {number} The chart URI length limit.
*/
goog.ui.ServerChart.prototype.getUriLengthLimit = function() {
return this.uriLengthLimit_;
};
/**
* Sets the upper limit on the length of the chart image URI, after encoding.
* If the URI's length equals or exceeds it, goog.ui.ServerChart.UriTooLongEvent
* is dispatched on the goog.ui.ServerChart object.
*
* @param {number} uriLengthLimit The chart URI length limit.
*/
goog.ui.ServerChart.prototype.setUriLengthLimit = function(uriLengthLimit) {
this.uriLengthLimit_ = uriLengthLimit;
};
/**
* Sets the 'chg' parameter of the chart Uri.
* This is used by various types of charts to specify Grids.
*
* @param {string} value Value for the 'chg' parameter in the chart Uri.
*/
goog.ui.ServerChart.prototype.setGridParameter = function(value) {
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.GRID, value);
};
/**
* Returns the 'chg' parameter of the chart Uri.
* This is used by various types of charts to specify Grids.
*
* @return {string|undefined} The 'chg' parameter of the chart Uri.
*/
goog.ui.ServerChart.prototype.getGridParameter = function() {
return /** @type {string} */ (
this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.GRID));
};
/**
* Sets the 'chm' parameter of the chart Uri.
* This is used by various types of charts to specify Markers.
*
* @param {string} value Value for the 'chm' parameter in the chart Uri.
*/
goog.ui.ServerChart.prototype.setMarkerParameter = function(value) {
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.MARKERS, value);
};
/**
* Returns the 'chm' parameter of the chart Uri.
* This is used by various types of charts to specify Markers.
*
* @return {string|undefined} The 'chm' parameter of the chart Uri.
*/
goog.ui.ServerChart.prototype.getMarkerParameter = function() {
return /** @type {string} */ (
this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.MARKERS));
};
/**
* Sets the 'chp' parameter of the chart Uri.
* This is used by various types of charts to specify certain options.
* e.g., finance charts use this to designate which line is the 0 axis.
*
* @param {string|number} value Value for the 'chp' parameter in the chart Uri.
*/
goog.ui.ServerChart.prototype.setMiscParameter = function(value) {
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.MISC_PARAMS,
String(value));
};
/**
* Returns the 'chp' parameter of the chart Uri.
* This is used by various types of charts to specify certain options.
* e.g., finance charts use this to designate which line is the 0 axis.
*
* @return {string|undefined} The 'chp' parameter of the chart Uri.
*/
goog.ui.ServerChart.prototype.getMiscParameter = function() {
return /** @type {string} */ (
this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.MISC_PARAMS));
};
/**
* Enum of chart data encoding types
*
* @enum {string}
*/
goog.ui.ServerChart.EncodingType = {
AUTOMATIC: '',
EXTENDED: 'e',
SIMPLE: 's',
TEXT: 't'
};
/**
* Enum of chart types with their short names used by the chartserver.
*
* @enum {string}
*/
goog.ui.ServerChart.ChartType = {
BAR: 'br',
CLOCK: 'cf',
CONCENTRIC_PIE: 'pc',
FILLEDLINE: 'lr',
FINANCE: 'lfi',
GOOGLEOMETER: 'gom',
HORIZONTAL_GROUPED_BAR: 'bhg',
HORIZONTAL_STACKED_BAR: 'bhs',
LINE: 'lc',
MAP: 't',
MAPUSA: 'tuss',
MAPWORLD: 'twoc',
PIE: 'p',
PIE3D: 'p3',
RADAR: 'rs',
SCATTER: 's',
SPARKLINE: 'ls',
VENN: 'v',
VERTICAL_GROUPED_BAR: 'bvg',
VERTICAL_STACKED_BAR: 'bvs',
XYLINE: 'lxy'
};
/**
* Enum of multi-axis types.
*
* @enum {string}
*/
goog.ui.ServerChart.MultiAxisType = {
X_AXIS: 'x',
LEFT_Y_AXIS: 'y',
RIGHT_Y_AXIS: 'r',
TOP_AXIS: 't'
};
/**
* Enum of multi-axis alignments.
*
* @enum {number}
*/
goog.ui.ServerChart.MultiAxisAlignment = {
ALIGN_LEFT: -1,
ALIGN_CENTER: 0,
ALIGN_RIGHT: 1
};
/**
* Enum of legend positions.
*
* @enum {string}
*/
goog.ui.ServerChart.LegendPosition = {
TOP: 't',
BOTTOM: 'b',
LEFT: 'l',
RIGHT: 'r'
};
/**
* Enum of line and tick options for an axis.
*
* @enum {string}
*/
goog.ui.ServerChart.AxisDisplayType = {
LINE_AND_TICKS: 'lt',
LINE: 'l',
TICKS: 't'
};
/**
* Enum of chart maximum values in pixels, as listed at:
* http://code.google.com/apis/chart/basics.html
*
* @enum {number}
*/
goog.ui.ServerChart.MaximumValue = {
WIDTH: 1000,
HEIGHT: 1000,
MAP_WIDTH: 440,
MAP_HEIGHT: 220,
TOTAL_AREA: 300000
};
/**
* Enum of ChartServer URI parameters.
*
* @enum {string}
*/
goog.ui.ServerChart.UriParam = {
BACKGROUND_FILL: 'chf',
BAR_HEIGHT: 'chbh',
DATA: 'chd',
DATA_COLORS: 'chco',
DATA_LABELS: 'chld',
DATA_SCALING: 'chds',
DIGITAL_SIGNATURE: 'sig',
GEOGRAPHICAL_REGION: 'chtm',
GRID: 'chg',
LABEL_COLORS: 'chlc',
LEFT_Y_LABELS: 'chly',
LEGEND: 'chdl',
LEGEND_POSITION: 'chdlp',
LEGEND_TEXTS: 'chdl',
LINE_STYLES: 'chls',
MARGINS: 'chma',
MARKERS: 'chm',
MISC_PARAMS: 'chp',
MULTI_AXIS_LABEL_POSITION: 'chxp',
MULTI_AXIS_LABEL_TEXT: 'chxl',
MULTI_AXIS_RANGE: 'chxr',
MULTI_AXIS_STYLE: 'chxs',
MULTI_AXIS_TYPES: 'chxt',
RIGHT_LABELS: 'chlr',
RIGHT_LABEL_POSITIONS: 'chlrp',
SIZE: 'chs',
TITLE: 'chtt',
TITLE_FORMAT: 'chts',
TYPE: 'cht',
X_AXIS_STYLE: 'chx',
X_LABELS: 'chl'
};
/**
* Sets the background fill.
*
* @param {Array.<Object>} fill An array of background fill specification
* objects. Each object may have the following properties:
* {string} area The area to fill, either 'bg' for background or 'c' for
* chart area. The default is 'bg'.
* {string} color (required) The color of the background fill.
* // TODO(user): Add support for gradient/stripes, which requires
* // a different object structure.
*/
goog.ui.ServerChart.prototype.setBackgroundFill = function(fill) {
var value = [];
goog.array.forEach(fill, function(spec) {
spec.area = spec.area || 'bg';
spec.effect = spec.effect || 's';
value.push([spec.area, spec.effect, spec.color].join(','));
});
value = value.join('|');
this.setParameterValue(goog.ui.ServerChart.UriParam.BACKGROUND_FILL, value);
};
/**
* Returns the background fill.
*
* @return {Array.<Object>} An array of background fill specifications.
* If the fill specification string is in an unsupported format, the method
* returns an empty array.
*/
goog.ui.ServerChart.prototype.getBackgroundFill = function() {
var value =
this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.BACKGROUND_FILL);
var result = [];
if (goog.isDefAndNotNull(value)) {
var fillSpecifications = value.split('|');
var valid = true;
goog.array.forEach(fillSpecifications, function(spec) {
var parts = spec.split(',');
if (valid && parts[1] == 's') {
result.push({area: parts[0], effect: parts[1], color: parts[2]});
} else {
// If the format is unsupported, return an empty array.
result = [];
valid = false;
}
});
}
return result;
};
/**
* Sets the encoding type.
*
* @param {goog.ui.ServerChart.EncodingType} type Desired data encoding type.
*/
goog.ui.ServerChart.prototype.setEncodingType = function(type) {
this.encodingType_ = type;
};
/**
* Gets the encoding type.
*
* @return {goog.ui.ServerChart.EncodingType} The encoding type.
*/
goog.ui.ServerChart.prototype.getEncodingType = function() {
return this.encodingType_;
};
/**
* Sets the chart type.
*
* @param {goog.ui.ServerChart.ChartType} type The desired chart type.
*/
goog.ui.ServerChart.prototype.setType = function(type) {
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.TYPE, type);
};
/**
* Returns the chart type.
*
* @return {goog.ui.ServerChart.ChartType} The chart type.
*/
goog.ui.ServerChart.prototype.getType = function() {
return /** @type {goog.ui.ServerChart.ChartType} */ (
this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.TYPE));
};
/**
* Sets the chart size.
*
* @param {number=} opt_width Optional chart width, defaults to 300.
* @param {number=} opt_height Optional chart height, defaults to 150.
*/
goog.ui.ServerChart.prototype.setSize = function(opt_width, opt_height) {
var sizeString = [opt_width || 300, opt_height || 150].join('x');
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.SIZE, sizeString);
};
/**
* Returns the chart size.
*
* @return {Array.<string>} [Width, Height].
*/
goog.ui.ServerChart.prototype.getSize = function() {
var sizeStr = this.uri_.getParameterValue(goog.ui.ServerChart.UriParam.SIZE);
return sizeStr.split('x');
};
/**
* Sets the minimum value of the chart.
*
* @param {number} minValue The minimum value of the chart.
*/
goog.ui.ServerChart.prototype.setMinValue = function(minValue) {
this.minValue_ = minValue;
};
/**
* @return {number} The minimum value of the chart.
*/
goog.ui.ServerChart.prototype.getMinValue = function() {
return this.minValue_;
};
/**
* Sets the maximum value of the chart.
*
* @param {number} maxValue The maximum value of the chart.
*/
goog.ui.ServerChart.prototype.setMaxValue = function(maxValue) {
this.maxValue_ = maxValue;
};
/**
* @return {number} The maximum value of the chart.
*/
goog.ui.ServerChart.prototype.getMaxValue = function() {
return this.maxValue_;
};
/**
* Sets the chart margins.
*
* @param {number} leftMargin The size in pixels of the left margin.
* @param {number} rightMargin The size in pixels of the right margin.
* @param {number} topMargin The size in pixels of the top margin.
* @param {number} bottomMargin The size in pixels of the bottom margin.
*/
goog.ui.ServerChart.prototype.setMargins = function(leftMargin, rightMargin,
topMargin, bottomMargin) {
var margins = [leftMargin, rightMargin, topMargin, bottomMargin].join(',');
var UriParam = goog.ui.ServerChart.UriParam;
this.uri_.setParameterValue(UriParam.MARGINS, margins);
};
/**
* Sets the number of grid lines along the X-axis.
*
* @param {number} gridlines The number of X-axis grid lines.
*/
goog.ui.ServerChart.prototype.setGridX = function(gridlines) {
// Need data for this to work.
this.gridX_ = gridlines;
this.setGrids_(this.gridX_, this.gridY_);
};
/**
* @return {number} The number of gridlines along the X-axis.
*/
goog.ui.ServerChart.prototype.getGridX = function() {
return this.gridX_;
};
/**
* Sets the number of grid lines along the Y-axis.
*
* @param {number} gridlines The number of Y-axis grid lines.
*/
goog.ui.ServerChart.prototype.setGridY = function(gridlines) {
// Need data for this to work.
this.gridY_ = gridlines;
this.setGrids_(this.gridX_, this.gridY_);
};
/**
* @return {number} The number of gridlines along the Y-axis.
*/
goog.ui.ServerChart.prototype.getGridY = function() {
return this.gridY_;
};
/**
* Sets the grids for the chart
*
* @private
* @param {number} x The number of grid lines along the x-axis.
* @param {number} y The number of grid lines along the y-axis.
*/
goog.ui.ServerChart.prototype.setGrids_ = function(x, y) {
var gridArray = [x == 0 ? 0 : 100 / x,
y == 0 ? 0 : 100 / y];
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.GRID,
gridArray.join(','));
};
/**
* Sets the X Labels for the chart.
*
* @param {Array.<string>} labels The X Labels for the chart.
*/
goog.ui.ServerChart.prototype.setXLabels = function(labels) {
this.xLabels_ = labels;
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.X_LABELS,
this.xLabels_.join('|'));
};
/**
* @return {Array.<string>} The X Labels for the chart.
*/
goog.ui.ServerChart.prototype.getXLabels = function() {
return this.xLabels_;
};
/**
* @return {boolean} Whether the chart is a bar chart.
*/
goog.ui.ServerChart.prototype.isBarChart = function() {
var type = this.getType();
return type == goog.ui.ServerChart.ChartType.BAR ||
type == goog.ui.ServerChart.ChartType.HORIZONTAL_GROUPED_BAR ||
type == goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR ||
type == goog.ui.ServerChart.ChartType.VERTICAL_GROUPED_BAR ||
type == goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR;
};
/**
* @return {boolean} Whether the chart is a pie chart.
*/
goog.ui.ServerChart.prototype.isPieChart = function() {
var type = this.getType();
return type == goog.ui.ServerChart.ChartType.PIE ||
type == goog.ui.ServerChart.ChartType.PIE3D ||
type == goog.ui.ServerChart.ChartType.CONCENTRIC_PIE;
};
/**
* @return {boolean} Whether the chart is a grouped bar chart.
*/
goog.ui.ServerChart.prototype.isGroupedBarChart = function() {
var type = this.getType();
return type == goog.ui.ServerChart.ChartType.HORIZONTAL_GROUPED_BAR ||
type == goog.ui.ServerChart.ChartType.VERTICAL_GROUPED_BAR;
};
/**
* @return {boolean} Whether the chart is a horizontal bar chart.
*/
goog.ui.ServerChart.prototype.isHorizontalBarChart = function() {
var type = this.getType();
return type == goog.ui.ServerChart.ChartType.BAR ||
type == goog.ui.ServerChart.ChartType.HORIZONTAL_GROUPED_BAR ||
type == goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR;
};
/**
* @return {boolean} Whether the chart is a line chart.
*/
goog.ui.ServerChart.prototype.isLineChart = function() {
var type = this.getType();
return type == goog.ui.ServerChart.ChartType.FILLEDLINE ||
type == goog.ui.ServerChart.ChartType.LINE ||
type == goog.ui.ServerChart.ChartType.SPARKLINE ||
type == goog.ui.ServerChart.ChartType.XYLINE;
};
/**
* @return {boolean} Whether the chart is a map.
*/
goog.ui.ServerChart.prototype.isMap = function() {
var type = this.getType();
return type == goog.ui.ServerChart.ChartType.MAP ||
type == goog.ui.ServerChart.ChartType.MAPUSA ||
type == goog.ui.ServerChart.ChartType.MAPWORLD;
};
/**
* @return {boolean} Whether the chart is a stacked bar chart.
*/
goog.ui.ServerChart.prototype.isStackedBarChart = function() {
var type = this.getType();
return type == goog.ui.ServerChart.ChartType.BAR ||
type == goog.ui.ServerChart.ChartType.HORIZONTAL_STACKED_BAR ||
type == goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR;
};
/**
* @return {boolean} Whether the chart is a vertical bar chart.
*/
goog.ui.ServerChart.prototype.isVerticalBarChart = function() {
var type = this.getType();
return type == goog.ui.ServerChart.ChartType.VERTICAL_GROUPED_BAR ||
type == goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR;
};
/**
* Sets the Left Labels for the chart.
* NOTE: The array should start with the lowest value, and then
* move progessively up the axis. So if you want labels
* from 0 to 100 with 0 at bottom of the graph, then you would
* want to pass something like [0,25,50,75,100].
*
* @param {Array.<string>} labels The Left Labels for the chart.
*/
goog.ui.ServerChart.prototype.setLeftLabels = function(labels) {
this.leftLabels_ = labels;
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.LEFT_Y_LABELS,
this.leftLabels_.reverse().join('|'));
};
/**
* @return {Array.<string>} The Left Labels for the chart.
*/
goog.ui.ServerChart.prototype.getLeftLabels = function() {
return this.leftLabels_;
};
/**
* Sets the given ChartServer parameter.
*
* @param {goog.ui.ServerChart.UriParam} key The ChartServer parameter to set.
* @param {string} value The value to set for the ChartServer parameter.
*/
goog.ui.ServerChart.prototype.setParameterValue = function(key, value) {
this.uri_.setParameterValue(key, value);
};
/**
* Removes the given ChartServer parameter.
*
* @param {goog.ui.ServerChart.UriParam} key The ChartServer parameter to
* remove.
*/
goog.ui.ServerChart.prototype.removeParameter = function(key) {
this.uri_.removeParameter(key);
};
/**
* Sets the Right Labels for the chart.
* NOTE: The array should start with the lowest value, and then
* move progessively up the axis. So if you want labels
* from 0 to 100 with 0 at bottom of the graph, then you would
* want to pass something like [0,25,50,75,100].
*
* @param {Array.<string>} labels The Right Labels for the chart.
*/
goog.ui.ServerChart.prototype.setRightLabels = function(labels) {
this.rightLabels_ = labels;
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.RIGHT_LABELS,
this.rightLabels_.reverse().join('|'));
};
/**
* @return {Array.<string>} The Right Labels for the chart.
*/
goog.ui.ServerChart.prototype.getRightLabels = function() {
return this.rightLabels_;
};
/**
* Sets the position relative to the chart where the legend is to be displayed.
*
* @param {goog.ui.ServerChart.LegendPosition} value Legend position.
*/
goog.ui.ServerChart.prototype.setLegendPosition = function(value) {
this.uri_.setParameterValue(
goog.ui.ServerChart.UriParam.LEGEND_POSITION, value);
};
/**
* Returns the position relative to the chart where the legend is to be
* displayed.
*
* @return {goog.ui.ServerChart.LegendPosition} Legend position.
*/
goog.ui.ServerChart.prototype.getLegendPosition = function() {
return /** @type {goog.ui.ServerChart.LegendPosition} */ (
this.uri_.getParameterValue(
goog.ui.ServerChart.UriParam.LEGEND_POSITION));
};
/**
* Sets the number of "visible" data sets. All data sets that come after
* the visible data set are not drawn as part of the chart. Instead, they
* are available for positioning markers.
* @param {?number} n The number of visible data sets, or null if all data
* sets are to be visible.
*/
goog.ui.ServerChart.prototype.setNumVisibleDataSets = function(n) {
this.numVisibleDataSets_ = n;
};
/**
* Returns the number of "visible" data sets. All data sets that come after
* the visible data set are not drawn as part of the chart. Instead, they
* are available for positioning markers.
*
* @return {?number} The number of visible data sets, or null if all data
* sets are visible.
*/
goog.ui.ServerChart.prototype.getNumVisibleDataSets = function() {
return this.numVisibleDataSets_;
};
/**
* Sets the weight function for a Venn Diagram along with the associated
* colors and legend text. Weights are assigned as follows:
* weights[0] is relative area of circle A.
* weights[1] is relative area of circle B.
* weights[2] is relative area of circle C.
* weights[3] is relative area of overlap of circles A and B.
* weights[4] is relative area of overlap of circles A and C.
* weights[5] is relative area of overlap of circles B and C.
* weights[6] is relative area of overlap of circles A, B and C.
* For a two circle Venn Diagram the weights are assigned as follows:
* weights[0] is relative area of circle A.
* weights[1] is relative area of circle B.
* weights[2] is relative area of overlap of circles A and B.
*
* @param {Array.<number>} weights The relative weights of the circles.
* @param {Array.<string>=} opt_legendText The legend labels for the circles.
* @param {Array.<string>=} opt_colors The colors for the circles.
*/
goog.ui.ServerChart.prototype.setVennSeries = function(
weights, opt_legendText, opt_colors) {
if (this.getType() != goog.ui.ServerChart.ChartType.VENN) {
throw Error('Can only set a weight function for a Venn diagram.');
}
var dataMin = this.arrayMin_(weights);
if (dataMin < this.minValue_) {
this.minValue_ = dataMin;
}
var dataMax = this.arrayMax_(weights);
if (dataMax > this.maxValue_) {
this.maxValue_ = dataMax;
}
if (goog.isDef(opt_legendText)) {
goog.array.forEach(
opt_legendText,
goog.bind(function(legend) {
this.setLegendTexts_.push(legend);
}, this));
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.LEGEND_TEXTS,
this.setLegendTexts_.join('|'));
}
// If the caller only gave three weights, then they wanted a two circle
// Venn Diagram. Create a 3 circle weight function where circle C has
// area zero.
if (weights.length == 3) {
weights[3] = weights[2];
weights[2] = 0.0;
}
this.dataSets_.push(weights);
if (goog.isDef(opt_colors)) {
goog.array.forEach(opt_colors, goog.bind(function(color) {
this.setColors_.push(color);
}, this));
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.DATA_COLORS,
this.setColors_.join(','));
}
};
/**
* Sets the title of the chart.
*
* @param {string} title The chart title.
*/
goog.ui.ServerChart.prototype.setTitle = function(title) {
this.title_ = title;
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.TITLE,
this.title_.replace(/\n/g, '|'));
};
/**
* Sets the size of the chart title.
*
* @param {number} size The title size, in points.
*/
goog.ui.ServerChart.prototype.setTitleSize = function(size) {
this.titleSize_ = size;
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.TITLE_FORMAT,
this.titleColor_ + ',' + this.titleSize_);
};
/**
* @return {number} size The title size, in points.
*/
goog.ui.ServerChart.prototype.getTitleSize = function() {
return this.titleSize_;
};
/**
* Sets the color of the chart title.
*
* NOTE: The color string should NOT have a '#' at the beginning of it.
*
* @param {string} color The hex value for the title color.
*/
goog.ui.ServerChart.prototype.setTitleColor = function(color) {
this.titleColor_ = color;
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.TITLE_FORMAT,
this.titleColor_ + ',' + this.titleSize_);
};
/**
* @return {string} color The hex value for the title color.
*/
goog.ui.ServerChart.prototype.getTitleColor = function() {
return this.titleColor_;
};
/**
* Adds a legend to the chart.
*
* @param {Array.<string>} legend The legend to add.
*/
goog.ui.ServerChart.prototype.setLegend = function(legend) {
this.legend_ = legend;
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.LEGEND,
this.legend_.join('|'));
};
/**
* Sets the data scaling.
* NOTE: This also changes the encoding type because data scaling will
* only work with {@code goog.ui.ServerChart.EncodingType.TEXT}
* encoding.
* @param {number} minimum The lowest number to apply to the data.
* @param {number} maximum The highest number to apply to the data.
*/
goog.ui.ServerChart.prototype.setDataScaling = function(minimum, maximum) {
this.encodingType_ = goog.ui.ServerChart.EncodingType.TEXT;
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.DATA_SCALING,
minimum + ',' + maximum);
};
/**
* Sets the widths of the bars and the spaces between the bars in a bar
* chart.
* NOTE: If the space between groups is specified but the space between
* bars is left undefined, the space between groups will be interpreted
* as the space between bars because this is the behavior exposed
* in the external developers guide.
* @param {number} barWidth The width of a bar in pixels.
* @param {number=} opt_spaceBars The width of the space between
* bars in a group in pixels.
* @param {number=} opt_spaceGroups The width of the space between
* groups.
*/
goog.ui.ServerChart.prototype.setBarSpaceWidths = function(barWidth,
opt_spaceBars,
opt_spaceGroups) {
var widths = [barWidth];
if (goog.isDef(opt_spaceBars)) {
widths.push(opt_spaceBars);
}
if (goog.isDef(opt_spaceGroups)) {
widths.push(opt_spaceGroups);
}
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT,
widths.join(','));
};
/**
* Specifies that the bar width in a bar chart should be calculated
* automatically given the space available in the chart, while optionally
* setting the spaces between the bars.
* NOTE: If the space between groups is specified but the space between
* bars is left undefined, the space between groups will be interpreted
* as the space between bars because this is the behavior exposed
* in the external developers guide.
* @param {number=} opt_spaceBars The width of the space between
* bars in a group in pixels.
* @param {number=} opt_spaceGroups The width of the space between
* groups.
*/
goog.ui.ServerChart.prototype.setAutomaticBarWidth = function(opt_spaceBars,
opt_spaceGroups) {
var widths = ['a'];
if (goog.isDef(opt_spaceBars)) {
widths.push(opt_spaceBars);
}
if (goog.isDef(opt_spaceGroups)) {
widths.push(opt_spaceGroups);
}
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.BAR_HEIGHT,
widths.join(','));
};
/**
* Adds a multi-axis to the chart, and sets its type. Multiple axes of the same
* type can be added.
*
* @param {goog.ui.ServerChart.MultiAxisType} axisType The desired axis type.
* @return {number} The index of the newly inserted axis, suitable for feeding
* to the setMultiAxis*() functions.
*/
goog.ui.ServerChart.prototype.addMultiAxis = function(axisType) {
this.multiAxisType_.push(axisType);
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.MULTI_AXIS_TYPES,
this.multiAxisType_.join(','));
return this.multiAxisType_.length - 1;
};
/**
* Returns the axis type for the given axis, or all of them in an array if the
* axis number is not given.
*
* @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis.
* @return {goog.ui.ServerChart.MultiAxisType|
* Array.<goog.ui.ServerChart.MultiAxisType>}
* The axis type for the given axis, or all of them in an array if the
* axis number is not given.
*/
goog.ui.ServerChart.prototype.getMultiAxisType = function(opt_axisNumber) {
if (goog.isDef(opt_axisNumber)) {
return this.multiAxisType_[opt_axisNumber];
}
return this.multiAxisType_;
};
/**
* Sets the label text (usually multiple values) for a given axis, overwriting
* any existing values.
*
* @param {number} axisNumber The axis index, as returned by addMultiAxis.
* @param {Array.<string>} labelText The actual label text to be added.
*/
goog.ui.ServerChart.prototype.setMultiAxisLabelText = function(axisNumber,
labelText) {
this.multiAxisLabelText_[axisNumber] = labelText;
var axisString = this.computeMultiAxisDataString_(this.multiAxisLabelText_,
':|',
'|',
'|');
this.uri_.setParameterValue(
goog.ui.ServerChart.UriParam.MULTI_AXIS_LABEL_TEXT,
axisString);
};
/**
* Returns the label text, or all of them in a two-dimensional array if the
* axis number is not given.
*
* @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis.
* @return {Object|Array.<string>} The label text, or all of them in a
* two-dimensional array if the axis number is not given.
*/
goog.ui.ServerChart.prototype.getMultiAxisLabelText = function(opt_axisNumber) {
if (goog.isDef(opt_axisNumber)) {
return this.multiAxisLabelText_[opt_axisNumber];
}
return this.multiAxisLabelText_;
};
/**
* Sets the label positions for a given axis, overwriting any existing values.
* The label positions are assumed to be floating-point numbers within the
* range of the axis.
*
* @param {number} axisNumber The axis index, as returned by addMultiAxis.
* @param {Array.<number>} labelPosition The actual label positions to be added.
*/
goog.ui.ServerChart.prototype.setMultiAxisLabelPosition = function(
axisNumber, labelPosition) {
this.multiAxisLabelPosition_[axisNumber] = labelPosition;
var positionString = this.computeMultiAxisDataString_(
this.multiAxisLabelPosition_,
',',
',',
'|');
this.uri_.setParameterValue(
goog.ui.ServerChart.UriParam.MULTI_AXIS_LABEL_POSITION,
positionString);
};
/**
* Returns the label positions for a given axis number, or all of them in a
* two-dimensional array if the axis number is not given.
*
* @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis.
* @return {Object|Array.<number>} The label positions for a given axis number,
* or all of them in a two-dimensional array if the axis number is not
* given.
*/
goog.ui.ServerChart.prototype.getMultiAxisLabelPosition =
function(opt_axisNumber) {
if (goog.isDef(opt_axisNumber)) {
return this.multiAxisLabelPosition_[opt_axisNumber];
}
return this.multiAxisLabelPosition_;
};
/**
* Sets the label range for a given axis, overwriting any existing range.
* The default range is from 0 to 100. If the start value is larger than the
* end value, the axis direction is reversed. rangeStart and rangeEnd must
* be two different finite numbers.
*
* @param {number} axisNumber The axis index, as returned by addMultiAxis.
* @param {number} rangeStart The new start of the range.
* @param {number} rangeEnd The new end of the range.
* @param {number=} opt_interval The interval between axis labels.
*/
goog.ui.ServerChart.prototype.setMultiAxisRange = function(axisNumber,
rangeStart,
rangeEnd,
opt_interval) {
goog.asserts.assert(rangeStart != rangeEnd,
'Range start and end cannot be the same value.');
goog.asserts.assert(isFinite(rangeStart) && isFinite(rangeEnd),
'Range start and end must be finite numbers.');
this.multiAxisRange_[axisNumber] = [rangeStart, rangeEnd];
if (goog.isDef(opt_interval)) {
this.multiAxisRange_[axisNumber].push(opt_interval);
}
var rangeString = this.computeMultiAxisDataString_(this.multiAxisRange_,
',', ',', '|');
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.MULTI_AXIS_RANGE,
rangeString);
};
/**
* Returns the label range for a given axis number as a two-element array of
* (range start, range end), or all of them in a two-dimensional array if the
* axis number is not given.
*
* @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis.
* @return {Object|Array.<number>} The label range for a given axis number as a
* two-element array of (range start, range end), or all of them in a
* two-dimensional array if the axis number is not given.
*/
goog.ui.ServerChart.prototype.getMultiAxisRange = function(opt_axisNumber) {
if (goog.isDef(opt_axisNumber)) {
return this.multiAxisRange_[opt_axisNumber];
}
return this.multiAxisRange_;
};
/**
* Sets the label style for a given axis, overwriting any existing style.
* The default style is as follows: Default is x-axis labels are centered, left
* hand y-axis labels are right aligned, right hand y-axis labels are left
* aligned. The font size and alignment are optional parameters.
*
* NOTE: The color string should NOT have a '#' at the beginning of it.
*
* @param {number} axisNumber The axis index, as returned by addMultiAxis.
* @param {string} color The hex value for this label's color.
* @param {number=} opt_fontSize The label font size, in pixels.
* @param {goog.ui.ServerChart.MultiAxisAlignment=} opt_alignment The label
* alignment.
* @param {goog.ui.ServerChart.AxisDisplayType=} opt_axisDisplay The axis
* line and ticks.
*/
goog.ui.ServerChart.prototype.setMultiAxisLabelStyle = function(
axisNumber, color, opt_fontSize, opt_alignment, opt_axisDisplay) {
var style = [color];
if (goog.isDef(opt_fontSize) || goog.isDef(opt_alignment)) {
style.push(opt_fontSize || '');
}
if (goog.isDef(opt_alignment)) {
style.push(opt_alignment);
}
if (opt_axisDisplay) {
style.push(opt_axisDisplay);
}
this.multiAxisLabelStyle_[axisNumber] = style;
var styleString = this.computeMultiAxisDataString_(this.multiAxisLabelStyle_,
',',
',',
'|');
this.uri_.setParameterValue(
goog.ui.ServerChart.UriParam.MULTI_AXIS_STYLE,
styleString);
};
/**
* Returns the label style for a given axis number as a one- to three-element
* array, or all of them in a two-dimensional array if the axis number is not
* given.
*
* @param {number=} opt_axisNumber The axis index, as returned by addMultiAxis.
* @return {Object|Array.<number>} The label style for a given axis number as a
* one- to three-element array, or all of them in a two-dimensional array if
* the axis number is not given.
*/
goog.ui.ServerChart.prototype.getMultiAxisLabelStyle =
function(opt_axisNumber) {
if (goog.isDef(opt_axisNumber)) {
return this.multiAxisLabelStyle_[opt_axisNumber];
}
return this.multiAxisLabelStyle_;
};
/**
* Adds a data set.
* NOTE: The color string should NOT have a '#' at the beginning of it.
*
* @param {Array.<number|null>} data An array of numbers (values can be
* NaN or null).
* @param {string} color The hex value for this data set's color.
* @param {string=} opt_legendText The legend text, if any, for this data
* series. NOTE: If specified, all previously added data sets must also
* have a legend text.
*/
goog.ui.ServerChart.prototype.addDataSet = function(data,
color,
opt_legendText) {
var dataMin = this.arrayMin_(data);
if (dataMin < this.minValue_) {
this.minValue_ = dataMin;
}
var dataMax = this.arrayMax_(data);
if (dataMax > this.maxValue_) {
this.maxValue_ = dataMax;
}
if (goog.isDef(opt_legendText)) {
if (this.setLegendTexts_.length < this.dataSets_.length) {
throw Error('Cannot start adding legends text after first element.');
}
this.setLegendTexts_.push(opt_legendText);
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.LEGEND_TEXTS,
this.setLegendTexts_.join('|'));
}
this.dataSets_.push(data);
this.setColors_.push(color);
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.DATA_COLORS,
this.setColors_.join(','));
};
/**
* Clears the data sets from the graph. All data, including the colors and
* legend text, is cleared.
*/
goog.ui.ServerChart.prototype.clearDataSets = function() {
var queryData = this.uri_.getQueryData();
queryData.remove(goog.ui.ServerChart.UriParam.LEGEND_TEXTS);
queryData.remove(goog.ui.ServerChart.UriParam.DATA_COLORS);
queryData.remove(goog.ui.ServerChart.UriParam.DATA);
this.setLegendTexts_.length = 0;
this.setColors_.length = 0;
this.dataSets_.length = 0;
};
/**
* Returns the given data set or all of them in a two-dimensional array if
* the set number is not given.
*
* @param {number=} opt_setNumber Optional data set number to get.
* @return {Array} The given data set or all of them in a two-dimensional array
* if the set number is not given.
*/
goog.ui.ServerChart.prototype.getData = function(opt_setNumber) {
if (goog.isDef(opt_setNumber)) {
return this.dataSets_[opt_setNumber];
}
return this.dataSets_;
};
/**
* Computes the data string using the data in this.dataSets_ and sets
* the object's URI accordingly. If the URI's length equals or exceeds the
* limit, goog.ui.ServerChart.UriTooLongEvent is dispatched on the
* goog.ui.ServerChart object.
* @private
*/
goog.ui.ServerChart.prototype.computeDataString_ = function() {
var ok;
if (this.encodingType_ != goog.ui.ServerChart.EncodingType.AUTOMATIC) {
ok = this.computeDataStringForEncoding_(this.encodingType_);
} else {
ok = this.computeDataStringForEncoding_(
goog.ui.ServerChart.EncodingType.EXTENDED);
if (!ok) {
ok = this.computeDataStringForEncoding_(
goog.ui.ServerChart.EncodingType.SIMPLE);
}
}
if (!ok) {
this.dispatchEvent(
new goog.ui.ServerChart.UriTooLongEvent(this.uri_.toString()));
}
};
/**
* Computes the data string using the data in this.dataSets_ and the encoding
* specified by the encoding parameter, which must not be AUTOMATIC, and sets
* the object's URI accordingly.
* @param {goog.ui.ServerChart.EncodingType} encoding The data encoding to use;
* must not be AUTOMATIC.
* @return {boolean} False if the resulting URI is too long.
* @private
*/
goog.ui.ServerChart.prototype.computeDataStringForEncoding_ = function(
encoding) {
var dataStrings = [];
for (var i = 0, setLen = this.dataSets_.length; i < setLen; ++i) {
dataStrings[i] = this.getChartServerValues_(this.dataSets_[i],
this.minValue_,
this.maxValue_,
encoding);
}
var delimiter = encoding == goog.ui.ServerChart.EncodingType.TEXT ? '|' : ',';
dataStrings = dataStrings.join(delimiter);
var data;
if (this.numVisibleDataSets_ == null) {
data = goog.string.buildString(encoding, ':', dataStrings);
} else {
data = goog.string.buildString(encoding, this.numVisibleDataSets_, ':',
dataStrings);
}
this.uri_.setParameterValue(goog.ui.ServerChart.UriParam.DATA, data);
return this.uri_.toString().length < this.uriLengthLimit_;
};
/**
* Computes a multi-axis data string from the given data and separators. The
* general data format for each index/element in the array will be
* "<arrayIndex><indexSeparator><arrayElement.join(elementSeparator)>", with
* axisSeparator used between multiple elements.
* @param {Object} data The data to compute the data string for, as a
* sparse array of arrays. NOTE: The function uses the length of
* multiAxisType_ to determine the upper bound for the outer array.
* @param {string} indexSeparator The separator string inserted between each
* index and the data itself, commonly a comma (,).
* @param {string} elementSeparator The separator string inserted between each
* element inside each sub-array in the data, if there are more than one;
* commonly a comma (,).
* @param {string} axisSeparator The separator string inserted between each
* axis specification, if there are more than one; usually a pipe sign (|).
* @return {string} The multi-axis data string.
* @private
*/
goog.ui.ServerChart.prototype.computeMultiAxisDataString_ = function(
data,
indexSeparator,
elementSeparator,
axisSeparator) {
var elementStrings = [];
for (var i = 0, setLen = this.multiAxisType_.length; i < setLen; ++i) {
if (data[i]) {
elementStrings.push(i + indexSeparator + data[i].join(elementSeparator));
}
}
return elementStrings.join(axisSeparator);
};
/**
* Array of possible ChartServer data values
* @type {string}
*/
goog.ui.ServerChart.CHART_VALUES = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz' +
'0123456789';
/**
* Array of extended ChartServer data values
* @type {string}
*/
goog.ui.ServerChart.CHART_VALUES_EXTENDED = goog.ui.ServerChart.CHART_VALUES +
'-.';
/**
* Upper bound for extended values
*/
goog.ui.ServerChart.EXTENDED_UPPER_BOUND =
Math.pow(goog.ui.ServerChart.CHART_VALUES_EXTENDED.length, 2) - 1;
/**
* Converts a single number to an encoded data value suitable for ChartServer.
* The TEXT encoding is the number in decimal; the SIMPLE encoding is a single
* character, and the EXTENDED encoding is two characters. See
* http://code.google.com/apis/chart/docs/data_formats.html for the detailed
* specification of these encoding formats.
*
* @private
* @param {?number} value The value to convert (null for a missing data point).
* @param {number} minValue The minimum value (used for normalization).
* @param {number} maxValue The maximum value (used for normalization).
* @param {goog.ui.ServerChart.EncodingType} encoding The data encoding to use;
* must not be AUTOMATIC.
* @return {string} The encoded data value.
*/
goog.ui.ServerChart.prototype.getConvertedValue_ = function(value,
minValue,
maxValue,
encoding) {
goog.asserts.assert(minValue <= maxValue,
'minValue should be less than or equal to maxValue');
var isExtended = (encoding == goog.ui.ServerChart.EncodingType.EXTENDED);
if (goog.isNull(value) || !goog.isDef(value) || isNaN(value) ||
value < minValue || value > maxValue) {
return isExtended ? '__' : '_';
}
if (encoding == goog.ui.ServerChart.EncodingType.TEXT) {
return String(value);
}
var frac = goog.ui.ServerChart.DEFAULT_NORMALIZATION;
if (maxValue > minValue) {
frac = (value - minValue) / (maxValue - minValue);
// Previous checks of value ensure that 0 <= frac <= 1 at this point.
}
if (isExtended) {
var maxIndex = goog.ui.ServerChart.CHART_VALUES_EXTENDED.length;
var upperBound = goog.ui.ServerChart.EXTENDED_UPPER_BOUND;
var index1 = Math.floor(frac * upperBound / maxIndex);
var index2 = Math.floor((frac * upperBound) % maxIndex);
var extendedVals = goog.ui.ServerChart.CHART_VALUES_EXTENDED;
return extendedVals.charAt(index1) + extendedVals.charAt(index2);
}
var index = Math.round(frac * (goog.ui.ServerChart.CHART_VALUES.length - 1));
return goog.ui.ServerChart.CHART_VALUES.charAt(index);
};
/**
* Creates the chd string for chartserver.
*
* @private
* @param {Array.<number>} values An array of numbers to graph.
* @param {number} minValue The minimum value (used for normalization).
* @param {number} maxValue The maximum value (used for normalization).
* @param {goog.ui.ServerChart.EncodingType} encoding The data encoding to use;
* must not be AUTOMATIC.
* @return {string} The chd string for chartserver.
*/
goog.ui.ServerChart.prototype.getChartServerValues_ = function(values,
minValue,
maxValue,
encoding) {
var s = [];
for (var i = 0, valuesLen = values.length; i < valuesLen; ++i) {
s.push(this.getConvertedValue_(values[i], minValue,
maxValue, encoding));
}
return s.join(
this.encodingType_ == goog.ui.ServerChart.EncodingType.TEXT ? ',' : '');
};
/**
* Finds the minimum value in an array and returns it.
* Needed because Math.min does not handle sparse arrays the way we want.
*
* @param {Array.<number?>} ary An array of values.
* @return {number} The minimum value.
* @private
*/
goog.ui.ServerChart.prototype.arrayMin_ = function(ary) {
var min = Infinity;
for (var i = 0, aryLen = ary.length; i < aryLen; ++i) {
var value = ary[i];
if (value != null && value < min) {
min = value;
}
}
return min;
};
/**
* Finds the maximum value in an array and returns it.
* Needed because Math.max does not handle sparse arrays the way we want.
*
* @param {Array.<number?>} ary An array of values.
* @return {number} The maximum value.
* @private
*/
goog.ui.ServerChart.prototype.arrayMax_ = function(ary) {
var max = -Infinity;
for (var i = 0, aryLen = ary.length; i < aryLen; ++i) {
var value = ary[i];
if (value != null && value > max) {
max = value;
}
}
return max;
};
/** @override */
goog.ui.ServerChart.prototype.disposeInternal = function() {
goog.ui.ServerChart.superClass_.disposeInternal.call(this);
delete this.xLabels_;
delete this.leftLabels_;
delete this.rightLabels_;
delete this.gridX_;
delete this.gridY_;
delete this.setColors_;
delete this.setLegendTexts_;
delete this.dataSets_;
this.uri_ = null;
delete this.minValue_;
delete this.maxValue_;
this.title_ = null;
delete this.multiAxisType_;
delete this.multiAxisLabelText_;
delete this.multiAxisLabelPosition_;
delete this.multiAxisRange_;
delete this.multiAxisLabelStyle_;
this.legend_ = null;
};
/**
* Event types dispatched by the ServerChart object
* @enum {string}
*/
goog.ui.ServerChart.Event = {
/**
* Dispatched when the resulting URI reaches or exceeds the URI length limit.
*/
URI_TOO_LONG: 'uritoolong'
};
/**
* Class for the event dispatched on the ServerChart when the resulting URI
* exceeds the URI length limit.
* @constructor
* @param {string} uri The overly-long URI string.
* @extends {goog.events.Event}
*/
goog.ui.ServerChart.UriTooLongEvent = function(uri) {
goog.events.Event.call(this, goog.ui.ServerChart.Event.URI_TOO_LONG);
/**
* The overly-long URI string.
* @type {string}
*/
this.uri = uri;
};
goog.inherits(goog.ui.ServerChart.UriTooLongEvent, goog.events.Event);
| 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.MenuSeparator}s.
*
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.ui.MenuSeparatorRenderer');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.ControlRenderer');
/**
* Renderer for menu separators.
* @constructor
* @extends {goog.ui.ControlRenderer}
*/
goog.ui.MenuSeparatorRenderer = function() {
goog.ui.ControlRenderer.call(this);
};
goog.inherits(goog.ui.MenuSeparatorRenderer, goog.ui.ControlRenderer);
goog.addSingletonGetter(goog.ui.MenuSeparatorRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.MenuSeparatorRenderer.CSS_CLASS = goog.getCssName('goog-menuseparator');
/**
* Returns an empty, styled menu separator DIV. Overrides {@link
* goog.ui.ControlRenderer#createDom}.
* @param {goog.ui.Control} separator goog.ui.Separator to render.
* @return {Element} Root element for the separator.
* @override
*/
goog.ui.MenuSeparatorRenderer.prototype.createDom = function(separator) {
return separator.getDomHelper().createDom('div', this.getCssClass());
};
/**
* Takes an existing element, and decorates it with the separator. Overrides
* {@link goog.ui.ControlRenderer#decorate}.
* @param {goog.ui.Control} separator goog.ui.MenuSeparator to decorate the
* element.
* @param {Element} element Element to decorate.
* @return {Element} Decorated element.
* @override
*/
goog.ui.MenuSeparatorRenderer.prototype.decorate = function(separator,
element) {
// Normally handled in the superclass. But we don't call the superclass.
if (element.id) {
separator.setId(element.id);
}
if (element.tagName == 'HR') {
// Replace HR with separator.
var hr = element;
element = this.createDom(separator);
goog.dom.insertSiblingBefore(element, hr);
goog.dom.removeNode(hr);
} else {
goog.dom.classes.add(element, this.getCssClass());
}
return element;
};
/**
* Overrides {@link goog.ui.ControlRenderer#setContent} to do nothing, since
* separators are empty.
* @param {Element} separator The separator's root element.
* @param {goog.ui.ControlContent} content Text caption or DOM structure to be
* set as the separators's content (ignored).
* @override
*/
goog.ui.MenuSeparatorRenderer.prototype.setContent = function(separator,
content) {
// Do nothing. Separators are empty.
};
/**
* Returns the CSS class to be applied to the root element of components
* rendered using this renderer.
* @return {string} Renderer-specific CSS class.
* @override
*/
goog.ui.MenuSeparatorRenderer.prototype.getCssClass = function() {
return goog.ui.MenuSeparatorRenderer.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 Class for showing simple modal popup.
*/
goog.provide('goog.ui.ModalPopup');
goog.require('goog.Timer');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.classes');
goog.require('goog.dom.iframe');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.events.FocusHandler');
goog.require('goog.fx.Transition');
goog.require('goog.style');
goog.require('goog.ui.Component');
goog.require('goog.ui.PopupBase.EventType');
goog.require('goog.userAgent');
/**
* Base class for modal popup UI components. This can also be used as
* a standalone component to render a modal popup with an empty div.
*
* WARNING: goog.ui.ModalPopup is only guaranteed to work when it is rendered
* directly in the 'body' element.
*
* The Html structure of the modal popup is:
* <pre>
* Element Function Class-name, goog-modalpopup = default
* ----------------------------------------------------------------------------
* - iframe Iframe mask goog-modalpopup-bg
* - div Background mask goog-modalpopup-bg
* - div Modal popup area goog-modalpopup
* - span Tab catcher
* </pre>
* @constructor
* @param {boolean=} opt_useIframeMask Work around windowed controls z-index
* issue by using an iframe instead of a div for bg element.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper; see {@link
* goog.ui.Component} for semantics.
* @extends {goog.ui.Component}
*/
goog.ui.ModalPopup = function(opt_useIframeMask, opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* Whether the modal popup should use an iframe as the background
* element to work around z-order issues.
* @type {boolean}
* @private
*/
this.useIframeMask_ = !!opt_useIframeMask;
};
goog.inherits(goog.ui.ModalPopup, goog.ui.Component);
/**
* Focus handler. It will be initialized in enterDocument.
* @type {goog.events.FocusHandler}
* @private
*/
goog.ui.ModalPopup.prototype.focusHandler_ = null;
/**
* Whether the modal popup is visible.
* @type {boolean}
* @private
*/
goog.ui.ModalPopup.prototype.visible_ = false;
/**
* Element for the background which obscures the UI and blocks events.
* @type {Element}
* @private
*/
goog.ui.ModalPopup.prototype.bgEl_ = null;
/**
* Iframe element that is only used for IE as a workaround to keep select-type
* elements from burning through background.
* @type {Element}
* @private
*/
goog.ui.ModalPopup.prototype.bgIframeEl_ = null;
/**
* Element used to catch focus and prevent the user from tabbing out
* of the popup.
* @type {Element}
* @private
*/
goog.ui.ModalPopup.prototype.tabCatcherElement_ = null;
/**
* Whether the modal popup is in the process of wrapping focus from the top of
* the popup to the last tabbable element.
* @type {boolean}
* @private
*/
goog.ui.ModalPopup.prototype.backwardTabWrapInProgress_ = false;
/**
* Transition to show the popup.
* @type {goog.fx.Transition}
* @private
*/
goog.ui.ModalPopup.prototype.popupShowTransition_;
/**
* Transition to hide the popup.
* @type {goog.fx.Transition}
* @private
*/
goog.ui.ModalPopup.prototype.popupHideTransition_;
/**
* Transition to show the background.
* @type {goog.fx.Transition}
* @private
*/
goog.ui.ModalPopup.prototype.bgShowTransition_;
/**
* Transition to hide the background.
* @type {goog.fx.Transition}
* @private
*/
goog.ui.ModalPopup.prototype.bgHideTransition_;
/**
* @return {string} Base CSS class for this component.
* @protected
*/
goog.ui.ModalPopup.prototype.getCssClass = function() {
return goog.getCssName('goog-modalpopup');
};
/**
* Returns the background iframe mask element, if any.
* @return {Element} The background iframe mask element, may return
* null/undefined if the modal popup does not use iframe mask.
*/
goog.ui.ModalPopup.prototype.getBackgroundIframe = function() {
return this.bgIframeEl_;
};
/**
* Returns the background mask element.
* @return {Element} The background mask element.
*/
goog.ui.ModalPopup.prototype.getBackgroundElement = function() {
return this.bgEl_;
};
/**
* Creates the initial DOM representation for the modal popup.
* @override
*/
goog.ui.ModalPopup.prototype.createDom = function() {
// Create the modal popup element, and make sure it's hidden.
goog.base(this, 'createDom');
var element = this.getElement();
goog.dom.classes.add(element, this.getCssClass());
goog.dom.setFocusableTabIndex(element, true);
goog.style.setElementShown(element, false);
// Manages the DOM for background mask elements.
this.manageBackgroundDom_();
this.createTabCatcher_();
};
/**
* Creates and disposes of the DOM for background mask elements.
* @private
*/
goog.ui.ModalPopup.prototype.manageBackgroundDom_ = function() {
if (this.useIframeMask_ && !this.bgIframeEl_) {
// IE renders the iframe on top of the select elements while still
// respecting the z-index of the other elements on the page. See
// http://support.microsoft.com/kb/177378 for more information.
// Flash and other controls behave in similar ways for other browsers
this.bgIframeEl_ = goog.dom.iframe.createBlank(this.getDomHelper());
this.bgIframeEl_.className = goog.getCssName(this.getCssClass(), 'bg');
goog.style.setElementShown(this.bgIframeEl_, false);
goog.style.setOpacity(this.bgIframeEl_, 0);
}
// Create the backgound mask, initialize its opacity, and make sure it's
// hidden.
if (!this.bgEl_) {
this.bgEl_ = this.getDomHelper().createDom(
'div', goog.getCssName(this.getCssClass(), 'bg'));
goog.style.setElementShown(this.bgEl_, false);
}
};
/**
* Creates the tab catcher element.
* @private
*/
goog.ui.ModalPopup.prototype.createTabCatcher_ = function() {
// Creates tab catcher element.
if (!this.tabCatcherElement_) {
this.tabCatcherElement_ = this.getDomHelper().createElement('span');
goog.style.setElementShown(this.tabCatcherElement_, false);
goog.dom.setFocusableTabIndex(this.tabCatcherElement_, true);
this.tabCatcherElement_.style.position = 'absolute';
}
};
/**
* Allow a shift-tab from the top of the modal popup to the last tabbable
* element by moving focus to the tab catcher. This should be called after
* catching a wrapping shift-tab event and before allowing it to propagate, so
* that focus will land on the last tabbable element before the tab catcher.
* @protected
*/
goog.ui.ModalPopup.prototype.setupBackwardTabWrap = function() {
this.backwardTabWrapInProgress_ = true;
try {
this.tabCatcherElement_.focus();
} catch (e) {
// Swallow this. IE can throw an error if the element can not be focused.
}
// Reset the flag on a timer in case anything goes wrong with the followup
// event.
goog.Timer.callOnce(this.resetBackwardTabWrap_, 0, this);
};
/**
* Resets the backward tab wrap flag.
* @private
*/
goog.ui.ModalPopup.prototype.resetBackwardTabWrap_ = function() {
this.backwardTabWrapInProgress_ = false;
};
/**
* Renders the background mask.
* @private
*/
goog.ui.ModalPopup.prototype.renderBackground_ = function() {
goog.asserts.assert(!!this.bgEl_, 'Background element must not be null.');
if (this.bgIframeEl_) {
goog.dom.insertSiblingBefore(this.bgIframeEl_, this.getElement());
}
goog.dom.insertSiblingBefore(this.bgEl_, this.getElement());
};
/** @override */
goog.ui.ModalPopup.prototype.canDecorate = function(element) {
// Assume we can decorate any DIV.
return !!element && element.tagName == goog.dom.TagName.DIV;
};
/** @override */
goog.ui.ModalPopup.prototype.decorateInternal = function(element) {
// Decorate the modal popup area element.
goog.base(this, 'decorateInternal', element);
goog.dom.classes.add(this.getElement(), this.getCssClass());
// Create the background mask...
this.manageBackgroundDom_();
this.createTabCatcher_();
// Make sure the decorated modal popup is hidden.
goog.style.setElementShown(this.getElement(), false);
};
/** @override */
goog.ui.ModalPopup.prototype.enterDocument = function() {
this.renderBackground_();
goog.base(this, 'enterDocument');
goog.dom.insertSiblingAfter(this.tabCatcherElement_, this.getElement());
this.focusHandler_ = new goog.events.FocusHandler(
this.getDomHelper().getDocument());
// We need to watch the entire document so that we can detect when the
// focus is moved out of this modal popup.
this.getHandler().listen(
this.focusHandler_, goog.events.FocusHandler.EventType.FOCUSIN,
this.onFocus_);
};
/** @override */
goog.ui.ModalPopup.prototype.exitDocument = function() {
if (this.isVisible()) {
this.setVisible(false);
}
goog.dispose(this.focusHandler_);
goog.base(this, 'exitDocument');
goog.dom.removeNode(this.bgIframeEl_);
goog.dom.removeNode(this.bgEl_);
goog.dom.removeNode(this.tabCatcherElement_);
};
/**
* Sets the visibility of the modal popup box and focus to the popup.
* Lazily renders the component if needed.
* @param {boolean} visible Whether the modal popup should be visible.
*/
goog.ui.ModalPopup.prototype.setVisible = function(visible) {
goog.asserts.assert(
this.isInDocument(), 'ModalPopup must be rendered first.');
if (visible == this.visible_) {
return;
}
if (this.popupShowTransition_) this.popupShowTransition_.stop();
if (this.bgShowTransition_) this.bgShowTransition_.stop();
if (this.popupHideTransition_) this.popupHideTransition_.stop();
if (this.bgHideTransition_) this.bgHideTransition_.stop();
if (visible) {
this.show_();
} else {
this.hide_();
}
};
/**
* Sets the transitions to show and hide the popup and background.
* @param {!goog.fx.Transition} popupShowTransition Transition to show the
* popup.
* @param {!goog.fx.Transition} popupHideTransition Transition to hide the
* popup.
* @param {!goog.fx.Transition} bgShowTransition Transition to show
* the background.
* @param {!goog.fx.Transition} bgHideTransition Transition to hide
* the background.
*/
goog.ui.ModalPopup.prototype.setTransition = function(popupShowTransition,
popupHideTransition, bgShowTransition, bgHideTransition) {
this.popupShowTransition_ = popupShowTransition;
this.popupHideTransition_ = popupHideTransition;
this.bgShowTransition_ = bgShowTransition;
this.bgHideTransition_ = bgHideTransition;
};
/**
* Shows the popup.
* @private
*/
goog.ui.ModalPopup.prototype.show_ = function() {
if (!this.dispatchEvent(goog.ui.PopupBase.EventType.BEFORE_SHOW)) {
return;
}
this.resizeBackground_();
this.reposition();
// Listen for keyboard and resize events while the modal popup is visible.
this.getHandler().listen(
this.getDomHelper().getWindow(), goog.events.EventType.RESIZE,
this.resizeBackground_);
this.showPopupElement_(true);
this.focus();
this.visible_ = true;
if (this.popupShowTransition_ && this.bgShowTransition_) {
goog.events.listenOnce(
/** @type {goog.events.EventTarget} */ (this.popupShowTransition_),
goog.fx.Transition.EventType.END, this.onShow, false, this);
this.bgShowTransition_.play();
this.popupShowTransition_.play();
} else {
this.onShow();
}
};
/**
* Hides the popup.
* @private
*/
goog.ui.ModalPopup.prototype.hide_ = function() {
if (!this.dispatchEvent(goog.ui.PopupBase.EventType.BEFORE_HIDE)) {
return;
}
// Stop listening for keyboard and resize events while the modal
// popup is hidden.
this.getHandler().unlisten(
this.getDomHelper().getWindow(), goog.events.EventType.RESIZE,
this.resizeBackground_);
// Set visibility to hidden even if there is a transition. This
// reduces complexity in subclasses who may want to override
// setVisible (such as goog.ui.Dialog).
this.visible_ = false;
if (this.popupHideTransition_ && this.bgHideTransition_) {
goog.events.listenOnce(
/** @type {goog.events.EventTarget} */ (this.popupHideTransition_),
goog.fx.Transition.EventType.END, this.onHide, false, this);
this.bgHideTransition_.play();
// The transition whose END event you are listening to must be played last
// to prevent errors when disposing on hide event, which occur on browsers
// that do not support CSS3 transitions.
this.popupHideTransition_.play();
} else {
this.onHide();
}
};
/**
* Shows or hides the popup element.
* @param {boolean} visible Shows the popup element if true, hides if false.
* @private
*/
goog.ui.ModalPopup.prototype.showPopupElement_ = function(visible) {
if (this.bgIframeEl_) {
goog.style.setElementShown(this.bgIframeEl_, visible);
}
if (this.bgEl_) {
goog.style.setElementShown(this.bgEl_, visible);
}
goog.style.setElementShown(this.getElement(), visible);
goog.style.setElementShown(this.tabCatcherElement_, visible);
};
/**
* Called after the popup is shown. If there is a transition, this
* will be called after the transition completed or stopped.
* @protected
*/
goog.ui.ModalPopup.prototype.onShow = function() {
this.dispatchEvent(goog.ui.PopupBase.EventType.SHOW);
};
/**
* Called after the popup is hidden. If there is a transition, this
* will be called after the transition completed or stopped.
* @protected
*/
goog.ui.ModalPopup.prototype.onHide = function() {
this.showPopupElement_(false);
this.dispatchEvent(goog.ui.PopupBase.EventType.HIDE);
};
/**
* @return {boolean} Whether the modal popup is visible.
*/
goog.ui.ModalPopup.prototype.isVisible = function() {
return this.visible_;
};
/**
* Focuses on the modal popup.
*/
goog.ui.ModalPopup.prototype.focus = function() {
this.focusElement_();
};
/**
* Make the background element the size of the document.
*
* NOTE(user): We must hide the background element before measuring the
* document, otherwise the size of the background will stop the document from
* shrinking to fit a smaller window. This does cause a slight flicker in Linux
* browsers, but should not be a common scenario.
* @private
*/
goog.ui.ModalPopup.prototype.resizeBackground_ = function() {
if (this.bgIframeEl_) {
goog.style.setElementShown(this.bgIframeEl_, false);
}
if (this.bgEl_) {
goog.style.setElementShown(this.bgEl_, false);
}
var doc = this.getDomHelper().getDocument();
var win = goog.dom.getWindow(doc) || window;
// Take the max of document height and view height, in case the document does
// not fill the viewport. Read from both the body element and the html element
// to account for browser differences in treatment of absolutely-positioned
// content.
var viewSize = goog.dom.getViewportSize(win);
var w = Math.max(viewSize.width,
Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth));
var h = Math.max(viewSize.height,
Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight));
if (this.bgIframeEl_) {
goog.style.setElementShown(this.bgIframeEl_, true);
goog.style.setSize(this.bgIframeEl_, w, h);
}
if (this.bgEl_) {
goog.style.setElementShown(this.bgEl_, true);
goog.style.setSize(this.bgEl_, w, h);
}
};
/**
* Centers the modal popup in the viewport, taking scrolling into account.
*/
goog.ui.ModalPopup.prototype.reposition = function() {
// TODO(user): Make this use goog.positioning as in goog.ui.PopupBase?
// Get the current viewport to obtain the scroll offset.
var doc = this.getDomHelper().getDocument();
var win = goog.dom.getWindow(doc) || window;
if (goog.style.getComputedPosition(this.getElement()) == 'fixed') {
var x = 0;
var y = 0;
} else {
var scroll = this.getDomHelper().getDocumentScroll();
var x = scroll.x;
var y = scroll.y;
}
var popupSize = goog.style.getSize(this.getElement());
var viewSize = goog.dom.getViewportSize(win);
// Make sure left and top are non-negatives.
var left = Math.max(x + viewSize.width / 2 - popupSize.width / 2, 0);
var top = Math.max(y + viewSize.height / 2 - popupSize.height / 2, 0);
goog.style.setPosition(this.getElement(), left, top);
// We place the tab catcher at the same position as the dialog to
// prevent IE from scrolling when users try to tab out of the dialog.
goog.style.setPosition(this.tabCatcherElement_, left, top);
};
/**
* Handles focus events. Makes sure that if the user tabs past the
* elements in the modal popup, the focus wraps back to the beginning, and that
* if the user shift-tabs past the front of the modal popup, focus wraps around
* to the end.
* @param {goog.events.BrowserEvent} e Browser's event object.
* @private
*/
goog.ui.ModalPopup.prototype.onFocus_ = function(e) {
if (this.backwardTabWrapInProgress_) {
this.resetBackwardTabWrap_();
} else if (e.target == this.tabCatcherElement_) {
goog.Timer.callOnce(this.focusElement_, 0, this);
}
};
/**
* Moves the focus to the modal popup.
* @private
*/
goog.ui.ModalPopup.prototype.focusElement_ = function() {
try {
if (goog.userAgent.IE) {
// In IE, we must first focus on the body or else focussing on a
// sub-element will not work.
this.getDomHelper().getDocument().body.focus();
}
this.getElement().focus();
} catch (e) {
// Swallow this. IE can throw an error if the element can not be focused.
}
};
/** @override */
goog.ui.ModalPopup.prototype.disposeInternal = function() {
goog.dispose(this.popupShowTransition_);
this.popupShowTransition_ = null;
goog.dispose(this.popupHideTransition_);
this.popupHideTransition_ = null;
goog.dispose(this.bgShowTransition_);
this.bgShowTransition_ = null;
goog.dispose(this.bgHideTransition_);
this.bgHideTransition_ = null;
goog.base(this, 'disposeInternal');
};
| 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 that supports single selection from a dropdown menu,
* with semantics similar to the native HTML <code><select></code>
* element.
*
* @author attila@google.com (Attila Bodis)
* @see ../demos/select.html
*/
goog.provide('goog.ui.Select');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.Role');
goog.require('goog.a11y.aria.State');
goog.require('goog.asserts');
goog.require('goog.events.EventType');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.MenuButton');
goog.require('goog.ui.SelectionModel');
goog.require('goog.ui.registry');
/**
* A selection control. Extends {@link goog.ui.MenuButton} by composing a
* menu with a selection model, and automatically updating the button's caption
* based on the current selection.
*
* Select fires the following events:
* CHANGE - after selection changes.
*
* @param {goog.ui.ControlContent} caption Default caption or existing DOM
* structure to display as the button's caption when nothing is selected.
* @param {goog.ui.Menu=} opt_menu Menu containing selection options.
* @param {goog.ui.ButtonRenderer=} opt_renderer Renderer used to render or
* decorate the control; defaults to {@link goog.ui.MenuButtonRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
* document interaction.
* @constructor
* @extends {goog.ui.MenuButton}
*/
goog.ui.Select = function(caption, opt_menu, opt_renderer, opt_domHelper) {
goog.ui.MenuButton.call(this, caption, opt_menu, opt_renderer, opt_domHelper);
this.setDefaultCaption(caption);
};
goog.inherits(goog.ui.Select, goog.ui.MenuButton);
/**
* The selection model controlling the items in the menu.
* @type {goog.ui.SelectionModel}
* @private
*/
goog.ui.Select.prototype.selectionModel_ = null;
/**
* Default caption to be shown when no option is selected.
* @type {goog.ui.ControlContent}
* @private
*/
goog.ui.Select.prototype.defaultCaption_ = null;
/** @override */
goog.ui.Select.prototype.enterDocument = function() {
goog.ui.Select.superClass_.enterDocument.call(this);
this.updateCaption();
this.listenToSelectionModelEvents_();
};
/**
* Decorates the given element with this control. Overrides the superclass
* implementation by initializing the default caption on the select button.
* @param {Element} element Element to decorate.
* @override
*/
goog.ui.Select.prototype.decorateInternal = function(element) {
goog.ui.Select.superClass_.decorateInternal.call(this, element);
var caption = this.getCaption();
if (caption) {
// Initialize the default caption.
this.setDefaultCaption(caption);
} else {
// There is no default caption; select the first option.
this.setSelectedIndex(0);
}
};
/** @override */
goog.ui.Select.prototype.disposeInternal = function() {
goog.ui.Select.superClass_.disposeInternal.call(this);
if (this.selectionModel_) {
this.selectionModel_.dispose();
this.selectionModel_ = null;
}
this.defaultCaption_ = null;
};
/**
* Handles {@link goog.ui.Component.EventType.ACTION} events dispatched by
* the menu item clicked by the user. Updates the selection model, calls
* the superclass implementation to hide the menu, stops the propagation of
* the event, and dispatches an ACTION event on behalf of the select control
* itself. Overrides {@link goog.ui.MenuButton#handleMenuAction}.
* @param {goog.events.Event} e Action event to handle.
* @override
*/
goog.ui.Select.prototype.handleMenuAction = function(e) {
this.setSelectedItem(/** @type {goog.ui.MenuItem} */ (e.target));
goog.base(this, 'handleMenuAction', e);
// NOTE(user): We should not stop propagation and then fire
// our own ACTION event. Fixing this without breaking anyone
// relying on this event is hard though.
e.stopPropagation();
this.dispatchEvent(goog.ui.Component.EventType.ACTION);
};
/**
* Handles {@link goog.events.EventType.SELECT} events raised by the
* selection model when the selection changes. Updates the contents of the
* select button.
* @param {goog.events.Event} e Selection event to handle.
*/
goog.ui.Select.prototype.handleSelectionChange = function(e) {
var item = this.getSelectedItem();
goog.ui.Select.superClass_.setValue.call(this, item && item.getValue());
this.updateCaption();
};
/**
* Replaces the menu currently attached to the control (if any) with the given
* argument, and updates the selection model. Does nothing if the new menu is
* the same as the old one. Overrides {@link goog.ui.MenuButton#setMenu}.
* @param {goog.ui.Menu} menu New menu to be attached to the menu button.
* @return {goog.ui.Menu|undefined} Previous menu (undefined if none).
* @override
*/
goog.ui.Select.prototype.setMenu = function(menu) {
// Call superclass implementation to replace the menu.
var oldMenu = goog.ui.Select.superClass_.setMenu.call(this, menu);
// Do nothing unless the new menu is different from the current one.
if (menu != oldMenu) {
// Clear the old selection model (if any).
if (this.selectionModel_) {
this.selectionModel_.clear();
}
// Initialize new selection model (unless the new menu is null).
if (menu) {
if (this.selectionModel_) {
menu.forEachChild(function(child, index) {
this.setCorrectAriaRole_(
/** @type {goog.ui.MenuItem|goog.ui.MenuSeparator} */ (child));
this.selectionModel_.addItem(child);
}, this);
} else {
this.createSelectionModel_(menu);
}
}
}
return oldMenu;
};
/**
* Returns the default caption to be shown when no option is selected.
* @return {goog.ui.ControlContent} Default caption.
*/
goog.ui.Select.prototype.getDefaultCaption = function() {
return this.defaultCaption_;
};
/**
* Sets the default caption to the given string or DOM structure.
* @param {goog.ui.ControlContent} caption Default caption to be shown
* when no option is selected.
*/
goog.ui.Select.prototype.setDefaultCaption = function(caption) {
this.defaultCaption_ = caption;
this.updateCaption();
};
/**
* Adds a new menu item at the end of the menu.
* @param {goog.ui.Control} item Menu item to add to the menu.
* @override
*/
goog.ui.Select.prototype.addItem = function(item) {
this.setCorrectAriaRole_(
/** @type {goog.ui.MenuItem|goog.ui.MenuSeparator} */ (item));
goog.ui.Select.superClass_.addItem.call(this, item);
if (this.selectionModel_) {
this.selectionModel_.addItem(item);
} else {
this.createSelectionModel_(this.getMenu());
}
};
/**
* Adds a new menu item at a specific index in the menu.
* @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu item to add to the
* menu.
* @param {number} index Index at which to insert the menu item.
* @override
*/
goog.ui.Select.prototype.addItemAt = function(item, index) {
this.setCorrectAriaRole_(
/** @type {goog.ui.MenuItem|goog.ui.MenuSeparator} */ (item));
goog.ui.Select.superClass_.addItemAt.call(this, item, index);
if (this.selectionModel_) {
this.selectionModel_.addItemAt(item, index);
} else {
this.createSelectionModel_(this.getMenu());
}
};
/**
* Removes an item from the menu and disposes it.
* @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item The menu item to remove.
* @override
*/
goog.ui.Select.prototype.removeItem = function(item) {
goog.ui.Select.superClass_.removeItem.call(this, item);
if (this.selectionModel_) {
this.selectionModel_.removeItem(item);
}
};
/**
* Removes a menu item at a given index in the menu and disposes it.
* @param {number} index Index of item.
* @override
*/
goog.ui.Select.prototype.removeItemAt = function(index) {
goog.ui.Select.superClass_.removeItemAt.call(this, index);
if (this.selectionModel_) {
this.selectionModel_.removeItemAt(index);
}
};
/**
* Selects the specified option (assumed to be in the select menu), and
* deselects the previously selected option, if any. A null argument clears
* the selection.
* @param {goog.ui.MenuItem} item Option to be selected (null to clear
* the selection).
*/
goog.ui.Select.prototype.setSelectedItem = function(item) {
if (this.selectionModel_) {
var prevItem = this.getSelectedItem();
this.selectionModel_.setSelectedItem(item);
if (item != prevItem) {
this.dispatchEvent(goog.ui.Component.EventType.CHANGE);
}
}
};
/**
* Selects the option at the specified index, or clears the selection if the
* index is out of bounds.
* @param {number} index Index of the option to be selected.
*/
goog.ui.Select.prototype.setSelectedIndex = function(index) {
if (this.selectionModel_) {
this.setSelectedItem(/** @type {goog.ui.MenuItem} */
(this.selectionModel_.getItemAt(index)));
}
};
/**
* Selects the first option found with an associated value equal to the
* argument, or clears the selection if no such option is found. A null
* argument also clears the selection. Overrides {@link
* goog.ui.Button#setValue}.
* @param {*} value Value of the option to be selected (null to clear
* the selection).
* @override
*/
goog.ui.Select.prototype.setValue = function(value) {
if (goog.isDefAndNotNull(value) && this.selectionModel_) {
for (var i = 0, item; item = this.selectionModel_.getItemAt(i); i++) {
if (item && typeof item.getValue == 'function' &&
item.getValue() == value) {
this.setSelectedItem(/** @type {goog.ui.MenuItem} */ (item));
return;
}
}
}
this.setSelectedItem(null);
};
/**
* Returns the currently selected option.
* @return {goog.ui.MenuItem} The currently selected option (null if none).
*/
goog.ui.Select.prototype.getSelectedItem = function() {
return this.selectionModel_ ?
/** @type {goog.ui.MenuItem} */ (this.selectionModel_.getSelectedItem()) :
null;
};
/**
* Returns the index of the currently selected option.
* @return {number} 0-based index of the currently selected option (-1 if none).
*/
goog.ui.Select.prototype.getSelectedIndex = function() {
return this.selectionModel_ ? this.selectionModel_.getSelectedIndex() : -1;
};
/**
* @return {goog.ui.SelectionModel} The selection model.
* @protected
*/
goog.ui.Select.prototype.getSelectionModel = function() {
return this.selectionModel_;
};
/**
* Creates a new selection model and sets up an event listener to handle
* {@link goog.events.EventType.SELECT} events dispatched by it.
* @param {goog.ui.Component=} opt_component If provided, will add the
* component's children as items to the selection model.
* @private
*/
goog.ui.Select.prototype.createSelectionModel_ = function(opt_component) {
this.selectionModel_ = new goog.ui.SelectionModel();
if (opt_component) {
opt_component.forEachChild(function(child, index) {
this.setCorrectAriaRole_(
/** @type {goog.ui.MenuItem|goog.ui.MenuSeparator} */ (child));
this.selectionModel_.addItem(child);
}, this);
}
this.listenToSelectionModelEvents_();
};
/**
* Subscribes to events dispatched by the selection model.
* @private
*/
goog.ui.Select.prototype.listenToSelectionModelEvents_ = function() {
if (this.selectionModel_) {
this.getHandler().listen(this.selectionModel_, goog.events.EventType.SELECT,
this.handleSelectionChange);
}
};
/**
* Updates the caption to be shown in the select button. If no option is
* selected and a default caption is set, sets the caption to the default
* caption; otherwise to the empty string.
* @protected
*/
goog.ui.Select.prototype.updateCaption = function() {
var item = this.getSelectedItem();
this.setContent(item ? item.getCaption() : this.defaultCaption_);
};
/**
* Sets the correct ARIA role for the menu item or separator.
* @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item The item to set.
* @private
*/
goog.ui.Select.prototype.setCorrectAriaRole_ = function(item) {
item.setPreferredAriaRole(item instanceof goog.ui.MenuItem ?
goog.a11y.aria.Role.OPTION : goog.a11y.aria.Role.SEPARATOR);
};
/**
* Opens or closes the menu. Overrides {@link goog.ui.MenuButton#setOpen} by
* highlighting the currently selected option on open.
* @param {boolean} open Whether to open or close the menu.
* @param {goog.events.Event=} opt_e Mousedown event that caused the menu to
* be opened.
* @override
*/
goog.ui.Select.prototype.setOpen = function(open, opt_e) {
goog.ui.Select.superClass_.setOpen.call(this, open, opt_e);
if (this.isOpen()) {
this.getMenu().setHighlightedIndex(this.getSelectedIndex());
}
};
// Register a decorator factory function for goog.ui.Selects.
goog.ui.registry.setDecoratorByClassName(
goog.getCssName('goog-select'), function() {
// Select defaults to using MenuButtonRenderer, since it shares its L&F.
return new goog.ui.Select(null);
});
| 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 class for showing popups. A single popup can be
* attached to multiple anchor points. The menu will try to reposition itself
* if it goes outside the viewport.
*
* Decoration is the same as goog.ui.Menu except that the outer DIV can have a
* 'for' property, which is the ID of the element which triggers the popup.
*
* Decorate Example:
* <button id="dButton">Decorated Popup</button>
* <div id="dMenu" for="dButton" class="goog-menu">
* <div class="goog-menuitem">A a</div>
* <div class="goog-menuitem">B b</div>
* <div class="goog-menuitem">C c</div>
* <div class="goog-menuitem">D d</div>
* <div class="goog-menuitem">E e</div>
* <div class="goog-menuitem">F f</div>
* </div>
*
* TESTED=FireFox 2.0, IE6, Opera 9, Chrome.
* TODO(user): Key handling is flakey in Opera and Chrome
*
* @see ../demos/popupmenu.html
*/
goog.provide('goog.ui.PopupMenu');
goog.require('goog.events.EventType');
goog.require('goog.positioning.AnchoredViewportPosition');
goog.require('goog.positioning.Corner');
goog.require('goog.positioning.MenuAnchoredPosition');
goog.require('goog.positioning.ViewportClientPosition');
goog.require('goog.structs');
goog.require('goog.structs.Map');
goog.require('goog.style');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.Menu');
goog.require('goog.ui.PopupBase');
goog.require('goog.userAgent');
/**
* A basic menu class.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @param {goog.ui.MenuRenderer=} opt_renderer Renderer used to render or
* decorate the container; defaults to {@link goog.ui.MenuRenderer}.
* @extends {goog.ui.Menu}
* @constructor
*/
goog.ui.PopupMenu = function(opt_domHelper, opt_renderer) {
goog.ui.Menu.call(this, opt_domHelper, opt_renderer);
this.setAllowAutoFocus(true);
// Popup menus are hidden by default.
this.setVisible(false, true);
/**
* Map of attachment points for the menu. Key -> Object
* @type {!goog.structs.Map}
* @private
*/
this.targets_ = new goog.structs.Map();
};
goog.inherits(goog.ui.PopupMenu, goog.ui.Menu);
/**
* If true, then if the menu will toggle off if it is already visible.
* @type {boolean}
* @private
*/
goog.ui.PopupMenu.prototype.toggleMode_ = false;
/**
* Time that the menu was last shown.
* @type {number}
* @private
*/
goog.ui.PopupMenu.prototype.lastHide_ = 0;
/**
* Current element where the popup menu is anchored.
* @type {Element}
* @private
*/
goog.ui.PopupMenu.prototype.currentAnchor_ = null;
/**
* Decorate an existing HTML structure with the menu. Menu items will be
* constructed from elements with classname 'goog-menuitem', separators will be
* made from HR elements.
* @param {Element} element Element to decorate.
* @override
*/
goog.ui.PopupMenu.prototype.decorateInternal = function(element) {
goog.ui.PopupMenu.superClass_.decorateInternal.call(this, element);
// 'for' is a custom attribute for attaching the menu to a click target
var htmlFor = element.getAttribute('for') || element.htmlFor;
if (htmlFor) {
this.attach(
this.getDomHelper().getElement(htmlFor),
goog.positioning.Corner.BOTTOM_LEFT);
}
};
/** @override */
goog.ui.PopupMenu.prototype.enterDocument = function() {
goog.ui.PopupMenu.superClass_.enterDocument.call(this);
goog.structs.forEach(this.targets_, this.attachEvent_, this);
var handler = this.getHandler();
handler.listen(
this, goog.ui.Component.EventType.ACTION, this.onAction_);
handler.listen(this.getDomHelper().getDocument(),
goog.events.EventType.MOUSEDOWN, this.onDocClick, true);
// Webkit doesn't fire a mousedown event when opening the context menu,
// but we need one to update menu visibility properly. So in Safari handle
// contextmenu mouse events like mousedown.
// {@link http://bugs.webkit.org/show_bug.cgi?id=6595}
if (goog.userAgent.WEBKIT) {
handler.listen(this.getDomHelper().getDocument(),
goog.events.EventType.CONTEXTMENU, this.onDocClick, true);
}
};
/**
* Attaches the menu to a new popup position and anchor element. A menu can
* only be attached to an element once, since attaching the same menu for
* multiple positions doesn't make sense.
*
* @param {Element} element Element whose click event should trigger the menu.
* @param {goog.positioning.Corner=} opt_targetCorner Corner of the target that
* the menu should be anchored to.
* @param {goog.positioning.Corner=} opt_menuCorner Corner of the menu that
* should be anchored.
* @param {boolean=} opt_contextMenu Whether the menu should show on
* {@link goog.events.EventType.CONTEXTMENU} events, false if it should
* show on {@link goog.events.EventType.MOUSEDOWN} events. Default is
* MOUSEDOWN.
* @param {goog.math.Box=} opt_margin Margin for the popup used in positioning
* algorithms.
*/
goog.ui.PopupMenu.prototype.attach = function(
element, opt_targetCorner, opt_menuCorner, opt_contextMenu, opt_margin) {
if (this.isAttachTarget(element)) {
// Already in the popup, so just return.
return;
}
var target = this.createAttachTarget(element, opt_targetCorner,
opt_menuCorner, opt_contextMenu, opt_margin);
if (this.isInDocument()) {
this.attachEvent_(target);
}
};
/**
* Creates an object describing how the popup menu should be attached to the
* anchoring element based on the given parameters. The created object is
* stored, keyed by {@code element} and is retrievable later by invoking
* {@link #getAttachTarget(element)} at a later point.
*
* Subclass may add more properties to the returned object, as needed.
*
* @param {Element} element Element whose click event should trigger the menu.
* @param {goog.positioning.Corner=} opt_targetCorner Corner of the target that
* the menu should be anchored to.
* @param {goog.positioning.Corner=} opt_menuCorner Corner of the menu that
* should be anchored.
* @param {boolean=} opt_contextMenu Whether the menu should show on
* {@link goog.events.EventType.CONTEXTMENU} events, false if it should
* show on {@link goog.events.EventType.MOUSEDOWN} events. Default is
* MOUSEDOWN.
* @param {goog.math.Box=} opt_margin Margin for the popup used in positioning
* algorithms.
*
* @return {Object} An object that describes how the popup menu should be
* attached to the anchoring element.
*
* @protected
*/
goog.ui.PopupMenu.prototype.createAttachTarget = function(
element, opt_targetCorner, opt_menuCorner, opt_contextMenu, opt_margin) {
if (!element) {
return null;
}
var target = {
element_: element,
targetCorner_: opt_targetCorner,
menuCorner_: opt_menuCorner,
eventType_: opt_contextMenu ? goog.events.EventType.CONTEXTMENU :
goog.events.EventType.MOUSEDOWN,
margin_: opt_margin
};
this.targets_.set(goog.getUid(element), target);
return target;
};
/**
* Returns the object describing how the popup menu should be attach to given
* element or {@code null}. The object is created and the association is formed
* when {@link #attach} is invoked.
*
* @param {Element} element DOM element.
* @return {Object} The object created when {@link attach} is invoked on
* {@code element}. Returns {@code null} if the element does not trigger
* the menu (i.e. {@link attach} has never been invoked on
* {@code element}).
* @protected
*/
goog.ui.PopupMenu.prototype.getAttachTarget = function(element) {
return element ?
/** @type {Object} */(this.targets_.get(goog.getUid(element))) :
null;
};
/**
* @param {Element} element Any DOM element.
* @return {boolean} Whether clicking on the given element will trigger the
* menu.
*
* @protected
*/
goog.ui.PopupMenu.prototype.isAttachTarget = function(element) {
return element ? this.targets_.containsKey(goog.getUid(element)) : false;
};
/**
* @return {Element} The current element where the popup is anchored, if it's
* visible.
*/
goog.ui.PopupMenu.prototype.getAttachedElement = function() {
return this.currentAnchor_;
};
/**
* Attaches an event listener to a target
* @param {Object} target The target to attach an event to.
* @private
*/
goog.ui.PopupMenu.prototype.attachEvent_ = function(target) {
this.getHandler().listen(
target.element_, target.eventType_, this.onTargetClick_);
};
/**
* Detaches all listeners
*/
goog.ui.PopupMenu.prototype.detachAll = function() {
if (this.isInDocument()) {
var keys = this.targets_.getKeys();
for (var i = 0; i < keys.length; i++) {
this.detachEvent_(/** @type {Object} */ (this.targets_.get(keys[i])));
}
}
this.targets_.clear();
};
/**
* Detaches a menu from a given element.
* @param {Element} element Element whose click event should trigger the menu.
*/
goog.ui.PopupMenu.prototype.detach = function(element) {
if (!this.isAttachTarget(element)) {
throw Error('Menu not attached to provided element, unable to detach.');
}
var key = goog.getUid(element);
if (this.isInDocument()) {
this.detachEvent_(/** @type {Object} */ (this.targets_.get(key)));
}
this.targets_.remove(key);
};
/**
* Detaches an event listener to a target
* @param {Object} target The target to detach events from.
* @private
*/
goog.ui.PopupMenu.prototype.detachEvent_ = function(target) {
this.getHandler().unlisten(
target.element_, target.eventType_, this.onTargetClick_);
};
/**
* Sets whether the menu should toggle if it is already open. For context
* menus this should be false, for toolbar menus it makes more sense to be true.
* @param {boolean} toggle The new toggle mode.
*/
goog.ui.PopupMenu.prototype.setToggleMode = function(toggle) {
this.toggleMode_ = toggle;
};
/**
* Gets whether the menu is in toggle mode
* @return {boolean} toggle.
*/
goog.ui.PopupMenu.prototype.getToggleMode = function() {
return this.toggleMode_;
};
/**
* Show the menu using given positioning object.
* @param {goog.positioning.AbstractPosition} position The positioning instance.
* @param {goog.positioning.Corner=} opt_menuCorner The corner of the menu to be
* positioned.
* @param {goog.math.Box=} opt_margin A margin specified in pixels.
* @param {Element=} opt_anchor The element which acts as visual anchor for this
* menu.
*/
goog.ui.PopupMenu.prototype.showWithPosition = function(position,
opt_menuCorner, opt_margin, opt_anchor) {
var isVisible = this.isVisible();
if (this.isOrWasRecentlyVisible() && this.toggleMode_) {
this.hide();
return;
}
// Set current anchor before dispatching BEFORE_SHOW. This is typically useful
// when we would need to make modifications based on the current anchor to the
// menu just before displaying it.
this.currentAnchor_ = opt_anchor || null;
// Notify event handlers that the menu is about to be shown.
if (!this.dispatchEvent(goog.ui.Component.EventType.BEFORE_SHOW)) {
return;
}
var menuCorner = typeof opt_menuCorner != 'undefined' ?
opt_menuCorner :
goog.positioning.Corner.TOP_START;
// This is a little hacky so that we can position the menu with minimal
// flicker.
if (!isVisible) {
// On IE, setting visibility = 'hidden' on a visible menu
// will cause a blur, forcing the menu to close immediately.
this.getElement().style.visibility = 'hidden';
}
goog.style.setElementShown(this.getElement(), true);
position.reposition(this.getElement(), menuCorner, opt_margin);
if (!isVisible) {
this.getElement().style.visibility = 'visible';
}
this.setHighlightedIndex(-1);
// setVisible dispatches a goog.ui.Component.EventType.SHOW event, which may
// be canceled to prevent the menu from being shown.
this.setVisible(true);
};
/**
* Show the menu at a given attached target.
* @param {Object} target Popup target.
* @param {number} x The client-X associated with the show event.
* @param {number} y The client-Y associated with the show event.
* @protected
*/
goog.ui.PopupMenu.prototype.showMenu = function(target, x, y) {
var position = goog.isDef(target.targetCorner_) ?
new goog.positioning.AnchoredViewportPosition(target.element_,
target.targetCorner_, true) :
new goog.positioning.ViewportClientPosition(x, y);
if (position.setLastResortOverflow) {
// This is a ViewportClientPosition, so we can set the overflow policy.
// Allow the menu to slide from the corner rather than clipping if it is
// completely impossible to fit it otherwise.
position.setLastResortOverflow(goog.positioning.Overflow.ADJUST_X |
goog.positioning.Overflow.ADJUST_Y);
}
this.showWithPosition(position, target.menuCorner_, target.margin_,
target.element_);
};
/**
* Shows the menu immediately at the given client coordinates.
* @param {number} x The client-X associated with the show event.
* @param {number} y The client-Y associated with the show event.
* @param {goog.positioning.Corner=} opt_menuCorner Corner of the menu that
* should be anchored.
*/
goog.ui.PopupMenu.prototype.showAt = function(x, y, opt_menuCorner) {
this.showWithPosition(
new goog.positioning.ViewportClientPosition(x, y), opt_menuCorner);
};
/**
* Shows the menu immediately attached to the given element
* @param {Element} element The element to show at.
* @param {goog.positioning.Corner} targetCorner The corner of the target to
* anchor to.
* @param {goog.positioning.Corner=} opt_menuCorner Corner of the menu that
* should be anchored.
*/
goog.ui.PopupMenu.prototype.showAtElement = function(element, targetCorner,
opt_menuCorner) {
this.showWithPosition(
new goog.positioning.MenuAnchoredPosition(element, targetCorner, true),
opt_menuCorner, null, element);
};
/**
* Hides the menu.
*/
goog.ui.PopupMenu.prototype.hide = function() {
if (!this.isVisible()) {
return;
}
// setVisible dispatches a goog.ui.Component.EventType.HIDE event, which may
// be canceled to prevent the menu from being hidden.
this.setVisible(false);
if (!this.isVisible()) {
// HIDE event wasn't canceled; the menu is now hidden.
this.lastHide_ = goog.now();
this.currentAnchor_ = null;
}
};
/**
* Returns whether the menu is currently visible or was visible within about
* 150 ms ago. This stops the menu toggling back on if the toggleMode == false.
* @return {boolean} Whether the popup is currently visible or was visible
* within about 150 ms ago.
*/
goog.ui.PopupMenu.prototype.isOrWasRecentlyVisible = function() {
return this.isVisible() || this.wasRecentlyHidden();
};
/**
* Used to stop the menu toggling back on if the toggleMode == false.
* @return {boolean} Whether the menu was recently hidden.
* @protected
*/
goog.ui.PopupMenu.prototype.wasRecentlyHidden = function() {
return goog.now() - this.lastHide_ < goog.ui.PopupBase.DEBOUNCE_DELAY_MS;
};
/**
* Dismiss the popup menu when an action fires.
* @param {goog.events.Event=} opt_e The optional event.
* @private
*/
goog.ui.PopupMenu.prototype.onAction_ = function(opt_e) {
this.hide();
};
/**
* Handles a browser event on one of the popup targets
* @param {goog.events.BrowserEvent} e The browser event.
* @private
*/
goog.ui.PopupMenu.prototype.onTargetClick_ = function(e) {
var keys = this.targets_.getKeys();
for (var i = 0; i < keys.length; i++) {
var target = /** @type {Object} */(this.targets_.get(keys[i]));
if (target.element_ == e.currentTarget) {
this.showMenu(target,
/** @type {number} */ (e.clientX),
/** @type {number} */ (e.clientY));
e.preventDefault();
e.stopPropagation();
return;
}
}
};
/**
* Handles click events that propagate to the document.
* @param {goog.events.BrowserEvent} e The browser event.
* @protected
*/
goog.ui.PopupMenu.prototype.onDocClick = function(e) {
if (this.isVisible() &&
!this.containsElement(/** @type {Element} */ (e.target))) {
this.hide();
}
};
/**
* Handles the key event target loosing focus.
* @param {goog.events.BrowserEvent} e The browser event.
* @protected
* @override
*/
goog.ui.PopupMenu.prototype.handleBlur = function(e) {
goog.ui.PopupMenu.superClass_.handleBlur.call(this, e);
this.hide();
};
/** @override */
goog.ui.PopupMenu.prototype.disposeInternal = function() {
// Always call the superclass' disposeInternal() first (Bug 715885).
goog.ui.PopupMenu.superClass_.disposeInternal.call(this);
// Disposes of the attachment target map.
if (this.targets_) {
this.targets_.clear();
delete this.targets_;
}
};
| 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 renderer.
*
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.ui.ToolbarMenuButtonRenderer');
goog.require('goog.ui.MenuButtonRenderer');
/**
* Toolbar-specific renderer for {@link goog.ui.MenuButton}s, based on {@link
* goog.ui.MenuButtonRenderer}.
* @constructor
* @extends {goog.ui.MenuButtonRenderer}
*/
goog.ui.ToolbarMenuButtonRenderer = function() {
goog.ui.MenuButtonRenderer.call(this);
};
goog.inherits(goog.ui.ToolbarMenuButtonRenderer, goog.ui.MenuButtonRenderer);
goog.addSingletonGetter(goog.ui.ToolbarMenuButtonRenderer);
/**
* Default CSS class to be applied to the root element of menu buttons rendered
* by this renderer.
* @type {string}
*/
goog.ui.ToolbarMenuButtonRenderer.CSS_CLASS =
goog.getCssName('goog-toolbar-menu-button');
/**
* Returns the CSS class to be applied to the root element of menu buttons
* rendered using this renderer.
* @return {string} Renderer-specific CSS class.
* @override
*/
goog.ui.ToolbarMenuButtonRenderer.prototype.getCssClass = function() {
return goog.ui.ToolbarMenuButtonRenderer.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 Class for splitting two areas with draggable control for
* changing size.
*
* The DOM that is created (or that can be decorated) looks like this:
* <div class='goog-splitpane'>
* <div class='goog-splitpane-first-container'></div>
* <div class='goog-splitpane-second-container'></div>
* <div class='goog-splitpane-handle'></div>
* </div>
*
* The content to be split goes in the first and second DIVs, the third one
* is for managing (and styling) the splitter handle.
*
* @see ../demos/splitpane.html
*/
goog.provide('goog.ui.SplitPane');
goog.provide('goog.ui.SplitPane.Orientation');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.events.EventType');
goog.require('goog.fx.Dragger');
goog.require('goog.fx.Dragger.EventType');
goog.require('goog.math.Rect');
goog.require('goog.math.Size');
goog.require('goog.style');
goog.require('goog.ui.Component');
goog.require('goog.ui.Component.EventType');
goog.require('goog.userAgent');
/**
* A left/right up/down Container SplitPane.
* Create SplitPane with two goog.ui.Component opjects to split.
* TODO(user): Support minimum splitpane size.
* TODO(user): Allow component change/orientation after init.
* TODO(user): Support hiding either side of handle (plus handle).
* TODO(user): Look at setBorderBoxSize fixes and revist borderwidth code.
*
* @param {goog.ui.Component} firstComponent Left or Top component.
* @param {goog.ui.Component} secondComponent Right or Bottom component.
* @param {goog.ui.SplitPane.Orientation} orientation SplitPane orientation.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @extends {goog.ui.Component}
* @constructor
*/
goog.ui.SplitPane = function(firstComponent, secondComponent, orientation,
opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* The orientation of the containers.
* @type {goog.ui.SplitPane.Orientation}
* @private
*/
this.orientation_ = orientation;
/**
* The left/top component.
* @type {goog.ui.Component}
* @private
*/
this.firstComponent_ = firstComponent;
this.addChild(firstComponent);
/**
* The right/bottom component.
* @type {goog.ui.Component}
* @private
*/
this.secondComponent_ = secondComponent;
this.addChild(secondComponent);
};
goog.inherits(goog.ui.SplitPane, goog.ui.Component);
/**
* Events.
* @enum {string}
*/
goog.ui.SplitPane.EventType = {
/**
* Dispatched after handle drag.
*/
HANDLE_DRAG: 'handle_drag',
/**
* Dispatched after handle drag end.
*/
HANDLE_DRAG_END: 'handle_drag_end'
};
/**
* CSS class names for splitpane outer container.
* @type {string}
* @private
*/
goog.ui.SplitPane.CLASS_NAME_ = goog.getCssName('goog-splitpane');
/**
* CSS class name for first splitpane container.
* @type {string}
* @private
*/
goog.ui.SplitPane.FIRST_CONTAINER_CLASS_NAME_ =
goog.getCssName('goog-splitpane-first-container');
/**
* CSS class name for second splitpane container.
* @type {string}
* @private
*/
goog.ui.SplitPane.SECOND_CONTAINER_CLASS_NAME_ =
goog.getCssName('goog-splitpane-second-container');
/**
* CSS class name for the splitpane handle.
* @type {string}
* @private
*/
goog.ui.SplitPane.HANDLE_CLASS_NAME_ = goog.getCssName('goog-splitpane-handle');
/**
* CSS class name for the splitpane handle in horizontal orientation.
* @type {string}
* @private
*/
goog.ui.SplitPane.HANDLE_CLASS_NAME_HORIZONTAL_ =
goog.getCssName('goog-splitpane-handle-horizontal');
/**
* CSS class name for the splitpane handle in horizontal orientation.
* @type {string}
* @private
*/
goog.ui.SplitPane.HANDLE_CLASS_NAME_VERTICAL_ =
goog.getCssName('goog-splitpane-handle-vertical');
/**
* The dragger to move the drag handle.
* @type {goog.fx.Dragger?}
* @private
*/
goog.ui.SplitPane.prototype.splitDragger_ = null;
/**
* The left/top component dom container.
* @type {Element}
* @private
*/
goog.ui.SplitPane.prototype.firstComponentContainer_ = null;
/**
* The right/bottom component dom container.
* @type {Element}
* @private
*/
goog.ui.SplitPane.prototype.secondComponentContainer_ = null;
/**
* The size (width or height) of the splitpane handle, default = 5.
* @type {number}
* @private
*/
goog.ui.SplitPane.prototype.handleSize_ = 5;
/**
* The initial size (width or height) of the left or top component.
* @type {?number}
* @private
*/
goog.ui.SplitPane.prototype.initialSize_ = null;
/**
* The saved size (width or height) of the left or top component on a
* double-click (snap).
* This needs to be saved so it can be restored after another double-click.
* @type {?number}
* @private
*/
goog.ui.SplitPane.prototype.savedSnapSize_ = null;
/**
* The first component size, so we don't change it on a window resize.
* @type {?number}
* @private
*/
goog.ui.SplitPane.prototype.firstComponentSize_ = null;
/**
* If we resize as they user moves the handle (default = true).
* @type {boolean}
* @private
*/
goog.ui.SplitPane.prototype.continuousResize_ = true;
/**
* Iframe overlay to prevent iframes from grabbing events.
* @type {Element}
* @private
*/
goog.ui.SplitPane.prototype.iframeOverlay_ = null;
/**
* Z indices for iframe overlay and splitter handle.
* @enum {number}
* @private
*/
goog.ui.SplitPane.IframeOverlayIndex_ = {
HIDDEN: -1,
OVERLAY: 1,
SPLITTER_HANDLE: 2
};
/**
* Orientation values for the splitpane.
* @enum {string}
*/
goog.ui.SplitPane.Orientation = {
/**
* Horizontal orientation means splitter moves right-left.
*/
HORIZONTAL: 'horizontal',
/**
* Vertical orientation means splitter moves up-down.
*/
VERTICAL: 'vertical'
};
/**
* Create the DOM node & text node needed for the splitpane.
* @override
*/
goog.ui.SplitPane.prototype.createDom = function() {
var dom = this.getDomHelper();
// Create the components.
var firstContainer = dom.createDom('div',
goog.ui.SplitPane.FIRST_CONTAINER_CLASS_NAME_);
var secondContainer = dom.createDom('div',
goog.ui.SplitPane.SECOND_CONTAINER_CLASS_NAME_);
var splitterHandle = dom.createDom('div',
goog.ui.SplitPane.HANDLE_CLASS_NAME_);
// Create the primary element, a DIV that holds the two containers and handle.
this.setElementInternal(dom.createDom('div', goog.ui.SplitPane.CLASS_NAME_,
firstContainer, secondContainer, splitterHandle));
this.firstComponentContainer_ = firstContainer;
this.secondComponentContainer_ = secondContainer;
this.splitpaneHandle_ = splitterHandle;
this.setUpHandle_();
this.finishSetup_();
};
/**
* Determines if a given element can be decorated by this type of component.
* @param {Element} element Element to decorate.
* @return {boolean} True if the element can be decorated, false otherwise.
* @override
*/
goog.ui.SplitPane.prototype.canDecorate = function(element) {
var className = goog.ui.SplitPane.FIRST_CONTAINER_CLASS_NAME_;
var firstContainer = this.getElementToDecorate_(element, className);
if (!firstContainer) {
return false;
}
// Since we have this component, save it so we don't have to get it
// again in decorateInternal. Same w/other components.
this.firstComponentContainer_ = firstContainer;
className = goog.ui.SplitPane.SECOND_CONTAINER_CLASS_NAME_;
var secondContainer = this.getElementToDecorate_(element, className);
if (!secondContainer) {
return false;
}
this.secondComponentContainer_ = secondContainer;
className = goog.ui.SplitPane.HANDLE_CLASS_NAME_;
var splitpaneHandle = this.getElementToDecorate_(element, className);
if (!splitpaneHandle) {
return false;
}
this.splitpaneHandle_ = splitpaneHandle;
// We found all the components we're looking for, so return true.
return true;
};
/**
* Obtains the element to be decorated by class name. If multiple such elements
* are found, preference is given to those directly attached to the specified
* root element.
* @param {Element} rootElement The root element from which to retrieve the
* element to be decorated.
* @param {!string} className The target class name.
* @return {Element} The element to decorate.
* @private
*/
goog.ui.SplitPane.prototype.getElementToDecorate_ = function(rootElement,
className) {
// Decorate the root element's children, if available.
var childElements = goog.dom.getChildren(rootElement);
for (var i = 0; i < childElements.length; i++) {
var childElement = childElements[i];
if (goog.dom.classes.has(childElement, className)) {
return childElement;
}
}
// Default to the first descendent element with the correct class.
return goog.dom.getElementsByTagNameAndClass(
null, className, rootElement)[0];
};
/**
* Decorates the given HTML element as a SplitPane. Overrides {@link
* goog.ui.Component#decorateInternal}. Considered protected.
* @param {Element} element Element (SplitPane div) to decorate.
* @protected
* @override
*/
goog.ui.SplitPane.prototype.decorateInternal = function(element) {
goog.base(this, 'decorateInternal', element);
this.setUpHandle_();
var elSize = goog.style.getBorderBoxSize(element);
this.setSize(new goog.math.Size(elSize.width, elSize.height));
this.finishSetup_();
};
/**
* Parent the passed in components to the split containers. Call their
* createDom methods if necessary.
* @private
*/
goog.ui.SplitPane.prototype.finishSetup_ = function() {
var dom = this.getDomHelper();
if (!this.firstComponent_.getElement()) {
this.firstComponent_.createDom();
}
dom.appendChild(this.firstComponentContainer_,
this.firstComponent_.getElement());
if (!this.secondComponent_.getElement()) {
this.secondComponent_.createDom();
}
dom.appendChild(this.secondComponentContainer_,
this.secondComponent_.getElement());
this.splitDragger_ = new goog.fx.Dragger(this.splitpaneHandle_,
this.splitpaneHandle_);
this.firstComponentContainer_.style.position = 'absolute';
this.secondComponentContainer_.style.position = 'absolute';
var handleStyle = this.splitpaneHandle_.style;
handleStyle.position = 'absolute';
handleStyle.overflow = 'hidden';
handleStyle.zIndex =
goog.ui.SplitPane.IframeOverlayIndex_.SPLITTER_HANDLE;
};
/**
* Setup all events and do an initial resize.
* @override
*/
goog.ui.SplitPane.prototype.enterDocument = function() {
goog.base(this, 'enterDocument');
// If position is not set in the inline style of the element, it is not
// possible to get the element's real CSS position until the element is in
// the document.
// When position:relative is set in the CSS and the element is not in the
// document, Safari, Chrome, and Opera always return the empty string; while
// IE always return "static".
// Do the final check to see if element's position is set as "relative",
// "absolute" or "fixed".
var element = this.getElement();
if (goog.style.getComputedPosition(element) == 'static') {
element.style.position = 'relative';
}
this.getHandler().
listen(this.splitpaneHandle_, goog.events.EventType.DBLCLICK,
this.handleDoubleClick_).
listen(this.splitDragger_, goog.fx.Dragger.EventType.START,
this.handleDragStart_).
listen(this.splitDragger_, goog.fx.Dragger.EventType.DRAG,
this.handleDrag_).
listen(this.splitDragger_, goog.fx.Dragger.EventType.END,
this.handleDragEnd_);
this.setFirstComponentSize(this.initialSize_);
};
/**
* Sets the initial size of the left or top component.
* @param {number} size The size in Pixels of the container.
*/
goog.ui.SplitPane.prototype.setInitialSize = function(size) {
this.initialSize_ = size;
};
/**
* Sets the SplitPane handle size.
* TODO(user): Make sure this works after initialization.
* @param {number} size The size of the handle in pixels.
*/
goog.ui.SplitPane.prototype.setHandleSize = function(size) {
this.handleSize_ = size;
};
/**
* Sets whether we resize on handle drag.
* @param {boolean} continuous The continuous resize value.
*/
goog.ui.SplitPane.prototype.setContinuousResize = function(continuous) {
this.continuousResize_ = continuous;
};
/**
* Returns whether the orientation for the split pane is vertical
* or not.
* @return {boolean} True if the orientation is vertical, false otherwise.
*/
goog.ui.SplitPane.prototype.isVertical = function() {
return this.orientation_ == goog.ui.SplitPane.Orientation.VERTICAL;
};
/**
* Initializes the handle by assigning the correct height/width and adding
* the correct class as per the orientation.
* @private
*/
goog.ui.SplitPane.prototype.setUpHandle_ = function() {
if (this.isVertical()) {
this.splitpaneHandle_.style.height = this.handleSize_ + 'px';
goog.dom.classes.add(this.splitpaneHandle_,
goog.ui.SplitPane.HANDLE_CLASS_NAME_VERTICAL_);
} else {
this.splitpaneHandle_.style.width = this.handleSize_ + 'px';
goog.dom.classes.add(this.splitpaneHandle_,
goog.ui.SplitPane.HANDLE_CLASS_NAME_HORIZONTAL_);
}
};
/**
* Sets the orientation class for the split pane handle.
* @protected
*/
goog.ui.SplitPane.prototype.setOrientationClassForHandle = function() {
if (this.isVertical()) {
goog.dom.classes.swap(this.splitpaneHandle_,
goog.ui.SplitPane.HANDLE_CLASS_NAME_HORIZONTAL_,
goog.ui.SplitPane.HANDLE_CLASS_NAME_VERTICAL_);
} else {
goog.dom.classes.swap(this.splitpaneHandle_,
goog.ui.SplitPane.HANDLE_CLASS_NAME_VERTICAL_,
goog.ui.SplitPane.HANDLE_CLASS_NAME_HORIZONTAL_);
}
};
/**
* Sets the orientation of the split pane.
* @param {goog.ui.SplitPane.Orientation} orientation SplitPane orientation.
*/
goog.ui.SplitPane.prototype.setOrientation = function(orientation) {
if (this.orientation_ != orientation) {
this.orientation_ = orientation;
var isVertical = this.isVertical();
// If the split pane is already in document, then the positions and sizes
// need to be adjusted.
if (this.isInDocument()) {
this.setOrientationClassForHandle();
// TODO(user): Should handleSize_ and initialSize_ also be adjusted ?
if (goog.isNumber(this.firstComponentSize_)) {
var splitpaneSize = goog.style.getBorderBoxSize(this.getElement());
var ratio = isVertical ? splitpaneSize.height / splitpaneSize.width :
splitpaneSize.width / splitpaneSize.height;
// TODO(user): Fix the behaviour for the case when the handle is
// placed on either of the edges of the split pane. Also, similar
// behaviour is present in {@link #setSize}. Probably need to modify
// {@link #setFirstComponentSize}.
this.setFirstComponentSize(this.firstComponentSize_ * ratio);
} else {
this.setFirstComponentSize();
}
}
}
};
/**
* Gets the orientation of the split pane.
* @return {goog.ui.SplitPane.Orientation} The orientation.
*/
goog.ui.SplitPane.prototype.getOrientation = function() {
return this.orientation_;
};
/**
* Move and resize a container. The sizing changes the BorderBoxSize.
* @param {Element} element The element to move and size.
* @param {goog.math.Rect} rect The top, left, width and height to change to.
* @private
*/
goog.ui.SplitPane.prototype.moveAndSize_ = function(element, rect) {
goog.style.setPosition(element, rect.left, rect.top);
// TODO(user): Add a goog.math.Size.max call for below.
goog.style.setBorderBoxSize(element,
new goog.math.Size(Math.max(rect.width, 0), Math.max(rect.height, 0)));
};
/**
* @return {?number} The size of the left/top component.
*/
goog.ui.SplitPane.prototype.getFirstComponentSize = function() {
return this.firstComponentSize_;
};
/**
* Set the size of the left/top component, and resize the other component based
* on that size and handle size.
* @param {?number=} opt_size The size of the top or left, in pixels.
*/
goog.ui.SplitPane.prototype.setFirstComponentSize = function(opt_size) {
var top = 0, left = 0;
var splitpaneSize = goog.style.getBorderBoxSize(this.getElement());
var isVertical = this.isVertical();
// Figure out first component size; it's either passed in, taken from the
// saved size, or is half of the total size.
var firstComponentSize = goog.isNumber(opt_size) ? opt_size :
goog.isNumber(this.firstComponentSize_) ? this.firstComponentSize_ :
Math.floor((isVertical ? splitpaneSize.height : splitpaneSize.width) / 2);
this.firstComponentSize_ = firstComponentSize;
var firstComponentWidth;
var firstComponentHeight;
var secondComponentWidth;
var secondComponentHeight;
var handleWidth;
var handleHeight;
var secondComponentLeft;
var secondComponentTop;
var handleLeft;
var handleTop;
if (isVertical) {
// Width for the handle and the first and second components will be the
// width of the split pane. The height for the first component will be
// the calculated first component size. The height for the second component
// will be the total height minus the heights of the first component and
// the handle.
firstComponentHeight = firstComponentSize;
firstComponentWidth = splitpaneSize.width;
handleWidth = splitpaneSize.width;
handleHeight = this.handleSize_;
secondComponentHeight = splitpaneSize.height - firstComponentHeight -
handleHeight;
secondComponentWidth = splitpaneSize.width;
handleTop = top + firstComponentHeight;
handleLeft = left;
secondComponentTop = handleTop + handleHeight;
secondComponentLeft = left;
} else {
// Height for the handle and the first and second components will be the
// height of the split pane. The width for the first component will be
// the calculated first component size. The width for the second component
// will be the total width minus the widths of the first component and
// the handle.
firstComponentWidth = firstComponentSize;
firstComponentHeight = splitpaneSize.height;
handleWidth = this.handleSize_;
handleHeight = splitpaneSize.height;
secondComponentWidth = splitpaneSize.width - firstComponentWidth -
handleWidth;
secondComponentHeight = splitpaneSize.height;
handleLeft = left + firstComponentWidth;
handleTop = top;
secondComponentLeft = handleLeft + handleWidth;
secondComponentTop = top;
}
// Now move and size the containers.
this.moveAndSize_(this.firstComponentContainer_,
new goog.math.Rect(left, top, firstComponentWidth, firstComponentHeight));
if (typeof this.firstComponent_.resize == 'function') {
this.firstComponent_.resize(new goog.math.Size(
firstComponentWidth, firstComponentHeight));
}
this.moveAndSize_(this.splitpaneHandle_, new goog.math.Rect(handleLeft,
handleTop, handleWidth, handleHeight));
this.moveAndSize_(this.secondComponentContainer_,
new goog.math.Rect(secondComponentLeft, secondComponentTop,
secondComponentWidth, secondComponentHeight));
if (typeof this.secondComponent_.resize == 'function') {
this.secondComponent_.resize(new goog.math.Size(secondComponentWidth,
secondComponentHeight));
}
// Fire a CHANGE event.
this.dispatchEvent(goog.ui.Component.EventType.CHANGE);
};
/**
* Dummy object to work around compiler warning.
* TODO(arv): Fix compiler or refactor to not depend on resize()
* @private
* @type {Object}
*/
goog.ui.SplitPane.resizeWarningWorkaround_ = {
/**
* @param {goog.math.Size} size The new size.
*/
resize: function(size) {}
};
/**
* Set the size of the splitpane. This is usually called by the controlling
* application. This will set the SplitPane BorderBoxSize.
* @param {goog.math.Size} size The size to set the splitpane.
*/
goog.ui.SplitPane.prototype.setSize = function(size) {
goog.style.setBorderBoxSize(this.getElement(), size);
if (this.iframeOverlay_) {
goog.style.setBorderBoxSize(this.iframeOverlay_, size);
}
this.setFirstComponentSize();
};
/**
* Snap the container to the left or top on a Double-click.
* @private
*/
goog.ui.SplitPane.prototype.snapIt_ = function() {
var handlePos = goog.style.getRelativePosition(this.splitpaneHandle_,
this.firstComponentContainer_);
var firstBorderBoxSize =
goog.style.getBorderBoxSize(this.firstComponentContainer_);
var firstContentBoxSize =
goog.style.getContentBoxSize(this.firstComponentContainer_);
var isVertical = this.isVertical();
// Where do we snap the handle (what size to make the component) and what
// is the current handle position.
var snapSize;
var handlePosition;
if (isVertical) {
snapSize = firstBorderBoxSize.height - firstContentBoxSize.height;
handlePosition = handlePos.y;
} else {
snapSize = firstBorderBoxSize.width - firstContentBoxSize.width;
handlePosition = handlePos.x;
}
if (snapSize == handlePosition) {
// This means we're 'unsnapping', set it back to where it was.
this.setFirstComponentSize(this.savedSnapSize_);
} else {
// This means we're 'snapping', set the size to snapSize, and hide the
// first component.
if (isVertical) {
this.savedSnapSize_ = goog.style.getBorderBoxSize(
this.firstComponentContainer_).height;
} else {
this.savedSnapSize_ = goog.style.getBorderBoxSize(
this.firstComponentContainer_).width;
}
this.setFirstComponentSize(snapSize);
}
};
/**
* Handle the start drag event - set up the dragger.
* @param {goog.events.Event} e The event.
* @private
*/
goog.ui.SplitPane.prototype.handleDragStart_ = function(e) {
// Setup iframe overlay to prevent iframes from grabbing events.
if (!this.iframeOverlay_) {
// Create the overlay.
var cssStyles = 'position: relative';
if (goog.userAgent.IE) {
// IE doesn't look at this div unless it has a background, so we'll
// put one on, but make it opaque.
cssStyles += ';background-color: #000;filter: Alpha(Opacity=0)';
}
this.iframeOverlay_ =
this.getDomHelper().createDom('div', {'style': cssStyles});
this.getDomHelper().appendChild(this.getElement(), this.iframeOverlay_);
}
this.iframeOverlay_.style.zIndex =
goog.ui.SplitPane.IframeOverlayIndex_.OVERLAY;
goog.style.setBorderBoxSize(this.iframeOverlay_,
goog.style.getBorderBoxSize(this.getElement()));
var pos = goog.style.getPosition(this.firstComponentContainer_);
// For the size of the limiting box, we add the container content box sizes
// so that if the handle is placed all the way to the end or the start, the
// border doesn't exceed the total size. For position, we add the difference
// between the border box and content box sizes of the first container to the
// position of the first container. The start position should be such that
// there is no overlap of borders.
var limitWidth = 0;
var limitHeight = 0;
var limitx = pos.x;
var limity = pos.y;
var firstBorderBoxSize =
goog.style.getBorderBoxSize(this.firstComponentContainer_);
var firstContentBoxSize =
goog.style.getContentBoxSize(this.firstComponentContainer_);
var secondContentBoxSize =
goog.style.getContentBoxSize(this.secondComponentContainer_);
if (this.isVertical()) {
limitHeight = firstContentBoxSize.height + secondContentBoxSize.height;
limity += firstBorderBoxSize.height - firstContentBoxSize.height;
} else {
limitWidth = firstContentBoxSize.width + secondContentBoxSize.width;
limitx += firstBorderBoxSize.width - firstContentBoxSize.width;
}
var limits = new goog.math.Rect(limitx, limity, limitWidth, limitHeight);
this.splitDragger_.setLimits(limits);
};
/**
* Find the location relative to the splitpane.
* @param {number} left The x location relative to the window.
* @return {number} The relative x location.
* @private
*/
goog.ui.SplitPane.prototype.getRelativeLeft_ = function(left) {
return left - goog.style.getPosition(this.firstComponentContainer_).x;
};
/**
* Find the location relative to the splitpane.
* @param {number} top The y location relative to the window.
* @return {number} The relative y location.
* @private
*/
goog.ui.SplitPane.prototype.getRelativeTop_ = function(top) {
return top - goog.style.getPosition(this.firstComponentContainer_).y;
};
/**
* Handle the drag event. Move the containers.
* @param {goog.events.Event} e The event.
* @private
*/
goog.ui.SplitPane.prototype.handleDrag_ = function(e) {
if (this.continuousResize_) {
if (this.isVertical()) {
var top = this.getRelativeTop_(e.top);
this.setFirstComponentSize(top);
} else {
var left = this.getRelativeLeft_(e.left);
this.setFirstComponentSize(left);
}
this.dispatchEvent(goog.ui.SplitPane.EventType.HANDLE_DRAG);
}
};
/**
* Handle the drag end event. If we're not doing continuous resize,
* resize the component. If we're doing continuous resize, the component
* is already the correct size.
* @param {goog.events.Event} e The event.
* @private
*/
goog.ui.SplitPane.prototype.handleDragEnd_ = function(e) {
// Push iframe overlay down.
this.iframeOverlay_.style.zIndex =
goog.ui.SplitPane.IframeOverlayIndex_.HIDDEN;
if (!this.continuousResize_) {
if (this.isVertical()) {
var top = this.getRelativeTop_(e.top);
this.setFirstComponentSize(top);
} else {
var left = this.getRelativeLeft_(e.left);
this.setFirstComponentSize(left);
}
}
this.dispatchEvent(goog.ui.SplitPane.EventType.HANDLE_DRAG_END);
};
/**
* Handle the Double-click. Call the snapIt method which snaps the container
* to the top or left.
* @param {goog.events.Event} e The event.
* @private
*/
goog.ui.SplitPane.prototype.handleDoubleClick_ = function(e) {
this.snapIt_();
};
/** @override */
goog.ui.SplitPane.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
this.splitDragger_.dispose();
this.splitDragger_ = null;
goog.dom.removeNode(this.iframeOverlay_);
this.iframeOverlay_ = 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 Idle Timer.
*
* Keeps track of transitions between active and idle. This class is built on
* top of ActivityMonitor. Whenever an active user becomes idle, this class
* dispatches a BECOME_IDLE event. Whenever an idle user becomes active, this
* class dispatches a BECOME_ACTIVE event. The amount of inactive time it
* takes for a user to be considered idle is specified by the client, and
* different instances of this class can all use different thresholds.
*
*/
goog.provide('goog.ui.IdleTimer');
goog.require('goog.Timer');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
goog.require('goog.structs.Set');
goog.require('goog.ui.ActivityMonitor');
/**
* Event target that will give notification of state changes between active and
* idle. This class is designed to require few resources while the user is
* active.
* @param {number} idleThreshold Amount of time in ms at which we consider the
* user has gone idle.
* @param {goog.ui.ActivityMonitor=} opt_activityMonitor The activity monitor
* keeping track of user interaction. Defaults to a default-constructed
* activity monitor. If a default activity monitor is used then this class
* will dispose of it. If an activity monitor is passed in then the caller
* remains responsible for disposing of it.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.ui.IdleTimer = function(idleThreshold, opt_activityMonitor) {
goog.events.EventTarget.call(this);
var activityMonitor = opt_activityMonitor ||
this.getDefaultActivityMonitor_();
/**
* The amount of time in ms at which we consider the user has gone idle
* @type {number}
* @private
*/
this.idleThreshold_ = idleThreshold;
/**
* The activity monitor keeping track of user interaction
* @type {goog.ui.ActivityMonitor}
* @private
*/
this.activityMonitor_ = activityMonitor;
/**
* Cached onActivityTick_ bound to the object for later use
* @type {Function}
* @private
*/
this.boundOnActivityTick_ = goog.bind(this.onActivityTick_, this);
// Decide whether the user is currently active or idle. This method will
// check whether it is correct to start with the user in the active state.
this.maybeStillActive_();
};
goog.inherits(goog.ui.IdleTimer, goog.events.EventTarget);
/**
* Whether a listener is currently registered for an idle timer event. On
* initialization, the user is assumed to be active.
* @type {boolean}
* @private
*/
goog.ui.IdleTimer.prototype.hasActivityListener_ = false;
/**
* Handle to the timer ID used for checking ongoing activity, or null
* @type {?number}
* @private
*/
goog.ui.IdleTimer.prototype.onActivityTimerId_ = null;
/**
* Whether the user is currently idle
* @type {boolean}
* @private
*/
goog.ui.IdleTimer.prototype.isIdle_ = false;
/**
* The default activity monitor created by this class, if any
* @type {goog.ui.ActivityMonitor?}
* @private
*/
goog.ui.IdleTimer.defaultActivityMonitor_ = null;
/**
* The idle timers that currently reference the default activity monitor
* @type {goog.structs.Set}
* @private
*/
goog.ui.IdleTimer.defaultActivityMonitorReferences_ = new goog.structs.Set();
/**
* Event constants for the idle timer event target
* @enum {string}
*/
goog.ui.IdleTimer.Event = {
/** Event fired when an idle user transitions into the active state */
BECOME_ACTIVE: 'active',
/** Event fired when an active user transitions into the idle state */
BECOME_IDLE: 'idle'
};
/**
* Gets the default activity monitor used by this class. If a default has not
* been created yet, then a new one will be created.
* @return {goog.ui.ActivityMonitor} The default activity monitor.
* @private
*/
goog.ui.IdleTimer.prototype.getDefaultActivityMonitor_ = function() {
goog.ui.IdleTimer.defaultActivityMonitorReferences_.add(this);
if (goog.ui.IdleTimer.defaultActivityMonitor_ == null) {
goog.ui.IdleTimer.defaultActivityMonitor_ = new goog.ui.ActivityMonitor();
}
return goog.ui.IdleTimer.defaultActivityMonitor_;
};
/**
* Removes the reference to the default activity monitor. If there are no more
* references then the default activity monitor gets disposed.
* @private
*/
goog.ui.IdleTimer.prototype.maybeDisposeDefaultActivityMonitor_ = function() {
goog.ui.IdleTimer.defaultActivityMonitorReferences_.remove(this);
if (goog.ui.IdleTimer.defaultActivityMonitor_ != null &&
goog.ui.IdleTimer.defaultActivityMonitorReferences_.isEmpty()) {
goog.ui.IdleTimer.defaultActivityMonitor_.dispose();
goog.ui.IdleTimer.defaultActivityMonitor_ = null;
}
};
/**
* Checks whether the user is active. If the user is still active, then a timer
* is started to check again later.
* @private
*/
goog.ui.IdleTimer.prototype.maybeStillActive_ = function() {
// See how long before the user would go idle. The user is considered idle
// after the idle time has passed, not exactly when the idle time arrives.
var remainingIdleThreshold = this.idleThreshold_ + 1 -
(goog.now() - this.activityMonitor_.getLastEventTime());
if (remainingIdleThreshold > 0) {
// The user is still active. Check again later.
this.onActivityTimerId_ = goog.Timer.callOnce(
this.boundOnActivityTick_, remainingIdleThreshold);
} else {
// The user has not been active recently.
this.becomeIdle_();
}
};
/**
* Handler for the timeout used for checking ongoing activity
* @private
*/
goog.ui.IdleTimer.prototype.onActivityTick_ = function() {
// The timer has fired.
this.onActivityTimerId_ = null;
// The maybeStillActive method will restart the timer, if appropriate.
this.maybeStillActive_();
};
/**
* Transitions from the active state to the idle state
* @private
*/
goog.ui.IdleTimer.prototype.becomeIdle_ = function() {
this.isIdle_ = true;
// The idle timer will send notification when the user does something
// interactive.
goog.events.listen(this.activityMonitor_,
goog.ui.ActivityMonitor.Event.ACTIVITY,
this.onActivity_, false, this);
this.hasActivityListener_ = true;
// Notify clients of the state change.
this.dispatchEvent(goog.ui.IdleTimer.Event.BECOME_IDLE);
};
/**
* Handler for idle timer events when the user does something interactive
* @param {goog.events.Event} e The event object.
* @private
*/
goog.ui.IdleTimer.prototype.onActivity_ = function(e) {
this.becomeActive_();
};
/**
* Transitions from the idle state to the active state
* @private
*/
goog.ui.IdleTimer.prototype.becomeActive_ = function() {
this.isIdle_ = false;
// Stop listening to every interactive event.
this.removeActivityListener_();
// Notify clients of the state change.
this.dispatchEvent(goog.ui.IdleTimer.Event.BECOME_ACTIVE);
// Periodically check whether the user has gone inactive.
this.maybeStillActive_();
};
/**
* Removes the activity listener, if necessary
* @private
*/
goog.ui.IdleTimer.prototype.removeActivityListener_ = function() {
if (this.hasActivityListener_) {
goog.events.unlisten(this.activityMonitor_,
goog.ui.ActivityMonitor.Event.ACTIVITY,
this.onActivity_, false, this);
this.hasActivityListener_ = false;
}
};
/** @override */
goog.ui.IdleTimer.prototype.disposeInternal = function() {
this.removeActivityListener_();
if (this.onActivityTimerId_ != null) {
goog.global.clearTimeout(this.onActivityTimerId_);
this.onActivityTimerId_ = null;
}
this.maybeDisposeDefaultActivityMonitor_();
goog.ui.IdleTimer.superClass_.disposeInternal.call(this);
};
/**
* @return {number} the amount of time at which we consider the user has gone
* idle in ms.
*/
goog.ui.IdleTimer.prototype.getIdleThreshold = function() {
return this.idleThreshold_;
};
/**
* @return {goog.ui.ActivityMonitor} the activity monitor keeping track of user
* interaction.
*/
goog.ui.IdleTimer.prototype.getActivityMonitor = function() {
return this.activityMonitor_;
};
/**
* Returns true if there has been no user action for at least the specified
* interval, and false otherwise
* @return {boolean} true if the user is idle, false otherwise.
*/
goog.ui.IdleTimer.prototype.isIdle = function() {
return this.isIdle_;
};
| 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.Menu}s.
*
* @author robbyw@google.com (Robby Walker)
* @author pupius@google.com (Daniel Pupius)
*/
goog.provide('goog.ui.MenuRenderer');
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.ui.ContainerRenderer');
goog.require('goog.ui.Separator');
/**
* Default renderer for {@link goog.ui.Menu}s, based on {@link
* goog.ui.ContainerRenderer}.
* @constructor
* @extends {goog.ui.ContainerRenderer}
*/
goog.ui.MenuRenderer = function() {
goog.ui.ContainerRenderer.call(this);
};
goog.inherits(goog.ui.MenuRenderer, goog.ui.ContainerRenderer);
goog.addSingletonGetter(goog.ui.MenuRenderer);
/**
* Default CSS class to be applied to the root element of toolbars rendered
* by this renderer.
* @type {string}
*/
goog.ui.MenuRenderer.CSS_CLASS = goog.getCssName('goog-menu');
/**
* Returns the ARIA role to be applied to menus.
* @return {string} ARIA role.
* @override
*/
goog.ui.MenuRenderer.prototype.getAriaRole = function() {
return goog.a11y.aria.Role.MENU;
};
/**
* Returns whether the element is a UL or acceptable to our superclass.
* @param {Element} element Element to decorate.
* @return {boolean} Whether the renderer can decorate the element.
* @override
*/
goog.ui.MenuRenderer.prototype.canDecorate = function(element) {
return element.tagName == 'UL' ||
goog.ui.MenuRenderer.superClass_.canDecorate.call(this, element);
};
/**
* Inspects the element, and creates an instance of {@link goog.ui.Control} or
* an appropriate subclass best suited to decorate it. Overrides the superclass
* implementation by recognizing HR elements as separators.
* @param {Element} element Element to decorate.
* @return {goog.ui.Control?} A new control suitable to decorate the element
* (null if none).
* @override
*/
goog.ui.MenuRenderer.prototype.getDecoratorForChild = function(element) {
return element.tagName == 'HR' ?
new goog.ui.Separator() :
goog.ui.MenuRenderer.superClass_.getDecoratorForChild.call(this,
element);
};
/**
* Returns whether the given element is contained in the menu's DOM.
* @param {goog.ui.Menu} menu The menu to test.
* @param {Element} element The element to test.
* @return {boolean} Whether the given element is contained in the menu.
*/
goog.ui.MenuRenderer.prototype.containsElement = function(menu, element) {
return goog.dom.contains(menu.getElement(), element);
};
/**
* Returns the CSS class to be applied to the root element of containers
* rendered using this renderer.
* @return {string} Renderer-specific CSS class.
* @override
*/
goog.ui.MenuRenderer.prototype.getCssClass = function() {
return goog.ui.MenuRenderer.CSS_CLASS;
};
/** @override */
goog.ui.MenuRenderer.prototype.initializeDom = function(container) {
goog.ui.MenuRenderer.superClass_.initializeDom.call(this, container);
var element = container.getElement();
goog.asserts.assert(element, 'The menu DOM element cannot be null.');
goog.a11y.aria.setState(element, goog.a11y.aria.State.HASPOPUP, 'true');
};
| 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 MenuBase class.
*
*/
goog.provide('goog.ui.MenuBase');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyHandler');
goog.require('goog.ui.Popup');
/**
* The MenuBase class provides an abstract base class for different
* implementations of menu controls.
*
* @param {Element=} opt_element A DOM element for the popup.
* @deprecated Use goog.ui.Menu.
* @constructor
* @extends {goog.ui.Popup}
*/
goog.ui.MenuBase = function(opt_element) {
goog.ui.Popup.call(this, opt_element);
/**
* Event handler for simplifiying adding/removing listeners.
* @type {goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler(this);
/**
* KeyHandler to cope with the vagaries of cross-browser key events.
* @type {goog.events.KeyHandler}
* @private
*/
this.keyHandler_ = new goog.events.KeyHandler(this.getElement());
};
goog.inherits(goog.ui.MenuBase, goog.ui.Popup);
/**
* Events fired by the Menu
*/
goog.ui.MenuBase.Events = {};
/**
* Event fired by the Menu when an item is "clicked".
*/
goog.ui.MenuBase.Events.ITEM_ACTION = 'itemaction';
/** @override */
goog.ui.MenuBase.prototype.disposeInternal = function() {
goog.ui.MenuBase.superClass_.disposeInternal.call(this);
this.eventHandler_.dispose();
this.keyHandler_.dispose();
};
/**
* Called after the menu is shown. Derived classes can override to hook this
* event but should make sure to call the parent class method.
*
* @protected
* @suppress {underscore}
* @override
*/
goog.ui.MenuBase.prototype.onShow_ = function() {
goog.ui.MenuBase.superClass_.onShow_.call(this);
// register common event handlers for derived classes
var el = this.getElement();
this.eventHandler_.listen(
el, goog.events.EventType.MOUSEOVER, this.onMouseOver);
this.eventHandler_.listen(
el, goog.events.EventType.MOUSEOUT, this.onMouseOut);
this.eventHandler_.listen(
el, goog.events.EventType.MOUSEDOWN, this.onMouseDown);
this.eventHandler_.listen(
el, goog.events.EventType.MOUSEUP, this.onMouseUp);
this.eventHandler_.listen(
this.keyHandler_,
goog.events.KeyHandler.EventType.KEY,
this.onKeyDown);
};
/**
* Called after the menu is hidden. Derived classes can override to hook this
* event but should make sure to call the parent class method.
* @param {Object=} opt_target Target of the event causing the hide.
* @protected
* @suppress {underscore}
* @override
*/
goog.ui.MenuBase.prototype.onHide_ = function(opt_target) {
goog.ui.MenuBase.superClass_.onHide_.call(this, opt_target);
// remove listeners when hidden
this.eventHandler_.removeAll();
};
/**
* Returns the selected item
*
* @return {Object} The item selected or null if no item is selected.
*/
goog.ui.MenuBase.prototype.getSelectedItem = function() {
return null;
};
/**
* Sets the selected item
*
* @param {Object} item The item to select. The type of this item is specific
* to the menu class.
*/
goog.ui.MenuBase.prototype.setSelectedItem = function(item) {
};
/**
* Mouse over handler for the menu. Derived classes should override.
*
* @param {goog.events.Event} e The event object.
* @protected
*/
goog.ui.MenuBase.prototype.onMouseOver = function(e) {
};
/**
* Mouse out handler for the menu. Derived classes should override.
*
* @param {goog.events.Event} e The event object.
* @protected
*/
goog.ui.MenuBase.prototype.onMouseOut = function(e) {
};
/**
* Mouse down handler for the menu. Derived classes should override.
*
* @param {!goog.events.Event} e The event object.
* @protected
*/
goog.ui.MenuBase.prototype.onMouseDown = function(e) {
};
/**
* Mouse up handler for the menu. Derived classes should override.
*
* @param {goog.events.Event} e The event object.
* @protected
*/
goog.ui.MenuBase.prototype.onMouseUp = function(e) {
};
/**
* Key down handler for the menu. Derived classes should override.
*
* @param {goog.events.KeyEvent} e The event object.
* @protected
*/
goog.ui.MenuBase.prototype.onKeyDown = function(e) {
};
| 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.ButtonRenderer},
* but uses a <div> element instead of a <button> or <input> element.
*
*/
goog.provide('goog.ui.FlatButtonRenderer');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.Role');
goog.require('goog.dom.classes');
goog.require('goog.ui.Button');
goog.require('goog.ui.ButtonRenderer');
goog.require('goog.ui.INLINE_BLOCK_CLASSNAME');
goog.require('goog.ui.registry');
/**
* Flat renderer for {@link goog.ui.Button}s. Flat buttons can contain
* almost arbitrary HTML content, will flow like inline elements, but can be
* styled like block-level elements.
* @constructor
* @extends {goog.ui.ButtonRenderer}
*/
goog.ui.FlatButtonRenderer = function() {
goog.ui.ButtonRenderer.call(this);
};
goog.inherits(goog.ui.FlatButtonRenderer, goog.ui.ButtonRenderer);
goog.addSingletonGetter(goog.ui.FlatButtonRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.FlatButtonRenderer.CSS_CLASS = goog.getCssName('goog-flat-button');
/**
* Returns the control's contents wrapped in a div element, with
* the renderer's own CSS class and additional state-specific classes applied
* to it, and the button's disabled attribute set or cleared as needed.
* Overrides {@link goog.ui.ButtonRenderer#createDom}.
* @param {goog.ui.Control} button Button to render.
* @return {Element} Root element for the button.
* @override
*/
goog.ui.FlatButtonRenderer.prototype.createDom = function(button) {
var classNames = this.getClassNames(button);
var attributes = {
'class': goog.ui.INLINE_BLOCK_CLASSNAME + ' ' + classNames.join(' '),
'title': button.getTooltip() || ''
};
return button.getDomHelper().createDom(
'div', attributes, button.getContent());
};
/**
* Returns the ARIA role to be applied to flat buttons.
* @return {goog.a11y.aria.Role|undefined} ARIA role.
* @override
*/
goog.ui.FlatButtonRenderer.prototype.getAriaRole = function() {
return goog.a11y.aria.Role.BUTTON;
};
/**
* Returns true if this renderer can decorate the element. Overrides
* {@link goog.ui.ButtonRenderer#canDecorate} by returning true if the
* element is a DIV, false otherwise.
* @param {Element} element Element to decorate.
* @return {boolean} Whether the renderer can decorate the element.
* @override
*/
goog.ui.FlatButtonRenderer.prototype.canDecorate = function(element) {
return element.tagName == 'DIV';
};
/**
* Takes an existing element and decorates it with the flat button control.
* Initializes the control's ID, content, tooltip, value, and state based
* on the ID of the element, its child nodes, and its CSS classes, respectively.
* Returns the element. Overrides {@link goog.ui.ButtonRenderer#decorate}.
* @param {goog.ui.Control} button Button instance to decorate the element.
* @param {Element} element Element to decorate.
* @return {Element} Decorated element.
* @override
*/
goog.ui.FlatButtonRenderer.prototype.decorate = function(button, element) {
goog.dom.classes.add(element, goog.ui.INLINE_BLOCK_CLASSNAME);
return goog.ui.FlatButtonRenderer.superClass_.decorate.call(this, button,
element);
};
/**
* Flat buttons can't use the value attribute since they are div elements.
* Overrides {@link goog.ui.ButtonRenderer#getValue} to prevent trying to
* access the element's value.
* @param {Element} element The button control's root element.
* @return {string} Value not valid for flat buttons.
* @override
*/
goog.ui.FlatButtonRenderer.prototype.getValue = function(element) {
// Flat buttons don't store their value in the DOM.
return '';
};
/**
* 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.FlatButtonRenderer.prototype.getCssClass = function() {
return goog.ui.FlatButtonRenderer.CSS_CLASS;
};
// Register a decorator factory function for Flat Buttons.
goog.ui.registry.setDecoratorByClassName(goog.ui.FlatButtonRenderer.CSS_CLASS,
function() {
// Uses goog.ui.Button, but with FlatButtonRenderer.
return new goog.ui.Button(null, goog.ui.FlatButtonRenderer.getInstance());
});
| 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 Native browser textarea renderer for {@link goog.ui.Textarea}s.
*/
goog.provide('goog.ui.TextareaRenderer');
goog.require('goog.ui.Component.State');
goog.require('goog.ui.ControlRenderer');
/**
* Renderer for {@link goog.ui.Textarea}s. Renders and decorates native HTML
* textarea elements. Since native HTML textareas have built-in support for
* many features, overrides many expensive (and redundant) superclass methods to
* be no-ops.
* @constructor
* @extends {goog.ui.ControlRenderer}
*/
goog.ui.TextareaRenderer = function() {
goog.ui.ControlRenderer.call(this);
};
goog.inherits(goog.ui.TextareaRenderer, goog.ui.ControlRenderer);
goog.addSingletonGetter(goog.ui.TextareaRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.TextareaRenderer.CSS_CLASS = goog.getCssName('goog-textarea');
/** @override */
goog.ui.TextareaRenderer.prototype.getAriaRole = function() {
// textareas don't need ARIA roles to be recognized by screen readers.
return undefined;
};
/** @override */
goog.ui.TextareaRenderer.prototype.decorate = function(control, element) {
this.setUpTextarea_(control);
goog.ui.TextareaRenderer.superClass_.decorate.call(this, control,
element);
control.setContent(element.value);
return element;
};
/**
* Returns the textarea's contents wrapped in an HTML textarea element. Sets
* the textarea's disabled attribute as needed.
* @param {goog.ui.Control} textarea Textarea to render.
* @return {Element} Root element for the Textarea control (an HTML textarea
* element).
* @override
*/
goog.ui.TextareaRenderer.prototype.createDom = function(textarea) {
this.setUpTextarea_(textarea);
var element = textarea.getDomHelper().createDom('textarea', {
'class': this.getClassNames(textarea).join(' '),
'disabled': !textarea.isEnabled()
}, textarea.getContent() || '');
return element;
};
/**
* Overrides {@link goog.ui.TextareaRenderer#canDecorate} by returning true only
* if the element is an HTML textarea.
* @param {Element} element Element to decorate.
* @return {boolean} Whether the renderer can decorate the element.
* @override
*/
goog.ui.TextareaRenderer.prototype.canDecorate = function(element) {
return element.tagName == goog.dom.TagName.TEXTAREA;
};
/**
* Textareas natively support right-to-left rendering.
* @override
*/
goog.ui.TextareaRenderer.prototype.setRightToLeft = goog.nullFunction;
/**
* Textareas are always focusable as long as they are enabled.
* @override
*/
goog.ui.TextareaRenderer.prototype.isFocusable = function(textarea) {
return textarea.isEnabled();
};
/**
* Textareas natively support keyboard focus.
* @override
*/
goog.ui.TextareaRenderer.prototype.setFocusable = goog.nullFunction;
/**
* Textareas also expose the DISABLED state in the HTML textarea's
* {@code disabled} attribute.
* @override
*/
goog.ui.TextareaRenderer.prototype.setState = function(textarea, state,
enable) {
goog.ui.TextareaRenderer.superClass_.setState.call(this, textarea, state,
enable);
var element = textarea.getElement();
if (element && state == goog.ui.Component.State.DISABLED) {
element.disabled = enable;
}
};
/**
* Textareas don't need ARIA states to support accessibility, so this is
* a no-op.
* @override
*/
goog.ui.TextareaRenderer.prototype.updateAriaState = goog.nullFunction;
/**
* Sets up the textarea control such that it doesn't waste time adding
* functionality that is already natively supported by browser
* textareas.
* @param {goog.ui.Control} textarea Textarea control to configure.
* @private
*/
goog.ui.TextareaRenderer.prototype.setUpTextarea_ = function(textarea) {
textarea.setHandleMouseEvents(false);
textarea.setAutoStates(goog.ui.Component.State.ALL, false);
textarea.setSupportedState(goog.ui.Component.State.FOCUSED, false);
};
/** @override **/
goog.ui.TextareaRenderer.prototype.setContent = function(element, value) {
if (element) {
element.value = value;
}
};
/** @override **/
goog.ui.TextareaRenderer.prototype.getCssClass = function() {
return goog.ui.TextareaRenderer.CSS_CLASS;
};
| 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 item observing the filter text in a
* {@link goog.ui.FilteredMenu}. The observer method is called when the filter
* text changes and allows the menu item to update its content and state based
* on the filter.
*
* @author eae@google.com (Emil A Eklund)
*/
goog.provide('goog.ui.FilterObservingMenuItem');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.FilterObservingMenuItemRenderer');
goog.require('goog.ui.MenuItem');
goog.require('goog.ui.registry');
/**
* Class representing a filter observing menu item.
*
* @param {goog.ui.ControlContent} content Text caption or DOM structure to
* display as the content of the item (use to add icons or styling to
* menus).
* @param {*=} opt_model Data/model associated with the menu item.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper used for
* document interactions.
* @param {goog.ui.MenuItemRenderer=} opt_renderer Optional renderer.
* @constructor
* @extends {goog.ui.MenuItem}
*/
goog.ui.FilterObservingMenuItem = function(content, opt_model, opt_domHelper,
opt_renderer) {
goog.ui.MenuItem.call(this, content, opt_model, opt_domHelper,
opt_renderer || new goog.ui.FilterObservingMenuItemRenderer());
};
goog.inherits(goog.ui.FilterObservingMenuItem, goog.ui.MenuItem);
/**
* Function called when the filter text changes.
* @type {Function} function(goog.ui.FilterObservingMenuItem, string)
* @private
*/
goog.ui.FilterObservingMenuItem.prototype.observer_ = null;
/** @override */
goog.ui.FilterObservingMenuItem.prototype.enterDocument = function() {
goog.ui.FilterObservingMenuItem.superClass_.enterDocument.call(this);
this.callObserver();
};
/**
* Sets the observer functions.
* @param {Function} f function(goog.ui.FilterObservingMenuItem, string).
*/
goog.ui.FilterObservingMenuItem.prototype.setObserver = function(f) {
this.observer_ = f;
this.callObserver();
};
/**
* Calls the observer function if one has been specified.
* @param {?string=} opt_str Filter string.
*/
goog.ui.FilterObservingMenuItem.prototype.callObserver = function(opt_str) {
if (this.observer_) {
this.observer_(this, opt_str || '');
}
};
// Register a decorator factory function for
// goog.ui.FilterObservingMenuItemRenderer.
goog.ui.registry.setDecoratorByClassName(
goog.ui.FilterObservingMenuItemRenderer.CSS_CLASS,
function() {
// FilterObservingMenuItem defaults to using
// FilterObservingMenuItemRenderer.
return new goog.ui.FilterObservingMenuItem(null);
});
| 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 button control.
*
* @author attila@google.com (Attila Bodis)
* @author ssaviano@google.com (Steven Saviano)
*/
goog.provide('goog.ui.ToolbarButton');
goog.require('goog.ui.Button');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.ToolbarButtonRenderer');
goog.require('goog.ui.registry');
/**
* A button control for a toolbar.
*
* @param {goog.ui.ControlContent} content Text caption or existing DOM
* structure to display as the button's caption.
* @param {goog.ui.ButtonRenderer=} opt_renderer Optional renderer used to
* render or decorate the button; defaults to
* {@link goog.ui.ToolbarButtonRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
* document interaction.
* @constructor
* @extends {goog.ui.Button}
*/
goog.ui.ToolbarButton = function(content, opt_renderer, opt_domHelper) {
goog.ui.Button.call(this, content, opt_renderer ||
goog.ui.ToolbarButtonRenderer.getInstance(), opt_domHelper);
};
goog.inherits(goog.ui.ToolbarButton, goog.ui.Button);
// Registers a decorator factory function for toolbar buttons.
goog.ui.registry.setDecoratorByClassName(
goog.ui.ToolbarButtonRenderer.CSS_CLASS,
function() {
return new goog.ui.ToolbarButton(null);
});
| 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 Tooltip widget implementation.
*
* @author eae@google.com (Emil A Eklund)
* @see ../demos/tooltip.html
*/
goog.provide('goog.ui.Tooltip');
goog.provide('goog.ui.Tooltip.CursorTooltipPosition');
goog.provide('goog.ui.Tooltip.ElementTooltipPosition');
goog.provide('goog.ui.Tooltip.State');
goog.require('goog.Timer');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.math.Box');
goog.require('goog.math.Coordinate');
goog.require('goog.positioning');
goog.require('goog.positioning.AnchoredPosition');
goog.require('goog.positioning.Corner');
goog.require('goog.positioning.Overflow');
goog.require('goog.positioning.OverflowStatus');
goog.require('goog.positioning.ViewportPosition');
goog.require('goog.structs.Set');
goog.require('goog.style');
goog.require('goog.ui.Popup');
goog.require('goog.ui.PopupBase');
/**
* Tooltip widget. Can be attached to one or more elements and is shown, with a
* slight delay, when the the cursor is over the element or the element gains
* focus.
*
* @param {Element|string=} opt_el Element to display tooltip for, either
* element reference or string id.
* @param {?string=} opt_str Text message to display in tooltip.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @constructor
* @extends {goog.ui.Popup}
*/
goog.ui.Tooltip = function(opt_el, opt_str, opt_domHelper) {
/**
* Dom Helper
* @type {goog.dom.DomHelper}
* @private
*/
this.dom_ = opt_domHelper || (opt_el ?
goog.dom.getDomHelper(goog.dom.getElement(opt_el)) :
goog.dom.getDomHelper());
goog.ui.Popup.call(this, this.dom_.createDom(
'div', {'style': 'position:absolute;display:none;'}));
/**
* Cursor position relative to the page.
* @type {!goog.math.Coordinate}
* @protected
*/
this.cursorPosition = new goog.math.Coordinate(1, 1);
/**
* Elements this widget is attached to.
* @type {goog.structs.Set}
* @private
*/
this.elements_ = new goog.structs.Set();
// Attach to element, if specified
if (opt_el) {
this.attach(opt_el);
}
// Set message, if specified.
if (opt_str != null) {
this.setText(opt_str);
}
};
goog.inherits(goog.ui.Tooltip, goog.ui.Popup);
/**
* List of active (open) tooltip widgets. Used to prevent multiple tooltips
* from appearing at once.
*
* @type {!Array.<goog.ui.Tooltip>}
* @private
*/
goog.ui.Tooltip.activeInstances_ = [];
/**
* Active element reference. Used by the delayed show functionality to keep
* track of the element the mouse is over or the element with focus.
* @type {Element}
* @private
*/
goog.ui.Tooltip.prototype.activeEl_ = null;
/**
* CSS class name for tooltip.
*
* @type {string}
*/
goog.ui.Tooltip.prototype.className = goog.getCssName('goog-tooltip');
/**
* Delay in milliseconds since the last mouseover or mousemove before the
* tooltip is displayed for an element.
*
* @type {number}
* @private
*/
goog.ui.Tooltip.prototype.showDelayMs_ = 500;
/**
* Timer for when to show.
*
* @type {number|undefined}
* @protected
*/
goog.ui.Tooltip.prototype.showTimer;
/**
* Delay in milliseconds before tooltips are hidden.
*
* @type {number}
* @private
*/
goog.ui.Tooltip.prototype.hideDelayMs_ = 0;
/**
* Timer for when to hide.
*
* @type {number|undefined}
* @protected
*/
goog.ui.Tooltip.prototype.hideTimer;
/**
* Element that triggered the tooltip. Note that if a second element triggers
* this tooltip, anchor becomes that second element, even if its show is
* cancelled and the original tooltip survives.
*
* @type {Element|undefined}
* @protected
*/
goog.ui.Tooltip.prototype.anchor;
/**
* Possible states for the tooltip to be in.
* @enum {number}
*/
goog.ui.Tooltip.State = {
INACTIVE: 0,
WAITING_TO_SHOW: 1,
SHOWING: 2,
WAITING_TO_HIDE: 3,
UPDATING: 4 // waiting to show new hovercard while old one still showing.
};
/**
* Popup activation types. Used to select a positioning strategy.
* @enum {number}
*/
goog.ui.Tooltip.Activation = {
CURSOR: 0,
FOCUS: 1
};
/**
* Whether the anchor has seen the cursor move or has received focus since the
* tooltip was last shown. Used to ignore mouse over events triggered by view
* changes and UI updates.
* @type {boolean|undefined}
* @private
*/
goog.ui.Tooltip.prototype.seenInteraction_;
/**
* Whether the cursor must have moved before the tooltip will be shown.
* @type {boolean|undefined}
* @private
*/
goog.ui.Tooltip.prototype.requireInteraction_;
/**
* If this tooltip's element contains another tooltip that becomes active, this
* property identifies that tooltip so that we can check if this tooltip should
* not be hidden because the nested tooltip is active.
* @type {goog.ui.Tooltip}
* @private
*/
goog.ui.Tooltip.prototype.childTooltip_;
/**
* If this tooltip is inside another tooltip's element, then it may have
* prevented that tooltip from hiding. When this tooltip hides, we'll need
* to check if the parent should be hidden as well.
* @type {goog.ui.Tooltip}
* @private
*/
goog.ui.Tooltip.prototype.parentTooltip_;
/**
* Returns the dom helper that is being used on this component.
* @return {goog.dom.DomHelper} The dom helper used on this component.
*/
goog.ui.Tooltip.prototype.getDomHelper = function() {
return this.dom_;
};
/**
* @return {goog.ui.Tooltip} Active tooltip in a child element, or null if none.
* @protected
*/
goog.ui.Tooltip.prototype.getChildTooltip = function() {
return this.childTooltip_;
};
/**
* Attach to element. Tooltip will be displayed when the cursor is over the
* element or when the element has been active for a few milliseconds.
*
* @param {Element|string} el Element to display tooltip for, either element
* reference or string id.
*/
goog.ui.Tooltip.prototype.attach = function(el) {
el = goog.dom.getElement(el);
this.elements_.add(el);
goog.events.listen(el, goog.events.EventType.MOUSEOVER,
this.handleMouseOver, false, this);
goog.events.listen(el, goog.events.EventType.MOUSEOUT,
this.handleMouseOutAndBlur, false, this);
goog.events.listen(el, goog.events.EventType.MOUSEMOVE,
this.handleMouseMove, false, this);
goog.events.listen(el, goog.events.EventType.FOCUS,
this.handleFocus, false, this);
goog.events.listen(el, goog.events.EventType.BLUR,
this.handleMouseOutAndBlur, false, this);
};
/**
* Detach from element(s).
*
* @param {Element|string=} opt_el Element to detach from, either element
* reference or string id. If no element is
* specified all are detached.
*/
goog.ui.Tooltip.prototype.detach = function(opt_el) {
if (opt_el) {
var el = goog.dom.getElement(opt_el);
this.detachElement_(el);
this.elements_.remove(el);
} else {
var a = this.elements_.getValues();
for (var el, i = 0; el = a[i]; i++) {
this.detachElement_(el);
}
this.elements_.clear();
}
};
/**
* Detach from element.
*
* @param {Element} el Element to detach from.
* @private
*/
goog.ui.Tooltip.prototype.detachElement_ = function(el) {
goog.events.unlisten(el, goog.events.EventType.MOUSEOVER,
this.handleMouseOver, false, this);
goog.events.unlisten(el, goog.events.EventType.MOUSEOUT,
this.handleMouseOutAndBlur, false, this);
goog.events.unlisten(el, goog.events.EventType.MOUSEMOVE,
this.handleMouseMove, false, this);
goog.events.unlisten(el, goog.events.EventType.FOCUS,
this.handleFocus, false, this);
goog.events.unlisten(el, goog.events.EventType.BLUR,
this.handleMouseOutAndBlur, false, this);
};
/**
* Sets delay in milliseconds before tooltip is displayed for an element.
*
* @param {number} delay The delay in milliseconds.
*/
goog.ui.Tooltip.prototype.setShowDelayMs = function(delay) {
this.showDelayMs_ = delay;
};
/**
* @return {number} The delay in milliseconds before tooltip is displayed for an
* element.
*/
goog.ui.Tooltip.prototype.getShowDelayMs = function() {
return this.showDelayMs_;
};
/**
* Sets delay in milliseconds before tooltip is hidden once the cursor leavs
* the element.
*
* @param {number} delay The delay in milliseconds.
*/
goog.ui.Tooltip.prototype.setHideDelayMs = function(delay) {
this.hideDelayMs_ = delay;
};
/**
* @return {number} The delay in milliseconds before tooltip is hidden once the
* cursor leaves the element.
*/
goog.ui.Tooltip.prototype.getHideDelayMs = function() {
return this.hideDelayMs_;
};
/**
* Sets tooltip message as plain text.
*
* @param {string} str Text message to display in tooltip.
*/
goog.ui.Tooltip.prototype.setText = function(str) {
goog.dom.setTextContent(this.getElement(), str);
};
/**
* Sets tooltip message as HTML markup.
*
* @param {string} str HTML message to display in tooltip.
*/
goog.ui.Tooltip.prototype.setHtml = function(str) {
this.getElement().innerHTML = str;
};
/**
* Sets tooltip element.
*
* @param {Element} el HTML element to use as the tooltip.
* @override
*/
goog.ui.Tooltip.prototype.setElement = function(el) {
var oldElement = this.getElement();
if (oldElement) {
goog.dom.removeNode(oldElement);
}
goog.ui.Tooltip.superClass_.setElement.call(this, el);
if (el) {
var body = this.dom_.getDocument().body;
body.insertBefore(el, body.lastChild);
}
};
/**
* @return {string} The tooltip message as plain text.
*/
goog.ui.Tooltip.prototype.getText = function() {
return goog.dom.getTextContent(this.getElement());
};
/**
* @return {string} The tooltip message as HTML.
*/
goog.ui.Tooltip.prototype.getHtml = function() {
return this.getElement().innerHTML;
};
/**
* @return {goog.ui.Tooltip.State} Current state of tooltip.
*/
goog.ui.Tooltip.prototype.getState = function() {
return this.showTimer ?
(this.isVisible() ? goog.ui.Tooltip.State.UPDATING :
goog.ui.Tooltip.State.WAITING_TO_SHOW) :
this.hideTimer ? goog.ui.Tooltip.State.WAITING_TO_HIDE :
this.isVisible() ? goog.ui.Tooltip.State.SHOWING :
goog.ui.Tooltip.State.INACTIVE;
};
/**
* Sets whether tooltip requires the mouse to have moved or the anchor receive
* focus before the tooltip will be shown.
* @param {boolean} requireInteraction Whether tooltip should require some user
* interaction before showing tooltip.
*/
goog.ui.Tooltip.prototype.setRequireInteraction = function(requireInteraction) {
this.requireInteraction_ = requireInteraction;
};
/**
* Returns true if the coord is in the tooltip.
* @param {goog.math.Coordinate} coord Coordinate being tested.
* @return {boolean} Whether the coord is in the tooltip.
*/
goog.ui.Tooltip.prototype.isCoordinateInTooltip = function(coord) {
// Check if coord is inside the the tooltip
if (!this.isVisible()) {
return false;
}
var offset = goog.style.getPageOffset(this.getElement());
var size = goog.style.getSize(this.getElement());
return offset.x <= coord.x && coord.x <= offset.x + size.width &&
offset.y <= coord.y && coord.y <= offset.y + size.height;
};
/**
* Called before the popup is shown.
*
* @return {boolean} Whether tooltip should be shown.
* @protected
* @override
*/
goog.ui.Tooltip.prototype.onBeforeShow = function() {
if (!goog.ui.PopupBase.prototype.onBeforeShow.call(this)) {
return false;
}
// Hide all open tooltips except if this tooltip is triggered by an element
// inside another tooltip.
if (this.anchor) {
for (var tt, i = 0; tt = goog.ui.Tooltip.activeInstances_[i]; i++) {
if (!goog.dom.contains(tt.getElement(), this.anchor)) {
tt.setVisible(false);
}
}
}
goog.array.insert(goog.ui.Tooltip.activeInstances_, this);
var element = this.getElement();
element.className = this.className;
this.clearHideTimer();
// Register event handlers for tooltip. Used to prevent the tooltip from
// closing if the cursor is over the tooltip rather then the element that
// triggered it.
goog.events.listen(element, goog.events.EventType.MOUSEOVER,
this.handleTooltipMouseOver, false, this);
goog.events.listen(element, goog.events.EventType.MOUSEOUT,
this.handleTooltipMouseOut, false, this);
this.clearShowTimer();
return true;
};
/**
* Called after the popup is hidden.
*
* @protected
* @suppress {underscore}
* @override
*/
goog.ui.Tooltip.prototype.onHide_ = function() {
goog.array.remove(goog.ui.Tooltip.activeInstances_, this);
// Hide all open tooltips triggered by an element inside this tooltip.
var element = this.getElement();
for (var tt, i = 0; tt = goog.ui.Tooltip.activeInstances_[i]; i++) {
if (tt.anchor && goog.dom.contains(element, tt.anchor)) {
tt.setVisible(false);
}
}
// If this tooltip is inside another tooltip, start hide timer for that
// tooltip in case this tooltip was the only reason it was still showing.
if (this.parentTooltip_) {
this.parentTooltip_.startHideTimer();
}
goog.events.unlisten(element, goog.events.EventType.MOUSEOVER,
this.handleTooltipMouseOver, false, this);
goog.events.unlisten(element, goog.events.EventType.MOUSEOUT,
this.handleTooltipMouseOut, false, this);
this.anchor = undefined;
// If we are still waiting to show a different hovercard, don't abort it
// because you think you haven't seen a mouse move:
if (this.getState() == goog.ui.Tooltip.State.INACTIVE) {
this.seenInteraction_ = false;
}
goog.ui.PopupBase.prototype.onHide_.call(this);
};
/**
* Called by timer from mouse over handler. Shows tooltip if cursor is still
* over the same element.
*
* @param {Element} el Element to show tooltip for.
* @param {goog.positioning.AbstractPosition=} opt_pos Position to display popup
* at.
*/
goog.ui.Tooltip.prototype.maybeShow = function(el, opt_pos) {
// Assert that the mouse is still over the same element, and that we have not
// detached from the anchor in the meantime.
if (this.anchor == el && this.elements_.contains(this.anchor)) {
if (this.seenInteraction_ || !this.requireInteraction_) {
// If it is currently showing, then hide it, and abort if it doesn't hide.
this.setVisible(false);
if (!this.isVisible()) {
this.positionAndShow_(el, opt_pos);
}
} else {
this.anchor = undefined;
}
}
this.showTimer = undefined;
};
/**
* @return {goog.structs.Set} Elements this widget is attached to.
* @protected
*/
goog.ui.Tooltip.prototype.getElements = function() {
return this.elements_;
};
/**
* @return {Element} Active element reference.
*/
goog.ui.Tooltip.prototype.getActiveElement = function() {
return this.activeEl_;
};
/**
* @param {Element} activeEl Active element reference.
* @protected
*/
goog.ui.Tooltip.prototype.setActiveElement = function(activeEl) {
this.activeEl_ = activeEl;
};
/**
* Shows tooltip for a specific element.
*
* @param {Element} el Element to show tooltip for.
* @param {goog.positioning.AbstractPosition=} opt_pos Position to display popup
* at.
*/
goog.ui.Tooltip.prototype.showForElement = function(el, opt_pos) {
this.attach(el);
this.activeEl_ = el;
this.positionAndShow_(el, opt_pos);
};
/**
* Sets tooltip position and shows it.
*
* @param {Element} el Element to show tooltip for.
* @param {goog.positioning.AbstractPosition=} opt_pos Position to display popup
* at.
* @private
*/
goog.ui.Tooltip.prototype.positionAndShow_ = function(el, opt_pos) {
this.anchor = el;
this.setPosition(opt_pos ||
this.getPositioningStrategy(goog.ui.Tooltip.Activation.CURSOR));
this.setVisible(true);
};
/**
* Called by timer from mouse out handler. Hides tooltip if cursor is still
* outside element and tooltip, or if a child of tooltip has the focus.
* @param {Element} el Tooltip's anchor when hide timer was started.
*/
goog.ui.Tooltip.prototype.maybeHide = function(el) {
this.hideTimer = undefined;
if (el == this.anchor) {
if ((this.activeEl_ == null || (this.activeEl_ != this.getElement() &&
!this.elements_.contains(this.activeEl_))) &&
!this.hasActiveChild()) {
this.setVisible(false);
}
}
};
/**
* @return {boolean} Whether tooltip element contains an active child tooltip,
* and should thus not be hidden. When the child tooltip is hidden, it
* will check if the parent should be hidden, too.
* @protected
*/
goog.ui.Tooltip.prototype.hasActiveChild = function() {
return !!(this.childTooltip_ && this.childTooltip_.activeEl_);
};
/**
* Saves the current mouse cursor position to {@code this.cursorPosition}.
* @param {goog.events.BrowserEvent} event MOUSEOVER or MOUSEMOVE event.
* @private
*/
goog.ui.Tooltip.prototype.saveCursorPosition_ = function(event) {
var scroll = this.dom_.getDocumentScroll();
this.cursorPosition.x = event.clientX + scroll.x;
this.cursorPosition.y = event.clientY + scroll.y;
};
/**
* Handler for mouse over events.
*
* @param {goog.events.BrowserEvent} event Event object.
* @protected
*/
goog.ui.Tooltip.prototype.handleMouseOver = function(event) {
var el = this.getAnchorFromElement(/** @type {Element} */ (event.target));
this.activeEl_ = /** @type {Element} */ (el);
this.clearHideTimer();
if (el != this.anchor) {
this.anchor = el;
this.startShowTimer(/** @type {Element} */ (el));
this.checkForParentTooltip_();
this.saveCursorPosition_(event);
}
};
/**
* Find anchor containing the given element, if any.
*
* @param {Element} el Element that triggered event.
* @return {Element} Element in elements_ array that contains given element,
* or null if not found.
* @protected
*/
goog.ui.Tooltip.prototype.getAnchorFromElement = function(el) {
// FireFox has a bug where mouse events relating to <input> elements are
// sometimes duplicated (often in FF2, rarely in FF3): once for the
// <input> element and once for a magic hidden <div> element. Javascript
// code does not have sufficient permissions to read properties on that
// magic element and thus will throw an error in this call to
// getAnchorFromElement_(). In that case we swallow the error.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=330961
try {
while (el && !this.elements_.contains(el)) {
el = /** @type {Element} */ (el.parentNode);
}
return el;
} catch (e) {
return null;
}
};
/**
* Handler for mouse move events.
*
* @param {goog.events.BrowserEvent} event MOUSEMOVE event.
* @protected
*/
goog.ui.Tooltip.prototype.handleMouseMove = function(event) {
this.saveCursorPosition_(event);
this.seenInteraction_ = true;
};
/**
* Handler for focus events.
*
* @param {goog.events.BrowserEvent} event Event object.
* @protected
*/
goog.ui.Tooltip.prototype.handleFocus = function(event) {
var el = this.getAnchorFromElement(/** @type {Element} */ (event.target));
this.activeEl_ = el;
this.seenInteraction_ = true;
if (this.anchor != el) {
this.anchor = el;
var pos = this.getPositioningStrategy(goog.ui.Tooltip.Activation.FOCUS);
this.clearHideTimer();
this.startShowTimer(/** @type {Element} */ (el), pos);
this.checkForParentTooltip_();
}
};
/**
* Return a Position instance for repositioning the tooltip. Override in
* subclasses to customize the way repositioning is done.
*
* @param {goog.ui.Tooltip.Activation} activationType Information about what
* kind of event caused the popup to be shown.
* @return {!goog.positioning.AbstractPosition} The position object used
* to position the tooltip.
* @protected
*/
goog.ui.Tooltip.prototype.getPositioningStrategy = function(activationType) {
if (activationType == goog.ui.Tooltip.Activation.CURSOR) {
var coord = this.cursorPosition.clone();
return new goog.ui.Tooltip.CursorTooltipPosition(coord);
}
return new goog.ui.Tooltip.ElementTooltipPosition(this.activeEl_);
};
/**
* Looks for an active tooltip whose element contains this tooltip's anchor.
* This allows us to prevent hides until they are really necessary.
*
* @private
*/
goog.ui.Tooltip.prototype.checkForParentTooltip_ = function() {
if (this.anchor) {
for (var tt, i = 0; tt = goog.ui.Tooltip.activeInstances_[i]; i++) {
if (goog.dom.contains(tt.getElement(), this.anchor)) {
tt.childTooltip_ = this;
this.parentTooltip_ = tt;
}
}
}
};
/**
* Handler for mouse out and blur events.
*
* @param {goog.events.BrowserEvent} event Event object.
* @protected
*/
goog.ui.Tooltip.prototype.handleMouseOutAndBlur = function(event) {
var el = this.getAnchorFromElement(/** @type {Element} */ (event.target));
var elTo = this.getAnchorFromElement(
/** @type {Element} */ (event.relatedTarget));
if (el == elTo) {
// We haven't really left the anchor, just moved from one child to
// another.
return;
}
if (el == this.activeEl_) {
this.activeEl_ = null;
}
this.clearShowTimer();
this.seenInteraction_ = false;
if (this.isVisible() && (!event.relatedTarget ||
!goog.dom.contains(this.getElement(), event.relatedTarget))) {
this.startHideTimer();
} else {
this.anchor = undefined;
}
};
/**
* Handler for mouse over events for the tooltip element.
*
* @param {goog.events.BrowserEvent} event Event object.
* @protected
*/
goog.ui.Tooltip.prototype.handleTooltipMouseOver = function(event) {
var element = this.getElement();
if (this.activeEl_ != element) {
this.clearHideTimer();
this.activeEl_ = element;
}
};
/**
* Handler for mouse out events for the tooltip element.
*
* @param {goog.events.BrowserEvent} event Event object.
* @protected
*/
goog.ui.Tooltip.prototype.handleTooltipMouseOut = function(event) {
var element = this.getElement();
if (this.activeEl_ == element && (!event.relatedTarget ||
!goog.dom.contains(element, event.relatedTarget))) {
this.activeEl_ = null;
this.startHideTimer();
}
};
/**
* Helper method, starts timer that calls maybeShow. Parameters are passed to
* the maybeShow method.
*
* @param {Element} el Element to show tooltip for.
* @param {goog.positioning.AbstractPosition=} opt_pos Position to display popup
* at.
* @protected
*/
goog.ui.Tooltip.prototype.startShowTimer = function(el, opt_pos) {
if (!this.showTimer) {
this.showTimer = goog.Timer.callOnce(
goog.bind(this.maybeShow, this, el, opt_pos), this.showDelayMs_);
}
};
/**
* Helper method called to clear the show timer.
*
* @protected
*/
goog.ui.Tooltip.prototype.clearShowTimer = function() {
if (this.showTimer) {
goog.Timer.clear(this.showTimer);
this.showTimer = undefined;
}
};
/**
* Helper method called to start the close timer.
* @protected
*/
goog.ui.Tooltip.prototype.startHideTimer = function() {
if (this.getState() == goog.ui.Tooltip.State.SHOWING) {
this.hideTimer = goog.Timer.callOnce(
goog.bind(this.maybeHide, this, this.anchor), this.getHideDelayMs());
}
};
/**
* Helper method called to clear the close timer.
* @protected
*/
goog.ui.Tooltip.prototype.clearHideTimer = function() {
if (this.hideTimer) {
goog.Timer.clear(this.hideTimer);
this.hideTimer = undefined;
}
};
/** @override */
goog.ui.Tooltip.prototype.disposeInternal = function() {
this.setVisible(false);
this.clearShowTimer();
this.detach();
if (this.getElement()) {
goog.dom.removeNode(this.getElement());
}
this.activeEl_ = null;
delete this.dom_;
goog.ui.Tooltip.superClass_.disposeInternal.call(this);
};
/**
* Popup position implementation that positions the popup (the tooltip in this
* case) based on the cursor position. It's positioned below the cursor to the
* right if there's enough room to fit all of it inside the Viewport. Otherwise
* it's displayed as far right as possible either above or below the element.
*
* Used to position tooltips triggered by the cursor.
*
* @param {number|!goog.math.Coordinate} arg1 Left position or coordinate.
* @param {number=} opt_arg2 Top position.
* @constructor
* @extends {goog.positioning.ViewportPosition}
*/
goog.ui.Tooltip.CursorTooltipPosition = function(arg1, opt_arg2) {
goog.positioning.ViewportPosition.call(this, arg1, opt_arg2);
};
goog.inherits(goog.ui.Tooltip.CursorTooltipPosition,
goog.positioning.ViewportPosition);
/**
* Repositions the popup based on cursor position.
*
* @param {Element} element The DOM element of the popup.
* @param {goog.positioning.Corner} popupCorner The corner of the popup element
* that that should be positioned adjacent to the anchorElement.
* @param {goog.math.Box=} opt_margin A margin specified in pixels.
* @override
*/
goog.ui.Tooltip.CursorTooltipPosition.prototype.reposition = function(
element, popupCorner, opt_margin) {
var viewportElt = goog.style.getClientViewportElement(element);
var viewport = goog.style.getVisibleRectForElement(viewportElt);
var margin = opt_margin ? new goog.math.Box(opt_margin.top + 10,
opt_margin.right, opt_margin.bottom, opt_margin.left + 10) :
new goog.math.Box(10, 0, 0, 10);
if (goog.positioning.positionAtCoordinate(this.coordinate, element,
goog.positioning.Corner.TOP_START, margin, viewport,
goog.positioning.Overflow.ADJUST_X | goog.positioning.Overflow.FAIL_Y
) & goog.positioning.OverflowStatus.FAILED) {
goog.positioning.positionAtCoordinate(this.coordinate, element,
goog.positioning.Corner.TOP_START, margin, viewport,
goog.positioning.Overflow.ADJUST_X |
goog.positioning.Overflow.ADJUST_Y);
}
};
/**
* Popup position implementation that positions the popup (the tooltip in this
* case) based on the element position. It's positioned below the element to the
* right if there's enough room to fit all of it inside the Viewport. Otherwise
* it's displayed as far right as possible either above or below the element.
*
* Used to position tooltips triggered by focus changes.
*
* @param {Element} element The element to anchor the popup at.
* @constructor
* @extends {goog.positioning.AnchoredPosition}
*/
goog.ui.Tooltip.ElementTooltipPosition = function(element) {
goog.positioning.AnchoredPosition.call(this, element,
goog.positioning.Corner.BOTTOM_RIGHT);
};
goog.inherits(goog.ui.Tooltip.ElementTooltipPosition,
goog.positioning.AnchoredPosition);
/**
* Repositions the popup based on element position.
*
* @param {Element} element The DOM element of the popup.
* @param {goog.positioning.Corner} popupCorner The corner of the popup element
* that should be positioned adjacent to the anchorElement.
* @param {goog.math.Box=} opt_margin A margin specified in pixels.
* @override
*/
goog.ui.Tooltip.ElementTooltipPosition.prototype.reposition = function(
element, popupCorner, opt_margin) {
var offset = new goog.math.Coordinate(10, 0);
if (goog.positioning.positionAtAnchor(this.element, this.corner, element,
popupCorner, offset, opt_margin,
goog.positioning.Overflow.ADJUST_X | goog.positioning.Overflow.FAIL_Y
) & goog.positioning.OverflowStatus.FAILED) {
goog.positioning.positionAtAnchor(this.element,
goog.positioning.Corner.TOP_RIGHT, element,
goog.positioning.Corner.BOTTOM_LEFT, offset, opt_margin,
goog.positioning.Overflow.ADJUST_X |
goog.positioning.Overflow.ADJUST_Y);
}
};
| 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 tab control, designed to be used in {@link goog.ui.TabBar}s.
*
* @author attila@google.com (Attila Bodis)
* @see ../demos/tabbar.html
*/
goog.provide('goog.ui.Tab');
goog.require('goog.ui.Component.State');
goog.require('goog.ui.Control');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.TabRenderer');
goog.require('goog.ui.registry');
/**
* Tab control, designed to be hosted in a {@link goog.ui.TabBar}. The tab's
* DOM may be different based on the configuration of the containing tab bar,
* so tabs should only be rendered or decorated as children of a tab bar.
* @param {goog.ui.ControlContent} content Text caption or DOM structure to
* display as the tab's caption (if any).
* @param {goog.ui.TabRenderer=} opt_renderer Optional renderer used to render
* or decorate the tab.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
* document interaction.
* @constructor
* @extends {goog.ui.Control}
*/
goog.ui.Tab = function(content, opt_renderer, opt_domHelper) {
goog.ui.Control.call(this, content,
opt_renderer || goog.ui.TabRenderer.getInstance(), opt_domHelper);
// Tabs support the SELECTED state.
this.setSupportedState(goog.ui.Component.State.SELECTED, true);
// Tabs must dispatch state transition events for the DISABLED and SELECTED
// states in order for the tab bar to function properly.
this.setDispatchTransitionEvents(
goog.ui.Component.State.DISABLED | goog.ui.Component.State.SELECTED,
true);
};
goog.inherits(goog.ui.Tab, goog.ui.Control);
/**
* Tooltip text for the tab, displayed on hover (if any).
* @type {string|undefined}
* @private
*/
goog.ui.Tab.prototype.tooltip_;
/**
* @return {string|undefined} Tab tooltip text (if any).
*/
goog.ui.Tab.prototype.getTooltip = function() {
return this.tooltip_;
};
/**
* Sets the tab tooltip text. If the tab has already been rendered, updates
* its tooltip.
* @param {string} tooltip New tooltip text.
*/
goog.ui.Tab.prototype.setTooltip = function(tooltip) {
this.getRenderer().setTooltip(this.getElement(), tooltip);
this.setTooltipInternal(tooltip);
};
/**
* Sets the tab tooltip text. Considered protected; to be called only by the
* renderer during element decoration.
* @param {string} tooltip New tooltip text.
* @protected
*/
goog.ui.Tab.prototype.setTooltipInternal = function(tooltip) {
this.tooltip_ = tooltip;
};
// Register a decorator factory function for goog.ui.Tabs.
goog.ui.registry.setDecoratorByClassName(goog.ui.TabRenderer.CSS_CLASS,
function() {
return new goog.ui.Tab(null);
});
| 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 Common CSS class name constants.
*
* @author mkretzschmar@google.com (Martin Kretzschmar)
*/
goog.provide('goog.ui.INLINE_BLOCK_CLASSNAME');
/**
* CSS class name for applying the "display: inline-block" property in a
* cross-browser way.
* @type {string}
*/
goog.ui.INLINE_BLOCK_CLASSNAME = goog.getCssName('goog-inline-block');
| JavaScript |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Default renderer for {@link goog.ui.Tab}s. Based on the
* original {@code TabPane} code.
*
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.ui.TabRenderer');
goog.require('goog.a11y.aria.Role');
goog.require('goog.ui.Component.State');
goog.require('goog.ui.ControlRenderer');
/**
* Default renderer for {@link goog.ui.Tab}s, based on the {@code TabPane} code.
* @constructor
* @extends {goog.ui.ControlRenderer}
*/
goog.ui.TabRenderer = function() {
goog.ui.ControlRenderer.call(this);
};
goog.inherits(goog.ui.TabRenderer, goog.ui.ControlRenderer);
goog.addSingletonGetter(goog.ui.TabRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.TabRenderer.CSS_CLASS = goog.getCssName('goog-tab');
/**
* Returns the CSS class name to be applied to the root element of all tabs
* rendered or decorated using this renderer.
* @return {string} Renderer-specific CSS class name.
* @override
*/
goog.ui.TabRenderer.prototype.getCssClass = function() {
return goog.ui.TabRenderer.CSS_CLASS;
};
/**
* Returns the ARIA role to be applied to the tab element.
* See http://wiki/Main/ARIA for more info.
* @return {goog.a11y.aria.Role} ARIA role.
* @override
*/
goog.ui.TabRenderer.prototype.getAriaRole = function() {
return goog.a11y.aria.Role.TAB;
};
/**
* Returns the tab's contents wrapped in a DIV, with the renderer's own CSS
* class and additional state-specific classes applied to it. Creates the
* following DOM structure:
* <pre>
* <div class="goog-tab" title="Title">Content</div>
* </pre>
* @param {goog.ui.Control} tab Tab to render.
* @return {Element} Root element for the tab.
* @override
*/
goog.ui.TabRenderer.prototype.createDom = function(tab) {
var element = goog.ui.TabRenderer.superClass_.createDom.call(this, tab);
var tooltip = tab.getTooltip();
if (tooltip) {
// Only update the element if the tab has a tooltip.
this.setTooltip(element, tooltip);
}
return element;
};
/**
* Decorates the element with the tab. Initializes the tab's ID, content,
* tooltip, and state based on the ID of the element, its title, child nodes,
* and CSS classes, respectively. Returns the element.
* @param {goog.ui.Control} tab Tab to decorate the element.
* @param {Element} element Element to decorate.
* @return {Element} Decorated element.
* @override
*/
goog.ui.TabRenderer.prototype.decorate = function(tab, element) {
element = goog.ui.TabRenderer.superClass_.decorate.call(this, tab, element);
var tooltip = this.getTooltip(element);
if (tooltip) {
// Only update the tab if the element has a tooltip.
tab.setTooltipInternal(tooltip);
}
// If the tab is selected and hosted in a tab bar, update the tab bar's
// selection model.
if (tab.isSelected()) {
var tabBar = tab.getParent();
if (tabBar && goog.isFunction(tabBar.setSelectedTab)) {
// We need to temporarily deselect the tab, so the tab bar can re-select
// it and thereby correctly initialize its state. We use the protected
// setState() method to avoid dispatching useless events.
tab.setState(goog.ui.Component.State.SELECTED, false);
tabBar.setSelectedTab(tab);
}
}
return element;
};
/**
* Takes a tab's root element, and returns its tooltip text, or the empty
* string if the element has no tooltip.
* @param {Element} element The tab's root element.
* @return {string} The tooltip text (empty string if none).
*/
goog.ui.TabRenderer.prototype.getTooltip = function(element) {
return element.title || '';
};
/**
* Takes a tab's root element and a tooltip string, and updates the element
* with the new tooltip. If the new tooltip is null or undefined, sets the
* element's title to the empty string.
* @param {Element} element The tab's root element.
* @param {string|null|undefined} tooltip New tooltip text (if any).
*/
goog.ui.TabRenderer.prototype.setTooltip = function(element, tooltip) {
if (element) {
element.title = tooltip || '';
}
};
| 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 HSV (hue/saturation/value) color palette/picker
* implementation. Inspired by examples like
* http://johndyer.name/lab/colorpicker/ and the author's initial work. This
* control allows for more control in picking colors than a simple swatch-based
* palette. Without the styles from the demo css file, only a hex color label
* and input field show up.
*
* @author arv@google.com (Erik Arvidsson)
* @author smcbride@google.com (Sean McBride)
* @author manucornet@google.com (Manu Cornet)
* @see ../demos/hsvpalette.html
*/
goog.provide('goog.ui.HsvPalette');
goog.require('goog.color');
goog.require('goog.dom');
goog.require('goog.dom.DomHelper');
goog.require('goog.events');
goog.require('goog.events.Event');
goog.require('goog.events.EventType');
goog.require('goog.events.InputHandler');
goog.require('goog.style');
goog.require('goog.style.bidi');
goog.require('goog.ui.Component');
goog.require('goog.ui.Component.EventType');
goog.require('goog.userAgent');
/**
* Creates an HSV palette. Allows a user to select the hue, saturation and
* value/brightness.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @param {string=} opt_color Optional initial color (default is red).
* @param {string=} opt_class Optional base for creating classnames (default is
* goog.getCssName('goog-hsv-palette')).
* @extends {goog.ui.Component}
* @constructor
*/
goog.ui.HsvPalette = function(opt_domHelper, opt_color, opt_class) {
goog.ui.Component.call(this, opt_domHelper);
this.setColor_(opt_color || '#f00');
/**
* The base class name for the component.
* @type {string}
* @protected
*/
this.className = opt_class || goog.getCssName('goog-hsv-palette');
/**
* The document which is being listened to.
* type {HTMLDocument}
* @private
*/
this.document_ = this.getDomHelper().getDocument();
};
goog.inherits(goog.ui.HsvPalette, goog.ui.Component);
// TODO(user): Make this inherit from goog.ui.Control and split this into
// a control and a renderer.
/**
* DOM element representing the hue/saturation background image.
* @type {Element}
* @private
*/
goog.ui.HsvPalette.prototype.hsImageEl_;
/**
* DOM element representing the hue/saturation handle.
* @type {Element}
* @private
*/
goog.ui.HsvPalette.prototype.hsHandleEl_;
/**
* DOM element representing the value background image.
* @type {Element}
* @protected
*/
goog.ui.HsvPalette.prototype.valueBackgroundImageElement;
/**
* DOM element representing the value handle.
* @type {Element}
* @private
*/
goog.ui.HsvPalette.prototype.vHandleEl_;
/**
* DOM element representing the current color swatch.
* @type {Element}
* @protected
*/
goog.ui.HsvPalette.prototype.swatchElement;
/**
* DOM element representing the hex color input text field.
* @type {Element}
* @protected
*/
goog.ui.HsvPalette.prototype.inputElement;
/**
* Input handler object for the hex value input field.
* @type {goog.events.InputHandler}
* @private
*/
goog.ui.HsvPalette.prototype.inputHandler_;
/**
* Listener key for the mousemove event (during a drag operation).
* @type {goog.events.Key}
* @private
*/
goog.ui.HsvPalette.prototype.mouseMoveListener_;
/**
* Listener key for the mouseup event (during a drag operation).
* @type {goog.events.Key}
* @private
*/
goog.ui.HsvPalette.prototype.mouseUpListener_;
/**
* Gets the color that is currently selected in this color picker.
* @return {string} The string of the selected color.
*/
goog.ui.HsvPalette.prototype.getColor = function() {
return this.color_;
};
/**
* Alpha transparency of the currently selected color, in [0, 1].
* For the HSV palette this always returns 1. The HSVA palette overrides
* this method.
* @return {number} The current alpha value.
*/
goog.ui.HsvPalette.prototype.getAlpha = function() {
return 1;
};
/**
* Updates the text entry field.
* @protected
*/
goog.ui.HsvPalette.prototype.updateInput = function() {
var parsed;
try {
parsed = goog.color.parse(this.inputElement.value).hex;
} catch (e) {
// ignore
}
if (this.color_ != parsed) {
this.inputElement.value = this.color_;
}
};
/**
* Sets which color is selected and update the UI.
* @param {string} color The selected color.
*/
goog.ui.HsvPalette.prototype.setColor = function(color) {
if (color != this.color_) {
this.setColor_(color);
this.updateUi();
this.dispatchEvent(goog.ui.Component.EventType.ACTION);
}
};
/**
* Sets which color is selected.
* @param {string} color The selected color.
* @private
*/
goog.ui.HsvPalette.prototype.setColor_ = function(color) {
var rgbHex = goog.color.parse(color).hex;
var rgbArray = goog.color.hexToRgb(rgbHex);
this.hsv_ = goog.color.rgbArrayToHsv(rgbArray);
// Hue is divided by 360 because the documentation for goog.color is currently
// incorrect.
// TODO(user): Fix this, see http://1324469 .
this.hsv_[0] = this.hsv_[0] / 360;
this.color_ = rgbHex;
};
/**
* Alters the hue, saturation, and/or value of the currently selected color and
* updates the UI.
* @param {?number=} opt_hue (optional) hue in [0, 1].
* @param {?number=} opt_saturation (optional) saturation in [0, 1].
* @param {?number=} opt_value (optional) value in [0, 255].
*/
goog.ui.HsvPalette.prototype.setHsv = function(opt_hue,
opt_saturation,
opt_value) {
if (opt_hue != null || opt_saturation != null || opt_value != null) {
this.setHsv_(opt_hue, opt_saturation, opt_value);
this.updateUi();
this.dispatchEvent(goog.ui.Component.EventType.ACTION);
}
};
/**
* Alters the hue, saturation, and/or value of the currently selected color.
* @param {?number=} opt_hue (optional) hue in [0, 1].
* @param {?number=} opt_saturation (optional) saturation in [0, 1].
* @param {?number=} opt_value (optional) value in [0, 255].
* @private
*/
goog.ui.HsvPalette.prototype.setHsv_ = function(opt_hue,
opt_saturation,
opt_value) {
this.hsv_[0] = (opt_hue != null) ? opt_hue : this.hsv_[0];
this.hsv_[1] = (opt_saturation != null) ? opt_saturation : this.hsv_[1];
this.hsv_[2] = (opt_value != null) ? opt_value : this.hsv_[2];
// Hue is multiplied by 360 because the documentation for goog.color is
// currently incorrect.
// TODO(user): Fix this, see http://1324469 .
this.color_ = goog.color.hsvArrayToHex([
this.hsv_[0] * 360,
this.hsv_[1],
this.hsv_[2]
]);
};
/**
* HsvPalettes cannot be used to decorate pre-existing html, since the
* structure they build is fairly complicated.
* @param {Element} element Element to decorate.
* @return {boolean} Returns always false.
* @override
*/
goog.ui.HsvPalette.prototype.canDecorate = function(element) {
return false;
};
/** @override */
goog.ui.HsvPalette.prototype.createDom = function() {
var dom = this.getDomHelper();
var noalpha = (goog.userAgent.IE && !goog.userAgent.isVersion('7')) ?
' ' + goog.getCssName(this.className, 'noalpha') : '';
var backdrop = dom.createDom(goog.dom.TagName.DIV,
goog.getCssName(this.className, 'hs-backdrop'));
this.hsHandleEl_ = dom.createDom(goog.dom.TagName.DIV,
goog.getCssName(this.className, 'hs-handle'));
this.hsImageEl_ = dom.createDom(goog.dom.TagName.DIV,
goog.getCssName(this.className, 'hs-image'),
this.hsHandleEl_);
this.valueBackgroundImageElement = dom.createDom(
goog.dom.TagName.DIV,
goog.getCssName(this.className, 'v-image'));
this.vHandleEl_ = dom.createDom(
goog.dom.TagName.DIV,
goog.getCssName(this.className, 'v-handle'));
this.swatchElement = dom.createDom(goog.dom.TagName.DIV,
goog.getCssName(this.className, 'swatch'));
this.inputElement = dom.createDom('input', {
'class': goog.getCssName(this.className, 'input'),
'type': 'text', 'dir': 'ltr'
});
var labelElement = dom.createDom('label', null, this.inputElement);
var element = dom.createDom(goog.dom.TagName.DIV,
this.className + noalpha,
backdrop,
this.hsImageEl_,
this.valueBackgroundImageElement,
this.vHandleEl_,
this.swatchElement,
labelElement);
this.setElementInternal(element);
// TODO(arv): Set tabIndex
};
/**
* Renders the color picker inside the provided element. This will override the
* current content of the element.
* @override
*/
goog.ui.HsvPalette.prototype.enterDocument = function() {
goog.ui.HsvPalette.superClass_.enterDocument.call(this);
// TODO(user): Accessibility.
this.updateUi();
var handler = this.getHandler();
handler.listen(this.getElement(), goog.events.EventType.MOUSEDOWN,
this.handleMouseDown, false, this);
// Cannot create InputHandler in createDom because IE throws an exception
// on document.activeElement
if (!this.inputHandler_) {
this.inputHandler_ = new goog.events.InputHandler(this.inputElement);
}
handler.listen(this.inputHandler_,
goog.events.InputHandler.EventType.INPUT, this.handleInput, false, this);
};
/** @override */
goog.ui.HsvPalette.prototype.disposeInternal = function() {
goog.ui.HsvPalette.superClass_.disposeInternal.call(this);
delete this.hsImageEl_;
delete this.hsHandleEl_;
delete this.valueBackgroundImageElement;
delete this.vHandleEl_;
delete this.swatchElement;
delete this.inputElement;
if (this.inputHandler_) {
this.inputHandler_.dispose();
delete this.inputHandler_;
}
goog.events.unlistenByKey(this.mouseMoveListener_);
goog.events.unlistenByKey(this.mouseUpListener_);
};
/**
* Updates the position, opacity, and styles for the UI representation of the
* palette.
* @protected
*/
goog.ui.HsvPalette.prototype.updateUi = function() {
if (this.isInDocument()) {
var h = this.hsv_[0];
var s = this.hsv_[1];
var v = this.hsv_[2];
var left = this.hsImageEl_.offsetWidth * h;
// We don't use a flipped gradient image in RTL, so we need to flip the
// offset in RTL so that it still hovers over the correct color on the
// gradiant.
if (this.isRightToLeft()) {
left = this.hsImageEl_.offsetWidth - left;
}
// We also need to account for the handle size.
var handleOffset = Math.ceil(this.hsHandleEl_.offsetWidth / 2);
left -= handleOffset;
var top = this.hsImageEl_.offsetHeight * (1 - s);
// Account for the handle size.
top -= Math.ceil(this.hsHandleEl_.offsetHeight / 2);
goog.style.bidi.setPosition(this.hsHandleEl_, left, top,
this.isRightToLeft());
top = this.valueBackgroundImageElement.offsetTop -
Math.floor(this.vHandleEl_.offsetHeight / 2) +
this.valueBackgroundImageElement.offsetHeight * ((255 - v) / 255);
this.vHandleEl_.style.top = top + 'px';
goog.style.setOpacity(this.hsImageEl_, (v / 255));
goog.style.setStyle(this.valueBackgroundImageElement, 'background-color',
goog.color.hsvToHex(this.hsv_[0] * 360, this.hsv_[1], 255));
goog.style.setStyle(this.swatchElement, 'background-color', this.color_);
goog.style.setStyle(this.swatchElement, 'color',
(this.hsv_[2] > 255 / 2) ? '#000' : '#fff');
this.updateInput();
}
};
/**
* Handles mousedown events on palette UI elements.
* @param {goog.events.BrowserEvent} e Event object.
* @protected
*/
goog.ui.HsvPalette.prototype.handleMouseDown = function(e) {
if (e.target == this.valueBackgroundImageElement ||
e.target == this.vHandleEl_) {
// Setup value change listeners
var b = goog.style.getBounds(this.valueBackgroundImageElement);
this.handleMouseMoveV_(b, e);
this.mouseMoveListener_ = goog.events.listen(this.document_,
goog.events.EventType.MOUSEMOVE,
goog.bind(this.handleMouseMoveV_, this, b));
this.mouseUpListener_ = goog.events.listen(this.document_,
goog.events.EventType.MOUSEUP, this.handleMouseUp, false, this);
} else if (e.target == this.hsImageEl_ || e.target == this.hsHandleEl_) {
// Setup hue/saturation change listeners
var b = goog.style.getBounds(this.hsImageEl_);
this.handleMouseMoveHs_(b, e);
this.mouseMoveListener_ = goog.events.listen(this.document_,
goog.events.EventType.MOUSEMOVE,
goog.bind(this.handleMouseMoveHs_, this, b));
this.mouseUpListener_ = goog.events.listen(this.document_,
goog.events.EventType.MOUSEUP, this.handleMouseUp, false, this);
}
};
/**
* Handles mousemove events on the document once a drag operation on the value
* slider has started.
* @param {goog.math.Rect} b Boundaries of the value slider object at the start
* of the drag operation.
* @param {goog.events.BrowserEvent} e Event object.
* @private
*/
goog.ui.HsvPalette.prototype.handleMouseMoveV_ = function(b, e) {
e.preventDefault();
var vportPos = this.getDomHelper().getDocumentScroll();
var height = Math.min(
Math.max(vportPos.y + e.clientY, b.top),
b.top + b.height);
var newV = Math.round(
255 * (b.top + b.height - height) / b.height);
this.setHsv(null, null, newV);
};
/**
* Handles mousemove events on the document once a drag operation on the
* hue/saturation slider has started.
* @param {goog.math.Rect} b Boundaries of the value slider object at the start
* of the drag operation.
* @param {goog.events.BrowserEvent} e Event object.
* @private
*/
goog.ui.HsvPalette.prototype.handleMouseMoveHs_ = function(b, e) {
e.preventDefault();
var vportPos = this.getDomHelper().getDocumentScroll();
var newH = (Math.min(Math.max(vportPos.x + e.clientX, b.left),
b.left + b.width) - b.left) / b.width;
var newS = (-Math.min(Math.max(vportPos.y + e.clientY, b.top),
b.top + b.height) + b.top + b.height) / b.height;
this.setHsv(newH, newS, null);
};
/**
* Handles mouseup events on the document, which ends a drag operation.
* @param {goog.events.Event} e Event object.
* @protected
*/
goog.ui.HsvPalette.prototype.handleMouseUp = function(e) {
goog.events.unlistenByKey(this.mouseMoveListener_);
goog.events.unlistenByKey(this.mouseUpListener_);
};
/**
* Handles input events on the hex value input field.
* @param {goog.events.Event} e Event object.
* @protected
*/
goog.ui.HsvPalette.prototype.handleInput = function(e) {
if (/^#[0-9a-f]{6}$/i.test(this.inputElement.value)) {
this.setColor(this.inputElement.value);
}
};
| 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 Behavior for combining a color button and a menu.
*
* @see ../demos/split.html
*/
goog.provide('goog.ui.ColorSplitBehavior');
goog.require('goog.ui.ColorButton');
goog.require('goog.ui.ColorMenuButton');
goog.require('goog.ui.SplitBehavior');
/**
* Constructs a ColorSplitBehavior for combining a color button and a menu.
* To use this, provide a goog.ui.ColorButton which will be attached with
* a goog.ui.ColorMenuButton (with no caption).
* Whenever a color is selected from the ColorMenuButton, it will be placed in
* the ColorButton and the user can apply it over and over (by clicking the
* ColorButton).
* Primary use case - setting the color of text/background in a text editor.
*
* @param {!goog.ui.Button} colorButton A button to interact with a color menu
* button (preferably a goog.ui.ColorButton).
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
* document interaction.
* @extends {goog.ui.SplitBehavior}
* @constructor
*/
goog.ui.ColorSplitBehavior = function(colorButton, opt_domHelper) {
goog.base(this, colorButton,
new goog.ui.ColorMenuButton(goog.ui.ColorSplitBehavior.ZERO_WIDTH_SPACE_),
goog.ui.SplitBehavior.DefaultHandlers.VALUE,
undefined,
opt_domHelper);
};
goog.inherits(goog.ui.ColorSplitBehavior, goog.ui.SplitBehavior);
/**
* A zero width space character.
* @type {string}
* @private
*/
goog.ui.ColorSplitBehavior.ZERO_WIDTH_SPACE_ = '\uFEFF';
| 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 color button rendered via
* {@link goog.ui.ColorButtonRenderer}.
*
*/
goog.provide('goog.ui.ColorButton');
goog.require('goog.ui.Button');
goog.require('goog.ui.ColorButtonRenderer');
goog.require('goog.ui.registry');
/**
* A color button control. Identical to {@link goog.ui.Button}, except it
* defaults its renderer to {@link goog.ui.ColorButtonRenderer}.
* This button displays a particular color and is clickable.
* It is primarily useful with {@link goog.ui.ColorSplitBehavior} to cache the
* last selected color.
*
* @param {goog.ui.ControlContent} content Text caption or existing DOM
* structure to display as the button's caption.
* @param {goog.ui.ButtonRenderer=} opt_renderer Optional renderer used to
* render or decorate the button; defaults to
* {@link goog.ui.ColorButtonRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
* document interaction.
* @constructor
* @extends {goog.ui.Button}
*/
goog.ui.ColorButton = function(content, opt_renderer, opt_domHelper) {
goog.ui.Button.call(this, content, opt_renderer ||
goog.ui.ColorButtonRenderer.getInstance(), opt_domHelper);
};
goog.inherits(goog.ui.ColorButton, goog.ui.Button);
// Register a decorator factory function for goog.ui.ColorButtons.
goog.ui.registry.setDecoratorByClassName(goog.ui.ColorButtonRenderer.CSS_CLASS,
function() {
// ColorButton defaults to using ColorButtonRenderer.
return new goog.ui.ColorButton(null);
});
| 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 palette with a button for adding additional colors
* manually.
*
*/
goog.provide('goog.ui.CustomColorPalette');
goog.require('goog.color');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.ui.ColorPalette');
goog.require('goog.ui.Component');
/**
* A custom color palette is a grid of color swatches and a button that allows
* the user to add additional colors to the palette
*
* @param {Array.<string>} initColors Array of initial colors to populate the
* palette with.
* @param {goog.ui.PaletteRenderer=} opt_renderer Renderer used to render or
* decorate the palette; defaults to {@link goog.ui.PaletteRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
* document interaction.
* @constructor
* @extends {goog.ui.ColorPalette}
*/
goog.ui.CustomColorPalette = function(initColors, opt_renderer, opt_domHelper) {
goog.ui.ColorPalette.call(this, initColors, opt_renderer, opt_domHelper);
this.setSupportedState(goog.ui.Component.State.OPENED, true);
};
goog.inherits(goog.ui.CustomColorPalette, goog.ui.ColorPalette);
/**
* Returns an array of DOM nodes for each color, and an additional cell with a
* '+'.
* @return {Array.<Node>} Array of div elements.
* @override
*/
goog.ui.CustomColorPalette.prototype.createColorNodes = function() {
/** @desc Hover caption for the button that allows the user to add a color. */
var MSG_CLOSURE_CUSTOM_COLOR_BUTTON = goog.getMsg('Add a color');
var nl = goog.base(this, 'createColorNodes');
nl.push(goog.dom.createDom('div', {
'class': goog.getCssName('goog-palette-customcolor'),
'title': MSG_CLOSURE_CUSTOM_COLOR_BUTTON
}, '+'));
return nl;
};
/**
* @override
* @param {goog.events.Event} e Mouse or key event that triggered the action.
* @return {boolean} True if the action was allowed to proceed, false otherwise.
*/
goog.ui.CustomColorPalette.prototype.performActionInternal = function(e) {
var item = /** @type {Element} */ (this.getHighlightedItem());
if (item) {
if (goog.dom.classes.has(
item, goog.getCssName('goog-palette-customcolor'))) {
// User activated the special "add custom color" swatch.
this.promptForCustomColor();
} else {
// User activated a normal color swatch.
this.setSelectedItem(item);
return this.dispatchEvent(goog.ui.Component.EventType.ACTION);
}
}
return false;
};
/**
* Prompts the user to enter a custom color. Currently uses a window.prompt
* but could be updated to use a dialog box with a WheelColorPalette.
*/
goog.ui.CustomColorPalette.prototype.promptForCustomColor = function() {
/** @desc Default custom color dialog. */
var MSG_CLOSURE_CUSTOM_COLOR_PROMPT = goog.getMsg(
'Input custom color, i.e. pink, #F00, #D015FF or rgb(100, 50, 25)');
// A CustomColorPalette is considered "open" while the color selection prompt
// is open. Enabling state transition events for the OPENED state and
// listening for OPEN events allows clients to save the selection before
// it is destroyed (see e.g. bug 1064701).
var response = null;
this.setOpen(true);
if (this.isOpen()) {
// The OPEN event wasn't canceled; prompt for custom color.
response = window.prompt(MSG_CLOSURE_CUSTOM_COLOR_PROMPT, '#FFFFFF');
this.setOpen(false);
}
if (!response) {
// The user hit cancel
return;
}
var color;
/** @preserveTry */
try {
color = goog.color.parse(response).hex;
} catch (er) {
/** @desc Alert message sent when the input string is not a valid color. */
var MSG_CLOSURE_CUSTOM_COLOR_INVALID_INPUT = goog.getMsg(
'ERROR: "{$color}" is not a valid color.', {'color': response});
alert(MSG_CLOSURE_CUSTOM_COLOR_INVALID_INPUT);
return;
}
// TODO(user): This is relatively inefficient. Consider adding
// functionality to palette to add individual items after render time.
var colors = this.getColors();
colors.push(color);
this.setColors(colors);
// Set the selected color to the new color and notify listeners of the action.
this.setSelectedColor(color);
this.dispatchEvent(goog.ui.Component.EventType.ACTION);
};
| 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 Behavior for combining two controls.
*
* @see ../demos/split.html
*/
goog.provide('goog.ui.SplitBehavior');
goog.provide('goog.ui.SplitBehavior.DefaultHandlers');
goog.require('goog.Disposable');
goog.require('goog.array');
goog.require('goog.dispose');
goog.require('goog.dom');
goog.require('goog.dom.DomHelper');
goog.require('goog.dom.classes');
goog.require('goog.events');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventType');
goog.require('goog.string');
goog.require('goog.ui.ButtonSide');
goog.require('goog.ui.Component');
goog.require('goog.ui.Component.Error');
goog.require('goog.ui.INLINE_BLOCK_CLASSNAME');
goog.require('goog.ui.decorate');
goog.require('goog.ui.registry');
/**
* Creates a behavior for combining two controls. The behavior is triggered
* by a given event type which applies the behavior handler.
* Can be used to also render or decorate the controls.
* For a usage example see {@link goog.ui.ColorSplitBehavior}
*
* @param {goog.ui.Control} first A ui control.
* @param {goog.ui.Control} second A ui control.
* @param {function(goog.ui.Control,Event)=} opt_behaviorHandler A handler
* to apply for the behavior.
* @param {string=} opt_eventType The event type triggering the
* handler.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
* document interaction.
* @constructor
* @extends {goog.Disposable}
*/
goog.ui.SplitBehavior = function(first, second, opt_behaviorHandler,
opt_eventType, opt_domHelper) {
goog.Disposable.call(this);
/**
* @type {goog.ui.Control}
* @private
*/
this.first_ = first;
/**
* @type {goog.ui.Control}
* @private
*/
this.second_ = second;
/**
* Handler for this behavior.
* @type {function(goog.ui.Control,Event)}
* @private
*/
this.behaviorHandler_ = opt_behaviorHandler ||
goog.ui.SplitBehavior.DefaultHandlers.CAPTION;
/**
* Event type triggering the behavior.
* @type {string}
* @private
*/
this.eventType_ = opt_eventType || goog.ui.Component.EventType.ACTION;
/**
* @type {goog.dom.DomHelper}
* @private
*/
this.dom_ = opt_domHelper || goog.dom.getDomHelper();
/**
* True iff the behavior is active.
* @type {boolean}
* @private
*/
this.isActive_ = false;
/**
* Event handler.
* @type {goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler();
/**
* Whether to dispose the first control when dispose is called.
* @type {boolean}
* @private
*/
this.disposeFirst_ = true;
/**
* Whether to dispose the second control when dispose is called.
* @type {boolean}
* @private
*/
this.disposeSecond_ = true;
};
goog.inherits(goog.ui.SplitBehavior, goog.Disposable);
/**
* Css class for elements rendered by this behavior.
* @type {string}
*/
goog.ui.SplitBehavior.CSS_CLASS = goog.getCssName('goog-split-behavior');
/**
* An emum of split behavior handlers.
* @enum {function(goog.ui.Control,Event)}
*/
goog.ui.SplitBehavior.DefaultHandlers = {
NONE: goog.nullFunction,
CAPTION: function(targetControl, e) {
var item = /** @type {goog.ui.MenuItem} */ (e.target);
var value = (/** @type {string} */((item && item.getValue()) || ''));
var button = /** @type {goog.ui.Button} */ (targetControl);
button.setCaption && button.setCaption(value);
button.setValue && button.setValue(value);
},
VALUE: function(targetControl, e) {
var item = /** @type {goog.ui.MenuItem} */ (e.target);
var value = (/** @type {string} */(item && item.getValue()) || '');
var button = /** @type {goog.ui.Button} */ (targetControl);
button.setValue && button.setValue(value);
}
};
/**
* The element containing the controls.
* @type {Element}
* @private
*/
goog.ui.SplitBehavior.prototype.element_ = null;
/**
* @return {Element} The element containing the controls.
*/
goog.ui.SplitBehavior.prototype.getElement = function() {
return this.element_;
};
/**
* @return {function(goog.ui.Control,Event)} The behavior handler.
*/
goog.ui.SplitBehavior.prototype.getBehaviorHandler = function() {
return this.behaviorHandler_;
};
/**
* @return {string} The behavior event type.
*/
goog.ui.SplitBehavior.prototype.getEventType = function() {
return this.eventType_;
};
/**
* Sets the disposeControls flags.
* @param {boolean} disposeFirst Whether to dispose the first control
* when dispose is called.
* @param {boolean} disposeSecond Whether to dispose the second control
* when dispose is called.
*/
goog.ui.SplitBehavior.prototype.setDisposeControls = function(disposeFirst,
disposeSecond) {
this.disposeFirst_ = !!disposeFirst;
this.disposeSecond_ = !!disposeSecond;
};
/**
* Sets the behavior handler.
* @param {function(goog.ui.Control,Event)} behaviorHandler The behavior
* handler.
*/
goog.ui.SplitBehavior.prototype.setHandler = function(behaviorHandler) {
this.behaviorHandler_ = behaviorHandler;
if (this.isActive_) {
this.setActive(false);
this.setActive(true);
}
};
/**
* Sets the behavior event type.
* @param {string} eventType The behavior event type.
*/
goog.ui.SplitBehavior.prototype.setEventType = function(eventType) {
this.eventType_ = eventType;
if (this.isActive_) {
this.setActive(false);
this.setActive(true);
}
};
/**
* Decorates an element and returns the behavior.
* @param {Element} element An element to decorate.
* @param {boolean=} opt_activate Whether to activate the behavior
* (default=true).
* @return {goog.ui.SplitBehavior} A split behavior.
*/
goog.ui.SplitBehavior.prototype.decorate = function(element, opt_activate) {
if (this.first_ || this.second_) {
throw Error('Cannot decorate controls are already set');
}
this.decorateChildren_(element);
var activate = goog.isDefAndNotNull(opt_activate) ? !!opt_activate : true;
this.element_ = element;
this.setActive(activate);
return this;
};
/**
* Renders an element and returns the behavior.
* @param {Element} element An element to decorate.
* @param {boolean=} opt_activate Whether to activate the behavior
* (default=true).
* @return {goog.ui.SplitBehavior} A split behavior.
*/
goog.ui.SplitBehavior.prototype.render = function(element, opt_activate) {
goog.dom.classes.add(element, goog.ui.SplitBehavior.CSS_CLASS);
this.first_.render(element);
this.second_.render(element);
this.collapseSides_(this.first_, this.second_);
var activate = goog.isDefAndNotNull(opt_activate) ? !!opt_activate : true;
this.element_ = element;
this.setActive(activate);
return this;
};
/**
* Activate or deactivate the behavior.
* @param {boolean} activate Whether to activate or deactivate the behavior.
*/
goog.ui.SplitBehavior.prototype.setActive = function(activate) {
if (this.isActive_ == activate) {
return;
}
this.isActive_ = activate;
if (activate) {
this.eventHandler_.listen(this.second_, this.eventType_,
goog.bind(this.behaviorHandler_, this, this.first_));
// TODO(user): should we call the handler here to sync between
// first_ and second_.
} else {
this.eventHandler_.removeAll();
}
};
/** @override */
goog.ui.SplitBehavior.prototype.disposeInternal = function() {
this.setActive(false);
goog.dispose(this.eventHandler_);
if (this.disposeFirst_) {
goog.dispose(this.first_);
}
if (this.disposeSecond_) {
goog.dispose(this.second_);
}
goog.ui.SplitBehavior.superClass_.disposeInternal.call(this);
};
/**
* Decorates two child nodes of the given element.
* @param {Element} element An element to render two of it's child nodes.
* @private
*/
goog.ui.SplitBehavior.prototype.decorateChildren_ = function(
element) {
var childNodes = element.childNodes;
var len = childNodes.length;
var finished = false;
for (var i = 0; i < len && !finished; i++) {
var child = childNodes[i];
if (child.nodeType == goog.dom.NodeType.ELEMENT) {
if (!this.first_) {
this.first_ = /** @type {goog.ui.Control} */ (goog.ui.decorate(child));
} else if (!this.second_) {
this.second_ = /** @type {goog.ui.Control} */ (goog.ui.decorate(child));
finished = true;
}
}
}
};
/**
* Collapse the the controls together.
* @param {goog.ui.Control} first The first element.
* @param {goog.ui.Control} second The second element.
* @private
*/
goog.ui.SplitBehavior.prototype.collapseSides_ = function(first, second) {
if (goog.isFunction(first.setCollapsed) &&
goog.isFunction(second.setCollapsed)) {
first.setCollapsed(goog.ui.ButtonSide.END);
second.setCollapsed(goog.ui.ButtonSide.START);
}
};
// Register a decorator factory function for goog.ui.Buttons.
goog.ui.registry.setDecoratorByClassName(goog.ui.SplitBehavior.CSS_CLASS,
function() {
return new goog.ui.SplitBehavior(null, null);
});
| 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 button control.
*
* @author attila@google.com (Attila Bodis)
* @see ../demos/menubutton.html
*/
goog.provide('goog.ui.MenuButton');
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.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.events.KeyHandler.EventType');
goog.require('goog.math.Box');
goog.require('goog.math.Rect');
goog.require('goog.positioning');
goog.require('goog.positioning.Corner');
goog.require('goog.positioning.MenuAnchoredPosition');
goog.require('goog.style');
goog.require('goog.ui.Button');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.Component.State');
goog.require('goog.ui.Menu');
goog.require('goog.ui.MenuButtonRenderer');
goog.require('goog.ui.registry');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');
/**
* A menu button control. Extends {@link goog.ui.Button} by composing a button
* with a dropdown arrow and a popup menu.
*
* @param {goog.ui.ControlContent} content Text caption or existing DOM
* structure to display as the button's caption (if any).
* @param {goog.ui.Menu=} opt_menu Menu to render under the button when clicked.
* @param {goog.ui.ButtonRenderer=} opt_renderer Renderer used to render or
* decorate the menu button; defaults to {@link goog.ui.MenuButtonRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
* document interaction.
* @constructor
* @extends {goog.ui.Button}
*/
goog.ui.MenuButton = function(content, opt_menu, opt_renderer, opt_domHelper) {
goog.ui.Button.call(this, content, opt_renderer ||
goog.ui.MenuButtonRenderer.getInstance(), opt_domHelper);
// Menu buttons support the OPENED state.
this.setSupportedState(goog.ui.Component.State.OPENED, true);
/**
* The menu position on this button.
* @type {!goog.positioning.AnchoredPosition}
* @private
*/
this.menuPosition_ = new goog.positioning.MenuAnchoredPosition(
null, goog.positioning.Corner.BOTTOM_START);
if (opt_menu) {
this.setMenu(opt_menu);
}
this.menuMargin_ = null;
this.timer_ = new goog.Timer(500); // 0.5 sec
// Phones running iOS prior to version 4.2.
if ((goog.userAgent.product.IPHONE || goog.userAgent.product.IPAD) &&
// Check the webkit version against the version for iOS 4.2.1.
!goog.userAgent.isVersion('533.17.9')) {
// @bug 4322060 This is required so that the menu works correctly on
// iOS prior to version 4.2. Otherwise, the blur action closes the menu
// before the menu button click can be processed.
this.setFocusablePopupMenu(true);
}
};
goog.inherits(goog.ui.MenuButton, goog.ui.Button);
/**
* The menu.
* @type {goog.ui.Menu|undefined}
* @private
*/
goog.ui.MenuButton.prototype.menu_;
/**
* The position element. If set, use positionElement_ to position the
* popup menu instead of the default which is to use the menu button element.
* @type {Element|undefined}
* @private
*/
goog.ui.MenuButton.prototype.positionElement_;
/**
* The margin to apply to the menu's position when it is shown. If null, no
* margin will be applied.
* @type {goog.math.Box}
* @private
*/
goog.ui.MenuButton.prototype.menuMargin_;
/**
* Whether the attached popup menu is focusable or not (defaults to false).
* Popup menus attached to menu buttons usually don't need to be focusable,
* i.e. the button retains keyboard focus, and forwards key events to the
* menu for processing. However, menus like {@link goog.ui.FilteredMenu}
* need to be focusable.
* @type {boolean}
* @private
*/
goog.ui.MenuButton.prototype.isFocusablePopupMenu_ = false;
/**
* A Timer to correct menu position.
* @type {goog.Timer}
* @private
*/
goog.ui.MenuButton.prototype.timer_;
/**
* The bounding rectangle of the button element.
* @type {goog.math.Rect}
* @private
*/
goog.ui.MenuButton.prototype.buttonRect_;
/**
* The viewport rectangle.
* @type {goog.math.Box}
* @private
*/
goog.ui.MenuButton.prototype.viewportBox_;
/**
* The original size.
* @type {goog.math.Size|undefined}
* @private
*/
goog.ui.MenuButton.prototype.originalSize_;
/**
* Do we render the drop down menu as a sibling to the label, or at the end
* of the current dom?
* @type {boolean}
* @private
*/
goog.ui.MenuButton.prototype.renderMenuAsSibling_ = false;
/**
* Sets up event handlers specific to menu buttons.
* @override
*/
goog.ui.MenuButton.prototype.enterDocument = function() {
goog.ui.MenuButton.superClass_.enterDocument.call(this);
if (this.menu_) {
this.attachMenuEventListeners_(this.menu_, true);
}
var element = this.getElement();
goog.asserts.assert(element, 'The menu button DOM element cannot be null.');
goog.a11y.aria.setState(element, goog.a11y.aria.State.HASPOPUP, 'true');
};
/**
* Removes event handlers specific to menu buttons, and ensures that the
* attached menu also exits the document.
* @override
*/
goog.ui.MenuButton.prototype.exitDocument = function() {
goog.ui.MenuButton.superClass_.exitDocument.call(this);
if (this.menu_) {
this.setOpen(false);
this.menu_.exitDocument();
this.attachMenuEventListeners_(this.menu_, false);
var menuElement = this.menu_.getElement();
if (menuElement) {
goog.dom.removeNode(menuElement);
}
}
};
/** @override */
goog.ui.MenuButton.prototype.disposeInternal = function() {
goog.ui.MenuButton.superClass_.disposeInternal.call(this);
if (this.menu_) {
this.menu_.dispose();
delete this.menu_;
}
delete this.positionElement_;
this.timer_.dispose();
};
/**
* Handles mousedown events. Invokes the superclass implementation to dispatch
* an ACTIVATE event and activate the button. Also toggles the visibility of
* the attached menu.
* @param {goog.events.Event} e Mouse event to handle.
* @override
* @protected
*/
goog.ui.MenuButton.prototype.handleMouseDown = function(e) {
goog.ui.MenuButton.superClass_.handleMouseDown.call(this, e);
if (this.isActive()) {
// The component was allowed to activate; toggle menu visibility.
this.setOpen(!this.isOpen(), e);
if (this.menu_) {
this.menu_.setMouseButtonPressed(this.isOpen());
}
}
};
/**
* Handles mouseup events. Invokes the superclass implementation to dispatch
* an ACTION event and deactivate the button.
* @param {goog.events.Event} e Mouse event to handle.
* @override
* @protected
*/
goog.ui.MenuButton.prototype.handleMouseUp = function(e) {
goog.ui.MenuButton.superClass_.handleMouseUp.call(this, e);
if (this.menu_ && !this.isActive()) {
this.menu_.setMouseButtonPressed(false);
}
};
/**
* Performs the appropriate action when the menu button is activated by the
* user. Overrides the superclass implementation by not dispatching an {@code
* ACTION} event, because menu buttons exist only to reveal menus, not to
* perform actions themselves. Calls {@link #setActive} to deactivate the
* button.
* @param {goog.events.Event} e Mouse or key event that triggered the action.
* @return {boolean} Whether the action was allowed to proceed.
* @override
* @protected
*/
goog.ui.MenuButton.prototype.performActionInternal = function(e) {
this.setActive(false);
return true;
};
/**
* Handles mousedown events over the document. If the mousedown happens over
* an element unrelated to the component, hides the menu.
* TODO(attila): Reconcile this with goog.ui.Popup (and handle frames/windows).
* @param {goog.events.BrowserEvent} e Mouse event to handle.
* @protected
*/
goog.ui.MenuButton.prototype.handleDocumentMouseDown = function(e) {
if (this.menu_ &&
this.menu_.isVisible() &&
!this.containsElement(/** @type {Element} */ (e.target))) {
// User clicked somewhere else in the document while the menu was visible;
// dismiss menu.
this.setOpen(false);
}
};
/**
* Returns true if the given element is to be considered part of the component,
* even if it isn't a DOM descendant of the component's root element.
* @param {Element} element Element to test (if any).
* @return {boolean} Whether the element is considered part of the component.
* @protected
*/
goog.ui.MenuButton.prototype.containsElement = function(element) {
return element && goog.dom.contains(this.getElement(), element) ||
this.menu_ && this.menu_.containsElement(element) || false;
};
/** @override */
goog.ui.MenuButton.prototype.handleKeyEventInternal = function(e) {
// Handle SPACE on keyup and all other keys on keypress.
if (e.keyCode == goog.events.KeyCodes.SPACE) {
// Prevent page scrolling in Chrome.
e.preventDefault();
if (e.type != goog.events.EventType.KEYUP) {
// Ignore events because KeyCodes.SPACE is handled further down.
return true;
}
} else if (e.type != goog.events.KeyHandler.EventType.KEY) {
return false;
}
if (this.menu_ && this.menu_.isVisible()) {
// Menu is open.
var handledByMenu = this.menu_.handleKeyEvent(e);
if (e.keyCode == goog.events.KeyCodes.ESC) {
// Dismiss the menu.
this.setOpen(false);
return true;
}
return handledByMenu;
}
if (e.keyCode == goog.events.KeyCodes.DOWN ||
e.keyCode == goog.events.KeyCodes.UP ||
e.keyCode == goog.events.KeyCodes.SPACE ||
e.keyCode == goog.events.KeyCodes.ENTER) {
// Menu is closed, and the user hit the down/up/space/enter key; open menu.
this.setOpen(true);
return true;
}
// Key event wasn't handled by the component.
return false;
};
/**
* Handles {@code ACTION} events dispatched by an activated menu item.
* @param {goog.events.Event} e Action event to handle.
* @protected
*/
goog.ui.MenuButton.prototype.handleMenuAction = function(e) {
// Close the menu on click.
this.setOpen(false);
};
/**
* Handles {@code BLUR} events dispatched by the popup menu by closing it.
* Only registered if the menu is focusable.
* @param {goog.events.Event} e Blur event dispatched by a focusable menu.
*/
goog.ui.MenuButton.prototype.handleMenuBlur = function(e) {
// Close the menu when it reports that it lost focus, unless the button is
// pressed (active).
if (!this.isActive()) {
this.setOpen(false);
}
};
/**
* Handles blur events dispatched by the button's key event target when it
* loses keyboard focus by closing the popup menu (unless it is focusable).
* Only registered if the button is focusable.
* @param {goog.events.Event} e Blur event dispatched by the menu button.
* @override
* @protected
*/
goog.ui.MenuButton.prototype.handleBlur = function(e) {
if (!this.isFocusablePopupMenu()) {
this.setOpen(false);
}
goog.ui.MenuButton.superClass_.handleBlur.call(this, e);
};
/**
* Returns the menu attached to the button. If no menu is attached, creates a
* new empty menu.
* @return {goog.ui.Menu} Popup menu attached to the menu button.
*/
goog.ui.MenuButton.prototype.getMenu = function() {
if (!this.menu_) {
this.setMenu(new goog.ui.Menu(this.getDomHelper()));
}
return this.menu_ || null;
};
/**
* Replaces the menu attached to the button with the argument, and returns the
* previous menu (if any).
* @param {goog.ui.Menu?} menu New menu to be attached to the menu button (null
* to remove the menu).
* @return {goog.ui.Menu|undefined} Previous menu (undefined if none).
*/
goog.ui.MenuButton.prototype.setMenu = function(menu) {
var oldMenu = this.menu_;
// Do nothing unless the new menu is different from the current one.
if (menu != oldMenu) {
if (oldMenu) {
this.setOpen(false);
if (this.isInDocument()) {
this.attachMenuEventListeners_(oldMenu, false);
}
delete this.menu_;
}
if (menu) {
this.menu_ = menu;
menu.setParent(this);
menu.setVisible(false);
menu.setAllowAutoFocus(this.isFocusablePopupMenu());
if (this.isInDocument()) {
this.attachMenuEventListeners_(menu, true);
}
}
}
return oldMenu;
};
/**
* Specify which positioning algorithm to use.
*
* This method is preferred over the fine-grained positioning methods like
* setPositionElement, setAlignMenuToStart, and setScrollOnOverflow. Calling
* this method will override settings by those methods.
*
* @param {goog.positioning.AnchoredPosition} position The position of the
* Menu the button. If the position has a null anchor, we will use the
* menubutton element as the anchor.
*/
goog.ui.MenuButton.prototype.setMenuPosition = function(position) {
if (position) {
this.menuPosition_ = position;
this.positionElement_ = position.element;
}
};
/**
* Sets an element for anchoring the menu.
* @param {Element} positionElement New element to use for
* positioning the dropdown menu. Null to use the default behavior
* of positioning to this menu button.
*/
goog.ui.MenuButton.prototype.setPositionElement = function(
positionElement) {
this.positionElement_ = positionElement;
this.positionMenu();
};
/**
* Sets a margin that will be applied to the menu's position when it is shown.
* If null, no margin will be applied.
* @param {goog.math.Box} margin Margin to apply.
*/
goog.ui.MenuButton.prototype.setMenuMargin = function(margin) {
this.menuMargin_ = margin;
};
/**
* Adds a new menu item at the end of the menu.
* @param {goog.ui.MenuItem|goog.ui.MenuSeparator|goog.ui.Control} item Menu
* item to add to the menu.
*/
goog.ui.MenuButton.prototype.addItem = function(item) {
this.getMenu().addChild(item, true);
};
/**
* Adds a new menu item at the specific index in the menu.
* @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item Menu item to add to the
* menu.
* @param {number} index Index at which to insert the menu item.
*/
goog.ui.MenuButton.prototype.addItemAt = function(item, index) {
this.getMenu().addChildAt(item, index, true);
};
/**
* Removes the item from the menu and disposes of it.
* @param {goog.ui.MenuItem|goog.ui.MenuSeparator} item The menu item to remove.
*/
goog.ui.MenuButton.prototype.removeItem = function(item) {
var child = this.getMenu().removeChild(item, true);
if (child) {
child.dispose();
}
};
/**
* Removes the menu item at a given index in the menu and disposes of it.
* @param {number} index Index of item.
*/
goog.ui.MenuButton.prototype.removeItemAt = function(index) {
var child = this.getMenu().removeChildAt(index, true);
if (child) {
child.dispose();
}
};
/**
* Returns the menu item at a given index.
* @param {number} index Index of menu item.
* @return {goog.ui.MenuItem?} Menu item (null if not found).
*/
goog.ui.MenuButton.prototype.getItemAt = function(index) {
return this.menu_ ?
/** @type {goog.ui.MenuItem} */ (this.menu_.getChildAt(index)) : null;
};
/**
* Returns the number of items in the menu (including separators).
* @return {number} The number of items in the menu.
*/
goog.ui.MenuButton.prototype.getItemCount = function() {
return this.menu_ ? this.menu_.getChildCount() : 0;
};
/**
* Shows/hides the menu button based on the value of the argument. Also hides
* the popup menu if the button is being hidden.
* @param {boolean} visible Whether to show or hide the button.
* @param {boolean=} opt_force If true, doesn't check whether the component
* already has the requested visibility, and doesn't dispatch any events.
* @return {boolean} Whether the visibility was changed.
* @override
*/
goog.ui.MenuButton.prototype.setVisible = function(visible, opt_force) {
var visibilityChanged = goog.ui.MenuButton.superClass_.setVisible.call(this,
visible, opt_force);
if (visibilityChanged && !this.isVisible()) {
this.setOpen(false);
}
return visibilityChanged;
};
/**
* Enables/disables the menu button based on the value of the argument, and
* updates its CSS styling. Also hides the popup menu if the button is being
* disabled.
* @param {boolean} enable Whether to enable or disable the button.
* @override
*/
goog.ui.MenuButton.prototype.setEnabled = function(enable) {
goog.ui.MenuButton.superClass_.setEnabled.call(this, enable);
if (!this.isEnabled()) {
this.setOpen(false);
}
};
// TODO(nicksantos): AlignMenuToStart and ScrollOnOverflow and PositionElement
// should all be deprecated, in favor of people setting their own
// AnchoredPosition with the parameters they need. Right now, we try
// to be backwards-compatible as possible, but this is incomplete because
// the APIs are non-orthogonal.
/**
* @return {boolean} Whether the menu is aligned to the start of the button
* (left if the render direction is left-to-right, right if the render
* direction is right-to-left).
*/
goog.ui.MenuButton.prototype.isAlignMenuToStart = function() {
var corner = this.menuPosition_.corner;
return corner == goog.positioning.Corner.BOTTOM_START ||
corner == goog.positioning.Corner.TOP_START;
};
/**
* Sets whether the menu is aligned to the start or the end of the button.
* @param {boolean} alignToStart Whether the menu is to be aligned to the start
* of the button (left if the render direction is left-to-right, right if
* the render direction is right-to-left).
*/
goog.ui.MenuButton.prototype.setAlignMenuToStart = function(alignToStart) {
this.menuPosition_.corner = alignToStart ?
goog.positioning.Corner.BOTTOM_START :
goog.positioning.Corner.BOTTOM_END;
};
/**
* Sets whether the menu should scroll when it's too big to fix vertically on
* the screen. The css of the menu element should have overflow set to auto.
* Note: Adding or removing items while the menu is open will not work correctly
* if scrollOnOverflow is on.
* @param {boolean} scrollOnOverflow Whether the menu should scroll when too big
* to fit on the screen. If false, adjust logic will be used to try and
* reposition the menu to fit.
*/
goog.ui.MenuButton.prototype.setScrollOnOverflow = function(scrollOnOverflow) {
if (this.menuPosition_.setLastResortOverflow) {
var overflowX = goog.positioning.Overflow.ADJUST_X;
var overflowY = scrollOnOverflow ?
goog.positioning.Overflow.RESIZE_HEIGHT :
goog.positioning.Overflow.ADJUST_Y;
this.menuPosition_.setLastResortOverflow(overflowX | overflowY);
}
};
/**
* @return {boolean} Wether the menu will scroll when it's to big to fit
* vertically on the screen.
*/
goog.ui.MenuButton.prototype.isScrollOnOverflow = function() {
return this.menuPosition_.getLastResortOverflow &&
!!(this.menuPosition_.getLastResortOverflow() &
goog.positioning.Overflow.RESIZE_HEIGHT);
};
/**
* @return {boolean} Whether the attached menu is focusable.
*/
goog.ui.MenuButton.prototype.isFocusablePopupMenu = function() {
return this.isFocusablePopupMenu_;
};
/**
* Sets whether the attached popup menu is focusable. If the popup menu is
* focusable, it may steal keyboard focus from the menu button, so the button
* will not hide the menu on blur.
* @param {boolean} focusable Whether the attached menu is focusable.
*/
goog.ui.MenuButton.prototype.setFocusablePopupMenu = function(focusable) {
// TODO(attila): The menu itself should advertise whether it is focusable.
this.isFocusablePopupMenu_ = focusable;
};
/**
* Sets whether to render the menu as a sibling element of the button.
* Normally, the menu is a child of document.body. This option is useful if
* you need the menu to inherit styles from a common parent element, or if you
* otherwise need it to share a parent element for desired event handling. One
* example of the latter is if the parent is in a goog.ui.Popup, to ensure that
* clicks on the menu are considered being within the popup.
* @param {boolean} renderMenuAsSibling Whether we render the menu at the end
* of the dom or as a sibling to the button/label that renders the drop
* down.
*/
goog.ui.MenuButton.prototype.setRenderMenuAsSibling = function(
renderMenuAsSibling) {
this.renderMenuAsSibling_ = renderMenuAsSibling;
};
/**
* Reveals the menu and hooks up menu-specific event handling.
* @deprecated Use {@link #setOpen} instead.
*/
goog.ui.MenuButton.prototype.showMenu = function() {
this.setOpen(true);
};
/**
* Hides the menu and cleans up menu-specific event handling.
* @deprecated Use {@link #setOpen} instead.
*/
goog.ui.MenuButton.prototype.hideMenu = function() {
this.setOpen(false);
};
/**
* Opens or closes the attached popup menu.
* @param {boolean} open Whether to open or close the menu.
* @param {goog.events.Event=} opt_e Mousedown event that caused the menu to
* be opened.
* @override
*/
goog.ui.MenuButton.prototype.setOpen = function(open, opt_e) {
goog.ui.MenuButton.superClass_.setOpen.call(this, open);
if (this.menu_ && this.hasState(goog.ui.Component.State.OPENED) == open) {
if (open) {
if (!this.menu_.isInDocument()) {
if (this.renderMenuAsSibling_) {
this.menu_.render(/** @type {Element} */ (
this.getElement().parentNode));
} else {
this.menu_.render();
}
}
this.viewportBox_ =
goog.style.getVisibleRectForElement(this.getElement());
this.buttonRect_ = goog.style.getBounds(this.getElement());
this.positionMenu();
this.menu_.setHighlightedIndex(-1);
} else {
this.setActive(false);
this.menu_.setMouseButtonPressed(false);
var element = this.getElement();
// Clear any remaining a11y state.
if (element) {
goog.a11y.aria.setState(element,
goog.a11y.aria.State.ACTIVEDESCENDANT,
'');
}
// Clear any sizes that might have been stored.
if (goog.isDefAndNotNull(this.originalSize_)) {
this.originalSize_ = undefined;
var elem = this.menu_.getElement();
if (elem) {
goog.style.setSize(elem, '', '');
}
}
}
this.menu_.setVisible(open, false, opt_e);
// In Pivot Tables the menu button somehow gets disposed of during the
// setVisible call, causing attachPopupListeners_ to fail.
// TODO(user): Debug what happens.
if (!this.isDisposed()) {
this.attachPopupListeners_(open);
}
}
};
/**
* Resets the MenuButton's size. This is useful for cases where items are added
* or removed from the menu and scrollOnOverflow is on. In those cases the
* menu will not behave correctly and resize itself unless this is called
* (usually followed by positionMenu()).
*/
goog.ui.MenuButton.prototype.invalidateMenuSize = function() {
this.originalSize_ = undefined;
};
/**
* Positions the menu under the button. May be called directly in cases when
* the menu size is known to change.
*/
goog.ui.MenuButton.prototype.positionMenu = function() {
if (!this.menu_.isInDocument()) {
return;
}
var positionElement = this.positionElement_ || this.getElement();
var position = this.menuPosition_;
this.menuPosition_.element = positionElement;
var elem = this.menu_.getElement();
if (!this.menu_.isVisible()) {
elem.style.visibility = 'hidden';
goog.style.setElementShown(elem, true);
}
if (!this.originalSize_ && this.isScrollOnOverflow()) {
this.originalSize_ = goog.style.getSize(elem);
}
var popupCorner = goog.positioning.flipCornerVertical(position.corner);
position.reposition(elem, popupCorner, this.menuMargin_, this.originalSize_);
if (!this.menu_.isVisible()) {
goog.style.setElementShown(elem, false);
elem.style.visibility = 'visible';
}
};
/**
* Periodically repositions the menu while it is visible.
*
* @param {goog.events.Event} e An event object.
* @private
*/
goog.ui.MenuButton.prototype.onTick_ = function(e) {
// Call positionMenu() only if the button position or size was
// changed, or if the window's viewport was changed.
var currentButtonRect = goog.style.getBounds(this.getElement());
var currentViewport = goog.style.getVisibleRectForElement(this.getElement());
if (!goog.math.Rect.equals(this.buttonRect_, currentButtonRect) ||
!goog.math.Box.equals(this.viewportBox_, currentViewport)) {
this.buttonRect_ = currentButtonRect;
this.viewportBox_ = currentViewport;
this.positionMenu();
}
};
/**
* Attaches or detaches menu event listeners to/from the given menu.
* Called each time a menu is attached to or detached from the button.
* @param {goog.ui.Menu} menu Menu on which to listen for events.
* @param {boolean} attach Whether to attach or detach event listeners.
* @private
*/
goog.ui.MenuButton.prototype.attachMenuEventListeners_ = function(menu,
attach) {
var handler = this.getHandler();
var method = attach ? handler.listen : handler.unlisten;
// Handle events dispatched by menu items.
method.call(handler, menu, goog.ui.Component.EventType.ACTION,
this.handleMenuAction);
method.call(handler, menu, goog.ui.Component.EventType.HIGHLIGHT,
this.handleHighlightItem);
method.call(handler, menu, goog.ui.Component.EventType.UNHIGHLIGHT,
this.handleUnHighlightItem);
};
/**
* Handles {@code HIGHLIGHT} events dispatched by the attached menu.
* @param {goog.events.Event} e Highlight event to handle.
*/
goog.ui.MenuButton.prototype.handleHighlightItem = function(e) {
var element = this.getElement();
goog.asserts.assert(element, 'The menu button DOM element cannot be null.');
if (e.target.getElement() != null) {
goog.a11y.aria.setState(element,
goog.a11y.aria.State.ACTIVEDESCENDANT,
e.target.getElement().id);
}
};
/**
* Handles UNHIGHLIGHT events dispatched by the associated menu.
* @param {goog.events.Event} e Unhighlight event to handle.
*/
goog.ui.MenuButton.prototype.handleUnHighlightItem = function(e) {
if (!this.menu_.getHighlighted()) {
var element = this.getElement();
goog.asserts.assert(element, 'The menu button DOM element cannot be null.');
goog.a11y.aria.setState(element,
goog.a11y.aria.State.ACTIVEDESCENDANT,
'');
}
};
/**
* Attaches or detaches event listeners depending on whether the popup menu
* is being shown or hidden. Starts listening for document mousedown events
* and for menu blur events when the menu is shown, and stops listening for
* these events when it is hidden. Called from {@link #setOpen}.
* @param {boolean} attach Whether to attach or detach event listeners.
* @private
*/
goog.ui.MenuButton.prototype.attachPopupListeners_ = function(attach) {
var handler = this.getHandler();
var method = attach ? handler.listen : handler.unlisten;
// Listen for document mousedown events in the capture phase, because
// the target may stop propagation of the event in the bubble phase.
method.call(handler, this.getDomHelper().getDocument(),
goog.events.EventType.MOUSEDOWN, this.handleDocumentMouseDown, true);
// Only listen for blur events dispatched by the menu if it is focusable.
if (this.isFocusablePopupMenu()) {
method.call(handler, /** @type {goog.events.EventTarget} */ (this.menu_),
goog.ui.Component.EventType.BLUR, this.handleMenuBlur);
}
method.call(handler, this.timer_, goog.Timer.TICK, this.onTick_);
if (attach) {
this.timer_.start();
} else {
this.timer_.stop();
}
};
// Register a decorator factory function for goog.ui.MenuButtons.
goog.ui.registry.setDecoratorByClassName(goog.ui.MenuButtonRenderer.CSS_CLASS,
function() {
// MenuButton defaults to using MenuButtonRenderer.
return new goog.ui.MenuButton(null);
});
| 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 Zippy widget implementation.
*
* @author eae@google.com (Emil A Eklund)
* @see ../demos/zippy.html
*/
goog.provide('goog.ui.Zippy');
goog.provide('goog.ui.Zippy.Events');
goog.provide('goog.ui.ZippyEvent');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.Role');
goog.require('goog.a11y.aria.State');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.events');
goog.require('goog.events.Event');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.style');
/**
* Zippy widget. Expandable/collapsible container, clicking the header toggles
* the visibility of the content.
*
* @extends {goog.events.EventTarget}
* @param {Element|string|null} header Header element, either element
* reference, string id or null if no header exists.
* @param {Element|string|function():Element=} opt_content Content element
* (if any), either element reference or string id. If skipped, the caller
* should handle the TOGGLE event in its own way. If a function is passed,
* then if will be called to create the content element the first time the
* zippy is expanded.
* @param {boolean=} opt_expanded Initial expanded/visibility state. Defaults to
* false.
* @param {Element|string=} opt_expandedHeader Element to use as the header when
* the zippy is expanded.
* @param {goog.dom.DomHelper=} opt_domHelper An optional DOM helper.
* @constructor
*/
goog.ui.Zippy = function(header, opt_content, opt_expanded,
opt_expandedHeader, opt_domHelper) {
goog.base(this);
/**
* DomHelper used to interact with the document, allowing components to be
* created in a different window.
* @type {!goog.dom.DomHelper}
* @private
*/
this.dom_ = opt_domHelper || goog.dom.getDomHelper();
/**
* Header element or null if no header exists.
* @type {Element}
* @private
*/
this.elHeader_ = this.dom_.getElement(header) || null;
/**
* When present, the header to use when the zippy is expanded.
* @type {Element}
* @private
*/
this.elExpandedHeader_ = this.dom_.getElement(opt_expandedHeader || null);
/**
* Function that will create the content element, or false if there is no such
* function.
* @type {?function():Element}
* @private
*/
this.lazyCreateFunc_ = goog.isFunction(opt_content) ? opt_content : null;
/**
* Content element.
* @type {Element}
* @private
*/
this.elContent_ = this.lazyCreateFunc_ || !opt_content ? null :
this.dom_.getElement(/** @type {Element} */ (opt_content));
/**
* Expanded state.
* @type {boolean}
* @private
*/
this.expanded_ = opt_expanded == true;
/**
* A keyboard events handler. If there are two headers it is shared for both.
* @type {goog.events.EventHandler}
* @private
*/
this.keyboardEventHandler_ = new goog.events.EventHandler(this);
/**
* A mouse events handler. If there are two headers it is shared for both.
* @type {goog.events.EventHandler}
* @private
*/
this.mouseEventHandler_ = new goog.events.EventHandler(this);
var self = this;
function addHeaderEvents(el) {
if (el) {
el.tabIndex = 0;
goog.a11y.aria.setRole(el, self.getAriaRole());
goog.dom.classes.add(el, goog.getCssName('goog-zippy-header'));
self.enableMouseEventsHandling_(el);
self.enableKeyboardEventsHandling_(el);
}
}
addHeaderEvents(this.elHeader_);
addHeaderEvents(this.elExpandedHeader_);
// initialize based on expanded state
this.setExpanded(this.expanded_);
};
goog.inherits(goog.ui.Zippy, goog.events.EventTarget);
/**
* Constants for event names
*
* @type {Object}
*/
goog.ui.Zippy.Events = {
// Zippy will dispatch an ACTION event for user interaction. Mimics
// {@code goog.ui.Controls#performActionInternal} by first changing
// the toggle state and then dispatching an ACTION event.
ACTION: 'action',
// Zippy state is toggled from collapsed to expanded or vice versa.
TOGGLE: 'toggle'
};
/**
* Whether to listen for and handle mouse events; defaults to true.
* @type {boolean}
* @private
*/
goog.ui.Zippy.prototype.handleMouseEvents_ = true;
/**
* Whether to listen for and handle key events; defaults to true.
* @type {boolean}
* @private
*/
goog.ui.Zippy.prototype.handleKeyEvents_ = true;
/** @override */
goog.ui.Zippy.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
goog.dispose(this.keyboardEventHandler_);
goog.dispose(this.mouseEventHandler_);
};
/**
* @return {goog.a11y.aria.Role} The ARIA role to be applied to Zippy element.
*/
goog.ui.Zippy.prototype.getAriaRole = function() {
return goog.a11y.aria.Role.TAB;
};
/**
* @return {Element} The content element.
*/
goog.ui.Zippy.prototype.getContentElement = function() {
return this.elContent_;
};
/**
* @return {Element} The visible header element.
*/
goog.ui.Zippy.prototype.getVisibleHeaderElement = function() {
var expandedHeader = this.elExpandedHeader_;
return expandedHeader && goog.style.isElementShown(expandedHeader) ?
expandedHeader : this.elHeader_;
};
/**
* Expands content pane.
*/
goog.ui.Zippy.prototype.expand = function() {
this.setExpanded(true);
};
/**
* Collapses content pane.
*/
goog.ui.Zippy.prototype.collapse = function() {
this.setExpanded(false);
};
/**
* Toggles expanded state.
*/
goog.ui.Zippy.prototype.toggle = function() {
this.setExpanded(!this.expanded_);
};
/**
* Sets expanded state.
*
* @param {boolean} expanded Expanded/visibility state.
*/
goog.ui.Zippy.prototype.setExpanded = function(expanded) {
if (this.elContent_) {
// Hide the element, if one is provided.
goog.style.setElementShown(this.elContent_, expanded);
} else if (expanded && this.lazyCreateFunc_) {
// Assume that when the element is not hidden upon creation.
this.elContent_ = this.lazyCreateFunc_();
}
if (this.elContent_) {
goog.dom.classes.add(this.elContent_,
goog.getCssName('goog-zippy-content'));
}
if (this.elExpandedHeader_) {
// Hide the show header and show the hide one.
goog.style.setElementShown(this.elHeader_, !expanded);
goog.style.setElementShown(this.elExpandedHeader_, expanded);
} else {
// Update header image, if any.
this.updateHeaderClassName(expanded);
}
this.setExpandedInternal(expanded);
// Fire toggle event
this.dispatchEvent(new goog.ui.ZippyEvent(goog.ui.Zippy.Events.TOGGLE,
this, this.expanded_));
};
/**
* Sets expanded internal state.
*
* @param {boolean} expanded Expanded/visibility state.
* @protected
*/
goog.ui.Zippy.prototype.setExpandedInternal = function(expanded) {
this.expanded_ = expanded;
};
/**
* @return {boolean} Whether the zippy is expanded.
*/
goog.ui.Zippy.prototype.isExpanded = function() {
return this.expanded_;
};
/**
* Updates the header element's className and ARIA (accessibility) EXPANDED
* state.
*
* @param {boolean} expanded Expanded/visibility state.
* @protected
*/
goog.ui.Zippy.prototype.updateHeaderClassName = function(expanded) {
if (this.elHeader_) {
goog.dom.classes.enable(this.elHeader_,
goog.getCssName('goog-zippy-expanded'), expanded);
goog.dom.classes.enable(this.elHeader_,
goog.getCssName('goog-zippy-collapsed'), !expanded);
goog.a11y.aria.setState(this.elHeader_,
goog.a11y.aria.State.EXPANDED,
expanded);
}
};
/**
* @return {boolean} Whether the Zippy handles its own key events.
*/
goog.ui.Zippy.prototype.isHandleKeyEvents = function() {
return this.handleKeyEvents_;
};
/**
* @return {boolean} Whether the Zippy handles its own mouse events.
*/
goog.ui.Zippy.prototype.isHandleMouseEvents = function() {
return this.handleMouseEvents_;
};
/**
* Sets whether the Zippy handles it's own keyboard events.
* @param {boolean} enable Whether the Zippy handles keyboard events.
*/
goog.ui.Zippy.prototype.setHandleKeyboardEvents = function(enable) {
if (this.handleKeyEvents_ != enable) {
this.handleKeyEvents_ = enable;
if (enable) {
this.enableKeyboardEventsHandling_(this.elHeader_);
this.enableKeyboardEventsHandling_(this.elExpandedHeader_);
} else {
this.keyboardEventHandler_.removeAll();
}
}
};
/**
* Sets whether the Zippy handles it's own mouse events.
* @param {boolean} enable Whether the Zippy handles mouse events.
*/
goog.ui.Zippy.prototype.setHandleMouseEvents = function(enable) {
if (this.handleMouseEvents_ != enable) {
this.handleMouseEvents_ = enable;
if (enable) {
this.enableMouseEventsHandling_(this.elHeader_);
this.enableMouseEventsHandling_(this.elExpandedHeader_);
} else {
this.mouseEventHandler_.removeAll();
}
}
};
/**
* Enables keyboard events handling for the passed header element.
* @param {Element} header The header element.
* @private
*/
goog.ui.Zippy.prototype.enableKeyboardEventsHandling_ = function(header) {
if (header) {
this.keyboardEventHandler_.listen(header, goog.events.EventType.KEYDOWN,
this.onHeaderKeyDown_);
}
};
/**
* Enables mouse events handling for the passed header element.
* @param {Element} header The header element.
* @private
*/
goog.ui.Zippy.prototype.enableMouseEventsHandling_ = function(header) {
if (header) {
this.mouseEventHandler_.listen(header, goog.events.EventType.CLICK,
this.onHeaderClick_);
}
};
/**
* KeyDown event handler for header element. Enter and space toggles expanded
* state.
*
* @param {goog.events.BrowserEvent} event KeyDown event.
* @private
*/
goog.ui.Zippy.prototype.onHeaderKeyDown_ = function(event) {
if (event.keyCode == goog.events.KeyCodes.ENTER ||
event.keyCode == goog.events.KeyCodes.SPACE) {
this.toggle();
this.dispatchActionEvent_();
// Prevent enter key from submitting form.
event.preventDefault();
event.stopPropagation();
}
};
/**
* Click event handler for header element.
*
* @param {goog.events.BrowserEvent} event Click event.
* @private
*/
goog.ui.Zippy.prototype.onHeaderClick_ = function(event) {
this.toggle();
this.dispatchActionEvent_();
};
/**
* Dispatch an ACTION event whenever there is user interaction with the header.
* Please note that after the zippy state change is completed a TOGGLE event
* will be dispatched. However, the TOGGLE event is dispatch on every toggle,
* including programmatic call to {@code #toggle}.
* @private
*/
goog.ui.Zippy.prototype.dispatchActionEvent_ = function() {
this.dispatchEvent(new goog.events.Event(goog.ui.Zippy.Events.ACTION, this));
};
/**
* Object representing a zippy toggle event.
*
* @param {string} type Event type.
* @param {goog.ui.Zippy} target Zippy widget initiating event.
* @param {boolean} expanded Expanded state.
* @extends {goog.events.Event}
* @constructor
*/
goog.ui.ZippyEvent = function(type, target, expanded) {
goog.base(this, type, target);
/**
* The expanded state.
* @type {boolean}
*/
this.expanded = expanded;
};
goog.inherits(goog.ui.ZippyEvent, goog.events.Event);
| 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 containers that host {@link goog.ui.Control}s,
* such as menus and toolbars. Provides default keyboard and mouse event
* handling and child management, based on a generalized version of
* {@link goog.ui.Menu}.
*
* @author attila@google.com (Attila Bodis)
* @see ../demos/container.html
*/
// TODO(attila): Fix code/logic duplication between this and goog.ui.Control.
// TODO(attila): Maybe pull common stuff all the way up into Component...?
goog.provide('goog.ui.Container');
goog.provide('goog.ui.Container.EventType');
goog.provide('goog.ui.Container.Orientation');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.State');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.events.KeyHandler');
goog.require('goog.events.KeyHandler.EventType');
goog.require('goog.object');
goog.require('goog.style');
goog.require('goog.ui.Component');
goog.require('goog.ui.Component.Error');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.Component.State');
goog.require('goog.ui.ContainerRenderer');
goog.require('goog.ui.Control');
/**
* Base class for containers. Extends {@link goog.ui.Component} by adding
* the following:
* <ul>
* <li>a {@link goog.events.KeyHandler}, to simplify keyboard handling,
* <li>a pluggable <em>renderer</em> framework, to simplify the creation of
* containers without the need to subclass this class,
* <li>methods to manage child controls hosted in the container,
* <li>default mouse and keyboard event handling methods.
* </ul>
* @param {?goog.ui.Container.Orientation=} opt_orientation Container
* orientation; defaults to {@code VERTICAL}.
* @param {goog.ui.ContainerRenderer=} opt_renderer Renderer used to render or
* decorate the container; defaults to {@link goog.ui.ContainerRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper, used for document
* interaction.
* @extends {goog.ui.Component}
* @constructor
*/
goog.ui.Container = function(opt_orientation, opt_renderer, opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
this.renderer_ = opt_renderer || goog.ui.ContainerRenderer.getInstance();
this.orientation_ = opt_orientation || this.renderer_.getDefaultOrientation();
};
goog.inherits(goog.ui.Container, goog.ui.Component);
/**
* Container-specific events.
* @enum {string}
*/
goog.ui.Container.EventType = {
/**
* Dispatched after a goog.ui.Container becomes visible. Non-cancellable.
* NOTE(user): This event really shouldn't exist, because the
* goog.ui.Component.EventType.SHOW event should behave like this one. But the
* SHOW event for containers has been behaving as other components'
* BEFORE_SHOW event for a long time, and too much code relies on that old
* behavior to fix it now.
*/
AFTER_SHOW: 'aftershow',
/**
* Dispatched after a goog.ui.Container becomes invisible. Non-cancellable.
*/
AFTER_HIDE: 'afterhide'
};
/**
* Container orientation constants.
* @enum {string}
*/
goog.ui.Container.Orientation = {
HORIZONTAL: 'horizontal',
VERTICAL: 'vertical'
};
/**
* Allows an alternative element to be set to receive key events, otherwise
* defers to the renderer's element choice.
* @type {Element|undefined}
* @private
*/
goog.ui.Container.prototype.keyEventTarget_ = null;
/**
* Keyboard event handler.
* @type {goog.events.KeyHandler?}
* @private
*/
goog.ui.Container.prototype.keyHandler_ = null;
/**
* Renderer for the container. Defaults to {@link goog.ui.ContainerRenderer}.
* @type {goog.ui.ContainerRenderer?}
* @private
*/
goog.ui.Container.prototype.renderer_ = null;
/**
* Container orientation; determines layout and default keyboard navigation.
* @type {?goog.ui.Container.Orientation}
* @private
*/
goog.ui.Container.prototype.orientation_ = null;
/**
* Whether the container is set to be visible. Defaults to true.
* @type {boolean}
* @private
*/
goog.ui.Container.prototype.visible_ = true;
/**
* Whether the container is enabled and reacting to keyboard and mouse events.
* Defaults to true.
* @type {boolean}
* @private
*/
goog.ui.Container.prototype.enabled_ = true;
/**
* Whether the container supports keyboard focus. Defaults to true. Focusable
* containers have a {@code tabIndex} and can be navigated to via the keyboard.
* @type {boolean}
* @private
*/
goog.ui.Container.prototype.focusable_ = true;
/**
* The 0-based index of the currently highlighted control in the container
* (-1 if none).
* @type {number}
* @private
*/
goog.ui.Container.prototype.highlightedIndex_ = -1;
/**
* The currently open (expanded) control in the container (null if none).
* @type {goog.ui.Control?}
* @private
*/
goog.ui.Container.prototype.openItem_ = null;
/**
* Whether the mouse button is held down. Defaults to false. This flag is set
* when the user mouses down over the container, and remains set until they
* release the mouse button.
* @type {boolean}
* @private
*/
goog.ui.Container.prototype.mouseButtonPressed_ = false;
/**
* Whether focus of child components should be allowed. Only effective if
* focusable_ is set to false.
* @type {boolean}
* @private
*/
goog.ui.Container.prototype.allowFocusableChildren_ = false;
/**
* Whether highlighting a child component should also open it.
* @type {boolean}
* @private
*/
goog.ui.Container.prototype.openFollowsHighlight_ = true;
/**
* Map of DOM IDs to child controls. Each key is the DOM ID of a child
* control's root element; each value is a reference to the child control
* itself. Used for looking up the child control corresponding to a DOM
* node in O(1) time.
* @type {Object}
* @private
*/
goog.ui.Container.prototype.childElementIdMap_ = null;
// Event handler and renderer management.
/**
* Returns the DOM element on which the container is listening for keyboard
* events (null if none).
* @return {Element} Element on which the container is listening for key
* events.
*/
goog.ui.Container.prototype.getKeyEventTarget = function() {
// Delegate to renderer, unless we've set an explicit target.
return this.keyEventTarget_ || this.renderer_.getKeyEventTarget(this);
};
/**
* Attaches an element on which to listen for key events.
* @param {Element|undefined} element The element to attach, or null/undefined
* to attach to the default element.
*/
goog.ui.Container.prototype.setKeyEventTarget = function(element) {
if (this.focusable_) {
var oldTarget = this.getKeyEventTarget();
var inDocument = this.isInDocument();
this.keyEventTarget_ = element;
var newTarget = this.getKeyEventTarget();
if (inDocument) {
// Unlisten for events on the old key target. Requires us to reset
// key target state temporarily.
this.keyEventTarget_ = oldTarget;
this.enableFocusHandling_(false);
this.keyEventTarget_ = element;
// Listen for events on the new key target.
this.getKeyHandler().attach(newTarget);
this.enableFocusHandling_(true);
}
} else {
throw Error('Can\'t set key event target for container ' +
'that doesn\'t support keyboard focus!');
}
};
/**
* Returns the keyboard event handler for this container, lazily created the
* first time this method is called. The keyboard event handler listens for
* keyboard events on the container's key event target, as determined by its
* renderer.
* @return {goog.events.KeyHandler} Keyboard event handler for this container.
*/
goog.ui.Container.prototype.getKeyHandler = function() {
return this.keyHandler_ ||
(this.keyHandler_ = new goog.events.KeyHandler(this.getKeyEventTarget()));
};
/**
* Returns the renderer used by this container to render itself or to decorate
* an existing element.
* @return {goog.ui.ContainerRenderer} Renderer used by the container.
*/
goog.ui.Container.prototype.getRenderer = function() {
return this.renderer_;
};
/**
* Registers the given renderer with the container. Changing renderers after
* the container has already been rendered or decorated is an error.
* @param {goog.ui.ContainerRenderer} renderer Renderer used by the container.
*/
goog.ui.Container.prototype.setRenderer = function(renderer) {
if (this.getElement()) {
// Too late.
throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
}
this.renderer_ = renderer;
};
// Standard goog.ui.Component implementation.
/**
* Creates the container's DOM.
* @override
*/
goog.ui.Container.prototype.createDom = function() {
// Delegate to renderer.
this.setElementInternal(this.renderer_.createDom(this));
};
/**
* Returns the DOM element into which child components are to be rendered,
* or null if the container itself hasn't been rendered yet. Overrides
* {@link goog.ui.Component#getContentElement} by delegating to the renderer.
* @return {Element} Element to contain child elements (null if none).
* @override
*/
goog.ui.Container.prototype.getContentElement = function() {
// Delegate to renderer.
return this.renderer_.getContentElement(this.getElement());
};
/**
* Returns true if the given element can be decorated by this container.
* Overrides {@link goog.ui.Component#canDecorate}.
* @param {Element} element Element to decorate.
* @return {boolean} True iff the element can be decorated.
* @override
*/
goog.ui.Container.prototype.canDecorate = function(element) {
// Delegate to renderer.
return this.renderer_.canDecorate(element);
};
/**
* Decorates the given element with this container. Overrides {@link
* goog.ui.Component#decorateInternal}. Considered protected.
* @param {Element} element Element to decorate.
* @override
*/
goog.ui.Container.prototype.decorateInternal = function(element) {
// Delegate to renderer.
this.setElementInternal(this.renderer_.decorate(this, element));
// Check whether the decorated element is explicitly styled to be invisible.
if (element.style.display == 'none') {
this.visible_ = false;
}
};
/**
* Configures the container after its DOM has been rendered, and sets up event
* handling. Overrides {@link goog.ui.Component#enterDocument}.
* @override
*/
goog.ui.Container.prototype.enterDocument = function() {
goog.ui.Container.superClass_.enterDocument.call(this);
this.forEachChild(function(child) {
if (child.isInDocument()) {
this.registerChildId_(child);
}
}, this);
var elem = this.getElement();
// Call the renderer's initializeDom method to initialize the container's DOM.
this.renderer_.initializeDom(this);
// Initialize visibility (opt_force = true, so we don't dispatch events).
this.setVisible(this.visible_, true);
// Handle events dispatched by child controls.
this.getHandler().
listen(this, goog.ui.Component.EventType.ENTER,
this.handleEnterItem).
listen(this, goog.ui.Component.EventType.HIGHLIGHT,
this.handleHighlightItem).
listen(this, goog.ui.Component.EventType.UNHIGHLIGHT,
this.handleUnHighlightItem).
listen(this, goog.ui.Component.EventType.OPEN, this.handleOpenItem).
listen(this, goog.ui.Component.EventType.CLOSE, this.handleCloseItem).
// Handle mouse events.
listen(elem, goog.events.EventType.MOUSEDOWN, this.handleMouseDown).
listen(goog.dom.getOwnerDocument(elem), goog.events.EventType.MOUSEUP,
this.handleDocumentMouseUp).
// Handle mouse events on behalf of controls in the container.
listen(elem, [
goog.events.EventType.MOUSEDOWN,
goog.events.EventType.MOUSEUP,
goog.events.EventType.MOUSEOVER,
goog.events.EventType.MOUSEOUT,
goog.events.EventType.CONTEXTMENU
], this.handleChildMouseEvents);
// If the container is focusable, set up keyboard event handling.
if (this.isFocusable()) {
this.enableFocusHandling_(true);
}
};
/**
* Sets up listening for events applicable to focusable containers.
* @param {boolean} enable Whether to enable or disable focus handling.
* @private
*/
goog.ui.Container.prototype.enableFocusHandling_ = function(enable) {
var handler = this.getHandler();
var keyTarget = this.getKeyEventTarget();
if (enable) {
handler.
listen(keyTarget, goog.events.EventType.FOCUS, this.handleFocus).
listen(keyTarget, goog.events.EventType.BLUR, this.handleBlur).
listen(this.getKeyHandler(), goog.events.KeyHandler.EventType.KEY,
this.handleKeyEvent);
} else {
handler.
unlisten(keyTarget, goog.events.EventType.FOCUS, this.handleFocus).
unlisten(keyTarget, goog.events.EventType.BLUR, this.handleBlur).
unlisten(this.getKeyHandler(), goog.events.KeyHandler.EventType.KEY,
this.handleKeyEvent);
}
};
/**
* Cleans up the container before its DOM is removed from the document, and
* removes event handlers. Overrides {@link goog.ui.Component#exitDocument}.
* @override
*/
goog.ui.Container.prototype.exitDocument = function() {
// {@link #setHighlightedIndex} has to be called before
// {@link goog.ui.Component#exitDocument}, otherwise it has no effect.
this.setHighlightedIndex(-1);
if (this.openItem_) {
this.openItem_.setOpen(false);
}
this.mouseButtonPressed_ = false;
goog.ui.Container.superClass_.exitDocument.call(this);
};
/** @override */
goog.ui.Container.prototype.disposeInternal = function() {
goog.ui.Container.superClass_.disposeInternal.call(this);
if (this.keyHandler_) {
this.keyHandler_.dispose();
this.keyHandler_ = null;
}
this.keyEventTarget_ = null;
this.childElementIdMap_ = null;
this.openItem_ = null;
this.renderer_ = null;
};
// Default event handlers.
/**
* Handles ENTER events raised by child controls when they are navigated to.
* @param {goog.events.Event} e ENTER event to handle.
* @return {boolean} Whether to prevent handleMouseOver from handling
* the event.
*/
goog.ui.Container.prototype.handleEnterItem = function(e) {
// Allow the Control to highlight itself.
return true;
};
/**
* Handles HIGHLIGHT events dispatched by items in the container when
* they are highlighted.
* @param {goog.events.Event} e Highlight event to handle.
*/
goog.ui.Container.prototype.handleHighlightItem = function(e) {
var index = this.indexOfChild(/** @type {goog.ui.Control} */ (e.target));
if (index > -1 && index != this.highlightedIndex_) {
var item = this.getHighlighted();
if (item) {
// Un-highlight previously highlighted item.
item.setHighlighted(false);
}
this.highlightedIndex_ = index;
item = this.getHighlighted();
if (this.isMouseButtonPressed()) {
// Activate item when mouse button is pressed, to allow MacOS-style
// dragging to choose menu items. Although this should only truly
// happen if the highlight is due to mouse movements, there is little
// harm in doing it for keyboard or programmatic highlights.
item.setActive(true);
}
// Update open item if open item needs follow highlight.
if (this.openFollowsHighlight_ &&
this.openItem_ && item != this.openItem_) {
if (item.isSupportedState(goog.ui.Component.State.OPENED)) {
item.setOpen(true);
} else {
this.openItem_.setOpen(false);
}
}
}
var element = this.getElement();
goog.asserts.assert(element,
'The DOM element for the container cannot be null.');
if (e.target.getElement() != null) {
goog.a11y.aria.setState(element,
goog.a11y.aria.State.ACTIVEDESCENDANT,
e.target.getElement().id);
}
};
/**
* Handles UNHIGHLIGHT events dispatched by items in the container when
* they are unhighlighted.
* @param {goog.events.Event} e Unhighlight event to handle.
*/
goog.ui.Container.prototype.handleUnHighlightItem = function(e) {
if (e.target == this.getHighlighted()) {
this.highlightedIndex_ = -1;
}
var element = this.getElement();
goog.asserts.assert(element,
'The DOM element for the container cannot be null.');
goog.a11y.aria.setState(element,
goog.a11y.aria.State.ACTIVEDESCENDANT,
'');
};
/**
* Handles OPEN events dispatched by items in the container when they are
* opened.
* @param {goog.events.Event} e Open event to handle.
*/
goog.ui.Container.prototype.handleOpenItem = function(e) {
var item = /** @type {goog.ui.Control} */ (e.target);
if (item && item != this.openItem_ && item.getParent() == this) {
if (this.openItem_) {
this.openItem_.setOpen(false);
}
this.openItem_ = item;
}
};
/**
* Handles CLOSE events dispatched by items in the container when they are
* closed.
* @param {goog.events.Event} e Close event to handle.
*/
goog.ui.Container.prototype.handleCloseItem = function(e) {
if (e.target == this.openItem_) {
this.openItem_ = null;
}
};
/**
* Handles mousedown events over the container. The default implementation
* sets the "mouse button pressed" flag and, if the container is focusable,
* grabs keyboard focus.
* @param {goog.events.BrowserEvent} e Mousedown event to handle.
*/
goog.ui.Container.prototype.handleMouseDown = function(e) {
if (this.enabled_) {
this.setMouseButtonPressed(true);
}
var keyTarget = this.getKeyEventTarget();
if (keyTarget && goog.dom.isFocusableTabIndex(keyTarget)) {
// The container is configured to receive keyboard focus.
keyTarget.focus();
} else {
// The control isn't configured to receive keyboard focus; prevent it
// from stealing focus or destroying the selection.
e.preventDefault();
}
};
/**
* Handles mouseup events over the document. The default implementation
* clears the "mouse button pressed" flag.
* @param {goog.events.BrowserEvent} e Mouseup event to handle.
*/
goog.ui.Container.prototype.handleDocumentMouseUp = function(e) {
this.setMouseButtonPressed(false);
};
/**
* Handles mouse events originating from nodes belonging to the controls hosted
* in the container. Locates the child control based on the DOM node that
* dispatched the event, and forwards the event to the control for handling.
* @param {goog.events.BrowserEvent} e Mouse event to handle.
*/
goog.ui.Container.prototype.handleChildMouseEvents = function(e) {
var control = this.getOwnerControl(/** @type {Node} */ (e.target));
if (control) {
// Child control identified; forward the event.
switch (e.type) {
case goog.events.EventType.MOUSEDOWN:
control.handleMouseDown(e);
break;
case goog.events.EventType.MOUSEUP:
control.handleMouseUp(e);
break;
case goog.events.EventType.MOUSEOVER:
control.handleMouseOver(e);
break;
case goog.events.EventType.MOUSEOUT:
control.handleMouseOut(e);
break;
case goog.events.EventType.CONTEXTMENU:
control.handleContextMenu(e);
break;
}
}
};
/**
* Returns the child control that owns the given DOM node, or null if no such
* control is found.
* @param {Node} node DOM node whose owner is to be returned.
* @return {goog.ui.Control?} Control hosted in the container to which the node
* belongs (if found).
* @protected
*/
goog.ui.Container.prototype.getOwnerControl = function(node) {
// Ensure that this container actually has child controls before
// looking up the owner.
if (this.childElementIdMap_) {
var elem = this.getElement();
// See http://b/2964418 . IE9 appears to evaluate '!=' incorrectly, so
// using '!==' instead.
// TODO(user): Possibly revert this change if/when IE9 fixes the issue.
while (node && node !== elem) {
var id = node.id;
if (id in this.childElementIdMap_) {
return this.childElementIdMap_[id];
}
node = node.parentNode;
}
}
return null;
};
/**
* Handles focus events raised when the container's key event target receives
* keyboard focus.
* @param {goog.events.BrowserEvent} e Focus event to handle.
*/
goog.ui.Container.prototype.handleFocus = function(e) {
// No-op in the base class.
};
/**
* Handles blur events raised when the container's key event target loses
* keyboard focus. The default implementation clears the highlight index.
* @param {goog.events.BrowserEvent} e Blur event to handle.
*/
goog.ui.Container.prototype.handleBlur = function(e) {
this.setHighlightedIndex(-1);
this.setMouseButtonPressed(false);
// If the container loses focus, and one of its children is open, close it.
if (this.openItem_) {
this.openItem_.setOpen(false);
}
};
/**
* Attempts to handle a keyboard event, if the control is enabled, by calling
* {@link handleKeyEventInternal}. Considered protected; should only be used
* within this package and by subclasses.
* @param {goog.events.KeyEvent} e Key event to handle.
* @return {boolean} Whether the key event was handled.
*/
goog.ui.Container.prototype.handleKeyEvent = function(e) {
if (this.isEnabled() && this.isVisible() &&
(this.getChildCount() != 0 || this.keyEventTarget_) &&
this.handleKeyEventInternal(e)) {
e.preventDefault();
e.stopPropagation();
return true;
}
return false;
};
/**
* Attempts to handle a keyboard event; returns true if the event was handled,
* false otherwise. If the container is enabled, and a child is highlighted,
* calls the child control's {@code handleKeyEvent} method to give the control
* a chance to handle the event first.
* @param {goog.events.KeyEvent} e Key event to handle.
* @return {boolean} Whether the event was handled by the container (or one of
* its children).
*/
goog.ui.Container.prototype.handleKeyEventInternal = function(e) {
// Give the highlighted control the chance to handle the key event.
var highlighted = this.getHighlighted();
if (highlighted && typeof highlighted.handleKeyEvent == 'function' &&
highlighted.handleKeyEvent(e)) {
return true;
}
// Give the open control the chance to handle the key event.
if (this.openItem_ && this.openItem_ != highlighted &&
typeof this.openItem_.handleKeyEvent == 'function' &&
this.openItem_.handleKeyEvent(e)) {
return true;
}
// Do not handle the key event if any modifier key is pressed.
if (e.shiftKey || e.ctrlKey || e.metaKey || e.altKey) {
return false;
}
// Either nothing is highlighted, or the highlighted control didn't handle
// the key event, so attempt to handle it here.
switch (e.keyCode) {
case goog.events.KeyCodes.ESC:
if (this.isFocusable()) {
this.getKeyEventTarget().blur();
} else {
return false;
}
break;
case goog.events.KeyCodes.HOME:
this.highlightFirst();
break;
case goog.events.KeyCodes.END:
this.highlightLast();
break;
case goog.events.KeyCodes.UP:
if (this.orientation_ == goog.ui.Container.Orientation.VERTICAL) {
this.highlightPrevious();
} else {
return false;
}
break;
case goog.events.KeyCodes.LEFT:
if (this.orientation_ == goog.ui.Container.Orientation.HORIZONTAL) {
if (this.isRightToLeft()) {
this.highlightNext();
} else {
this.highlightPrevious();
}
} else {
return false;
}
break;
case goog.events.KeyCodes.DOWN:
if (this.orientation_ == goog.ui.Container.Orientation.VERTICAL) {
this.highlightNext();
} else {
return false;
}
break;
case goog.events.KeyCodes.RIGHT:
if (this.orientation_ == goog.ui.Container.Orientation.HORIZONTAL) {
if (this.isRightToLeft()) {
this.highlightPrevious();
} else {
this.highlightNext();
}
} else {
return false;
}
break;
default:
return false;
}
return true;
};
// Child component management.
/**
* Creates a DOM ID for the child control and registers it to an internal
* hash table to be able to find it fast by id.
* @param {goog.ui.Component} child The child control. Its root element has
* to be created yet.
* @private
*/
goog.ui.Container.prototype.registerChildId_ = function(child) {
// Map the DOM ID of the control's root element to the control itself.
var childElem = child.getElement();
// If the control's root element doesn't have a DOM ID assign one.
var id = childElem.id || (childElem.id = child.getId());
// Lazily create the child element ID map on first use.
if (!this.childElementIdMap_) {
this.childElementIdMap_ = {};
}
this.childElementIdMap_[id] = child;
};
/**
* Adds the specified control as the last child of this container. See
* {@link goog.ui.Container#addChildAt} for detailed semantics.
* @param {goog.ui.Component} child The new child control.
* @param {boolean=} opt_render Whether the new child should be rendered
* immediately after being added (defaults to false).
* @override
*/
goog.ui.Container.prototype.addChild = function(child, opt_render) {
goog.asserts.assertInstanceof(child, goog.ui.Control,
'The child of a container must be a control');
goog.ui.Container.superClass_.addChild.call(this, child, opt_render);
};
/**
* Overrides {@link goog.ui.Container#getChild} to make it clear that it
* only returns {@link goog.ui.Control}s.
* @param {string} id Child component ID.
* @return {goog.ui.Control} The child with the given ID; null if none.
* @override
*/
goog.ui.Container.prototype.getChild;
/**
* Overrides {@link goog.ui.Container#getChildAt} to make it clear that it
* only returns {@link goog.ui.Control}s.
* @param {number} index 0-based index.
* @return {goog.ui.Control} The child with the given ID; null if none.
* @override
*/
goog.ui.Container.prototype.getChildAt;
/**
* Adds the control as a child of this container at the given 0-based index.
* Overrides {@link goog.ui.Component#addChildAt} by also updating the
* container's highlight index. Since {@link goog.ui.Component#addChild} uses
* {@link #addChildAt} internally, we only need to override this method.
* @param {goog.ui.Component} control New child.
* @param {number} index Index at which the new child is to be added.
* @param {boolean=} opt_render Whether the new child should be rendered
* immediately after being added (defaults to false).
* @override
*/
goog.ui.Container.prototype.addChildAt = function(control, index, opt_render) {
// Make sure the child control dispatches HIGHLIGHT, UNHIGHLIGHT, OPEN, and
// CLOSE events, and that it doesn't steal keyboard focus.
control.setDispatchTransitionEvents(goog.ui.Component.State.HOVER, true);
control.setDispatchTransitionEvents(goog.ui.Component.State.OPENED, true);
if (this.isFocusable() || !this.isFocusableChildrenAllowed()) {
control.setSupportedState(goog.ui.Component.State.FOCUSED, false);
}
// Disable mouse event handling by child controls.
control.setHandleMouseEvents(false);
// Let the superclass implementation do the work.
goog.ui.Container.superClass_.addChildAt.call(this, control, index,
opt_render);
if (control.isInDocument() && this.isInDocument()) {
this.registerChildId_(control);
}
// Update the highlight index, if needed.
if (index <= this.highlightedIndex_) {
this.highlightedIndex_++;
}
};
/**
* Removes a child control. Overrides {@link goog.ui.Component#removeChild} by
* updating the highlight index. Since {@link goog.ui.Component#removeChildAt}
* uses {@link #removeChild} internally, we only need to override this method.
* @param {string|goog.ui.Component} control The ID of the child to remove, or
* the control itself.
* @param {boolean=} opt_unrender Whether to call {@code exitDocument} on the
* removed control, and detach its DOM from the document (defaults to
* false).
* @return {goog.ui.Control} The removed control, if any.
* @override
*/
goog.ui.Container.prototype.removeChild = function(control, opt_unrender) {
control = goog.isString(control) ? this.getChild(control) : control;
if (control) {
var index = this.indexOfChild(control);
if (index != -1) {
if (index == this.highlightedIndex_) {
control.setHighlighted(false);
} else if (index < this.highlightedIndex_) {
this.highlightedIndex_--;
}
}
// Remove the mapping from the child element ID map.
var childElem = control.getElement();
if (childElem && childElem.id && this.childElementIdMap_) {
goog.object.remove(this.childElementIdMap_, childElem.id);
}
}
control = /** @type {goog.ui.Control} */ (
goog.ui.Container.superClass_.removeChild.call(this, control,
opt_unrender));
// Re-enable mouse event handling (in case the control is reused elsewhere).
control.setHandleMouseEvents(true);
return control;
};
// Container state management.
/**
* Returns the container's orientation.
* @return {?goog.ui.Container.Orientation} Container orientation.
*/
goog.ui.Container.prototype.getOrientation = function() {
return this.orientation_;
};
/**
* Sets the container's orientation.
* @param {goog.ui.Container.Orientation} orientation Container orientation.
*/
// TODO(attila): Do we need to support containers with dynamic orientation?
goog.ui.Container.prototype.setOrientation = function(orientation) {
if (this.getElement()) {
// Too late.
throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
}
this.orientation_ = orientation;
};
/**
* Returns true if the container's visibility is set to visible, false if
* it is set to hidden. A container that is set to hidden is guaranteed
* to be hidden from the user, but the reverse isn't necessarily true.
* A container may be set to visible but can otherwise be obscured by another
* element, rendered off-screen, or hidden using direct CSS manipulation.
* @return {boolean} Whether the container is set to be visible.
*/
goog.ui.Container.prototype.isVisible = function() {
return this.visible_;
};
/**
* Shows or hides the container. Does nothing if the container already has
* the requested visibility. Otherwise, dispatches a SHOW or HIDE event as
* appropriate, giving listeners a chance to prevent the visibility change.
* @param {boolean} visible Whether to show or hide the container.
* @param {boolean=} opt_force If true, doesn't check whether the container
* already has the requested visibility, and doesn't dispatch any events.
* @return {boolean} Whether the visibility was changed.
*/
goog.ui.Container.prototype.setVisible = function(visible, opt_force) {
if (opt_force || (this.visible_ != visible && this.dispatchEvent(visible ?
goog.ui.Component.EventType.SHOW : goog.ui.Component.EventType.HIDE))) {
this.visible_ = visible;
var elem = this.getElement();
if (elem) {
goog.style.setElementShown(elem, visible);
if (this.isFocusable()) {
// Enable keyboard access only for enabled & visible containers.
this.renderer_.enableTabIndex(this.getKeyEventTarget(),
this.enabled_ && this.visible_);
}
if (!opt_force) {
this.dispatchEvent(this.visible_ ?
goog.ui.Container.EventType.AFTER_SHOW :
goog.ui.Container.EventType.AFTER_HIDE);
}
}
return true;
}
return false;
};
/**
* Returns true if the container is enabled, false otherwise.
* @return {boolean} Whether the container is enabled.
*/
goog.ui.Container.prototype.isEnabled = function() {
return this.enabled_;
};
/**
* Enables/disables the container based on the {@code enable} argument.
* Dispatches an {@code ENABLED} or {@code DISABLED} event prior to changing
* the container's state, which may be caught and canceled to prevent the
* container from changing state. Also enables/disables child controls.
* @param {boolean} enable Whether to enable or disable the container.
*/
goog.ui.Container.prototype.setEnabled = function(enable) {
if (this.enabled_ != enable && this.dispatchEvent(enable ?
goog.ui.Component.EventType.ENABLE :
goog.ui.Component.EventType.DISABLE)) {
if (enable) {
// Flag the container as enabled first, then update children. This is
// because controls can't be enabled if their parent is disabled.
this.enabled_ = true;
this.forEachChild(function(child) {
// Enable child control unless it is flagged.
if (child.wasDisabled) {
delete child.wasDisabled;
} else {
child.setEnabled(true);
}
});
} else {
// Disable children first, then flag the container as disabled. This is
// because controls can't be disabled if their parent is already disabled.
this.forEachChild(function(child) {
// Disable child control, or flag it if it's already disabled.
if (child.isEnabled()) {
child.setEnabled(false);
} else {
child.wasDisabled = true;
}
});
this.enabled_ = false;
this.setMouseButtonPressed(false);
}
if (this.isFocusable()) {
// Enable keyboard access only for enabled & visible components.
this.renderer_.enableTabIndex(this.getKeyEventTarget(),
enable && this.visible_);
}
}
};
/**
* Returns true if the container is focusable, false otherwise. The default
* is true. Focusable containers always have a tab index and allocate a key
* handler to handle keyboard events while focused.
* @return {boolean} Whether the component is focusable.
*/
goog.ui.Container.prototype.isFocusable = function() {
return this.focusable_;
};
/**
* Sets whether the container is focusable. The default is true. Focusable
* containers always have a tab index and allocate a key handler to handle
* keyboard events while focused.
* @param {boolean} focusable Whether the component is to be focusable.
*/
goog.ui.Container.prototype.setFocusable = function(focusable) {
if (focusable != this.focusable_ && this.isInDocument()) {
this.enableFocusHandling_(focusable);
}
this.focusable_ = focusable;
if (this.enabled_ && this.visible_) {
this.renderer_.enableTabIndex(this.getKeyEventTarget(), focusable);
}
};
/**
* Returns true if the container allows children to be focusable, false
* otherwise. Only effective if the container is not focusable.
* @return {boolean} Whether children should be focusable.
*/
goog.ui.Container.prototype.isFocusableChildrenAllowed = function() {
return this.allowFocusableChildren_;
};
/**
* Sets whether the container allows children to be focusable, false
* otherwise. Only effective if the container is not focusable.
* @param {boolean} focusable Whether the children should be focusable.
*/
goog.ui.Container.prototype.setFocusableChildrenAllowed = function(focusable) {
this.allowFocusableChildren_ = focusable;
};
/**
* @return {boolean} Whether highlighting a child component should also open it.
*/
goog.ui.Container.prototype.isOpenFollowsHighlight = function() {
return this.openFollowsHighlight_;
};
/**
* Sets whether highlighting a child component should also open it.
* @param {boolean} follow Whether highlighting a child component also opens it.
*/
goog.ui.Container.prototype.setOpenFollowsHighlight = function(follow) {
this.openFollowsHighlight_ = follow;
};
// Highlight management.
/**
* Returns the index of the currently highlighted item (-1 if none).
* @return {number} Index of the currently highlighted item.
*/
goog.ui.Container.prototype.getHighlightedIndex = function() {
return this.highlightedIndex_;
};
/**
* Highlights the item at the given 0-based index (if any). If another item
* was previously highlighted, it is un-highlighted.
* @param {number} index Index of item to highlight (-1 removes the current
* highlight).
*/
goog.ui.Container.prototype.setHighlightedIndex = function(index) {
var child = this.getChildAt(index);
if (child) {
child.setHighlighted(true);
} else if (this.highlightedIndex_ > -1) {
this.getHighlighted().setHighlighted(false);
}
};
/**
* Highlights the given item if it exists and is a child of the container;
* otherwise un-highlights the currently highlighted item.
* @param {goog.ui.Control} item Item to highlight.
*/
goog.ui.Container.prototype.setHighlighted = function(item) {
this.setHighlightedIndex(this.indexOfChild(item));
};
/**
* Returns the currently highlighted item (if any).
* @return {goog.ui.Control?} Highlighted item (null if none).
*/
goog.ui.Container.prototype.getHighlighted = function() {
return this.getChildAt(this.highlightedIndex_);
};
/**
* Highlights the first highlightable item in the container
*/
goog.ui.Container.prototype.highlightFirst = function() {
this.highlightHelper(function(index, max) {
return (index + 1) % max;
}, this.getChildCount() - 1);
};
/**
* Highlights the last highlightable item in the container.
*/
goog.ui.Container.prototype.highlightLast = function() {
this.highlightHelper(function(index, max) {
index--;
return index < 0 ? max - 1 : index;
}, 0);
};
/**
* Highlights the next highlightable item (or the first if nothing is currently
* highlighted).
*/
goog.ui.Container.prototype.highlightNext = function() {
this.highlightHelper(function(index, max) {
return (index + 1) % max;
}, this.highlightedIndex_);
};
/**
* Highlights the previous highlightable item (or the last if nothing is
* currently highlighted).
*/
goog.ui.Container.prototype.highlightPrevious = function() {
this.highlightHelper(function(index, max) {
index--;
return index < 0 ? max - 1 : index;
}, this.highlightedIndex_);
};
/**
* Helper function that manages the details of moving the highlight among
* child controls in response to keyboard events.
* @param {function(number, number) : number} fn Function that accepts the
* current and maximum indices, and returns the next index to check.
* @param {number} startIndex Start index.
* @return {boolean} Whether the highlight has changed.
* @protected
*/
goog.ui.Container.prototype.highlightHelper = function(fn, startIndex) {
// If the start index is -1 (meaning there's nothing currently highlighted),
// try starting from the currently open item, if any.
var curIndex = startIndex < 0 ?
this.indexOfChild(this.openItem_) : startIndex;
var numItems = this.getChildCount();
curIndex = fn.call(this, curIndex, numItems);
var visited = 0;
while (visited <= numItems) {
var control = this.getChildAt(curIndex);
if (control && this.canHighlightItem(control)) {
this.setHighlightedIndexFromKeyEvent(curIndex);
return true;
}
visited++;
curIndex = fn.call(this, curIndex, numItems);
}
return false;
};
/**
* Returns whether the given item can be highlighted.
* @param {goog.ui.Control} item The item to check.
* @return {boolean} Whether the item can be highlighted.
* @protected
*/
goog.ui.Container.prototype.canHighlightItem = function(item) {
return item.isVisible() && item.isEnabled() &&
item.isSupportedState(goog.ui.Component.State.HOVER);
};
/**
* Helper method that sets the highlighted index to the given index in response
* to a keyboard event. The base class implementation simply calls the
* {@link #setHighlightedIndex} method, but subclasses can override this
* behavior as needed.
* @param {number} index Index of item to highlight.
* @protected
*/
goog.ui.Container.prototype.setHighlightedIndexFromKeyEvent = function(index) {
this.setHighlightedIndex(index);
};
/**
* Returns the currently open (expanded) control in the container (null if
* none).
* @return {goog.ui.Control?} The currently open control.
*/
goog.ui.Container.prototype.getOpenItem = function() {
return this.openItem_;
};
/**
* Returns true if the mouse button is pressed, false otherwise.
* @return {boolean} Whether the mouse button is pressed.
*/
goog.ui.Container.prototype.isMouseButtonPressed = function() {
return this.mouseButtonPressed_;
};
/**
* Sets or clears the "mouse button pressed" flag.
* @param {boolean} pressed Whether the mouse button is presed.
*/
goog.ui.Container.prototype.setMouseButtonPressed = function(pressed) {
this.mouseButtonPressed_ = pressed;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Definition of goog.ui.MockActivityMonitor.
*/
goog.provide('goog.ui.MockActivityMonitor');
goog.require('goog.events.EventType');
goog.require('goog.ui.ActivityMonitor');
/**
* A mock implementation of goog.ui.ActivityMonitor for unit testing. Clients
* of this class should override goog.now to return a synthetic time from
* the unit test.
* @constructor
* @extends {goog.ui.ActivityMonitor}
*/
goog.ui.MockActivityMonitor = function() {
goog.base(this);
/**
* Tracks whether an event has been fired. Used by simulateEvent.
* @type {boolean}
* @private
*/
this.eventFired_ = false;
};
goog.inherits(goog.ui.MockActivityMonitor, goog.ui.ActivityMonitor);
/**
* Simulates an event that updates the user to being non-idle.
* @param {goog.events.EventType=} opt_type The type of event that made the user
* not idle. If not specified, defaults to MOUSEMOVE.
*/
goog.ui.MockActivityMonitor.prototype.simulateEvent = function(opt_type) {
var eventTime = goog.now();
var eventType = opt_type || goog.events.EventType.MOUSEMOVE;
this.eventFired_ = false;
this.updateIdleTime(eventTime, eventType);
if (!this.eventFired_) {
this.dispatchEvent(goog.ui.ActivityMonitor.Event.ACTIVITY);
}
};
/**
* @override
*/
goog.ui.MockActivityMonitor.prototype.dispatchEvent = function(e) {
goog.base(this, 'dispatchEvent', e);
this.eventFired_ = true;
};
| 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 Plain text spell checker implementation.
*
* @author eae@google.com (Emil A Eklund)
* @author sergeys@google.com (Sergey Solyanik)
* @see ../demos/plaintextspellchecker.html
*/
goog.provide('goog.ui.PlainTextSpellChecker');
goog.require('goog.Timer');
goog.require('goog.a11y.aria');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.events.KeyHandler');
goog.require('goog.spell.SpellCheck');
goog.require('goog.style');
goog.require('goog.ui.AbstractSpellChecker');
goog.require('goog.ui.Component');
goog.require('goog.userAgent');
/**
* Plain text spell checker implementation.
*
* @param {goog.spell.SpellCheck} handler Instance of the SpellCheckHandler
* support object to use. A single instance can be shared by multiple
* editor components.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @constructor
* @extends {goog.ui.AbstractSpellChecker}
*/
goog.ui.PlainTextSpellChecker = function(handler, opt_domHelper) {
goog.ui.AbstractSpellChecker.call(this, handler, opt_domHelper);
/**
* Correction UI container.
* @type {HTMLDivElement}
* @private
*/
this.overlay_ = /** @type {HTMLDivElement} */
(this.getDomHelper().createDom('div'));
goog.style.setPreWrap(this.overlay_);
/**
* Bound async function (to avoid rebinding it on every call).
* @type {Function}
* @private
*/
this.boundContinueAsyncFn_ = goog.bind(this.continueAsync_, this);
/**
* Regular expression for matching line breaks.
* @type {RegExp}
* @private
*/
this.endOfLineMatcher_ = new RegExp('(.*)(\n|\r\n){0,1}', 'g');
};
goog.inherits(goog.ui.PlainTextSpellChecker, goog.ui.AbstractSpellChecker);
/**
* Class name for invalid words.
* @type {string}
*/
goog.ui.PlainTextSpellChecker.prototype.invalidWordClassName =
goog.getCssName('goog-spellcheck-invalidword');
/**
* Class name for corrected words.
* @type {string}
*/
goog.ui.PlainTextSpellChecker.prototype.correctedWordClassName =
goog.getCssName('goog-spellcheck-correctedword');
/**
* Class name for correction pane.
* @type {string}
*/
goog.ui.PlainTextSpellChecker.prototype.correctionPaneClassName =
goog.getCssName('goog-spellcheck-correctionpane');
/**
* Number of words to scan to precharge the dictionary.
* @type {number}
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.dictionaryPreScanSize_ = 1000;
/**
* Size of window. Used to check if a resize operation actually changed the size
* of the window.
* @type {goog.math.Size|undefined}
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.winSize_;
/**
* Numeric Id of the element that has focus. 0 when not set.
*
* @type {number}
* @private
*/
goog.ui.AbstractSpellChecker.prototype.focusedElementId_ = 0;
/**
* Event handler for listening to events without leaking.
* @type {goog.events.EventHandler|undefined}
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.eventHandler_;
/**
* The object handling keyboard events.
* @type {goog.events.KeyHandler|undefined}
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.keyHandler_;
/**
* Creates the initial DOM representation for the component.
* @override
*/
goog.ui.PlainTextSpellChecker.prototype.createDom = function() {
this.setElementInternal(this.getDomHelper().createElement('textarea'));
};
/** @override */
goog.ui.PlainTextSpellChecker.prototype.enterDocument = function() {
goog.ui.PlainTextSpellChecker.superClass_.enterDocument.call(this);
this.eventHandler_ = new goog.events.EventHandler(this);
this.keyHandler_ = new goog.events.KeyHandler(this.overlay_);
this.initSuggestionsMenu();
this.initAccessibility_();
};
/** @override */
goog.ui.PlainTextSpellChecker.prototype.exitDocument = function() {
goog.ui.PlainTextSpellChecker.superClass_.exitDocument.call(this);
if (this.eventHandler_) {
this.eventHandler_.dispose();
this.eventHandler_ = undefined;
}
if (this.keyHandler_) {
this.keyHandler_.dispose();
this.keyHandler_ = undefined;
}
};
/**
* Initializes suggestions menu. Populates menu with separator and ignore option
* that are always valid. Suggestions are later added above the separator.
* @override
*/
goog.ui.PlainTextSpellChecker.prototype.initSuggestionsMenu = function() {
goog.ui.PlainTextSpellChecker.superClass_.initSuggestionsMenu.call(this);
this.eventHandler_.listen(/** @type {goog.ui.PopupMenu} */ (this.getMenu()),
goog.ui.Component.EventType.BLUR, this.onCorrectionBlur_);
};
/**
* Checks spelling for all text and displays correction UI.
* @override
*/
goog.ui.PlainTextSpellChecker.prototype.check = function() {
var text = this.getElement().value;
this.getElement().readOnly = true;
// Prepare and position correction UI.
this.overlay_.innerHTML = '';
this.overlay_.className = this.correctionPaneClassName;
if (this.getElement().parentNode != this.overlay_.parentNode) {
this.getElement().parentNode.appendChild(this.overlay_);
}
goog.style.setElementShown(this.overlay_, false);
this.preChargeDictionary_(text);
};
/**
* Final stage of spell checking - displays the correction UI.
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.finishCheck_ = function() {
// Show correction UI.
this.positionOverlay_();
goog.style.setElementShown(this.getElement(), false);
goog.style.setElementShown(this.overlay_, true);
var eh = this.eventHandler_;
eh.listen(this.overlay_, goog.events.EventType.CLICK, this.onWordClick_);
eh.listen(/** @type {goog.events.KeyHandler} */ (this.keyHandler_),
goog.events.KeyHandler.EventType.KEY, this.handleOverlayKeyEvent);
// The position and size of the overlay element needs to be recalculated if
// the browser window is resized.
var win = goog.dom.getWindow(this.getDomHelper().getDocument()) || window;
this.winSize_ = goog.dom.getViewportSize(win);
eh.listen(win, goog.events.EventType.RESIZE, this.onWindowResize_);
goog.ui.PlainTextSpellChecker.superClass_.check.call(this);
};
/**
* Start the scan after the dictionary was loaded.
*
* @param {string} text text to process.
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.preChargeDictionary_ = function(text) {
this.eventHandler_.listen(this.handler_,
goog.spell.SpellCheck.EventType.READY, this.onDictionaryCharged_, true);
this.populateDictionary(text, this.dictionaryPreScanSize_);
};
/**
* Loads few initial dictionary words into the cache.
*
* @param {goog.events.Event} e goog.spell.SpellCheck.EventType.READY event.
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.onDictionaryCharged_ = function(e) {
e.stopPropagation();
this.eventHandler_.unlisten(this.handler_,
goog.spell.SpellCheck.EventType.READY, this.onDictionaryCharged_, true);
this.checkAsync_(this.getElement().value);
};
/**
* Processes the included and skips the excluded text ranges.
* @return {goog.ui.AbstractSpellChecker.AsyncResult} Whether the spell
* checking is pending or done.
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.spellCheckLoop_ = function() {
for (var i = this.textArrayIndex_; i < this.textArray_.length; ++i) {
var text = this.textArray_[i];
if (this.textArrayProcess_[i]) {
var result = this.processTextAsync(this.overlay_, text);
if (result == goog.ui.AbstractSpellChecker.AsyncResult.PENDING) {
this.textArrayIndex_ = i + 1;
goog.Timer.callOnce(this.boundContinueAsyncFn_);
return result;
}
} else {
this.processRange(this.overlay_, text);
}
}
this.textArray_ = [];
this.textArrayProcess_ = [];
return goog.ui.AbstractSpellChecker.AsyncResult.DONE;
};
/**
* Breaks text into included and excluded ranges using the marker RegExp
* supplied by the caller.
*
* @param {string} text text to process.
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.initTextArray_ = function(text) {
if (!this.excludeMarker) {
this.textArray_ = [text];
this.textArrayProcess_ = [true];
return;
}
this.textArray_ = [];
this.textArrayProcess_ = [];
this.excludeMarker.lastIndex = 0;
var stringSegmentStart = 0;
var result;
while (result = this.excludeMarker.exec(text)) {
if (result[0].length == 0) {
break;
}
var excludedRange = result[0];
var includedRange = text.substr(stringSegmentStart, result.index -
stringSegmentStart);
if (includedRange) {
this.textArray_.push(includedRange);
this.textArrayProcess_.push(true);
}
this.textArray_.push(excludedRange);
this.textArrayProcess_.push(false);
stringSegmentStart = this.excludeMarker.lastIndex;
}
var leftoverText = text.substr(stringSegmentStart);
if (leftoverText) {
this.textArray_.push(leftoverText);
this.textArrayProcess_.push(true);
}
};
/**
* Starts asynchrnonous spell checking.
*
* @param {string} text text to process.
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.checkAsync_ = function(text) {
this.initializeAsyncMode();
this.initTextArray_(text);
this.textArrayIndex_ = 0;
if (this.spellCheckLoop_() ==
goog.ui.AbstractSpellChecker.AsyncResult.PENDING) {
return;
}
this.finishAsyncProcessing();
this.finishCheck_();
};
/**
* Continues asynchrnonous spell checking.
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.continueAsync_ = function() {
// First finish with the current segment.
var result = this.continueAsyncProcessing();
if (result == goog.ui.AbstractSpellChecker.AsyncResult.PENDING) {
goog.Timer.callOnce(this.boundContinueAsyncFn_);
return;
}
if (this.spellCheckLoop_() ==
goog.ui.AbstractSpellChecker.AsyncResult.PENDING) {
return;
}
this.finishAsyncProcessing();
this.finishCheck_();
};
/**
* Processes word.
*
* @param {Node} node Node containing word.
* @param {string} word Word to process.
* @param {goog.spell.SpellCheck.WordStatus} status Status of word.
* @override
*/
goog.ui.PlainTextSpellChecker.prototype.processWord = function(node, word,
status) {
node.appendChild(this.createWordElement_(word, status));
};
/**
* Processes range of text - recognized words and separators.
*
* @param {Node} node Node containing separator.
* @param {string} text text to process.
* @override
*/
goog.ui.PlainTextSpellChecker.prototype.processRange = function(node, text) {
this.endOfLineMatcher_.lastIndex = 0;
var result;
while (result = this.endOfLineMatcher_.exec(text)) {
if (result[0].length == 0) {
break;
}
node.appendChild(this.getDomHelper().createTextNode(result[1]));
if (result[2]) {
node.appendChild(this.getDomHelper().createElement('br'));
}
}
};
/**
* Hides correction UI.
* @override
*/
goog.ui.PlainTextSpellChecker.prototype.resume = function() {
var wasVisible = this.isVisible();
goog.ui.PlainTextSpellChecker.superClass_.resume.call(this);
goog.style.setElementShown(this.overlay_, false);
goog.style.setElementShown(this.getElement(), true);
this.getElement().readOnly = false;
if (wasVisible) {
this.getElement().value = goog.dom.getRawTextContent(this.overlay_);
this.overlay_.innerHTML = '';
var eh = this.eventHandler_;
eh.unlisten(this.overlay_, goog.events.EventType.CLICK, this.onWordClick_);
eh.unlisten(/** @type {goog.events.KeyHandler} */ (this.keyHandler_),
goog.events.KeyHandler.EventType.KEY, this.handleOverlayKeyEvent);
var win = goog.dom.getWindow(this.getDomHelper().getDocument()) || window;
eh.unlisten(win, goog.events.EventType.RESIZE, this.onWindowResize_);
}
};
/**
* Returns desired element properties for the specified status.
*
* @param {goog.spell.SpellCheck.WordStatus} status Status of word.
* @return {Object} Properties to apply to word element.
* @override
*/
goog.ui.PlainTextSpellChecker.prototype.getElementProperties =
function(status) {
if (status == goog.spell.SpellCheck.WordStatus.INVALID) {
return {'class': this.invalidWordClassName};
} else if (status == goog.spell.SpellCheck.WordStatus.CORRECTED) {
return {'class': this.correctedWordClassName};
}
return {'class': ''};
};
/**
* Handles the click events.
*
* @param {goog.events.BrowserEvent} event Event object.
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.onWordClick_ = function(event) {
if (event.target.className == this.invalidWordClassName ||
event.target.className == this.correctedWordClassName) {
this.showSuggestionsMenu(/** @type {Element} */ (event.target), event);
// Prevent document click handler from closing the menu.
event.stopPropagation();
}
};
/**
* Handles window resize events.
*
* @param {goog.events.BrowserEvent} event Event object.
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.onWindowResize_ = function(event) {
var win = goog.dom.getWindow(this.getDomHelper().getDocument()) || window;
var size = goog.dom.getViewportSize(win);
if (size.width != this.winSize_.width ||
size.height != this.winSize_.height) {
goog.style.setElementShown(this.overlay_, false);
goog.style.setElementShown(this.getElement(), true);
// IE requires a slight delay, allowing the resize operation to take effect.
if (goog.userAgent.IE) {
goog.Timer.callOnce(this.resizeOverlay_, 100, this);
} else {
this.resizeOverlay_();
}
this.winSize_ = size;
}
};
/**
* Resizes overlay to match the size of the bound element then displays the
* overlay. Helper for {@link #onWindowResize_}.
*
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.resizeOverlay_ = function() {
this.positionOverlay_();
goog.style.setElementShown(this.getElement(), false);
goog.style.setElementShown(this.overlay_, true);
};
/**
* Updates the position and size of the overlay to match the original element.
*
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.positionOverlay_ = function() {
goog.style.setPosition(
this.overlay_, goog.style.getPosition(this.getElement()));
goog.style.setSize(this.overlay_, goog.style.getSize(this.getElement()));
};
/** @override */
goog.ui.PlainTextSpellChecker.prototype.disposeInternal = function() {
this.getDomHelper().removeNode(this.overlay_);
delete this.overlay_;
delete this.boundContinueAsyncFn_;
delete this.endOfLineMatcher_;
goog.ui.PlainTextSpellChecker.superClass_.disposeInternal.call(this);
};
/**
* Specify ARIA roles and states as appropriate.
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.initAccessibility_ = function() {
goog.asserts.assert(this.overlay_,
'The plain text spell checker DOM element cannot be null.');
goog.a11y.aria.setRole(this.overlay_, 'region');
goog.a11y.aria.setState(this.overlay_, 'live', 'assertive');
this.overlay_.tabIndex = 0;
/** @desc Title for Spell Checker's overlay.*/
var MSG_SPELLCHECKER_OVERLAY_TITLE = goog.getMsg('Spell Checker');
this.overlay_.title = MSG_SPELLCHECKER_OVERLAY_TITLE;
};
/**
* Handles key down for overlay.
* @param {goog.events.BrowserEvent} e The browser event.
* @return {boolean|undefined} The handled value.
*/
goog.ui.PlainTextSpellChecker.prototype.handleOverlayKeyEvent = function(e) {
var handled = false;
switch (e.keyCode) {
case goog.events.KeyCodes.RIGHT:
if (e.ctrlKey) {
handled = this.navigate_(goog.ui.AbstractSpellChecker.Direction.NEXT);
}
break;
case goog.events.KeyCodes.LEFT:
if (e.ctrlKey) {
handled = this.navigate_(
goog.ui.AbstractSpellChecker.Direction.PREVIOUS);
}
break;
case goog.events.KeyCodes.DOWN:
if (this.focusedElementId_) {
var el = this.getDomHelper().getElement(this.makeElementId(
this.focusedElementId_));
if (el) {
var position = goog.style.getPosition(el);
var size = goog.style.getSize(el);
position.x += size.width / 2;
position.y += size.height / 2;
this.showSuggestionsMenu(el, position);
handled = undefined;
}
}
break;
}
if (handled) {
e.preventDefault();
}
return handled;
};
/**
* Navigate keyboard focus in the given direction.
*
* @param {goog.ui.AbstractSpellChecker.Direction} direction The direction to
* navigate in.
* @return {boolean} Whether the action is handled here. If not handled
* here, the initiating event may be propagated.
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.navigate_ = function(direction) {
var handled = false;
var previous = direction == goog.ui.AbstractSpellChecker.Direction.PREVIOUS;
var lastId = goog.ui.AbstractSpellChecker.getNextId();
var focusedId = this.focusedElementId_;
var el;
do {
focusedId += previous ? -1 : 1;
if (focusedId < 1 || focusedId > lastId) {
focusedId = 0;
break;
}
} while (!(el = this.getElementById(focusedId)));
if (el) {
el.focus();
this.focusedElementId_ = focusedId;
handled = true;
}
return handled;
};
/**
* Handles correction menu actions.
*
* @param {goog.events.Event} event Action event.
* @override
*/
goog.ui.PlainTextSpellChecker.prototype.onCorrectionAction = function(event) {
goog.ui.PlainTextSpellChecker.superClass_.onCorrectionAction.call(this,
event);
// In case of editWord base class has already set the focus (on the input),
// otherwise set the focus back on the word.
if (event.target != this.getMenuEdit()) {
this.reFocus_();
}
};
/**
* Handles blur on the menu.
* @param {goog.events.BrowserEvent} event Blur event.
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.onCorrectionBlur_ = function(event) {
this.reFocus_();
};
/**
* Sets the focus back on the previously focused word element.
* @private
*/
goog.ui.PlainTextSpellChecker.prototype.reFocus_ = function() {
var el = this.getElementById(this.focusedElementId_);
if (el) {
el.focus();
} else {
this.overlay_.focus();
}
};
| 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 Rounded corner tab renderer for {@link goog.ui.Tab}s.
*
* @author attila@google.com (Attila Bodis)
*/
goog.provide('goog.ui.RoundedTabRenderer');
goog.require('goog.dom');
goog.require('goog.ui.Tab');
goog.require('goog.ui.TabBar.Location');
goog.require('goog.ui.TabRenderer');
goog.require('goog.ui.registry');
/**
* Rounded corner tab renderer for {@link goog.ui.Tab}s.
* @constructor
* @extends {goog.ui.TabRenderer}
*/
goog.ui.RoundedTabRenderer = function() {
goog.ui.TabRenderer.call(this);
};
goog.inherits(goog.ui.RoundedTabRenderer, goog.ui.TabRenderer);
goog.addSingletonGetter(goog.ui.RoundedTabRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.RoundedTabRenderer.CSS_CLASS = goog.getCssName('goog-rounded-tab');
/**
* Returns the CSS class name to be applied to the root element of all tabs
* rendered or decorated using this renderer.
* @return {string} Renderer-specific CSS class name.
* @override
*/
goog.ui.RoundedTabRenderer.prototype.getCssClass = function() {
return goog.ui.RoundedTabRenderer.CSS_CLASS;
};
/**
* Creates the tab's DOM structure, based on the containing tab bar's location
* relative to tab contents. For example, the DOM for a tab in a tab bar
* located above tab contents would look like this:
* <pre>
* <div class="goog-rounded-tab" title="...">
* <table class="goog-rounded-tab-table">
* <tbody>
* <tr>
* <td nowrap>
* <div class="goog-rounded-tab-outer-edge"></div>
* <div class="goog-rounded-tab-inner-edge"></div>
* </td>
* </tr>
* <tr>
* <td nowrap>
* <div class="goog-rounded-tab-caption">Hello, world</div>
* </td>
* </tr>
* </tbody>
* </table>
* </div>
* </pre>
* @param {goog.ui.Control} tab Tab to render.
* @return {Element} Root element for the tab.
* @override
*/
goog.ui.RoundedTabRenderer.prototype.createDom = function(tab) {
return this.decorate(tab,
goog.ui.RoundedTabRenderer.superClass_.createDom.call(this, tab));
};
/**
* Decorates the element with the tab. Overrides the superclass implementation
* by wrapping the tab's content in a table that implements rounded corners.
* @param {goog.ui.Control} tab Tab to decorate the element.
* @param {Element} element Element to decorate.
* @return {Element} Decorated element.
* @override
*/
goog.ui.RoundedTabRenderer.prototype.decorate = function(tab, element) {
var tabBar = tab.getParent();
if (!this.getContentElement(element)) {
// The element to be decorated doesn't appear to have the full tab DOM,
// so we have to create it.
element.appendChild(this.createTab(tab.getDomHelper(), element.childNodes,
tabBar.getLocation()));
}
return goog.ui.RoundedTabRenderer.superClass_.decorate.call(this, tab,
element);
};
/**
* Creates a table implementing a rounded corner tab.
* @param {goog.dom.DomHelper} dom DOM helper to use for element construction.
* @param {goog.ui.ControlContent} caption Text caption or DOM structure
* to display as the tab's caption.
* @param {goog.ui.TabBar.Location} location Tab bar location relative to the
* tab contents.
* @return {Element} Table implementing a rounded corner tab.
* @protected
*/
goog.ui.RoundedTabRenderer.prototype.createTab = function(dom, caption,
location) {
var rows = [];
if (location != goog.ui.TabBar.Location.BOTTOM) {
// This is a left, right, or top tab, so it needs a rounded top edge.
rows.push(this.createEdge(dom, /* isTopEdge */ true));
}
rows.push(this.createCaption(dom, caption));
if (location != goog.ui.TabBar.Location.TOP) {
// This is a left, right, or bottom tab, so it needs a rounded bottom edge.
rows.push(this.createEdge(dom, /* isTopEdge */ false));
}
return dom.createDom('table', {
'cellPadding': 0,
'cellSpacing': 0,
'className': goog.getCssName(this.getStructuralCssClass(), 'table')
}, dom.createDom('tbody', null, rows));
};
/**
* Creates a table row implementing the tab caption.
* @param {goog.dom.DomHelper} dom DOM helper to use for element construction.
* @param {goog.ui.ControlContent} caption Text caption or DOM structure
* to display as the tab's caption.
* @return {Element} Tab caption table row.
* @protected
*/
goog.ui.RoundedTabRenderer.prototype.createCaption = function(dom, caption) {
var baseClass = this.getStructuralCssClass();
return dom.createDom('tr', null,
dom.createDom('td', {'noWrap': true},
dom.createDom('div', goog.getCssName(baseClass, 'caption'),
caption)));
};
/**
* Creates a table row implementing a rounded tab edge.
* @param {goog.dom.DomHelper} dom DOM helper to use for element construction.
* @param {boolean} isTopEdge Whether to create a top or bottom edge.
* @return {Element} Rounded tab edge table row.
* @protected
*/
goog.ui.RoundedTabRenderer.prototype.createEdge = function(dom, isTopEdge) {
var baseClass = this.getStructuralCssClass();
var inner = dom.createDom('div', goog.getCssName(baseClass, 'inner-edge'));
var outer = dom.createDom('div', goog.getCssName(baseClass, 'outer-edge'));
return dom.createDom('tr', null,
dom.createDom('td', {'noWrap': true},
isTopEdge ? [outer, inner] : [inner, outer]));
};
/** @override */
goog.ui.RoundedTabRenderer.prototype.getContentElement = function(element) {
var baseClass = this.getStructuralCssClass();
return element && goog.dom.getElementsByTagNameAndClass(
'div', goog.getCssName(baseClass, 'caption'), element)[0];
};
// Register a decorator factory function for goog.ui.Tabs using the rounded
// tab renderer.
goog.ui.registry.setDecoratorByClassName(goog.ui.RoundedTabRenderer.CSS_CLASS,
function() {
return new goog.ui.Tab(null, goog.ui.RoundedTabRenderer.getInstance());
});
| 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 Definition of MenuBarRenderer decorator, a static call into
* the goog.ui.registry.
*
* @see ../demos/menubar.html
*/
/** @suppress {extraProvide} */
goog.provide('goog.ui.menuBarDecorator');
goog.require('goog.ui.MenuBarRenderer');
goog.require('goog.ui.menuBar');
goog.require('goog.ui.registry');
/**
* Register a decorator factory function. 'goog-menubar' defaults to
* goog.ui.MenuBarRenderer.
*/
goog.ui.registry.setDecoratorByClassName(goog.ui.MenuBarRenderer.CSS_CLASS,
goog.ui.menuBar.create);
| 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 slider implementation that allows to select a value within a
* range by dragging a thumb. The selected value is exposed through getValue().
*
* To decorate, the slider should be bound to an element with the class name
* 'goog-slider-[vertical / horizontal]' containing a child with the classname
* 'goog-slider-thumb'.
*
* Decorate Example:
* <div id="slider" class="goog-slider-horizontal">
* <div class="goog-twothumbslider-thumb">
* </div>
* <script>
*
* var slider = new goog.ui.Slider;
* slider.decorate(document.getElementById('slider'));
*
* @author arv@google.com (Erik Arvidsson)
* @see ../demos/slider.html
*/
// Implementation note: We implement slider by inheriting from baseslider,
// which allows to select sub-ranges within a range using two thumbs. All we do
// is we co-locate the two thumbs into one.
goog.provide('goog.ui.Slider');
goog.provide('goog.ui.Slider.Orientation');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.Role');
goog.require('goog.dom');
goog.require('goog.ui.SliderBase');
goog.require('goog.ui.SliderBase.Orientation');
/**
* This creates a slider object.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @constructor
* @extends {goog.ui.SliderBase}
*/
goog.ui.Slider = function(opt_domHelper) {
goog.ui.SliderBase.call(this, opt_domHelper);
this.rangeModel.setExtent(0);
};
goog.inherits(goog.ui.Slider, goog.ui.SliderBase);
/**
* Expose Enum of superclass (representing the orientation of the slider) within
* Slider namespace.
*
* @enum {string}
*/
goog.ui.Slider.Orientation = goog.ui.SliderBase.Orientation;
/**
* The prefix we use for the CSS class names for the slider and its elements.
* @type {string}
*/
goog.ui.Slider.CSS_CLASS_PREFIX = goog.getCssName('goog-slider');
/**
* CSS class name for the single thumb element.
* @type {string}
*/
goog.ui.Slider.THUMB_CSS_CLASS =
goog.getCssName(goog.ui.Slider.CSS_CLASS_PREFIX, 'thumb');
/**
* Returns CSS class applied to the slider element.
* @param {goog.ui.SliderBase.Orientation} orient Orientation of the slider.
* @return {string} The CSS class applied to the slider element.
* @protected
* @override
*/
goog.ui.Slider.prototype.getCssClass = function(orient) {
return orient == goog.ui.SliderBase.Orientation.VERTICAL ?
goog.getCssName(goog.ui.Slider.CSS_CLASS_PREFIX, 'vertical') :
goog.getCssName(goog.ui.Slider.CSS_CLASS_PREFIX, 'horizontal');
};
/** @override */
goog.ui.Slider.prototype.createThumbs = function() {
// find thumb
var element = this.getElement();
var thumb = goog.dom.getElementsByTagNameAndClass(
null, goog.ui.Slider.THUMB_CSS_CLASS, element)[0];
if (!thumb) {
thumb = this.createThumb_();
element.appendChild(thumb);
}
this.valueThumb = this.extentThumb = thumb;
};
/**
* Creates the thumb element.
* @return {HTMLDivElement} The created thumb element.
* @private
*/
goog.ui.Slider.prototype.createThumb_ = function() {
var thumb =
this.getDomHelper().createDom('div', goog.ui.Slider.THUMB_CSS_CLASS);
goog.a11y.aria.setRole(thumb, goog.a11y.aria.Role.BUTTON);
return /** @type {HTMLDivElement} */ (thumb);
};
| 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 AttachableMenu class.
*
*/
goog.provide('goog.ui.AttachableMenu');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.State');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.events.Event');
goog.require('goog.events.KeyCodes');
goog.require('goog.string');
goog.require('goog.style');
goog.require('goog.ui.ItemEvent');
goog.require('goog.ui.MenuBase');
goog.require('goog.ui.PopupBase');
goog.require('goog.userAgent');
/**
* An implementation of a menu that can attach itself to DOM element that
* are annotated appropriately.
*
* The following attributes are used by the AttachableMenu
*
* menu-item - Should be set on DOM elements that function as items in the
* menu that can be selected.
* classNameSelected - A class that will be added to the element's class names
* when the item is selected via keyboard or mouse.
*
* @param {Element=} opt_element A DOM element for the popup.
* @constructor
* @extends {goog.ui.MenuBase}
* @deprecated Use goog.ui.PopupMenu.
*/
goog.ui.AttachableMenu = function(opt_element) {
goog.ui.MenuBase.call(this, opt_element);
};
goog.inherits(goog.ui.AttachableMenu, goog.ui.MenuBase);
/**
* The currently selected element (mouse was moved over it or keyboard arrows)
* @type {Element}
* @private
*/
goog.ui.AttachableMenu.prototype.selectedElement_ = null;
/**
* Class name to append to a menu item's class when it's selected
* @type {string}
* @private
*/
goog.ui.AttachableMenu.prototype.itemClassName_ = 'menu-item';
/**
* Class name to append to a menu item's class when it's selected
* @type {string}
* @private
*/
goog.ui.AttachableMenu.prototype.selectedItemClassName_ = 'menu-item-selected';
/**
* Keep track of when the last key was pressed so that a keydown-scroll doesn't
* trigger a mouseover event
* @type {number}
* @private
*/
goog.ui.AttachableMenu.prototype.lastKeyDown_ = goog.now();
/** @override */
goog.ui.AttachableMenu.prototype.disposeInternal = function() {
goog.ui.AttachableMenu.superClass_.disposeInternal.call(this);
this.selectedElement_ = null;
};
/**
* Sets the class name to use for menu items
*
* @return {string} The class name to use for items.
*/
goog.ui.AttachableMenu.prototype.getItemClassName = function() {
return this.itemClassName_;
};
/**
* Sets the class name to use for menu items
*
* @param {string} name The class name to use for items.
*/
goog.ui.AttachableMenu.prototype.setItemClassName = function(name) {
this.itemClassName_ = name;
};
/**
* Sets the class name to use for selected menu items
* todo(user) - reevaluate if we can simulate pseudo classes in IE
*
* @return {string} The class name to use for selected items.
*/
goog.ui.AttachableMenu.prototype.getSelectedItemClassName = function() {
return this.selectedItemClassName_;
};
/**
* Sets the class name to use for selected menu items
* todo(user) - reevaluate if we can simulate pseudo classes in IE
*
* @param {string} name The class name to use for selected items.
*/
goog.ui.AttachableMenu.prototype.setSelectedItemClassName = function(name) {
this.selectedItemClassName_ = name;
};
/**
* Returns the selected item
*
* @return {Element} The item selected or null if no item is selected.
* @override
*/
goog.ui.AttachableMenu.prototype.getSelectedItem = function() {
return this.selectedElement_;
};
/** @override */
goog.ui.AttachableMenu.prototype.setSelectedItem = function(obj) {
var elt = /** @type {Element} */ (obj);
if (this.selectedElement_) {
goog.dom.classes.remove(this.selectedElement_, this.selectedItemClassName_);
}
this.selectedElement_ = elt;
var el = this.getElement();
goog.asserts.assert(el, 'The attachable menu DOM element cannot be null.');
if (this.selectedElement_) {
goog.dom.classes.add(this.selectedElement_, this.selectedItemClassName_);
if (elt.id) {
// Update activedescendant to reflect the new selection. ARIA roles for
// menu and menuitem can be set statically (thru Soy templates, for
// example) whereas this needs to be updated as the selection changes.
goog.a11y.aria.setState(el, goog.a11y.aria.State.ACTIVEDESCENDANT,
elt.id);
}
var top = this.selectedElement_.offsetTop;
var height = this.selectedElement_.offsetHeight;
var scrollTop = el.scrollTop;
var scrollHeight = el.offsetHeight;
// If the menu is scrollable this scrolls the selected item into view
// (this has no effect when the menu doesn't scroll)
if (top < scrollTop) {
el.scrollTop = top;
} else if (top + height > scrollTop + scrollHeight) {
el.scrollTop = top + height - scrollHeight;
}
} else {
// Clear off activedescendant to reflect no selection.
goog.a11y.aria.setState(el, goog.a11y.aria.State.ACTIVEDESCENDANT, '');
}
};
/** @override */
goog.ui.AttachableMenu.prototype.showPopupElement = function() {
// The scroll position cannot be set for hidden (display: none) elements in
// gecko browsers.
var el = /** @type {Element} */ (this.getElement());
goog.style.setElementShown(el, true);
el.scrollTop = 0;
el.style.visibility = 'visible';
};
/**
* Called after the menu is shown.
* @protected
* @suppress {underscore}
* @override
*/
goog.ui.AttachableMenu.prototype.onShow_ = function() {
goog.ui.AttachableMenu.superClass_.onShow_.call(this);
// In IE, focusing the menu causes weird scrolling to happen. Focusing the
// first child makes the scroll behavior better, and the key handling still
// works. In FF, focusing the first child causes us to lose key events, so we
// still focus the menu.
var el = this.getElement();
goog.userAgent.IE ? el.firstChild.focus() :
el.focus();
};
/**
* Returns the next or previous item. Used for up/down arrows.
*
* @param {boolean} prev True to go to the previous element instead of next.
* @return {Element} The next or previous element.
* @protected
*/
goog.ui.AttachableMenu.prototype.getNextPrevItem = function(prev) {
// first find the index of the next element
var elements = this.getElement().getElementsByTagName('*');
var elementCount = elements.length;
var index;
// if there is a selected element, find its index and then inc/dec by one
if (this.selectedElement_) {
for (var i = 0; i < elementCount; i++) {
if (elements[i] == this.selectedElement_) {
index = prev ? i - 1 : i + 1;
break;
}
}
}
// if no selected element, start from beginning or end
if (!goog.isDef(index)) {
index = prev ? elementCount - 1 : 0;
}
// iterate forward or backwards through the elements finding the next
// menu item
for (var i = 0; i < elementCount; i++) {
var multiplier = prev ? -1 : 1;
var nextIndex = index + (multiplier * i) % elementCount;
// if overflowed/underflowed, wrap around
if (nextIndex < 0) {
nextIndex += elementCount;
} else if (nextIndex >= elementCount) {
nextIndex -= elementCount;
}
if (this.isMenuItem_(elements[nextIndex])) {
return elements[nextIndex];
}
}
return null;
};
/**
* Mouse over handler for the menu.
* @param {goog.events.Event} e The event object.
* @protected
* @override
*/
goog.ui.AttachableMenu.prototype.onMouseOver = function(e) {
var eltItem = this.getAncestorMenuItem_(/** @type {Element} */ (e.target));
if (eltItem == null) {
return;
}
// Stop the keydown triggering a mouseover in FF.
if (goog.now() - this.lastKeyDown_ > goog.ui.PopupBase.DEBOUNCE_DELAY_MS) {
this.setSelectedItem(eltItem);
}
};
/**
* Mouse out handler for the menu.
* @param {goog.events.Event} e The event object.
* @protected
* @override
*/
goog.ui.AttachableMenu.prototype.onMouseOut = function(e) {
var eltItem = this.getAncestorMenuItem_(/** @type {Element} */ (e.target));
if (eltItem == null) {
return;
}
// Stop the keydown triggering a mouseout in FF.
if (goog.now() - this.lastKeyDown_ > goog.ui.PopupBase.DEBOUNCE_DELAY_MS) {
this.setSelectedItem(null);
}
};
/**
* Mouse down handler for the menu. Prevents default to avoid text selection.
* @param {!goog.events.Event} e The event object.
* @protected
* @override
*/
goog.ui.AttachableMenu.prototype.onMouseDown = goog.events.Event.preventDefault;
/**
* Mouse up handler for the menu.
* @param {goog.events.Event} e The event object.
* @protected
* @override
*/
goog.ui.AttachableMenu.prototype.onMouseUp = function(e) {
var eltItem = this.getAncestorMenuItem_(/** @type {Element} */ (e.target));
if (eltItem == null) {
return;
}
this.setVisible(false);
this.onItemSelected_(eltItem);
};
/**
* Key down handler for the menu.
* @param {goog.events.KeyEvent} e The event object.
* @protected
* @override
*/
goog.ui.AttachableMenu.prototype.onKeyDown = function(e) {
switch (e.keyCode) {
case goog.events.KeyCodes.DOWN:
this.setSelectedItem(this.getNextPrevItem(false));
this.lastKeyDown_ = goog.now();
break;
case goog.events.KeyCodes.UP:
this.setSelectedItem(this.getNextPrevItem(true));
this.lastKeyDown_ = goog.now();
break;
case goog.events.KeyCodes.ENTER:
if (this.selectedElement_) {
this.onItemSelected_();
this.setVisible(false);
}
break;
case goog.events.KeyCodes.ESC:
this.setVisible(false);
break;
default:
if (e.charCode) {
var charStr = String.fromCharCode(e.charCode);
this.selectByName_(charStr, 1, true);
}
break;
}
// Prevent the browser's default keydown behaviour when the menu is open,
// e.g. keyboard scrolling.
e.preventDefault();
// Stop propagation to prevent application level keyboard shortcuts from
// firing.
e.stopPropagation();
this.dispatchEvent(e);
};
/**
* Find an item that has the given prefix and select it.
*
* @param {string} prefix The entered prefix, so far.
* @param {number=} opt_direction 1 to search forward from the selection
* (default), -1 to search backward (e.g. to go to the previous match).
* @param {boolean=} opt_skip True if should skip the current selection,
* unless no other item has the given prefix.
* @private
*/
goog.ui.AttachableMenu.prototype.selectByName_ =
function(prefix, opt_direction, opt_skip) {
var elements = this.getElement().getElementsByTagName('*');
var elementCount = elements.length;
var index;
if (elementCount == 0) {
return;
}
if (!this.selectedElement_ ||
(index = goog.array.indexOf(elements, this.selectedElement_)) == -1) {
// no selection or selection isn't known => start at the beginning
index = 0;
}
var start = index;
var re = new RegExp('^' + goog.string.regExpEscape(prefix), 'i');
var skip = opt_skip && this.selectedElement_;
var dir = opt_direction || 1;
do {
if (elements[index] != skip && this.isMenuItem_(elements[index])) {
var name = goog.dom.getTextContent(elements[index]);
if (name.match(re)) {
break;
}
}
index += dir;
if (index == elementCount) {
index = 0;
} else if (index < 0) {
index = elementCount - 1;
}
} while (index != start);
if (this.selectedElement_ != elements[index]) {
this.setSelectedItem(elements[index]);
}
};
/**
* Dispatch an ITEM_ACTION event when an item is selected
* @param {Object=} opt_item Item selected.
* @private
*/
goog.ui.AttachableMenu.prototype.onItemSelected_ = function(opt_item) {
this.dispatchEvent(new goog.ui.ItemEvent(goog.ui.MenuBase.Events.ITEM_ACTION,
this, opt_item || this.selectedElement_));
};
/**
* Returns whether the specified element is a menu item.
* @param {Element|undefined} elt The element to find a menu item ancestor of.
* @return {boolean} Whether the specified element is a menu item.
* @private
*/
goog.ui.AttachableMenu.prototype.isMenuItem_ = function(elt) {
return !!elt && goog.dom.classes.has(elt, this.itemClassName_);
};
/**
* Returns the menu-item scoping the specified element, or null if there is
* none.
* @param {Element|undefined} elt The element to find a menu item ancestor of.
* @return {Element} The menu-item scoping the specified element, or null if
* there is none.
* @private
*/
goog.ui.AttachableMenu.prototype.getAncestorMenuItem_ = function(elt) {
if (elt) {
var ownerDocumentBody = goog.dom.getOwnerDocument(elt).body;
while (elt != null && elt != ownerDocumentBody) {
if (this.isMenuItem_(elt)) {
return elt;
}
elt = /** @type {Element} */ (elt.parentNode);
}
}
return null;
};
| 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 Input Date Picker implementation. Pairs a
* goog.ui.PopupDatePicker with an input element and handles the input from
* either.
*
* @see ../demos/inputdatepicker.html
*/
goog.provide('goog.ui.InputDatePicker');
goog.require('goog.date.DateTime');
goog.require('goog.dom');
goog.require('goog.string');
goog.require('goog.ui.Component');
goog.require('goog.ui.DatePicker');
goog.require('goog.ui.PopupBase');
goog.require('goog.ui.PopupDatePicker');
/**
* Input date picker widget.
*
* @param {goog.i18n.DateTimeFormat} dateTimeFormatter A formatter instance
* used to format the date picker's date for display in the input element.
* @param {goog.i18n.DateTimeParse} dateTimeParser A parser instance used to
* parse the input element's string as a date to set the picker.
* @param {goog.ui.DatePicker=} opt_datePicker Optional DatePicker. This
* enables the use of a custom date-picker instance.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @extends {goog.ui.Component}
* @constructor
*/
goog.ui.InputDatePicker = function(
dateTimeFormatter, dateTimeParser, opt_datePicker, opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
this.dateTimeFormatter_ = dateTimeFormatter;
this.dateTimeParser_ = dateTimeParser;
this.popupDatePicker_ = new goog.ui.PopupDatePicker(
opt_datePicker, opt_domHelper);
this.addChild(this.popupDatePicker_);
this.popupDatePicker_.setAllowAutoFocus(false);
};
goog.inherits(goog.ui.InputDatePicker, goog.ui.Component);
/**
* Used to format the date picker's date for display in the input element.
* @type {goog.i18n.DateTimeFormat}
* @private
*/
goog.ui.InputDatePicker.prototype.dateTimeFormatter_ = null;
/**
* Used to parse the input element's string as a date to set the picker.
* @type {goog.i18n.DateTimeParse}
* @private
*/
goog.ui.InputDatePicker.prototype.dateTimeParser_ = null;
/**
* The instance of goog.ui.PopupDatePicker used to pop up and select the date.
* @type {goog.ui.PopupDatePicker}
* @private
*/
goog.ui.InputDatePicker.prototype.popupDatePicker_ = null;
/**
* The element that the PopupDatePicker should be parented to. Defaults to the
* body element of the page.
* @type {Element}
* @private
*/
goog.ui.InputDatePicker.prototype.popupParentElement_ = null;
/**
* Returns the PopupDatePicker's internal DatePicker instance. This can be
* used to customize the date picker's styling.
*
* @return {goog.ui.DatePicker} The internal DatePicker instance.
*/
goog.ui.InputDatePicker.prototype.getDatePicker = function() {
return this.popupDatePicker_.getDatePicker();
};
/**
* Returns the selected date, if any. Compares the dates from the date picker
* and the input field, causing them to be synced if different.
* @return {goog.date.Date?} The selected date, if any.
*/
goog.ui.InputDatePicker.prototype.getDate = function() {
// The user expectation is that the date be whatever the input shows.
// This method biases towards the input value to conform to that expectation.
var inputDate = this.getInputValueAsDate_();
var pickerDate = this.popupDatePicker_.getDate();
if (inputDate && pickerDate) {
if (!inputDate.equals(pickerDate)) {
this.popupDatePicker_.setDate(inputDate);
}
} else {
this.popupDatePicker_.setDate(null);
}
return inputDate;
};
/**
* Sets the selected date. See goog.ui.PopupDatePicker.setDate().
* @param {goog.date.Date?} date The date to set.
*/
goog.ui.InputDatePicker.prototype.setDate = function(date) {
this.popupDatePicker_.setDate(date);
};
/**
* Sets the value of the input element. This can be overridden to support
* alternative types of input setting.
*
* @param {string} value The value to set.
*/
goog.ui.InputDatePicker.prototype.setInputValue = function(value) {
var el = this.getElement();
if (el.labelInput_) {
var labelInput = /** @type {goog.ui.LabelInput} */ (el.labelInput_);
labelInput.setValue(value);
} else {
el.value = value;
}
};
/**
* Returns the value of the input element. This can be overridden to support
* alternative types of input getting.
*
* @return {string} The input value.
*/
goog.ui.InputDatePicker.prototype.getInputValue = function() {
var el = this.getElement();
if (el.labelInput_) {
var labelInput = /** @type {goog.ui.LabelInput} */ (el.labelInput_);
return labelInput.getValue();
} else {
return el.value;
}
};
/**
* Gets the input element value and attempts to parse it as a date.
*
* @return {goog.date.Date?} The date object is returned if the parse
* is successful, null is returned on failure.
* @private
*/
goog.ui.InputDatePicker.prototype.getInputValueAsDate_ = function() {
var value = goog.string.trim(this.getInputValue());
if (value) {
var date = new goog.date.DateTime();
// DateTime needed as parse assumes it can call getHours(), getMinutes(),
// etc, on the date if hours and minutes aren't defined.
if (this.dateTimeParser_.strictParse(value, date) > 0) {
return date;
}
}
return null;
};
/**
* Creates an input element for use with the popup date picker.
* @override
*/
goog.ui.InputDatePicker.prototype.createDom = function() {
this.setElementInternal(
this.getDomHelper().createDom('input', {'type': 'text'}));
this.popupDatePicker_.createDom();
};
/**
* Sets the element that the PopupDatePicker should be parented to. If not set,
* defaults to the body element of the page.
* @param {Element} el The element that the PopupDatePicker should be parented
* to.
*/
goog.ui.InputDatePicker.prototype.setPopupParentElement = function(el) {
this.popupParentElement_ = el;
};
/** @override */
goog.ui.InputDatePicker.prototype.enterDocument = function() {
goog.ui.InputDatePicker.superClass_.enterDocument.call(this);
var el = this.getElement();
(this.popupParentElement_ || this.getDomHelper().getDocument().body).
appendChild(this.popupDatePicker_.getElement());
this.popupDatePicker_.enterDocument();
this.popupDatePicker_.attach(el);
// Set the date picker to have the input's initial value, if any.
this.popupDatePicker_.setDate(this.getInputValueAsDate_());
var handler = this.getHandler();
handler.listen(this.popupDatePicker_, goog.ui.DatePicker.Events.CHANGE,
this.onDateChanged_);
handler.listen(this.popupDatePicker_, goog.ui.PopupBase.EventType.SHOW,
this.onPopup_);
};
/** @override */
goog.ui.InputDatePicker.prototype.exitDocument = function() {
goog.ui.InputDatePicker.superClass_.exitDocument.call(this);
var el = this.getElement();
this.popupDatePicker_.detach(el);
this.popupDatePicker_.exitDocument();
goog.dom.removeNode(this.popupDatePicker_.getElement());
};
/** @override */
goog.ui.InputDatePicker.prototype.decorateInternal = function(element) {
goog.ui.InputDatePicker.superClass_.decorateInternal.call(this, element);
this.popupDatePicker_.createDom();
};
/** @override */
goog.ui.InputDatePicker.prototype.disposeInternal = function() {
goog.ui.InputDatePicker.superClass_.disposeInternal.call(this);
this.popupDatePicker_.dispose();
this.popupDatePicker_ = null;
this.popupParentElement_ = null;
};
/**
* See goog.ui.PopupDatePicker.showPopup().
* @param {Element} element Reference element for displaying the popup -- popup
* will appear at the bottom-left corner of this element.
*/
goog.ui.InputDatePicker.prototype.showForElement = function(element) {
this.popupDatePicker_.showPopup(element);
};
/**
* See goog.ui.PopupDatePicker.hidePopup().
*/
goog.ui.InputDatePicker.prototype.hidePopup = function() {
this.popupDatePicker_.hidePopup();
};
/**
* Event handler for popup date picker popup events.
*
* @param {goog.events.Event} e popup event.
* @private
*/
goog.ui.InputDatePicker.prototype.onPopup_ = function(e) {
this.setDate(this.getInputValueAsDate_());
};
/**
* Event handler for date change events. Called when the date changes.
*
* @param {goog.ui.DatePickerEvent} e Date change event.
* @private
*/
goog.ui.InputDatePicker.prototype.onDateChanged_ = function(e) {
this.setInputValue(e.date ? this.dateTimeFormatter_.format(e.date) : '');
};
| 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 color menu button control.
*
* @author attila@google.com (Attila Bodis)
* @author ssaviano@google.com (Steven Saviano)
*/
goog.provide('goog.ui.ToolbarColorMenuButton');
goog.require('goog.ui.ColorMenuButton');
goog.require('goog.ui.ControlContent');
goog.require('goog.ui.ToolbarColorMenuButtonRenderer');
goog.require('goog.ui.registry');
/**
* A color menu button control for a toolbar.
*
* @param {goog.ui.ControlContent} content Text caption or existing DOM
* structure to display as the button's caption.
* @param {goog.ui.Menu=} opt_menu Menu to render under the button when clicked;
* should contain at least one {@link goog.ui.ColorPalette} if present.
* @param {goog.ui.ColorMenuButtonRenderer=} opt_renderer Optional
* renderer used to render or decorate the button; defaults to
* {@link goog.ui.ToolbarColorMenuButtonRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
* document interaction.
* @constructor
* @extends {goog.ui.ColorMenuButton}
*/
goog.ui.ToolbarColorMenuButton = function(
content, opt_menu, opt_renderer, opt_domHelper) {
goog.ui.ColorMenuButton.call(this, content, opt_menu, opt_renderer ||
goog.ui.ToolbarColorMenuButtonRenderer.getInstance(), opt_domHelper);
};
goog.inherits(goog.ui.ToolbarColorMenuButton, goog.ui.ColorMenuButton);
// Registers a decorator factory function for toolbar color menu buttons.
goog.ui.registry.setDecoratorByClassName(
goog.getCssName('goog-toolbar-color-menu-button'),
function() {
return new goog.ui.ToolbarColorMenuButton(null);
});
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.