spectrum.js 67 KB

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