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

spectrum.js 78KB

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