jquery.sparkline.js 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063
  1. /**
  2. *
  3. * jquery.sparkline.js
  4. *
  5. * v2.1.3
  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. shape, i;
  2161. if (!pie._super.render.call(this)) {
  2162. return;
  2163. }
  2164. if (borderWidth) {
  2165. target.drawCircle(radius, radius, Math.floor(radius - (borderWidth / 2)),
  2166. options.get('borderColor'), undefined, borderWidth).append();
  2167. }
  2168. for (i = values.length; i--;) {
  2169. if (values[i]) { // don't render zero values
  2170. shape = this.renderSlice(i).append();
  2171. this.valueShapes[i] = shape.id; // store just the shapeid
  2172. this.shapes[shape.id] = i;
  2173. }
  2174. }
  2175. target.render();
  2176. }
  2177. });
  2178. /**
  2179. * Box plots
  2180. */
  2181. $.fn.sparkline.box = box = createClass($.fn.sparkline._base, {
  2182. type: 'box',
  2183. init: function (el, values, options, width, height) {
  2184. box._super.init.call(this, el, values, options, width, height);
  2185. this.values = $.map(values, Number);
  2186. this.width = options.get('width') === 'auto' ? '4.0em' : width;
  2187. this.initTarget();
  2188. if (!this.values.length) {
  2189. this.disabled = 1;
  2190. }
  2191. },
  2192. /**
  2193. * Simulate a single region
  2194. */
  2195. getRegion: function () {
  2196. return 1;
  2197. },
  2198. getCurrentRegionFields: function () {
  2199. var result = [
  2200. { field: 'lq', value: this.quartiles[0] },
  2201. { field: 'med', value: this.quartiles[1] },
  2202. { field: 'uq', value: this.quartiles[2] }
  2203. ];
  2204. if (this.loutlier !== undefined) {
  2205. result.push({ field: 'lo', value: this.loutlier});
  2206. }
  2207. if (this.routlier !== undefined) {
  2208. result.push({ field: 'ro', value: this.routlier});
  2209. }
  2210. if (this.lwhisker !== undefined) {
  2211. result.push({ field: 'lw', value: this.lwhisker});
  2212. }
  2213. if (this.rwhisker !== undefined) {
  2214. result.push({ field: 'rw', value: this.rwhisker});
  2215. }
  2216. return result;
  2217. },
  2218. render: function () {
  2219. var target = this.target,
  2220. values = this.values,
  2221. vlen = values.length,
  2222. options = this.options,
  2223. canvasWidth = this.canvasWidth,
  2224. canvasHeight = this.canvasHeight,
  2225. minValue = options.get('chartRangeMin') === undefined ? Math.min.apply(Math, values) : options.get('chartRangeMin'),
  2226. maxValue = options.get('chartRangeMax') === undefined ? Math.max.apply(Math, values) : options.get('chartRangeMax'),
  2227. canvasLeft = 0,
  2228. lwhisker, loutlier, iqr, q1, q2, q3, rwhisker, routlier, i,
  2229. size, unitSize;
  2230. if (!box._super.render.call(this)) {
  2231. return;
  2232. }
  2233. if (options.get('raw')) {
  2234. if (options.get('showOutliers') && values.length > 5) {
  2235. loutlier = values[0];
  2236. lwhisker = values[1];
  2237. q1 = values[2];
  2238. q2 = values[3];
  2239. q3 = values[4];
  2240. rwhisker = values[5];
  2241. routlier = values[6];
  2242. } else {
  2243. lwhisker = values[0];
  2244. q1 = values[1];
  2245. q2 = values[2];
  2246. q3 = values[3];
  2247. rwhisker = values[4];
  2248. }
  2249. } else {
  2250. values.sort(function (a, b) { return a - b; });
  2251. q1 = quartile(values, 1);
  2252. q2 = quartile(values, 2);
  2253. q3 = quartile(values, 3);
  2254. iqr = q3 - q1;
  2255. if (options.get('showOutliers')) {
  2256. lwhisker = rwhisker = undefined;
  2257. for (i = 0; i < vlen; i++) {
  2258. if (lwhisker === undefined && values[i] > q1 - (iqr * options.get('outlierIQR'))) {
  2259. lwhisker = values[i];
  2260. }
  2261. if (values[i] < q3 + (iqr * options.get('outlierIQR'))) {
  2262. rwhisker = values[i];
  2263. }
  2264. }
  2265. loutlier = values[0];
  2266. routlier = values[vlen - 1];
  2267. } else {
  2268. lwhisker = values[0];
  2269. rwhisker = values[vlen - 1];
  2270. }
  2271. }
  2272. this.quartiles = [q1, q2, q3];
  2273. this.lwhisker = lwhisker;
  2274. this.rwhisker = rwhisker;
  2275. this.loutlier = loutlier;
  2276. this.routlier = routlier;
  2277. unitSize = canvasWidth / (maxValue - minValue + 1);
  2278. if (options.get('showOutliers')) {
  2279. canvasLeft = Math.ceil(options.get('spotRadius'));
  2280. canvasWidth -= 2 * Math.ceil(options.get('spotRadius'));
  2281. unitSize = canvasWidth / (maxValue - minValue + 1);
  2282. if (loutlier < lwhisker) {
  2283. target.drawCircle((loutlier - minValue) * unitSize + canvasLeft,
  2284. canvasHeight / 2,
  2285. options.get('spotRadius'),
  2286. options.get('outlierLineColor'),
  2287. options.get('outlierFillColor')).append();
  2288. }
  2289. if (routlier > rwhisker) {
  2290. target.drawCircle((routlier - minValue) * unitSize + canvasLeft,
  2291. canvasHeight / 2,
  2292. options.get('spotRadius'),
  2293. options.get('outlierLineColor'),
  2294. options.get('outlierFillColor')).append();
  2295. }
  2296. }
  2297. // box
  2298. target.drawRect(
  2299. Math.round((q1 - minValue) * unitSize + canvasLeft),
  2300. Math.round(canvasHeight * 0.1),
  2301. Math.round((q3 - q1) * unitSize),
  2302. Math.round(canvasHeight * 0.8),
  2303. options.get('boxLineColor'),
  2304. options.get('boxFillColor')).append();
  2305. // left whisker
  2306. target.drawLine(
  2307. Math.round((lwhisker - minValue) * unitSize + canvasLeft),
  2308. Math.round(canvasHeight / 2),
  2309. Math.round((q1 - minValue) * unitSize + canvasLeft),
  2310. Math.round(canvasHeight / 2),
  2311. options.get('lineColor')).append();
  2312. target.drawLine(
  2313. Math.round((lwhisker - minValue) * unitSize + canvasLeft),
  2314. Math.round(canvasHeight / 4),
  2315. Math.round((lwhisker - minValue) * unitSize + canvasLeft),
  2316. Math.round(canvasHeight - canvasHeight / 4),
  2317. options.get('whiskerColor')).append();
  2318. // right whisker
  2319. target.drawLine(Math.round((rwhisker - minValue) * unitSize + canvasLeft),
  2320. Math.round(canvasHeight / 2),
  2321. Math.round((q3 - minValue) * unitSize + canvasLeft),
  2322. Math.round(canvasHeight / 2),
  2323. options.get('lineColor')).append();
  2324. target.drawLine(
  2325. Math.round((rwhisker - minValue) * unitSize + canvasLeft),
  2326. Math.round(canvasHeight / 4),
  2327. Math.round((rwhisker - minValue) * unitSize + canvasLeft),
  2328. Math.round(canvasHeight - canvasHeight / 4),
  2329. options.get('whiskerColor')).append();
  2330. // median line
  2331. target.drawLine(
  2332. Math.round((q2 - minValue) * unitSize + canvasLeft),
  2333. Math.round(canvasHeight * 0.1),
  2334. Math.round((q2 - minValue) * unitSize + canvasLeft),
  2335. Math.round(canvasHeight * 0.9),
  2336. options.get('medianColor')).append();
  2337. if (options.get('target')) {
  2338. size = Math.ceil(options.get('spotRadius'));
  2339. target.drawLine(
  2340. Math.round((options.get('target') - minValue) * unitSize + canvasLeft),
  2341. Math.round((canvasHeight / 2) - size),
  2342. Math.round((options.get('target') - minValue) * unitSize + canvasLeft),
  2343. Math.round((canvasHeight / 2) + size),
  2344. options.get('targetColor')).append();
  2345. target.drawLine(
  2346. Math.round((options.get('target') - minValue) * unitSize + canvasLeft - size),
  2347. Math.round(canvasHeight / 2),
  2348. Math.round((options.get('target') - minValue) * unitSize + canvasLeft + size),
  2349. Math.round(canvasHeight / 2),
  2350. options.get('targetColor')).append();
  2351. }
  2352. target.render();
  2353. }
  2354. });
  2355. // Setup a very simple "virtual canvas" to make drawing the few shapes we need easier
  2356. // This is accessible as $(foo).simpledraw()
  2357. VShape = createClass({
  2358. init: function (target, id, type, args) {
  2359. this.target = target;
  2360. this.id = id;
  2361. this.type = type;
  2362. this.args = args;
  2363. },
  2364. append: function () {
  2365. this.target.appendShape(this);
  2366. return this;
  2367. }
  2368. });
  2369. VCanvas_base = createClass({
  2370. _pxregex: /(\d+)(px)?\s*$/i,
  2371. init: function (width, height, target) {
  2372. if (!width) {
  2373. return;
  2374. }
  2375. this.width = width;
  2376. this.height = height;
  2377. this.target = target;
  2378. this.lastShapeId = null;
  2379. if (target[0]) {
  2380. target = target[0];
  2381. }
  2382. $.data(target, '_jqs_vcanvas', this);
  2383. },
  2384. drawLine: function (x1, y1, x2, y2, lineColor, lineWidth) {
  2385. return this.drawShape([[x1, y1], [x2, y2]], lineColor, lineWidth);
  2386. },
  2387. drawShape: function (path, lineColor, fillColor, lineWidth) {
  2388. return this._genShape('Shape', [path, lineColor, fillColor, lineWidth]);
  2389. },
  2390. drawCircle: function (x, y, radius, lineColor, fillColor, lineWidth) {
  2391. return this._genShape('Circle', [x, y, radius, lineColor, fillColor, lineWidth]);
  2392. },
  2393. drawPieSlice: function (x, y, radius, startAngle, endAngle, lineColor, fillColor) {
  2394. return this._genShape('PieSlice', [x, y, radius, startAngle, endAngle, lineColor, fillColor]);
  2395. },
  2396. drawRect: function (x, y, width, height, lineColor, fillColor) {
  2397. return this._genShape('Rect', [x, y, width, height, lineColor, fillColor]);
  2398. },
  2399. getElement: function () {
  2400. return this.canvas;
  2401. },
  2402. /**
  2403. * Return the most recently inserted shape id
  2404. */
  2405. getLastShapeId: function () {
  2406. return this.lastShapeId;
  2407. },
  2408. /**
  2409. * Clear and reset the canvas
  2410. */
  2411. reset: function () {
  2412. alert('reset not implemented');
  2413. },
  2414. _insert: function (el, target) {
  2415. $(target).html(el);
  2416. },
  2417. /**
  2418. * Calculate the pixel dimensions of the canvas
  2419. */
  2420. _calculatePixelDims: function (width, height, canvas) {
  2421. // XXX This should probably be a configurable option
  2422. var match;
  2423. match = this._pxregex.exec(height);
  2424. if (match) {
  2425. this.pixelHeight = match[1];
  2426. } else {
  2427. this.pixelHeight = $(canvas).height();
  2428. }
  2429. match = this._pxregex.exec(width);
  2430. if (match) {
  2431. this.pixelWidth = match[1];
  2432. } else {
  2433. this.pixelWidth = $(canvas).width();
  2434. }
  2435. },
  2436. /**
  2437. * Generate a shape object and id for later rendering
  2438. */
  2439. _genShape: function (shapetype, shapeargs) {
  2440. var id = shapeCount++;
  2441. shapeargs.unshift(id);
  2442. return new VShape(this, id, shapetype, shapeargs);
  2443. },
  2444. /**
  2445. * Add a shape to the end of the render queue
  2446. */
  2447. appendShape: function (shape) {
  2448. alert('appendShape not implemented');
  2449. },
  2450. /**
  2451. * Replace one shape with another
  2452. */
  2453. replaceWithShape: function (shapeid, shape) {
  2454. alert('replaceWithShape not implemented');
  2455. },
  2456. /**
  2457. * Insert one shape after another in the render queue
  2458. */
  2459. insertAfterShape: function (shapeid, shape) {
  2460. alert('insertAfterShape not implemented');
  2461. },
  2462. /**
  2463. * Remove a shape from the queue
  2464. */
  2465. removeShapeId: function (shapeid) {
  2466. alert('removeShapeId not implemented');
  2467. },
  2468. /**
  2469. * Find a shape at the specified x/y co-ordinates
  2470. */
  2471. getShapeAt: function (el, x, y) {
  2472. alert('getShapeAt not implemented');
  2473. },
  2474. /**
  2475. * Render all queued shapes onto the canvas
  2476. */
  2477. render: function () {
  2478. alert('render not implemented');
  2479. }
  2480. });
  2481. VCanvas_canvas = createClass(VCanvas_base, {
  2482. init: function (width, height, target, interact) {
  2483. VCanvas_canvas._super.init.call(this, width, height, target);
  2484. this.canvas = document.createElement('canvas');
  2485. if (target[0]) {
  2486. target = target[0];
  2487. }
  2488. $.data(target, '_jqs_vcanvas', this);
  2489. $(this.canvas).css({ display: 'inline-block', width: width, height: height, verticalAlign: 'top' });
  2490. this._insert(this.canvas, target);
  2491. this._calculatePixelDims(width, height, this.canvas);
  2492. this.canvas.width = this.pixelWidth;
  2493. this.canvas.height = this.pixelHeight;
  2494. this.interact = interact;
  2495. this.shapes = {};
  2496. this.shapeseq = [];
  2497. this.currentTargetShapeId = undefined;
  2498. $(this.canvas).css({width: this.pixelWidth, height: this.pixelHeight});
  2499. },
  2500. _getContext: function (lineColor, fillColor, lineWidth) {
  2501. var context = this.canvas.getContext('2d');
  2502. if (lineColor !== undefined) {
  2503. context.strokeStyle = lineColor;
  2504. }
  2505. context.lineWidth = lineWidth === undefined ? 1 : lineWidth;
  2506. if (fillColor !== undefined) {
  2507. context.fillStyle = fillColor;
  2508. }
  2509. return context;
  2510. },
  2511. reset: function () {
  2512. var context = this._getContext();
  2513. context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
  2514. this.shapes = {};
  2515. this.shapeseq = [];
  2516. this.currentTargetShapeId = undefined;
  2517. },
  2518. _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) {
  2519. var context = this._getContext(lineColor, fillColor, lineWidth),
  2520. i, plen;
  2521. context.beginPath();
  2522. context.moveTo(path[0][0] + 0.5, path[0][1] + 0.5);
  2523. for (i = 1, plen = path.length; i < plen; i++) {
  2524. context.lineTo(path[i][0] + 0.5, path[i][1] + 0.5); // the 0.5 offset gives us crisp pixel-width lines
  2525. }
  2526. if (lineColor !== undefined) {
  2527. context.stroke();
  2528. }
  2529. if (fillColor !== undefined) {
  2530. context.fill();
  2531. }
  2532. if (this.targetX !== undefined && this.targetY !== undefined &&
  2533. context.isPointInPath(this.targetX, this.targetY)) {
  2534. this.currentTargetShapeId = shapeid;
  2535. }
  2536. },
  2537. _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) {
  2538. var context = this._getContext(lineColor, fillColor, lineWidth);
  2539. context.beginPath();
  2540. context.arc(x, y, radius, 0, 2 * Math.PI, false);
  2541. if (this.targetX !== undefined && this.targetY !== undefined &&
  2542. context.isPointInPath(this.targetX, this.targetY)) {
  2543. this.currentTargetShapeId = shapeid;
  2544. }
  2545. if (lineColor !== undefined) {
  2546. context.stroke();
  2547. }
  2548. if (fillColor !== undefined) {
  2549. context.fill();
  2550. }
  2551. },
  2552. _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) {
  2553. var context = this._getContext(lineColor, fillColor);
  2554. context.beginPath();
  2555. context.moveTo(x, y);
  2556. context.arc(x, y, radius, startAngle, endAngle, false);
  2557. context.lineTo(x, y);
  2558. context.closePath();
  2559. if (lineColor !== undefined) {
  2560. context.stroke();
  2561. }
  2562. if (fillColor) {
  2563. context.fill();
  2564. }
  2565. if (this.targetX !== undefined && this.targetY !== undefined &&
  2566. context.isPointInPath(this.targetX, this.targetY)) {
  2567. this.currentTargetShapeId = shapeid;
  2568. }
  2569. },
  2570. _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) {
  2571. return this._drawShape(shapeid, [[x, y], [x + width, y], [x + width, y + height], [x, y + height], [x, y]], lineColor, fillColor);
  2572. },
  2573. appendShape: function (shape) {
  2574. this.shapes[shape.id] = shape;
  2575. this.shapeseq.push(shape.id);
  2576. this.lastShapeId = shape.id;
  2577. return shape.id;
  2578. },
  2579. replaceWithShape: function (shapeid, shape) {
  2580. var shapeseq = this.shapeseq,
  2581. i;
  2582. this.shapes[shape.id] = shape;
  2583. for (i = shapeseq.length; i--;) {
  2584. if (shapeseq[i] == shapeid) {
  2585. shapeseq[i] = shape.id;
  2586. }
  2587. }
  2588. delete this.shapes[shapeid];
  2589. },
  2590. replaceWithShapes: function (shapeids, shapes) {
  2591. var shapeseq = this.shapeseq,
  2592. shapemap = {},
  2593. sid, i, first;
  2594. for (i = shapeids.length; i--;) {
  2595. shapemap[shapeids[i]] = true;
  2596. }
  2597. for (i = shapeseq.length; i--;) {
  2598. sid = shapeseq[i];
  2599. if (shapemap[sid]) {
  2600. shapeseq.splice(i, 1);
  2601. delete this.shapes[sid];
  2602. first = i;
  2603. }
  2604. }
  2605. for (i = shapes.length; i--;) {
  2606. shapeseq.splice(first, 0, shapes[i].id);
  2607. this.shapes[shapes[i].id] = shapes[i];
  2608. }
  2609. },
  2610. insertAfterShape: function (shapeid, shape) {
  2611. var shapeseq = this.shapeseq,
  2612. i;
  2613. for (i = shapeseq.length; i--;) {
  2614. if (shapeseq[i] === shapeid) {
  2615. shapeseq.splice(i + 1, 0, shape.id);
  2616. this.shapes[shape.id] = shape;
  2617. return;
  2618. }
  2619. }
  2620. },
  2621. removeShapeId: function (shapeid) {
  2622. var shapeseq = this.shapeseq,
  2623. i;
  2624. for (i = shapeseq.length; i--;) {
  2625. if (shapeseq[i] === shapeid) {
  2626. shapeseq.splice(i, 1);
  2627. break;
  2628. }
  2629. }
  2630. delete this.shapes[shapeid];
  2631. },
  2632. getShapeAt: function (el, x, y) {
  2633. this.targetX = x;
  2634. this.targetY = y;
  2635. this.render();
  2636. return this.currentTargetShapeId;
  2637. },
  2638. render: function () {
  2639. var shapeseq = this.shapeseq,
  2640. shapes = this.shapes,
  2641. shapeCount = shapeseq.length,
  2642. context = this._getContext(),
  2643. shapeid, shape, i;
  2644. context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
  2645. for (i = 0; i < shapeCount; i++) {
  2646. shapeid = shapeseq[i];
  2647. shape = shapes[shapeid];
  2648. this['_draw' + shape.type].apply(this, shape.args);
  2649. }
  2650. if (!this.interact) {
  2651. // not interactive so no need to keep the shapes array
  2652. this.shapes = {};
  2653. this.shapeseq = [];
  2654. }
  2655. }
  2656. });
  2657. VCanvas_vml = createClass(VCanvas_base, {
  2658. init: function (width, height, target) {
  2659. var groupel;
  2660. VCanvas_vml._super.init.call(this, width, height, target);
  2661. if (target[0]) {
  2662. target = target[0];
  2663. }
  2664. $.data(target, '_jqs_vcanvas', this);
  2665. this.canvas = document.createElement('span');
  2666. $(this.canvas).css({ display: 'inline-block', position: 'relative', overflow: 'hidden', width: width, height: height, margin: '0px', padding: '0px', verticalAlign: 'top'});
  2667. this._insert(this.canvas, target);
  2668. this._calculatePixelDims(width, height, this.canvas);
  2669. this.canvas.width = this.pixelWidth;
  2670. this.canvas.height = this.pixelHeight;
  2671. groupel = '<v:group coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '"' +
  2672. ' style="position:absolute;top:0;left:0;width:' + this.pixelWidth + 'px;height=' + this.pixelHeight + 'px;"></v:group>';
  2673. this.canvas.insertAdjacentHTML('beforeEnd', groupel);
  2674. this.group = $(this.canvas).children()[0];
  2675. this.rendered = false;
  2676. this.prerender = '';
  2677. },
  2678. _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) {
  2679. var vpath = [],
  2680. initial, stroke, fill, closed, vel, plen, i;
  2681. for (i = 0, plen = path.length; i < plen; i++) {
  2682. vpath[i] = '' + (path[i][0]) + ',' + (path[i][1]);
  2683. }
  2684. initial = vpath.splice(0, 1);
  2685. lineWidth = lineWidth === undefined ? 1 : lineWidth;
  2686. stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" ';
  2687. fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
  2688. closed = vpath[0] === vpath[vpath.length - 1] ? 'x ' : '';
  2689. vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' +
  2690. ' id="jqsshape' + shapeid + '" ' +
  2691. stroke +
  2692. fill +
  2693. ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' +
  2694. ' path="m ' + initial + ' l ' + vpath.join(', ') + ' ' + closed + 'e">' +
  2695. ' </v:shape>';
  2696. return vel;
  2697. },
  2698. _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) {
  2699. var stroke, fill, vel;
  2700. x -= radius;
  2701. y -= radius;
  2702. stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" ';
  2703. fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
  2704. vel = '<v:oval ' +
  2705. ' id="jqsshape' + shapeid + '" ' +
  2706. stroke +
  2707. fill +
  2708. ' style="position:absolute;top:' + y + 'px; left:' + x + 'px; width:' + (radius * 2) + 'px; height:' + (radius * 2) + 'px"></v:oval>';
  2709. return vel;
  2710. },
  2711. _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) {
  2712. var vpath, startx, starty, endx, endy, stroke, fill, vel;
  2713. if (startAngle === endAngle) {
  2714. return ''; // VML seems to have problem when start angle equals end angle.
  2715. }
  2716. if ((endAngle - startAngle) === (2 * Math.PI)) {
  2717. startAngle = 0.0; // VML seems to have a problem when drawing a full circle that doesn't start 0
  2718. endAngle = (2 * Math.PI);
  2719. }
  2720. startx = x + Math.round(Math.cos(startAngle) * radius);
  2721. starty = y + Math.round(Math.sin(startAngle) * radius);
  2722. endx = x + Math.round(Math.cos(endAngle) * radius);
  2723. endy = y + Math.round(Math.sin(endAngle) * radius);
  2724. if (startx === endx && starty === endy) {
  2725. if ((endAngle - startAngle) < Math.PI) {
  2726. // Prevent very small slices from being mistaken as a whole pie
  2727. return '';
  2728. }
  2729. // essentially going to be the entire circle, so ignore startAngle
  2730. startx = endx = x + radius;
  2731. starty = endy = y;
  2732. }
  2733. if (startx === endx && starty === endy && (endAngle - startAngle) < Math.PI) {
  2734. return '';
  2735. }
  2736. vpath = [x - radius, y - radius, x + radius, y + radius, startx, starty, endx, endy];
  2737. stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="1px" strokeColor="' + lineColor + '" ';
  2738. fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
  2739. vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' +
  2740. ' id="jqsshape' + shapeid + '" ' +
  2741. stroke +
  2742. fill +
  2743. ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' +
  2744. ' path="m ' + x + ',' + y + ' wa ' + vpath.join(', ') + ' x e">' +
  2745. ' </v:shape>';
  2746. return vel;
  2747. },
  2748. _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) {
  2749. return this._drawShape(shapeid, [[x, y], [x, y + height], [x + width, y + height], [x + width, y], [x, y]], lineColor, fillColor);
  2750. },
  2751. reset: function () {
  2752. this.group.innerHTML = '';
  2753. },
  2754. appendShape: function (shape) {
  2755. var vel = this['_draw' + shape.type].apply(this, shape.args);
  2756. if (this.rendered) {
  2757. this.group.insertAdjacentHTML('beforeEnd', vel);
  2758. } else {
  2759. this.prerender += vel;
  2760. }
  2761. this.lastShapeId = shape.id;
  2762. return shape.id;
  2763. },
  2764. replaceWithShape: function (shapeid, shape) {
  2765. var existing = $('#jqsshape' + shapeid),
  2766. vel = this['_draw' + shape.type].apply(this, shape.args);
  2767. existing[0].outerHTML = vel;
  2768. },
  2769. replaceWithShapes: function (shapeids, shapes) {
  2770. // replace the first shapeid with all the new shapes then toast the remaining old shapes
  2771. var existing = $('#jqsshape' + shapeids[0]),
  2772. replace = '',
  2773. slen = shapes.length,
  2774. i;
  2775. for (i = 0; i < slen; i++) {
  2776. replace += this['_draw' + shapes[i].type].apply(this, shapes[i].args);
  2777. }
  2778. existing[0].outerHTML = replace;
  2779. for (i = 1; i < shapeids.length; i++) {
  2780. $('#jqsshape' + shapeids[i]).remove();
  2781. }
  2782. },
  2783. insertAfterShape: function (shapeid, shape) {
  2784. var existing = $('#jqsshape' + shapeid),
  2785. vel = this['_draw' + shape.type].apply(this, shape.args);
  2786. existing[0].insertAdjacentHTML('afterEnd', vel);
  2787. },
  2788. removeShapeId: function (shapeid) {
  2789. var existing = $('#jqsshape' + shapeid);
  2790. this.group.removeChild(existing[0]);
  2791. },
  2792. getShapeAt: function (el, x, y) {
  2793. var shapeid = el.id.substr(8);
  2794. return shapeid;
  2795. },
  2796. render: function () {
  2797. if (!this.rendered) {
  2798. // batch the intial render into a single repaint
  2799. this.group.innerHTML = this.prerender;
  2800. this.rendered = true;
  2801. }
  2802. }
  2803. });
  2804. }))}(document, Math));