Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

2338 строки
82 KiB

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