sparkline.bundle.js 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113
  1. /**
  2. *
  3. * jquery.sparkline.js
  4. *
  5. * v2.4.1
  6. * (c) Splunk, Inc
  7. * Contact: Gareth Watts (gareth@splunk.com)
  8. * http://omnipotent.net/jquery.sparkline/
  9. *
  10. * Generates inline sparkline charts from data supplied either to the method
  11. * or inline in HTML
  12. *
  13. * Compatible with Internet Explorer 6.0+ and modern browsers equipped with the canvas tag
  14. * (Firefox 2.0+, Safari, Opera, etc)
  15. *
  16. * License: New BSD License
  17. *
  18. * Copyright (c) 2012, Splunk Inc.
  19. * All rights reserved.
  20. *
  21. * Redistribution and use in source and binary forms, with or without modification,
  22. * are permitted provided that the following conditions are met:
  23. *
  24. * * Redistributions of source code must retain the above copyright notice,
  25. * this list of conditions and the following disclaimer.
  26. * * Redistributions in binary form must reproduce the above copyright notice,
  27. * this list of conditions and the following disclaimer in the documentation
  28. * and/or other materials provided with the distribution.
  29. * * Neither the name of Splunk Inc nor the names of its contributors may
  30. * be used to endorse or promote products derived from this software without
  31. * specific prior written permission.
  32. *
  33. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
  34. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
  36. * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  37. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
  38. * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  39. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  40. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  41. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. *
  43. *
  44. * Usage:
  45. * $(selector).sparkline(values, options)
  46. *
  47. * If values is undefined or set to 'html' then the data values are read from the specified tag:
  48. * <p>Sparkline: <span class="sparkline">1,4,6,6,8,5,3,5</span></p>
  49. * $('.sparkline').sparkline();
  50. * There must be no spaces in the enclosed data set
  51. *
  52. * Otherwise values must be an array of numbers or null values
  53. * <p>Sparkline: <span id="sparkline1">This text replaced if the browser is compatible</span></p>
  54. * $('#sparkline1').sparkline([1,4,6,6,8,5,3,5])
  55. * $('#sparkline2').sparkline([1,4,6,null,null,5,3,5])
  56. *
  57. * Values can also be specified in an HTML comment, or as a values attribute:
  58. * <p>Sparkline: <span class="sparkline"><!--1,4,6,6,8,5,3,5 --></span></p>
  59. * <p>Sparkline: <span class="sparkline" values="1,4,6,6,8,5,3,5"></span></p>
  60. * $('.sparkline').sparkline();
  61. *
  62. * For line charts, x values can also be specified:
  63. * <p>Sparkline: <span class="sparkline">1:1,2.7:4,3.4:6,5:6,6:8,8.7:5,9:3,10:5</span></p>
  64. * $('#sparkline1').sparkline([ [1,1], [2.7,4], [3.4,6], [5,6], [6,8], [8.7,5], [9,3], [10,5] ])
  65. *
  66. * By default, options should be passed in as the second argument to the sparkline function:
  67. * $('.sparkline').sparkline([1,2,3,4], {type: 'bar'})
  68. *
  69. * Options can also be set by passing them on the tag itself. This feature is disabled by default though
  70. * as there's a slight performance overhead:
  71. * $('.sparkline').sparkline([1,2,3,4], {enableTagOptions: true})
  72. * <p>Sparkline: <span class="sparkline" sparkType="bar" sparkBarColor="red">loading</span></p>
  73. * Prefix all options supplied as tag attribute with "spark" (configurable by setting tagOptionsPrefix)
  74. *
  75. * Supported options:
  76. * lineColor - Color of the line used for the chart
  77. * fillColor - Color used to fill in the chart - Set to '' or false for a transparent chart
  78. * width - Width of the chart - Defaults to 3 times the number of values in pixels
  79. * height - Height of the chart - Defaults to the height of the containing element
  80. * chartRangeMin - Specify the minimum value to use for the Y range of the chart - Defaults to the minimum value supplied
  81. * chartRangeMax - Specify the maximum value to use for the Y range of the chart - Defaults to the maximum value supplied
  82. * chartRangeClip - Clip out of range values to the max/min specified by chartRangeMin and chartRangeMax
  83. * chartRangeMinX - Specify the minimum value to use for the X range of the chart - Defaults to the minimum value supplied
  84. * chartRangeMaxX - Specify the maximum value to use for the X range of the chart - Defaults to the maximum value supplied
  85. * composite - If true then don't erase any existing chart attached to the tag, but draw
  86. * another chart over the top - Note that width and height are ignored if an
  87. * existing chart is detected.
  88. * tagValuesAttribute - Name of tag attribute to check for data values - Defaults to 'values'
  89. * enableTagOptions - Whether to check tags for sparkline options
  90. * tagOptionsPrefix - Prefix used for options supplied as tag attributes - Defaults to 'spark'
  91. * disableHiddenCheck - If set to true, then the plugin will assume that charts will never be drawn into a
  92. * hidden dom element, avoding a browser reflow
  93. * disableInteraction - If set to true then all mouseover/click interaction behaviour will be disabled,
  94. * making the plugin perform much like it did in 1.x
  95. * disableTooltips - If set to true then tooltips will be disabled - Defaults to false (tooltips enabled)
  96. * disableHighlight - If set to true then highlighting of selected chart elements on mouseover will be disabled
  97. * defaults to false (highlights enabled)
  98. * highlightLighten - Factor to lighten/darken highlighted chart values by - Defaults to 1.4 for a 40% increase
  99. * tooltipContainer - Specify which DOM element the tooltip should be rendered into - defaults to document.body
  100. * tooltipClassname - Optional CSS classname to apply to tooltips - If not specified then a default style will be applied
  101. * tooltipOffsetX - How many pixels away from the mouse pointer to render the tooltip on the X axis
  102. * tooltipOffsetY - How many pixels away from the mouse pointer to render the tooltip on the r axis
  103. * tooltipFormatter - Optional callback that allows you to override the HTML displayed in the tooltip
  104. * callback is given arguments of (sparkline, options, fields)
  105. * tooltipChartTitle - If specified then the tooltip uses the string specified by this setting as a title
  106. * tooltipFormat - A format string or SPFormat object (or an array thereof for multiple entries)
  107. * to control the format of the tooltip
  108. * tooltipPrefix - A string to prepend to each field displayed in a tooltip
  109. * tooltipSuffix - A string to append to each field displayed in a tooltip
  110. * tooltipSkipNull - If true then null values will not have a tooltip displayed (defaults to true)
  111. * tooltipValueLookups - An object or range map to map field values to tooltip strings
  112. * (eg. to map -1 to "Lost", 0 to "Draw", and 1 to "Win")
  113. * numberFormatter - Optional callback for formatting numbers in tooltips
  114. * numberDigitGroupSep - Character to use for group separator in numbers "1,234" - Defaults to ","
  115. * numberDecimalMark - Character to use for the decimal point when formatting numbers - Defaults to "."
  116. * numberDigitGroupCount - Number of digits between group separator - Defaults to 3
  117. *
  118. * There are 7 types of sparkline, selected by supplying a "type" option of 'line' (default),
  119. * 'bar', 'tristate', 'bullet', 'discrete', 'pie' or 'box'
  120. * line - Line chart. Options:
  121. * spotColor - Set to '' to not end each line in a circular spot
  122. * minSpotColor - If set, color of spot at minimum value
  123. * maxSpotColor - If set, color of spot at maximum value
  124. * spotRadius - Radius in pixels
  125. * lineWidth - Width of line in pixels
  126. * normalRangeMin
  127. * normalRangeMax - If set draws a filled horizontal bar between these two values marking the "normal"
  128. * or expected range of values
  129. * normalRangeColor - Color to use for the above bar
  130. * drawNormalOnTop - Draw the normal range above the chart fill color if true
  131. * defaultPixelsPerValue - Defaults to 3 pixels of width for each value in the chart
  132. * highlightSpotColor - The color to use for drawing a highlight spot on mouseover - Set to null to disable
  133. * highlightLineColor - The color to use for drawing a highlight line on mouseover - Set to null to disable
  134. * valueSpots - Specify which points to draw spots on, and in which color. Accepts a range map
  135. *
  136. * bar - Bar chart. Options:
  137. * barColor - Color of bars for postive values
  138. * negBarColor - Color of bars for negative values
  139. * zeroColor - Color of bars with zero values
  140. * nullColor - Color of bars with null values - Defaults to omitting the bar entirely
  141. * barWidth - Width of bars in pixels
  142. * colorMap - Optional mappnig of values to colors to override the *BarColor values above
  143. * can be an Array of values to control the color of individual bars or a range map
  144. * to specify colors for individual ranges of values
  145. * barSpacing - Gap between bars in pixels
  146. * zeroAxis - Centers the y-axis around zero if true
  147. *
  148. * tristate - Charts values of win (>0), lose (<0) or draw (=0)
  149. * posBarColor - Color of win values
  150. * negBarColor - Color of lose values
  151. * zeroBarColor - Color of draw values
  152. * barWidth - Width of bars in pixels
  153. * barSpacing - Gap between bars in pixels
  154. * colorMap - Optional mappnig of values to colors to override the *BarColor values above
  155. * can be an Array of values to control the color of individual bars or a range map
  156. * to specify colors for individual ranges of values
  157. *
  158. * discrete - Options:
  159. * lineHeight - Height of each line in pixels - Defaults to 30% of the graph height
  160. * thesholdValue - Values less than this value will be drawn using thresholdColor instead of lineColor
  161. * thresholdColor
  162. *
  163. * bullet - Values for bullet graphs msut be in the order: target, performance, range1, range2, range3, ...
  164. * options:
  165. * targetColor - The color of the vertical target marker
  166. * targetWidth - The width of the target marker in pixels
  167. * performanceColor - The color of the performance measure horizontal bar
  168. * rangeColors - Colors to use for each qualitative range background color
  169. *
  170. * pie - Pie chart. Options:
  171. * sliceColors - An array of colors to use for pie slices
  172. * offset - Angle in degrees to offset the first slice - Try -90 or +90
  173. * borderWidth - Width of border to draw around the pie chart, in pixels - Defaults to 0 (no border)
  174. * borderColor - Color to use for the pie chart border - Defaults to #000
  175. *
  176. * box - Box plot. Options:
  177. * raw - Set to true to supply pre-computed plot points as values
  178. * values should be: low_outlier, low_whisker, q1, median, q3, high_whisker, high_outlier
  179. * When set to false you can supply any number of values and the box plot will
  180. * be computed for you. Default is false.
  181. * showOutliers - Set to true (default) to display outliers as circles
  182. * outlierIQR - Interquartile range used to determine outliers. Default 1.5
  183. * boxLineColor - Outline color of the box
  184. * boxFillColor - Fill color for the box
  185. * whiskerColor - Line color used for whiskers
  186. * outlierLineColor - Outline color of outlier circles
  187. * outlierFillColor - Fill color of the outlier circles
  188. * spotRadius - Radius of outlier circles
  189. * medianColor - Line color of the median line
  190. * target - Draw a target cross hair at the supplied value (default undefined)
  191. *
  192. *
  193. *
  194. * Examples:
  195. * $('#sparkline1').sparkline(myvalues, { lineColor: '#f00', fillColor: false });
  196. * $('.barsparks').sparkline('html', { type:'bar', height:'40px', barWidth:5 });
  197. * $('#tristate').sparkline([1,1,-1,1,0,0,-1], { type:'tristate' }):
  198. * $('#discrete').sparkline([1,3,4,5,5,3,4,5], { type:'discrete' });
  199. * $('#bullet').sparkline([10,12,12,9,7], { type:'bullet' });
  200. * $('#pie').sparkline([1,1,2], { type:'pie' });
  201. */
  202. /*jslint regexp: true, browser: true, jquery: true, white: true, nomen: false, plusplus: false, maxerr: 500, indent: 4 */
  203. (function(document, Math, undefined) { // performance/minified-size optimization
  204. (function(factory) {
  205. if(typeof define === 'function' && define.amd) {
  206. define(['jquery'], factory);
  207. } else if (jQuery && !jQuery.fn.sparkline) {
  208. factory(jQuery);
  209. }
  210. }
  211. (function($) {
  212. 'use strict';
  213. var UNSET_OPTION = {},
  214. getDefaults, createClass, SPFormat, clipval, quartile, normalizeValue, normalizeValues,
  215. remove, isNumber, all, sum, addCSS, ensureArray, formatNumber, RangeMap,
  216. MouseHandler, Tooltip, barHighlightMixin,
  217. line, bar, tristate, discrete, bullet, pie, box, defaultStyles, initStyles,
  218. VShape, VCanvas_base, VCanvas_canvas, VCanvas_vml, pending, shapeCount = 0;
  219. /**
  220. * Default configuration settings
  221. */
  222. getDefaults = function () {
  223. return {
  224. // Settings common to most/all chart types
  225. common: {
  226. type: 'line',
  227. lineColor: '#00f',
  228. fillColor: '#cdf',
  229. defaultPixelsPerValue: 3,
  230. width: 'auto',
  231. height: 'auto',
  232. composite: false,
  233. tagValuesAttribute: 'values',
  234. tagOptionsPrefix: 'spark',
  235. enableTagOptions: false,
  236. enableHighlight: true,
  237. highlightLighten: 1.4,
  238. tooltipSkipNull: true,
  239. tooltipPrefix: '',
  240. tooltipSuffix: '',
  241. disableHiddenCheck: false,
  242. numberFormatter: false,
  243. numberDigitGroupCount: 3,
  244. numberDigitGroupSep: ',',
  245. numberDecimalMark: '.',
  246. disableTooltips: false,
  247. disableInteraction: false
  248. },
  249. // Defaults for line charts
  250. line: {
  251. spotColor: '#f80',
  252. highlightSpotColor: '#5f5',
  253. highlightLineColor: '#f22',
  254. spotRadius: 1.5,
  255. minSpotColor: '#f80',
  256. maxSpotColor: '#f80',
  257. lineWidth: 1,
  258. normalRangeMin: undefined,
  259. normalRangeMax: undefined,
  260. normalRangeColor: '#ccc',
  261. drawNormalOnTop: false,
  262. chartRangeMin: undefined,
  263. chartRangeMax: undefined,
  264. chartRangeMinX: undefined,
  265. chartRangeMaxX: undefined,
  266. tooltipFormat: new SPFormat('<span style="color: {{color}}">&#9679;</span> {{prefix}}{{y}}{{suffix}}')
  267. },
  268. // Defaults for bar charts
  269. bar: {
  270. barColor: '#3366cc',
  271. negBarColor: '#f44',
  272. stackedBarColor: ['#3366cc', '#dc3912', '#ff9900', '#109618', '#66aa00',
  273. '#dd4477', '#0099c6', '#990099'],
  274. zeroColor: undefined,
  275. nullColor: undefined,
  276. zeroAxis: true,
  277. barWidth: 4,
  278. barSpacing: 1,
  279. chartRangeMax: undefined,
  280. chartRangeMin: undefined,
  281. chartRangeClip: false,
  282. colorMap: undefined,
  283. tooltipFormat: new SPFormat('<span style="color: {{color}}">&#9679;</span> {{prefix}}{{value}}{{suffix}}')
  284. },
  285. // Defaults for tristate charts
  286. tristate: {
  287. barWidth: 4,
  288. barSpacing: 1,
  289. posBarColor: '#6f6',
  290. negBarColor: '#f44',
  291. zeroBarColor: '#999',
  292. colorMap: {},
  293. tooltipFormat: new SPFormat('<span style="color: {{color}}">&#9679;</span> {{value:map}}'),
  294. tooltipValueLookups: { map: { '-1': 'Loss', '0': 'Draw', '1': 'Win' } }
  295. },
  296. // Defaults for discrete charts
  297. discrete: {
  298. lineHeight: 'auto',
  299. thresholdColor: undefined,
  300. thresholdValue: 0,
  301. chartRangeMax: undefined,
  302. chartRangeMin: undefined,
  303. chartRangeClip: false,
  304. tooltipFormat: new SPFormat('{{prefix}}{{value}}{{suffix}}')
  305. },
  306. // Defaults for bullet charts
  307. bullet: {
  308. targetColor: '#f33',
  309. targetWidth: 3, // width of the target bar in pixels
  310. performanceColor: '#33f',
  311. rangeColors: ['#d3dafe', '#a8b6ff', '#7f94ff'],
  312. base: undefined, // set this to a number to change the base start number
  313. tooltipFormat: new SPFormat('{{fieldkey:fields}} - {{value}}'),
  314. tooltipValueLookups: { fields: {r: 'Range', p: 'Performance', t: 'Target'} }
  315. },
  316. // Defaults for pie charts
  317. pie: {
  318. offset: 0,
  319. sliceColors: ['#3366cc', '#dc3912', '#ff9900', '#109618', '#66aa00',
  320. '#dd4477', '#0099c6', '#990099'],
  321. borderWidth: 0,
  322. borderColor: '#000',
  323. tooltipFormat: new SPFormat('<span style="color: {{color}}">&#9679;</span> {{value}} ({{percent.1}}%)')
  324. },
  325. // Defaults for box plots
  326. box: {
  327. raw: false,
  328. boxLineColor: '#000',
  329. boxFillColor: '#cdf',
  330. whiskerColor: '#000',
  331. outlierLineColor: '#333',
  332. outlierFillColor: '#fff',
  333. medianColor: '#f00',
  334. showOutliers: true,
  335. outlierIQR: 1.5,
  336. spotRadius: 1.5,
  337. target: undefined,
  338. targetColor: '#4a2',
  339. chartRangeMax: undefined,
  340. chartRangeMin: undefined,
  341. tooltipFormat: new SPFormat('{{field:fields}}: {{value}}'),
  342. tooltipFormatFieldlistKey: 'field',
  343. tooltipValueLookups: { fields: { lq: 'Lower Quartile', med: 'Median',
  344. uq: 'Upper Quartile', lo: 'Left Outlier', ro: 'Right Outlier',
  345. lw: 'Left Whisker', rw: 'Right Whisker'} }
  346. }
  347. };
  348. };
  349. // You can have tooltips use a css class other than jqstooltip by specifying tooltipClassname
  350. defaultStyles = '.jqstooltip { ' +
  351. 'position: absolute;' +
  352. 'left: 0px;' +
  353. 'top: 0px;' +
  354. 'visibility: hidden;' +
  355. 'background: rgb(0, 0, 0) transparent;' +
  356. 'background-color: rgba(0,0,0,0.6);' +
  357. 'filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);' +
  358. '-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";' +
  359. 'color: white;' +
  360. 'font: 10px arial, san serif;' +
  361. 'text-align: left;' +
  362. 'white-space: nowrap;' +
  363. 'padding: 5px;' +
  364. 'border: 1px solid white;' +
  365. 'box-sizing: content-box;' +
  366. 'z-index: 10000;' +
  367. '}' +
  368. '.jqsfield { ' +
  369. 'color: white;' +
  370. 'font: 10px arial, san serif;' +
  371. 'text-align: left;' +
  372. '}';
  373. /**
  374. * Utilities
  375. */
  376. createClass = function (/* [baseclass, [mixin, ...]], definition */) {
  377. var Class, args;
  378. Class = function () {
  379. this.init.apply(this, arguments);
  380. };
  381. if (arguments.length > 1) {
  382. if (arguments[0]) {
  383. Class.prototype = $.extend(new arguments[0](), arguments[arguments.length - 1]);
  384. Class._super = arguments[0].prototype;
  385. } else {
  386. Class.prototype = arguments[arguments.length - 1];
  387. }
  388. if (arguments.length > 2) {
  389. args = Array.prototype.slice.call(arguments, 1, -1);
  390. args.unshift(Class.prototype);
  391. $.extend.apply($, args);
  392. }
  393. } else {
  394. Class.prototype = arguments[0];
  395. }
  396. Class.prototype.cls = Class;
  397. return Class;
  398. };
  399. /**
  400. * Wraps a format string for tooltips
  401. * {{x}}
  402. * {{x.2}
  403. * {{x:months}}
  404. */
  405. $.SPFormatClass = SPFormat = createClass({
  406. fre: /\{\{([\w.]+?)(:(.+?))?\}\}/g,
  407. precre: /(\w+)\.(\d+)/,
  408. init: function (format, fclass) {
  409. this.format = format;
  410. this.fclass = fclass;
  411. },
  412. render: function (fieldset, lookups, options) {
  413. var self = this,
  414. fields = fieldset,
  415. match, token, lookupkey, fieldvalue, prec;
  416. return this.format.replace(this.fre, function () {
  417. var lookup;
  418. token = arguments[1];
  419. lookupkey = arguments[3];
  420. match = self.precre.exec(token);
  421. if (match) {
  422. prec = match[2];
  423. token = match[1];
  424. } else {
  425. prec = false;
  426. }
  427. fieldvalue = fields[token];
  428. if (fieldvalue === undefined) {
  429. return '';
  430. }
  431. if (lookupkey && lookups && lookups[lookupkey]) {
  432. lookup = lookups[lookupkey];
  433. if (lookup.get) { // RangeMap
  434. return lookups[lookupkey].get(fieldvalue) || fieldvalue;
  435. } else {
  436. return lookups[lookupkey][fieldvalue] || fieldvalue;
  437. }
  438. }
  439. if (isNumber(fieldvalue)) {
  440. if (options.get('numberFormatter')) {
  441. fieldvalue = options.get('numberFormatter')(fieldvalue);
  442. } else {
  443. fieldvalue = formatNumber(fieldvalue, prec,
  444. options.get('numberDigitGroupCount'),
  445. options.get('numberDigitGroupSep'),
  446. options.get('numberDecimalMark'));
  447. }
  448. }
  449. return fieldvalue;
  450. });
  451. }
  452. });
  453. // convience method to avoid needing the new operator
  454. $.spformat = function(format, fclass) {
  455. return new SPFormat(format, fclass);
  456. };
  457. clipval = function (val, min, max) {
  458. if (val < min) {
  459. return min;
  460. }
  461. if (val > max) {
  462. return max;
  463. }
  464. return val;
  465. };
  466. quartile = function (values, q) {
  467. var vl;
  468. if (q === 2) {
  469. vl = Math.floor(values.length / 2);
  470. return values.length % 2 ? values[vl] : (values[vl-1] + values[vl]) / 2;
  471. } else {
  472. if (values.length % 2 ) { // odd
  473. vl = (values.length * q + q) / 4;
  474. return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1];
  475. } else { //even
  476. vl = (values.length * q + 2) / 4;
  477. return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1];
  478. }
  479. }
  480. };
  481. normalizeValue = function (val) {
  482. var nf;
  483. switch (val) {
  484. case 'undefined':
  485. val = undefined;
  486. break;
  487. case 'null':
  488. val = null;
  489. break;
  490. case 'true':
  491. val = true;
  492. break;
  493. case 'false':
  494. val = false;
  495. break;
  496. default:
  497. nf = parseFloat(val);
  498. if (val == nf) {
  499. val = nf;
  500. }
  501. }
  502. return val;
  503. };
  504. normalizeValues = function (vals) {
  505. var i, result = [];
  506. for (i = vals.length; i--;) {
  507. result[i] = normalizeValue(vals[i]);
  508. }
  509. return result;
  510. };
  511. remove = function (vals, filter) {
  512. var i, vl, result = [];
  513. for (i = 0, vl = vals.length; i < vl; i++) {
  514. if (vals[i] !== filter) {
  515. result.push(vals[i]);
  516. }
  517. }
  518. return result;
  519. };
  520. isNumber = function (num) {
  521. return !isNaN(parseFloat(num)) && isFinite(num);
  522. };
  523. formatNumber = function (num, prec, groupsize, groupsep, decsep) {
  524. var p, i;
  525. num = (prec === false ? parseFloat(num).toString() : num.toFixed(prec)).split('');
  526. p = (p = $.inArray('.', num)) < 0 ? num.length : p;
  527. if (p < num.length) {
  528. num[p] = decsep;
  529. }
  530. for (i = p - groupsize; i > 0; i -= groupsize) {
  531. num.splice(i, 0, groupsep);
  532. }
  533. return num.join('');
  534. };
  535. // determine if all values of an array match a value
  536. // returns true if the array is empty
  537. all = function (val, arr, ignoreNull) {
  538. var i;
  539. for (i = arr.length; i--; ) {
  540. if (ignoreNull && arr[i] === null) continue;
  541. if (arr[i] !== val) {
  542. return false;
  543. }
  544. }
  545. return true;
  546. };
  547. // sums the numeric values in an array, ignoring other values
  548. sum = function (vals) {
  549. var total = 0, i;
  550. for (i = vals.length; i--;) {
  551. total += typeof vals[i] === 'number' ? vals[i] : 0;
  552. }
  553. return total;
  554. };
  555. ensureArray = function (val) {
  556. return $.isArray(val) ? val : [val];
  557. };
  558. // http://paulirish.com/2008/bookmarklet-inject-new-css-rules/
  559. addCSS = function(css) {
  560. var tag, iefail;
  561. if (document.createStyleSheet) {
  562. try {
  563. document.createStyleSheet().cssText = css;
  564. return;
  565. } catch (e) {
  566. // IE <= 9 maxes out at 31 stylesheets; inject into page instead.
  567. iefail = true;
  568. }
  569. }
  570. tag = document.createElement('style');
  571. tag.type = 'text/css';
  572. document.getElementsByTagName('head')[0].appendChild(tag);
  573. if (iefail) {
  574. document.styleSheets[document.styleSheets.length - 1].cssText = css;
  575. } else {
  576. tag[(typeof document.body.style.WebkitAppearance == 'string') /* webkit only */ ? 'innerText' : 'innerHTML'] = css;
  577. }
  578. };
  579. // Provide a cross-browser interface to a few simple drawing primitives
  580. $.fn.simpledraw = function (width, height, useExisting, interact) {
  581. var target, mhandler;
  582. if (useExisting && (target = this.data('_jqs_vcanvas'))) {
  583. return target;
  584. }
  585. if ($.fn.sparkline.canvas === false) {
  586. // We've already determined that neither Canvas nor VML are available
  587. return false;
  588. } else if ($.fn.sparkline.canvas === undefined) {
  589. // No function defined yet -- need to see if we support Canvas or VML
  590. var el = document.createElement('canvas');
  591. if (!!(el.getContext && el.getContext('2d'))) {
  592. // Canvas is available
  593. $.fn.sparkline.canvas = function(width, height, target, interact) {
  594. return new VCanvas_canvas(width, height, target, interact);
  595. };
  596. } else if (document.namespaces && !document.namespaces.v) {
  597. // VML is available
  598. document.namespaces.add('v', 'urn:schemas-microsoft-com:vml', '#default#VML');
  599. $.fn.sparkline.canvas = function(width, height, target, interact) {
  600. return new VCanvas_vml(width, height, target);
  601. };
  602. } else {
  603. // Neither Canvas nor VML are available
  604. $.fn.sparkline.canvas = false;
  605. return false;
  606. }
  607. }
  608. if (width === undefined) {
  609. width = $(this).innerWidth();
  610. }
  611. if (height === undefined) {
  612. height = $(this).innerHeight();
  613. }
  614. target = $.fn.sparkline.canvas(width, height, this, interact);
  615. mhandler = $(this).data('_jqs_mhandler');
  616. if (mhandler) {
  617. mhandler.registerCanvas(target);
  618. }
  619. return target;
  620. };
  621. $.fn.cleardraw = function () {
  622. var target = this.data('_jqs_vcanvas');
  623. if (target) {
  624. target.reset();
  625. }
  626. };
  627. $.RangeMapClass = RangeMap = createClass({
  628. init: function (map) {
  629. var key, range, rangelist = [];
  630. for (key in map) {
  631. if (map.hasOwnProperty(key) && typeof key === 'string' && key.indexOf(':') > -1) {
  632. range = key.split(':');
  633. range[0] = range[0].length === 0 ? -Infinity : parseFloat(range[0]);
  634. range[1] = range[1].length === 0 ? Infinity : parseFloat(range[1]);
  635. range[2] = map[key];
  636. rangelist.push(range);
  637. }
  638. }
  639. this.map = map;
  640. this.rangelist = rangelist || false;
  641. },
  642. get: function (value) {
  643. var rangelist = this.rangelist,
  644. i, range, result;
  645. if ((result = this.map[value]) !== undefined) {
  646. return result;
  647. }
  648. if (rangelist) {
  649. for (i = rangelist.length; i--;) {
  650. range = rangelist[i];
  651. if (range[0] <= value && range[1] >= value) {
  652. return range[2];
  653. }
  654. }
  655. }
  656. return undefined;
  657. }
  658. });
  659. // Convenience function
  660. $.range_map = function(map) {
  661. return new RangeMap(map);
  662. };
  663. MouseHandler = createClass({
  664. init: function (el, options) {
  665. var $el = $(el);
  666. this.$el = $el;
  667. this.options = options;
  668. this.currentPageX = 0;
  669. this.currentPageY = 0;
  670. this.el = el;
  671. this.splist = [];
  672. this.tooltip = null;
  673. this.over = false;
  674. this.displayTooltips = !options.get('disableTooltips');
  675. this.highlightEnabled = !options.get('disableHighlight');
  676. },
  677. registerSparkline: function (sp) {
  678. this.splist.push(sp);
  679. if (this.over) {
  680. this.updateDisplay();
  681. }
  682. },
  683. registerCanvas: function (canvas) {
  684. var $canvas = $(canvas.canvas);
  685. this.canvas = canvas;
  686. this.$canvas = $canvas;
  687. $canvas.mouseenter($.proxy(this.mouseenter, this));
  688. $canvas.mouseleave($.proxy(this.mouseleave, this));
  689. $canvas.click($.proxy(this.mouseclick, this));
  690. },
  691. reset: function (removeTooltip) {
  692. this.splist = [];
  693. if (this.tooltip && removeTooltip) {
  694. this.tooltip.remove();
  695. this.tooltip = undefined;
  696. }
  697. },
  698. mouseclick: function (e) {
  699. var clickEvent = $.Event('sparklineClick');
  700. clickEvent.originalEvent = e;
  701. clickEvent.sparklines = this.splist;
  702. this.$el.trigger(clickEvent);
  703. },
  704. mouseenter: function (e) {
  705. $(document.body).unbind('mousemove.jqs');
  706. $(document.body).bind('mousemove.jqs', $.proxy(this.mousemove, this));
  707. this.over = true;
  708. this.currentPageX = e.pageX;
  709. this.currentPageY = e.pageY;
  710. this.currentEl = e.target;
  711. if (!this.tooltip && this.displayTooltips) {
  712. this.tooltip = new Tooltip(this.options);
  713. this.tooltip.updatePosition(e.pageX, e.pageY);
  714. }
  715. this.updateDisplay();
  716. },
  717. mouseleave: function () {
  718. $(document.body).unbind('mousemove.jqs');
  719. var splist = this.splist,
  720. spcount = splist.length,
  721. needsRefresh = false,
  722. sp, i;
  723. this.over = false;
  724. this.currentEl = null;
  725. if (this.tooltip) {
  726. this.tooltip.remove();
  727. this.tooltip = null;
  728. }
  729. for (i = 0; i < spcount; i++) {
  730. sp = splist[i];
  731. if (sp.clearRegionHighlight()) {
  732. needsRefresh = true;
  733. }
  734. }
  735. if (needsRefresh) {
  736. this.canvas.render();
  737. }
  738. },
  739. mousemove: function (e) {
  740. this.currentPageX = e.pageX;
  741. this.currentPageY = e.pageY;
  742. this.currentEl = e.target;
  743. if (this.tooltip) {
  744. this.tooltip.updatePosition(e.pageX, e.pageY);
  745. }
  746. this.updateDisplay();
  747. },
  748. updateDisplay: function () {
  749. var splist = this.splist,
  750. spcount = splist.length,
  751. needsRefresh = false,
  752. offset = this.$canvas.offset(),
  753. localX = this.currentPageX - offset.left,
  754. localY = this.currentPageY - offset.top,
  755. tooltiphtml, sp, i, result, changeEvent;
  756. if (!this.over) {
  757. return;
  758. }
  759. for (i = 0; i < spcount; i++) {
  760. sp = splist[i];
  761. result = sp.setRegionHighlight(this.currentEl, localX, localY);
  762. if (result) {
  763. needsRefresh = true;
  764. }
  765. }
  766. if (needsRefresh) {
  767. changeEvent = $.Event('sparklineRegionChange');
  768. changeEvent.sparklines = this.splist;
  769. this.$el.trigger(changeEvent);
  770. if (this.tooltip) {
  771. tooltiphtml = '';
  772. for (i = 0; i < spcount; i++) {
  773. sp = splist[i];
  774. tooltiphtml += sp.getCurrentRegionTooltip();
  775. }
  776. this.tooltip.setContent(tooltiphtml);
  777. }
  778. if (!this.disableHighlight) {
  779. this.canvas.render();
  780. }
  781. }
  782. if (result === null) {
  783. this.mouseleave();
  784. }
  785. }
  786. });
  787. Tooltip = createClass({
  788. sizeStyle: 'position: static !important;' +
  789. 'display: block !important;' +
  790. 'visibility: hidden !important;' +
  791. 'float: left !important;',
  792. init: function (options) {
  793. var tooltipClassname = options.get('tooltipClassname', 'jqstooltip'),
  794. sizetipStyle = this.sizeStyle,
  795. offset;
  796. this.container = options.get('tooltipContainer') || document.body;
  797. this.tooltipOffsetX = options.get('tooltipOffsetX', 10);
  798. this.tooltipOffsetY = options.get('tooltipOffsetY', 12);
  799. // remove any previous lingering tooltip
  800. $('#jqssizetip').remove();
  801. $('#jqstooltip').remove();
  802. this.sizetip = $('<div/>', {
  803. id: 'jqssizetip',
  804. style: sizetipStyle,
  805. 'class': tooltipClassname
  806. });
  807. this.tooltip = $('<div/>', {
  808. id: 'jqstooltip',
  809. 'class': tooltipClassname
  810. }).appendTo(this.container);
  811. // account for the container's location
  812. offset = this.tooltip.offset();
  813. this.offsetLeft = offset.left;
  814. this.offsetTop = offset.top;
  815. this.hidden = true;
  816. $(window).unbind('resize.jqs scroll.jqs');
  817. $(window).bind('resize.jqs scroll.jqs', $.proxy(this.updateWindowDims, this));
  818. this.updateWindowDims();
  819. },
  820. updateWindowDims: function () {
  821. this.scrollTop = $(window).scrollTop();
  822. this.scrollLeft = $(window).scrollLeft();
  823. this.scrollRight = this.scrollLeft + $(window).width();
  824. this.updatePosition();
  825. },
  826. getSize: function (content) {
  827. this.sizetip.html(content).appendTo(this.container);
  828. this.width = this.sizetip.width() + 1;
  829. this.height = this.sizetip.height();
  830. this.sizetip.remove();
  831. },
  832. setContent: function (content) {
  833. if (!content) {
  834. this.tooltip.css('visibility', 'hidden');
  835. this.hidden = true;
  836. return;
  837. }
  838. this.getSize(content);
  839. this.tooltip.html(content)
  840. .css({
  841. 'width': this.width,
  842. 'height': this.height,
  843. 'visibility': 'visible'
  844. });
  845. if (this.hidden) {
  846. this.hidden = false;
  847. this.updatePosition();
  848. }
  849. },
  850. updatePosition: function (x, y) {
  851. if (x === undefined) {
  852. if (this.mousex === undefined) {
  853. return;
  854. }
  855. x = this.mousex - this.offsetLeft;
  856. y = this.mousey - this.offsetTop;
  857. } else {
  858. this.mousex = x = x - this.offsetLeft;
  859. this.mousey = y = y - this.offsetTop;
  860. }
  861. if (!this.height || !this.width || this.hidden) {
  862. return;
  863. }
  864. y -= this.height + this.tooltipOffsetY;
  865. x += this.tooltipOffsetX;
  866. if (y < this.scrollTop) {
  867. y = this.scrollTop;
  868. }
  869. if (x < this.scrollLeft) {
  870. x = this.scrollLeft;
  871. } else if (x + this.width > this.scrollRight) {
  872. x = this.scrollRight - this.width;
  873. }
  874. this.tooltip.css({
  875. 'left': x,
  876. 'top': y
  877. });
  878. },
  879. remove: function () {
  880. this.tooltip.remove();
  881. this.sizetip.remove();
  882. this.sizetip = this.tooltip = undefined;
  883. $(window).unbind('resize.jqs scroll.jqs');
  884. }
  885. });
  886. initStyles = function() {
  887. addCSS(defaultStyles);
  888. };
  889. $(initStyles);
  890. pending = [];
  891. $.fn.sparkline = function (userValues, userOptions) {
  892. return this.each(function () {
  893. var options = new $.fn.sparkline.options(this, userOptions),
  894. $this = $(this),
  895. render, i;
  896. render = function () {
  897. var values, width, height, tmp, mhandler, sp, vals;
  898. if (userValues === 'html' || userValues === undefined) {
  899. vals = this.getAttribute(options.get('tagValuesAttribute'));
  900. if (vals === undefined || vals === null) {
  901. vals = $this.html();
  902. }
  903. values = vals.replace(/(^\s*<!--)|(-->\s*$)|\s+/g, '').split(',');
  904. } else {
  905. values = userValues;
  906. }
  907. width = options.get('width') === 'auto' ? values.length * options.get('defaultPixelsPerValue') : options.get('width');
  908. if (options.get('height') === 'auto') {
  909. if (!options.get('composite') || !$.data(this, '_jqs_vcanvas')) {
  910. // must be a better way to get the line height
  911. tmp = document.createElement('span');
  912. tmp.innerHTML = 'a';
  913. $this.html(tmp);
  914. height = $(tmp).innerHeight() || $(tmp).height();
  915. $(tmp).remove();
  916. tmp = null;
  917. }
  918. } else {
  919. height = options.get('height');
  920. }
  921. if (!options.get('disableInteraction')) {
  922. mhandler = $.data(this, '_jqs_mhandler');
  923. if (!mhandler) {
  924. mhandler = new MouseHandler(this, options);
  925. $.data(this, '_jqs_mhandler', mhandler);
  926. } else if (!options.get('composite')) {
  927. mhandler.reset();
  928. }
  929. } else {
  930. mhandler = false;
  931. }
  932. if (options.get('composite') && !$.data(this, '_jqs_vcanvas')) {
  933. if (!$.data(this, '_jqs_errnotify')) {
  934. alert('Attempted to attach a composite sparkline to an element with no existing sparkline');
  935. $.data(this, '_jqs_errnotify', true);
  936. }
  937. return;
  938. }
  939. sp = new $.fn.sparkline[options.get('type')](this, values, options, width, height);
  940. sp.render();
  941. if (mhandler) {
  942. mhandler.registerSparkline(sp);
  943. }
  944. };
  945. if (($(this).html() && !options.get('disableHiddenCheck') && $(this).is(':hidden')) || !$(this).parents('body').length) {
  946. if (!options.get('composite') && $.data(this, '_jqs_pending')) {
  947. // remove any existing references to the element
  948. for (i = pending.length; i; i--) {
  949. if (pending[i - 1][0] == this) {
  950. pending.splice(i - 1, 1);
  951. }
  952. }
  953. }
  954. pending.push([this, render]);
  955. $.data(this, '_jqs_pending', true);
  956. } else {
  957. render.call(this);
  958. }
  959. });
  960. };
  961. $.fn.sparkline.defaults = getDefaults();
  962. $.sparkline_display_visible = function () {
  963. var el, i, pl;
  964. var done = [];
  965. for (i = 0, pl = pending.length; i < pl; i++) {
  966. el = pending[i][0];
  967. if ($(el).is(':visible') && !$(el).parents().is(':hidden')) {
  968. pending[i][1].call(el);
  969. $.data(pending[i][0], '_jqs_pending', false);
  970. done.push(i);
  971. } else if (!$(el).closest('html').length && !$.data(el, '_jqs_pending')) {
  972. // element has been inserted and removed from the DOM
  973. // If it was not yet inserted into the dom then the .data request
  974. // will return true.
  975. // removing from the dom causes the data to be removed.
  976. $.data(pending[i][0], '_jqs_pending', false);
  977. done.push(i);
  978. }
  979. }
  980. for (i = done.length; i; i--) {
  981. pending.splice(done[i - 1], 1);
  982. }
  983. };
  984. /**
  985. * User option handler
  986. */
  987. $.fn.sparkline.options = createClass({
  988. init: function (tag, userOptions) {
  989. var extendedOptions, defaults, base, tagOptionType;
  990. this.userOptions = userOptions = userOptions || {};
  991. this.tag = tag;
  992. this.tagValCache = {};
  993. defaults = $.fn.sparkline.defaults;
  994. base = defaults.common;
  995. this.tagOptionsPrefix = userOptions.enableTagOptions && (userOptions.tagOptionsPrefix || base.tagOptionsPrefix);
  996. tagOptionType = this.getTagSetting('type');
  997. if (tagOptionType === UNSET_OPTION) {
  998. extendedOptions = defaults[userOptions.type || base.type];
  999. } else {
  1000. extendedOptions = defaults[tagOptionType];
  1001. }
  1002. this.mergedOptions = $.extend({}, base, extendedOptions, userOptions);
  1003. },
  1004. getTagSetting: function (key) {
  1005. var prefix = this.tagOptionsPrefix,
  1006. val, i, pairs, keyval;
  1007. if (prefix === false || prefix === undefined) {
  1008. return UNSET_OPTION;
  1009. }
  1010. if (this.tagValCache.hasOwnProperty(key)) {
  1011. val = this.tagValCache.key;
  1012. } else {
  1013. val = this.tag.getAttribute(prefix + key);
  1014. if (val === undefined || val === null) {
  1015. val = UNSET_OPTION;
  1016. } else if (val.substr(0, 1) === '[') {
  1017. val = val.substr(1, val.length - 2).split(',');
  1018. for (i = val.length; i--;) {
  1019. val[i] = normalizeValue(val[i].replace(/(^\s*)|(\s*$)/g, ''));
  1020. }
  1021. } else if (val.substr(0, 1) === '{') {
  1022. pairs = val.substr(1, val.length - 2).split(',');
  1023. val = {};
  1024. for (i = pairs.length; i--;) {
  1025. keyval = pairs[i].split(':', 2);
  1026. val[keyval[0].replace(/(^\s*)|(\s*$)/g, '')] = normalizeValue(keyval[1].replace(/(^\s*)|(\s*$)/g, ''));
  1027. }
  1028. } else {
  1029. val = normalizeValue(val);
  1030. }
  1031. this.tagValCache.key = val;
  1032. }
  1033. return val;
  1034. },
  1035. get: function (key, defaultval) {
  1036. var tagOption = this.getTagSetting(key),
  1037. result;
  1038. if (tagOption !== UNSET_OPTION) {
  1039. return tagOption;
  1040. }
  1041. return (result = this.mergedOptions[key]) === undefined ? defaultval : result;
  1042. }
  1043. });
  1044. $.fn.sparkline._base = createClass({
  1045. disabled: false,
  1046. init: function (el, values, options, width, height) {
  1047. this.el = el;
  1048. this.$el = $(el);
  1049. this.values = values;
  1050. this.options = options;
  1051. this.width = width;
  1052. this.height = height;
  1053. this.currentRegion = undefined;
  1054. },
  1055. /**
  1056. * Setup the canvas
  1057. */
  1058. initTarget: function () {
  1059. var interactive = !this.options.get('disableInteraction');
  1060. if (!(this.target = this.$el.simpledraw(this.width, this.height, this.options.get('composite'), interactive))) {
  1061. this.disabled = true;
  1062. } else {
  1063. this.canvasWidth = this.target.pixelWidth;
  1064. this.canvasHeight = this.target.pixelHeight;
  1065. }
  1066. },
  1067. /**
  1068. * Actually render the chart to the canvas
  1069. */
  1070. render: function () {
  1071. if (this.disabled) {
  1072. this.el.innerHTML = '';
  1073. return false;
  1074. }
  1075. return true;
  1076. },
  1077. /**
  1078. * Return a region id for a given x/y co-ordinate
  1079. */
  1080. getRegion: function (x, y) {
  1081. },
  1082. /**
  1083. * Highlight an item based on the moused-over x,y co-ordinate
  1084. */
  1085. setRegionHighlight: function (el, x, y) {
  1086. var currentRegion = this.currentRegion,
  1087. highlightEnabled = !this.options.get('disableHighlight'),
  1088. newRegion;
  1089. if (x > this.canvasWidth || y > this.canvasHeight || x < 0 || y < 0) {
  1090. return null;
  1091. }
  1092. newRegion = this.getRegion(el, x, y);
  1093. if (currentRegion !== newRegion) {
  1094. if (currentRegion !== undefined && highlightEnabled) {
  1095. this.removeHighlight();
  1096. }
  1097. this.currentRegion = newRegion;
  1098. if (newRegion !== undefined && highlightEnabled) {
  1099. this.renderHighlight();
  1100. }
  1101. return true;
  1102. }
  1103. return false;
  1104. },
  1105. /**
  1106. * Reset any currently highlighted item
  1107. */
  1108. clearRegionHighlight: function () {
  1109. if (this.currentRegion !== undefined) {
  1110. this.removeHighlight();
  1111. this.currentRegion = undefined;
  1112. return true;
  1113. }
  1114. return false;
  1115. },
  1116. renderHighlight: function () {
  1117. this.changeHighlight(true);
  1118. },
  1119. removeHighlight: function () {
  1120. this.changeHighlight(false);
  1121. },
  1122. changeHighlight: function (highlight) {},
  1123. /**
  1124. * Fetch the HTML to display as a tooltip
  1125. */
  1126. getCurrentRegionTooltip: function () {
  1127. var options = this.options,
  1128. header = '',
  1129. entries = [],
  1130. fields, formats, formatlen, fclass, text, i,
  1131. showFields, showFieldsKey, newFields, fv,
  1132. formatter, format, fieldlen, j;
  1133. if (this.currentRegion === undefined) {
  1134. return '';
  1135. }
  1136. fields = this.getCurrentRegionFields();
  1137. formatter = options.get('tooltipFormatter');
  1138. if (formatter) {
  1139. return formatter(this, options, fields);
  1140. }
  1141. if (options.get('tooltipChartTitle')) {
  1142. header += '<div class="jqs jqstitle">' + options.get('tooltipChartTitle') + '</div>\n';
  1143. }
  1144. formats = this.options.get('tooltipFormat');
  1145. if (!formats) {
  1146. return '';
  1147. }
  1148. if (!$.isArray(formats)) {
  1149. formats = [formats];
  1150. }
  1151. if (!$.isArray(fields)) {
  1152. fields = [fields];
  1153. }
  1154. showFields = this.options.get('tooltipFormatFieldlist');
  1155. showFieldsKey = this.options.get('tooltipFormatFieldlistKey');
  1156. if (showFields && showFieldsKey) {
  1157. // user-selected ordering of fields
  1158. newFields = [];
  1159. for (i = fields.length; i--;) {
  1160. fv = fields[i][showFieldsKey];
  1161. if ((j = $.inArray(fv, showFields)) != -1) {
  1162. newFields[j] = fields[i];
  1163. }
  1164. }
  1165. fields = newFields;
  1166. }
  1167. formatlen = formats.length;
  1168. fieldlen = fields.length;
  1169. for (i = 0; i < formatlen; i++) {
  1170. format = formats[i];
  1171. if (typeof format === 'string') {
  1172. format = new SPFormat(format);
  1173. }
  1174. fclass = format.fclass || 'jqsfield';
  1175. for (j = 0; j < fieldlen; j++) {
  1176. if (!fields[j].isNull || !options.get('tooltipSkipNull')) {
  1177. $.extend(fields[j], {
  1178. prefix: options.get('tooltipPrefix'),
  1179. suffix: options.get('tooltipSuffix')
  1180. });
  1181. text = format.render(fields[j], options.get('tooltipValueLookups'), options);
  1182. entries.push('<div class="' + fclass + '">' + text + '</div>');
  1183. }
  1184. }
  1185. }
  1186. if (entries.length) {
  1187. return header + entries.join('\n');
  1188. }
  1189. return '';
  1190. },
  1191. getCurrentRegionFields: function () {},
  1192. calcHighlightColor: function (color, options) {
  1193. var highlightColor = options.get('highlightColor'),
  1194. lighten = options.get('highlightLighten'),
  1195. parse, mult, rgbnew, i;
  1196. if (highlightColor) {
  1197. return highlightColor;
  1198. }
  1199. if (lighten) {
  1200. // extract RGB values
  1201. parse = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(color) || /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color);
  1202. if (parse) {
  1203. rgbnew = [];
  1204. mult = color.length === 4 ? 16 : 1;
  1205. for (i = 0; i < 3; i++) {
  1206. rgbnew[i] = clipval(Math.round(parseInt(parse[i + 1], 16) * mult * lighten), 0, 255);
  1207. }
  1208. return 'rgb(' + rgbnew.join(',') + ')';
  1209. }
  1210. }
  1211. return color;
  1212. }
  1213. });
  1214. barHighlightMixin = {
  1215. changeHighlight: function (highlight) {
  1216. var currentRegion = this.currentRegion,
  1217. target = this.target,
  1218. shapeids = this.regionShapes[currentRegion],
  1219. newShapes;
  1220. // will be null if the region value was null
  1221. if (shapeids) {
  1222. newShapes = this.renderRegion(currentRegion, highlight);
  1223. if ($.isArray(newShapes) || $.isArray(shapeids)) {
  1224. target.replaceWithShapes(shapeids, newShapes);
  1225. this.regionShapes[currentRegion] = $.map(newShapes, function (newShape) {
  1226. return newShape.id;
  1227. });
  1228. } else {
  1229. target.replaceWithShape(shapeids, newShapes);
  1230. this.regionShapes[currentRegion] = newShapes.id;
  1231. }
  1232. }
  1233. },
  1234. render: function () {
  1235. var values = this.values,
  1236. target = this.target,
  1237. regionShapes = this.regionShapes,
  1238. shapes, ids, i, j;
  1239. if (!this.cls._super.render.call(this)) {
  1240. return;
  1241. }
  1242. for (i = values.length; i--;) {
  1243. shapes = this.renderRegion(i);
  1244. if (shapes) {
  1245. if ($.isArray(shapes)) {
  1246. ids = [];
  1247. for (j = shapes.length; j--;) {
  1248. shapes[j].append();
  1249. ids.push(shapes[j].id);
  1250. }
  1251. regionShapes[i] = ids;
  1252. } else {
  1253. shapes.append();
  1254. regionShapes[i] = shapes.id; // store just the shapeid
  1255. }
  1256. } else {
  1257. // null value
  1258. regionShapes[i] = null;
  1259. }
  1260. }
  1261. target.render();
  1262. }
  1263. };
  1264. /**
  1265. * Line charts
  1266. */
  1267. $.fn.sparkline.line = line = createClass($.fn.sparkline._base, {
  1268. type: 'line',
  1269. init: function (el, values, options, width, height) {
  1270. line._super.init.call(this, el, values, options, width, height);
  1271. this.vertices = [];
  1272. this.regionMap = [];
  1273. this.xvalues = [];
  1274. this.yvalues = [];
  1275. this.yminmax = [];
  1276. this.hightlightSpotId = null;
  1277. this.lastShapeId = null;
  1278. this.initTarget();
  1279. },
  1280. getRegion: function (el, x, y) {
  1281. var i,
  1282. regionMap = this.regionMap; // maps regions to value positions
  1283. for (i = regionMap.length; i--;) {
  1284. if (regionMap[i] !== null && x >= regionMap[i][0] && x <= regionMap[i][1]) {
  1285. return regionMap[i][2];
  1286. }
  1287. }
  1288. return undefined;
  1289. },
  1290. getCurrentRegionFields: function () {
  1291. var currentRegion = this.currentRegion;
  1292. return {
  1293. isNull: this.yvalues[currentRegion] === null,
  1294. x: this.xvalues[currentRegion],
  1295. y: this.yvalues[currentRegion],
  1296. color: this.options.get('lineColor'),
  1297. fillColor: this.options.get('fillColor'),
  1298. offset: currentRegion
  1299. };
  1300. },
  1301. renderHighlight: function () {
  1302. var currentRegion = this.currentRegion,
  1303. target = this.target,
  1304. vertex = this.vertices[currentRegion],
  1305. options = this.options,
  1306. spotRadius = options.get('spotRadius'),
  1307. highlightSpotColor = options.get('highlightSpotColor'),
  1308. highlightLineColor = options.get('highlightLineColor'),
  1309. highlightSpot, highlightLine;
  1310. if (!vertex) {
  1311. return;
  1312. }
  1313. if (spotRadius && highlightSpotColor) {
  1314. highlightSpot = target.drawCircle(vertex[0], vertex[1],
  1315. spotRadius, undefined, highlightSpotColor);
  1316. this.highlightSpotId = highlightSpot.id;
  1317. target.insertAfterShape(this.lastShapeId, highlightSpot);
  1318. }
  1319. if (highlightLineColor) {
  1320. highlightLine = target.drawLine(vertex[0], this.canvasTop, vertex[0],
  1321. this.canvasTop + this.canvasHeight, highlightLineColor);
  1322. this.highlightLineId = highlightLine.id;
  1323. target.insertAfterShape(this.lastShapeId, highlightLine);
  1324. }
  1325. },
  1326. removeHighlight: function () {
  1327. var target = this.target;
  1328. if (this.highlightSpotId) {
  1329. target.removeShapeId(this.highlightSpotId);
  1330. this.highlightSpotId = null;
  1331. }
  1332. if (this.highlightLineId) {
  1333. target.removeShapeId(this.highlightLineId);
  1334. this.highlightLineId = null;
  1335. }
  1336. },
  1337. scanValues: function () {
  1338. var values = this.values,
  1339. valcount = values.length,
  1340. xvalues = this.xvalues,
  1341. yvalues = this.yvalues,
  1342. yminmax = this.yminmax,
  1343. i, val, isStr, isArray, sp;
  1344. for (i = 0; i < valcount; i++) {
  1345. val = values[i];
  1346. isStr = typeof(values[i]) === 'string';
  1347. isArray = typeof(values[i]) === 'object' && values[i] instanceof Array;
  1348. sp = isStr && values[i].split(':');
  1349. if (isStr && sp.length === 2) { // x:y
  1350. xvalues.push(Number(sp[0]));
  1351. yvalues.push(Number(sp[1]));
  1352. yminmax.push(Number(sp[1]));
  1353. } else if (isArray) {
  1354. xvalues.push(val[0]);
  1355. yvalues.push(val[1]);
  1356. yminmax.push(val[1]);
  1357. } else {
  1358. xvalues.push(i);
  1359. if (values[i] === null || values[i] === 'null') {
  1360. yvalues.push(null);
  1361. } else {
  1362. yvalues.push(Number(val));
  1363. yminmax.push(Number(val));
  1364. }
  1365. }
  1366. }
  1367. if (this.options.get('xvalues')) {
  1368. xvalues = this.options.get('xvalues');
  1369. }
  1370. this.maxy = this.maxyorg = Math.max.apply(Math, yminmax);
  1371. this.miny = this.minyorg = Math.min.apply(Math, yminmax);
  1372. this.maxx = Math.max.apply(Math, xvalues);
  1373. this.minx = Math.min.apply(Math, xvalues);
  1374. this.xvalues = xvalues;
  1375. this.yvalues = yvalues;
  1376. this.yminmax = yminmax;
  1377. },
  1378. processRangeOptions: function () {
  1379. var options = this.options,
  1380. normalRangeMin = options.get('normalRangeMin'),
  1381. normalRangeMax = options.get('normalRangeMax');
  1382. if (normalRangeMin !== undefined) {
  1383. if (normalRangeMin < this.miny) {
  1384. this.miny = normalRangeMin;
  1385. }
  1386. if (normalRangeMax > this.maxy) {
  1387. this.maxy = normalRangeMax;
  1388. }
  1389. }
  1390. if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.miny)) {
  1391. this.miny = options.get('chartRangeMin');
  1392. }
  1393. if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.maxy)) {
  1394. this.maxy = options.get('chartRangeMax');
  1395. }
  1396. if (options.get('chartRangeMinX') !== undefined && (options.get('chartRangeClipX') || options.get('chartRangeMinX') < this.minx)) {
  1397. this.minx = options.get('chartRangeMinX');
  1398. }
  1399. if (options.get('chartRangeMaxX') !== undefined && (options.get('chartRangeClipX') || options.get('chartRangeMaxX') > this.maxx)) {
  1400. this.maxx = options.get('chartRangeMaxX');
  1401. }
  1402. },
  1403. drawNormalRange: function (canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey) {
  1404. var normalRangeMin = this.options.get('normalRangeMin'),
  1405. normalRangeMax = this.options.get('normalRangeMax'),
  1406. ytop = canvasTop + Math.round(canvasHeight - (canvasHeight * ((normalRangeMax - this.miny) / rangey))),
  1407. height = Math.round((canvasHeight * (normalRangeMax - normalRangeMin)) / rangey);
  1408. this.target.drawRect(canvasLeft, ytop, canvasWidth, height, undefined, this.options.get('normalRangeColor')).append();
  1409. },
  1410. render: function () {
  1411. var options = this.options,
  1412. target = this.target,
  1413. canvasWidth = this.canvasWidth,
  1414. canvasHeight = this.canvasHeight,
  1415. vertices = this.vertices,
  1416. spotRadius = options.get('spotRadius'),
  1417. regionMap = this.regionMap,
  1418. rangex, rangey, yvallast,
  1419. canvasTop, canvasLeft,
  1420. vertex, path, paths, x, y, xnext, xpos, xposnext,
  1421. last, next, yvalcount, lineShapes, fillShapes, plen,
  1422. valueSpots, hlSpotsEnabled, color, xvalues, yvalues, i;
  1423. if (!line._super.render.call(this)) {
  1424. return;
  1425. }
  1426. this.scanValues();
  1427. this.processRangeOptions();
  1428. xvalues = this.xvalues;
  1429. yvalues = this.yvalues;
  1430. if (!this.yminmax.length || this.yvalues.length < 2) {
  1431. // empty or all null valuess
  1432. return;
  1433. }
  1434. canvasTop = canvasLeft = 0;
  1435. rangex = this.maxx - this.minx === 0 ? 1 : this.maxx - this.minx;
  1436. rangey = this.maxy - this.miny === 0 ? 1 : this.maxy - this.miny;
  1437. yvallast = this.yvalues.length - 1;
  1438. if (spotRadius && (canvasWidth < (spotRadius * 4) || canvasHeight < (spotRadius * 4))) {
  1439. spotRadius = 0;
  1440. }
  1441. if (spotRadius) {
  1442. // adjust the canvas size as required so that spots will fit
  1443. hlSpotsEnabled = options.get('highlightSpotColor') && !options.get('disableInteraction');
  1444. if (hlSpotsEnabled || options.get('minSpotColor') || (options.get('spotColor') && yvalues[yvallast] === this.miny)) {
  1445. canvasHeight -= Math.ceil(spotRadius);
  1446. }
  1447. if (hlSpotsEnabled || options.get('maxSpotColor') || (options.get('spotColor') && yvalues[yvallast] === this.maxy)) {
  1448. canvasHeight -= Math.ceil(spotRadius);
  1449. canvasTop += Math.ceil(spotRadius);
  1450. }
  1451. if (hlSpotsEnabled ||
  1452. ((options.get('minSpotColor') || options.get('maxSpotColor')) && (yvalues[0] === this.miny || yvalues[0] === this.maxy))) {
  1453. canvasLeft += Math.ceil(spotRadius);
  1454. canvasWidth -= Math.ceil(spotRadius);
  1455. }
  1456. if (hlSpotsEnabled || options.get('spotColor') ||
  1457. (options.get('minSpotColor') || options.get('maxSpotColor') &&
  1458. (yvalues[yvallast] === this.miny || yvalues[yvallast] === this.maxy))) {
  1459. canvasWidth -= Math.ceil(spotRadius);
  1460. }
  1461. }
  1462. canvasHeight--;
  1463. if (options.get('normalRangeMin') !== undefined && !options.get('drawNormalOnTop')) {
  1464. this.drawNormalRange(canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey);
  1465. }
  1466. path = [];
  1467. paths = [path];
  1468. last = next = null;
  1469. yvalcount = yvalues.length;
  1470. for (i = 0; i < yvalcount; i++) {
  1471. x = xvalues[i];
  1472. xnext = xvalues[i + 1];
  1473. y = yvalues[i];
  1474. xpos = canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex));
  1475. xposnext = i < yvalcount - 1 ? canvasLeft + Math.round((xnext - this.minx) * (canvasWidth / rangex)) : canvasWidth;
  1476. next = xpos + ((xposnext - xpos) / 2);
  1477. regionMap[i] = [last || 0, next, i];
  1478. last = next;
  1479. if (y === null) {
  1480. if (i) {
  1481. if (yvalues[i - 1] !== null) {
  1482. path = [];
  1483. paths.push(path);
  1484. }
  1485. vertices.push(null);
  1486. }
  1487. } else {
  1488. if (y < this.miny) {
  1489. y = this.miny;
  1490. }
  1491. if (y > this.maxy) {
  1492. y = this.maxy;
  1493. }
  1494. if (!path.length) {
  1495. // previous value was null
  1496. path.push([xpos, canvasTop + canvasHeight]);
  1497. }
  1498. vertex = [xpos, canvasTop + Math.round(canvasHeight - (canvasHeight * ((y - this.miny) / rangey)))];
  1499. path.push(vertex);
  1500. vertices.push(vertex);
  1501. }
  1502. }
  1503. lineShapes = [];
  1504. fillShapes = [];
  1505. plen = paths.length;
  1506. for (i = 0; i < plen; i++) {
  1507. path = paths[i];
  1508. if (path.length) {
  1509. if (options.get('fillColor')) {
  1510. path.push([path[path.length - 1][0], (canvasTop + canvasHeight)]);
  1511. fillShapes.push(path.slice(0));
  1512. path.pop();
  1513. }
  1514. // if there's only a single point in this path, then we want to display it
  1515. // as a vertical line which means we keep path[0] as is
  1516. if (path.length > 2) {
  1517. // else we want the first value
  1518. path[0] = [path[0][0], path[1][1]];
  1519. }
  1520. lineShapes.push(path);
  1521. }
  1522. }
  1523. // draw the fill first, then optionally the normal range, then the line on top of that
  1524. plen = fillShapes.length;
  1525. for (i = 0; i < plen; i++) {
  1526. target.drawShape(fillShapes[i],
  1527. options.get('fillColor'), options.get('fillColor')).append();
  1528. }
  1529. if (options.get('normalRangeMin') !== undefined && options.get('drawNormalOnTop')) {
  1530. this.drawNormalRange(canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey);
  1531. }
  1532. plen = lineShapes.length;
  1533. for (i = 0; i < plen; i++) {
  1534. target.drawShape(lineShapes[i], options.get('lineColor'), undefined,
  1535. options.get('lineWidth')).append();
  1536. }
  1537. if (spotRadius && options.get('valueSpots')) {
  1538. valueSpots = options.get('valueSpots');
  1539. if (valueSpots.get === undefined) {
  1540. valueSpots = new RangeMap(valueSpots);
  1541. }
  1542. for (i = 0; i < yvalcount; i++) {
  1543. color = valueSpots.get(yvalues[i]);
  1544. if (color) {
  1545. target.drawCircle(canvasLeft + Math.round((xvalues[i] - this.minx) * (canvasWidth / rangex)),
  1546. canvasTop + Math.round(canvasHeight - (canvasHeight * ((yvalues[i] - this.miny) / rangey))),
  1547. spotRadius, undefined,
  1548. color).append();
  1549. }
  1550. }
  1551. }
  1552. if (spotRadius && options.get('spotColor') && yvalues[yvallast] !== null) {
  1553. target.drawCircle(canvasLeft + Math.round((xvalues[xvalues.length - 1] - this.minx) * (canvasWidth / rangex)),
  1554. canvasTop + Math.round(canvasHeight - (canvasHeight * ((yvalues[yvallast] - this.miny) / rangey))),
  1555. spotRadius, undefined,
  1556. options.get('spotColor')).append();
  1557. }
  1558. if (this.maxy !== this.minyorg) {
  1559. if (spotRadius && options.get('minSpotColor')) {
  1560. x = xvalues[$.inArray(this.minyorg, yvalues)];
  1561. target.drawCircle(canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)),
  1562. canvasTop + Math.round(canvasHeight - (canvasHeight * ((this.minyorg - this.miny) / rangey))),
  1563. spotRadius, undefined,
  1564. options.get('minSpotColor')).append();
  1565. }
  1566. if (spotRadius && options.get('maxSpotColor')) {
  1567. x = xvalues[$.inArray(this.maxyorg, yvalues)];
  1568. target.drawCircle(canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)),
  1569. canvasTop + Math.round(canvasHeight - (canvasHeight * ((this.maxyorg - this.miny) / rangey))),
  1570. spotRadius, undefined,
  1571. options.get('maxSpotColor')).append();
  1572. }
  1573. }
  1574. this.lastShapeId = target.getLastShapeId();
  1575. this.canvasTop = canvasTop;
  1576. target.render();
  1577. }
  1578. });
  1579. /**
  1580. * Bar charts
  1581. */
  1582. $.fn.sparkline.bar = bar = createClass($.fn.sparkline._base, barHighlightMixin, {
  1583. type: 'bar',
  1584. init: function (el, values, options, width, height) {
  1585. var barWidth = parseInt(options.get('barWidth'), 10),
  1586. barSpacing = parseInt(options.get('barSpacing'), 10),
  1587. chartRangeMin = options.get('chartRangeMin'),
  1588. chartRangeMax = options.get('chartRangeMax'),
  1589. chartRangeClip = options.get('chartRangeClip'),
  1590. stackMin = Infinity,
  1591. stackMax = -Infinity,
  1592. isStackString, groupMin, groupMax, stackRanges,
  1593. numValues, i, vlen, range, zeroAxis, xaxisOffset, min, max, clipMin, clipMax,
  1594. stacked, vlist, j, slen, svals, val, yoffset, yMaxCalc, canvasHeightEf;
  1595. bar._super.init.call(this, el, values, options, width, height);
  1596. // scan values to determine whether to stack bars
  1597. for (i = 0, vlen = values.length; i < vlen; i++) {
  1598. val = values[i];
  1599. isStackString = typeof(val) === 'string' && val.indexOf(':') > -1;
  1600. if (isStackString || $.isArray(val)) {
  1601. stacked = true;
  1602. if (isStackString) {
  1603. val = values[i] = normalizeValues(val.split(':'));
  1604. }
  1605. val = remove(val, null); // min/max will treat null as zero
  1606. groupMin = Math.min.apply(Math, val);
  1607. groupMax = Math.max.apply(Math, val);
  1608. if (groupMin < stackMin) {
  1609. stackMin = groupMin;
  1610. }
  1611. if (groupMax > stackMax) {
  1612. stackMax = groupMax;
  1613. }
  1614. }
  1615. }
  1616. this.stacked = stacked;
  1617. this.regionShapes = {};
  1618. this.barWidth = barWidth;
  1619. this.barSpacing = barSpacing;
  1620. this.totalBarWidth = barWidth + barSpacing;
  1621. this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing);
  1622. this.initTarget();
  1623. if (chartRangeClip) {
  1624. clipMin = chartRangeMin === undefined ? -Infinity : chartRangeMin;
  1625. clipMax = chartRangeMax === undefined ? Infinity : chartRangeMax;
  1626. }
  1627. numValues = [];
  1628. stackRanges = stacked ? [] : numValues;
  1629. var stackTotals = [];
  1630. var stackRangesNeg = [];
  1631. for (i = 0, vlen = values.length; i < vlen; i++) {
  1632. if (stacked) {
  1633. vlist = values[i];
  1634. values[i] = svals = [];
  1635. stackTotals[i] = 0;
  1636. stackRanges[i] = stackRangesNeg[i] = 0;
  1637. for (j = 0, slen = vlist.length; j < slen; j++) {
  1638. val = svals[j] = chartRangeClip ? clipval(vlist[j], clipMin, clipMax) : vlist[j];
  1639. if (val !== null) {
  1640. if (val > 0) {
  1641. stackTotals[i] += val;
  1642. }
  1643. if (stackMin < 0 && stackMax > 0) {
  1644. if (val < 0) {
  1645. stackRangesNeg[i] += Math.abs(val);
  1646. } else {
  1647. stackRanges[i] += val;
  1648. }
  1649. } else {
  1650. stackRanges[i] += Math.abs(val - (val < 0 ? stackMax : stackMin));
  1651. }
  1652. numValues.push(val);
  1653. }
  1654. }
  1655. } else {
  1656. val = chartRangeClip ? clipval(values[i], clipMin, clipMax) : values[i];
  1657. val = values[i] = normalizeValue(val);
  1658. if (val !== null) {
  1659. numValues.push(val);
  1660. }
  1661. }
  1662. }
  1663. this.max = max = Math.max.apply(Math, numValues);
  1664. this.min = min = Math.min.apply(Math, numValues);
  1665. this.stackMax = stackMax = stacked ? Math.max.apply(Math, stackTotals) : max;
  1666. this.stackMin = stackMin = stacked ? Math.min.apply(Math, numValues) : min;
  1667. if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < min)) {
  1668. min = options.get('chartRangeMin');
  1669. }
  1670. if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > max)) {
  1671. max = options.get('chartRangeMax');
  1672. }
  1673. this.zeroAxis = zeroAxis = options.get('zeroAxis', true);
  1674. if (min <= 0 && max >= 0 && zeroAxis) {
  1675. xaxisOffset = 0;
  1676. } else if (zeroAxis == false) {
  1677. xaxisOffset = min;
  1678. } else if (min > 0) {
  1679. xaxisOffset = min;
  1680. } else {
  1681. xaxisOffset = max;
  1682. }
  1683. this.xaxisOffset = xaxisOffset;
  1684. range = stacked ? (Math.max.apply(Math, stackRanges) + Math.max.apply(Math, stackRangesNeg)) : max - min;
  1685. // as we plot zero/min values a single pixel line, we add a pixel to all other
  1686. // values - Reduce the effective canvas size to suit
  1687. this.canvasHeightEf = (zeroAxis && min < 0) ? this.canvasHeight - 2 : this.canvasHeight - 1;
  1688. if (min < xaxisOffset) {
  1689. yMaxCalc = (stacked && max >= 0) ? stackMax : max;
  1690. yoffset = (yMaxCalc - xaxisOffset) / range * this.canvasHeight;
  1691. if (yoffset !== Math.ceil(yoffset)) {
  1692. this.canvasHeightEf -= 2;
  1693. yoffset = Math.ceil(yoffset);
  1694. }
  1695. } else {
  1696. yoffset = this.canvasHeight;
  1697. }
  1698. this.yoffset = yoffset;
  1699. if ($.isArray(options.get('colorMap'))) {
  1700. this.colorMapByIndex = options.get('colorMap');
  1701. this.colorMapByValue = null;
  1702. } else {
  1703. this.colorMapByIndex = null;
  1704. this.colorMapByValue = options.get('colorMap');
  1705. if (this.colorMapByValue && this.colorMapByValue.get === undefined) {
  1706. this.colorMapByValue = new RangeMap(this.colorMapByValue);
  1707. }
  1708. }
  1709. this.range = range;
  1710. },
  1711. getRegion: function (el, x, y) {
  1712. var result = Math.floor(x / this.totalBarWidth);
  1713. return (result < 0 || result >= this.values.length) ? undefined : result;
  1714. },
  1715. getCurrentRegionFields: function () {
  1716. var currentRegion = this.currentRegion,
  1717. values = ensureArray(this.values[currentRegion]),
  1718. result = [],
  1719. value, i;
  1720. for (i = values.length; i--;) {
  1721. value = values[i];
  1722. result.push({
  1723. isNull: value === null,
  1724. value: value,
  1725. color: this.calcColor(i, value, currentRegion),
  1726. offset: currentRegion
  1727. });
  1728. }
  1729. return result;
  1730. },
  1731. calcColor: function (stacknum, value, valuenum) {
  1732. var colorMapByIndex = this.colorMapByIndex,
  1733. colorMapByValue = this.colorMapByValue,
  1734. options = this.options,
  1735. color, newColor;
  1736. if (this.stacked) {
  1737. color = options.get('stackedBarColor');
  1738. } else {
  1739. color = (value < 0) ? options.get('negBarColor') : options.get('barColor');
  1740. }
  1741. if (value === 0 && options.get('zeroColor') !== undefined) {
  1742. color = options.get('zeroColor');
  1743. }
  1744. if (colorMapByValue && (newColor = colorMapByValue.get(value))) {
  1745. color = newColor;
  1746. } else if (colorMapByIndex && colorMapByIndex.length > valuenum) {
  1747. color = colorMapByIndex[valuenum];
  1748. }
  1749. return $.isArray(color) ? color[stacknum % color.length] : color;
  1750. },
  1751. /**
  1752. * Render bar(s) for a region
  1753. */
  1754. renderRegion: function (valuenum, highlight) {
  1755. var vals = this.values[valuenum],
  1756. options = this.options,
  1757. xaxisOffset = this.xaxisOffset,
  1758. result = [],
  1759. range = this.range,
  1760. stacked = this.stacked,
  1761. target = this.target,
  1762. x = valuenum * this.totalBarWidth,
  1763. canvasHeightEf = this.canvasHeightEf,
  1764. yoffset = this.yoffset,
  1765. y, height, color, isNull, yoffsetNeg, i, valcount, val, minPlotted, allMin;
  1766. vals = $.isArray(vals) ? vals : [vals];
  1767. valcount = vals.length;
  1768. val = vals[0];
  1769. isNull = all(null, vals);
  1770. allMin = all(xaxisOffset, vals, true);
  1771. if (isNull) {
  1772. if (options.get('nullColor')) {
  1773. color = highlight ? options.get('nullColor') : this.calcHighlightColor(options.get('nullColor'), options);
  1774. y = (yoffset > 0) ? yoffset - 1 : yoffset;
  1775. return target.drawRect(x, y, this.barWidth - 1, 0, color, color);
  1776. } else {
  1777. return undefined;
  1778. }
  1779. }
  1780. yoffsetNeg = yoffset;
  1781. for (i = 0; i < valcount; i++) {
  1782. val = vals[i];
  1783. if (stacked && val === xaxisOffset) {
  1784. if (!allMin || minPlotted) {
  1785. continue;
  1786. }
  1787. minPlotted = true;
  1788. }
  1789. if (range > 0) {
  1790. height = Math.floor(canvasHeightEf * ((Math.abs(val - xaxisOffset) / range))) + 1;
  1791. } else {
  1792. height = 1;
  1793. }
  1794. if (val < xaxisOffset || (val === xaxisOffset && yoffset === 0)) {
  1795. y = yoffsetNeg;
  1796. yoffsetNeg += height;
  1797. } else {
  1798. y = yoffset - height;
  1799. yoffset -= height;
  1800. }
  1801. color = this.calcColor(i, val, valuenum);
  1802. if (highlight) {
  1803. color = this.calcHighlightColor(color, options);
  1804. }
  1805. result.push(target.drawRect(x, y, this.barWidth - 1, height - 1, color, color));
  1806. }
  1807. if (result.length === 1) {
  1808. return result[0];
  1809. }
  1810. return result;
  1811. }
  1812. });
  1813. /**
  1814. * Tristate charts
  1815. */
  1816. $.fn.sparkline.tristate = tristate = createClass($.fn.sparkline._base, barHighlightMixin, {
  1817. type: 'tristate',
  1818. init: function (el, values, options, width, height) {
  1819. var barWidth = parseInt(options.get('barWidth'), 10),
  1820. barSpacing = parseInt(options.get('barSpacing'), 10);
  1821. tristate._super.init.call(this, el, values, options, width, height);
  1822. this.regionShapes = {};
  1823. this.barWidth = barWidth;
  1824. this.barSpacing = barSpacing;
  1825. this.totalBarWidth = barWidth + barSpacing;
  1826. this.values = $.map(values, Number);
  1827. this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing);
  1828. if ($.isArray(options.get('colorMap'))) {
  1829. this.colorMapByIndex = options.get('colorMap');
  1830. this.colorMapByValue = null;
  1831. } else {
  1832. this.colorMapByIndex = null;
  1833. this.colorMapByValue = options.get('colorMap');
  1834. if (this.colorMapByValue && this.colorMapByValue.get === undefined) {
  1835. this.colorMapByValue = new RangeMap(this.colorMapByValue);
  1836. }
  1837. }
  1838. this.initTarget();
  1839. },
  1840. getRegion: function (el, x, y) {
  1841. return Math.floor(x / this.totalBarWidth);
  1842. },
  1843. getCurrentRegionFields: function () {
  1844. var currentRegion = this.currentRegion;
  1845. return {
  1846. isNull: this.values[currentRegion] === undefined,
  1847. value: this.values[currentRegion],
  1848. color: this.calcColor(this.values[currentRegion], currentRegion),
  1849. offset: currentRegion
  1850. };
  1851. },
  1852. calcColor: function (value, valuenum) {
  1853. var values = this.values,
  1854. options = this.options,
  1855. colorMapByIndex = this.colorMapByIndex,
  1856. colorMapByValue = this.colorMapByValue,
  1857. color, newColor;
  1858. if (colorMapByValue && (newColor = colorMapByValue.get(value))) {
  1859. color = newColor;
  1860. } else if (colorMapByIndex && colorMapByIndex.length > valuenum) {
  1861. color = colorMapByIndex[valuenum];
  1862. } else if (values[valuenum] < 0) {
  1863. color = options.get('negBarColor');
  1864. } else if (values[valuenum] > 0) {
  1865. color = options.get('posBarColor');
  1866. } else {
  1867. color = options.get('zeroBarColor');
  1868. }
  1869. return color;
  1870. },
  1871. renderRegion: function (valuenum, highlight) {
  1872. var values = this.values,
  1873. options = this.options,
  1874. target = this.target,
  1875. canvasHeight, height, halfHeight,
  1876. x, y, color;
  1877. canvasHeight = target.pixelHeight;
  1878. halfHeight = Math.round(canvasHeight / 2);
  1879. x = valuenum * this.totalBarWidth;
  1880. if (values[valuenum] < 0) {
  1881. y = halfHeight;
  1882. height = halfHeight - 1;
  1883. } else if (values[valuenum] > 0) {
  1884. y = 0;
  1885. height = halfHeight - 1;
  1886. } else {
  1887. y = halfHeight - 1;
  1888. height = 2;
  1889. }
  1890. color = this.calcColor(values[valuenum], valuenum);
  1891. if (color === null) {
  1892. return;
  1893. }
  1894. if (highlight) {
  1895. color = this.calcHighlightColor(color, options);
  1896. }
  1897. return target.drawRect(x, y, this.barWidth - 1, height - 1, color, color);
  1898. }
  1899. });
  1900. /**
  1901. * Discrete charts
  1902. */
  1903. $.fn.sparkline.discrete = discrete = createClass($.fn.sparkline._base, barHighlightMixin, {
  1904. type: 'discrete',
  1905. init: function (el, values, options, width, height) {
  1906. discrete._super.init.call(this, el, values, options, width, height);
  1907. this.regionShapes = {};
  1908. this.values = values = $.map(values, Number);
  1909. this.min = Math.min.apply(Math, values);
  1910. this.max = Math.max.apply(Math, values);
  1911. this.range = this.max - this.min;
  1912. this.width = width = options.get('width') === 'auto' ? values.length * 2 : this.width;
  1913. this.interval = Math.floor(width / values.length);
  1914. this.itemWidth = width / values.length;
  1915. if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.min)) {
  1916. this.min = options.get('chartRangeMin');
  1917. }
  1918. if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.max)) {
  1919. this.max = options.get('chartRangeMax');
  1920. }
  1921. this.initTarget();
  1922. if (this.target) {
  1923. this.lineHeight = options.get('lineHeight') === 'auto' ? Math.round(this.canvasHeight * 0.3) : options.get('lineHeight');
  1924. }
  1925. },
  1926. getRegion: function (el, x, y) {
  1927. return Math.floor(x / this.itemWidth);
  1928. },
  1929. getCurrentRegionFields: function () {
  1930. var currentRegion = this.currentRegion;
  1931. return {
  1932. isNull: this.values[currentRegion] === undefined,
  1933. value: this.values[currentRegion],
  1934. offset: currentRegion
  1935. };
  1936. },
  1937. renderRegion: function (valuenum, highlight) {
  1938. var values = this.values,
  1939. options = this.options,
  1940. min = this.min,
  1941. max = this.max,
  1942. range = this.range,
  1943. interval = this.interval,
  1944. target = this.target,
  1945. canvasHeight = this.canvasHeight,
  1946. lineHeight = this.lineHeight,
  1947. pheight = canvasHeight - lineHeight,
  1948. ytop, val, color, x;
  1949. val = clipval(values[valuenum], min, max);
  1950. x = valuenum * interval;
  1951. ytop = Math.round(pheight - pheight * ((val - min) / range));
  1952. color = (options.get('thresholdColor') && val < options.get('thresholdValue')) ? options.get('thresholdColor') : options.get('lineColor');
  1953. if (highlight) {
  1954. color = this.calcHighlightColor(color, options);
  1955. }
  1956. return target.drawLine(x, ytop, x, ytop + lineHeight, color);
  1957. }
  1958. });
  1959. /**
  1960. * Bullet charts
  1961. */
  1962. $.fn.sparkline.bullet = bullet = createClass($.fn.sparkline._base, {
  1963. type: 'bullet',
  1964. init: function (el, values, options, width, height) {
  1965. var min, max, vals;
  1966. bullet._super.init.call(this, el, values, options, width, height);
  1967. // values: target, performance, range1, range2, range3
  1968. this.values = values = normalizeValues(values);
  1969. // target or performance could be null
  1970. vals = values.slice();
  1971. vals[0] = vals[0] === null ? vals[2] : vals[0];
  1972. vals[1] = values[1] === null ? vals[2] : vals[1];
  1973. min = Math.min.apply(Math, values);
  1974. max = Math.max.apply(Math, values);
  1975. if (options.get('base') === undefined) {
  1976. min = min < 0 ? min : 0;
  1977. } else {
  1978. min = options.get('base');
  1979. }
  1980. this.min = min;
  1981. this.max = max;
  1982. this.range = max - min;
  1983. this.shapes = {};
  1984. this.valueShapes = {};
  1985. this.regiondata = {};
  1986. this.width = width = options.get('width') === 'auto' ? '4.0em' : width;
  1987. this.target = this.$el.simpledraw(width, height, options.get('composite'));
  1988. if (!values.length) {
  1989. this.disabled = true;
  1990. }
  1991. this.initTarget();
  1992. },
  1993. getRegion: function (el, x, y) {
  1994. var shapeid = this.target.getShapeAt(el, x, y);
  1995. return (shapeid !== undefined && this.shapes[shapeid] !== undefined) ? this.shapes[shapeid] : undefined;
  1996. },
  1997. getCurrentRegionFields: function () {
  1998. var currentRegion = this.currentRegion;
  1999. return {
  2000. fieldkey: currentRegion.substr(0, 1),
  2001. value: this.values[currentRegion.substr(1)],
  2002. region: currentRegion
  2003. };
  2004. },
  2005. changeHighlight: function (highlight) {
  2006. var currentRegion = this.currentRegion,
  2007. shapeid = this.valueShapes[currentRegion],
  2008. shape;
  2009. delete this.shapes[shapeid];
  2010. switch (currentRegion.substr(0, 1)) {
  2011. case 'r':
  2012. shape = this.renderRange(currentRegion.substr(1), highlight);
  2013. break;
  2014. case 'p':
  2015. shape = this.renderPerformance(highlight);
  2016. break;
  2017. case 't':
  2018. shape = this.renderTarget(highlight);
  2019. break;
  2020. }
  2021. this.valueShapes[currentRegion] = shape.id;
  2022. this.shapes[shape.id] = currentRegion;
  2023. this.target.replaceWithShape(shapeid, shape);
  2024. },
  2025. renderRange: function (rn, highlight) {
  2026. var rangeval = this.values[rn],
  2027. rangewidth = Math.round(this.canvasWidth * ((rangeval - this.min) / this.range)),
  2028. color = this.options.get('rangeColors')[rn - 2];
  2029. if (highlight) {
  2030. color = this.calcHighlightColor(color, this.options);
  2031. }
  2032. return this.target.drawRect(0, 0, rangewidth - 1, this.canvasHeight - 1, color, color);
  2033. },
  2034. renderPerformance: function (highlight) {
  2035. var perfval = this.values[1],
  2036. perfwidth = Math.round(this.canvasWidth * ((perfval - this.min) / this.range)),
  2037. color = this.options.get('performanceColor');
  2038. if (highlight) {
  2039. color = this.calcHighlightColor(color, this.options);
  2040. }
  2041. return this.target.drawRect(0, Math.round(this.canvasHeight * 0.3), perfwidth - 1,
  2042. Math.round(this.canvasHeight * 0.4) - 1, color, color);
  2043. },
  2044. renderTarget: function (highlight) {
  2045. var targetval = this.values[0],
  2046. x = Math.round(this.canvasWidth * ((targetval - this.min) / this.range) - (this.options.get('targetWidth') / 2)),
  2047. targettop = Math.round(this.canvasHeight * 0.10),
  2048. targetheight = this.canvasHeight - (targettop * 2),
  2049. color = this.options.get('targetColor');
  2050. if (highlight) {
  2051. color = this.calcHighlightColor(color, this.options);
  2052. }
  2053. return this.target.drawRect(x, targettop, this.options.get('targetWidth') - 1, targetheight - 1, color, color);
  2054. },
  2055. render: function () {
  2056. var vlen = this.values.length,
  2057. target = this.target,
  2058. i, shape;
  2059. if (!bullet._super.render.call(this)) {
  2060. return;
  2061. }
  2062. for (i = 2; i < vlen; i++) {
  2063. shape = this.renderRange(i).append();
  2064. this.shapes[shape.id] = 'r' + i;
  2065. this.valueShapes['r' + i] = shape.id;
  2066. }
  2067. if (this.values[1] !== null) {
  2068. shape = this.renderPerformance().append();
  2069. this.shapes[shape.id] = 'p1';
  2070. this.valueShapes.p1 = shape.id;
  2071. }
  2072. if (this.values[0] !== null) {
  2073. shape = this.renderTarget().append();
  2074. this.shapes[shape.id] = 't0';
  2075. this.valueShapes.t0 = shape.id;
  2076. }
  2077. target.render();
  2078. }
  2079. });
  2080. /**
  2081. * Pie charts
  2082. */
  2083. $.fn.sparkline.pie = pie = createClass($.fn.sparkline._base, {
  2084. type: 'pie',
  2085. init: function (el, values, options, width, height) {
  2086. var total = 0, i;
  2087. pie._super.init.call(this, el, values, options, width, height);
  2088. this.shapes = {}; // map shape ids to value offsets
  2089. this.valueShapes = {}; // maps value offsets to shape ids
  2090. this.values = values = $.map(values, Number);
  2091. if (options.get('width') === 'auto') {
  2092. this.width = this.height;
  2093. }
  2094. if (values.length > 0) {
  2095. for (i = values.length; i--;) {
  2096. total += values[i];
  2097. }
  2098. }
  2099. this.total = total;
  2100. this.initTarget();
  2101. this.radius = Math.floor(Math.min(this.canvasWidth, this.canvasHeight) / 2);
  2102. },
  2103. getRegion: function (el, x, y) {
  2104. var shapeid = this.target.getShapeAt(el, x, y);
  2105. return (shapeid !== undefined && this.shapes[shapeid] !== undefined) ? this.shapes[shapeid] : undefined;
  2106. },
  2107. getCurrentRegionFields: function () {
  2108. var currentRegion = this.currentRegion;
  2109. return {
  2110. isNull: this.values[currentRegion] === undefined,
  2111. value: this.values[currentRegion],
  2112. percent: this.values[currentRegion] / this.total * 100,
  2113. color: this.options.get('sliceColors')[currentRegion % this.options.get('sliceColors').length],
  2114. offset: currentRegion
  2115. };
  2116. },
  2117. changeHighlight: function (highlight) {
  2118. var currentRegion = this.currentRegion,
  2119. newslice = this.renderSlice(currentRegion, highlight),
  2120. shapeid = this.valueShapes[currentRegion];
  2121. delete this.shapes[shapeid];
  2122. this.target.replaceWithShape(shapeid, newslice);
  2123. this.valueShapes[currentRegion] = newslice.id;
  2124. this.shapes[newslice.id] = currentRegion;
  2125. },
  2126. renderSlice: function (valuenum, highlight) {
  2127. var target = this.target,
  2128. options = this.options,
  2129. radius = this.radius,
  2130. borderWidth = options.get('borderWidth'),
  2131. offset = options.get('offset'),
  2132. circle = 2 * Math.PI,
  2133. values = this.values,
  2134. total = this.total,
  2135. next = offset ? (2*Math.PI)*(offset/360) : 0,
  2136. start, end, i, vlen, color;
  2137. vlen = values.length;
  2138. for (i = 0; i < vlen; i++) {
  2139. start = next;
  2140. end = next;
  2141. if (total > 0) { // avoid divide by zero
  2142. end = next + (circle * (values[i] / total));
  2143. }
  2144. if (valuenum === i) {
  2145. color = options.get('sliceColors')[i % options.get('sliceColors').length];
  2146. if (highlight) {
  2147. color = this.calcHighlightColor(color, options);
  2148. }
  2149. return target.drawPieSlice(radius, radius, radius - borderWidth, start, end, undefined, color);
  2150. }
  2151. next = end;
  2152. }
  2153. },
  2154. render: function () {
  2155. var target = this.target,
  2156. values = this.values,
  2157. options = this.options,
  2158. radius = this.radius,
  2159. borderWidth = options.get('borderWidth'),
  2160. donutWidth = options.get('donutWidth'),
  2161. shape, i;
  2162. if (!pie._super.render.call(this)) {
  2163. return;
  2164. }
  2165. if (borderWidth) {
  2166. target.drawCircle(radius, radius, Math.floor(radius - (borderWidth / 2)),
  2167. options.get('borderColor'), undefined, borderWidth).append();
  2168. }
  2169. for (i = values.length; i--;) {
  2170. if (values[i]) { // don't render zero values
  2171. shape = this.renderSlice(i).append();
  2172. this.valueShapes[i] = shape.id; // store just the shapeid
  2173. this.shapes[shape.id] = i;
  2174. }
  2175. }
  2176. if (donutWidth) {
  2177. target.drawCircle(radius, radius, radius - donutWidth, options.get('donutColor'),
  2178. options.get('donutColor'), 0).append();
  2179. }
  2180. target.render();
  2181. }
  2182. });
  2183. /**
  2184. * Box plots
  2185. */
  2186. $.fn.sparkline.box = box = createClass($.fn.sparkline._base, {
  2187. type: 'box',
  2188. init: function (el, values, options, width, height) {
  2189. box._super.init.call(this, el, values, options, width, height);
  2190. this.values = $.map(values, Number);
  2191. this.width = options.get('width') === 'auto' ? '4.0em' : width;
  2192. this.initTarget();
  2193. if (!this.values.length) {
  2194. this.disabled = 1;
  2195. }
  2196. },
  2197. /**
  2198. * Simulate a single region
  2199. */
  2200. getRegion: function () {
  2201. return 1;
  2202. },
  2203. getCurrentRegionFields: function () {
  2204. var result = [
  2205. { field: 'lq', value: this.quartiles[0] },
  2206. { field: 'med', value: this.quartiles[1] },
  2207. { field: 'uq', value: this.quartiles[2] }
  2208. ];
  2209. if (this.loutlier !== undefined) {
  2210. result.push({ field: 'lo', value: this.loutlier});
  2211. }
  2212. if (this.routlier !== undefined) {
  2213. result.push({ field: 'ro', value: this.routlier});
  2214. }
  2215. if (this.lwhisker !== undefined) {
  2216. result.push({ field: 'lw', value: this.lwhisker});
  2217. }
  2218. if (this.rwhisker !== undefined) {
  2219. result.push({ field: 'rw', value: this.rwhisker});
  2220. }
  2221. return result;
  2222. },
  2223. render: function () {
  2224. var target = this.target,
  2225. values = this.values,
  2226. vlen = values.length,
  2227. options = this.options,
  2228. canvasWidth = this.canvasWidth,
  2229. canvasHeight = this.canvasHeight,
  2230. minValue = options.get('chartRangeMin') === undefined ? Math.min.apply(Math, values) : options.get('chartRangeMin'),
  2231. maxValue = options.get('chartRangeMax') === undefined ? Math.max.apply(Math, values) : options.get('chartRangeMax'),
  2232. canvasLeft = 0,
  2233. lwhisker, loutlier, iqr, q1, q2, q3, rwhisker, routlier, i,
  2234. size, unitSize;
  2235. if (!box._super.render.call(this)) {
  2236. return;
  2237. }
  2238. if (options.get('raw')) {
  2239. if (options.get('showOutliers') && values.length > 5) {
  2240. loutlier = values[0];
  2241. lwhisker = values[1];
  2242. q1 = values[2];
  2243. q2 = values[3];
  2244. q3 = values[4];
  2245. rwhisker = values[5];
  2246. routlier = values[6];
  2247. } else {
  2248. lwhisker = values[0];
  2249. q1 = values[1];
  2250. q2 = values[2];
  2251. q3 = values[3];
  2252. rwhisker = values[4];
  2253. }
  2254. } else {
  2255. values.sort(function (a, b) { return a - b; });
  2256. q1 = quartile(values, 1);
  2257. q2 = quartile(values, 2);
  2258. q3 = quartile(values, 3);
  2259. iqr = q3 - q1;
  2260. if (options.get('showOutliers')) {
  2261. lwhisker = rwhisker = undefined;
  2262. for (i = 0; i < vlen; i++) {
  2263. if (lwhisker === undefined && values[i] > q1 - (iqr * options.get('outlierIQR'))) {
  2264. lwhisker = values[i];
  2265. }
  2266. if (values[i] < q3 + (iqr * options.get('outlierIQR'))) {
  2267. rwhisker = values[i];
  2268. }
  2269. }
  2270. loutlier = values[0];
  2271. routlier = values[vlen - 1];
  2272. } else {
  2273. lwhisker = values[0];
  2274. rwhisker = values[vlen - 1];
  2275. }
  2276. }
  2277. this.quartiles = [q1, q2, q3];
  2278. this.lwhisker = lwhisker;
  2279. this.rwhisker = rwhisker;
  2280. this.loutlier = loutlier;
  2281. this.routlier = routlier;
  2282. unitSize = canvasWidth / (maxValue - minValue + 1);
  2283. if (options.get('showOutliers')) {
  2284. canvasLeft = Math.ceil(options.get('spotRadius'));
  2285. canvasWidth -= 2 * Math.ceil(options.get('spotRadius'));
  2286. unitSize = canvasWidth / (maxValue - minValue + 1);
  2287. if (loutlier < lwhisker) {
  2288. target.drawCircle((loutlier - minValue) * unitSize + canvasLeft,
  2289. canvasHeight / 2,
  2290. options.get('spotRadius'),
  2291. options.get('outlierLineColor'),
  2292. options.get('outlierFillColor')).append();
  2293. }
  2294. if (routlier > rwhisker) {
  2295. target.drawCircle((routlier - minValue) * unitSize + canvasLeft,
  2296. canvasHeight / 2,
  2297. options.get('spotRadius'),
  2298. options.get('outlierLineColor'),
  2299. options.get('outlierFillColor')).append();
  2300. }
  2301. }
  2302. // box
  2303. target.drawRect(
  2304. Math.round((q1 - minValue) * unitSize + canvasLeft),
  2305. Math.round(canvasHeight * 0.1),
  2306. Math.round((q3 - q1) * unitSize),
  2307. Math.round(canvasHeight * 0.8),
  2308. options.get('boxLineColor'),
  2309. options.get('boxFillColor')).append();
  2310. // left whisker
  2311. target.drawLine(
  2312. Math.round((lwhisker - minValue) * unitSize + canvasLeft),
  2313. Math.round(canvasHeight / 2),
  2314. Math.round((q1 - minValue) * unitSize + canvasLeft),
  2315. Math.round(canvasHeight / 2),
  2316. options.get('lineColor')).append();
  2317. target.drawLine(
  2318. Math.round((lwhisker - minValue) * unitSize + canvasLeft),
  2319. Math.round(canvasHeight / 4),
  2320. Math.round((lwhisker - minValue) * unitSize + canvasLeft),
  2321. Math.round(canvasHeight - canvasHeight / 4),
  2322. options.get('whiskerColor')).append();
  2323. // right whisker
  2324. target.drawLine(Math.round((rwhisker - minValue) * unitSize + canvasLeft),
  2325. Math.round(canvasHeight / 2),
  2326. Math.round((q3 - minValue) * unitSize + canvasLeft),
  2327. Math.round(canvasHeight / 2),
  2328. options.get('lineColor')).append();
  2329. target.drawLine(
  2330. Math.round((rwhisker - minValue) * unitSize + canvasLeft),
  2331. Math.round(canvasHeight / 4),
  2332. Math.round((rwhisker - minValue) * unitSize + canvasLeft),
  2333. Math.round(canvasHeight - canvasHeight / 4),
  2334. options.get('whiskerColor')).append();
  2335. // median line
  2336. target.drawLine(
  2337. Math.round((q2 - minValue) * unitSize + canvasLeft),
  2338. Math.round(canvasHeight * 0.1),
  2339. Math.round((q2 - minValue) * unitSize + canvasLeft),
  2340. Math.round(canvasHeight * 0.9),
  2341. options.get('medianColor')).append();
  2342. if (options.get('target')) {
  2343. size = Math.ceil(options.get('spotRadius'));
  2344. target.drawLine(
  2345. Math.round((options.get('target') - minValue) * unitSize + canvasLeft),
  2346. Math.round((canvasHeight / 2) - size),
  2347. Math.round((options.get('target') - minValue) * unitSize + canvasLeft),
  2348. Math.round((canvasHeight / 2) + size),
  2349. options.get('targetColor')).append();
  2350. target.drawLine(
  2351. Math.round((options.get('target') - minValue) * unitSize + canvasLeft - size),
  2352. Math.round(canvasHeight / 2),
  2353. Math.round((options.get('target') - minValue) * unitSize + canvasLeft + size),
  2354. Math.round(canvasHeight / 2),
  2355. options.get('targetColor')).append();
  2356. }
  2357. target.render();
  2358. }
  2359. });
  2360. // Setup a very simple "virtual canvas" to make drawing the few shapes we need easier
  2361. // This is accessible as $(foo).simpledraw()
  2362. VShape = createClass({
  2363. init: function (target, id, type, args) {
  2364. this.target = target;
  2365. this.id = id;
  2366. this.type = type;
  2367. this.args = args;
  2368. },
  2369. append: function () {
  2370. this.target.appendShape(this);
  2371. return this;
  2372. }
  2373. });
  2374. VCanvas_base = createClass({
  2375. _pxregex: /(\d+)(px)?\s*$/i,
  2376. init: function (width, height, target) {
  2377. if (!width) {
  2378. return;
  2379. }
  2380. this.width = width;
  2381. this.height = height;
  2382. this.target = target;
  2383. this.lastShapeId = null;
  2384. if (target[0]) {
  2385. target = target[0];
  2386. }
  2387. $.data(target, '_jqs_vcanvas', this);
  2388. },
  2389. drawLine: function (x1, y1, x2, y2, lineColor, lineWidth) {
  2390. return this.drawShape([[x1, y1], [x2, y2]], lineColor, lineWidth);
  2391. },
  2392. drawShape: function (path, lineColor, fillColor, lineWidth) {
  2393. return this._genShape('Shape', [path, lineColor, fillColor, lineWidth]);
  2394. },
  2395. drawCircle: function (x, y, radius, lineColor, fillColor, lineWidth) {
  2396. return this._genShape('Circle', [x, y, radius, lineColor, fillColor, lineWidth]);
  2397. },
  2398. drawPieSlice: function (x, y, radius, startAngle, endAngle, lineColor, fillColor) {
  2399. return this._genShape('PieSlice', [x, y, radius, startAngle, endAngle, lineColor, fillColor]);
  2400. },
  2401. drawRect: function (x, y, width, height, lineColor, fillColor) {
  2402. return this._genShape('Rect', [x, y, width, height, lineColor, fillColor]);
  2403. },
  2404. getElement: function () {
  2405. return this.canvas;
  2406. },
  2407. /**
  2408. * Return the most recently inserted shape id
  2409. */
  2410. getLastShapeId: function () {
  2411. return this.lastShapeId;
  2412. },
  2413. /**
  2414. * Clear and reset the canvas
  2415. */
  2416. reset: function () {
  2417. alert('reset not implemented');
  2418. },
  2419. _insert: function (el, target) {
  2420. $(target).html(el);
  2421. },
  2422. /**
  2423. * Calculate the pixel dimensions of the canvas
  2424. */
  2425. _calculatePixelDims: function (width, height, canvas) {
  2426. // XXX This should probably be a configurable option
  2427. var match;
  2428. match = this._pxregex.exec(height);
  2429. if (match) {
  2430. this.pixelHeight = match[1];
  2431. } else {
  2432. this.pixelHeight = $(canvas).height();
  2433. }
  2434. match = this._pxregex.exec(width);
  2435. if (match) {
  2436. this.pixelWidth = match[1];
  2437. } else {
  2438. this.pixelWidth = $(canvas).width();
  2439. }
  2440. },
  2441. /**
  2442. * Generate a shape object and id for later rendering
  2443. */
  2444. _genShape: function (shapetype, shapeargs) {
  2445. var id = shapeCount++;
  2446. shapeargs.unshift(id);
  2447. return new VShape(this, id, shapetype, shapeargs);
  2448. },
  2449. /**
  2450. * Add a shape to the end of the render queue
  2451. */
  2452. appendShape: function (shape) {
  2453. alert('appendShape not implemented');
  2454. },
  2455. /**
  2456. * Replace one shape with another
  2457. */
  2458. replaceWithShape: function (shapeid, shape) {
  2459. alert('replaceWithShape not implemented');
  2460. },
  2461. /**
  2462. * Insert one shape after another in the render queue
  2463. */
  2464. insertAfterShape: function (shapeid, shape) {
  2465. alert('insertAfterShape not implemented');
  2466. },
  2467. /**
  2468. * Remove a shape from the queue
  2469. */
  2470. removeShapeId: function (shapeid) {
  2471. alert('removeShapeId not implemented');
  2472. },
  2473. /**
  2474. * Find a shape at the specified x/y co-ordinates
  2475. */
  2476. getShapeAt: function (el, x, y) {
  2477. alert('getShapeAt not implemented');
  2478. },
  2479. /**
  2480. * Render all queued shapes onto the canvas
  2481. */
  2482. render: function () {
  2483. alert('render not implemented');
  2484. }
  2485. });
  2486. VCanvas_canvas = createClass(VCanvas_base, {
  2487. init: function (width, height, target, interact) {
  2488. VCanvas_canvas._super.init.call(this, width, height, target);
  2489. this.canvas = document.createElement('canvas');
  2490. if (target[0]) {
  2491. target = target[0];
  2492. }
  2493. $.data(target, '_jqs_vcanvas', this);
  2494. $(this.canvas).css({ display: 'inline-block', width: width, height: height, verticalAlign: 'top' });
  2495. this._insert(this.canvas, target);
  2496. this._calculatePixelDims(width, height, this.canvas);
  2497. this.canvas.width = this.pixelWidth;
  2498. this.canvas.height = this.pixelHeight;
  2499. this.interact = interact;
  2500. this.shapes = {};
  2501. this.shapeseq = [];
  2502. this.currentTargetShapeId = undefined;
  2503. $(this.canvas).css({width: this.pixelWidth, height: this.pixelHeight});
  2504. },
  2505. _getContext: function (lineColor, fillColor, lineWidth) {
  2506. var context = this.canvas.getContext('2d');
  2507. if (lineColor !== undefined) {
  2508. context.strokeStyle = lineColor;
  2509. }
  2510. context.lineWidth = lineWidth === undefined ? 1 : lineWidth;
  2511. if (fillColor !== undefined) {
  2512. context.fillStyle = fillColor;
  2513. }
  2514. return context;
  2515. },
  2516. reset: function () {
  2517. var context = this._getContext();
  2518. context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
  2519. this.shapes = {};
  2520. this.shapeseq = [];
  2521. this.currentTargetShapeId = undefined;
  2522. },
  2523. _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) {
  2524. var context = this._getContext(lineColor, fillColor, lineWidth),
  2525. i, plen;
  2526. context.beginPath();
  2527. context.moveTo(path[0][0] + 0.5, path[0][1] + 0.5);
  2528. for (i = 1, plen = path.length; i < plen; i++) {
  2529. context.lineTo(path[i][0] + 0.5, path[i][1] + 0.5); // the 0.5 offset gives us crisp pixel-width lines
  2530. }
  2531. if (lineColor !== undefined) {
  2532. context.stroke();
  2533. }
  2534. if (fillColor !== undefined) {
  2535. context.fill();
  2536. }
  2537. if (this.targetX !== undefined && this.targetY !== undefined &&
  2538. context.isPointInPath(this.targetX, this.targetY)) {
  2539. this.currentTargetShapeId = shapeid;
  2540. }
  2541. },
  2542. _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) {
  2543. var context = this._getContext(lineColor, fillColor, lineWidth);
  2544. context.beginPath();
  2545. context.arc(x, y, radius, 0, 2 * Math.PI, false);
  2546. if (this.targetX !== undefined && this.targetY !== undefined &&
  2547. context.isPointInPath(this.targetX, this.targetY)) {
  2548. this.currentTargetShapeId = shapeid;
  2549. }
  2550. if (lineColor !== undefined) {
  2551. context.stroke();
  2552. }
  2553. if (fillColor !== undefined) {
  2554. context.fill();
  2555. }
  2556. },
  2557. _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) {
  2558. var context = this._getContext(lineColor, fillColor);
  2559. context.beginPath();
  2560. context.moveTo(x, y);
  2561. context.arc(x, y, radius, startAngle, endAngle, false);
  2562. context.lineTo(x, y);
  2563. context.closePath();
  2564. if (lineColor !== undefined) {
  2565. context.stroke();
  2566. }
  2567. if (fillColor) {
  2568. context.fill();
  2569. }
  2570. if (this.targetX !== undefined && this.targetY !== undefined &&
  2571. context.isPointInPath(this.targetX, this.targetY)) {
  2572. this.currentTargetShapeId = shapeid;
  2573. }
  2574. },
  2575. _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) {
  2576. return this._drawShape(shapeid, [[x, y], [x + width, y], [x + width, y + height], [x, y + height], [x, y]], lineColor, fillColor);
  2577. },
  2578. appendShape: function (shape) {
  2579. this.shapes[shape.id] = shape;
  2580. this.shapeseq.push(shape.id);
  2581. this.lastShapeId = shape.id;
  2582. return shape.id;
  2583. },
  2584. replaceWithShape: function (shapeid, shape) {
  2585. var shapeseq = this.shapeseq,
  2586. i;
  2587. this.shapes[shape.id] = shape;
  2588. for (i = shapeseq.length; i--;) {
  2589. if (shapeseq[i] == shapeid) {
  2590. shapeseq[i] = shape.id;
  2591. }
  2592. }
  2593. delete this.shapes[shapeid];
  2594. },
  2595. replaceWithShapes: function (shapeids, shapes) {
  2596. var shapeseq = this.shapeseq,
  2597. shapemap = {},
  2598. sid, i, first;
  2599. for (i = shapeids.length; i--;) {
  2600. shapemap[shapeids[i]] = true;
  2601. }
  2602. for (i = shapeseq.length; i--;) {
  2603. sid = shapeseq[i];
  2604. if (shapemap[sid]) {
  2605. shapeseq.splice(i, 1);
  2606. delete this.shapes[sid];
  2607. first = i;
  2608. }
  2609. }
  2610. for (i = shapes.length; i--;) {
  2611. shapeseq.splice(first, 0, shapes[i].id);
  2612. this.shapes[shapes[i].id] = shapes[i];
  2613. }
  2614. },
  2615. insertAfterShape: function (shapeid, shape) {
  2616. var shapeseq = this.shapeseq,
  2617. i;
  2618. for (i = shapeseq.length; i--;) {
  2619. if (shapeseq[i] === shapeid) {
  2620. shapeseq.splice(i + 1, 0, shape.id);
  2621. this.shapes[shape.id] = shape;
  2622. return;
  2623. }
  2624. }
  2625. },
  2626. removeShapeId: function (shapeid) {
  2627. var shapeseq = this.shapeseq,
  2628. i;
  2629. for (i = shapeseq.length; i--;) {
  2630. if (shapeseq[i] === shapeid) {
  2631. shapeseq.splice(i, 1);
  2632. break;
  2633. }
  2634. }
  2635. delete this.shapes[shapeid];
  2636. },
  2637. getShapeAt: function (el, x, y) {
  2638. this.targetX = x;
  2639. this.targetY = y;
  2640. this.render();
  2641. return this.currentTargetShapeId;
  2642. },
  2643. render: function () {
  2644. var shapeseq = this.shapeseq,
  2645. shapes = this.shapes,
  2646. shapeCount = shapeseq.length,
  2647. context = this._getContext(),
  2648. shapeid, shape, i;
  2649. context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
  2650. for (i = 0; i < shapeCount; i++) {
  2651. shapeid = shapeseq[i];
  2652. shape = shapes[shapeid];
  2653. this['_draw' + shape.type].apply(this, shape.args);
  2654. }
  2655. if (!this.interact) {
  2656. // not interactive so no need to keep the shapes array
  2657. this.shapes = {};
  2658. this.shapeseq = [];
  2659. }
  2660. }
  2661. });
  2662. VCanvas_vml = createClass(VCanvas_base, {
  2663. init: function (width, height, target) {
  2664. var groupel;
  2665. VCanvas_vml._super.init.call(this, width, height, target);
  2666. if (target[0]) {
  2667. target = target[0];
  2668. }
  2669. $.data(target, '_jqs_vcanvas', this);
  2670. this.canvas = document.createElement('span');
  2671. $(this.canvas).css({ display: 'inline-block', position: 'relative', overflow: 'hidden', width: width, height: height, margin: '0px', padding: '0px', verticalAlign: 'top'});
  2672. this._insert(this.canvas, target);
  2673. this._calculatePixelDims(width, height, this.canvas);
  2674. this.canvas.width = this.pixelWidth;
  2675. this.canvas.height = this.pixelHeight;
  2676. groupel = '<v:group coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '"' +
  2677. ' style="position:absolute;top:0;left:0;width:' + this.pixelWidth + 'px;height=' + this.pixelHeight + 'px;"></v:group>';
  2678. this.canvas.insertAdjacentHTML('beforeEnd', groupel);
  2679. this.group = $(this.canvas).children()[0];
  2680. this.rendered = false;
  2681. this.prerender = '';
  2682. },
  2683. _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) {
  2684. var vpath = [],
  2685. initial, stroke, fill, closed, vel, plen, i;
  2686. for (i = 0, plen = path.length; i < plen; i++) {
  2687. vpath[i] = '' + (path[i][0]) + ',' + (path[i][1]);
  2688. }
  2689. initial = vpath.splice(0, 1);
  2690. lineWidth = lineWidth === undefined ? 1 : lineWidth;
  2691. stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" ';
  2692. fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
  2693. closed = vpath[0] === vpath[vpath.length - 1] ? 'x ' : '';
  2694. vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' +
  2695. ' id="jqsshape' + shapeid + '" ' +
  2696. stroke +
  2697. fill +
  2698. ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' +
  2699. ' path="m ' + initial + ' l ' + vpath.join(', ') + ' ' + closed + 'e">' +
  2700. ' </v:shape>';
  2701. return vel;
  2702. },
  2703. _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) {
  2704. var stroke, fill, vel;
  2705. x -= radius;
  2706. y -= radius;
  2707. stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" ';
  2708. fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
  2709. vel = '<v:oval ' +
  2710. ' id="jqsshape' + shapeid + '" ' +
  2711. stroke +
  2712. fill +
  2713. ' style="position:absolute;top:' + y + 'px; left:' + x + 'px; width:' + (radius * 2) + 'px; height:' + (radius * 2) + 'px"></v:oval>';
  2714. return vel;
  2715. },
  2716. _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) {
  2717. var vpath, startx, starty, endx, endy, stroke, fill, vel;
  2718. if (startAngle === endAngle) {
  2719. return ''; // VML seems to have problem when start angle equals end angle.
  2720. }
  2721. if ((endAngle - startAngle) === (2 * Math.PI)) {
  2722. startAngle = 0.0; // VML seems to have a problem when drawing a full circle that doesn't start 0
  2723. endAngle = (2 * Math.PI);
  2724. }
  2725. startx = x + Math.round(Math.cos(startAngle) * radius);
  2726. starty = y + Math.round(Math.sin(startAngle) * radius);
  2727. endx = x + Math.round(Math.cos(endAngle) * radius);
  2728. endy = y + Math.round(Math.sin(endAngle) * radius);
  2729. if (startx === endx && starty === endy) {
  2730. if ((endAngle - startAngle) < Math.PI) {
  2731. // Prevent very small slices from being mistaken as a whole pie
  2732. return '';
  2733. }
  2734. // essentially going to be the entire circle, so ignore startAngle
  2735. startx = endx = x + radius;
  2736. starty = endy = y;
  2737. }
  2738. if (startx === endx && starty === endy && (endAngle - startAngle) < Math.PI) {
  2739. return '';
  2740. }
  2741. vpath = [x - radius, y - radius, x + radius, y + radius, startx, starty, endx, endy];
  2742. stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="1px" strokeColor="' + lineColor + '" ';
  2743. fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
  2744. vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' +
  2745. ' id="jqsshape' + shapeid + '" ' +
  2746. stroke +
  2747. fill +
  2748. ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' +
  2749. ' path="m ' + x + ',' + y + ' wa ' + vpath.join(', ') + ' x e">' +
  2750. ' </v:shape>';
  2751. return vel;
  2752. },
  2753. _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) {
  2754. return this._drawShape(shapeid, [[x, y], [x, y + height], [x + width, y + height], [x + width, y], [x, y]], lineColor, fillColor);
  2755. },
  2756. reset: function () {
  2757. this.group.innerHTML = '';
  2758. },
  2759. appendShape: function (shape) {
  2760. var vel = this['_draw' + shape.type].apply(this, shape.args);
  2761. if (this.rendered) {
  2762. this.group.insertAdjacentHTML('beforeEnd', vel);
  2763. } else {
  2764. this.prerender += vel;
  2765. }
  2766. this.lastShapeId = shape.id;
  2767. return shape.id;
  2768. },
  2769. replaceWithShape: function (shapeid, shape) {
  2770. var existing = $('#jqsshape' + shapeid),
  2771. vel = this['_draw' + shape.type].apply(this, shape.args);
  2772. existing[0].outerHTML = vel;
  2773. },
  2774. replaceWithShapes: function (shapeids, shapes) {
  2775. // replace the first shapeid with all the new shapes then toast the remaining old shapes
  2776. var existing = $('#jqsshape' + shapeids[0]),
  2777. replace = '',
  2778. slen = shapes.length,
  2779. i;
  2780. for (i = 0; i < slen; i++) {
  2781. replace += this['_draw' + shapes[i].type].apply(this, shapes[i].args);
  2782. }
  2783. existing[0].outerHTML = replace;
  2784. for (i = 1; i < shapeids.length; i++) {
  2785. $('#jqsshape' + shapeids[i]).remove();
  2786. }
  2787. },
  2788. insertAfterShape: function (shapeid, shape) {
  2789. var existing = $('#jqsshape' + shapeid),
  2790. vel = this['_draw' + shape.type].apply(this, shape.args);
  2791. existing[0].insertAdjacentHTML('afterEnd', vel);
  2792. },
  2793. removeShapeId: function (shapeid) {
  2794. var existing = $('#jqsshape' + shapeid);
  2795. this.group.removeChild(existing[0]);
  2796. },
  2797. getShapeAt: function (el, x, y) {
  2798. var shapeid = el.id.substr(8);
  2799. return shapeid;
  2800. },
  2801. render: function () {
  2802. if (!this.rendered) {
  2803. // batch the intial render into a single repaint
  2804. this.group.innerHTML = this.prerender;
  2805. this.rendered = true;
  2806. }
  2807. }
  2808. });
  2809. }))}(document, Math));
  2810. document.addEventListener('DOMContentLoaded', function () {
  2811. /* this sets all default colors and width sizes - however you can still override them with the HTML tagOptions */
  2812. /* this is a non-destructive settings which can be applied to any sparkline chart to keep things constant */
  2813. $('.sparklines').sparkline('html', {
  2814. // enables you to use HTML tad options (eg. sparkBarWidth="100")
  2815. enableTagOptions: true,
  2816. // you can also use percentage (eg. "100%")
  2817. width: 110,
  2818. // globalized height
  2819. height: 40,
  2820. // globalize bar spacing
  2821. barSpacing: "3px",
  2822. // globalized bar width
  2823. barWidth: "7px",
  2824. // the point radius of line chart
  2825. spotRadius: 3,
  2826. // the red line color
  2827. highlightLineColor: rgb2hex($('#js-color-profile .color-danger-700').css('color')),
  2828. // used for box chart
  2829. targetColor: rgb2hex($('#js-color-profile .color-danger-500').css('color')),
  2830. // used for box chart
  2831. performanceColor: rgb2hex($('#js-color-profile .color-primary-700').css('color')),
  2832. // range colors
  2833. rangeColors: [ rgb2hex($('#js-color-profile .color-primary-100').css('color')),
  2834. rgb2hex($('#js-color-profile .color-primary-200').css('color')),
  2835. rgb2hex($('#js-color-profile .color-primary-300').css('color'))],
  2836. // stacked bar colors
  2837. barColor: rgb2hex($('#js-color-profile .color-primary-500').css('color')),
  2838. stackedBarColor: [
  2839. rgb2hex($('#js-color-profile .color-danger-300').css('color')),
  2840. rgb2hex($('#js-color-profile .color-info-300').css('color'))],
  2841. //pie colors
  2842. sliceColors: [ rgb2hex($('#js-color-profile .color-success-500').css('color')),
  2843. rgb2hex($('#js-color-profile .color-info-500').css('color')),
  2844. rgb2hex($('#js-color-profile .color-danger-500').css('color')),
  2845. rgb2hex($('#js-color-profile .color-primary-500').css('color')),
  2846. rgb2hex($('#js-color-profile .color-warning-500').css('color')),
  2847. rgb2hex($('#js-color-profile .color-primary-700').css('color')),
  2848. rgb2hex($('#js-color-profile .color-info-700').css('color')),
  2849. rgb2hex($('#js-color-profile .color-danger-700').css('color'))
  2850. ]
  2851. });
  2852. });