Debian Codegraph @

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

raw
1 // Copyright 2006 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 base ratings widget that allows the user to select a rating,
17 * like "star video" in Google Video. This fires a "change" event when the user
18 * selects a rating.
19 *
20 * Keyboard:
21 * ESC = Clear (if supported)
22 * Home = 1 star
23 * End = Full rating
24 * Left arrow = Decrease rating
25 * Right arrow = Increase rating
26 * 0 = Clear (if supported)
27 * 1 - 9 = nth star
28 *
29 * @see ../demos/ratings.html
30 */
31
32 goog.provide('goog.ui.Ratings');
33 goog.provide('goog.ui.Ratings.EventType');
34
35 goog.require('goog.a11y.aria');
36 goog.require('goog.a11y.aria.Role');
37 goog.require('goog.a11y.aria.State');
38 goog.require('goog.asserts');
39 goog.require('goog.dom');
40 goog.require('goog.dom.TagName');
41 goog.require('goog.dom.classlist');
42 goog.require('goog.events.EventType');
43 goog.require('goog.ui.Component');
44
45
46
47 /**
48 * A UI Control used for rating things, i.e. videos on Google Video.
49 * @param {Array<string>=} opt_ratings Ratings. Default: [1,2,3,4,5].
50 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
51 * @constructor
52 * @extends {goog.ui.Component}
53 */
54 goog.ui.Ratings = function(opt_ratings, opt_domHelper) {
55 goog.ui.Component.call(this, opt_domHelper);
56
57 /**
58 * Ordered ratings that can be picked, Default: [1,2,3,4,5]
59 * @type {Array<string>}
60 * @private
61 */
62 this.ratings_ = opt_ratings || ['1', '2', '3', '4', '5'];
63
64 /**
65 * Array containing references to the star elements
66 * @type {Array<Element>}
67 * @private
68 */
69 this.stars_ = [];
70
71
72 // Awkward name because the obvious name is taken by subclasses already.
73 /**
74 * Whether the control is enabled.
75 * @type {boolean}
76 * @private
77 */
78 this.isEnabled_ = true;
79
80
81 /**
82 * The last index to be highlighted
83 * @type {number}
84 * @private
85 */
86 this.highlightedIndex_ = -1;
87
88
89 /**
90 * The currently selected index
91 * @type {number}
92 * @private
93 */
94 this.selectedIndex_ = -1;
95
96
97 /**
98 * An attached form field to set the value to
99 * @type {HTMLInputElement|HTMLSelectElement|null}
100 * @private
101 */
102 this.attachedFormField_ = null;
103 };
104 goog.inherits(goog.ui.Ratings, goog.ui.Component);
105 goog.tagUnsealableClass(goog.ui.Ratings);
106
107
108 /**
109 * Default CSS class to be applied to the root element of components rendered
110 * by this renderer.
111 * @type {string}
112 */
113 goog.ui.Ratings.CSS_CLASS = goog.getCssName('goog-ratings');
114
115
116 /**
117 * Enums for Ratings event type.
118 * @enum {string}
119 */
120 goog.ui.Ratings.EventType = {
121 CHANGE: 'change',
122 HIGHLIGHT_CHANGE: 'highlightchange',
123 HIGHLIGHT: 'highlight',
124 UNHIGHLIGHT: 'unhighlight'
125 };
126
127
128 /**
129 * Decorate a HTML structure already in the document. Expects the structure:
130 * <pre>
131 * - div
132 * - select
133 * - option 1 #text = 1 star
134 * - option 2 #text = 2 stars
135 * - option 3 #text = 3 stars
136 * - option N (where N is max number of ratings)
137 * </pre>
138 *
139 * The div can contain other elements for graceful degredation, but they will be
140 * hidden when the decoration occurs.
141 *
142 * @param {Element} el Div element to decorate.
143 * @override
144 */
145 goog.ui.Ratings.prototype.decorateInternal = function(el) {
146 var select = goog.dom.getElementsByTagName(
147 goog.dom.TagName.SELECT, goog.asserts.assert(el))[0];
148 if (!select) {
149 throw new Error(
150 'Can not decorate ' + el + ', with Ratings. Must ' +
151 'contain select box');
152 }
153 this.ratings_.length = 0;
154 for (var i = 0, n = select.options.length; i < n; i++) {
155 var option = select.options[i];
156 this.ratings_.push(option.text);
157 }
158 this.setSelectedIndex(select.selectedIndex);
159 select.style.display = 'none';
160 this.attachedFormField_ = /** @type {HTMLSelectElement} */ (select);
161 this.createDom();
162 el.insertBefore(this.getElement(), select);
163 };
164
165
166 /**
167 * Render the rating widget inside the provided element. This will override the
168 * current content of the element.
169 * @override
170 */
171 goog.ui.Ratings.prototype.enterDocument = function() {
172 var el = this.getElement();
173 goog.asserts.assert(el, 'The DOM element for ratings cannot be null.');
174 goog.ui.Ratings.base(this, 'enterDocument');
175 el.tabIndex = 0;
176 goog.dom.classlist.add(el, this.getCssClass());
177 goog.a11y.aria.setRole(el, goog.a11y.aria.Role.SLIDER);
178 goog.a11y.aria.setState(el, goog.a11y.aria.State.VALUEMIN, 0);
179 var max = this.ratings_.length - 1;
180 goog.a11y.aria.setState(el, goog.a11y.aria.State.VALUEMAX, max);
181 var handler = this.getHandler();
182 handler.listen(el, 'keydown', this.onKeyDown_);
183
184 // Create the elements for the stars
185 for (var i = 0; i < this.ratings_.length; i++) {
186 var star = this.getDomHelper().createDom(goog.dom.TagName.SPAN, {
187 'title': this.ratings_[i],
188 'class': this.getClassName_(i, false),
189 'index': i
190 });
191 this.stars_.push(star);
192 el.appendChild(star);
193 }
194
195 handler.listen(el, goog.events.EventType.CLICK, this.onClick_);
196 handler.listen(el, goog.events.EventType.MOUSEOUT, this.onMouseOut_);
197 handler.listen(el, goog.events.EventType.MOUSEOVER, this.onMouseOver_);
198
199 this.highlightIndex_(this.selectedIndex_);
200 };
201
202
203 /**
204 * Should be called when the widget is removed from the document but may be
205 * reused. This removes all the listeners the widget has attached and destroys
206 * the DOM nodes it uses.
207 * @override
208 */
209 goog.ui.Ratings.prototype.exitDocument = function() {
210 goog.ui.Ratings.superClass_.exitDocument.call(this);
211 for (var i = 0; i < this.stars_.length; i++) {
212 this.getDomHelper().removeNode(this.stars_[i]);
213 }
214 this.stars_.length = 0;
215 };
216
217
218 /** @override */
219 goog.ui.Ratings.prototype.disposeInternal = function() {
220 goog.ui.Ratings.superClass_.disposeInternal.call(this);
221 this.ratings_.length = 0;
222 };
223
224
225 /**
226 * Returns the base CSS class used by subcomponents of this component.
227 * @return {string} Component-specific CSS class.
228 */
229 goog.ui.Ratings.prototype.getCssClass = function() {
230 return goog.ui.Ratings.CSS_CLASS;
231 };
232
233
234 /**
235 * Sets the selected index. If the provided index is greater than the number of
236 * ratings then the max is set. 0 is the first item, -1 is no selection.
237 * @param {number} index The index of the rating to select.
238 */
239 goog.ui.Ratings.prototype.setSelectedIndex = function(index) {
240 index = Math.max(-1, Math.min(index, this.ratings_.length - 1));
241 if (index != this.selectedIndex_) {
242 this.selectedIndex_ = index;
243 this.highlightIndex_(this.selectedIndex_);
244 if (this.attachedFormField_) {
245 if (this.attachedFormField_.tagName == goog.dom.TagName.SELECT) {
246 this.attachedFormField_.selectedIndex = index;
247 } else {
248 this.attachedFormField_.value =
249 /** @type {string} */ (this.getValue());
250 }
251 var ratingsElement = this.getElement();
252 goog.asserts.assert(
253 ratingsElement, 'The DOM ratings element cannot be null.');
254 goog.a11y.aria.setState(
255 ratingsElement, goog.a11y.aria.State.VALUENOW, this.ratings_[index]);
256 }
257 this.dispatchEvent(goog.ui.Ratings.EventType.CHANGE);
258 }
259 };
260
261
262 /**
263 * @return {number} The index of the currently selected rating.
264 */
265 goog.ui.Ratings.prototype.getSelectedIndex = function() {
266 return this.selectedIndex_;
267 };
268
269
270 /**
271 * Returns the rating value of the currently selected rating
272 * @return {?string} The value of the currently selected rating (or null).
273 */
274 goog.ui.Ratings.prototype.getValue = function() {
275 return this.selectedIndex_ == -1 ? null : this.ratings_[this.selectedIndex_];
276 };
277
278
279 /**
280 * Returns the index of the currently highlighted rating, -1 if the mouse isn't
281 * currently over the widget
282 * @return {number} The index of the currently highlighted rating.
283 */
284 goog.ui.Ratings.prototype.getHighlightedIndex = function() {
285 return this.highlightedIndex_;
286 };
287
288
289 /**
290 * Returns the value of the currently highlighted rating, null if the mouse
291 * isn't currently over the widget
292 * @return {?string} The value of the currently highlighted rating, or null.
293 */
294 goog.ui.Ratings.prototype.getHighlightedValue = function() {
295 return this.highlightedIndex_ == -1 ? null :
296 this.ratings_[this.highlightedIndex_];
297 };
298
299
300 /**
301 * Sets the array of ratings that the comonent
302 * @param {Array<string>} ratings Array of value to use as ratings.
303 */
304 goog.ui.Ratings.prototype.setRatings = function(ratings) {
305 this.ratings_ = ratings;
306 // TODO(user): If rendered update stars
307 };
308
309
310 /**
311 * Gets the array of ratings that the component
312 * @return {Array<string>} Array of ratings.
313 */
314 goog.ui.Ratings.prototype.getRatings = function() {
315 return this.ratings_;
316 };
317
318
319 /**
320 * Attaches an input or select element to the ratings widget. The value or
321 * index of the field will be updated along with the ratings widget.
322 * @param {HTMLSelectElement|HTMLInputElement} field The field to attach to.
323 */
324 goog.ui.Ratings.prototype.setAttachedFormField = function(field) {
325 this.attachedFormField_ = field;
326 };
327
328
329 /**
330 * Returns the attached input or select element to the ratings widget.
331 * @return {HTMLSelectElement|HTMLInputElement|null} The attached form field.
332 */
333 goog.ui.Ratings.prototype.getAttachedFormField = function() {
334 return this.attachedFormField_;
335 };
336
337
338 /**
339 * Enables or disables the ratings control.
340 * @param {boolean} enable Whether to enable or disable the control.
341 */
342 goog.ui.Ratings.prototype.setEnabled = function(enable) {
343 this.isEnabled_ = enable;
344 if (!enable) {
345 // Undo any highlighting done during mouseover when disabling the control
346 // and highlight the last selected rating.
347 this.resetHighlights_();
348 }
349 };
350
351
352 /**
353 * @return {boolean} Whether the ratings control is enabled.
354 */
355 goog.ui.Ratings.prototype.isEnabled = function() {
356 return this.isEnabled_;
357 };
358
359
360 /**
361 * Handle the mouse moving over a star.
362 * @param {goog.events.BrowserEvent} e The browser event.
363 * @private
364 */
365 goog.ui.Ratings.prototype.onMouseOver_ = function(e) {
366 if (!this.isEnabled()) {
367 return;
368 }
369 if (goog.isDef(e.target.index)) {
370 var n = e.target.index;
371 if (this.highlightedIndex_ != n) {
372 this.highlightIndex_(n);
373 this.highlightedIndex_ = n;
374 this.dispatchEvent(goog.ui.Ratings.EventType.HIGHLIGHT_CHANGE);
375 this.dispatchEvent(goog.ui.Ratings.EventType.HIGHLIGHT);
376 }
377 }
378 };
379
380
381 /**
382 * Handle the mouse moving over a star.
383 * @param {goog.events.BrowserEvent} e The browser event.
384 * @private
385 */
386 goog.ui.Ratings.prototype.onMouseOut_ = function(e) {
387 // Only remove the highlight if the mouse is not moving to another star
388 if (e.relatedTarget && !goog.isDef(e.relatedTarget.index)) {
389 this.resetHighlights_();
390 }
391 };
392
393
394 /**
395 * Handle the mouse moving over a star.
396 * @param {goog.events.BrowserEvent} e The browser event.
397 * @private
398 */
399 goog.ui.Ratings.prototype.onClick_ = function(e) {
400 if (!this.isEnabled()) {
401 return;
402 }
403
404 if (goog.isDef(e.target.index)) {
405 this.setSelectedIndex(e.target.index);
406 }
407 };
408
409
410 /**
411 * Handle the key down event. 0 = unselected in this case, 1 = the first rating
412 * @param {goog.events.BrowserEvent} e The browser event.
413 * @private
414 */
415 goog.ui.Ratings.prototype.onKeyDown_ = function(e) {
416 if (!this.isEnabled()) {
417 return;
418 }
419 switch (e.keyCode) {
420 case 27: // esc
421 this.setSelectedIndex(-1);
422 break;
423 case 36: // home
424 this.setSelectedIndex(0);
425 break;
426 case 35: // end
427 this.setSelectedIndex(this.ratings_.length);
428 break;
429 case 37: // left arrow
430 this.setSelectedIndex(this.getSelectedIndex() - 1);
431 break;
432 case 39: // right arrow
433 this.setSelectedIndex(this.getSelectedIndex() + 1);
434 break;
435 default:
436 // Detected a numeric key stroke, such as 0 - 9. 0 clears, 1 is first
437 // star, 9 is 9th star or last if there are less than 9 stars.
438 var num = parseInt(String.fromCharCode(e.keyCode), 10);
439 if (!isNaN(num)) {
440 this.setSelectedIndex(num - 1);
441 }
442 }
443 };
444
445
446 /**
447 * Resets the highlights to the selected rating to undo highlights due to hover
448 * effects.
449 * @private
450 */
451 goog.ui.Ratings.prototype.resetHighlights_ = function() {
452 this.highlightIndex_(this.selectedIndex_);
453 this.highlightedIndex_ = -1;
454 this.dispatchEvent(goog.ui.Ratings.EventType.HIGHLIGHT_CHANGE);
455 this.dispatchEvent(goog.ui.Ratings.EventType.UNHIGHLIGHT);
456 };
457
458
459 /**
460 * Highlights the ratings up to a specific index
461 * @param {number} n Index to highlight.
462 * @private
463 */
464 goog.ui.Ratings.prototype.highlightIndex_ = function(n) {
465 for (var i = 0, star; star = this.stars_[i]; i++) {
466 goog.dom.classlist.set(star, this.getClassName_(i, i <= n));
467 }
468 };
469
470
471 /**
472 * Get the class name for a given rating. All stars have the class:
473 * goog-ratings-star.
474 * Other possible classnames dependent on position and state are:
475 * goog-ratings-firststar-on
476 * goog-ratings-firststar-off
477 * goog-ratings-midstar-on
478 * goog-ratings-midstar-off
479 * goog-ratings-laststar-on
480 * goog-ratings-laststar-off
481 * @param {number} i Index to get class name for.
482 * @param {boolean} on Whether it should be on.
483 * @return {string} The class name.
484 * @private
485 */
486 goog.ui.Ratings.prototype.getClassName_ = function(i, on) {
487 var className;
488 var enabledClassName;
489 var baseClass = this.getCssClass();
490
491 if (i === 0) {
492 className = goog.getCssName(baseClass, 'firststar');
493 } else if (i == this.ratings_.length - 1) {
494 className = goog.getCssName(baseClass, 'laststar');
495 } else {
496 className = goog.getCssName(baseClass, 'midstar');
497 }
498
499 if (on) {
500 className = goog.getCssName(className, 'on');
501 } else {
502 className = goog.getCssName(className, 'off');
503 }
504
505 if (this.isEnabled_) {
506 enabledClassName = goog.getCssName(baseClass, 'enabled');
507 } else {
508 enabledClassName = goog.getCssName(baseClass, 'disabled');
509 }
510
511 return goog.getCssName(baseClass, 'star') + ' ' + className + ' ' +
512 enabledClassName;
513 };