spectrum.js 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324
  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 id = this[dataID];
  968. var spect = spectrums[id];
  969. if (spect) {
  970. var method = spect[opts];
  971. if (!method) {
  972. throw new Error( "Spectrum: no such method: '" + opts + "'" );
  973. }
  974. if (opts == "get") {
  975. returnValue = spect.get();
  976. }
  977. else if (opts == "container") {
  978. returnValue = spect.container;
  979. }
  980. else if (opts == "option") {
  981. returnValue = spect.option.apply(spect, args);
  982. }
  983. else if (opts == "destroy") {
  984. spect.destroy();
  985. this[dataID] = undefined;
  986. }
  987. else {
  988. method.apply(spect, args);
  989. }
  990. }
  991. });
  992. return returnValue;
  993. }
  994. // Initializing a new instance of spectrum
  995. return this.spectrum("destroy").each(function () {
  996. var options = $.extend({}, opts, $(this).data());
  997. var spect = spectrum(this, options);
  998. this[dataID] = spect.id;
  999. });
  1000. };
  1001. $.fn.spectrum.load = true;
  1002. $.fn.spectrum.loadOpts = {};
  1003. $.fn.spectrum.draggable = draggable;
  1004. $.fn.spectrum.defaults = defaultOpts;
  1005. $.fn.spectrum.inputTypeColorSupport = function inputTypeColorSupport() {
  1006. if (typeof inputTypeColorSupport._cachedResult === "undefined") {
  1007. var colorInput = $("<input type='color'/>")[0]; // if color element is supported, value will default to not null
  1008. inputTypeColorSupport._cachedResult = colorInput.type === "color" && colorInput.value !== "";
  1009. }
  1010. return inputTypeColorSupport._cachedResult;
  1011. };
  1012. $.spectrum = { };
  1013. $.spectrum.localization = { };
  1014. $.spectrum.palettes = { };
  1015. $.fn.spectrum.processNativeColorInputs = function () {
  1016. var colorInputs = $("input[type=color]");
  1017. if (colorInputs.length && !inputTypeColorSupport()) {
  1018. colorInputs.spectrum({
  1019. preferredFormat: "hex6"
  1020. });
  1021. }
  1022. };
  1023. // TinyColor v1.1.2
  1024. // https://github.com/bgrins/TinyColor
  1025. // Brian Grinstead, MIT License
  1026. (function() {
  1027. var trimLeft = /^[\s,#]+/,
  1028. trimRight = /\s+$/,
  1029. tinyCounter = 0,
  1030. math = Math,
  1031. mathRound = math.round,
  1032. mathMin = math.min,
  1033. mathMax = math.max,
  1034. mathRandom = math.random;
  1035. var tinycolor = function(color, opts) {
  1036. color = (color) ? color : '';
  1037. opts = opts || { };
  1038. // If input is already a tinycolor, return itself
  1039. if (color instanceof tinycolor) {
  1040. return color;
  1041. }
  1042. // If we are called as a function, call using new instead
  1043. if (!(this instanceof tinycolor)) {
  1044. return new tinycolor(color, opts);
  1045. }
  1046. var rgb = inputToRGB(color);
  1047. this._originalInput = color,
  1048. this._r = rgb.r,
  1049. this._g = rgb.g,
  1050. this._b = rgb.b,
  1051. this._a = rgb.a,
  1052. this._roundA = mathRound(100*this._a) / 100,
  1053. this._format = opts.format || rgb.format;
  1054. this._gradientType = opts.gradientType;
  1055. // Don't let the range of [0,255] come back in [0,1].
  1056. // Potentially lose a little bit of precision here, but will fix issues where
  1057. // .5 gets interpreted as half of the total, instead of half of 1
  1058. // If it was supposed to be 128, this was already taken care of by `inputToRgb`
  1059. if (this._r < 1) { this._r = mathRound(this._r); }
  1060. if (this._g < 1) { this._g = mathRound(this._g); }
  1061. if (this._b < 1) { this._b = mathRound(this._b); }
  1062. this._ok = rgb.ok;
  1063. this._tc_id = tinyCounter++;
  1064. };
  1065. tinycolor.prototype = {
  1066. isDark: function() {
  1067. return this.getBrightness() < 128;
  1068. },
  1069. isLight: function() {
  1070. return !this.isDark();
  1071. },
  1072. isValid: function() {
  1073. return this._ok;
  1074. },
  1075. getOriginalInput: function() {
  1076. return this._originalInput;
  1077. },
  1078. getFormat: function() {
  1079. return this._format;
  1080. },
  1081. getAlpha: function() {
  1082. return this._a;
  1083. },
  1084. getBrightness: function() {
  1085. var rgb = this.toRgb();
  1086. return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
  1087. },
  1088. setAlpha: function(value) {
  1089. this._a = boundAlpha(value);
  1090. this._roundA = mathRound(100*this._a) / 100;
  1091. return this;
  1092. },
  1093. toHsv: function() {
  1094. var hsv = rgbToHsv(this._r, this._g, this._b);
  1095. return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
  1096. },
  1097. toHsvString: function() {
  1098. var hsv = rgbToHsv(this._r, this._g, this._b);
  1099. var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
  1100. return (this._a == 1) ?
  1101. "hsv(" + h + ", " + s + "%, " + v + "%)" :
  1102. "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
  1103. },
  1104. toHsl: function() {
  1105. var hsl = rgbToHsl(this._r, this._g, this._b);
  1106. return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
  1107. },
  1108. toHslString: function() {
  1109. var hsl = rgbToHsl(this._r, this._g, this._b);
  1110. var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
  1111. return (this._a == 1) ?
  1112. "hsl(" + h + ", " + s + "%, " + l + "%)" :
  1113. "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
  1114. },
  1115. toHex: function(allow3Char) {
  1116. return rgbToHex(this._r, this._g, this._b, allow3Char);
  1117. },
  1118. toHexString: function(allow3Char) {
  1119. return '#' + this.toHex(allow3Char);
  1120. },
  1121. toHex8: function() {
  1122. return rgbaToHex(this._r, this._g, this._b, this._a);
  1123. },
  1124. toHex8String: function() {
  1125. return '#' + this.toHex8();
  1126. },
  1127. toRgb: function() {
  1128. return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
  1129. },
  1130. toRgbString: function() {
  1131. return (this._a == 1) ?
  1132. "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
  1133. "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
  1134. },
  1135. toPercentageRgb: function() {
  1136. 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 };
  1137. },
  1138. toPercentageRgbString: function() {
  1139. return (this._a == 1) ?
  1140. "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
  1141. "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
  1142. },
  1143. toName: function() {
  1144. if (this._a === 0) {
  1145. return "transparent";
  1146. }
  1147. if (this._a < 1) {
  1148. return false;
  1149. }
  1150. return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
  1151. },
  1152. toFilter: function(secondColor) {
  1153. var hex8String = '#' + rgbaToHex(this._r, this._g, this._b, this._a);
  1154. var secondHex8String = hex8String;
  1155. var gradientType = this._gradientType ? "GradientType = 1, " : "";
  1156. if (secondColor) {
  1157. var s = tinycolor(secondColor);
  1158. secondHex8String = s.toHex8String();
  1159. }
  1160. return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
  1161. },
  1162. toString: function(format) {
  1163. var formatSet = !!format;
  1164. format = format || this._format;
  1165. var formattedString = false;
  1166. var hasAlpha = this._a < 1 && this._a >= 0;
  1167. var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name");
  1168. if (needsAlphaFormat) {
  1169. // Special case for "transparent", all other non-alpha formats
  1170. // will return rgba when there is transparency.
  1171. if (format === "name" && this._a === 0) {
  1172. return this.toName();
  1173. }
  1174. return this.toRgbString();
  1175. }
  1176. if (format === "rgb") {
  1177. formattedString = this.toRgbString();
  1178. }
  1179. if (format === "prgb") {
  1180. formattedString = this.toPercentageRgbString();
  1181. }
  1182. if (format === "hex" || format === "hex6") {
  1183. formattedString = this.toHexString();
  1184. }
  1185. if (format === "hex3") {
  1186. formattedString = this.toHexString(true);
  1187. }
  1188. if (format === "hex8") {
  1189. formattedString = this.toHex8String();
  1190. }
  1191. if (format === "name") {
  1192. formattedString = this.toName();
  1193. }
  1194. if (format === "hsl") {
  1195. formattedString = this.toHslString();
  1196. }
  1197. if (format === "hsv") {
  1198. formattedString = this.toHsvString();
  1199. }
  1200. return formattedString || this.toHexString();
  1201. },
  1202. _applyModification: function(fn, args) {
  1203. var color = fn.apply(null, [this].concat([].slice.call(args)));
  1204. this._r = color._r;
  1205. this._g = color._g;
  1206. this._b = color._b;
  1207. this.setAlpha(color._a);
  1208. return this;
  1209. },
  1210. lighten: function() {
  1211. return this._applyModification(lighten, arguments);
  1212. },
  1213. brighten: function() {
  1214. return this._applyModification(brighten, arguments);
  1215. },
  1216. darken: function() {
  1217. return this._applyModification(darken, arguments);
  1218. },
  1219. desaturate: function() {
  1220. return this._applyModification(desaturate, arguments);
  1221. },
  1222. saturate: function() {
  1223. return this._applyModification(saturate, arguments);
  1224. },
  1225. greyscale: function() {
  1226. return this._applyModification(greyscale, arguments);
  1227. },
  1228. spin: function() {
  1229. return this._applyModification(spin, arguments);
  1230. },
  1231. _applyCombination: function(fn, args) {
  1232. return fn.apply(null, [this].concat([].slice.call(args)));
  1233. },
  1234. analogous: function() {
  1235. return this._applyCombination(analogous, arguments);
  1236. },
  1237. complement: function() {
  1238. return this._applyCombination(complement, arguments);
  1239. },
  1240. monochromatic: function() {
  1241. return this._applyCombination(monochromatic, arguments);
  1242. },
  1243. splitcomplement: function() {
  1244. return this._applyCombination(splitcomplement, arguments);
  1245. },
  1246. triad: function() {
  1247. return this._applyCombination(triad, arguments);
  1248. },
  1249. tetrad: function() {
  1250. return this._applyCombination(tetrad, arguments);
  1251. }
  1252. };
  1253. // If input is an object, force 1 into "1.0" to handle ratios properly
  1254. // String input requires "1.0" as input, so 1 will be treated as 1
  1255. tinycolor.fromRatio = function(color, opts) {
  1256. if (typeof color == "object") {
  1257. var newColor = {};
  1258. for (var i in color) {
  1259. if (color.hasOwnProperty(i)) {
  1260. if (i === "a") {
  1261. newColor[i] = color[i];
  1262. }
  1263. else {
  1264. newColor[i] = convertToPercentage(color[i]);
  1265. }
  1266. }
  1267. }
  1268. color = newColor;
  1269. }
  1270. return tinycolor(color, opts);
  1271. };
  1272. // Given a string or object, convert that input to RGB
  1273. // Possible string inputs:
  1274. //
  1275. // "red"
  1276. // "#f00" or "f00"
  1277. // "#ff0000" or "ff0000"
  1278. // "#ff000000" or "ff000000"
  1279. // "rgb 255 0 0" or "rgb (255, 0, 0)"
  1280. // "rgb 1.0 0 0" or "rgb (1, 0, 0)"
  1281. // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
  1282. // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
  1283. // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
  1284. // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
  1285. // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
  1286. //
  1287. function inputToRGB(color) {
  1288. var rgb = { r: 0, g: 0, b: 0 };
  1289. var a = 1;
  1290. var ok = false;
  1291. var format = false;
  1292. if (typeof color == "string") {
  1293. color = stringInputToObject(color);
  1294. }
  1295. if (typeof color == "object") {
  1296. if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) {
  1297. rgb = rgbToRgb(color.r, color.g, color.b);
  1298. ok = true;
  1299. format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
  1300. }
  1301. else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) {
  1302. color.s = convertToPercentage(color.s);
  1303. color.v = convertToPercentage(color.v);
  1304. rgb = hsvToRgb(color.h, color.s, color.v);
  1305. ok = true;
  1306. format = "hsv";
  1307. }
  1308. else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) {
  1309. color.s = convertToPercentage(color.s);
  1310. color.l = convertToPercentage(color.l);
  1311. rgb = hslToRgb(color.h, color.s, color.l);
  1312. ok = true;
  1313. format = "hsl";
  1314. }
  1315. if (color.hasOwnProperty("a")) {
  1316. a = color.a;
  1317. }
  1318. }
  1319. a = boundAlpha(a);
  1320. return {
  1321. ok: ok,
  1322. format: color.format || format,
  1323. r: mathMin(255, mathMax(rgb.r, 0)),
  1324. g: mathMin(255, mathMax(rgb.g, 0)),
  1325. b: mathMin(255, mathMax(rgb.b, 0)),
  1326. a: a
  1327. };
  1328. }
  1329. // Conversion Functions
  1330. // --------------------
  1331. // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
  1332. // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
  1333. // `rgbToRgb`
  1334. // Handle bounds / percentage checking to conform to CSS color spec
  1335. // <http://www.w3.org/TR/css3-color/>
  1336. // *Assumes:* r, g, b in [0, 255] or [0, 1]
  1337. // *Returns:* { r, g, b } in [0, 255]
  1338. function rgbToRgb(r, g, b){
  1339. return {
  1340. r: bound01(r, 255) * 255,
  1341. g: bound01(g, 255) * 255,
  1342. b: bound01(b, 255) * 255
  1343. };
  1344. }
  1345. // `rgbToHsl`
  1346. // Converts an RGB color value to HSL.
  1347. // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
  1348. // *Returns:* { h, s, l } in [0,1]
  1349. function rgbToHsl(r, g, b) {
  1350. r = bound01(r, 255);
  1351. g = bound01(g, 255);
  1352. b = bound01(b, 255);
  1353. var max = mathMax(r, g, b), min = mathMin(r, g, b);
  1354. var h, s, l = (max + min) / 2;
  1355. if(max == min) {
  1356. h = s = 0; // achromatic
  1357. }
  1358. else {
  1359. var d = max - min;
  1360. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  1361. switch(max) {
  1362. case r: h = (g - b) / d + (g < b ? 6 : 0); break;
  1363. case g: h = (b - r) / d + 2; break;
  1364. case b: h = (r - g) / d + 4; break;
  1365. }
  1366. h /= 6;
  1367. }
  1368. return { h: h, s: s, l: l };
  1369. }
  1370. // `hslToRgb`
  1371. // Converts an HSL color value to RGB.
  1372. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
  1373. // *Returns:* { r, g, b } in the set [0, 255]
  1374. function hslToRgb(h, s, l) {
  1375. var r, g, b;
  1376. h = bound01(h, 360);
  1377. s = bound01(s, 100);
  1378. l = bound01(l, 100);
  1379. function hue2rgb(p, q, t) {
  1380. if(t < 0) t += 1;
  1381. if(t > 1) t -= 1;
  1382. if(t < 1/6) return p + (q - p) * 6 * t;
  1383. if(t < 1/2) return q;
  1384. if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
  1385. return p;
  1386. }
  1387. if(s === 0) {
  1388. r = g = b = l; // achromatic
  1389. }
  1390. else {
  1391. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  1392. var p = 2 * l - q;
  1393. r = hue2rgb(p, q, h + 1/3);
  1394. g = hue2rgb(p, q, h);
  1395. b = hue2rgb(p, q, h - 1/3);
  1396. }
  1397. return { r: r * 255, g: g * 255, b: b * 255 };
  1398. }
  1399. // `rgbToHsv`
  1400. // Converts an RGB color value to HSV
  1401. // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
  1402. // *Returns:* { h, s, v } in [0,1]
  1403. function rgbToHsv(r, g, b) {
  1404. r = bound01(r, 255);
  1405. g = bound01(g, 255);
  1406. b = bound01(b, 255);
  1407. var max = mathMax(r, g, b), min = mathMin(r, g, b);
  1408. var h, s, v = max;
  1409. var d = max - min;
  1410. s = max === 0 ? 0 : d / max;
  1411. if(max == min) {
  1412. h = 0; // achromatic
  1413. }
  1414. else {
  1415. switch(max) {
  1416. case r: h = (g - b) / d + (g < b ? 6 : 0); break;
  1417. case g: h = (b - r) / d + 2; break;
  1418. case b: h = (r - g) / d + 4; break;
  1419. }
  1420. h /= 6;
  1421. }
  1422. return { h: h, s: s, v: v };
  1423. }
  1424. // `hsvToRgb`
  1425. // Converts an HSV color value to RGB.
  1426. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
  1427. // *Returns:* { r, g, b } in the set [0, 255]
  1428. function hsvToRgb(h, s, v) {
  1429. h = bound01(h, 360) * 6;
  1430. s = bound01(s, 100);
  1431. v = bound01(v, 100);
  1432. var i = math.floor(h),
  1433. f = h - i,
  1434. p = v * (1 - s),
  1435. q = v * (1 - f * s),
  1436. t = v * (1 - (1 - f) * s),
  1437. mod = i % 6,
  1438. r = [v, q, p, p, t, v][mod],
  1439. g = [t, v, v, q, p, p][mod],
  1440. b = [p, p, t, v, v, q][mod];
  1441. return { r: r * 255, g: g * 255, b: b * 255 };
  1442. }
  1443. // `rgbToHex`
  1444. // Converts an RGB color to hex
  1445. // Assumes r, g, and b are contained in the set [0, 255]
  1446. // Returns a 3 or 6 character hex
  1447. function rgbToHex(r, g, b, allow3Char) {
  1448. var hex = [
  1449. pad2(mathRound(r).toString(16)),
  1450. pad2(mathRound(g).toString(16)),
  1451. pad2(mathRound(b).toString(16))
  1452. ];
  1453. // Return a 3 character hex if possible
  1454. 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)) {
  1455. return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
  1456. }
  1457. return hex.join("");
  1458. }
  1459. // `rgbaToHex`
  1460. // Converts an RGBA color plus alpha transparency to hex
  1461. // Assumes r, g, b and a are contained in the set [0, 255]
  1462. // Returns an 8 character hex
  1463. function rgbaToHex(r, g, b, a) {
  1464. var hex = [
  1465. pad2(convertDecimalToHex(a)),
  1466. pad2(mathRound(r).toString(16)),
  1467. pad2(mathRound(g).toString(16)),
  1468. pad2(mathRound(b).toString(16))
  1469. ];
  1470. return hex.join("");
  1471. }
  1472. // `equals`
  1473. // Can be called with any tinycolor input
  1474. tinycolor.equals = function (color1, color2) {
  1475. if (!color1 || !color2) { return false; }
  1476. return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
  1477. };
  1478. tinycolor.random = function() {
  1479. return tinycolor.fromRatio({
  1480. r: mathRandom(),
  1481. g: mathRandom(),
  1482. b: mathRandom()
  1483. });
  1484. };
  1485. // Modification Functions
  1486. // ----------------------
  1487. // Thanks to less.js for some of the basics here
  1488. // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>
  1489. function desaturate(color, amount) {
  1490. amount = (amount === 0) ? 0 : (amount || 10);
  1491. var hsl = tinycolor(color).toHsl();
  1492. hsl.s -= amount / 100;
  1493. hsl.s = clamp01(hsl.s);
  1494. return tinycolor(hsl);
  1495. }
  1496. function saturate(color, amount) {
  1497. amount = (amount === 0) ? 0 : (amount || 10);
  1498. var hsl = tinycolor(color).toHsl();
  1499. hsl.s += amount / 100;
  1500. hsl.s = clamp01(hsl.s);
  1501. return tinycolor(hsl);
  1502. }
  1503. function greyscale(color) {
  1504. return tinycolor(color).desaturate(100);
  1505. }
  1506. function lighten (color, amount) {
  1507. amount = (amount === 0) ? 0 : (amount || 10);
  1508. var hsl = tinycolor(color).toHsl();
  1509. hsl.l += amount / 100;
  1510. hsl.l = clamp01(hsl.l);
  1511. return tinycolor(hsl);
  1512. }
  1513. function brighten(color, amount) {
  1514. amount = (amount === 0) ? 0 : (amount || 10);
  1515. var rgb = tinycolor(color).toRgb();
  1516. rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
  1517. rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
  1518. rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
  1519. return tinycolor(rgb);
  1520. }
  1521. function darken (color, amount) {
  1522. amount = (amount === 0) ? 0 : (amount || 10);
  1523. var hsl = tinycolor(color).toHsl();
  1524. hsl.l -= amount / 100;
  1525. hsl.l = clamp01(hsl.l);
  1526. return tinycolor(hsl);
  1527. }
  1528. // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
  1529. // Values outside of this range will be wrapped into this range.
  1530. function spin(color, amount) {
  1531. var hsl = tinycolor(color).toHsl();
  1532. var hue = (mathRound(hsl.h) + amount) % 360;
  1533. hsl.h = hue < 0 ? 360 + hue : hue;
  1534. return tinycolor(hsl);
  1535. }
  1536. // Combination Functions
  1537. // ---------------------
  1538. // Thanks to jQuery xColor for some of the ideas behind these
  1539. // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>
  1540. function complement(color) {
  1541. var hsl = tinycolor(color).toHsl();
  1542. hsl.h = (hsl.h + 180) % 360;
  1543. return tinycolor(hsl);
  1544. }
  1545. function triad(color) {
  1546. var hsl = tinycolor(color).toHsl();
  1547. var h = hsl.h;
  1548. return [
  1549. tinycolor(color),
  1550. tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
  1551. tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
  1552. ];
  1553. }
  1554. function tetrad(color) {
  1555. var hsl = tinycolor(color).toHsl();
  1556. var h = hsl.h;
  1557. return [
  1558. tinycolor(color),
  1559. tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
  1560. tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
  1561. tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
  1562. ];
  1563. }
  1564. function splitcomplement(color) {
  1565. var hsl = tinycolor(color).toHsl();
  1566. var h = hsl.h;
  1567. return [
  1568. tinycolor(color),
  1569. tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
  1570. tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
  1571. ];
  1572. }
  1573. function analogous(color, results, slices) {
  1574. results = results || 6;
  1575. slices = slices || 30;
  1576. var hsl = tinycolor(color).toHsl();
  1577. var part = 360 / slices;
  1578. var ret = [tinycolor(color)];
  1579. for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
  1580. hsl.h = (hsl.h + part) % 360;
  1581. ret.push(tinycolor(hsl));
  1582. }
  1583. return ret;
  1584. }
  1585. function monochromatic(color, results) {
  1586. results = results || 6;
  1587. var hsv = tinycolor(color).toHsv();
  1588. var h = hsv.h, s = hsv.s, v = hsv.v;
  1589. var ret = [];
  1590. var modification = 1 / results;
  1591. while (results--) {
  1592. ret.push(tinycolor({ h: h, s: s, v: v}));
  1593. v = (v + modification) % 1;
  1594. }
  1595. return ret;
  1596. }
  1597. // Utility Functions
  1598. // ---------------------
  1599. tinycolor.mix = function(color1, color2, amount) {
  1600. amount = (amount === 0) ? 0 : (amount || 50);
  1601. var rgb1 = tinycolor(color1).toRgb();
  1602. var rgb2 = tinycolor(color2).toRgb();
  1603. var p = amount / 100;
  1604. var w = p * 2 - 1;
  1605. var a = rgb2.a - rgb1.a;
  1606. var w1;
  1607. if (w * a == -1) {
  1608. w1 = w;
  1609. } else {
  1610. w1 = (w + a) / (1 + w * a);
  1611. }
  1612. w1 = (w1 + 1) / 2;
  1613. var w2 = 1 - w1;
  1614. var rgba = {
  1615. r: rgb2.r * w1 + rgb1.r * w2,
  1616. g: rgb2.g * w1 + rgb1.g * w2,
  1617. b: rgb2.b * w1 + rgb1.b * w2,
  1618. a: rgb2.a * p + rgb1.a * (1 - p)
  1619. };
  1620. return tinycolor(rgba);
  1621. };
  1622. // Readability Functions
  1623. // ---------------------
  1624. // <http://www.w3.org/TR/AERT#color-contrast>
  1625. // `readability`
  1626. // Analyze the 2 colors and returns an object with the following properties:
  1627. // `brightness`: difference in brightness between the two colors
  1628. // `color`: difference in color/hue between the two colors
  1629. tinycolor.readability = function(color1, color2) {
  1630. var c1 = tinycolor(color1);
  1631. var c2 = tinycolor(color2);
  1632. var rgb1 = c1.toRgb();
  1633. var rgb2 = c2.toRgb();
  1634. var brightnessA = c1.getBrightness();
  1635. var brightnessB = c2.getBrightness();
  1636. var colorDiff = (
  1637. Math.max(rgb1.r, rgb2.r) - Math.min(rgb1.r, rgb2.r) +
  1638. Math.max(rgb1.g, rgb2.g) - Math.min(rgb1.g, rgb2.g) +
  1639. Math.max(rgb1.b, rgb2.b) - Math.min(rgb1.b, rgb2.b)
  1640. );
  1641. return {
  1642. brightness: Math.abs(brightnessA - brightnessB),
  1643. color: colorDiff
  1644. };
  1645. };
  1646. // `readable`
  1647. // http://www.w3.org/TR/AERT#color-contrast
  1648. // Ensure that foreground and background color combinations provide sufficient contrast.
  1649. // *Example*
  1650. // tinycolor.isReadable("#000", "#111") => false
  1651. tinycolor.isReadable = function(color1, color2) {
  1652. var readability = tinycolor.readability(color1, color2);
  1653. return readability.brightness > 125 && readability.color > 500;
  1654. };
  1655. // `mostReadable`
  1656. // Given a base color and a list of possible foreground or background
  1657. // colors for that base, returns the most readable color.
  1658. // *Example*
  1659. // tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000"
  1660. tinycolor.mostReadable = function(baseColor, colorList) {
  1661. var bestColor = null;
  1662. var bestScore = 0;
  1663. var bestIsReadable = false;
  1664. for (var i=0; i < colorList.length; i++) {
  1665. // We normalize both around the "acceptable" breaking point,
  1666. // but rank brightness constrast higher than hue.
  1667. var readability = tinycolor.readability(baseColor, colorList[i]);
  1668. var readable = readability.brightness > 125 && readability.color > 500;
  1669. var score = 3 * (readability.brightness / 125) + (readability.color / 500);
  1670. if ((readable && ! bestIsReadable) ||
  1671. (readable && bestIsReadable && score > bestScore) ||
  1672. ((! readable) && (! bestIsReadable) && score > bestScore)) {
  1673. bestIsReadable = readable;
  1674. bestScore = score;
  1675. bestColor = tinycolor(colorList[i]);
  1676. }
  1677. }
  1678. return bestColor;
  1679. };
  1680. // Big List of Colors
  1681. // ------------------
  1682. // <http://www.w3.org/TR/css3-color/#svg-color>
  1683. var names = tinycolor.names = {
  1684. aliceblue: "f0f8ff",
  1685. antiquewhite: "faebd7",
  1686. aqua: "0ff",
  1687. aquamarine: "7fffd4",
  1688. azure: "f0ffff",
  1689. beige: "f5f5dc",
  1690. bisque: "ffe4c4",
  1691. black: "000",
  1692. blanchedalmond: "ffebcd",
  1693. blue: "00f",
  1694. blueviolet: "8a2be2",
  1695. brown: "a52a2a",
  1696. burlywood: "deb887",
  1697. burntsienna: "ea7e5d",
  1698. cadetblue: "5f9ea0",
  1699. chartreuse: "7fff00",
  1700. chocolate: "d2691e",
  1701. coral: "ff7f50",
  1702. cornflowerblue: "6495ed",
  1703. cornsilk: "fff8dc",
  1704. crimson: "dc143c",
  1705. cyan: "0ff",
  1706. darkblue: "00008b",
  1707. darkcyan: "008b8b",
  1708. darkgoldenrod: "b8860b",
  1709. darkgray: "a9a9a9",
  1710. darkgreen: "006400",
  1711. darkgrey: "a9a9a9",
  1712. darkkhaki: "bdb76b",
  1713. darkmagenta: "8b008b",
  1714. darkolivegreen: "556b2f",
  1715. darkorange: "ff8c00",
  1716. darkorchid: "9932cc",
  1717. darkred: "8b0000",
  1718. darksalmon: "e9967a",
  1719. darkseagreen: "8fbc8f",
  1720. darkslateblue: "483d8b",
  1721. darkslategray: "2f4f4f",
  1722. darkslategrey: "2f4f4f",
  1723. darkturquoise: "00ced1",
  1724. darkviolet: "9400d3",
  1725. deeppink: "ff1493",
  1726. deepskyblue: "00bfff",
  1727. dimgray: "696969",
  1728. dimgrey: "696969",
  1729. dodgerblue: "1e90ff",
  1730. firebrick: "b22222",
  1731. floralwhite: "fffaf0",
  1732. forestgreen: "228b22",
  1733. fuchsia: "f0f",
  1734. gainsboro: "dcdcdc",
  1735. ghostwhite: "f8f8ff",
  1736. gold: "ffd700",
  1737. goldenrod: "daa520",
  1738. gray: "808080",
  1739. green: "008000",
  1740. greenyellow: "adff2f",
  1741. grey: "808080",
  1742. honeydew: "f0fff0",
  1743. hotpink: "ff69b4",
  1744. indianred: "cd5c5c",
  1745. indigo: "4b0082",
  1746. ivory: "fffff0",
  1747. khaki: "f0e68c",
  1748. lavender: "e6e6fa",
  1749. lavenderblush: "fff0f5",
  1750. lawngreen: "7cfc00",
  1751. lemonchiffon: "fffacd",
  1752. lightblue: "add8e6",
  1753. lightcoral: "f08080",
  1754. lightcyan: "e0ffff",
  1755. lightgoldenrodyellow: "fafad2",
  1756. lightgray: "d3d3d3",
  1757. lightgreen: "90ee90",
  1758. lightgrey: "d3d3d3",
  1759. lightpink: "ffb6c1",
  1760. lightsalmon: "ffa07a",
  1761. lightseagreen: "20b2aa",
  1762. lightskyblue: "87cefa",
  1763. lightslategray: "789",
  1764. lightslategrey: "789",
  1765. lightsteelblue: "b0c4de",
  1766. lightyellow: "ffffe0",
  1767. lime: "0f0",
  1768. limegreen: "32cd32",
  1769. linen: "faf0e6",
  1770. magenta: "f0f",
  1771. maroon: "800000",
  1772. mediumaquamarine: "66cdaa",
  1773. mediumblue: "0000cd",
  1774. mediumorchid: "ba55d3",
  1775. mediumpurple: "9370db",
  1776. mediumseagreen: "3cb371",
  1777. mediumslateblue: "7b68ee",
  1778. mediumspringgreen: "00fa9a",
  1779. mediumturquoise: "48d1cc",
  1780. mediumvioletred: "c71585",
  1781. midnightblue: "191970",
  1782. mintcream: "f5fffa",
  1783. mistyrose: "ffe4e1",
  1784. moccasin: "ffe4b5",
  1785. navajowhite: "ffdead",
  1786. navy: "000080",
  1787. oldlace: "fdf5e6",
  1788. olive: "808000",
  1789. olivedrab: "6b8e23",
  1790. orange: "ffa500",
  1791. orangered: "ff4500",
  1792. orchid: "da70d6",
  1793. palegoldenrod: "eee8aa",
  1794. palegreen: "98fb98",
  1795. paleturquoise: "afeeee",
  1796. palevioletred: "db7093",
  1797. papayawhip: "ffefd5",
  1798. peachpuff: "ffdab9",
  1799. peru: "cd853f",
  1800. pink: "ffc0cb",
  1801. plum: "dda0dd",
  1802. powderblue: "b0e0e6",
  1803. purple: "800080",
  1804. rebeccapurple: "663399",
  1805. red: "f00",
  1806. rosybrown: "bc8f8f",
  1807. royalblue: "4169e1",
  1808. saddlebrown: "8b4513",
  1809. salmon: "fa8072",
  1810. sandybrown: "f4a460",
  1811. seagreen: "2e8b57",
  1812. seashell: "fff5ee",
  1813. sienna: "a0522d",
  1814. silver: "c0c0c0",
  1815. skyblue: "87ceeb",
  1816. slateblue: "6a5acd",
  1817. slategray: "708090",
  1818. slategrey: "708090",
  1819. snow: "fffafa",
  1820. springgreen: "00ff7f",
  1821. steelblue: "4682b4",
  1822. tan: "d2b48c",
  1823. teal: "008080",
  1824. thistle: "d8bfd8",
  1825. tomato: "ff6347",
  1826. turquoise: "40e0d0",
  1827. violet: "ee82ee",
  1828. wheat: "f5deb3",
  1829. white: "fff",
  1830. whitesmoke: "f5f5f5",
  1831. yellow: "ff0",
  1832. yellowgreen: "9acd32"
  1833. };
  1834. // Make it easy to access colors via `hexNames[hex]`
  1835. var hexNames = tinycolor.hexNames = flip(names);
  1836. // Utilities
  1837. // ---------
  1838. // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
  1839. function flip(o) {
  1840. var flipped = { };
  1841. for (var i in o) {
  1842. if (o.hasOwnProperty(i)) {
  1843. flipped[o[i]] = i;
  1844. }
  1845. }
  1846. return flipped;
  1847. }
  1848. // Return a valid alpha value [0,1] with all invalid values being set to 1
  1849. function boundAlpha(a) {
  1850. a = parseFloat(a);
  1851. if (isNaN(a) || a < 0 || a > 1) {
  1852. a = 1;
  1853. }
  1854. return a;
  1855. }
  1856. // Take input from [0, n] and return it as [0, 1]
  1857. function bound01(n, max) {
  1858. if (isOnePointZero(n)) { n = "100%"; }
  1859. var processPercent = isPercentage(n);
  1860. n = mathMin(max, mathMax(0, parseFloat(n)));
  1861. // Automatically convert percentage into number
  1862. if (processPercent) {
  1863. n = parseInt(n * max, 10) / 100;
  1864. }
  1865. // Handle floating point rounding errors
  1866. if ((math.abs(n - max) < 0.000001)) {
  1867. return 1;
  1868. }
  1869. // Convert into [0, 1] range if it isn't already
  1870. return (n % max) / parseFloat(max);
  1871. }
  1872. // Force a number between 0 and 1
  1873. function clamp01(val) {
  1874. return mathMin(1, mathMax(0, val));
  1875. }
  1876. // Parse a base-16 hex value into a base-10 integer
  1877. function parseIntFromHex(val) {
  1878. return parseInt(val, 16);
  1879. }
  1880. // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
  1881. // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
  1882. function isOnePointZero(n) {
  1883. return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
  1884. }
  1885. // Check to see if string passed in is a percentage
  1886. function isPercentage(n) {
  1887. return typeof n === "string" && n.indexOf('%') != -1;
  1888. }
  1889. // Force a hex value to have 2 characters
  1890. function pad2(c) {
  1891. return c.length == 1 ? '0' + c : '' + c;
  1892. }
  1893. // Replace a decimal with it's percentage value
  1894. function convertToPercentage(n) {
  1895. if (n <= 1) {
  1896. n = (n * 100) + "%";
  1897. }
  1898. return n;
  1899. }
  1900. // Converts a decimal to a hex value
  1901. function convertDecimalToHex(d) {
  1902. return Math.round(parseFloat(d) * 255).toString(16);
  1903. }
  1904. // Converts a hex value to a decimal
  1905. function convertHexToDecimal(h) {
  1906. return (parseIntFromHex(h) / 255);
  1907. }
  1908. var matchers = (function() {
  1909. // <http://www.w3.org/TR/css3-values/#integers>
  1910. var CSS_INTEGER = "[-\\+]?\\d+%?";
  1911. // <http://www.w3.org/TR/css3-values/#number-value>
  1912. var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
  1913. // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
  1914. var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
  1915. // Actual matching.
  1916. // Parentheses and commas are optional, but not required.
  1917. // Whitespace can take the place of commas or opening paren
  1918. var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
  1919. var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
  1920. return {
  1921. rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
  1922. rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
  1923. hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
  1924. hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
  1925. hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
  1926. hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
  1927. hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
  1928. hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
  1929. hex8: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
  1930. };
  1931. })();
  1932. // `stringInputToObject`
  1933. // Permissive string parsing. Take in a number of formats, and output an object
  1934. // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
  1935. function stringInputToObject(color) {
  1936. color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
  1937. var named = false;
  1938. if (names[color]) {
  1939. color = names[color];
  1940. named = true;
  1941. }
  1942. else if (color == 'transparent') {
  1943. return { r: 0, g: 0, b: 0, a: 0, format: "name" };
  1944. }
  1945. // Try to match string input using regular expressions.
  1946. // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
  1947. // Just return an object and let the conversion functions handle that.
  1948. // This way the result will be the same whether the tinycolor is initialized with string or object.
  1949. var match;
  1950. if ((match = matchers.rgb.exec(color))) {
  1951. return { r: match[1], g: match[2], b: match[3] };
  1952. }
  1953. if ((match = matchers.rgba.exec(color))) {
  1954. return { r: match[1], g: match[2], b: match[3], a: match[4] };
  1955. }
  1956. if ((match = matchers.hsl.exec(color))) {
  1957. return { h: match[1], s: match[2], l: match[3] };
  1958. }
  1959. if ((match = matchers.hsla.exec(color))) {
  1960. return { h: match[1], s: match[2], l: match[3], a: match[4] };
  1961. }
  1962. if ((match = matchers.hsv.exec(color))) {
  1963. return { h: match[1], s: match[2], v: match[3] };
  1964. }
  1965. if ((match = matchers.hsva.exec(color))) {
  1966. return { h: match[1], s: match[2], v: match[3], a: match[4] };
  1967. }
  1968. if ((match = matchers.hex8.exec(color))) {
  1969. return {
  1970. a: convertHexToDecimal(match[1]),
  1971. r: parseIntFromHex(match[2]),
  1972. g: parseIntFromHex(match[3]),
  1973. b: parseIntFromHex(match[4]),
  1974. format: named ? "name" : "hex8"
  1975. };
  1976. }
  1977. if ((match = matchers.hex6.exec(color))) {
  1978. return {
  1979. r: parseIntFromHex(match[1]),
  1980. g: parseIntFromHex(match[2]),
  1981. b: parseIntFromHex(match[3]),
  1982. format: named ? "name" : "hex"
  1983. };
  1984. }
  1985. if ((match = matchers.hex3.exec(color))) {
  1986. return {
  1987. r: parseIntFromHex(match[1] + '' + match[1]),
  1988. g: parseIntFromHex(match[2] + '' + match[2]),
  1989. b: parseIntFromHex(match[3] + '' + match[3]),
  1990. format: named ? "name" : "hex"
  1991. };
  1992. }
  1993. return false;
  1994. }
  1995. window.tinycolor = tinycolor;
  1996. })();
  1997. $(function () {
  1998. if ($.fn.spectrum.load) {
  1999. $.fn.spectrum.processNativeColorInputs();
  2000. }
  2001. });
  2002. });