You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2323 lines
77 KiB

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