spectrum.js 67 KB

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