Debian Codegraph @

closure-library/closure/goog/ui/palette.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 A palette control. A palette is a grid that the user can
17 * highlight or select via the keyboard or the mouse.
18 *
19 * @author [email protected] (Attila Bodis)
20 * @see ../demos/palette.html
21 */
22
23 goog.provide('goog.ui.Palette');
24
25 goog.require('goog.array');
26 goog.require('goog.dom');
27 goog.require('goog.events');
28 goog.require('goog.events.EventType');
29 goog.require('goog.events.KeyCodes');
30 goog.require('goog.math.Size');
31 goog.require('goog.ui.Component');
32 goog.require('goog.ui.Control');
33 goog.require('goog.ui.PaletteRenderer');
34 goog.require('goog.ui.SelectionModel');
35
36
37
38 /**
39 * A palette is a grid of DOM nodes that the user can highlight or select via
40 * the keyboard or the mouse. The selection state of the palette is controlled
41 * an ACTION event. Event listeners may retrieve the selected item using the
42 * {@link #getSelectedItem} or {@link #getSelectedIndex} method.
43 *
44 * Use this class as the base for components like color palettes or emoticon
45 * pickers. Use {@link #setContent} to set/change the items in the palette
46 * after construction. See palette.html demo for example usage.
47 *
48 * @param {Array<Node>} items Array of DOM nodes to be displayed as items
49 * in the palette grid (limited to one per cell).
50 * @param {goog.ui.PaletteRenderer=} opt_renderer Renderer used to render or
51 * decorate the palette; defaults to {@link goog.ui.PaletteRenderer}.
52 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
53 * document interaction.
54 * @constructor
55 * @extends {goog.ui.Control}
56 */
57 goog.ui.Palette = function(items, opt_renderer, opt_domHelper) {
58 goog.ui.Palette.base(
59 this, 'constructor', items,
60 opt_renderer || goog.ui.PaletteRenderer.getInstance(), opt_domHelper);
61 this.setAutoStates(
62 goog.ui.Component.State.CHECKED | goog.ui.Component.State.SELECTED |
63 goog.ui.Component.State.OPENED,
64 false);
65
66 /**
67 * A fake component for dispatching events on palette cell changes.
68 * @type {!goog.ui.Palette.CurrentCell_}
69 * @private
70 */
71 this.currentCellControl_ = new goog.ui.Palette.CurrentCell_();
72 this.currentCellControl_.setParentEventTarget(this);
73
74 /**
75 * @private {number} The last highlighted index, or -1 if it never had one.
76 */
77 this.lastHighlightedIndex_ = -1;
78 };
79 goog.inherits(goog.ui.Palette, goog.ui.Control);
80 goog.tagUnsealableClass(goog.ui.Palette);
81
82
83 /**
84 * Events fired by the palette object
85 * @enum {string}
86 */
87 goog.ui.Palette.EventType = {
88 AFTER_HIGHLIGHT: goog.events.getUniqueId('afterhighlight')
89 };
90
91
92 /**
93 * Palette dimensions (columns x rows). If the number of rows is undefined,
94 * it is calculated on first use.
95 * @type {goog.math.Size}
96 * @private
97 */
98 goog.ui.Palette.prototype.size_ = null;
99
100
101 /**
102 * Index of the currently highlighted item (-1 if none).
103 * @type {number}
104 * @private
105 */
106 goog.ui.Palette.prototype.highlightedIndex_ = -1;
107
108
109 /**
110 * Selection model controlling the palette's selection state.
111 * @type {goog.ui.SelectionModel}
112 * @private
113 */
114 goog.ui.Palette.prototype.selectionModel_ = null;
115
116
117 // goog.ui.Component / goog.ui.Control implementation.
118
119
120 /** @override */
121 goog.ui.Palette.prototype.disposeInternal = function() {
122 goog.ui.Palette.superClass_.disposeInternal.call(this);
123
124 if (this.selectionModel_) {
125 this.selectionModel_.dispose();
126 this.selectionModel_ = null;
127 }
128
129 this.size_ = null;
130
131 this.currentCellControl_.dispose();
132 };
133
134
135 /**
136 * Overrides {@link goog.ui.Control#setContentInternal} by also updating the
137 * grid size and the selection model. Considered protected.
138 * @param {goog.ui.ControlContent} content Array of DOM nodes to be displayed
139 * as items in the palette grid (one item per cell).
140 * @protected
141 * @override
142 */
143 goog.ui.Palette.prototype.setContentInternal = function(content) {
144 var items = /** @type {Array<Node>} */ (content);
145 goog.ui.Palette.superClass_.setContentInternal.call(this, items);
146
147 // Adjust the palette size.
148 this.adjustSize_();
149
150 // Add the items to the selection model, replacing previous items (if any).
151 if (this.selectionModel_) {
152 // We already have a selection model; just replace the items.
153 this.selectionModel_.clear();
154 this.selectionModel_.addItems(items);
155 } else {
156 // Create a selection model, initialize the items, and hook up handlers.
157 this.selectionModel_ = new goog.ui.SelectionModel(items);
158 this.selectionModel_.setSelectionHandler(goog.bind(this.selectItem_, this));
159 this.getHandler().listen(
160 this.selectionModel_, goog.events.EventType.SELECT,
161 this.handleSelectionChange);
162 }
163
164 // In all cases, clear the highlight.
165 this.highlightedIndex_ = -1;
166 };
167
168
169 /**
170 * Overrides {@link goog.ui.Control#getCaption} to return the empty string,
171 * since palettes don't have text captions.
172 * @return {string} The empty string.
173 * @override
174 */
175 goog.ui.Palette.prototype.getCaption = function() {
176 return '';
177 };
178
179
180 /**
181 * Overrides {@link goog.ui.Control#setCaption} to be a no-op, since palettes
182 * don't have text captions.
183 * @param {string} caption Ignored.
184 * @override
185 */
186 goog.ui.Palette.prototype.setCaption = function(caption) {
187 // Do nothing.
188 };
189
190
191 // Palette event handling.
192
193
194 /**
195 * Handles mouseover events. Overrides {@link goog.ui.Control#handleMouseOver}
196 * by determining which palette item (if any) was moused over, highlighting it,
197 * and un-highlighting any previously-highlighted item.
198 * @param {goog.events.BrowserEvent} e Mouse event to handle.
199 * @override
200 */
201 goog.ui.Palette.prototype.handleMouseOver = function(e) {
202 goog.ui.Palette.superClass_.handleMouseOver.call(this, e);
203
204 var item = this.getRenderer().getContainingItem(this, e.target);
205 if (item && e.relatedTarget && goog.dom.contains(item, e.relatedTarget)) {
206 // Ignore internal mouse moves.
207 return;
208 }
209
210 if (item != this.getHighlightedItem()) {
211 this.setHighlightedItem(item);
212 }
213 };
214
215
216 /**
217 * Handles mousedown events. Overrides {@link goog.ui.Control#handleMouseDown}
218 * by ensuring that the item on which the user moused down is highlighted.
219 * @param {goog.events.Event} e Mouse event to handle.
220 * @override
221 */
222 goog.ui.Palette.prototype.handleMouseDown = function(e) {
223 goog.ui.Palette.superClass_.handleMouseDown.call(this, e);
224
225 if (this.isActive()) {
226 // Make sure we move the highlight to the cell on which the user moused
227 // down.
228 var item = this.getRenderer().getContainingItem(this, e.target);
229 if (item != this.getHighlightedItem()) {
230 this.setHighlightedItem(item);
231 }
232 }
233 };
234
235
236 /**
237 * Selects the currently highlighted palette item (triggered by mouseup or by
238 * keyboard action). Overrides {@link goog.ui.Control#performActionInternal}
239 * by selecting the highlighted item and dispatching an ACTION event.
240 * @param {goog.events.Event} e Mouse or key event that triggered the action.
241 * @return {boolean} True if the action was allowed to proceed, false otherwise.
242 * @override
243 */
244 goog.ui.Palette.prototype.performActionInternal = function(e) {
245 var highlightedItem = this.getHighlightedItem();
246 if (highlightedItem) {
247 if (e && this.shouldSelectHighlightedItem_(e)) {
248 this.setSelectedItem(highlightedItem);
249 }
250 return goog.ui.Palette.base(this, 'performActionInternal', e);
251 }
252 return false;
253 };
254
255
256 /**
257 * Determines whether to select the highlighted item while handling an internal
258 * action. The highlighted item should not be selected if the action is a mouse
259 * event occurring outside the palette or in an "empty" cell.
260 * @param {!goog.events.Event} e Mouseup or key event being handled.
261 * @return {boolean} True if the highlighted item should be selected.
262 * @private
263 */
264 goog.ui.Palette.prototype.shouldSelectHighlightedItem_ = function(e) {
265 if (!this.getSelectedItem()) {
266 // It's always ok to select when nothing is selected yet.
267 return true;
268 } else if (e.type != 'mouseup') {
269 // Keyboard can only act on valid cells.
270 return true;
271 } else {
272 // Return whether or not the mouse action was in the palette.
273 return !!this.getRenderer().getContainingItem(this, e.target);
274 }
275 };
276
277
278 /**
279 * Handles keyboard events dispatched while the palette has focus. Moves the
280 * highlight on arrow keys, and selects the highlighted item on Enter or Space.
281 * Returns true if the event was handled, false otherwise. In particular, if
282 * the user attempts to navigate out of the grid, the highlight isn't changed,
283 * and this method returns false; it is then up to the parent component to
284 * handle the event (e.g. by wrapping the highlight around). Overrides {@link
285 * goog.ui.Control#handleKeyEvent}.
286 * @param {goog.events.KeyEvent} e Key event to handle.
287 * @return {boolean} True iff the key event was handled by the component.
288 * @override
289 */
290 goog.ui.Palette.prototype.handleKeyEvent = function(e) {
291 var items = this.getContent();
292 var numItems = items ? items.length : 0;
293 var numColumns = this.size_.width;
294
295 // If the component is disabled or the palette is empty, bail.
296 if (numItems == 0 || !this.isEnabled()) {
297 return false;
298 }
299
300 // User hit ENTER or SPACE; trigger action.
301 if (e.keyCode == goog.events.KeyCodes.ENTER ||
302 e.keyCode == goog.events.KeyCodes.SPACE) {
303 return this.performActionInternal(e);
304 }
305
306 // User hit HOME or END; move highlight.
307 if (e.keyCode == goog.events.KeyCodes.HOME) {
308 this.setHighlightedIndex(0);
309 return true;
310 } else if (e.keyCode == goog.events.KeyCodes.END) {
311 this.setHighlightedIndex(numItems - 1);
312 return true;
313 }
314
315 // If nothing is highlighted, start from the selected index. If nothing is
316 // selected either, highlightedIndex is -1.
317 var highlightedIndex = this.highlightedIndex_ < 0 ? this.getSelectedIndex() :
318 this.highlightedIndex_;
319
320 switch (e.keyCode) {
321 case goog.events.KeyCodes.LEFT:
322 // If the highlighted index is uninitialized, or is at the beginning, move
323 // it to the end.
324 if (highlightedIndex == -1 || highlightedIndex == 0) {
325 highlightedIndex = numItems;
326 }
327 this.setHighlightedIndex(highlightedIndex - 1);
328 e.preventDefault();
329 return true;
330 break;
331
332 case goog.events.KeyCodes.RIGHT:
333 // If the highlighted index at the end, move it to the beginning.
334 if (highlightedIndex == numItems - 1) {
335 highlightedIndex = -1;
336 }
337 this.setHighlightedIndex(highlightedIndex + 1);
338 e.preventDefault();
339 return true;
340 break;
341
342 case goog.events.KeyCodes.UP:
343 if (highlightedIndex == -1) {
344 highlightedIndex = numItems + numColumns - 1;
345 }
346 if (highlightedIndex >= numColumns) {
347 this.setHighlightedIndex(highlightedIndex - numColumns);
348 e.preventDefault();
349 return true;
350 }
351 break;
352
353 case goog.events.KeyCodes.DOWN:
354 if (highlightedIndex == -1) {
355 highlightedIndex = -numColumns;
356 }
357 if (highlightedIndex < numItems - numColumns) {
358 this.setHighlightedIndex(highlightedIndex + numColumns);
359 e.preventDefault();
360 return true;
361 }
362 break;
363 }
364
365 return false;
366 };
367
368
369 /**
370 * Handles selection change events dispatched by the selection model.
371 * @param {goog.events.Event} e Selection event to handle.
372 */
373 goog.ui.Palette.prototype.handleSelectionChange = function(e) {
374 // No-op in the base class.
375 };
376
377
378 // Palette management.
379
380
381 /**
382 * Returns the size of the palette grid.
383 * @return {goog.math.Size} Palette size (columns x rows).
384 */
385 goog.ui.Palette.prototype.getSize = function() {
386 return this.size_;
387 };
388
389
390 /**
391 * Sets the size of the palette grid to the given size. Callers can either
392 * pass a single {@link goog.math.Size} or a pair of numbers (first the number
393 * of columns, then the number of rows) to this method. In both cases, the
394 * number of rows is optional and will be calculated automatically if needed.
395 * It is an error to attempt to change the size of the palette after it has
396 * been rendered.
397 * @param {goog.math.Size|number} size Either a size object or the number of
398 * columns.
399 * @param {number=} opt_rows The number of rows (optional).
400 */
401 goog.ui.Palette.prototype.setSize = function(size, opt_rows) {
402 if (this.getElement()) {
403 throw new Error(goog.ui.Component.Error.ALREADY_RENDERED);
404 }
405
406 this.size_ = goog.isNumber(size) ?
407 new goog.math.Size(size, /** @type {number} */ (opt_rows)) :
408 size;
409
410 // Adjust size, if needed.
411 this.adjustSize_();
412 };
413
414
415 /**
416 * Returns the 0-based index of the currently highlighted palette item, or -1
417 * if no item is highlighted.
418 * @return {number} Index of the highlighted item (-1 if none).
419 */
420 goog.ui.Palette.prototype.getHighlightedIndex = function() {
421 return this.highlightedIndex_;
422 };
423
424
425 /**
426 * Returns the currently highlighted palette item, or null if no item is
427 * highlighted.
428 * @return {Node} The highlighted item (undefined if none).
429 */
430 goog.ui.Palette.prototype.getHighlightedItem = function() {
431 var items = this.getContent();
432 return items && items[this.highlightedIndex_];
433 };
434
435
436 /**
437 * @return {Element} The highlighted cell.
438 * @private
439 */
440 goog.ui.Palette.prototype.getHighlightedCellElement_ = function() {
441 return this.getRenderer().getCellForItem(this.getHighlightedItem());
442 };
443
444
445 /**
446 * Highlights the item at the given 0-based index, or removes the highlight
447 * if the argument is -1 or out of range. Any previously-highlighted item
448 * will be un-highlighted.
449 * @param {number} index 0-based index of the item to highlight.
450 */
451 goog.ui.Palette.prototype.setHighlightedIndex = function(index) {
452 if (index != this.highlightedIndex_) {
453 this.highlightIndex_(this.highlightedIndex_, false);
454 this.lastHighlightedIndex_ = this.highlightedIndex_;
455 this.highlightedIndex_ = index;
456 this.highlightIndex_(index, true);
457 this.dispatchEvent(goog.ui.Palette.EventType.AFTER_HIGHLIGHT);
458 }
459 };
460
461
462 /**
463 * Highlights the given item, or removes the highlight if the argument is null
464 * or invalid. Any previously-highlighted item will be un-highlighted.
465 * @param {Node|undefined} item Item to highlight.
466 */
467 goog.ui.Palette.prototype.setHighlightedItem = function(item) {
468 var items = /** @type {Array<Node>} */ (this.getContent());
469 this.setHighlightedIndex(
470 (items && item) ? goog.array.indexOf(items, item) : -1);
471 };
472
473
474 /**
475 * Returns the 0-based index of the currently selected palette item, or -1
476 * if no item is selected.
477 * @return {number} Index of the selected item (-1 if none).
478 */
479 goog.ui.Palette.prototype.getSelectedIndex = function() {
480 return this.selectionModel_ ? this.selectionModel_.getSelectedIndex() : -1;
481 };
482
483
484 /**
485 * Returns the currently selected palette item, or null if no item is selected.
486 * @return {Node} The selected item (null if none).
487 */
488 goog.ui.Palette.prototype.getSelectedItem = function() {
489 return this.selectionModel_ ?
490 /** @type {Node} */ (this.selectionModel_.getSelectedItem()) :
491 null;
492 };
493
494
495 /**
496 * Selects the item at the given 0-based index, or clears the selection
497 * if the argument is -1 or out of range. Any previously-selected item
498 * will be deselected.
499 * @param {number} index 0-based index of the item to select.
500 */
501 goog.ui.Palette.prototype.setSelectedIndex = function(index) {
502 if (this.selectionModel_) {
503 this.selectionModel_.setSelectedIndex(index);
504 }
505 };
506
507
508 /**
509 * Selects the given item, or clears the selection if the argument is null or
510 * invalid. Any previously-selected item will be deselected.
511 * @param {Node} item Item to select.
512 */
513 goog.ui.Palette.prototype.setSelectedItem = function(item) {
514 if (this.selectionModel_) {
515 this.selectionModel_.setSelectedItem(item);
516 }
517 };
518
519
520 /**
521 * Private helper; highlights or un-highlights the item at the given index
522 * based on the value of the Boolean argument. This implementation simply
523 * applies highlight styling to the cell containing the item to be highighted.
524 * Does nothing if the palette hasn't been rendered yet.
525 * @param {number} index 0-based index of item to highlight or un-highlight.
526 * @param {boolean} highlight If true, the item is highlighted; otherwise it
527 * is un-highlighted.
528 * @private
529 */
530 goog.ui.Palette.prototype.highlightIndex_ = function(index, highlight) {
531 if (this.getElement()) {
532 var items = this.getContent();
533 if (items && index >= 0 && index < items.length) {
534 var cellEl = this.getHighlightedCellElement_();
535 if (this.currentCellControl_.getElement() != cellEl) {
536 this.currentCellControl_.setElementInternal(cellEl);
537 }
538 if (this.currentCellControl_.tryHighlight(highlight)) {
539 this.getRenderer().highlightCell(this, items[index], highlight);
540 }
541 }
542 }
543 };
544
545
546 /** @override */
547 goog.ui.Palette.prototype.setHighlighted = function(highlight) {
548 if (highlight && this.highlightedIndex_ == -1) {
549 // If there was a last highlighted index, use that. Otherwise, highlight the
550 // first cell.
551 this.setHighlightedIndex(
552 this.lastHighlightedIndex_ > -1 ? this.lastHighlightedIndex_ : 0);
553 } else if (!highlight) {
554 this.setHighlightedIndex(-1);
555 }
556 // The highlight event should be fired once the component has updated its own
557 // state.
558 goog.ui.Palette.base(this, 'setHighlighted', highlight);
559 };
560
561
562 /**
563 * Private helper; selects or deselects the given item based on the value of
564 * the Boolean argument. This implementation simply applies selection styling
565 * to the cell containing the item to be selected. Does nothing if the palette
566 * hasn't been rendered yet.
567 * @param {Node} item Item to select or deselect.
568 * @param {boolean} select If true, the item is selected; otherwise it is
569 * deselected.
570 * @private
571 */
572 goog.ui.Palette.prototype.selectItem_ = function(item, select) {
573 if (this.getElement()) {
574 this.getRenderer().selectCell(this, item, select);
575 }
576 };
577
578
579 /**
580 * Calculates and updates the size of the palette based on any preset values
581 * and the number of palette items. If there is no preset size, sets the
582 * palette size to the smallest square big enough to contain all items. If
583 * there is a preset number of columns, increases the number of rows to hold
584 * all items if needed. (If there are too many rows, does nothing.)
585 * @private
586 */
587 goog.ui.Palette.prototype.adjustSize_ = function() {
588 var items = this.getContent();
589 if (items) {
590 if (this.size_ && this.size_.width) {
591 // There is already a size set; honor the number of columns (if >0), but
592 // increase the number of rows if needed.
593 var minRows = Math.ceil(items.length / this.size_.width);
594 if (!goog.isNumber(this.size_.height) || this.size_.height < minRows) {
595 this.size_.height = minRows;
596 }
597 } else {
598 // No size has been set; size the grid to the smallest square big enough
599 // to hold all items (hey, why not?).
600 var length = Math.ceil(Math.sqrt(items.length));
601 this.size_ = new goog.math.Size(length, length);
602 }
603 } else {
604 // No items; set size to 0x0.
605 this.size_ = new goog.math.Size(0, 0);
606 }
607 };
608
609
610
611 /**
612 * A component to represent the currently highlighted cell.
613 * @constructor
614 * @extends {goog.ui.Control}
615 * @private
616 */
617 goog.ui.Palette.CurrentCell_ = function() {
618 goog.ui.Palette.CurrentCell_.base(this, 'constructor', null);
619 this.setDispatchTransitionEvents(goog.ui.Component.State.HOVER, true);
620 };
621 goog.inherits(goog.ui.Palette.CurrentCell_, goog.ui.Control);
622
623
624 /**
625 * @param {boolean} highlight Whether to highlight or unhighlight the component.
626 * @return {boolean} Whether it was successful.
627 */
628 goog.ui.Palette.CurrentCell_.prototype.tryHighlight = function(highlight) {
629 this.setHighlighted(highlight);
630 return this.isHighlighted() == highlight;
631 };