spectrum.js 81 KB

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