spectrum.js 77 KB

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