source: other-projects/nz-flag-design/trunk/main-form/bgrins-spectrum/spectrum.js@ 29741

Last change on this file since 29741 was 29741, checked in by davidb, 9 years ago

Support JS library for colour picker

  • Property svn:executable set to *
File size: 76.0 KB
Line 
1// Spectrum Colorpicker v1.6.0
2// https://github.com/bgrins/spectrum
3// Author: Brian Grinstead
4// License: MIT
5
6(function (factory) {
7 "use strict";
8
9 if (typeof define === 'function' && define.amd) { // AMD
10 define(['jquery'], factory);
11 }
12 else if (typeof exports == "object" && typeof module == "object") { // CommonJS
13 module.exports = factory;
14 }
15 else { // Browser
16 factory(jQuery);
17 }
18})(function($, undefined) {
19 "use strict";
20
21 var defaultOpts = {
22
23 // Callbacks
24 beforeShow: noop,
25 move: noop,
26 change: noop,
27 show: noop,
28 hide: noop,
29
30 // Options
31 color: false,
32 flat: false,
33 showInput: false,
34 allowEmpty: false,
35 showButtons: true,
36 clickoutFiresChange: false,
37 showInitial: false,
38 showPalette: false,
39 showPaletteOnly: false,
40 hideAfterPaletteSelect: false,
41 togglePaletteOnly: false,
42 showSelectionPalette: true,
43 localStorageKey: false,
44 appendTo: "body",
45 maxSelectionSize: 7,
46 cancelText: "cancel",
47 chooseText: "choose",
48 togglePaletteMoreText: "more",
49 togglePaletteLessText: "less",
50 clearText: "Clear Color Selection",
51 noColorSelectedText: "No Color Selected",
52 preferredFormat: false,
53 className: "", // Deprecated - use containerClassName and replacerClassName instead.
54 containerClassName: "",
55 replacerClassName: "",
56 showAlpha: false,
57 theme: "sp-light",
58 palette: [["#ffffff", "#000000", "#ff0000", "#ff8000", "#ffff00", "#008000", "#0000ff", "#4b0082", "#9400d3"]],
59 selectionPalette: [],
60 disabled: false,
61 offset: null
62 },
63 spectrums = [],
64 IE = !!/msie/i.exec( window.navigator.userAgent ),
65 rgbaSupport = (function() {
66 function contains( str, substr ) {
67 return !!~('' + str).indexOf(substr);
68 }
69
70 var elem = document.createElement('div');
71 var style = elem.style;
72 style.cssText = 'background-color:rgba(0,0,0,.5)';
73 return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla');
74 })(),
75 inputTypeColorSupport = (function() {
76 var colorInput = $("<input type='color' value='!' />")[0];
77 return colorInput.type === "color" && colorInput.value !== "!";
78 })(),
79 replaceInput = [
80 "<div class='sp-replacer'>",
81 "<div class='sp-preview'><div class='sp-preview-inner'></div></div>",
82 "<div class='sp-dd'>&#9660;</div>",
83 "</div>"
84 ].join(''),
85 markup = (function () {
86
87 // IE does not support gradients with multiple stops, so we need to simulate
88 // that for the rainbow slider with 8 divs that each have a single gradient
89 var gradientFix = "";
90 if (IE) {
91 for (var i = 1; i <= 6; i++) {
92 gradientFix += "<div class='sp-" + i + "'></div>";
93 }
94 }
95
96 return [
97 "<div class='sp-container sp-hidden'>",
98 "<div class='sp-palette-container'>",
99 "<div class='sp-palette sp-thumb sp-cf'></div>",
100 "<div class='sp-palette-button-container sp-cf'>",
101 "<button type='button' class='sp-palette-toggle'></button>",
102 "</div>",
103 "</div>",
104 "<div class='sp-picker-container'>",
105 "<div class='sp-top sp-cf'>",
106 "<div class='sp-fill'></div>",
107 "<div class='sp-top-inner'>",
108 "<div class='sp-color'>",
109 "<div class='sp-sat'>",
110 "<div class='sp-val'>",
111 "<div class='sp-dragger'></div>",
112 "</div>",
113 "</div>",
114 "</div>",
115 "<div class='sp-clear sp-clear-display'>",
116 "</div>",
117 "<div class='sp-hue'>",
118 "<div class='sp-slider'></div>",
119 gradientFix,
120 "</div>",
121 "</div>",
122 "<div class='sp-alpha'><div class='sp-alpha-inner'><div class='sp-alpha-handle'></div></div></div>",
123 "</div>",
124 "<div class='sp-input-container sp-cf'>",
125 "<input class='sp-input' type='text' spellcheck='false' />",
126 "</div>",
127 "<div class='sp-initial sp-thumb sp-cf'></div>",
128 "<div class='sp-button-container sp-cf'>",
129 "<a class='sp-cancel' href='#'></a>",
130 "<button type='button' class='sp-choose'></button>",
131 "</div>",
132 "</div>",
133 "</div>"
134 ].join("");
135 })();
136
137 function paletteTemplate (p, color, className, opts) {
138 var html = [];
139 for (var i = 0; i < p.length; i++) {
140 var current = p[i];
141 if(current) {
142 var tiny = tinycolor(current);
143 var c = tiny.toHsl().l < 0.5 ? "sp-thumb-el sp-thumb-dark" : "sp-thumb-el sp-thumb-light";
144 c += (tinycolor.equals(color, current)) ? " sp-thumb-active" : "";
145 var formattedString = tiny.toString(opts.preferredFormat || "rgb");
146 var swatchStyle = rgbaSupport ? ("background-color:" + tiny.toRgbString()) : "filter:" + tiny.toFilter();
147 html.push('<span title="' + formattedString + '" data-color="' + tiny.toRgbString() + '" class="' + c + '"><span class="sp-thumb-inner" style="' + swatchStyle + ';" /></span>');
148 } else {
149 var cls = 'sp-clear-display';
150 html.push($('<div />')
151 .append($('<span data-color="" style="background-color:transparent;" class="' + cls + '"></span>')
152 .attr('title', opts.noColorSelectedText)
153 )
154 .html()
155 );
156 }
157 }
158 return "<div class='sp-cf " + className + "'>" + html.join('') + "</div>";
159 }
160
161 function hideAll() {
162 for (var i = 0; i < spectrums.length; i++) {
163 if (spectrums[i]) {
164 spectrums[i].hide();
165 }
166 }
167 }
168
169 function instanceOptions(o, callbackContext) {
170 var opts = $.extend({}, defaultOpts, o);
171 opts.callbacks = {
172 'move': bind(opts.move, callbackContext),
173 'change': bind(opts.change, callbackContext),
174 'show': bind(opts.show, callbackContext),
175 'hide': bind(opts.hide, callbackContext),
176 'beforeShow': bind(opts.beforeShow, callbackContext)
177 };
178
179 return opts;
180 }
181
182 function spectrum(element, o) {
183
184 var opts = instanceOptions(o, element),
185 flat = opts.flat,
186 showSelectionPalette = opts.showSelectionPalette,
187 localStorageKey = opts.localStorageKey,
188 theme = opts.theme,
189 callbacks = opts.callbacks,
190 resize = throttle(reflow, 10),
191 visible = false,
192 dragWidth = 0,
193 dragHeight = 0,
194 dragHelperHeight = 0,
195 slideHeight = 0,
196 slideWidth = 0,
197 alphaWidth = 0,
198 alphaSlideHelperWidth = 0,
199 slideHelperHeight = 0,
200 currentHue = 0,
201 currentSaturation = 0,
202 currentValue = 0,
203 currentAlpha = 1,
204 palette = [],
205 paletteArray = [],
206 paletteLookup = {},
207 selectionPalette = opts.selectionPalette.slice(0),
208 maxSelectionSize = opts.maxSelectionSize,
209 draggingClass = "sp-dragging",
210 shiftMovementDirection = null;
211
212 var doc = element.ownerDocument,
213 body = doc.body,
214 boundElement = $(element),
215 disabled = false,
216 container = $(markup, doc).addClass(theme),
217 pickerContainer = container.find(".sp-picker-container"),
218 dragger = container.find(".sp-color"),
219 dragHelper = container.find(".sp-dragger"),
220 slider = container.find(".sp-hue"),
221 slideHelper = container.find(".sp-slider"),
222 alphaSliderInner = container.find(".sp-alpha-inner"),
223 alphaSlider = container.find(".sp-alpha"),
224 alphaSlideHelper = container.find(".sp-alpha-handle"),
225 textInput = container.find(".sp-input"),
226 paletteContainer = container.find(".sp-palette"),
227 initialColorContainer = container.find(".sp-initial"),
228 cancelButton = container.find(".sp-cancel"),
229 clearButton = container.find(".sp-clear"),
230 chooseButton = container.find(".sp-choose"),
231 toggleButton = container.find(".sp-palette-toggle"),
232 isInput = boundElement.is("input"),
233 isInputTypeColor = isInput && inputTypeColorSupport && boundElement.attr("type") === "color",
234 shouldReplace = isInput && !flat,
235 replacer = (shouldReplace) ? $(replaceInput).addClass(theme).addClass(opts.className).addClass(opts.replacerClassName) : $([]),
236 offsetElement = (shouldReplace) ? replacer : boundElement,
237 previewElement = replacer.find(".sp-preview-inner"),
238 initialColor = opts.color || (isInput && boundElement.val()),
239 colorOnShow = false,
240 preferredFormat = opts.preferredFormat,
241 currentPreferredFormat = preferredFormat,
242 clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange,
243 isEmpty = !initialColor,
244 allowEmpty = opts.allowEmpty && !isInputTypeColor;
245
246 function applyOptions() {
247
248 if (opts.showPaletteOnly) {
249 opts.showPalette = true;
250 }
251
252 toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText);
253
254 if (opts.palette) {
255 palette = opts.palette.slice(0);
256 paletteArray = $.isArray(palette[0]) ? palette : [palette];
257 paletteLookup = {};
258 for (var i = 0; i < paletteArray.length; i++) {
259 for (var j = 0; j < paletteArray[i].length; j++) {
260 var rgb = tinycolor(paletteArray[i][j]).toRgbString();
261 paletteLookup[rgb] = true;
262 }
263 }
264 }
265
266 container.toggleClass("sp-flat", flat);
267 container.toggleClass("sp-input-disabled", !opts.showInput);
268 container.toggleClass("sp-alpha-enabled", opts.showAlpha);
269 container.toggleClass("sp-clear-enabled", allowEmpty);
270 container.toggleClass("sp-buttons-disabled", !opts.showButtons);
271 container.toggleClass("sp-palette-buttons-disabled", !opts.togglePaletteOnly);
272 container.toggleClass("sp-palette-disabled", !opts.showPalette);
273 container.toggleClass("sp-palette-only", opts.showPaletteOnly);
274 container.toggleClass("sp-initial-disabled", !opts.showInitial);
275 container.addClass(opts.className).addClass(opts.containerClassName);
276
277 reflow();
278 }
279
280 function initialize() {
281
282 if (IE) {
283 container.find("*:not(input)").attr("unselectable", "on");
284 }
285
286 applyOptions();
287
288 if (shouldReplace) {
289 boundElement.after(replacer).hide();
290 }
291
292 if (!allowEmpty) {
293 clearButton.hide();
294 }
295
296 if (flat) {
297 boundElement.after(container).hide();
298 }
299 else {
300
301 var appendTo = opts.appendTo === "parent" ? boundElement.parent() : $(opts.appendTo);
302 if (appendTo.length !== 1) {
303 appendTo = $("body");
304 }
305
306 appendTo.append(container);
307 }
308
309 updateSelectionPaletteFromStorage();
310
311 offsetElement.bind("click.spectrum touchstart.spectrum", function (e) {
312 if (!disabled) {
313 toggle();
314 }
315
316 e.stopPropagation();
317
318 if (!$(e.target).is("input")) {
319 e.preventDefault();
320 }
321 });
322
323 if(boundElement.is(":disabled") || (opts.disabled === true)) {
324 disable();
325 }
326
327 // Prevent clicks from bubbling up to document. This would cause it to be hidden.
328 container.click(stopPropagation);
329
330 // Handle user typed input
331 textInput.change(setFromTextInput);
332 textInput.bind("paste", function () {
333 setTimeout(setFromTextInput, 1);
334 });
335 textInput.keydown(function (e) { if (e.keyCode == 13) { setFromTextInput(); } });
336
337 cancelButton.text(opts.cancelText);
338 cancelButton.bind("click.spectrum", function (e) {
339 e.stopPropagation();
340 e.preventDefault();
341 revert();
342 hide();
343 });
344
345 clearButton.attr("title", opts.clearText);
346 clearButton.bind("click.spectrum", function (e) {
347 e.stopPropagation();
348 e.preventDefault();
349 isEmpty = true;
350 move();
351
352 if(flat) {
353 //for the flat style, this is a change event
354 updateOriginalInput(true);
355 }
356 });
357
358 chooseButton.text(opts.chooseText);
359 chooseButton.bind("click.spectrum", function (e) {
360 e.stopPropagation();
361 e.preventDefault();
362
363 if (isValid()) {
364 updateOriginalInput(true);
365 hide();
366 }
367 });
368
369 toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText);
370 toggleButton.bind("click.spectrum", function (e) {
371 e.stopPropagation();
372 e.preventDefault();
373
374 opts.showPaletteOnly = !opts.showPaletteOnly;
375
376 // To make sure the Picker area is drawn on the right, next to the
377 // Palette area (and not below the palette), first move the Palette
378 // to the left to make space for the picker, plus 5px extra.
379 // The 'applyOptions' function puts the whole container back into place
380 // and takes care of the button-text and the sp-palette-only CSS class.
381 if (!opts.showPaletteOnly && !flat) {
382 container.css('left', '-=' + (pickerContainer.outerWidth(true) + 5));
383 }
384 applyOptions();
385 });
386
387 draggable(alphaSlider, function (dragX, dragY, e) {
388 currentAlpha = (dragX / alphaWidth);
389 isEmpty = false;
390 if (e.shiftKey) {
391 currentAlpha = Math.round(currentAlpha * 10) / 10;
392 }
393
394 move();
395 }, dragStart, dragStop);
396
397 draggable(slider, function (dragX, dragY) {
398 currentHue = parseFloat(dragY / slideHeight);
399 isEmpty = false;
400 if (!opts.showAlpha) {
401 currentAlpha = 1;
402 }
403 move();
404 }, dragStart, dragStop);
405
406 draggable(dragger, function (dragX, dragY, e) {
407
408 // shift+drag should snap the movement to either the x or y axis.
409 if (!e.shiftKey) {
410 shiftMovementDirection = null;
411 }
412 else if (!shiftMovementDirection) {
413 var oldDragX = currentSaturation * dragWidth;
414 var oldDragY = dragHeight - (currentValue * dragHeight);
415 var furtherFromX = Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY);
416
417 shiftMovementDirection = furtherFromX ? "x" : "y";
418 }
419
420 var setSaturation = !shiftMovementDirection || shiftMovementDirection === "x";
421 var setValue = !shiftMovementDirection || shiftMovementDirection === "y";
422
423 if (setSaturation) {
424 currentSaturation = parseFloat(dragX / dragWidth);
425 }
426 if (setValue) {
427 currentValue = parseFloat((dragHeight - dragY) / dragHeight);
428 }
429
430 isEmpty = false;
431 if (!opts.showAlpha) {
432 currentAlpha = 1;
433 }
434
435 move();
436
437 }, dragStart, dragStop);
438
439 if (!!initialColor) {
440 set(initialColor);
441
442 // In case color was black - update the preview UI and set the format
443 // since the set function will not run (default color is black).
444 updateUI();
445 currentPreferredFormat = preferredFormat || tinycolor(initialColor).format;
446
447 addColorToSelectionPalette(initialColor);
448 }
449 else {
450 updateUI();
451 }
452
453 if (flat) {
454 show();
455 }
456
457 function paletteElementClick(e) {
458 if (e.data && e.data.ignore) {
459 set($(e.target).closest(".sp-thumb-el").data("color"));
460 move();
461 }
462 else {
463 set($(e.target).closest(".sp-thumb-el").data("color"));
464 move();
465 updateOriginalInput(true);
466 if (opts.hideAfterPaletteSelect) {
467 hide();
468 }
469 }
470
471 return false;
472 }
473
474 var paletteEvent = IE ? "mousedown.spectrum" : "click.spectrum touchstart.spectrum";
475 paletteContainer.delegate(".sp-thumb-el", paletteEvent, paletteElementClick);
476 initialColorContainer.delegate(".sp-thumb-el:nth-child(1)", paletteEvent, { ignore: true }, paletteElementClick);
477 }
478
479 function updateSelectionPaletteFromStorage() {
480
481 if (localStorageKey && window.localStorage) {
482
483 // Migrate old palettes over to new format. May want to remove this eventually.
484 try {
485 var oldPalette = window.localStorage[localStorageKey].split(",#");
486 if (oldPalette.length > 1) {
487 delete window.localStorage[localStorageKey];
488 $.each(oldPalette, function(i, c) {
489 addColorToSelectionPalette(c);
490 });
491 }
492 }
493 catch(e) { }
494
495 try {
496 selectionPalette = window.localStorage[localStorageKey].split(";");
497 }
498 catch (e) { }
499 }
500 }
501
502 function addColorToSelectionPalette(color) {
503 if (showSelectionPalette) {
504 var rgb = tinycolor(color).toRgbString();
505 if (!paletteLookup[rgb] && $.inArray(rgb, selectionPalette) === -1) {
506 selectionPalette.push(rgb);
507 while(selectionPalette.length > maxSelectionSize) {
508 selectionPalette.shift();
509 }
510 }
511
512 if (localStorageKey && window.localStorage) {
513 try {
514 window.localStorage[localStorageKey] = selectionPalette.join(";");
515 }
516 catch(e) { }
517 }
518 }
519 }
520
521 function getUniqueSelectionPalette() {
522 var unique = [];
523 if (opts.showPalette) {
524 for (var i = 0; i < selectionPalette.length; i++) {
525 var rgb = tinycolor(selectionPalette[i]).toRgbString();
526
527 if (!paletteLookup[rgb]) {
528 unique.push(selectionPalette[i]);
529 }
530 }
531 }
532
533 return unique.reverse().slice(0, opts.maxSelectionSize);
534 }
535
536 function drawPalette() {
537
538 var currentColor = get();
539
540 var html = $.map(paletteArray, function (palette, i) {
541 return paletteTemplate(palette, currentColor, "sp-palette-row sp-palette-row-" + i, opts);
542 });
543
544 updateSelectionPaletteFromStorage();
545
546 if (selectionPalette) {
547 html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, "sp-palette-row sp-palette-row-selection", opts));
548 }
549
550 paletteContainer.html(html.join(""));
551 }
552
553 function drawInitial() {
554 if (opts.showInitial) {
555 var initial = colorOnShow;
556 var current = get();
557 initialColorContainer.html(paletteTemplate([initial, current], current, "sp-palette-row-initial", opts));
558 }
559 }
560
561 function dragStart() {
562 if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) {
563 reflow();
564 }
565 container.addClass(draggingClass);
566 shiftMovementDirection = null;
567 boundElement.trigger('dragstart.spectrum', [ get() ]);
568 }
569
570 function dragStop() {
571 container.removeClass(draggingClass);
572 boundElement.trigger('dragstop.spectrum', [ get() ]);
573 }
574
575 function setFromTextInput() {
576
577 var value = textInput.val();
578
579 if ((value === null || value === "") && allowEmpty) {
580 set(null);
581 updateOriginalInput(true);
582 }
583 else {
584 var tiny = tinycolor(value);
585 if (tiny.isValid()) {
586 set(tiny);
587 updateOriginalInput(true);
588 }
589 else {
590 textInput.addClass("sp-validation-error");
591 }
592 }
593 }
594
595 function toggle() {
596 if (visible) {
597 hide();
598 }
599 else {
600 show();
601 }
602 }
603
604 function show() {
605 var event = $.Event('beforeShow.spectrum');
606
607 if (visible) {
608 reflow();
609 return;
610 }
611
612 boundElement.trigger(event, [ get() ]);
613
614 if (callbacks.beforeShow(get()) === false || event.isDefaultPrevented()) {
615 return;
616 }
617
618 hideAll();
619 visible = true;
620
621 $(doc).bind("click.spectrum", clickout);
622 $(window).bind("resize.spectrum", resize);
623 replacer.addClass("sp-active");
624 container.removeClass("sp-hidden");
625
626 reflow();
627 updateUI();
628
629 colorOnShow = get();
630
631 drawInitial();
632 callbacks.show(colorOnShow);
633 boundElement.trigger('show.spectrum', [ colorOnShow ]);
634 }
635
636 function clickout(e) {
637 // Return on right click.
638 if (e.button == 2) { return; }
639
640 if (clickoutFiresChange) {
641 updateOriginalInput(true);
642 }
643 else {
644 revert();
645 }
646 hide();
647 }
648
649 function hide() {
650 // Return if hiding is unnecessary
651 if (!visible || flat) { return; }
652 visible = false;
653
654 $(doc).unbind("click.spectrum", clickout);
655 $(window).unbind("resize.spectrum", resize);
656
657 replacer.removeClass("sp-active");
658 container.addClass("sp-hidden");
659
660 callbacks.hide(get());
661 boundElement.trigger('hide.spectrum', [ get() ]);
662 }
663
664 function revert() {
665 set(colorOnShow, true);
666 }
667
668 function set(color, ignoreFormatChange) {
669 if (tinycolor.equals(color, get())) {
670 // Update UI just in case a validation error needs
671 // to be cleared.
672 updateUI();
673 return;
674 }
675
676 var newColor, newHsv;
677 if (!color && allowEmpty) {
678 isEmpty = true;
679 } else {
680 isEmpty = false;
681 newColor = tinycolor(color);
682 newHsv = newColor.toHsv();
683
684 currentHue = (newHsv.h % 360) / 360;
685 currentSaturation = newHsv.s;
686 currentValue = newHsv.v;
687 currentAlpha = newHsv.a;
688 }
689 updateUI();
690
691 if (newColor && newColor.isValid() && !ignoreFormatChange) {
692 currentPreferredFormat = preferredFormat || newColor.getFormat();
693 }
694 }
695
696 function get(opts) {
697 opts = opts || { };
698
699 if (allowEmpty && isEmpty) {
700 return null;
701 }
702
703 return tinycolor.fromRatio({
704 h: currentHue,
705 s: currentSaturation,
706 v: currentValue,
707 a: Math.round(currentAlpha * 100) / 100
708 }, { format: opts.format || currentPreferredFormat });
709 }
710
711 function isValid() {
712 return !textInput.hasClass("sp-validation-error");
713 }
714
715 function move() {
716 updateUI();
717
718 callbacks.move(get());
719 boundElement.trigger('move.spectrum', [ get() ]);
720 }
721
722 function updateUI() {
723
724 textInput.removeClass("sp-validation-error");
725
726 updateHelperLocations();
727
728 // Update dragger background color (gradients take care of saturation and value).
729 var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 });
730 dragger.css("background-color", flatColor.toHexString());
731
732 // Get a format that alpha will be included in (hex and names ignore alpha)
733 var format = currentPreferredFormat;
734 if (currentAlpha < 1 && !(currentAlpha === 0 && format === "name")) {
735 if (format === "hex" || format === "hex3" || format === "hex6" || format === "name") {
736 format = "rgb";
737 }
738 }
739
740 var realColor = get({ format: format }),
741 displayColor = '';
742
743 //reset background info for preview element
744 previewElement.removeClass("sp-clear-display");
745 previewElement.css('background-color', 'transparent');
746
747 if (!realColor && allowEmpty) {
748 // Update the replaced elements background with icon indicating no color selection
749 previewElement.addClass("sp-clear-display");
750 }
751 else {
752 var realHex = realColor.toHexString(),
753 realRgb = realColor.toRgbString();
754
755 // Update the replaced elements background color (with actual selected color)
756 if (rgbaSupport || realColor.alpha === 1) {
757 previewElement.css("background-color", realRgb);
758 }
759 else {
760 previewElement.css("background-color", "transparent");
761 previewElement.css("filter", realColor.toFilter());
762 }
763
764 if (opts.showAlpha) {
765 var rgb = realColor.toRgb();
766 rgb.a = 0;
767 var realAlpha = tinycolor(rgb).toRgbString();
768 var gradient = "linear-gradient(left, " + realAlpha + ", " + realHex + ")";
769
770 if (IE) {
771 alphaSliderInner.css("filter", tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex));
772 }
773 else {
774 alphaSliderInner.css("background", "-webkit-" + gradient);
775 alphaSliderInner.css("background", "-moz-" + gradient);
776 alphaSliderInner.css("background", "-ms-" + gradient);
777 // Use current syntax gradient on unprefixed property.
778 alphaSliderInner.css("background",
779 "linear-gradient(to right, " + realAlpha + ", " + realHex + ")");
780 }
781 }
782
783 displayColor = realColor.toString(format);
784 }
785
786 // Update the text entry input as it changes happen
787 if (opts.showInput) {
788 textInput.val(displayColor);
789 }
790
791 if (opts.showPalette) {
792 drawPalette();
793 }
794
795 drawInitial();
796 }
797
798 function updateHelperLocations() {
799 var s = currentSaturation;
800 var v = currentValue;
801
802 if(allowEmpty && isEmpty) {
803 //if selected color is empty, hide the helpers
804 alphaSlideHelper.hide();
805 slideHelper.hide();
806 dragHelper.hide();
807 }
808 else {
809 //make sure helpers are visible
810 alphaSlideHelper.show();
811 slideHelper.show();
812 dragHelper.show();
813
814 // Where to show the little circle in that displays your current selected color
815 var dragX = s * dragWidth;
816 var dragY = dragHeight - (v * dragHeight);
817 dragX = Math.max(
818 -dragHelperHeight,
819 Math.min(dragWidth - dragHelperHeight, dragX - dragHelperHeight)
820 );
821 dragY = Math.max(
822 -dragHelperHeight,
823 Math.min(dragHeight - dragHelperHeight, dragY - dragHelperHeight)
824 );
825 dragHelper.css({
826 "top": dragY + "px",
827 "left": dragX + "px"
828 });
829
830 var alphaX = currentAlpha * alphaWidth;
831 alphaSlideHelper.css({
832 "left": (alphaX - (alphaSlideHelperWidth / 2)) + "px"
833 });
834
835 // Where to show the bar that displays your current selected hue
836 var slideY = (currentHue) * slideHeight;
837 slideHelper.css({
838 "top": (slideY - slideHelperHeight) + "px"
839 });
840 }
841 }
842
843 function updateOriginalInput(fireCallback) {
844 var color = get(),
845 displayColor = '',
846 hasChanged = !tinycolor.equals(color, colorOnShow);
847
848 if (color) {
849 displayColor = color.toString(currentPreferredFormat);
850 // Update the selection palette with the current color
851 addColorToSelectionPalette(color);
852 }
853
854 if (isInput) {
855 boundElement.val(displayColor);
856 }
857
858 if (fireCallback && hasChanged) {
859 callbacks.change(color);
860 boundElement.trigger('change', [ color ]);
861 }
862 }
863
864 function reflow() {
865 dragWidth = dragger.width();
866 dragHeight = dragger.height();
867 dragHelperHeight = dragHelper.height();
868 slideWidth = slider.width();
869 slideHeight = slider.height();
870 slideHelperHeight = slideHelper.height();
871 alphaWidth = alphaSlider.width();
872 alphaSlideHelperWidth = alphaSlideHelper.width();
873
874 if (!flat) {
875 container.css("position", "absolute");
876 if (opts.offset) {
877 container.offset(opts.offset);
878 } else {
879 container.offset(getOffset(container, offsetElement));
880 }
881 }
882
883 updateHelperLocations();
884
885 if (opts.showPalette) {
886 drawPalette();
887 }
888
889 boundElement.trigger('reflow.spectrum');
890 }
891
892 function destroy() {
893 boundElement.show();
894 offsetElement.unbind("click.spectrum touchstart.spectrum");
895 container.remove();
896 replacer.remove();
897 spectrums[spect.id] = null;
898 }
899
900 function option(optionName, optionValue) {
901 if (optionName === undefined) {
902 return $.extend({}, opts);
903 }
904 if (optionValue === undefined) {
905 return opts[optionName];
906 }
907
908 opts[optionName] = optionValue;
909 applyOptions();
910 }
911
912 function enable() {
913 disabled = false;
914 boundElement.attr("disabled", false);
915 offsetElement.removeClass("sp-disabled");
916 }
917
918 function disable() {
919 hide();
920 disabled = true;
921 boundElement.attr("disabled", true);
922 offsetElement.addClass("sp-disabled");
923 }
924
925 function setOffset(coord) {
926 opts.offset = coord;
927 reflow();
928 }
929
930 initialize();
931
932 var spect = {
933 show: show,
934 hide: hide,
935 toggle: toggle,
936 reflow: reflow,
937 option: option,
938 enable: enable,
939 disable: disable,
940 offset: setOffset,
941 set: function (c) {
942 set(c);
943 updateOriginalInput();
944 },
945 get: get,
946 destroy: destroy,
947 container: container
948 };
949
950 spect.id = spectrums.push(spect) - 1;
951
952 return spect;
953 }
954
955 /**
956 * checkOffset - get the offset below/above and left/right element depending on screen position
957 * Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js
958 */
959 function getOffset(picker, input) {
960 var extraY = 0;
961 var dpWidth = picker.outerWidth();
962 var dpHeight = picker.outerHeight();
963 var inputHeight = input.outerHeight();
964 var doc = picker[0].ownerDocument;
965 var docElem = doc.documentElement;
966 var viewWidth = docElem.clientWidth + $(doc).scrollLeft();
967 var viewHeight = docElem.clientHeight + $(doc).scrollTop();
968 var offset = input.offset();
969 offset.top += inputHeight;
970
971 offset.left -=
972 Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
973 Math.abs(offset.left + dpWidth - viewWidth) : 0);
974
975 offset.top -=
976 Math.min(offset.top, ((offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
977 Math.abs(dpHeight + inputHeight - extraY) : extraY));
978
979 return offset;
980 }
981
982 /**
983 * noop - do nothing
984 */
985 function noop() {
986
987 }
988
989 /**
990 * stopPropagation - makes the code only doing this a little easier to read in line
991 */
992 function stopPropagation(e) {
993 e.stopPropagation();
994 }
995
996 /**
997 * Create a function bound to a given object
998 * Thanks to underscore.js
999 */
1000 function bind(func, obj) {
1001 var slice = Array.prototype.slice;
1002 var args = slice.call(arguments, 2);
1003 return function () {
1004 return func.apply(obj, args.concat(slice.call(arguments)));
1005 };
1006 }
1007
1008 /**
1009 * Lightweight drag helper. Handles containment within the element, so that
1010 * when dragging, the x is within [0,element.width] and y is within [0,element.height]
1011 */
1012 function draggable(element, onmove, onstart, onstop) {
1013 onmove = onmove || function () { };
1014 onstart = onstart || function () { };
1015 onstop = onstop || function () { };
1016 var doc = document;
1017 var dragging = false;
1018 var offset = {};
1019 var maxHeight = 0;
1020 var maxWidth = 0;
1021 var hasTouch = ('ontouchstart' in window);
1022
1023 var duringDragEvents = {};
1024 duringDragEvents["selectstart"] = prevent;
1025 duringDragEvents["dragstart"] = prevent;
1026 duringDragEvents["touchmove mousemove"] = move;
1027 duringDragEvents["touchend mouseup"] = stop;
1028
1029 function prevent(e) {
1030 if (e.stopPropagation) {
1031 e.stopPropagation();
1032 }
1033 if (e.preventDefault) {
1034 e.preventDefault();
1035 }
1036 e.returnValue = false;
1037 }
1038
1039 function move(e) {
1040 if (dragging) {
1041 // Mouseup happened outside of window
1042 if (IE && doc.documentMode < 9 && !e.button) {
1043 return stop();
1044 }
1045
1046 var touches = e.originalEvent && e.originalEvent.touches;
1047 var pageX = touches ? touches[0].pageX : e.pageX;
1048 var pageY = touches ? touches[0].pageY : e.pageY;
1049
1050 var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth));
1051 var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight));
1052
1053 if (hasTouch) {
1054 // Stop scrolling in iOS
1055 prevent(e);
1056 }
1057
1058 onmove.apply(element, [dragX, dragY, e]);
1059 }
1060 }
1061
1062 function start(e) {
1063 var rightclick = (e.which) ? (e.which == 3) : (e.button == 2);
1064
1065 if (!rightclick && !dragging) {
1066 if (onstart.apply(element, arguments) !== false) {
1067 dragging = true;
1068 maxHeight = $(element).height();
1069 maxWidth = $(element).width();
1070 offset = $(element).offset();
1071
1072 $(doc).bind(duringDragEvents);
1073 $(doc.body).addClass("sp-dragging");
1074
1075 if (!hasTouch) {
1076 move(e);
1077 }
1078
1079 prevent(e);
1080 }
1081 }
1082 }
1083
1084 function stop() {
1085 if (dragging) {
1086 $(doc).unbind(duringDragEvents);
1087 $(doc.body).removeClass("sp-dragging");
1088 onstop.apply(element, arguments);
1089 }
1090 dragging = false;
1091 }
1092
1093 $(element).bind("touchstart mousedown", start);
1094 }
1095
1096 function throttle(func, wait, debounce) {
1097 var timeout;
1098 return function () {
1099 var context = this, args = arguments;
1100 var throttler = function () {
1101 timeout = null;
1102 func.apply(context, args);
1103 };
1104 if (debounce) clearTimeout(timeout);
1105 if (debounce || !timeout) timeout = setTimeout(throttler, wait);
1106 };
1107 }
1108
1109 /**
1110 * Define a jQuery plugin
1111 */
1112 var dataID = "spectrum.id";
1113 $.fn.spectrum = function (opts, extra) {
1114
1115 if (typeof opts == "string") {
1116
1117 var returnValue = this;
1118 var args = Array.prototype.slice.call( arguments, 1 );
1119
1120 this.each(function () {
1121 var spect = spectrums[$(this).data(dataID)];
1122 if (spect) {
1123 var method = spect[opts];
1124 if (!method) {
1125 throw new Error( "Spectrum: no such method: '" + opts + "'" );
1126 }
1127
1128 if (opts == "get") {
1129 returnValue = spect.get();
1130 }
1131 else if (opts == "container") {
1132 returnValue = spect.container;
1133 }
1134 else if (opts == "option") {
1135 returnValue = spect.option.apply(spect, args);
1136 }
1137 else if (opts == "destroy") {
1138 spect.destroy();
1139 $(this).removeData(dataID);
1140 }
1141 else {
1142 method.apply(spect, args);
1143 }
1144 }
1145 });
1146
1147 return returnValue;
1148 }
1149
1150 // Initializing a new instance of spectrum
1151 return this.spectrum("destroy").each(function () {
1152 var options = $.extend({}, opts, $(this).data());
1153 var spect = spectrum(this, options);
1154 $(this).data(dataID, spect.id);
1155 });
1156 };
1157
1158 $.fn.spectrum.load = true;
1159 $.fn.spectrum.loadOpts = {};
1160 $.fn.spectrum.draggable = draggable;
1161 $.fn.spectrum.defaults = defaultOpts;
1162
1163 $.spectrum = { };
1164 $.spectrum.localization = { };
1165 $.spectrum.palettes = { };
1166
1167 $.fn.spectrum.processNativeColorInputs = function () {
1168 if (!inputTypeColorSupport) {
1169 $("input[type=color]").spectrum({
1170 preferredFormat: "hex6"
1171 });
1172 }
1173 };
1174
1175 // TinyColor v1.1.1
1176 // https://github.com/bgrins/TinyColor
1177 // Brian Grinstead, MIT License
1178
1179 (function() {
1180
1181 var trimLeft = /^[\s,#]+/,
1182 trimRight = /\s+$/,
1183 tinyCounter = 0,
1184 math = Math,
1185 mathRound = math.round,
1186 mathMin = math.min,
1187 mathMax = math.max,
1188 mathRandom = math.random;
1189
1190 var tinycolor = function tinycolor (color, opts) {
1191
1192 color = (color) ? color : '';
1193 opts = opts || { };
1194
1195 // If input is already a tinycolor, return itself
1196 if (color instanceof tinycolor) {
1197 return color;
1198 }
1199 // If we are called as a function, call using new instead
1200 if (!(this instanceof tinycolor)) {
1201 return new tinycolor(color, opts);
1202 }
1203
1204 var rgb = inputToRGB(color);
1205 this._originalInput = color,
1206 this._r = rgb.r,
1207 this._g = rgb.g,
1208 this._b = rgb.b,
1209 this._a = rgb.a,
1210 this._roundA = mathRound(100*this._a) / 100,
1211 this._format = opts.format || rgb.format;
1212 this._gradientType = opts.gradientType;
1213
1214 // Don't let the range of [0,255] come back in [0,1].
1215 // Potentially lose a little bit of precision here, but will fix issues where
1216 // .5 gets interpreted as half of the total, instead of half of 1
1217 // If it was supposed to be 128, this was already taken care of by `inputToRgb`
1218 if (this._r < 1) { this._r = mathRound(this._r); }
1219 if (this._g < 1) { this._g = mathRound(this._g); }
1220 if (this._b < 1) { this._b = mathRound(this._b); }
1221
1222 this._ok = rgb.ok;
1223 this._tc_id = tinyCounter++;
1224 };
1225
1226 tinycolor.prototype = {
1227 isDark: function() {
1228 return this.getBrightness() < 128;
1229 },
1230 isLight: function() {
1231 return !this.isDark();
1232 },
1233 isValid: function() {
1234 return this._ok;
1235 },
1236 getOriginalInput: function() {
1237 return this._originalInput;
1238 },
1239 getFormat: function() {
1240 return this._format;
1241 },
1242 getAlpha: function() {
1243 return this._a;
1244 },
1245 getBrightness: function() {
1246 var rgb = this.toRgb();
1247 return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
1248 },
1249 setAlpha: function(value) {
1250 this._a = boundAlpha(value);
1251 this._roundA = mathRound(100*this._a) / 100;
1252 return this;
1253 },
1254 toHsv: function() {
1255 var hsv = rgbToHsv(this._r, this._g, this._b);
1256 return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
1257 },
1258 toHsvString: function() {
1259 var hsv = rgbToHsv(this._r, this._g, this._b);
1260 var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
1261 return (this._a == 1) ?
1262 "hsv(" + h + ", " + s + "%, " + v + "%)" :
1263 "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
1264 },
1265 toHsl: function() {
1266 var hsl = rgbToHsl(this._r, this._g, this._b);
1267 return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
1268 },
1269 toHslString: function() {
1270 var hsl = rgbToHsl(this._r, this._g, this._b);
1271 var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
1272 return (this._a == 1) ?
1273 "hsl(" + h + ", " + s + "%, " + l + "%)" :
1274 "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
1275 },
1276 toHex: function(allow3Char) {
1277 return rgbToHex(this._r, this._g, this._b, allow3Char);
1278 },
1279 toHexString: function(allow3Char) {
1280 return '#' + this.toHex(allow3Char);
1281 },
1282 toHex8: function() {
1283 return rgbaToHex(this._r, this._g, this._b, this._a);
1284 },
1285 toHex8String: function() {
1286 return '#' + this.toHex8();
1287 },
1288 toRgb: function() {
1289 return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
1290 },
1291 toRgbString: function() {
1292 return (this._a == 1) ?
1293 "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
1294 "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
1295 },
1296 toPercentageRgb: function() {
1297 return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
1298 },
1299 toPercentageRgbString: function() {
1300 return (this._a == 1) ?
1301 "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
1302 "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
1303 },
1304 toName: function() {
1305 if (this._a === 0) {
1306 return "transparent";
1307 }
1308
1309 if (this._a < 1) {
1310 return false;
1311 }
1312
1313 return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
1314 },
1315 toFilter: function(secondColor) {
1316 var hex8String = '#' + rgbaToHex(this._r, this._g, this._b, this._a);
1317 var secondHex8String = hex8String;
1318 var gradientType = this._gradientType ? "GradientType = 1, " : "";
1319
1320 if (secondColor) {
1321 var s = tinycolor(secondColor);
1322 secondHex8String = s.toHex8String();
1323 }
1324
1325 return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
1326 },
1327 toString: function(format) {
1328 var formatSet = !!format;
1329 format = format || this._format;
1330
1331 var formattedString = false;
1332 var hasAlpha = this._a < 1 && this._a >= 0;
1333 var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name");
1334
1335 if (needsAlphaFormat) {
1336 // Special case for "transparent", all other non-alpha formats
1337 // will return rgba when there is transparency.
1338 if (format === "name" && this._a === 0) {
1339 return this.toName();
1340 }
1341 return this.toRgbString();
1342 }
1343 if (format === "rgb") {
1344 formattedString = this.toRgbString();
1345 }
1346 if (format === "prgb") {
1347 formattedString = this.toPercentageRgbString();
1348 }
1349 if (format === "hex" || format === "hex6") {
1350 formattedString = this.toHexString();
1351 }
1352 if (format === "hex3") {
1353 formattedString = this.toHexString(true);
1354 }
1355 if (format === "hex8") {
1356 formattedString = this.toHex8String();
1357 }
1358 if (format === "name") {
1359 formattedString = this.toName();
1360 }
1361 if (format === "hsl") {
1362 formattedString = this.toHslString();
1363 }
1364 if (format === "hsv") {
1365 formattedString = this.toHsvString();
1366 }
1367
1368 return formattedString || this.toHexString();
1369 },
1370
1371 _applyModification: function(fn, args) {
1372 var color = fn.apply(null, [this].concat([].slice.call(args)));
1373 this._r = color._r;
1374 this._g = color._g;
1375 this._b = color._b;
1376 this.setAlpha(color._a);
1377 return this;
1378 },
1379 lighten: function() {
1380 return this._applyModification(lighten, arguments);
1381 },
1382 brighten: function() {
1383 return this._applyModification(brighten, arguments);
1384 },
1385 darken: function() {
1386 return this._applyModification(darken, arguments);
1387 },
1388 desaturate: function() {
1389 return this._applyModification(desaturate, arguments);
1390 },
1391 saturate: function() {
1392 return this._applyModification(saturate, arguments);
1393 },
1394 greyscale: function() {
1395 return this._applyModification(greyscale, arguments);
1396 },
1397 spin: function() {
1398 return this._applyModification(spin, arguments);
1399 },
1400
1401 _applyCombination: function(fn, args) {
1402 return fn.apply(null, [this].concat([].slice.call(args)));
1403 },
1404 analogous: function() {
1405 return this._applyCombination(analogous, arguments);
1406 },
1407 complement: function() {
1408 return this._applyCombination(complement, arguments);
1409 },
1410 monochromatic: function() {
1411 return this._applyCombination(monochromatic, arguments);
1412 },
1413 splitcomplement: function() {
1414 return this._applyCombination(splitcomplement, arguments);
1415 },
1416 triad: function() {
1417 return this._applyCombination(triad, arguments);
1418 },
1419 tetrad: function() {
1420 return this._applyCombination(tetrad, arguments);
1421 }
1422 };
1423
1424 // If input is an object, force 1 into "1.0" to handle ratios properly
1425 // String input requires "1.0" as input, so 1 will be treated as 1
1426 tinycolor.fromRatio = function(color, opts) {
1427 if (typeof color == "object") {
1428 var newColor = {};
1429 for (var i in color) {
1430 if (color.hasOwnProperty(i)) {
1431 if (i === "a") {
1432 newColor[i] = color[i];
1433 }
1434 else {
1435 newColor[i] = convertToPercentage(color[i]);
1436 }
1437 }
1438 }
1439 color = newColor;
1440 }
1441
1442 return tinycolor(color, opts);
1443 };
1444
1445 // Given a string or object, convert that input to RGB
1446 // Possible string inputs:
1447 //
1448 // "red"
1449 // "#f00" or "f00"
1450 // "#ff0000" or "ff0000"
1451 // "#ff000000" or "ff000000"
1452 // "rgb 255 0 0" or "rgb (255, 0, 0)"
1453 // "rgb 1.0 0 0" or "rgb (1, 0, 0)"
1454 // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
1455 // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
1456 // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
1457 // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
1458 // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
1459 //
1460 function inputToRGB(color) {
1461
1462 var rgb = { r: 0, g: 0, b: 0 };
1463 var a = 1;
1464 var ok = false;
1465 var format = false;
1466
1467 if (typeof color == "string") {
1468 color = stringInputToObject(color);
1469 }
1470
1471 if (typeof color == "object") {
1472 if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) {
1473 rgb = rgbToRgb(color.r, color.g, color.b);
1474 ok = true;
1475 format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
1476 }
1477 else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) {
1478 color.s = convertToPercentage(color.s);
1479 color.v = convertToPercentage(color.v);
1480 rgb = hsvToRgb(color.h, color.s, color.v);
1481 ok = true;
1482 format = "hsv";
1483 }
1484 else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) {
1485 color.s = convertToPercentage(color.s);
1486 color.l = convertToPercentage(color.l);
1487 rgb = hslToRgb(color.h, color.s, color.l);
1488 ok = true;
1489 format = "hsl";
1490 }
1491
1492 if (color.hasOwnProperty("a")) {
1493 a = color.a;
1494 }
1495 }
1496
1497 a = boundAlpha(a);
1498
1499 return {
1500 ok: ok,
1501 format: color.format || format,
1502 r: mathMin(255, mathMax(rgb.r, 0)),
1503 g: mathMin(255, mathMax(rgb.g, 0)),
1504 b: mathMin(255, mathMax(rgb.b, 0)),
1505 a: a
1506 };
1507 }
1508
1509
1510 // Conversion Functions
1511 // --------------------
1512
1513 // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
1514 // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
1515
1516 // `rgbToRgb`
1517 // Handle bounds / percentage checking to conform to CSS color spec
1518 // <http://www.w3.org/TR/css3-color/>
1519 // *Assumes:* r, g, b in [0, 255] or [0, 1]
1520 // *Returns:* { r, g, b } in [0, 255]
1521 function rgbToRgb(r, g, b){
1522 return {
1523 r: bound01(r, 255) * 255,
1524 g: bound01(g, 255) * 255,
1525 b: bound01(b, 255) * 255
1526 };
1527 }
1528
1529 // `rgbToHsl`
1530 // Converts an RGB color value to HSL.
1531 // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
1532 // *Returns:* { h, s, l } in [0,1]
1533 function rgbToHsl(r, g, b) {
1534
1535 r = bound01(r, 255);
1536 g = bound01(g, 255);
1537 b = bound01(b, 255);
1538
1539 var max = mathMax(r, g, b), min = mathMin(r, g, b);
1540 var h, s, l = (max + min) / 2;
1541
1542 if(max == min) {
1543 h = s = 0; // achromatic
1544 }
1545 else {
1546 var d = max - min;
1547 s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
1548 switch(max) {
1549 case r: h = (g - b) / d + (g < b ? 6 : 0); break;
1550 case g: h = (b - r) / d + 2; break;
1551 case b: h = (r - g) / d + 4; break;
1552 }
1553
1554 h /= 6;
1555 }
1556
1557 return { h: h, s: s, l: l };
1558 }
1559
1560 // `hslToRgb`
1561 // Converts an HSL color value to RGB.
1562 // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
1563 // *Returns:* { r, g, b } in the set [0, 255]
1564 function hslToRgb(h, s, l) {
1565 var r, g, b;
1566
1567 h = bound01(h, 360);
1568 s = bound01(s, 100);
1569 l = bound01(l, 100);
1570
1571 function hue2rgb(p, q, t) {
1572 if(t < 0) t += 1;
1573 if(t > 1) t -= 1;
1574 if(t < 1/6) return p + (q - p) * 6 * t;
1575 if(t < 1/2) return q;
1576 if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
1577 return p;
1578 }
1579
1580 if(s === 0) {
1581 r = g = b = l; // achromatic
1582 }
1583 else {
1584 var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
1585 var p = 2 * l - q;
1586 r = hue2rgb(p, q, h + 1/3);
1587 g = hue2rgb(p, q, h);
1588 b = hue2rgb(p, q, h - 1/3);
1589 }
1590
1591 return { r: r * 255, g: g * 255, b: b * 255 };
1592 }
1593
1594 // `rgbToHsv`
1595 // Converts an RGB color value to HSV
1596 // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
1597 // *Returns:* { h, s, v } in [0,1]
1598 function rgbToHsv(r, g, b) {
1599
1600 r = bound01(r, 255);
1601 g = bound01(g, 255);
1602 b = bound01(b, 255);
1603
1604 var max = mathMax(r, g, b), min = mathMin(r, g, b);
1605 var h, s, v = max;
1606
1607 var d = max - min;
1608 s = max === 0 ? 0 : d / max;
1609
1610 if(max == min) {
1611 h = 0; // achromatic
1612 }
1613 else {
1614 switch(max) {
1615 case r: h = (g - b) / d + (g < b ? 6 : 0); break;
1616 case g: h = (b - r) / d + 2; break;
1617 case b: h = (r - g) / d + 4; break;
1618 }
1619 h /= 6;
1620 }
1621 return { h: h, s: s, v: v };
1622 }
1623
1624 // `hsvToRgb`
1625 // Converts an HSV color value to RGB.
1626 // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
1627 // *Returns:* { r, g, b } in the set [0, 255]
1628 function hsvToRgb(h, s, v) {
1629
1630 h = bound01(h, 360) * 6;
1631 s = bound01(s, 100);
1632 v = bound01(v, 100);
1633
1634 var i = math.floor(h),
1635 f = h - i,
1636 p = v * (1 - s),
1637 q = v * (1 - f * s),
1638 t = v * (1 - (1 - f) * s),
1639 mod = i % 6,
1640 r = [v, q, p, p, t, v][mod],
1641 g = [t, v, v, q, p, p][mod],
1642 b = [p, p, t, v, v, q][mod];
1643
1644 return { r: r * 255, g: g * 255, b: b * 255 };
1645 }
1646
1647 // `rgbToHex`
1648 // Converts an RGB color to hex
1649 // Assumes r, g, and b are contained in the set [0, 255]
1650 // Returns a 3 or 6 character hex
1651 function rgbToHex(r, g, b, allow3Char) {
1652
1653 var hex = [
1654 pad2(mathRound(r).toString(16)),
1655 pad2(mathRound(g).toString(16)),
1656 pad2(mathRound(b).toString(16))
1657 ];
1658
1659 // Return a 3 character hex if possible
1660 if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
1661 return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
1662 }
1663
1664 return hex.join("");
1665 }
1666 // `rgbaToHex`
1667 // Converts an RGBA color plus alpha transparency to hex
1668 // Assumes r, g, b and a are contained in the set [0, 255]
1669 // Returns an 8 character hex
1670 function rgbaToHex(r, g, b, a) {
1671
1672 var hex = [
1673 pad2(convertDecimalToHex(a)),
1674 pad2(mathRound(r).toString(16)),
1675 pad2(mathRound(g).toString(16)),
1676 pad2(mathRound(b).toString(16))
1677 ];
1678
1679 return hex.join("");
1680 }
1681
1682 // `equals`
1683 // Can be called with any tinycolor input
1684 tinycolor.equals = function (color1, color2) {
1685 if (!color1 || !color2) { return false; }
1686 return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
1687 };
1688 tinycolor.random = function() {
1689 return tinycolor.fromRatio({
1690 r: mathRandom(),
1691 g: mathRandom(),
1692 b: mathRandom()
1693 });
1694 };
1695
1696
1697 // Modification Functions
1698 // ----------------------
1699 // Thanks to less.js for some of the basics here
1700 // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>
1701
1702 function desaturate(color, amount) {
1703 amount = (amount === 0) ? 0 : (amount || 10);
1704 var hsl = tinycolor(color).toHsl();
1705 hsl.s -= amount / 100;
1706 hsl.s = clamp01(hsl.s);
1707 return tinycolor(hsl);
1708 }
1709
1710 function saturate(color, amount) {
1711 amount = (amount === 0) ? 0 : (amount || 10);
1712 var hsl = tinycolor(color).toHsl();
1713 hsl.s += amount / 100;
1714 hsl.s = clamp01(hsl.s);
1715 return tinycolor(hsl);
1716 }
1717
1718 function greyscale(color) {
1719 return tinycolor(color).desaturate(100);
1720 }
1721
1722 function lighten (color, amount) {
1723 amount = (amount === 0) ? 0 : (amount || 10);
1724 var hsl = tinycolor(color).toHsl();
1725 hsl.l += amount / 100;
1726 hsl.l = clamp01(hsl.l);
1727 return tinycolor(hsl);
1728 }
1729
1730 function brighten(color, amount) {
1731 amount = (amount === 0) ? 0 : (amount || 10);
1732 var rgb = tinycolor(color).toRgb();
1733 rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
1734 rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
1735 rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
1736 return tinycolor(rgb);
1737 }
1738
1739 function darken (color, amount) {
1740 amount = (amount === 0) ? 0 : (amount || 10);
1741 var hsl = tinycolor(color).toHsl();
1742 hsl.l -= amount / 100;
1743 hsl.l = clamp01(hsl.l);
1744 return tinycolor(hsl);
1745 }
1746
1747 // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
1748 // Values outside of this range will be wrapped into this range.
1749 function spin(color, amount) {
1750 var hsl = tinycolor(color).toHsl();
1751 var hue = (mathRound(hsl.h) + amount) % 360;
1752 hsl.h = hue < 0 ? 360 + hue : hue;
1753 return tinycolor(hsl);
1754 }
1755
1756 // Combination Functions
1757 // ---------------------
1758 // Thanks to jQuery xColor for some of the ideas behind these
1759 // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>
1760
1761 function complement(color) {
1762 var hsl = tinycolor(color).toHsl();
1763 hsl.h = (hsl.h + 180) % 360;
1764 return tinycolor(hsl);
1765 }
1766
1767 function triad(color) {
1768 var hsl = tinycolor(color).toHsl();
1769 var h = hsl.h;
1770 return [
1771 tinycolor(color),
1772 tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
1773 tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
1774 ];
1775 }
1776
1777 function tetrad(color) {
1778 var hsl = tinycolor(color).toHsl();
1779 var h = hsl.h;
1780 return [
1781 tinycolor(color),
1782 tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
1783 tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
1784 tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
1785 ];
1786 }
1787
1788 function splitcomplement(color) {
1789 var hsl = tinycolor(color).toHsl();
1790 var h = hsl.h;
1791 return [
1792 tinycolor(color),
1793 tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
1794 tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
1795 ];
1796 }
1797
1798 function analogous(color, results, slices) {
1799 results = results || 6;
1800 slices = slices || 30;
1801
1802 var hsl = tinycolor(color).toHsl();
1803 var part = 360 / slices;
1804 var ret = [tinycolor(color)];
1805
1806 for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
1807 hsl.h = (hsl.h + part) % 360;
1808 ret.push(tinycolor(hsl));
1809 }
1810 return ret;
1811 }
1812
1813 function monochromatic(color, results) {
1814 results = results || 6;
1815 var hsv = tinycolor(color).toHsv();
1816 var h = hsv.h, s = hsv.s, v = hsv.v;
1817 var ret = [];
1818 var modification = 1 / results;
1819
1820 while (results--) {
1821 ret.push(tinycolor({ h: h, s: s, v: v}));
1822 v = (v + modification) % 1;
1823 }
1824
1825 return ret;
1826 }
1827
1828 // Utility Functions
1829 // ---------------------
1830
1831 tinycolor.mix = function(color1, color2, amount) {
1832 amount = (amount === 0) ? 0 : (amount || 50);
1833
1834 var rgb1 = tinycolor(color1).toRgb();
1835 var rgb2 = tinycolor(color2).toRgb();
1836
1837 var p = amount / 100;
1838 var w = p * 2 - 1;
1839 var a = rgb2.a - rgb1.a;
1840
1841 var w1;
1842
1843 if (w * a == -1) {
1844 w1 = w;
1845 } else {
1846 w1 = (w + a) / (1 + w * a);
1847 }
1848
1849 w1 = (w1 + 1) / 2;
1850
1851 var w2 = 1 - w1;
1852
1853 var rgba = {
1854 r: rgb2.r * w1 + rgb1.r * w2,
1855 g: rgb2.g * w1 + rgb1.g * w2,
1856 b: rgb2.b * w1 + rgb1.b * w2,
1857 a: rgb2.a * p + rgb1.a * (1 - p)
1858 };
1859
1860 return tinycolor(rgba);
1861 };
1862
1863
1864 // Readability Functions
1865 // ---------------------
1866 // <http://www.w3.org/TR/AERT#color-contrast>
1867
1868 // `readability`
1869 // Analyze the 2 colors and returns an object with the following properties:
1870 // `brightness`: difference in brightness between the two colors
1871 // `color`: difference in color/hue between the two colors
1872 tinycolor.readability = function(color1, color2) {
1873 var c1 = tinycolor(color1);
1874 var c2 = tinycolor(color2);
1875 var rgb1 = c1.toRgb();
1876 var rgb2 = c2.toRgb();
1877 var brightnessA = c1.getBrightness();
1878 var brightnessB = c2.getBrightness();
1879 var colorDiff = (
1880 Math.max(rgb1.r, rgb2.r) - Math.min(rgb1.r, rgb2.r) +
1881 Math.max(rgb1.g, rgb2.g) - Math.min(rgb1.g, rgb2.g) +
1882 Math.max(rgb1.b, rgb2.b) - Math.min(rgb1.b, rgb2.b)
1883 );
1884
1885 return {
1886 brightness: Math.abs(brightnessA - brightnessB),
1887 color: colorDiff
1888 };
1889 };
1890
1891 // `readable`
1892 // http://www.w3.org/TR/AERT#color-contrast
1893 // Ensure that foreground and background color combinations provide sufficient contrast.
1894 // *Example*
1895 // tinycolor.isReadable("#000", "#111") => false
1896 tinycolor.isReadable = function(color1, color2) {
1897 var readability = tinycolor.readability(color1, color2);
1898 return readability.brightness > 125 && readability.color > 500;
1899 };
1900
1901 // `mostReadable`
1902 // Given a base color and a list of possible foreground or background
1903 // colors for that base, returns the most readable color.
1904 // *Example*
1905 // tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000"
1906 tinycolor.mostReadable = function(baseColor, colorList) {
1907 var bestColor = null;
1908 var bestScore = 0;
1909 var bestIsReadable = false;
1910 for (var i=0; i < colorList.length; i++) {
1911
1912 // We normalize both around the "acceptable" breaking point,
1913 // but rank brightness constrast higher than hue.
1914
1915 var readability = tinycolor.readability(baseColor, colorList[i]);
1916 var readable = readability.brightness > 125 && readability.color > 500;
1917 var score = 3 * (readability.brightness / 125) + (readability.color / 500);
1918
1919 if ((readable && ! bestIsReadable) ||
1920 (readable && bestIsReadable && score > bestScore) ||
1921 ((! readable) && (! bestIsReadable) && score > bestScore)) {
1922 bestIsReadable = readable;
1923 bestScore = score;
1924 bestColor = tinycolor(colorList[i]);
1925 }
1926 }
1927 return bestColor;
1928 };
1929
1930
1931 // Big List of Colors
1932 // ------------------
1933 // <http://www.w3.org/TR/css3-color/#svg-color>
1934 var names = tinycolor.names = {
1935 aliceblue: "f0f8ff",
1936 antiquewhite: "faebd7",
1937 aqua: "0ff",
1938 aquamarine: "7fffd4",
1939 azure: "f0ffff",
1940 beige: "f5f5dc",
1941 bisque: "ffe4c4",
1942 black: "000",
1943 blanchedalmond: "ffebcd",
1944 blue: "00f",
1945 blueviolet: "8a2be2",
1946 brown: "a52a2a",
1947 burlywood: "deb887",
1948 burntsienna: "ea7e5d",
1949 cadetblue: "5f9ea0",
1950 chartreuse: "7fff00",
1951 chocolate: "d2691e",
1952 coral: "ff7f50",
1953 cornflowerblue: "6495ed",
1954 cornsilk: "fff8dc",
1955 crimson: "dc143c",
1956 cyan: "0ff",
1957 darkblue: "00008b",
1958 darkcyan: "008b8b",
1959 darkgoldenrod: "b8860b",
1960 darkgray: "a9a9a9",
1961 darkgreen: "006400",
1962 darkgrey: "a9a9a9",
1963 darkkhaki: "bdb76b",
1964 darkmagenta: "8b008b",
1965 darkolivegreen: "556b2f",
1966 darkorange: "ff8c00",
1967 darkorchid: "9932cc",
1968 darkred: "8b0000",
1969 darksalmon: "e9967a",
1970 darkseagreen: "8fbc8f",
1971 darkslateblue: "483d8b",
1972 darkslategray: "2f4f4f",
1973 darkslategrey: "2f4f4f",
1974 darkturquoise: "00ced1",
1975 darkviolet: "9400d3",
1976 deeppink: "ff1493",
1977 deepskyblue: "00bfff",
1978 dimgray: "696969",
1979 dimgrey: "696969",
1980 dodgerblue: "1e90ff",
1981 firebrick: "b22222",
1982 floralwhite: "fffaf0",
1983 forestgreen: "228b22",
1984 fuchsia: "f0f",
1985 gainsboro: "dcdcdc",
1986 ghostwhite: "f8f8ff",
1987 gold: "ffd700",
1988 goldenrod: "daa520",
1989 gray: "808080",
1990 green: "008000",
1991 greenyellow: "adff2f",
1992 grey: "808080",
1993 honeydew: "f0fff0",
1994 hotpink: "ff69b4",
1995 indianred: "cd5c5c",
1996 indigo: "4b0082",
1997 ivory: "fffff0",
1998 khaki: "f0e68c",
1999 lavender: "e6e6fa",
2000 lavenderblush: "fff0f5",
2001 lawngreen: "7cfc00",
2002 lemonchiffon: "fffacd",
2003 lightblue: "add8e6",
2004 lightcoral: "f08080",
2005 lightcyan: "e0ffff",
2006 lightgoldenrodyellow: "fafad2",
2007 lightgray: "d3d3d3",
2008 lightgreen: "90ee90",
2009 lightgrey: "d3d3d3",
2010 lightpink: "ffb6c1",
2011 lightsalmon: "ffa07a",
2012 lightseagreen: "20b2aa",
2013 lightskyblue: "87cefa",
2014 lightslategray: "789",
2015 lightslategrey: "789",
2016 lightsteelblue: "b0c4de",
2017 lightyellow: "ffffe0",
2018 lime: "0f0",
2019 limegreen: "32cd32",
2020 linen: "faf0e6",
2021 magenta: "f0f",
2022 maroon: "800000",
2023 mediumaquamarine: "66cdaa",
2024 mediumblue: "0000cd",
2025 mediumorchid: "ba55d3",
2026 mediumpurple: "9370db",
2027 mediumseagreen: "3cb371",
2028 mediumslateblue: "7b68ee",
2029 mediumspringgreen: "00fa9a",
2030 mediumturquoise: "48d1cc",
2031 mediumvioletred: "c71585",
2032 midnightblue: "191970",
2033 mintcream: "f5fffa",
2034 mistyrose: "ffe4e1",
2035 moccasin: "ffe4b5",
2036 navajowhite: "ffdead",
2037 navy: "000080",
2038 oldlace: "fdf5e6",
2039 olive: "808000",
2040 olivedrab: "6b8e23",
2041 orange: "ffa500",
2042 orangered: "ff4500",
2043 orchid: "da70d6",
2044 palegoldenrod: "eee8aa",
2045 palegreen: "98fb98",
2046 paleturquoise: "afeeee",
2047 palevioletred: "db7093",
2048 papayawhip: "ffefd5",
2049 peachpuff: "ffdab9",
2050 peru: "cd853f",
2051 pink: "ffc0cb",
2052 plum: "dda0dd",
2053 powderblue: "b0e0e6",
2054 purple: "800080",
2055 rebeccapurple: "663399",
2056 red: "f00",
2057 rosybrown: "bc8f8f",
2058 royalblue: "4169e1",
2059 saddlebrown: "8b4513",
2060 salmon: "fa8072",
2061 sandybrown: "f4a460",
2062 seagreen: "2e8b57",
2063 seashell: "fff5ee",
2064 sienna: "a0522d",
2065 silver: "c0c0c0",
2066 skyblue: "87ceeb",
2067 slateblue: "6a5acd",
2068 slategray: "708090",
2069 slategrey: "708090",
2070 snow: "fffafa",
2071 springgreen: "00ff7f",
2072 steelblue: "4682b4",
2073 tan: "d2b48c",
2074 teal: "008080",
2075 thistle: "d8bfd8",
2076 tomato: "ff6347",
2077 turquoise: "40e0d0",
2078 violet: "ee82ee",
2079 wheat: "f5deb3",
2080 white: "fff",
2081 whitesmoke: "f5f5f5",
2082 yellow: "ff0",
2083 yellowgreen: "9acd32"
2084 };
2085
2086 // Make it easy to access colors via `hexNames[hex]`
2087 var hexNames = tinycolor.hexNames = flip(names);
2088
2089
2090 // Utilities
2091 // ---------
2092
2093 // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
2094 function flip(o) {
2095 var flipped = { };
2096 for (var i in o) {
2097 if (o.hasOwnProperty(i)) {
2098 flipped[o[i]] = i;
2099 }
2100 }
2101 return flipped;
2102 }
2103
2104 // Return a valid alpha value [0,1] with all invalid values being set to 1
2105 function boundAlpha(a) {
2106 a = parseFloat(a);
2107
2108 if (isNaN(a) || a < 0 || a > 1) {
2109 a = 1;
2110 }
2111
2112 return a;
2113 }
2114
2115 // Take input from [0, n] and return it as [0, 1]
2116 function bound01(n, max) {
2117 if (isOnePointZero(n)) { n = "100%"; }
2118
2119 var processPercent = isPercentage(n);
2120 n = mathMin(max, mathMax(0, parseFloat(n)));
2121
2122 // Automatically convert percentage into number
2123 if (processPercent) {
2124 n = parseInt(n * max, 10) / 100;
2125 }
2126
2127 // Handle floating point rounding errors
2128 if ((math.abs(n - max) < 0.000001)) {
2129 return 1;
2130 }
2131
2132 // Convert into [0, 1] range if it isn't already
2133 return (n % max) / parseFloat(max);
2134 }
2135
2136 // Force a number between 0 and 1
2137 function clamp01(val) {
2138 return mathMin(1, mathMax(0, val));
2139 }
2140
2141 // Parse a base-16 hex value into a base-10 integer
2142 function parseIntFromHex(val) {
2143 return parseInt(val, 16);
2144 }
2145
2146 // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
2147 // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
2148 function isOnePointZero(n) {
2149 return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
2150 }
2151
2152 // Check to see if string passed in is a percentage
2153 function isPercentage(n) {
2154 return typeof n === "string" && n.indexOf('%') != -1;
2155 }
2156
2157 // Force a hex value to have 2 characters
2158 function pad2(c) {
2159 return c.length == 1 ? '0' + c : '' + c;
2160 }
2161
2162 // Replace a decimal with it's percentage value
2163 function convertToPercentage(n) {
2164 if (n <= 1) {
2165 n = (n * 100) + "%";
2166 }
2167
2168 return n;
2169 }
2170
2171 // Converts a decimal to a hex value
2172 function convertDecimalToHex(d) {
2173 return Math.round(parseFloat(d) * 255).toString(16);
2174 }
2175 // Converts a hex value to a decimal
2176 function convertHexToDecimal(h) {
2177 return (parseIntFromHex(h) / 255);
2178 }
2179
2180 var matchers = (function() {
2181
2182 // <http://www.w3.org/TR/css3-values/#integers>
2183 var CSS_INTEGER = "[-\\+]?\\d+%?";
2184
2185 // <http://www.w3.org/TR/css3-values/#number-value>
2186 var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
2187
2188 // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
2189 var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
2190
2191 // Actual matching.
2192 // Parentheses and commas are optional, but not required.
2193 // Whitespace can take the place of commas or opening paren
2194 var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
2195 var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
2196
2197 return {
2198 rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
2199 rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
2200 hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
2201 hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
2202 hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
2203 hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
2204 hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
2205 hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
2206 hex8: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
2207 };
2208 })();
2209
2210 // `stringInputToObject`
2211 // Permissive string parsing. Take in a number of formats, and output an object
2212 // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
2213 function stringInputToObject(color) {
2214
2215 color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
2216 var named = false;
2217 if (names[color]) {
2218 color = names[color];
2219 named = true;
2220 }
2221 else if (color == 'transparent') {
2222 return { r: 0, g: 0, b: 0, a: 0, format: "name" };
2223 }
2224
2225 // Try to match string input using regular expressions.
2226 // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
2227 // Just return an object and let the conversion functions handle that.
2228 // This way the result will be the same whether the tinycolor is initialized with string or object.
2229 var match;
2230 if ((match = matchers.rgb.exec(color))) {
2231 return { r: match[1], g: match[2], b: match[3] };
2232 }
2233 if ((match = matchers.rgba.exec(color))) {
2234 return { r: match[1], g: match[2], b: match[3], a: match[4] };
2235 }
2236 if ((match = matchers.hsl.exec(color))) {
2237 return { h: match[1], s: match[2], l: match[3] };
2238 }
2239 if ((match = matchers.hsla.exec(color))) {
2240 return { h: match[1], s: match[2], l: match[3], a: match[4] };
2241 }
2242 if ((match = matchers.hsv.exec(color))) {
2243 return { h: match[1], s: match[2], v: match[3] };
2244 }
2245 if ((match = matchers.hsva.exec(color))) {
2246 return { h: match[1], s: match[2], v: match[3], a: match[4] };
2247 }
2248 if ((match = matchers.hex8.exec(color))) {
2249 return {
2250 a: convertHexToDecimal(match[1]),
2251 r: parseIntFromHex(match[2]),
2252 g: parseIntFromHex(match[3]),
2253 b: parseIntFromHex(match[4]),
2254 format: named ? "name" : "hex8"
2255 };
2256 }
2257 if ((match = matchers.hex6.exec(color))) {
2258 return {
2259 r: parseIntFromHex(match[1]),
2260 g: parseIntFromHex(match[2]),
2261 b: parseIntFromHex(match[3]),
2262 format: named ? "name" : "hex"
2263 };
2264 }
2265 if ((match = matchers.hex3.exec(color))) {
2266 return {
2267 r: parseIntFromHex(match[1] + '' + match[1]),
2268 g: parseIntFromHex(match[2] + '' + match[2]),
2269 b: parseIntFromHex(match[3] + '' + match[3]),
2270 format: named ? "name" : "hex"
2271 };
2272 }
2273
2274 return false;
2275 }
2276
2277 window.tinycolor = tinycolor;
2278 })();
2279
2280
2281 $(function () {
2282 if ($.fn.spectrum.load) {
2283 $.fn.spectrum.processNativeColorInputs();
2284 }
2285 });
2286
2287});
Note: See TracBrowser for help on using the repository browser.