Debian Codegraph @

closure-library/closure/goog/ui/component.js

raw
1 // Copyright 2007 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Abstract class for all UI components. This defines the standard
17 * design pattern that all UI components should follow.
18 *
19 * @author [email protected] (Attila Bodis)
20 * @see ../demos/samplecomponent.html
21 * @see http://code.google.com/p/closure-library/wiki/IntroToComponents
22 */
23
24 goog.provide('goog.ui.Component');
25 goog.provide('goog.ui.Component.Error');
26 goog.provide('goog.ui.Component.EventType');
27 goog.provide('goog.ui.Component.State');
28
29 goog.require('goog.array');
30 goog.require('goog.asserts');
31 goog.require('goog.dom');
32 goog.require('goog.dom.NodeType');
33 goog.require('goog.dom.TagName');
34 goog.require('goog.events.EventHandler');
35 goog.require('goog.events.EventTarget');
36 goog.require('goog.object');
37 goog.require('goog.style');
38 goog.require('goog.ui.IdGenerator');
39
40
41
42 /**
43 * Default implementation of UI component.
44 *
45 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
46 * @constructor
47 * @extends {goog.events.EventTarget}
48 * @suppress {underscore}
49 */
50 goog.ui.Component = function(opt_domHelper) {
51 goog.events.EventTarget.call(this);
52 /**
53 * DomHelper used to interact with the document, allowing components to be
54 * created in a different window.
55 * @protected {!goog.dom.DomHelper}
56 * @suppress {underscore|visibility}
57 */
58 this.dom_ = opt_domHelper || goog.dom.getDomHelper();
59
60 /**
61 * Whether the component is rendered right-to-left. Right-to-left is set
62 * lazily when {@link #isRightToLeft} is called the first time, unless it has
63 * been set by calling {@link #setRightToLeft} explicitly.
64 * @private {?boolean}
65 */
66 this.rightToLeft_ = goog.ui.Component.defaultRightToLeft_;
67
68 /**
69 * Unique ID of the component, lazily initialized in {@link
70 * goog.ui.Component#getId} if needed. This property is strictly private and
71 * must not be accessed directly outside of this class!
72 * @private {?string}
73 */
74 this.id_ = null;
75
76 /**
77 * Whether the component is in the document.
78 * @private {boolean}
79 */
80 this.inDocument_ = false;
81
82 // TODO(attila): Stop referring to this private field in subclasses.
83 /**
84 * The DOM element for the component.
85 * @private {Element}
86 */
87 this.element_ = null;
88
89 /**
90 * Event handler.
91 * TODO(user): rename it to handler_ after all component subclasses in
92 * inside Google have been cleaned up.
93 * Code search: http://go/component_code_search
94 * @private {goog.events.EventHandler|undefined}
95 */
96 this.googUiComponentHandler_ = void 0;
97
98 /**
99 * Arbitrary data object associated with the component. Such as meta-data.
100 * @private {*}
101 */
102 this.model_ = null;
103
104 /**
105 * Parent component to which events will be propagated. This property is
106 * strictly private and must not be accessed directly outside of this class!
107 * @private {goog.ui.Component?}
108 */
109 this.parent_ = null;
110
111 /**
112 * Array of child components. Lazily initialized on first use. Must be kept
113 * in sync with {@code childIndex_}. This property is strictly private and
114 * must not be accessed directly outside of this class!
115 * @private {Array<goog.ui.Component>?}
116 */
117 this.children_ = null;
118
119 /**
120 * Map of child component IDs to child components. Used for constant-time
121 * random access to child components by ID. Lazily initialized on first use.
122 * Must be kept in sync with {@code children_}. This property is strictly
123 * private and must not be accessed directly outside of this class!
124 *
125 * We use a plain Object, not a {@link goog.structs.Map}, for simplicity.
126 * This means components can't have children with IDs such as 'constructor' or
127 * 'valueOf', but this shouldn't really be an issue in practice, and if it is,
128 * we can always fix it later without changing the API.
129 *
130 * @private {Object}
131 */
132 this.childIndex_ = null;
133
134 /**
135 * Flag used to keep track of whether a component decorated an already
136 * existing element or whether it created the DOM itself.
137 *
138 * If an element is decorated, dispose will leave the node in the document.
139 * It is up to the app to remove the node.
140 *
141 * If an element was rendered, dispose will remove the node automatically.
142 *
143 * @private {boolean}
144 */
145 this.wasDecorated_ = false;
146 };
147 goog.inherits(goog.ui.Component, goog.events.EventTarget);
148
149
150 /**
151 * @define {boolean} Whether to support calling decorate with an element that is
152 * not yet in the document. If true, we check if the element is in the
153 * document, and avoid calling enterDocument if it isn't. If false, we
154 * maintain legacy behavior (always call enterDocument from decorate).
155 */
156 goog.define('goog.ui.Component.ALLOW_DETACHED_DECORATION', false);
157
158
159 /**
160 * Generator for unique IDs.
161 * @type {goog.ui.IdGenerator}
162 * @private
163 */
164 goog.ui.Component.prototype.idGenerator_ = goog.ui.IdGenerator.getInstance();
165
166
167 // TODO(gboyer): See if we can remove this and just check goog.i18n.bidi.IS_RTL.
168 /**
169 * @define {number} Defines the default BIDI directionality.
170 * 0: Unknown.
171 * 1: Left-to-right.
172 * -1: Right-to-left.
173 */
174 goog.define('goog.ui.Component.DEFAULT_BIDI_DIR', 0);
175
176
177 /**
178 * The default right to left value.
179 * @type {?boolean}
180 * @private
181 */
182 goog.ui.Component.defaultRightToLeft_ =
183 (goog.ui.Component.DEFAULT_BIDI_DIR == 1) ?
184 false :
185 (goog.ui.Component.DEFAULT_BIDI_DIR == -1) ? true : null;
186
187
188 /**
189 * Common events fired by components so that event propagation is useful. Not
190 * all components are expected to dispatch or listen for all event types.
191 * Events dispatched before a state transition should be cancelable to prevent
192 * the corresponding state change.
193 * @enum {string}
194 */
195 goog.ui.Component.EventType = {
196 /** Dispatched before the component becomes visible. */
197 BEFORE_SHOW: 'beforeshow',
198
199 /**
200 * Dispatched after the component becomes visible.
201 * NOTE(user): For goog.ui.Container, this actually fires before containers
202 * are shown. Use goog.ui.Container.EventType.AFTER_SHOW if you want an event
203 * that fires after a goog.ui.Container is shown.
204 */
205 SHOW: 'show',
206
207 /** Dispatched before the component becomes hidden. */
208 HIDE: 'hide',
209
210 /** Dispatched before the component becomes disabled. */
211 DISABLE: 'disable',
212
213 /** Dispatched before the component becomes enabled. */
214 ENABLE: 'enable',
215
216 /** Dispatched before the component becomes highlighted. */
217 HIGHLIGHT: 'highlight',
218
219 /** Dispatched before the component becomes un-highlighted. */
220 UNHIGHLIGHT: 'unhighlight',
221
222 /** Dispatched before the component becomes activated. */
223 ACTIVATE: 'activate',
224
225 /** Dispatched before the component becomes deactivated. */
226 DEACTIVATE: 'deactivate',
227
228 /** Dispatched before the component becomes selected. */
229 SELECT: 'select',
230
231 /** Dispatched before the component becomes un-selected. */
232 UNSELECT: 'unselect',
233
234 /** Dispatched before a component becomes checked. */
235 CHECK: 'check',
236
237 /** Dispatched before a component becomes un-checked. */
238 UNCHECK: 'uncheck',
239
240 /** Dispatched before a component becomes focused. */
241 FOCUS: 'focus',
242
243 /** Dispatched before a component becomes blurred. */
244 BLUR: 'blur',
245
246 /** Dispatched before a component is opened (expanded). */
247 OPEN: 'open',
248
249 /** Dispatched before a component is closed (collapsed). */
250 CLOSE: 'close',
251
252 /** Dispatched after a component is moused over. */
253 ENTER: 'enter',
254
255 /** Dispatched after a component is moused out of. */
256 LEAVE: 'leave',
257
258 /** Dispatched after the user activates the component. */
259 ACTION: 'action',
260
261 /** Dispatched after the external-facing state of a component is changed. */
262 CHANGE: 'change'
263 };
264
265
266 /**
267 * Errors thrown by the component.
268 * @enum {string}
269 */
270 goog.ui.Component.Error = {
271 /**
272 * Error when a method is not supported.
273 */
274 NOT_SUPPORTED: 'Method not supported',
275
276 /**
277 * Error when the given element can not be decorated.
278 */
279 DECORATE_INVALID: 'Invalid element to decorate',
280
281 /**
282 * Error when the component is already rendered and another render attempt is
283 * made.
284 */
285 ALREADY_RENDERED: 'Component already rendered',
286
287 /**
288 * Error when an attempt is made to set the parent of a component in a way
289 * that would result in an inconsistent object graph.
290 */
291 PARENT_UNABLE_TO_BE_SET: 'Unable to set parent component',
292
293 /**
294 * Error when an attempt is made to add a child component at an out-of-bounds
295 * index. We don't support sparse child arrays.
296 */
297 CHILD_INDEX_OUT_OF_BOUNDS: 'Child component index out of bounds',
298
299 /**
300 * Error when an attempt is made to remove a child component from a component
301 * other than its parent.
302 */
303 NOT_OUR_CHILD: 'Child is not in parent component',
304
305 /**
306 * Error when an operation requiring DOM interaction is made when the
307 * component is not in the document
308 */
309 NOT_IN_DOCUMENT: 'Operation not supported while component is not in document',
310
311 /**
312 * Error when an invalid component state is encountered.
313 */
314 STATE_INVALID: 'Invalid component state'
315 };
316
317
318 /**
319 * Common component states. Components may have distinct appearance depending
320 * on what state(s) apply to them. Not all components are expected to support
321 * all states.
322 * @enum {number}
323 */
324 goog.ui.Component.State = {
325 /**
326 * Union of all supported component states.
327 */
328 ALL: 0xFF,
329
330 /**
331 * Component is disabled.
332 * @see goog.ui.Component.EventType.DISABLE
333 * @see goog.ui.Component.EventType.ENABLE
334 */
335 DISABLED: 0x01,
336
337 /**
338 * Component is highlighted.
339 * @see goog.ui.Component.EventType.HIGHLIGHT
340 * @see goog.ui.Component.EventType.UNHIGHLIGHT
341 */
342 HOVER: 0x02,
343
344 /**
345 * Component is active (or "pressed").
346 * @see goog.ui.Component.EventType.ACTIVATE
347 * @see goog.ui.Component.EventType.DEACTIVATE
348 */
349 ACTIVE: 0x04,
350
351 /**
352 * Component is selected.
353 * @see goog.ui.Component.EventType.SELECT
354 * @see goog.ui.Component.EventType.UNSELECT
355 */
356 SELECTED: 0x08,
357
358 /**
359 * Component is checked.
360 * @see goog.ui.Component.EventType.CHECK
361 * @see goog.ui.Component.EventType.UNCHECK
362 */
363 CHECKED: 0x10,
364
365 /**
366 * Component has focus.
367 * @see goog.ui.Component.EventType.FOCUS
368 * @see goog.ui.Component.EventType.BLUR
369 */
370 FOCUSED: 0x20,
371
372 /**
373 * Component is opened (expanded). Applies to tree nodes, menu buttons,
374 * submenus, zippys (zippies?), etc.
375 * @see goog.ui.Component.EventType.OPEN
376 * @see goog.ui.Component.EventType.CLOSE
377 */
378 OPENED: 0x40
379 };
380
381
382 /**
383 * Static helper method; returns the type of event components are expected to
384 * dispatch when transitioning to or from the given state.
385 * @param {goog.ui.Component.State} state State to/from which the component
386 * is transitioning.
387 * @param {boolean} isEntering Whether the component is entering or leaving the
388 * state.
389 * @return {goog.ui.Component.EventType} Event type to dispatch.
390 */
391 goog.ui.Component.getStateTransitionEvent = function(state, isEntering) {
392 switch (state) {
393 case goog.ui.Component.State.DISABLED:
394 return isEntering ? goog.ui.Component.EventType.DISABLE :
395 goog.ui.Component.EventType.ENABLE;
396 case goog.ui.Component.State.HOVER:
397 return isEntering ? goog.ui.Component.EventType.HIGHLIGHT :
398 goog.ui.Component.EventType.UNHIGHLIGHT;
399 case goog.ui.Component.State.ACTIVE:
400 return isEntering ? goog.ui.Component.EventType.ACTIVATE :
401 goog.ui.Component.EventType.DEACTIVATE;
402 case goog.ui.Component.State.SELECTED:
403 return isEntering ? goog.ui.Component.EventType.SELECT :
404 goog.ui.Component.EventType.UNSELECT;
405 case goog.ui.Component.State.CHECKED:
406 return isEntering ? goog.ui.Component.EventType.CHECK :
407 goog.ui.Component.EventType.UNCHECK;
408 case goog.ui.Component.State.FOCUSED:
409 return isEntering ? goog.ui.Component.EventType.FOCUS :
410 goog.ui.Component.EventType.BLUR;
411 case goog.ui.Component.State.OPENED:
412 return isEntering ? goog.ui.Component.EventType.OPEN :
413 goog.ui.Component.EventType.CLOSE;
414 default:
415 // Fall through.
416 }
417
418 // Invalid state.
419 throw new Error(goog.ui.Component.Error.STATE_INVALID);
420 };
421
422
423 /**
424 * Set the default right-to-left value. This causes all component's created from
425 * this point forward to have the given value. This is useful for cases where
426 * a given page is always in one directionality, avoiding unnecessary
427 * right to left determinations.
428 * @param {?boolean} rightToLeft Whether the components should be rendered
429 * right-to-left. Null iff components should determine their directionality.
430 */
431 goog.ui.Component.setDefaultRightToLeft = function(rightToLeft) {
432 goog.ui.Component.defaultRightToLeft_ = rightToLeft;
433 };
434
435
436 /**
437 * Gets the unique ID for the instance of this component. If the instance
438 * doesn't already have an ID, generates one on the fly.
439 * @return {string} Unique component ID.
440 */
441 goog.ui.Component.prototype.getId = function() {
442 return this.id_ || (this.id_ = this.idGenerator_.getNextUniqueId());
443 };
444
445
446 /**
447 * Assigns an ID to this component instance. It is the caller's responsibility
448 * to guarantee that the ID is unique. If the component is a child of a parent
449 * component, then the parent component's child index is updated to reflect the
450 * new ID; this may throw an error if the parent already has a child with an ID
451 * that conflicts with the new ID.
452 * @param {string} id Unique component ID.
453 */
454 goog.ui.Component.prototype.setId = function(id) {
455 if (this.parent_ && this.parent_.childIndex_) {
456 // Update the parent's child index.
457 goog.object.remove(this.parent_.childIndex_, this.id_);
458 goog.object.add(this.parent_.childIndex_, id, this);
459 }
460
461 // Update the component ID.
462 this.id_ = id;
463 };
464
465
466 /**
467 * Gets the component's element.
468 * @return {Element} The element for the component.
469 */
470 goog.ui.Component.prototype.getElement = function() {
471 return this.element_;
472 };
473
474
475 /**
476 * Gets the component's element. This differs from getElement in that
477 * it assumes that the element exists (i.e. the component has been
478 * rendered/decorated) and will cause an assertion error otherwise (if
479 * assertion is enabled).
480 * @return {!Element} The element for the component.
481 */
482 goog.ui.Component.prototype.getElementStrict = function() {
483 var el = this.element_;
484 goog.asserts.assert(
485 el, 'Can not call getElementStrict before rendering/decorating.');
486 return el;
487 };
488
489
490 /**
491 * Sets the component's root element to the given element. Considered
492 * protected and final.
493 *
494 * This should generally only be called during createDom. Setting the element
495 * does not actually change which element is rendered, only the element that is
496 * associated with this UI component.
497 *
498 * This should only be used by subclasses and its associated renderers.
499 *
500 * @param {Element} element Root element for the component.
501 */
502 goog.ui.Component.prototype.setElementInternal = function(element) {
503 this.element_ = element;
504 };
505
506
507 /**
508 * Returns an array of all the elements in this component's DOM with the
509 * provided className.
510 * @param {string} className The name of the class to look for.
511 * @return {!IArrayLike<!Element>} The items found with the class name provided.
512 */
513 goog.ui.Component.prototype.getElementsByClass = function(className) {
514 return this.element_ ?
515 this.dom_.getElementsByClass(className, this.element_) :
516 [];
517 };
518
519
520 /**
521 * Returns the first element in this component's DOM with the provided
522 * className.
523 * @param {string} className The name of the class to look for.
524 * @return {Element} The first item with the class name provided.
525 */
526 goog.ui.Component.prototype.getElementByClass = function(className) {
527 return this.element_ ? this.dom_.getElementByClass(className, this.element_) :
528 null;
529 };
530
531
532 /**
533 * Similar to {@code getElementByClass} except that it expects the
534 * element to be present in the dom thus returning a required value. Otherwise,
535 * will assert.
536 * @param {string} className The name of the class to look for.
537 * @return {!Element} The first item with the class name provided.
538 */
539 goog.ui.Component.prototype.getRequiredElementByClass = function(className) {
540 var el = this.getElementByClass(className);
541 goog.asserts.assert(
542 el, 'Expected element in component with class: %s', className);
543 return el;
544 };
545
546
547 /**
548 * Returns the event handler for this component, lazily created the first time
549 * this method is called.
550 * @return {!goog.events.EventHandler<T>} Event handler for this component.
551 * @protected
552 * @this {T}
553 * @template T
554 */
555 goog.ui.Component.prototype.getHandler = function() {
556 // TODO(user): templated "this" values currently result in "this" being
557 // "unknown" in the body of the function.
558 var self = /** @type {goog.ui.Component} */ (this);
559 if (!self.googUiComponentHandler_) {
560 self.googUiComponentHandler_ = new goog.events.EventHandler(self);
561 }
562 return self.googUiComponentHandler_;
563 };
564
565
566 /**
567 * Sets the parent of this component to use for event bubbling. Throws an error
568 * if the component already has a parent or if an attempt is made to add a
569 * component to itself as a child. Callers must use {@code removeChild}
570 * or {@code removeChildAt} to remove components from their containers before
571 * calling this method.
572 * @see goog.ui.Component#removeChild
573 * @see goog.ui.Component#removeChildAt
574 * @param {goog.ui.Component} parent The parent component.
575 */
576 goog.ui.Component.prototype.setParent = function(parent) {
577 if (this == parent) {
578 // Attempting to add a child to itself is an error.
579 throw new Error(goog.ui.Component.Error.PARENT_UNABLE_TO_BE_SET);
580 }
581
582 if (parent && this.parent_ && this.id_ && this.parent_.getChild(this.id_) &&
583 this.parent_ != parent) {
584 // This component is already the child of some parent, so it should be
585 // removed using removeChild/removeChildAt first.
586 throw new Error(goog.ui.Component.Error.PARENT_UNABLE_TO_BE_SET);
587 }
588
589 this.parent_ = parent;
590 goog.ui.Component.superClass_.setParentEventTarget.call(this, parent);
591 };
592
593
594 /**
595 * Returns the component's parent, if any.
596 * @return {goog.ui.Component?} The parent component.
597 */
598 goog.ui.Component.prototype.getParent = function() {
599 return this.parent_;
600 };
601
602
603 /**
604 * Overrides {@link goog.events.EventTarget#setParentEventTarget} to throw an
605 * error if the parent component is set, and the argument is not the parent.
606 * @override
607 */
608 goog.ui.Component.prototype.setParentEventTarget = function(parent) {
609 if (this.parent_ && this.parent_ != parent) {
610 throw new Error(goog.ui.Component.Error.NOT_SUPPORTED);
611 }
612 goog.ui.Component.superClass_.setParentEventTarget.call(this, parent);
613 };
614
615
616 /**
617 * Returns the dom helper that is being used on this component.
618 * @return {!goog.dom.DomHelper} The dom helper used on this component.
619 */
620 goog.ui.Component.prototype.getDomHelper = function() {
621 return this.dom_;
622 };
623
624
625 /**
626 * Determines whether the component has been added to the document.
627 * @return {boolean} TRUE if rendered. Otherwise, FALSE.
628 */
629 goog.ui.Component.prototype.isInDocument = function() {
630 return this.inDocument_;
631 };
632
633
634 /**
635 * Creates the initial DOM representation for the component. The default
636 * implementation is to set this.element_ = div.
637 */
638 goog.ui.Component.prototype.createDom = function() {
639 this.element_ = this.dom_.createElement(goog.dom.TagName.DIV);
640 };
641
642
643 /**
644 * Renders the component. If a parent element is supplied, the component's
645 * element will be appended to it. If there is no optional parent element and
646 * the element doesn't have a parentNode then it will be appended to the
647 * document body.
648 *
649 * If this component has a parent component, and the parent component is
650 * not in the document already, then this will not call {@code enterDocument}
651 * on this component.
652 *
653 * Throws an Error if the component is already rendered.
654 *
655 * @param {Element=} opt_parentElement Optional parent element to render the
656 * component into.
657 */
658 goog.ui.Component.prototype.render = function(opt_parentElement) {
659 this.render_(opt_parentElement);
660 };
661
662
663 /**
664 * Renders the component before another element. The other element should be in
665 * the document already.
666 *
667 * Throws an Error if the component is already rendered.
668 *
669 * @param {Node} sibling Node to render the component before.
670 */
671 goog.ui.Component.prototype.renderBefore = function(sibling) {
672 this.render_(/** @type {Element} */ (sibling.parentNode), sibling);
673 };
674
675
676 /**
677 * Renders the component. If a parent element is supplied, the component's
678 * element will be appended to it. If there is no optional parent element and
679 * the element doesn't have a parentNode then it will be appended to the
680 * document body.
681 *
682 * If this component has a parent component, and the parent component is
683 * not in the document already, then this will not call {@code enterDocument}
684 * on this component.
685 *
686 * Throws an Error if the component is already rendered.
687 *
688 * @param {Element=} opt_parentElement Optional parent element to render the
689 * component into.
690 * @param {Node=} opt_beforeNode Node before which the component is to
691 * be rendered. If left out the node is appended to the parent element.
692 * @private
693 */
694 goog.ui.Component.prototype.render_ = function(
695 opt_parentElement, opt_beforeNode) {
696 if (this.inDocument_) {
697 throw new Error(goog.ui.Component.Error.ALREADY_RENDERED);
698 }
699
700 if (!this.element_) {
701 this.createDom();
702 }
703
704 if (opt_parentElement) {
705 opt_parentElement.insertBefore(this.element_, opt_beforeNode || null);
706 } else {
707 this.dom_.getDocument().body.appendChild(this.element_);
708 }
709
710 // If this component has a parent component that isn't in the document yet,
711 // we don't call enterDocument() here. Instead, when the parent component
712 // enters the document, the enterDocument() call will propagate to its
713 // children, including this one. If the component doesn't have a parent
714 // or if the parent is already in the document, we call enterDocument().
715 if (!this.parent_ || this.parent_.isInDocument()) {
716 this.enterDocument();
717 }
718 };
719
720
721 /**
722 * Decorates the element for the UI component. If the element is in the
723 * document, the enterDocument method will be called.
724 *
725 * If goog.ui.Component.ALLOW_DETACHED_DECORATION is false, the caller must
726 * pass an element that is in the document.
727 *
728 * @param {Element} element Element to decorate.
729 */
730 goog.ui.Component.prototype.decorate = function(element) {
731 if (this.inDocument_) {
732 throw new Error(goog.ui.Component.Error.ALREADY_RENDERED);
733 } else if (element && this.canDecorate(element)) {
734 this.wasDecorated_ = true;
735
736 // Set the DOM helper of the component to match the decorated element.
737 var doc = goog.dom.getOwnerDocument(element);
738 if (!this.dom_ || this.dom_.getDocument() != doc) {
739 this.dom_ = goog.dom.getDomHelper(element);
740 }
741
742 // Call specific component decorate logic.
743 this.decorateInternal(element);
744
745 // If supporting detached decoration, check that element is in doc.
746 if (!goog.ui.Component.ALLOW_DETACHED_DECORATION ||
747 goog.dom.contains(doc, element)) {
748 this.enterDocument();
749 }
750 } else {
751 throw new Error(goog.ui.Component.Error.DECORATE_INVALID);
752 }
753 };
754
755
756 /**
757 * Determines if a given element can be decorated by this type of component.
758 * This method should be overridden by inheriting objects.
759 * @param {Element} element Element to decorate.
760 * @return {boolean} True if the element can be decorated, false otherwise.
761 */
762 goog.ui.Component.prototype.canDecorate = function(element) {
763 return true;
764 };
765
766
767 /**
768 * @return {boolean} Whether the component was decorated.
769 */
770 goog.ui.Component.prototype.wasDecorated = function() {
771 return this.wasDecorated_;
772 };
773
774
775 /**
776 * Actually decorates the element. Should be overridden by inheriting objects.
777 * This method can assume there are checks to ensure the component has not
778 * already been rendered have occurred and that enter document will be called
779 * afterwards. This method is considered protected.
780 * @param {Element} element Element to decorate.
781 * @protected
782 */
783 goog.ui.Component.prototype.decorateInternal = function(element) {
784 this.element_ = element;
785 };
786
787
788 /**
789 * Called when the component's element is known to be in the document. Anything
790 * using document.getElementById etc. should be done at this stage.
791 *
792 * If the component contains child components, this call is propagated to its
793 * children.
794 */
795 goog.ui.Component.prototype.enterDocument = function() {
796 this.inDocument_ = true;
797
798 // Propagate enterDocument to child components that have a DOM, if any.
799 // If a child was decorated before entering the document (permitted when
800 // goog.ui.Component.ALLOW_DETACHED_DECORATION is true), its enterDocument
801 // will be called here.
802 this.forEachChild(function(child) {
803 if (!child.isInDocument() && child.getElement()) {
804 child.enterDocument();
805 }
806 });
807 };
808
809
810 /**
811 * Called by dispose to clean up the elements and listeners created by a
812 * component, or by a parent component/application who has removed the
813 * component from the document but wants to reuse it later.
814 *
815 * If the component contains child components, this call is propagated to its
816 * children.
817 *
818 * It should be possible for the component to be rendered again once this method
819 * has been called.
820 */
821 goog.ui.Component.prototype.exitDocument = function() {
822 // Propagate exitDocument to child components that have been rendered, if any.
823 this.forEachChild(function(child) {
824 if (child.isInDocument()) {
825 child.exitDocument();
826 }
827 });
828
829 if (this.googUiComponentHandler_) {
830 this.googUiComponentHandler_.removeAll();
831 }
832
833 this.inDocument_ = false;
834 };
835
836
837 /**
838 * Disposes of the component. Calls {@code exitDocument}, which is expected to
839 * remove event handlers and clean up the component. Propagates the call to
840 * the component's children, if any. Removes the component's DOM from the
841 * document unless it was decorated.
842 * @override
843 * @protected
844 */
845 goog.ui.Component.prototype.disposeInternal = function() {
846 if (this.inDocument_) {
847 this.exitDocument();
848 }
849
850 if (this.googUiComponentHandler_) {
851 this.googUiComponentHandler_.dispose();
852 delete this.googUiComponentHandler_;
853 }
854
855 // Disposes of the component's children, if any.
856 this.forEachChild(function(child) { child.dispose(); });
857
858 // Detach the component's element from the DOM, unless it was decorated.
859 if (!this.wasDecorated_ && this.element_) {
860 goog.dom.removeNode(this.element_);
861 }
862
863 this.children_ = null;
864 this.childIndex_ = null;
865 this.element_ = null;
866 this.model_ = null;
867 this.parent_ = null;
868
869 goog.ui.Component.superClass_.disposeInternal.call(this);
870 };
871
872
873 /**
874 * Helper function for subclasses that gets a unique id for a given fragment,
875 * this can be used by components to generate unique string ids for DOM
876 * elements.
877 * @param {string} idFragment A partial id.
878 * @return {string} Unique element id.
879 */
880 goog.ui.Component.prototype.makeId = function(idFragment) {
881 return this.getId() + '.' + idFragment;
882 };
883
884
885 /**
886 * Makes a collection of ids. This is a convenience method for makeId. The
887 * object's values are the id fragments and the new values are the generated
888 * ids. The key will remain the same.
889 * @param {Object} object The object that will be used to create the ids.
890 * @return {!Object<string, string>} An object of id keys to generated ids.
891 */
892 goog.ui.Component.prototype.makeIds = function(object) {
893 var ids = {};
894 for (var key in object) {
895 ids[key] = this.makeId(object[key]);
896 }
897 return ids;
898 };
899
900
901 /**
902 * Returns the model associated with the UI component.
903 * @return {*} The model.
904 */
905 goog.ui.Component.prototype.getModel = function() {
906 return this.model_;
907 };
908
909
910 /**
911 * Sets the model associated with the UI component.
912 * @param {*} obj The model.
913 */
914 goog.ui.Component.prototype.setModel = function(obj) {
915 this.model_ = obj;
916 };
917
918
919 /**
920 * Helper function for returning the fragment portion of an id generated using
921 * makeId().
922 * @param {string} id Id generated with makeId().
923 * @return {string} Fragment.
924 */
925 goog.ui.Component.prototype.getFragmentFromId = function(id) {
926 return id.substring(this.getId().length + 1);
927 };
928
929
930 /**
931 * Helper function for returning an element in the document with a unique id
932 * generated using makeId().
933 * @param {string} idFragment The partial id.
934 * @return {Element} The element with the unique id, or null if it cannot be
935 * found.
936 */
937 goog.ui.Component.prototype.getElementByFragment = function(idFragment) {
938 if (!this.inDocument_) {
939 throw new Error(goog.ui.Component.Error.NOT_IN_DOCUMENT);
940 }
941 return this.dom_.getElement(this.makeId(idFragment));
942 };
943
944
945 /**
946 * Adds the specified component as the last child of this component. See
947 * {@link goog.ui.Component#addChildAt} for detailed semantics.
948 *
949 * @see goog.ui.Component#addChildAt
950 * @param {goog.ui.Component} child The new child component.
951 * @param {boolean=} opt_render If true, the child component will be rendered
952 * into the parent.
953 */
954 goog.ui.Component.prototype.addChild = function(child, opt_render) {
955 // TODO(gboyer): addChildAt(child, this.getChildCount(), false) will
956 // reposition any already-rendered child to the end. Instead, perhaps
957 // addChild(child, false) should never reposition the child; instead, clients
958 // that need the repositioning will use addChildAt explicitly. Right now,
959 // clients can get around this by calling addChild before calling decorate.
960 this.addChildAt(child, this.getChildCount(), opt_render);
961 };
962
963
964 /**
965 * Adds the specified component as a child of this component at the given
966 * 0-based index.
967 *
968 * Both {@code addChild} and {@code addChildAt} assume the following contract
969 * between parent and child components:
970 * <ul>
971 * <li>the child component's element must be a descendant of the parent
972 * component's element, and
973 * <li>the DOM state of the child component must be consistent with the DOM
974 * state of the parent component (see {@code isInDocument}) in the
975 * steady state -- the exception is to addChildAt(child, i, false) and
976 * then immediately decorate/render the child.
977 * </ul>
978 *
979 * In particular, {@code parent.addChild(child)} will throw an error if the
980 * child component is already in the document, but the parent isn't.
981 *
982 * Clients of this API may call {@code addChild} and {@code addChildAt} with
983 * {@code opt_render} set to true. If {@code opt_render} is true, calling these
984 * methods will automatically render the child component's element into the
985 * parent component's element. If the parent does not yet have an element, then
986 * {@code createDom} will automatically be invoked on the parent before
987 * rendering the child.
988 *
989 * Invoking {@code parent.addChild(child, true)} will throw an error if the
990 * child component is already in the document, regardless of the parent's DOM
991 * state.
992 *
993 * If {@code opt_render} is true and the parent component is not already
994 * in the document, {@code enterDocument} will not be called on this component
995 * at this point.
996 *
997 * Finally, this method also throws an error if the new child already has a
998 * different parent, or the given index is out of bounds.
999 *
1000 * @see goog.ui.Component#addChild
1001 * @param {goog.ui.Component} child The new child component.
1002 * @param {number} index 0-based index at which the new child component is to be
1003 * added; must be between 0 and the current child count (inclusive).
1004 * @param {boolean=} opt_render If true, the child component will be rendered
1005 * into the parent.
1006 * @return {void} Nada.
1007 */
1008 goog.ui.Component.prototype.addChildAt = function(child, index, opt_render) {
1009 goog.asserts.assert(!!child, 'Provided element must not be null.');
1010
1011 if (child.inDocument_ && (opt_render || !this.inDocument_)) {
1012 // Adding a child that's already in the document is an error, except if the
1013 // parent is also in the document and opt_render is false (e.g. decorate()).
1014 throw new Error(goog.ui.Component.Error.ALREADY_RENDERED);
1015 }
1016
1017 if (index < 0 || index > this.getChildCount()) {
1018 // Allowing sparse child arrays would lead to strange behavior, so we don't.
1019 throw new Error(goog.ui.Component.Error.CHILD_INDEX_OUT_OF_BOUNDS);
1020 }
1021
1022 // Create the index and the child array on first use.
1023 if (!this.childIndex_ || !this.children_) {
1024 this.childIndex_ = {};
1025 this.children_ = [];
1026 }
1027
1028 // Moving child within component, remove old reference.
1029 if (child.getParent() == this) {
1030 goog.object.set(this.childIndex_, child.getId(), child);
1031 goog.array.remove(this.children_, child);
1032
1033 // Add the child to this component. goog.object.add() throws an error if
1034 // a child with the same ID already exists.
1035 } else {
1036 goog.object.add(this.childIndex_, child.getId(), child);
1037 }
1038
1039 // Set the parent of the child to this component. This throws an error if
1040 // the child is already contained by another component.
1041 child.setParent(this);
1042 goog.array.insertAt(this.children_, child, index);
1043
1044 if (child.inDocument_ && this.inDocument_ && child.getParent() == this) {
1045 // Changing the position of an existing child, move the DOM node (if
1046 // necessary).
1047 var contentElement = this.getContentElement();
1048 var insertBeforeElement = contentElement.childNodes[index] || null;
1049 if (insertBeforeElement != child.getElement()) {
1050 contentElement.insertBefore(child.getElement(), insertBeforeElement);
1051 }
1052 } else if (opt_render) {
1053 // If this (parent) component doesn't have a DOM yet, call createDom now
1054 // to make sure we render the child component's element into the correct
1055 // parent element (otherwise render_ with a null first argument would
1056 // render the child into the document body, which is almost certainly not
1057 // what we want).
1058 if (!this.element_) {
1059 this.createDom();
1060 }
1061 // Render the child into the parent at the appropriate location. Note that
1062 // getChildAt(index + 1) returns undefined if inserting at the end.
1063 // TODO(attila): We should have a renderer with a renderChildAt API.
1064 var sibling = this.getChildAt(index + 1);
1065 // render_() calls enterDocument() if the parent is already in the document.
1066 child.render_(this.getContentElement(), sibling ? sibling.element_ : null);
1067 } else if (
1068 this.inDocument_ && !child.inDocument_ && child.element_ &&
1069 child.element_.parentNode &&
1070 // Under some circumstances, IE8 implicitly creates a Document Fragment
1071 // for detached nodes, so ensure the parent is an Element as it should be.
1072 child.element_.parentNode.nodeType == goog.dom.NodeType.ELEMENT) {
1073 // We don't touch the DOM, but if the parent is in the document, and the
1074 // child element is in the document but not marked as such, then we call
1075 // enterDocument on the child.
1076 // TODO(gboyer): It would be nice to move this condition entirely, but
1077 // there's a large risk of breaking existing applications that manually
1078 // append the child to the DOM and then call addChild.
1079 child.enterDocument();
1080 }
1081 };
1082
1083
1084 /**
1085 * Returns the DOM element into which child components are to be rendered,
1086 * or null if the component itself hasn't been rendered yet. This default
1087 * implementation returns the component's root element. Subclasses with
1088 * complex DOM structures must override this method.
1089 * @return {Element} Element to contain child elements (null if none).
1090 */
1091 goog.ui.Component.prototype.getContentElement = function() {
1092 return this.element_;
1093 };
1094
1095
1096 /**
1097 * Returns true if the component is rendered right-to-left, false otherwise.
1098 * The first time this function is invoked, the right-to-left rendering property
1099 * is set if it has not been already.
1100 * @return {boolean} Whether the control is rendered right-to-left.
1101 */
1102 goog.ui.Component.prototype.isRightToLeft = function() {
1103 if (this.rightToLeft_ == null) {
1104 this.rightToLeft_ = goog.style.isRightToLeft(
1105 this.inDocument_ ? this.element_ : this.dom_.getDocument().body);
1106 }
1107 return this.rightToLeft_;
1108 };
1109
1110
1111 /**
1112 * Set is right-to-left. This function should be used if the component needs
1113 * to know the rendering direction during dom creation (i.e. before
1114 * {@link #enterDocument} is called and is right-to-left is set).
1115 * @param {boolean} rightToLeft Whether the component is rendered
1116 * right-to-left.
1117 */
1118 goog.ui.Component.prototype.setRightToLeft = function(rightToLeft) {
1119 if (this.inDocument_) {
1120 throw new Error(goog.ui.Component.Error.ALREADY_RENDERED);
1121 }
1122 this.rightToLeft_ = rightToLeft;
1123 };
1124
1125
1126 /**
1127 * Returns true if the component has children.
1128 * @return {boolean} True if the component has children.
1129 */
1130 goog.ui.Component.prototype.hasChildren = function() {
1131 return !!this.children_ && this.children_.length != 0;
1132 };
1133
1134
1135 /**
1136 * Returns the number of children of this component.
1137 * @return {number} The number of children.
1138 */
1139 goog.ui.Component.prototype.getChildCount = function() {
1140 return this.children_ ? this.children_.length : 0;
1141 };
1142
1143
1144 /**
1145 * Returns an array containing the IDs of the children of this component, or an
1146 * empty array if the component has no children.
1147 * @return {!Array<string>} Child component IDs.
1148 */
1149 goog.ui.Component.prototype.getChildIds = function() {
1150 var ids = [];
1151
1152 // We don't use goog.object.getKeys(this.childIndex_) because we want to
1153 // return the IDs in the correct order as determined by this.children_.
1154 this.forEachChild(function(child) {
1155 // addChild()/addChildAt() guarantee that the child array isn't sparse.
1156 ids.push(child.getId());
1157 });
1158
1159 return ids;
1160 };
1161
1162
1163 /**
1164 * Returns the child with the given ID, or null if no such child exists.
1165 * @param {string} id Child component ID.
1166 * @return {goog.ui.Component?} The child with the given ID; null if none.
1167 */
1168 goog.ui.Component.prototype.getChild = function(id) {
1169 // Use childIndex_ for O(1) access by ID.
1170 return (this.childIndex_ && id) ?
1171 /** @type {goog.ui.Component} */ (
1172 goog.object.get(this.childIndex_, id)) ||
1173 null :
1174 null;
1175 };
1176
1177
1178 /**
1179 * Returns the child at the given index, or null if the index is out of bounds.
1180 * @param {number} index 0-based index.
1181 * @return {goog.ui.Component?} The child at the given index; null if none.
1182 */
1183 goog.ui.Component.prototype.getChildAt = function(index) {
1184 // Use children_ for access by index.
1185 return this.children_ ? this.children_[index] || null : null;
1186 };
1187
1188
1189 /**
1190 * Calls the given function on each of this component's children in order. If
1191 * {@code opt_obj} is provided, it will be used as the 'this' object in the
1192 * function when called. The function should take two arguments: the child
1193 * component and its 0-based index. The return value is ignored.
1194 * @param {function(this:T,?,number):?} f The function to call for every
1195 * child component; should take 2 arguments (the child and its index).
1196 * @param {T=} opt_obj Used as the 'this' object in f when called.
1197 * @template T
1198 */
1199 goog.ui.Component.prototype.forEachChild = function(f, opt_obj) {
1200 if (this.children_) {
1201 goog.array.forEach(this.children_, f, opt_obj);
1202 }
1203 };
1204
1205
1206 /**
1207 * Returns the 0-based index of the given child component, or -1 if no such
1208 * child is found.
1209 * @param {goog.ui.Component?} child The child component.
1210 * @return {number} 0-based index of the child component; -1 if not found.
1211 */
1212 goog.ui.Component.prototype.indexOfChild = function(child) {
1213 return (this.children_ && child) ? goog.array.indexOf(this.children_, child) :
1214 -1;
1215 };
1216
1217
1218 /**
1219 * Removes the given child from this component, and returns it. Throws an error
1220 * if the argument is invalid or if the specified child isn't found in the
1221 * parent component. The argument can either be a string (interpreted as the
1222 * ID of the child component to remove) or the child component itself.
1223 *
1224 * If {@code opt_unrender} is true, calls {@link goog.ui.component#exitDocument}
1225 * on the removed child, and subsequently detaches the child's DOM from the
1226 * document. Otherwise it is the caller's responsibility to clean up the child
1227 * component's DOM.
1228 *
1229 * @see goog.ui.Component#removeChildAt
1230 * @param {string|goog.ui.Component|null} child The ID of the child to remove,
1231 * or the child component itself.
1232 * @param {boolean=} opt_unrender If true, calls {@code exitDocument} on the
1233 * removed child component, and detaches its DOM from the document.
1234 * @return {goog.ui.Component} The removed component, if any.
1235 */
1236 goog.ui.Component.prototype.removeChild = function(child, opt_unrender) {
1237 if (child) {
1238 // Normalize child to be the object and id to be the ID string. This also
1239 // ensures that the child is really ours.
1240 var id = goog.isString(child) ? child : child.getId();
1241 child = this.getChild(id);
1242
1243 if (id && child) {
1244 goog.object.remove(this.childIndex_, id);
1245 goog.array.remove(this.children_, child);
1246
1247 if (opt_unrender) {
1248 // Remove the child component's DOM from the document. We have to call
1249 // exitDocument first (see documentation).
1250 child.exitDocument();
1251 if (child.element_) {
1252 goog.dom.removeNode(child.element_);
1253 }
1254 }
1255
1256 // Child's parent must be set to null after exitDocument is called
1257 // so that the child can unlisten to its parent if required.
1258 child.setParent(null);
1259 }
1260 }
1261
1262 if (!child) {
1263 throw new Error(goog.ui.Component.Error.NOT_OUR_CHILD);
1264 }
1265
1266 return /** @type {!goog.ui.Component} */ (child);
1267 };
1268
1269
1270 /**
1271 * Removes the child at the given index from this component, and returns it.
1272 * Throws an error if the argument is out of bounds, or if the specified child
1273 * isn't found in the parent. See {@link goog.ui.Component#removeChild} for
1274 * detailed semantics.
1275 *
1276 * @see goog.ui.Component#removeChild
1277 * @param {number} index 0-based index of the child to remove.
1278 * @param {boolean=} opt_unrender If true, calls {@code exitDocument} on the
1279 * removed child component, and detaches its DOM from the document.
1280 * @return {goog.ui.Component} The removed component, if any.
1281 */
1282 goog.ui.Component.prototype.removeChildAt = function(index, opt_unrender) {
1283 // removeChild(null) will throw error.
1284 return this.removeChild(this.getChildAt(index), opt_unrender);
1285 };
1286
1287
1288 /**
1289 * Removes every child component attached to this one and returns them.
1290 *
1291 * @see goog.ui.Component#removeChild
1292 * @param {boolean=} opt_unrender If true, calls {@link #exitDocument} on the
1293 * removed child components, and detaches their DOM from the document.
1294 * @return {!Array<goog.ui.Component>} The removed components if any.
1295 */
1296 goog.ui.Component.prototype.removeChildren = function(opt_unrender) {
1297 var removedChildren = [];
1298 while (this.hasChildren()) {
1299 removedChildren.push(this.removeChildAt(0, opt_unrender));
1300 }
1301 return removedChildren;
1302 };