spectrum.js 70 KB

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