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