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