Debian Codegraph @

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

raw
1 // Copyright 2008 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 An HSV (hue/saturation/value) color palette/picker
17 * implementation. Inspired by examples like
18 * http://johndyer.name/lab/colorpicker/ and the author's initial work. This
19 * control allows for more control in picking colors than a simple swatch-based
20 * palette. Without the styles from the demo css file, only a hex color label
21 * and input field show up.
22 *
23 * @author [email protected] (Erik Arvidsson)
24 * @see ../demos/hsvpalette.html
25 */
26
27 goog.provide('goog.ui.HsvPalette');
28
29 goog.require('goog.color');
30 goog.require('goog.dom.InputType');
31 goog.require('goog.dom.TagName');
32 goog.require('goog.events');
33 goog.require('goog.events.EventType');
34 goog.require('goog.events.InputHandler');
35 goog.require('goog.style');
36 goog.require('goog.style.bidi');
37 goog.require('goog.ui.Component');
38 goog.require('goog.userAgent');
39
40
41
42 /**
43 * Creates an HSV palette. Allows a user to select the hue, saturation and
44 * value/brightness.
45 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
46 * @param {string=} opt_color Optional initial color (default is red).
47 * @param {string=} opt_class Optional base for creating classnames (default is
48 * goog.getCssName('goog-hsv-palette')).
49 * @extends {goog.ui.Component}
50 * @constructor
51 */
52 goog.ui.HsvPalette = function(opt_domHelper, opt_color, opt_class) {
53 goog.ui.Component.call(this, opt_domHelper);
54
55 this.setColorInternal(opt_color || '#f00');
56
57 /**
58 * The base class name for the component.
59 * @type {string}
60 * @protected
61 */
62 this.className = opt_class || goog.getCssName('goog-hsv-palette');
63
64 /**
65 * The document which is being listened to.
66 * type {HTMLDocument}
67 * @private
68 */
69 this.document_ = this.getDomHelper().getDocument();
70 };
71 goog.inherits(goog.ui.HsvPalette, goog.ui.Component);
72 // TODO(user): Make this inherit from goog.ui.Control and split this into
73 // a control and a renderer.
74 goog.tagUnsealableClass(goog.ui.HsvPalette);
75
76
77 /**
78 * @desc Label for an input field where a user can enter a hexadecimal color
79 * specification, such as #ff0000 for red.
80 * @private
81 */
82 goog.ui.HsvPalette.MSG_HSV_PALETTE_HEX_COLOR_ = goog.getMsg('Hex color');
83
84
85 /**
86 * DOM element representing the hue/saturation background image.
87 * @type {HTMLElement}
88 * @private
89 */
90 goog.ui.HsvPalette.prototype.hsImageEl_;
91
92
93 /**
94 * DOM element representing the hue/saturation handle.
95 * @type {HTMLElement}
96 * @private
97 */
98 goog.ui.HsvPalette.prototype.hsHandleEl_;
99
100
101 /**
102 * DOM element representing the value background image.
103 * @type {HTMLElement}
104 * @protected
105 */
106 goog.ui.HsvPalette.prototype.valueBackgroundImageElement;
107
108
109 /**
110 * DOM element representing the value handle.
111 * @type {HTMLElement}
112 * @private
113 */
114 goog.ui.HsvPalette.prototype.vHandleEl_;
115
116
117 /**
118 * DOM element representing the current color swatch.
119 * @type {Element}
120 * @protected
121 */
122 goog.ui.HsvPalette.prototype.swatchElement;
123
124
125 /**
126 * DOM element representing the hex color input text field.
127 * @type {Element}
128 * @protected
129 */
130 goog.ui.HsvPalette.prototype.inputElement;
131
132
133 /**
134 * Input handler object for the hex value input field.
135 * @type {goog.events.InputHandler}
136 * @private
137 */
138 goog.ui.HsvPalette.prototype.inputHandler_;
139
140
141 /**
142 * Listener key for the mousemove event (during a drag operation).
143 * @type {goog.events.Key}
144 * @protected
145 */
146 goog.ui.HsvPalette.prototype.mouseMoveListener;
147
148
149 /**
150 * Listener key for the mouseup event (during a drag operation).
151 * @type {goog.events.Key}
152 * @protected
153 */
154 goog.ui.HsvPalette.prototype.mouseUpListener;
155
156
157 /** @private {!goog.color.Hsv} */
158 goog.ui.HsvPalette.prototype.hsv_;
159
160
161 /**
162 * Hex representation of the color.
163 * @protected {string}
164 */
165 goog.ui.HsvPalette.prototype.color;
166
167
168 /**
169 * Gets the color that is currently selected in this color picker.
170 * @return {string} The string of the selected color.
171 */
172 goog.ui.HsvPalette.prototype.getColor = function() {
173 return this.color;
174 };
175
176
177 /**
178 * Alpha transparency of the currently selected color, in [0, 1].
179 * For the HSV palette this always returns 1. The HSVA palette overrides
180 * this method.
181 * @return {number} The current alpha value.
182 */
183 goog.ui.HsvPalette.prototype.getAlpha = function() {
184 return 1;
185 };
186
187
188 /**
189 * Updates the text entry field.
190 * @protected
191 */
192 goog.ui.HsvPalette.prototype.updateInput = function() {
193 var parsed;
194 try {
195 parsed = goog.color.parse(this.inputElement.value).hex;
196 } catch (e) {
197 // ignore
198 }
199 if (this.color != parsed) {
200 this.inputElement.value = this.color;
201 }
202 };
203
204
205 /**
206 * Sets which color is selected and update the UI.
207 * @param {string} color The selected color.
208 */
209 goog.ui.HsvPalette.prototype.setColor = function(color) {
210 if (color != this.color) {
211 this.setColorInternal(color);
212 this.updateUi();
213 this.dispatchEvent(goog.ui.Component.EventType.ACTION);
214 }
215 };
216
217
218 /**
219 * Sets which color is selected.
220 * @param {string} color The selected color.
221 * @protected
222 */
223 goog.ui.HsvPalette.prototype.setColorInternal = function(color) {
224 var rgbHex = goog.color.parse(color).hex;
225 var rgbArray = goog.color.hexToRgb(rgbHex);
226 this.hsv_ = goog.color.rgbArrayToHsv(rgbArray);
227 // Hue is divided by 360 because the documentation for goog.color is currently
228 // incorrect.
229 // TODO(user): Fix this, see http://1324469 .
230 this.hsv_[0] = this.hsv_[0] / 360;
231 this.color = rgbHex;
232 };
233
234
235 /**
236 * Alters the hue, saturation, and/or value of the currently selected color and
237 * updates the UI.
238 * @param {?number=} opt_hue (optional) hue in [0, 1].
239 * @param {?number=} opt_saturation (optional) saturation in [0, 1].
240 * @param {?number=} opt_value (optional) value in [0, 255].
241 */
242 goog.ui.HsvPalette.prototype.setHsv = function(
243 opt_hue, opt_saturation, opt_value) {
244 if (opt_hue != null || opt_saturation != null || opt_value != null) {
245 this.setHsv_(opt_hue, opt_saturation, opt_value);
246 this.updateUi();
247 this.dispatchEvent(goog.ui.Component.EventType.ACTION);
248 }
249 };
250
251
252 /**
253 * Alters the hue, saturation, and/or value of the currently selected color.
254 * @param {?number=} opt_hue (optional) hue in [0, 1].
255 * @param {?number=} opt_saturation (optional) saturation in [0, 1].
256 * @param {?number=} opt_value (optional) value in [0, 255].
257 * @private
258 */
259 goog.ui.HsvPalette.prototype.setHsv_ = function(
260 opt_hue, opt_saturation, opt_value) {
261 this.hsv_[0] = (opt_hue != null) ? opt_hue : this.hsv_[0];
262 this.hsv_[1] = (opt_saturation != null) ? opt_saturation : this.hsv_[1];
263 this.hsv_[2] = (opt_value != null) ? opt_value : this.hsv_[2];
264 // Hue is multiplied by 360 because the documentation for goog.color is
265 // currently incorrect.
266 // TODO(user): Fix this, see http://1324469 .
267 this.color = goog.color.hsvArrayToHex(
268 [this.hsv_[0] * 360, this.hsv_[1], this.hsv_[2]]);
269 };
270
271
272 /**
273 * HsvPalettes cannot be used to decorate pre-existing html, since the
274 * structure they build is fairly complicated.
275 * @param {Element} element Element to decorate.
276 * @return {boolean} Returns always false.
277 * @override
278 */
279 goog.ui.HsvPalette.prototype.canDecorate = function(element) {
280 return false;
281 };
282
283
284 /** @override */
285 goog.ui.HsvPalette.prototype.createDom = function() {
286 var dom = this.getDomHelper();
287 var noalpha = (goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('7')) ?
288 ' ' + goog.getCssName(this.className, 'noalpha') :
289 '';
290
291 var backdrop = dom.createDom(
292 goog.dom.TagName.DIV, goog.getCssName(this.className, 'hs-backdrop'));
293
294 this.hsHandleEl_ = /** @type {!HTMLElement} */ (
295 dom.createDom(
296 goog.dom.TagName.DIV, goog.getCssName(this.className, 'hs-handle')));
297
298 this.hsImageEl_ = /** @type {!HTMLElement} */ (
299 dom.createDom(
300 goog.dom.TagName.DIV, goog.getCssName(this.className, 'hs-image'),
301 this.hsHandleEl_));
302
303 this.valueBackgroundImageElement = /** @type {!HTMLElement} */ (
304 dom.createDom(
305 goog.dom.TagName.DIV, goog.getCssName(this.className, 'v-image')));
306
307 this.vHandleEl_ = /** @type {!HTMLElement} */ (
308 dom.createDom(
309 goog.dom.TagName.DIV, goog.getCssName(this.className, 'v-handle')));
310
311 this.swatchElement = dom.createDom(
312 goog.dom.TagName.DIV, goog.getCssName(this.className, 'swatch'));
313
314 this.inputElement = dom.createDom(goog.dom.TagName.INPUT, {
315 'class': goog.getCssName(this.className, 'input'),
316 'aria-label': goog.ui.HsvPalette.MSG_HSV_PALETTE_HEX_COLOR_,
317 'type': goog.dom.InputType.TEXT,
318 'dir': 'ltr'
319 });
320
321 var labelElement =
322 dom.createDom(goog.dom.TagName.LABEL, null, this.inputElement);
323
324 var element = dom.createDom(
325 goog.dom.TagName.DIV, this.className + noalpha, backdrop, this.hsImageEl_,
326 this.valueBackgroundImageElement, this.vHandleEl_, this.swatchElement,
327 labelElement);
328
329 this.setElementInternal(element);
330
331 // TODO(arv): Set tabIndex
332 };
333
334
335 /**
336 * Renders the color picker inside the provided element. This will override the
337 * current content of the element.
338 * @override
339 */
340 goog.ui.HsvPalette.prototype.enterDocument = function() {
341 goog.ui.HsvPalette.superClass_.enterDocument.call(this);
342
343 // TODO(user): Accessibility.
344
345 this.updateUi();
346
347 var handler = this.getHandler();
348 handler.listen(
349 this.getElement(), goog.events.EventType.MOUSEDOWN, this.handleMouseDown);
350
351 // Cannot create InputHandler in createDom because IE throws an exception
352 // on document.activeElement
353 if (!this.inputHandler_) {
354 this.inputHandler_ = new goog.events.InputHandler(this.inputElement);
355 }
356
357 handler.listen(
358 this.inputHandler_, goog.events.InputHandler.EventType.INPUT,
359 this.handleInput);
360 };
361
362
363 /** @override */
364 goog.ui.HsvPalette.prototype.disposeInternal = function() {
365 goog.ui.HsvPalette.superClass_.disposeInternal.call(this);
366
367 delete this.hsImageEl_;
368 delete this.hsHandleEl_;
369 delete this.valueBackgroundImageElement;
370 delete this.vHandleEl_;
371 delete this.swatchElement;
372 delete this.inputElement;
373 if (this.inputHandler_) {
374 this.inputHandler_.dispose();
375 delete this.inputHandler_;
376 }
377 goog.events.unlistenByKey(this.mouseMoveListener);
378 goog.events.unlistenByKey(this.mouseUpListener);
379 };
380
381
382 /**
383 * Updates the position, opacity, and styles for the UI representation of the
384 * palette.
385 * @protected
386 */
387 goog.ui.HsvPalette.prototype.updateUi = function() {
388 if (this.isInDocument()) {
389 var h = this.hsv_[0];
390 var s = this.hsv_[1];
391 var v = this.hsv_[2];
392
393 var left = this.hsImageEl_.offsetWidth * h;
394
395 // We don't use a flipped gradient image in RTL, so we need to flip the
396 // offset in RTL so that it still hovers over the correct color on the
397 // gradiant.
398 if (this.isRightToLeft()) {
399 left = this.hsImageEl_.offsetWidth - left;
400 }
401
402 // We also need to account for the handle size.
403 var handleOffset = Math.ceil(this.hsHandleEl_.offsetWidth / 2);
404 left -= handleOffset;
405
406 var top = this.hsImageEl_.offsetHeight * (1 - s);
407 // Account for the handle size.
408 top -= Math.ceil(this.hsHandleEl_.offsetHeight / 2);
409
410 goog.style.bidi.setPosition(
411 this.hsHandleEl_, left, top, this.isRightToLeft());
412
413 top = this.valueBackgroundImageElement.offsetTop -
414 Math.floor(this.vHandleEl_.offsetHeight / 2) +
415 this.valueBackgroundImageElement.offsetHeight * ((255 - v) / 255);
416
417 this.vHandleEl_.style.top = top + 'px';
418 goog.style.setOpacity(this.hsImageEl_, (v / 255));
419
420 goog.style.setStyle(
421 this.valueBackgroundImageElement, 'background-color',
422 goog.color.hsvToHex(this.hsv_[0] * 360, this.hsv_[1], 255));
423
424 goog.style.setStyle(this.swatchElement, 'background-color', this.color);
425 goog.style.setStyle(
426 this.swatchElement, 'color',
427 (this.hsv_[2] > 255 / 2) ? '#000' : '#fff');
428 this.updateInput();
429 }
430 };
431
432
433 /**
434 * Handles mousedown events on palette UI elements.
435 * @param {goog.events.BrowserEvent} e Event object.
436 * @protected
437 */
438 goog.ui.HsvPalette.prototype.handleMouseDown = function(e) {
439 if (e.target == this.valueBackgroundImageElement ||
440 e.target == this.vHandleEl_) {
441 // Setup value change listeners
442 var b = goog.style.getBounds(this.valueBackgroundImageElement);
443 this.handleMouseMoveV_(b, e);
444 this.mouseMoveListener = goog.events.listen(
445 this.document_, goog.events.EventType.MOUSEMOVE,
446 goog.bind(this.handleMouseMoveV_, this, b));
447 this.mouseUpListener = goog.events.listen(
448 this.document_, goog.events.EventType.MOUSEUP, this.handleMouseUp,
449 false, this);
450 } else if (e.target == this.hsImageEl_ || e.target == this.hsHandleEl_) {
451 // Setup hue/saturation change listeners
452 var b = goog.style.getBounds(this.hsImageEl_);
453 this.handleMouseMoveHs_(b, e);
454 this.mouseMoveListener = goog.events.listen(
455 this.document_, goog.events.EventType.MOUSEMOVE,
456 goog.bind(this.handleMouseMoveHs_, this, b));
457 this.mouseUpListener = goog.events.listen(
458 this.document_, goog.events.EventType.MOUSEUP, this.handleMouseUp,
459 false, this);
460 }
461 };
462
463
464 /**
465 * Handles mousemove events on the document once a drag operation on the value
466 * slider has started.
467 * @param {goog.math.Rect} b Boundaries of the value slider object at the start
468 * of the drag operation.
469 * @param {goog.events.BrowserEvent} e Event object.
470 * @private
471 */
472 goog.ui.HsvPalette.prototype.handleMouseMoveV_ = function(b, e) {
473 e.preventDefault();
474 var vportPos = this.getDomHelper().getDocumentScroll();
475
476 var height =
477 Math.min(Math.max(vportPos.y + e.clientY, b.top), b.top + b.height);
478
479 var newV = Math.round(255 * (b.top + b.height - height) / b.height);
480
481 this.setHsv(null, null, newV);
482 };
483
484
485 /**
486 * Handles mousemove events on the document once a drag operation on the
487 * hue/saturation slider has started.
488 * @param {goog.math.Rect} b Boundaries of the value slider object at the start
489 * of the drag operation.
490 * @param {goog.events.BrowserEvent} e Event object.
491 * @private
492 */
493 goog.ui.HsvPalette.prototype.handleMouseMoveHs_ = function(b, e) {
494 e.preventDefault();
495 var vportPos = this.getDomHelper().getDocumentScroll();
496 var newH =
497 (Math.min(Math.max(vportPos.x + e.clientX, b.left), b.left + b.width) -
498 b.left) /
499 b.width;
500 var newS =
501 (-Math.min(Math.max(vportPos.y + e.clientY, b.top), b.top + b.height) +
502 b.top + b.height) /
503 b.height;
504 this.setHsv(newH, newS, null);
505 };
506
507
508 /**
509 * Handles mouseup events on the document, which ends a drag operation.
510 * @param {goog.events.Event} e Event object.
511 * @protected
512 */
513 goog.ui.HsvPalette.prototype.handleMouseUp = function(e) {
514 goog.events.unlistenByKey(this.mouseMoveListener);
515 goog.events.unlistenByKey(this.mouseUpListener);
516 };
517
518
519 /**
520 * Handles input events on the hex value input field.
521 * @param {goog.events.Event} e Event object.
522 * @protected
523 */
524 goog.ui.HsvPalette.prototype.handleInput = function(e) {
525 if (/^#?[0-9a-f]{6}$/i.test(this.inputElement.value)) {
526 this.setColor(this.inputElement.value);
527 }
528 };