Dashboard sipadu mbip
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

jquery.sparkline.js 124KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055
  1. /**
  2. *
  3. * jquery.sparkline.js
  4. *
  5. * v2.1.2
  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 teh 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 tagOptionPrefix)
  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. * tagOptionPrefix - 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. 'z-index: 10000;' +
  366. '}' +
  367. '.jqsfield { ' +
  368. 'color: white;' +
  369. 'font: 10px arial, san serif;' +
  370. 'text-align: left;' +
  371. '}';
  372. /**
  373. * Utilities
  374. */
  375. createClass = function (/* [baseclass, [mixin, ...]], definition */) {
  376. var Class, args;
  377. Class = function () {
  378. this.init.apply(this, arguments);
  379. };
  380. if (arguments.length > 1) {
  381. if (arguments[0]) {
  382. Class.prototype = $.extend(new arguments[0](), arguments[arguments.length - 1]);
  383. Class._super = arguments[0].prototype;
  384. } else {
  385. Class.prototype = arguments[arguments.length - 1];
  386. }
  387. if (arguments.length > 2) {
  388. args = Array.prototype.slice.call(arguments, 1, -1);
  389. args.unshift(Class.prototype);
  390. $.extend.apply($, args);
  391. }
  392. } else {
  393. Class.prototype = arguments[0];
  394. }
  395. Class.prototype.cls = Class;
  396. return Class;
  397. };
  398. /**
  399. * Wraps a format string for tooltips
  400. * {{x}}
  401. * {{x.2}
  402. * {{x:months}}
  403. */
  404. $.SPFormatClass = SPFormat = createClass({
  405. fre: /\{\{([\w.]+?)(:(.+?))?\}\}/g,
  406. precre: /(\w+)\.(\d+)/,
  407. init: function (format, fclass) {
  408. this.format = format;
  409. this.fclass = fclass;
  410. },
  411. render: function (fieldset, lookups, options) {
  412. var self = this,
  413. fields = fieldset,
  414. match, token, lookupkey, fieldvalue, prec;
  415. return this.format.replace(this.fre, function () {
  416. var lookup;
  417. token = arguments[1];
  418. lookupkey = arguments[3];
  419. match = self.precre.exec(token);
  420. if (match) {
  421. prec = match[2];
  422. token = match[1];
  423. } else {
  424. prec = false;
  425. }
  426. fieldvalue = fields[token];
  427. if (fieldvalue === undefined) {
  428. return '';
  429. }
  430. if (lookupkey && lookups && lookups[lookupkey]) {
  431. lookup = lookups[lookupkey];
  432. if (lookup.get) { // RangeMap
  433. return lookups[lookupkey].get(fieldvalue) || fieldvalue;
  434. } else {
  435. return lookups[lookupkey][fieldvalue] || fieldvalue;
  436. }
  437. }
  438. if (isNumber(fieldvalue)) {
  439. if (options.get('numberFormatter')) {
  440. fieldvalue = options.get('numberFormatter')(fieldvalue);
  441. } else {
  442. fieldvalue = formatNumber(fieldvalue, prec,
  443. options.get('numberDigitGroupCount'),
  444. options.get('numberDigitGroupSep'),
  445. options.get('numberDecimalMark'));
  446. }
  447. }
  448. return fieldvalue;
  449. });
  450. }
  451. });
  452. // convience method to avoid needing the new operator
  453. $.spformat = function(format, fclass) {
  454. return new SPFormat(format, fclass);
  455. };
  456. clipval = function (val, min, max) {
  457. if (val < min) {
  458. return min;
  459. }
  460. if (val > max) {
  461. return max;
  462. }
  463. return val;
  464. };
  465. quartile = function (values, q) {
  466. var vl;
  467. if (q === 2) {
  468. vl = Math.floor(values.length / 2);
  469. return values.length % 2 ? values[vl] : (values[vl-1] + values[vl]) / 2;
  470. } else {
  471. if (values.length % 2 ) { // odd
  472. vl = (values.length * q + q) / 4;
  473. return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1];
  474. } else { //even
  475. vl = (values.length * q + 2) / 4;
  476. return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1];
  477. }
  478. }
  479. };
  480. normalizeValue = function (val) {
  481. var nf;
  482. switch (val) {
  483. case 'undefined':
  484. val = undefined;
  485. break;
  486. case 'null':
  487. val = null;
  488. break;
  489. case 'true':
  490. val = true;
  491. break;
  492. case 'false':
  493. val = false;
  494. break;
  495. default:
  496. nf = parseFloat(val);
  497. if (val == nf) {
  498. val = nf;
  499. }
  500. }
  501. return val;
  502. };
  503. normalizeValues = function (vals) {
  504. var i, result = [];
  505. for (i = vals.length; i--;) {
  506. result[i] = normalizeValue(vals[i]);
  507. }
  508. return result;
  509. };
  510. remove = function (vals, filter) {
  511. var i, vl, result = [];
  512. for (i = 0, vl = vals.length; i < vl; i++) {
  513. if (vals[i] !== filter) {
  514. result.push(vals[i]);
  515. }
  516. }
  517. return result;
  518. };
  519. isNumber = function (num) {
  520. return !isNaN(parseFloat(num)) && isFinite(num);
  521. };
  522. formatNumber = function (num, prec, groupsize, groupsep, decsep) {
  523. var p, i;
  524. num = (prec === false ? parseFloat(num).toString() : num.toFixed(prec)).split('');
  525. p = (p = $.inArray('.', num)) < 0 ? num.length : p;
  526. if (p < num.length) {
  527. num[p] = decsep;
  528. }
  529. for (i = p - groupsize; i > 0; i -= groupsize) {
  530. num.splice(i, 0, groupsep);
  531. }
  532. return num.join('');
  533. };
  534. // determine if all values of an array match a value
  535. // returns true if the array is empty
  536. all = function (val, arr, ignoreNull) {
  537. var i;
  538. for (i = arr.length; i--; ) {
  539. if (ignoreNull && arr[i] === null) continue;
  540. if (arr[i] !== val) {
  541. return false;
  542. }
  543. }
  544. return true;
  545. };
  546. // sums the numeric values in an array, ignoring other values
  547. sum = function (vals) {
  548. var total = 0, i;
  549. for (i = vals.length; i--;) {
  550. total += typeof vals[i] === 'number' ? vals[i] : 0;
  551. }
  552. return total;
  553. };
  554. ensureArray = function (val) {
  555. return $.isArray(val) ? val : [val];
  556. };
  557. // http://paulirish.com/2008/bookmarklet-inject-new-css-rules/
  558. addCSS = function(css) {
  559. var tag;
  560. //if ('\v' == 'v') /* ie only */ {
  561. if (document.createStyleSheet) {
  562. document.createStyleSheet().cssText = css;
  563. } else {
  564. tag = document.createElement('style');
  565. tag.type = 'text/css';
  566. document.getElementsByTagName('head')[0].appendChild(tag);
  567. tag[(typeof document.body.style.WebkitAppearance == 'string') /* webkit only */ ? 'innerText' : 'innerHTML'] = css;
  568. }
  569. };
  570. // Provide a cross-browser interface to a few simple drawing primitives
  571. $.fn.simpledraw = function (width, height, useExisting, interact) {
  572. var target, mhandler;
  573. if (useExisting && (target = this.data('_jqs_vcanvas'))) {
  574. return target;
  575. }
  576. if ($.fn.sparkline.canvas === false) {
  577. // We've already determined that neither Canvas nor VML are available
  578. return false;
  579. } else if ($.fn.sparkline.canvas === undefined) {
  580. // No function defined yet -- need to see if we support Canvas or VML
  581. var el = document.createElement('canvas');
  582. if (!!(el.getContext && el.getContext('2d'))) {
  583. // Canvas is available
  584. $.fn.sparkline.canvas = function(width, height, target, interact) {
  585. return new VCanvas_canvas(width, height, target, interact);
  586. };
  587. } else if (document.namespaces && !document.namespaces.v) {
  588. // VML is available
  589. document.namespaces.add('v', 'urn:schemas-microsoft-com:vml', '#default#VML');
  590. $.fn.sparkline.canvas = function(width, height, target, interact) {
  591. return new VCanvas_vml(width, height, target);
  592. };
  593. } else {
  594. // Neither Canvas nor VML are available
  595. $.fn.sparkline.canvas = false;
  596. return false;
  597. }
  598. }
  599. if (width === undefined) {
  600. width = $(this).innerWidth();
  601. }
  602. if (height === undefined) {
  603. height = $(this).innerHeight();
  604. }
  605. target = $.fn.sparkline.canvas(width, height, this, interact);
  606. mhandler = $(this).data('_jqs_mhandler');
  607. if (mhandler) {
  608. mhandler.registerCanvas(target);
  609. }
  610. return target;
  611. };
  612. $.fn.cleardraw = function () {
  613. var target = this.data('_jqs_vcanvas');
  614. if (target) {
  615. target.reset();
  616. }
  617. };
  618. $.RangeMapClass = RangeMap = createClass({
  619. init: function (map) {
  620. var key, range, rangelist = [];
  621. for (key in map) {
  622. if (map.hasOwnProperty(key) && typeof key === 'string' && key.indexOf(':') > -1) {
  623. range = key.split(':');
  624. range[0] = range[0].length === 0 ? -Infinity : parseFloat(range[0]);
  625. range[1] = range[1].length === 0 ? Infinity : parseFloat(range[1]);
  626. range[2] = map[key];
  627. rangelist.push(range);
  628. }
  629. }
  630. this.map = map;
  631. this.rangelist = rangelist || false;
  632. },
  633. get: function (value) {
  634. var rangelist = this.rangelist,
  635. i, range, result;
  636. if ((result = this.map[value]) !== undefined) {
  637. return result;
  638. }
  639. if (rangelist) {
  640. for (i = rangelist.length; i--;) {
  641. range = rangelist[i];
  642. if (range[0] <= value && range[1] >= value) {
  643. return range[2];
  644. }
  645. }
  646. }
  647. return undefined;
  648. }
  649. });
  650. // Convenience function
  651. $.range_map = function(map) {
  652. return new RangeMap(map);
  653. };
  654. MouseHandler = createClass({
  655. init: function (el, options) {
  656. var $el = $(el);
  657. this.$el = $el;
  658. this.options = options;
  659. this.currentPageX = 0;
  660. this.currentPageY = 0;
  661. this.el = el;
  662. this.splist = [];
  663. this.tooltip = null;
  664. this.over = false;
  665. this.displayTooltips = !options.get('disableTooltips');
  666. this.highlightEnabled = !options.get('disableHighlight');
  667. },
  668. registerSparkline: function (sp) {
  669. this.splist.push(sp);
  670. if (this.over) {
  671. this.updateDisplay();
  672. }
  673. },
  674. registerCanvas: function (canvas) {
  675. var $canvas = $(canvas.canvas);
  676. this.canvas = canvas;
  677. this.$canvas = $canvas;
  678. $canvas.mouseenter($.proxy(this.mouseenter, this));
  679. $canvas.mouseleave($.proxy(this.mouseleave, this));
  680. $canvas.click($.proxy(this.mouseclick, this));
  681. },
  682. reset: function (removeTooltip) {
  683. this.splist = [];
  684. if (this.tooltip && removeTooltip) {
  685. this.tooltip.remove();
  686. this.tooltip = undefined;
  687. }
  688. },
  689. mouseclick: function (e) {
  690. var clickEvent = $.Event('sparklineClick');
  691. clickEvent.originalEvent = e;
  692. clickEvent.sparklines = this.splist;
  693. this.$el.trigger(clickEvent);
  694. },
  695. mouseenter: function (e) {
  696. $(document.body).unbind('mousemove.jqs');
  697. $(document.body).bind('mousemove.jqs', $.proxy(this.mousemove, this));
  698. this.over = true;
  699. this.currentPageX = e.pageX;
  700. this.currentPageY = e.pageY;
  701. this.currentEl = e.target;
  702. if (!this.tooltip && this.displayTooltips) {
  703. this.tooltip = new Tooltip(this.options);
  704. this.tooltip.updatePosition(e.pageX, e.pageY);
  705. }
  706. this.updateDisplay();
  707. },
  708. mouseleave: function () {
  709. $(document.body).unbind('mousemove.jqs');
  710. var splist = this.splist,
  711. spcount = splist.length,
  712. needsRefresh = false,
  713. sp, i;
  714. this.over = false;
  715. this.currentEl = null;
  716. if (this.tooltip) {
  717. this.tooltip.remove();
  718. this.tooltip = null;
  719. }
  720. for (i = 0; i < spcount; i++) {
  721. sp = splist[i];
  722. if (sp.clearRegionHighlight()) {
  723. needsRefresh = true;
  724. }
  725. }
  726. if (needsRefresh) {
  727. this.canvas.render();
  728. }
  729. },
  730. mousemove: function (e) {
  731. this.currentPageX = e.pageX;
  732. this.currentPageY = e.pageY;
  733. this.currentEl = e.target;
  734. if (this.tooltip) {
  735. this.tooltip.updatePosition(e.pageX, e.pageY);
  736. }
  737. this.updateDisplay();
  738. },
  739. updateDisplay: function () {
  740. var splist = this.splist,
  741. spcount = splist.length,
  742. needsRefresh = false,
  743. offset = this.$canvas.offset(),
  744. localX = this.currentPageX - offset.left,
  745. localY = this.currentPageY - offset.top,
  746. tooltiphtml, sp, i, result, changeEvent;
  747. if (!this.over) {
  748. return;
  749. }
  750. for (i = 0; i < spcount; i++) {
  751. sp = splist[i];
  752. result = sp.setRegionHighlight(this.currentEl, localX, localY);
  753. if (result) {
  754. needsRefresh = true;
  755. }
  756. }
  757. if (needsRefresh) {
  758. changeEvent = $.Event('sparklineRegionChange');
  759. changeEvent.sparklines = this.splist;
  760. this.$el.trigger(changeEvent);
  761. if (this.tooltip) {
  762. tooltiphtml = '';
  763. for (i = 0; i < spcount; i++) {
  764. sp = splist[i];
  765. tooltiphtml += sp.getCurrentRegionTooltip();
  766. }
  767. this.tooltip.setContent(tooltiphtml);
  768. }
  769. if (!this.disableHighlight) {
  770. this.canvas.render();
  771. }
  772. }
  773. if (result === null) {
  774. this.mouseleave();
  775. }
  776. }
  777. });
  778. Tooltip = createClass({
  779. sizeStyle: 'position: static !important;' +
  780. 'display: block !important;' +
  781. 'visibility: hidden !important;' +
  782. 'float: left !important;' +
  783. 'margin: -15px',
  784. init: function (options) {
  785. var tooltipClassname = options.get('tooltipClassname', 'jqstooltip'),
  786. sizetipStyle = this.sizeStyle,
  787. offset;
  788. this.container = options.get('tooltipContainer') || document.body;
  789. this.tooltipOffsetX = options.get('tooltipOffsetX', 20);
  790. this.tooltipOffsetY = options.get('tooltipOffsetY', 12);
  791. // remove any previous lingering tooltip
  792. $('#jqssizetip').remove();
  793. $('#jqstooltip').remove();
  794. this.sizetip = $('<div/>', {
  795. id: 'jqssizetip',
  796. style: sizetipStyle,
  797. 'class': tooltipClassname
  798. });
  799. this.tooltip = $('<div/>', {
  800. id: 'jqstooltip',
  801. 'class': tooltipClassname
  802. }).appendTo(this.container);
  803. // account for the container's location
  804. offset = this.tooltip.offset();
  805. this.offsetLeft = offset.left;
  806. this.offsetTop = offset.top;
  807. this.hidden = true;
  808. $(window).unbind('resize.jqs scroll.jqs');
  809. $(window).bind('resize.jqs scroll.jqs', $.proxy(this.updateWindowDims, this));
  810. this.updateWindowDims();
  811. },
  812. updateWindowDims: function () {
  813. this.scrollTop = $(window).scrollTop();
  814. this.scrollLeft = $(window).scrollLeft();
  815. this.scrollRight = this.scrollLeft + $(window).width();
  816. this.updatePosition();
  817. },
  818. getSize: function (content) {
  819. this.sizetip.html(content).appendTo(this.container);
  820. this.width = this.sizetip.width() + 1;
  821. this.height = this.sizetip.height();
  822. this.sizetip.remove();
  823. },
  824. setContent: function (content) {
  825. if (!content) {
  826. this.tooltip.css('visibility', 'hidden');
  827. this.hidden = true;
  828. return;
  829. }
  830. this.getSize(content);
  831. this.tooltip.html(content)
  832. .css({
  833. 'width': this.width,
  834. 'height': this.height,
  835. 'visibility': 'visible'
  836. });
  837. if (this.hidden) {
  838. this.hidden = false;
  839. this.updatePosition();
  840. }
  841. },
  842. updatePosition: function (x, y) {
  843. if (x === undefined) {
  844. if (this.mousex === undefined) {
  845. return;
  846. }
  847. x = this.mousex - this.offsetLeft;
  848. y = this.mousey - this.offsetTop;
  849. } else {
  850. this.mousex = x = x - this.offsetLeft;
  851. this.mousey = y = y - this.offsetTop;
  852. }
  853. if (!this.height || !this.width || this.hidden) {
  854. return;
  855. }
  856. y -= this.height + this.tooltipOffsetY;
  857. x += this.tooltipOffsetX;
  858. if (y < this.scrollTop) {
  859. y = this.scrollTop;
  860. }
  861. if (x < this.scrollLeft) {
  862. x = this.scrollLeft;
  863. } else if (x + this.width > this.scrollRight) {
  864. x = this.scrollRight - this.width;
  865. }
  866. this.tooltip.css({
  867. 'left': x,
  868. 'top': y
  869. });
  870. },
  871. remove: function () {
  872. this.tooltip.remove();
  873. this.sizetip.remove();
  874. this.sizetip = this.tooltip = undefined;
  875. $(window).unbind('resize.jqs scroll.jqs');
  876. }
  877. });
  878. initStyles = function() {
  879. addCSS(defaultStyles);
  880. };
  881. $(initStyles);
  882. pending = [];
  883. $.fn.sparkline = function (userValues, userOptions) {
  884. return this.each(function () {
  885. var options = new $.fn.sparkline.options(this, userOptions),
  886. $this = $(this),
  887. render, i;
  888. render = function () {
  889. var values, width, height, tmp, mhandler, sp, vals;
  890. if (userValues === 'html' || userValues === undefined) {
  891. vals = this.getAttribute(options.get('tagValuesAttribute'));
  892. if (vals === undefined || vals === null) {
  893. vals = $this.html();
  894. }
  895. values = vals.replace(/(^\s*<!--)|(-->\s*$)|\s+/g, '').split(',');
  896. } else {
  897. values = userValues;
  898. }
  899. width = options.get('width') === 'auto' ? values.length * options.get('defaultPixelsPerValue') : options.get('width');
  900. if (options.get('height') === 'auto') {
  901. if (!options.get('composite') || !$.data(this, '_jqs_vcanvas')) {
  902. // must be a better way to get the line height
  903. tmp = document.createElement('span');
  904. tmp.innerHTML = 'a';
  905. $this.html(tmp);
  906. height = $(tmp).innerHeight() || $(tmp).height();
  907. $(tmp).remove();
  908. tmp = null;
  909. }
  910. } else {
  911. height = options.get('height');
  912. }
  913. if (!options.get('disableInteraction')) {
  914. mhandler = $.data(this, '_jqs_mhandler');
  915. if (!mhandler) {
  916. mhandler = new MouseHandler(this, options);
  917. $.data(this, '_jqs_mhandler', mhandler);
  918. } else if (!options.get('composite')) {
  919. mhandler.reset();
  920. }
  921. } else {
  922. mhandler = false;
  923. }
  924. if (options.get('composite') && !$.data(this, '_jqs_vcanvas')) {
  925. if (!$.data(this, '_jqs_errnotify')) {
  926. alert('Attempted to attach a composite sparkline to an element with no existing sparkline');
  927. $.data(this, '_jqs_errnotify', true);
  928. }
  929. return;
  930. }
  931. sp = new $.fn.sparkline[options.get('type')](this, values, options, width, height);
  932. sp.render();
  933. if (mhandler) {
  934. mhandler.registerSparkline(sp);
  935. }
  936. };
  937. if (($(this).html() && !options.get('disableHiddenCheck') && $(this).is(':hidden')) || !$(this).parents('body').length) {
  938. if (!options.get('composite') && $.data(this, '_jqs_pending')) {
  939. // remove any existing references to the element
  940. for (i = pending.length; i; i--) {
  941. if (pending[i - 1][0] == this) {
  942. pending.splice(i - 1, 1);
  943. }
  944. }
  945. }
  946. pending.push([this, render]);
  947. $.data(this, '_jqs_pending', true);
  948. } else {
  949. render.call(this);
  950. }
  951. });
  952. };
  953. $.fn.sparkline.defaults = getDefaults();
  954. $.sparkline_display_visible = function () {
  955. var el, i, pl;
  956. var done = [];
  957. for (i = 0, pl = pending.length; i < pl; i++) {
  958. el = pending[i][0];
  959. if ($(el).is(':visible') && !$(el).parents().is(':hidden')) {
  960. pending[i][1].call(el);
  961. $.data(pending[i][0], '_jqs_pending', false);
  962. done.push(i);
  963. } else if (!$(el).closest('html').length && !$.data(el, '_jqs_pending')) {
  964. // element has been inserted and removed from the DOM
  965. // If it was not yet inserted into the dom then the .data request
  966. // will return true.
  967. // removing from the dom causes the data to be removed.
  968. $.data(pending[i][0], '_jqs_pending', false);
  969. done.push(i);
  970. }
  971. }
  972. for (i = done.length; i; i--) {
  973. pending.splice(done[i - 1], 1);
  974. }
  975. };
  976. /**
  977. * User option handler
  978. */
  979. $.fn.sparkline.options = createClass({
  980. init: function (tag, userOptions) {
  981. var extendedOptions, defaults, base, tagOptionType;
  982. this.userOptions = userOptions = userOptions || {};
  983. this.tag = tag;
  984. this.tagValCache = {};
  985. defaults = $.fn.sparkline.defaults;
  986. base = defaults.common;
  987. this.tagOptionsPrefix = userOptions.enableTagOptions && (userOptions.tagOptionsPrefix || base.tagOptionsPrefix);
  988. tagOptionType = this.getTagSetting('type');
  989. if (tagOptionType === UNSET_OPTION) {
  990. extendedOptions = defaults[userOptions.type || base.type];
  991. } else {
  992. extendedOptions = defaults[tagOptionType];
  993. }
  994. this.mergedOptions = $.extend({}, base, extendedOptions, userOptions);
  995. },
  996. getTagSetting: function (key) {
  997. var prefix = this.tagOptionsPrefix,
  998. val, i, pairs, keyval;
  999. if (prefix === false || prefix === undefined) {
  1000. return UNSET_OPTION;
  1001. }
  1002. if (this.tagValCache.hasOwnProperty(key)) {
  1003. val = this.tagValCache.key;
  1004. } else {
  1005. val = this.tag.getAttribute(prefix + key);
  1006. if (val === undefined || val === null) {
  1007. val = UNSET_OPTION;
  1008. } else if (val.substr(0, 1) === '[') {
  1009. val = val.substr(1, val.length - 2).split(',');
  1010. for (i = val.length; i--;) {
  1011. val[i] = normalizeValue(val[i].replace(/(^\s*)|(\s*$)/g, ''));
  1012. }
  1013. } else if (val.substr(0, 1) === '{') {
  1014. pairs = val.substr(1, val.length - 2).split(',');
  1015. val = {};
  1016. for (i = pairs.length; i--;) {
  1017. keyval = pairs[i].split(':', 2);
  1018. val[keyval[0].replace(/(^\s*)|(\s*$)/g, '')] = normalizeValue(keyval[1].replace(/(^\s*)|(\s*$)/g, ''));
  1019. }
  1020. } else {
  1021. val = normalizeValue(val);
  1022. }
  1023. this.tagValCache.key = val;
  1024. }
  1025. return val;
  1026. },
  1027. get: function (key, defaultval) {
  1028. var tagOption = this.getTagSetting(key),
  1029. result;
  1030. if (tagOption !== UNSET_OPTION) {
  1031. return tagOption;
  1032. }
  1033. return (result = this.mergedOptions[key]) === undefined ? defaultval : result;
  1034. }
  1035. });
  1036. $.fn.sparkline._base = createClass({
  1037. disabled: false,
  1038. init: function (el, values, options, width, height) {
  1039. this.el = el;
  1040. this.$el = $(el);
  1041. this.values = values;
  1042. this.options = options;
  1043. this.width = width;
  1044. this.height = height;
  1045. this.currentRegion = undefined;
  1046. },
  1047. /**
  1048. * Setup the canvas
  1049. */
  1050. initTarget: function () {
  1051. var interactive = !this.options.get('disableInteraction');
  1052. if (!(this.target = this.$el.simpledraw(this.width, this.height, this.options.get('composite'), interactive))) {
  1053. this.disabled = true;
  1054. } else {
  1055. this.canvasWidth = this.target.pixelWidth;
  1056. this.canvasHeight = this.target.pixelHeight;
  1057. }
  1058. },
  1059. /**
  1060. * Actually render the chart to the canvas
  1061. */
  1062. render: function () {
  1063. if (this.disabled) {
  1064. this.el.innerHTML = '';
  1065. return false;
  1066. }
  1067. return true;
  1068. },
  1069. /**
  1070. * Return a region id for a given x/y co-ordinate
  1071. */
  1072. getRegion: function (x, y) {
  1073. },
  1074. /**
  1075. * Highlight an item based on the moused-over x,y co-ordinate
  1076. */
  1077. setRegionHighlight: function (el, x, y) {
  1078. var currentRegion = this.currentRegion,
  1079. highlightEnabled = !this.options.get('disableHighlight'),
  1080. newRegion;
  1081. if (x > this.canvasWidth || y > this.canvasHeight || x < 0 || y < 0) {
  1082. return null;
  1083. }
  1084. newRegion = this.getRegion(el, x, y);
  1085. if (currentRegion !== newRegion) {
  1086. if (currentRegion !== undefined && highlightEnabled) {
  1087. this.removeHighlight();
  1088. }
  1089. this.currentRegion = newRegion;
  1090. if (newRegion !== undefined && highlightEnabled) {
  1091. this.renderHighlight();
  1092. }
  1093. return true;
  1094. }
  1095. return false;
  1096. },
  1097. /**
  1098. * Reset any currently highlighted item
  1099. */
  1100. clearRegionHighlight: function () {
  1101. if (this.currentRegion !== undefined) {
  1102. this.removeHighlight();
  1103. this.currentRegion = undefined;
  1104. return true;
  1105. }
  1106. return false;
  1107. },
  1108. renderHighlight: function () {
  1109. this.changeHighlight(true);
  1110. },
  1111. removeHighlight: function () {
  1112. this.changeHighlight(false);
  1113. },
  1114. changeHighlight: function (highlight) {},
  1115. /**
  1116. * Fetch the HTML to display as a tooltip
  1117. */
  1118. getCurrentRegionTooltip: function () {
  1119. var options = this.options,
  1120. header = '',
  1121. entries = [],
  1122. fields, formats, formatlen, fclass, text, i,
  1123. showFields, showFieldsKey, newFields, fv,
  1124. formatter, format, fieldlen, j;
  1125. if (this.currentRegion === undefined) {
  1126. return '';
  1127. }
  1128. fields = this.getCurrentRegionFields();
  1129. formatter = options.get('tooltipFormatter');
  1130. if (formatter) {
  1131. return formatter(this, options, fields);
  1132. }
  1133. if (options.get('tooltipChartTitle')) {
  1134. header += '<div class="jqs jqstitle">' + options.get('tooltipChartTitle') + '</div>\n';
  1135. }
  1136. formats = this.options.get('tooltipFormat');
  1137. if (!formats) {
  1138. return '';
  1139. }
  1140. if (!$.isArray(formats)) {
  1141. formats = [formats];
  1142. }
  1143. if (!$.isArray(fields)) {
  1144. fields = [fields];
  1145. }
  1146. showFields = this.options.get('tooltipFormatFieldlist');
  1147. showFieldsKey = this.options.get('tooltipFormatFieldlistKey');
  1148. if (showFields && showFieldsKey) {
  1149. // user-selected ordering of fields
  1150. newFields = [];
  1151. for (i = fields.length; i--;) {
  1152. fv = fields[i][showFieldsKey];
  1153. if ((j = $.inArray(fv, showFields)) != -1) {
  1154. newFields[j] = fields[i];
  1155. }
  1156. }
  1157. fields = newFields;
  1158. }
  1159. formatlen = formats.length;
  1160. fieldlen = fields.length;
  1161. for (i = 0; i < formatlen; i++) {
  1162. format = formats[i];
  1163. if (typeof format === 'string') {
  1164. format = new SPFormat(format);
  1165. }
  1166. fclass = format.fclass || 'def';
  1167. for (j = 0; j < fieldlen; j++) {
  1168. if (!fields[j].isNull || !options.get('tooltipSkipNull')) {
  1169. $.extend(fields[j], {
  1170. prefix: options.get('tooltipPrefix'),
  1171. suffix: options.get('tooltipSuffix')
  1172. });
  1173. text = format.render(fields[j], options.get('tooltipValueLookups'), options);
  1174. entries.push('<div class="' + fclass + '">' + text + '</div>');
  1175. }
  1176. }
  1177. }
  1178. if (entries.length) {
  1179. return header + entries.join('\n');
  1180. }
  1181. return '';
  1182. },
  1183. getCurrentRegionFields: function () {},
  1184. calcHighlightColor: function (color, options) {
  1185. var highlightColor = options.get('highlightColor'),
  1186. lighten = options.get('highlightLighten'),
  1187. parse, mult, rgbnew, i;
  1188. if (highlightColor) {
  1189. return highlightColor;
  1190. }
  1191. if (lighten) {
  1192. // extract RGB values
  1193. 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);
  1194. if (parse) {
  1195. rgbnew = [];
  1196. mult = color.length === 4 ? 16 : 1;
  1197. for (i = 0; i < 3; i++) {
  1198. rgbnew[i] = clipval(Math.round(parseInt(parse[i + 1], 16) * mult * lighten), 0, 255);
  1199. }
  1200. return 'rgb(' + rgbnew.join(',') + ')';
  1201. }
  1202. }
  1203. return color;
  1204. }
  1205. });
  1206. barHighlightMixin = {
  1207. changeHighlight: function (highlight) {
  1208. var currentRegion = this.currentRegion,
  1209. target = this.target,
  1210. shapeids = this.regionShapes[currentRegion],
  1211. newShapes;
  1212. // will be null if the region value was null
  1213. if (shapeids) {
  1214. newShapes = this.renderRegion(currentRegion, highlight);
  1215. if ($.isArray(newShapes) || $.isArray(shapeids)) {
  1216. target.replaceWithShapes(shapeids, newShapes);
  1217. this.regionShapes[currentRegion] = $.map(newShapes, function (newShape) {
  1218. return newShape.id;
  1219. });
  1220. } else {
  1221. target.replaceWithShape(shapeids, newShapes);
  1222. this.regionShapes[currentRegion] = newShapes.id;
  1223. }
  1224. }
  1225. },
  1226. render: function () {
  1227. var values = this.values,
  1228. target = this.target,
  1229. regionShapes = this.regionShapes,
  1230. shapes, ids, i, j;
  1231. if (!this.cls._super.render.call(this)) {
  1232. return;
  1233. }
  1234. for (i = values.length; i--;) {
  1235. shapes = this.renderRegion(i);
  1236. if (shapes) {
  1237. if ($.isArray(shapes)) {
  1238. ids = [];
  1239. for (j = shapes.length; j--;) {
  1240. shapes[j].append();
  1241. ids.push(shapes[j].id);
  1242. }
  1243. regionShapes[i] = ids;
  1244. } else {
  1245. shapes.append();
  1246. regionShapes[i] = shapes.id; // store just the shapeid
  1247. }
  1248. } else {
  1249. // null value
  1250. regionShapes[i] = null;
  1251. }
  1252. }
  1253. target.render();
  1254. }
  1255. };
  1256. /**
  1257. * Line charts
  1258. */
  1259. $.fn.sparkline.line = line = createClass($.fn.sparkline._base, {
  1260. type: 'line',
  1261. init: function (el, values, options, width, height) {
  1262. line._super.init.call(this, el, values, options, width, height);
  1263. this.vertices = [];
  1264. this.regionMap = [];
  1265. this.xvalues = [];
  1266. this.yvalues = [];
  1267. this.yminmax = [];
  1268. this.hightlightSpotId = null;
  1269. this.lastShapeId = null;
  1270. this.initTarget();
  1271. },
  1272. getRegion: function (el, x, y) {
  1273. var i,
  1274. regionMap = this.regionMap; // maps regions to value positions
  1275. for (i = regionMap.length; i--;) {
  1276. if (regionMap[i] !== null && x >= regionMap[i][0] && x <= regionMap[i][1]) {
  1277. return regionMap[i][2];
  1278. }
  1279. }
  1280. return undefined;
  1281. },
  1282. getCurrentRegionFields: function () {
  1283. var currentRegion = this.currentRegion;
  1284. return {
  1285. isNull: this.yvalues[currentRegion] === null,
  1286. x: this.xvalues[currentRegion],
  1287. y: this.yvalues[currentRegion],
  1288. color: this.options.get('lineColor'),
  1289. fillColor: this.options.get('fillColor'),
  1290. offset: currentRegion
  1291. };
  1292. },
  1293. renderHighlight: function () {
  1294. var currentRegion = this.currentRegion,
  1295. target = this.target,
  1296. vertex = this.vertices[currentRegion],
  1297. options = this.options,
  1298. spotRadius = options.get('spotRadius'),
  1299. highlightSpotColor = options.get('highlightSpotColor'),
  1300. highlightLineColor = options.get('highlightLineColor'),
  1301. highlightSpot, highlightLine;
  1302. if (!vertex) {
  1303. return;
  1304. }
  1305. if (spotRadius && highlightSpotColor) {
  1306. highlightSpot = target.drawCircle(vertex[0], vertex[1],
  1307. spotRadius, undefined, highlightSpotColor);
  1308. this.highlightSpotId = highlightSpot.id;
  1309. target.insertAfterShape(this.lastShapeId, highlightSpot);
  1310. }
  1311. if (highlightLineColor) {
  1312. highlightLine = target.drawLine(vertex[0], this.canvasTop, vertex[0],
  1313. this.canvasTop + this.canvasHeight, highlightLineColor);
  1314. this.highlightLineId = highlightLine.id;
  1315. target.insertAfterShape(this.lastShapeId, highlightLine);
  1316. }
  1317. },
  1318. removeHighlight: function () {
  1319. var target = this.target;
  1320. if (this.highlightSpotId) {
  1321. target.removeShapeId(this.highlightSpotId);
  1322. this.highlightSpotId = null;
  1323. }
  1324. if (this.highlightLineId) {
  1325. target.removeShapeId(this.highlightLineId);
  1326. this.highlightLineId = null;
  1327. }
  1328. },
  1329. scanValues: function () {
  1330. var values = this.values,
  1331. valcount = values.length,
  1332. xvalues = this.xvalues,
  1333. yvalues = this.yvalues,
  1334. yminmax = this.yminmax,
  1335. i, val, isStr, isArray, sp;
  1336. for (i = 0; i < valcount; i++) {
  1337. val = values[i];
  1338. isStr = typeof(values[i]) === 'string';
  1339. isArray = typeof(values[i]) === 'object' && values[i] instanceof Array;
  1340. sp = isStr && values[i].split(':');
  1341. if (isStr && sp.length === 2) { // x:y
  1342. xvalues.push(Number(sp[0]));
  1343. yvalues.push(Number(sp[1]));
  1344. yminmax.push(Number(sp[1]));
  1345. } else if (isArray) {
  1346. xvalues.push(val[0]);
  1347. yvalues.push(val[1]);
  1348. yminmax.push(val[1]);
  1349. } else {
  1350. xvalues.push(i);
  1351. if (values[i] === null || values[i] === 'null') {
  1352. yvalues.push(null);
  1353. } else {
  1354. yvalues.push(Number(val));
  1355. yminmax.push(Number(val));
  1356. }
  1357. }
  1358. }
  1359. if (this.options.get('xvalues')) {
  1360. xvalues = this.options.get('xvalues');
  1361. }
  1362. this.maxy = this.maxyorg = Math.max.apply(Math, yminmax);
  1363. this.miny = this.minyorg = Math.min.apply(Math, yminmax);
  1364. this.maxx = Math.max.apply(Math, xvalues);
  1365. this.minx = Math.min.apply(Math, xvalues);
  1366. this.xvalues = xvalues;
  1367. this.yvalues = yvalues;
  1368. this.yminmax = yminmax;
  1369. },
  1370. processRangeOptions: function () {
  1371. var options = this.options,
  1372. normalRangeMin = options.get('normalRangeMin'),
  1373. normalRangeMax = options.get('normalRangeMax');
  1374. if (normalRangeMin !== undefined) {
  1375. if (normalRangeMin < this.miny) {
  1376. this.miny = normalRangeMin;
  1377. }
  1378. if (normalRangeMax > this.maxy) {
  1379. this.maxy = normalRangeMax;
  1380. }
  1381. }
  1382. if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.miny)) {
  1383. this.miny = options.get('chartRangeMin');
  1384. }
  1385. if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.maxy)) {
  1386. this.maxy = options.get('chartRangeMax');
  1387. }
  1388. if (options.get('chartRangeMinX') !== undefined && (options.get('chartRangeClipX') || options.get('chartRangeMinX') < this.minx)) {
  1389. this.minx = options.get('chartRangeMinX');
  1390. }
  1391. if (options.get('chartRangeMaxX') !== undefined && (options.get('chartRangeClipX') || options.get('chartRangeMaxX') > this.maxx)) {
  1392. this.maxx = options.get('chartRangeMaxX');
  1393. }
  1394. },
  1395. drawNormalRange: function (canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey) {
  1396. var normalRangeMin = this.options.get('normalRangeMin'),
  1397. normalRangeMax = this.options.get('normalRangeMax'),
  1398. ytop = canvasTop + Math.round(canvasHeight - (canvasHeight * ((normalRangeMax - this.miny) / rangey))),
  1399. height = Math.round((canvasHeight * (normalRangeMax - normalRangeMin)) / rangey);
  1400. this.target.drawRect(canvasLeft, ytop, canvasWidth, height, undefined, this.options.get('normalRangeColor')).append();
  1401. },
  1402. render: function () {
  1403. var options = this.options,
  1404. target = this.target,
  1405. canvasWidth = this.canvasWidth,
  1406. canvasHeight = this.canvasHeight,
  1407. vertices = this.vertices,
  1408. spotRadius = options.get('spotRadius'),
  1409. regionMap = this.regionMap,
  1410. rangex, rangey, yvallast,
  1411. canvasTop, canvasLeft,
  1412. vertex, path, paths, x, y, xnext, xpos, xposnext,
  1413. last, next, yvalcount, lineShapes, fillShapes, plen,
  1414. valueSpots, hlSpotsEnabled, color, xvalues, yvalues, i;
  1415. if (!line._super.render.call(this)) {
  1416. return;
  1417. }
  1418. this.scanValues();
  1419. this.processRangeOptions();
  1420. xvalues = this.xvalues;
  1421. yvalues = this.yvalues;
  1422. if (!this.yminmax.length || this.yvalues.length < 2) {
  1423. // empty or all null valuess
  1424. return;
  1425. }
  1426. canvasTop = canvasLeft = 0;
  1427. rangex = this.maxx - this.minx === 0 ? 1 : this.maxx - this.minx;
  1428. rangey = this.maxy - this.miny === 0 ? 1 : this.maxy - this.miny;
  1429. yvallast = this.yvalues.length - 1;
  1430. if (spotRadius && (canvasWidth < (spotRadius * 4) || canvasHeight < (spotRadius * 4))) {
  1431. spotRadius = 0;
  1432. }
  1433. if (spotRadius) {
  1434. // adjust the canvas size as required so that spots will fit
  1435. hlSpotsEnabled = options.get('highlightSpotColor') && !options.get('disableInteraction');
  1436. if (hlSpotsEnabled || options.get('minSpotColor') || (options.get('spotColor') && yvalues[yvallast] === this.miny)) {
  1437. canvasHeight -= Math.ceil(spotRadius);
  1438. }
  1439. if (hlSpotsEnabled || options.get('maxSpotColor') || (options.get('spotColor') && yvalues[yvallast] === this.maxy)) {
  1440. canvasHeight -= Math.ceil(spotRadius);
  1441. canvasTop += Math.ceil(spotRadius);
  1442. }
  1443. if (hlSpotsEnabled ||
  1444. ((options.get('minSpotColor') || options.get('maxSpotColor')) && (yvalues[0] === this.miny || yvalues[0] === this.maxy))) {
  1445. canvasLeft += Math.ceil(spotRadius);
  1446. canvasWidth -= Math.ceil(spotRadius);
  1447. }
  1448. if (hlSpotsEnabled || options.get('spotColor') ||
  1449. (options.get('minSpotColor') || options.get('maxSpotColor') &&
  1450. (yvalues[yvallast] === this.miny || yvalues[yvallast] === this.maxy))) {
  1451. canvasWidth -= Math.ceil(spotRadius);
  1452. }
  1453. }
  1454. canvasHeight--;
  1455. if (options.get('normalRangeMin') !== undefined && !options.get('drawNormalOnTop')) {
  1456. this.drawNormalRange(canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey);
  1457. }
  1458. path = [];
  1459. paths = [path];
  1460. last = next = null;
  1461. yvalcount = yvalues.length;
  1462. for (i = 0; i < yvalcount; i++) {
  1463. x = xvalues[i];
  1464. xnext = xvalues[i + 1];
  1465. y = yvalues[i];
  1466. xpos = canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex));
  1467. xposnext = i < yvalcount - 1 ? canvasLeft + Math.round((xnext - this.minx) * (canvasWidth / rangex)) : canvasWidth;
  1468. next = xpos + ((xposnext - xpos) / 2);
  1469. regionMap[i] = [last || 0, next, i];
  1470. last = next;
  1471. if (y === null) {
  1472. if (i) {
  1473. if (yvalues[i - 1] !== null) {
  1474. path = [];
  1475. paths.push(path);
  1476. }
  1477. vertices.push(null);
  1478. }
  1479. } else {
  1480. if (y < this.miny) {
  1481. y = this.miny;
  1482. }
  1483. if (y > this.maxy) {
  1484. y = this.maxy;
  1485. }
  1486. if (!path.length) {
  1487. // previous value was null
  1488. path.push([xpos, canvasTop + canvasHeight]);
  1489. }
  1490. vertex = [xpos, canvasTop + Math.round(canvasHeight - (canvasHeight * ((y - this.miny) / rangey)))];
  1491. path.push(vertex);
  1492. vertices.push(vertex);
  1493. }
  1494. }
  1495. lineShapes = [];
  1496. fillShapes = [];
  1497. plen = paths.length;
  1498. for (i = 0; i < plen; i++) {
  1499. path = paths[i];
  1500. if (path.length) {
  1501. if (options.get('fillColor')) {
  1502. path.push([path[path.length - 1][0], (canvasTop + canvasHeight)]);
  1503. fillShapes.push(path.slice(0));
  1504. path.pop();
  1505. }
  1506. // if there's only a single point in this path, then we want to display it
  1507. // as a vertical line which means we keep path[0] as is
  1508. if (path.length > 2) {
  1509. // else we want the first value
  1510. path[0] = [path[0][0], path[1][1]];
  1511. }
  1512. lineShapes.push(path);
  1513. }
  1514. }
  1515. // draw the fill first, then optionally the normal range, then the line on top of that
  1516. plen = fillShapes.length;
  1517. for (i = 0; i < plen; i++) {
  1518. target.drawShape(fillShapes[i],
  1519. options.get('fillColor'), options.get('fillColor')).append();
  1520. }
  1521. if (options.get('normalRangeMin') !== undefined && options.get('drawNormalOnTop')) {
  1522. this.drawNormalRange(canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey);
  1523. }
  1524. plen = lineShapes.length;
  1525. for (i = 0; i < plen; i++) {
  1526. target.drawShape(lineShapes[i], options.get('lineColor'), undefined,
  1527. options.get('lineWidth')).append();
  1528. }
  1529. if (spotRadius && options.get('valueSpots')) {
  1530. valueSpots = options.get('valueSpots');
  1531. if (valueSpots.get === undefined) {
  1532. valueSpots = new RangeMap(valueSpots);
  1533. }
  1534. for (i = 0; i < yvalcount; i++) {
  1535. color = valueSpots.get(yvalues[i]);
  1536. if (color) {
  1537. target.drawCircle(canvasLeft + Math.round((xvalues[i] - this.minx) * (canvasWidth / rangex)),
  1538. canvasTop + Math.round(canvasHeight - (canvasHeight * ((yvalues[i] - this.miny) / rangey))),
  1539. spotRadius, undefined,
  1540. color).append();
  1541. }
  1542. }
  1543. }
  1544. if (spotRadius && options.get('spotColor') && yvalues[yvallast] !== null) {
  1545. target.drawCircle(canvasLeft + Math.round((xvalues[xvalues.length - 1] - this.minx) * (canvasWidth / rangex)),
  1546. canvasTop + Math.round(canvasHeight - (canvasHeight * ((yvalues[yvallast] - this.miny) / rangey))),
  1547. spotRadius, undefined,
  1548. options.get('spotColor')).append();
  1549. }
  1550. if (this.maxy !== this.minyorg) {
  1551. if (spotRadius && options.get('minSpotColor')) {
  1552. x = xvalues[$.inArray(this.minyorg, yvalues)];
  1553. target.drawCircle(canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)),
  1554. canvasTop + Math.round(canvasHeight - (canvasHeight * ((this.minyorg - this.miny) / rangey))),
  1555. spotRadius, undefined,
  1556. options.get('minSpotColor')).append();
  1557. }
  1558. if (spotRadius && options.get('maxSpotColor')) {
  1559. x = xvalues[$.inArray(this.maxyorg, yvalues)];
  1560. target.drawCircle(canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)),
  1561. canvasTop + Math.round(canvasHeight - (canvasHeight * ((this.maxyorg - this.miny) / rangey))),
  1562. spotRadius, undefined,
  1563. options.get('maxSpotColor')).append();
  1564. }
  1565. }
  1566. this.lastShapeId = target.getLastShapeId();
  1567. this.canvasTop = canvasTop;
  1568. target.render();
  1569. }
  1570. });
  1571. /**
  1572. * Bar charts
  1573. */
  1574. $.fn.sparkline.bar = bar = createClass($.fn.sparkline._base, barHighlightMixin, {
  1575. type: 'bar',
  1576. init: function (el, values, options, width, height) {
  1577. var barWidth = parseInt(options.get('barWidth'), 10),
  1578. barSpacing = parseInt(options.get('barSpacing'), 10),
  1579. chartRangeMin = options.get('chartRangeMin'),
  1580. chartRangeMax = options.get('chartRangeMax'),
  1581. chartRangeClip = options.get('chartRangeClip'),
  1582. stackMin = Infinity,
  1583. stackMax = -Infinity,
  1584. isStackString, groupMin, groupMax, stackRanges,
  1585. numValues, i, vlen, range, zeroAxis, xaxisOffset, min, max, clipMin, clipMax,
  1586. stacked, vlist, j, slen, svals, val, yoffset, yMaxCalc, canvasHeightEf;
  1587. bar._super.init.call(this, el, values, options, width, height);
  1588. // scan values to determine whether to stack bars
  1589. for (i = 0, vlen = values.length; i < vlen; i++) {
  1590. val = values[i];
  1591. isStackString = typeof(val) === 'string' && val.indexOf(':') > -1;
  1592. if (isStackString || $.isArray(val)) {
  1593. stacked = true;
  1594. if (isStackString) {
  1595. val = values[i] = normalizeValues(val.split(':'));
  1596. }
  1597. val = remove(val, null); // min/max will treat null as zero
  1598. groupMin = Math.min.apply(Math, val);
  1599. groupMax = Math.max.apply(Math, val);
  1600. if (groupMin < stackMin) {
  1601. stackMin = groupMin;
  1602. }
  1603. if (groupMax > stackMax) {
  1604. stackMax = groupMax;
  1605. }
  1606. }
  1607. }
  1608. this.stacked = stacked;
  1609. this.regionShapes = {};
  1610. this.barWidth = barWidth;
  1611. this.barSpacing = barSpacing;
  1612. this.totalBarWidth = barWidth + barSpacing;
  1613. this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing);
  1614. this.initTarget();
  1615. if (chartRangeClip) {
  1616. clipMin = chartRangeMin === undefined ? -Infinity : chartRangeMin;
  1617. clipMax = chartRangeMax === undefined ? Infinity : chartRangeMax;
  1618. }
  1619. numValues = [];
  1620. stackRanges = stacked ? [] : numValues;
  1621. var stackTotals = [];
  1622. var stackRangesNeg = [];
  1623. for (i = 0, vlen = values.length; i < vlen; i++) {
  1624. if (stacked) {
  1625. vlist = values[i];
  1626. values[i] = svals = [];
  1627. stackTotals[i] = 0;
  1628. stackRanges[i] = stackRangesNeg[i] = 0;
  1629. for (j = 0, slen = vlist.length; j < slen; j++) {
  1630. val = svals[j] = chartRangeClip ? clipval(vlist[j], clipMin, clipMax) : vlist[j];
  1631. if (val !== null) {
  1632. if (val > 0) {
  1633. stackTotals[i] += val;
  1634. }
  1635. if (stackMin < 0 && stackMax > 0) {
  1636. if (val < 0) {
  1637. stackRangesNeg[i] += Math.abs(val);
  1638. } else {
  1639. stackRanges[i] += val;
  1640. }
  1641. } else {
  1642. stackRanges[i] += Math.abs(val - (val < 0 ? stackMax : stackMin));
  1643. }
  1644. numValues.push(val);
  1645. }
  1646. }
  1647. } else {
  1648. val = chartRangeClip ? clipval(values[i], clipMin, clipMax) : values[i];
  1649. val = values[i] = normalizeValue(val);
  1650. if (val !== null) {
  1651. numValues.push(val);
  1652. }
  1653. }
  1654. }
  1655. this.max = max = Math.max.apply(Math, numValues);
  1656. this.min = min = Math.min.apply(Math, numValues);
  1657. this.stackMax = stackMax = stacked ? Math.max.apply(Math, stackTotals) : max;
  1658. this.stackMin = stackMin = stacked ? Math.min.apply(Math, numValues) : min;
  1659. if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < min)) {
  1660. min = options.get('chartRangeMin');
  1661. }
  1662. if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > max)) {
  1663. max = options.get('chartRangeMax');
  1664. }
  1665. this.zeroAxis = zeroAxis = options.get('zeroAxis', true);
  1666. if (min <= 0 && max >= 0 && zeroAxis) {
  1667. xaxisOffset = 0;
  1668. } else if (zeroAxis == false) {
  1669. xaxisOffset = min;
  1670. } else if (min > 0) {
  1671. xaxisOffset = min;
  1672. } else {
  1673. xaxisOffset = max;
  1674. }
  1675. this.xaxisOffset = xaxisOffset;
  1676. range = stacked ? (Math.max.apply(Math, stackRanges) + Math.max.apply(Math, stackRangesNeg)) : max - min;
  1677. // as we plot zero/min values a single pixel line, we add a pixel to all other
  1678. // values - Reduce the effective canvas size to suit
  1679. this.canvasHeightEf = (zeroAxis && min < 0) ? this.canvasHeight - 2 : this.canvasHeight - 1;
  1680. if (min < xaxisOffset) {
  1681. yMaxCalc = (stacked && max >= 0) ? stackMax : max;
  1682. yoffset = (yMaxCalc - xaxisOffset) / range * this.canvasHeight;
  1683. if (yoffset !== Math.ceil(yoffset)) {
  1684. this.canvasHeightEf -= 2;
  1685. yoffset = Math.ceil(yoffset);
  1686. }
  1687. } else {
  1688. yoffset = this.canvasHeight;
  1689. }
  1690. this.yoffset = yoffset;
  1691. if ($.isArray(options.get('colorMap'))) {
  1692. this.colorMapByIndex = options.get('colorMap');
  1693. this.colorMapByValue = null;
  1694. } else {
  1695. this.colorMapByIndex = null;
  1696. this.colorMapByValue = options.get('colorMap');
  1697. if (this.colorMapByValue && this.colorMapByValue.get === undefined) {
  1698. this.colorMapByValue = new RangeMap(this.colorMapByValue);
  1699. }
  1700. }
  1701. this.range = range;
  1702. },
  1703. getRegion: function (el, x, y) {
  1704. var result = Math.floor(x / this.totalBarWidth);
  1705. return (result < 0 || result >= this.values.length) ? undefined : result;
  1706. },
  1707. getCurrentRegionFields: function () {
  1708. var currentRegion = this.currentRegion,
  1709. values = ensureArray(this.values[currentRegion]),
  1710. result = [],
  1711. value, i;
  1712. for (i = values.length; i--;) {
  1713. value = values[i];
  1714. result.push({
  1715. isNull: value === null,
  1716. value: value,
  1717. color: this.calcColor(i, value, currentRegion),
  1718. offset: currentRegion
  1719. });
  1720. }
  1721. return result;
  1722. },
  1723. calcColor: function (stacknum, value, valuenum) {
  1724. var colorMapByIndex = this.colorMapByIndex,
  1725. colorMapByValue = this.colorMapByValue,
  1726. options = this.options,
  1727. color, newColor;
  1728. if (this.stacked) {
  1729. color = options.get('stackedBarColor');
  1730. } else {
  1731. color = (value < 0) ? options.get('negBarColor') : options.get('barColor');
  1732. }
  1733. if (value === 0 && options.get('zeroColor') !== undefined) {
  1734. color = options.get('zeroColor');
  1735. }
  1736. if (colorMapByValue && (newColor = colorMapByValue.get(value))) {
  1737. color = newColor;
  1738. } else if (colorMapByIndex && colorMapByIndex.length > valuenum) {
  1739. color = colorMapByIndex[valuenum];
  1740. }
  1741. return $.isArray(color) ? color[stacknum % color.length] : color;
  1742. },
  1743. /**
  1744. * Render bar(s) for a region
  1745. */
  1746. renderRegion: function (valuenum, highlight) {
  1747. var vals = this.values[valuenum],
  1748. options = this.options,
  1749. xaxisOffset = this.xaxisOffset,
  1750. result = [],
  1751. range = this.range,
  1752. stacked = this.stacked,
  1753. target = this.target,
  1754. x = valuenum * this.totalBarWidth,
  1755. canvasHeightEf = this.canvasHeightEf,
  1756. yoffset = this.yoffset,
  1757. y, height, color, isNull, yoffsetNeg, i, valcount, val, minPlotted, allMin;
  1758. vals = $.isArray(vals) ? vals : [vals];
  1759. valcount = vals.length;
  1760. val = vals[0];
  1761. isNull = all(null, vals);
  1762. allMin = all(xaxisOffset, vals, true);
  1763. if (isNull) {
  1764. if (options.get('nullColor')) {
  1765. color = highlight ? options.get('nullColor') : this.calcHighlightColor(options.get('nullColor'), options);
  1766. y = (yoffset > 0) ? yoffset - 1 : yoffset;
  1767. return target.drawRect(x, y, this.barWidth - 1, 0, color, color);
  1768. } else {
  1769. return undefined;
  1770. }
  1771. }
  1772. yoffsetNeg = yoffset;
  1773. for (i = 0; i < valcount; i++) {
  1774. val = vals[i];
  1775. if (stacked && val === xaxisOffset) {
  1776. if (!allMin || minPlotted) {
  1777. continue;
  1778. }
  1779. minPlotted = true;
  1780. }
  1781. if (range > 0) {
  1782. height = Math.floor(canvasHeightEf * ((Math.abs(val - xaxisOffset) / range))) + 1;
  1783. } else {
  1784. height = 1;
  1785. }
  1786. if (val < xaxisOffset || (val === xaxisOffset && yoffset === 0)) {
  1787. y = yoffsetNeg;
  1788. yoffsetNeg += height;
  1789. } else {
  1790. y = yoffset - height;
  1791. yoffset -= height;
  1792. }
  1793. color = this.calcColor(i, val, valuenum);
  1794. if (highlight) {
  1795. color = this.calcHighlightColor(color, options);
  1796. }
  1797. result.push(target.drawRect(x, y, this.barWidth - 1, height - 1, color, color));
  1798. }
  1799. if (result.length === 1) {
  1800. return result[0];
  1801. }
  1802. return result;
  1803. }
  1804. });
  1805. /**
  1806. * Tristate charts
  1807. */
  1808. $.fn.sparkline.tristate = tristate = createClass($.fn.sparkline._base, barHighlightMixin, {
  1809. type: 'tristate',
  1810. init: function (el, values, options, width, height) {
  1811. var barWidth = parseInt(options.get('barWidth'), 10),
  1812. barSpacing = parseInt(options.get('barSpacing'), 10);
  1813. tristate._super.init.call(this, el, values, options, width, height);
  1814. this.regionShapes = {};
  1815. this.barWidth = barWidth;
  1816. this.barSpacing = barSpacing;
  1817. this.totalBarWidth = barWidth + barSpacing;
  1818. this.values = $.map(values, Number);
  1819. this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing);
  1820. if ($.isArray(options.get('colorMap'))) {
  1821. this.colorMapByIndex = options.get('colorMap');
  1822. this.colorMapByValue = null;
  1823. } else {
  1824. this.colorMapByIndex = null;
  1825. this.colorMapByValue = options.get('colorMap');
  1826. if (this.colorMapByValue && this.colorMapByValue.get === undefined) {
  1827. this.colorMapByValue = new RangeMap(this.colorMapByValue);
  1828. }
  1829. }
  1830. this.initTarget();
  1831. },
  1832. getRegion: function (el, x, y) {
  1833. return Math.floor(x / this.totalBarWidth);
  1834. },
  1835. getCurrentRegionFields: function () {
  1836. var currentRegion = this.currentRegion;
  1837. return {
  1838. isNull: this.values[currentRegion] === undefined,
  1839. value: this.values[currentRegion],
  1840. color: this.calcColor(this.values[currentRegion], currentRegion),
  1841. offset: currentRegion
  1842. };
  1843. },
  1844. calcColor: function (value, valuenum) {
  1845. var values = this.values,
  1846. options = this.options,
  1847. colorMapByIndex = this.colorMapByIndex,
  1848. colorMapByValue = this.colorMapByValue,
  1849. color, newColor;
  1850. if (colorMapByValue && (newColor = colorMapByValue.get(value))) {
  1851. color = newColor;
  1852. } else if (colorMapByIndex && colorMapByIndex.length > valuenum) {
  1853. color = colorMapByIndex[valuenum];
  1854. } else if (values[valuenum] < 0) {
  1855. color = options.get('negBarColor');
  1856. } else if (values[valuenum] > 0) {
  1857. color = options.get('posBarColor');
  1858. } else {
  1859. color = options.get('zeroBarColor');
  1860. }
  1861. return color;
  1862. },
  1863. renderRegion: function (valuenum, highlight) {
  1864. var values = this.values,
  1865. options = this.options,
  1866. target = this.target,
  1867. canvasHeight, height, halfHeight,
  1868. x, y, color;
  1869. canvasHeight = target.pixelHeight;
  1870. halfHeight = Math.round(canvasHeight / 2);
  1871. x = valuenum * this.totalBarWidth;
  1872. if (values[valuenum] < 0) {
  1873. y = halfHeight;
  1874. height = halfHeight - 1;
  1875. } else if (values[valuenum] > 0) {
  1876. y = 0;
  1877. height = halfHeight - 1;
  1878. } else {
  1879. y = halfHeight - 1;
  1880. height = 2;
  1881. }
  1882. color = this.calcColor(values[valuenum], valuenum);
  1883. if (color === null) {
  1884. return;
  1885. }
  1886. if (highlight) {
  1887. color = this.calcHighlightColor(color, options);
  1888. }
  1889. return target.drawRect(x, y, this.barWidth - 1, height - 1, color, color);
  1890. }
  1891. });
  1892. /**
  1893. * Discrete charts
  1894. */
  1895. $.fn.sparkline.discrete = discrete = createClass($.fn.sparkline._base, barHighlightMixin, {
  1896. type: 'discrete',
  1897. init: function (el, values, options, width, height) {
  1898. discrete._super.init.call(this, el, values, options, width, height);
  1899. this.regionShapes = {};
  1900. this.values = values = $.map(values, Number);
  1901. this.min = Math.min.apply(Math, values);
  1902. this.max = Math.max.apply(Math, values);
  1903. this.range = this.max - this.min;
  1904. this.width = width = options.get('width') === 'auto' ? values.length * 2 : this.width;
  1905. this.interval = Math.floor(width / values.length);
  1906. this.itemWidth = width / values.length;
  1907. if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.min)) {
  1908. this.min = options.get('chartRangeMin');
  1909. }
  1910. if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.max)) {
  1911. this.max = options.get('chartRangeMax');
  1912. }
  1913. this.initTarget();
  1914. if (this.target) {
  1915. this.lineHeight = options.get('lineHeight') === 'auto' ? Math.round(this.canvasHeight * 0.3) : options.get('lineHeight');
  1916. }
  1917. },
  1918. getRegion: function (el, x, y) {
  1919. return Math.floor(x / this.itemWidth);
  1920. },
  1921. getCurrentRegionFields: function () {
  1922. var currentRegion = this.currentRegion;
  1923. return {
  1924. isNull: this.values[currentRegion] === undefined,
  1925. value: this.values[currentRegion],
  1926. offset: currentRegion
  1927. };
  1928. },
  1929. renderRegion: function (valuenum, highlight) {
  1930. var values = this.values,
  1931. options = this.options,
  1932. min = this.min,
  1933. max = this.max,
  1934. range = this.range,
  1935. interval = this.interval,
  1936. target = this.target,
  1937. canvasHeight = this.canvasHeight,
  1938. lineHeight = this.lineHeight,
  1939. pheight = canvasHeight - lineHeight,
  1940. ytop, val, color, x;
  1941. val = clipval(values[valuenum], min, max);
  1942. x = valuenum * interval;
  1943. ytop = Math.round(pheight - pheight * ((val - min) / range));
  1944. color = (options.get('thresholdColor') && val < options.get('thresholdValue')) ? options.get('thresholdColor') : options.get('lineColor');
  1945. if (highlight) {
  1946. color = this.calcHighlightColor(color, options);
  1947. }
  1948. return target.drawLine(x, ytop, x, ytop + lineHeight, color);
  1949. }
  1950. });
  1951. /**
  1952. * Bullet charts
  1953. */
  1954. $.fn.sparkline.bullet = bullet = createClass($.fn.sparkline._base, {
  1955. type: 'bullet',
  1956. init: function (el, values, options, width, height) {
  1957. var min, max, vals;
  1958. bullet._super.init.call(this, el, values, options, width, height);
  1959. // values: target, performance, range1, range2, range3
  1960. this.values = values = normalizeValues(values);
  1961. // target or performance could be null
  1962. vals = values.slice();
  1963. vals[0] = vals[0] === null ? vals[2] : vals[0];
  1964. vals[1] = values[1] === null ? vals[2] : vals[1];
  1965. min = Math.min.apply(Math, values);
  1966. max = Math.max.apply(Math, values);
  1967. if (options.get('base') === undefined) {
  1968. min = min < 0 ? min : 0;
  1969. } else {
  1970. min = options.get('base');
  1971. }
  1972. this.min = min;
  1973. this.max = max;
  1974. this.range = max - min;
  1975. this.shapes = {};
  1976. this.valueShapes = {};
  1977. this.regiondata = {};
  1978. this.width = width = options.get('width') === 'auto' ? '4.0em' : width;
  1979. this.target = this.$el.simpledraw(width, height, options.get('composite'));
  1980. if (!values.length) {
  1981. this.disabled = true;
  1982. }
  1983. this.initTarget();
  1984. },
  1985. getRegion: function (el, x, y) {
  1986. var shapeid = this.target.getShapeAt(el, x, y);
  1987. return (shapeid !== undefined && this.shapes[shapeid] !== undefined) ? this.shapes[shapeid] : undefined;
  1988. },
  1989. getCurrentRegionFields: function () {
  1990. var currentRegion = this.currentRegion;
  1991. return {
  1992. fieldkey: currentRegion.substr(0, 1),
  1993. value: this.values[currentRegion.substr(1)],
  1994. region: currentRegion
  1995. };
  1996. },
  1997. changeHighlight: function (highlight) {
  1998. var currentRegion = this.currentRegion,
  1999. shapeid = this.valueShapes[currentRegion],
  2000. shape;
  2001. delete this.shapes[shapeid];
  2002. switch (currentRegion.substr(0, 1)) {
  2003. case 'r':
  2004. shape = this.renderRange(currentRegion.substr(1), highlight);
  2005. break;
  2006. case 'p':
  2007. shape = this.renderPerformance(highlight);
  2008. break;
  2009. case 't':
  2010. shape = this.renderTarget(highlight);
  2011. break;
  2012. }
  2013. this.valueShapes[currentRegion] = shape.id;
  2014. this.shapes[shape.id] = currentRegion;
  2015. this.target.replaceWithShape(shapeid, shape);
  2016. },
  2017. renderRange: function (rn, highlight) {
  2018. var rangeval = this.values[rn],
  2019. rangewidth = Math.round(this.canvasWidth * ((rangeval - this.min) / this.range)),
  2020. color = this.options.get('rangeColors')[rn - 2];
  2021. if (highlight) {
  2022. color = this.calcHighlightColor(color, this.options);
  2023. }
  2024. return this.target.drawRect(0, 0, rangewidth - 1, this.canvasHeight - 1, color, color);
  2025. },
  2026. renderPerformance: function (highlight) {
  2027. var perfval = this.values[1],
  2028. perfwidth = Math.round(this.canvasWidth * ((perfval - this.min) / this.range)),
  2029. color = this.options.get('performanceColor');
  2030. if (highlight) {
  2031. color = this.calcHighlightColor(color, this.options);
  2032. }
  2033. return this.target.drawRect(0, Math.round(this.canvasHeight * 0.3), perfwidth - 1,
  2034. Math.round(this.canvasHeight * 0.4) - 1, color, color);
  2035. },
  2036. renderTarget: function (highlight) {
  2037. var targetval = this.values[0],
  2038. x = Math.round(this.canvasWidth * ((targetval - this.min) / this.range) - (this.options.get('targetWidth') / 2)),
  2039. targettop = Math.round(this.canvasHeight * 0.10),
  2040. targetheight = this.canvasHeight - (targettop * 2),
  2041. color = this.options.get('targetColor');
  2042. if (highlight) {
  2043. color = this.calcHighlightColor(color, this.options);
  2044. }
  2045. return this.target.drawRect(x, targettop, this.options.get('targetWidth') - 1, targetheight - 1, color, color);
  2046. },
  2047. render: function () {
  2048. var vlen = this.values.length,
  2049. target = this.target,
  2050. i, shape;
  2051. if (!bullet._super.render.call(this)) {
  2052. return;
  2053. }
  2054. for (i = 2; i < vlen; i++) {
  2055. shape = this.renderRange(i).append();
  2056. this.shapes[shape.id] = 'r' + i;
  2057. this.valueShapes['r' + i] = shape.id;
  2058. }
  2059. if (this.values[1] !== null) {
  2060. shape = this.renderPerformance().append();
  2061. this.shapes[shape.id] = 'p1';
  2062. this.valueShapes.p1 = shape.id;
  2063. }
  2064. if (this.values[0] !== null) {
  2065. shape = this.renderTarget().append();
  2066. this.shapes[shape.id] = 't0';
  2067. this.valueShapes.t0 = shape.id;
  2068. }
  2069. target.render();
  2070. }
  2071. });
  2072. /**
  2073. * Pie charts
  2074. */
  2075. $.fn.sparkline.pie = pie = createClass($.fn.sparkline._base, {
  2076. type: 'pie',
  2077. init: function (el, values, options, width, height) {
  2078. var total = 0, i;
  2079. pie._super.init.call(this, el, values, options, width, height);
  2080. this.shapes = {}; // map shape ids to value offsets
  2081. this.valueShapes = {}; // maps value offsets to shape ids
  2082. this.values = values = $.map(values, Number);
  2083. if (options.get('width') === 'auto') {
  2084. this.width = this.height;
  2085. }
  2086. if (values.length > 0) {
  2087. for (i = values.length; i--;) {
  2088. total += values[i];
  2089. }
  2090. }
  2091. this.total = total;
  2092. this.initTarget();
  2093. this.radius = Math.floor(Math.min(this.canvasWidth, this.canvasHeight) / 2);
  2094. },
  2095. getRegion: function (el, x, y) {
  2096. var shapeid = this.target.getShapeAt(el, x, y);
  2097. return (shapeid !== undefined && this.shapes[shapeid] !== undefined) ? this.shapes[shapeid] : undefined;
  2098. },
  2099. getCurrentRegionFields: function () {
  2100. var currentRegion = this.currentRegion;
  2101. return {
  2102. isNull: this.values[currentRegion] === undefined,
  2103. value: this.values[currentRegion],
  2104. percent: this.values[currentRegion] / this.total * 100,
  2105. color: this.options.get('sliceColors')[currentRegion % this.options.get('sliceColors').length],
  2106. offset: currentRegion
  2107. };
  2108. },
  2109. changeHighlight: function (highlight) {
  2110. var currentRegion = this.currentRegion,
  2111. newslice = this.renderSlice(currentRegion, highlight),
  2112. shapeid = this.valueShapes[currentRegion];
  2113. delete this.shapes[shapeid];
  2114. this.target.replaceWithShape(shapeid, newslice);
  2115. this.valueShapes[currentRegion] = newslice.id;
  2116. this.shapes[newslice.id] = currentRegion;
  2117. },
  2118. renderSlice: function (valuenum, highlight) {
  2119. var target = this.target,
  2120. options = this.options,
  2121. radius = this.radius,
  2122. borderWidth = options.get('borderWidth'),
  2123. offset = options.get('offset'),
  2124. circle = 2 * Math.PI,
  2125. values = this.values,
  2126. total = this.total,
  2127. next = offset ? (2*Math.PI)*(offset/360) : 0,
  2128. start, end, i, vlen, color;
  2129. vlen = values.length;
  2130. for (i = 0; i < vlen; i++) {
  2131. start = next;
  2132. end = next;
  2133. if (total > 0) { // avoid divide by zero
  2134. end = next + (circle * (values[i] / total));
  2135. }
  2136. if (valuenum === i) {
  2137. color = options.get('sliceColors')[i % options.get('sliceColors').length];
  2138. if (highlight) {
  2139. color = this.calcHighlightColor(color, options);
  2140. }
  2141. return target.drawPieSlice(radius, radius, radius - borderWidth, start, end, undefined, color);
  2142. }
  2143. next = end;
  2144. }
  2145. },
  2146. render: function () {
  2147. var target = this.target,
  2148. values = this.values,
  2149. options = this.options,
  2150. radius = this.radius,
  2151. borderWidth = options.get('borderWidth'),
  2152. shape, i;
  2153. if (!pie._super.render.call(this)) {
  2154. return;
  2155. }
  2156. if (borderWidth) {
  2157. target.drawCircle(radius, radius, Math.floor(radius - (borderWidth / 2)),
  2158. options.get('borderColor'), undefined, borderWidth).append();
  2159. }
  2160. for (i = values.length; i--;) {
  2161. if (values[i]) { // don't render zero values
  2162. shape = this.renderSlice(i).append();
  2163. this.valueShapes[i] = shape.id; // store just the shapeid
  2164. this.shapes[shape.id] = i;
  2165. }
  2166. }
  2167. target.render();
  2168. }
  2169. });
  2170. /**
  2171. * Box plots
  2172. */
  2173. $.fn.sparkline.box = box = createClass($.fn.sparkline._base, {
  2174. type: 'box',
  2175. init: function (el, values, options, width, height) {
  2176. box._super.init.call(this, el, values, options, width, height);
  2177. this.values = $.map(values, Number);
  2178. this.width = options.get('width') === 'auto' ? '4.0em' : width;
  2179. this.initTarget();
  2180. if (!this.values.length) {
  2181. this.disabled = 1;
  2182. }
  2183. },
  2184. /**
  2185. * Simulate a single region
  2186. */
  2187. getRegion: function () {
  2188. return 1;
  2189. },
  2190. getCurrentRegionFields: function () {
  2191. var result = [
  2192. { field: 'lq', value: this.quartiles[0] },
  2193. { field: 'med', value: this.quartiles[1] },
  2194. { field: 'uq', value: this.quartiles[2] }
  2195. ];
  2196. if (this.loutlier !== undefined) {
  2197. result.push({ field: 'lo', value: this.loutlier});
  2198. }
  2199. if (this.routlier !== undefined) {
  2200. result.push({ field: 'ro', value: this.routlier});
  2201. }
  2202. if (this.lwhisker !== undefined) {
  2203. result.push({ field: 'lw', value: this.lwhisker});
  2204. }
  2205. if (this.rwhisker !== undefined) {
  2206. result.push({ field: 'rw', value: this.rwhisker});
  2207. }
  2208. return result;
  2209. },
  2210. render: function () {
  2211. var target = this.target,
  2212. values = this.values,
  2213. vlen = values.length,
  2214. options = this.options,
  2215. canvasWidth = this.canvasWidth,
  2216. canvasHeight = this.canvasHeight,
  2217. minValue = options.get('chartRangeMin') === undefined ? Math.min.apply(Math, values) : options.get('chartRangeMin'),
  2218. maxValue = options.get('chartRangeMax') === undefined ? Math.max.apply(Math, values) : options.get('chartRangeMax'),
  2219. canvasLeft = 0,
  2220. lwhisker, loutlier, iqr, q1, q2, q3, rwhisker, routlier, i,
  2221. size, unitSize;
  2222. if (!box._super.render.call(this)) {
  2223. return;
  2224. }
  2225. if (options.get('raw')) {
  2226. if (options.get('showOutliers') && values.length > 5) {
  2227. loutlier = values[0];
  2228. lwhisker = values[1];
  2229. q1 = values[2];
  2230. q2 = values[3];
  2231. q3 = values[4];
  2232. rwhisker = values[5];
  2233. routlier = values[6];
  2234. } else {
  2235. lwhisker = values[0];
  2236. q1 = values[1];
  2237. q2 = values[2];
  2238. q3 = values[3];
  2239. rwhisker = values[4];
  2240. }
  2241. } else {
  2242. values.sort(function (a, b) { return a - b; });
  2243. q1 = quartile(values, 1);
  2244. q2 = quartile(values, 2);
  2245. q3 = quartile(values, 3);
  2246. iqr = q3 - q1;
  2247. if (options.get('showOutliers')) {
  2248. lwhisker = rwhisker = undefined;
  2249. for (i = 0; i < vlen; i++) {
  2250. if (lwhisker === undefined && values[i] > q1 - (iqr * options.get('outlierIQR'))) {
  2251. lwhisker = values[i];
  2252. }
  2253. if (values[i] < q3 + (iqr * options.get('outlierIQR'))) {
  2254. rwhisker = values[i];
  2255. }
  2256. }
  2257. loutlier = values[0];
  2258. routlier = values[vlen - 1];
  2259. } else {
  2260. lwhisker = values[0];
  2261. rwhisker = values[vlen - 1];
  2262. }
  2263. }
  2264. this.quartiles = [q1, q2, q3];
  2265. this.lwhisker = lwhisker;
  2266. this.rwhisker = rwhisker;
  2267. this.loutlier = loutlier;
  2268. this.routlier = routlier;
  2269. unitSize = canvasWidth / (maxValue - minValue + 1);
  2270. if (options.get('showOutliers')) {
  2271. canvasLeft = Math.ceil(options.get('spotRadius'));
  2272. canvasWidth -= 2 * Math.ceil(options.get('spotRadius'));
  2273. unitSize = canvasWidth / (maxValue - minValue + 1);
  2274. if (loutlier < lwhisker) {
  2275. target.drawCircle((loutlier - minValue) * unitSize + canvasLeft,
  2276. canvasHeight / 2,
  2277. options.get('spotRadius'),
  2278. options.get('outlierLineColor'),
  2279. options.get('outlierFillColor')).append();
  2280. }
  2281. if (routlier > rwhisker) {
  2282. target.drawCircle((routlier - minValue) * unitSize + canvasLeft,
  2283. canvasHeight / 2,
  2284. options.get('spotRadius'),
  2285. options.get('outlierLineColor'),
  2286. options.get('outlierFillColor')).append();
  2287. }
  2288. }
  2289. // box
  2290. target.drawRect(
  2291. Math.round((q1 - minValue) * unitSize + canvasLeft),
  2292. Math.round(canvasHeight * 0.1),
  2293. Math.round((q3 - q1) * unitSize),
  2294. Math.round(canvasHeight * 0.8),
  2295. options.get('boxLineColor'),
  2296. options.get('boxFillColor')).append();
  2297. // left whisker
  2298. target.drawLine(
  2299. Math.round((lwhisker - minValue) * unitSize + canvasLeft),
  2300. Math.round(canvasHeight / 2),
  2301. Math.round((q1 - minValue) * unitSize + canvasLeft),
  2302. Math.round(canvasHeight / 2),
  2303. options.get('lineColor')).append();
  2304. target.drawLine(
  2305. Math.round((lwhisker - minValue) * unitSize + canvasLeft),
  2306. Math.round(canvasHeight / 4),
  2307. Math.round((lwhisker - minValue) * unitSize + canvasLeft),
  2308. Math.round(canvasHeight - canvasHeight / 4),
  2309. options.get('whiskerColor')).append();
  2310. // right whisker
  2311. target.drawLine(Math.round((rwhisker - minValue) * unitSize + canvasLeft),
  2312. Math.round(canvasHeight / 2),
  2313. Math.round((q3 - minValue) * unitSize + canvasLeft),
  2314. Math.round(canvasHeight / 2),
  2315. options.get('lineColor')).append();
  2316. target.drawLine(
  2317. Math.round((rwhisker - minValue) * unitSize + canvasLeft),
  2318. Math.round(canvasHeight / 4),
  2319. Math.round((rwhisker - minValue) * unitSize + canvasLeft),
  2320. Math.round(canvasHeight - canvasHeight / 4),
  2321. options.get('whiskerColor')).append();
  2322. // median line
  2323. target.drawLine(
  2324. Math.round((q2 - minValue) * unitSize + canvasLeft),
  2325. Math.round(canvasHeight * 0.1),
  2326. Math.round((q2 - minValue) * unitSize + canvasLeft),
  2327. Math.round(canvasHeight * 0.9),
  2328. options.get('medianColor')).append();
  2329. if (options.get('target')) {
  2330. size = Math.ceil(options.get('spotRadius'));
  2331. target.drawLine(
  2332. Math.round((options.get('target') - minValue) * unitSize + canvasLeft),
  2333. Math.round((canvasHeight / 2) - size),
  2334. Math.round((options.get('target') - minValue) * unitSize + canvasLeft),
  2335. Math.round((canvasHeight / 2) + size),
  2336. options.get('targetColor')).append();
  2337. target.drawLine(
  2338. Math.round((options.get('target') - minValue) * unitSize + canvasLeft - size),
  2339. Math.round(canvasHeight / 2),
  2340. Math.round((options.get('target') - minValue) * unitSize + canvasLeft + size),
  2341. Math.round(canvasHeight / 2),
  2342. options.get('targetColor')).append();
  2343. }
  2344. target.render();
  2345. }
  2346. });
  2347. // Setup a very simple "virtual canvas" to make drawing the few shapes we need easier
  2348. // This is accessible as $(foo).simpledraw()
  2349. VShape = createClass({
  2350. init: function (target, id, type, args) {
  2351. this.target = target;
  2352. this.id = id;
  2353. this.type = type;
  2354. this.args = args;
  2355. },
  2356. append: function () {
  2357. this.target.appendShape(this);
  2358. return this;
  2359. }
  2360. });
  2361. VCanvas_base = createClass({
  2362. _pxregex: /(\d+)(px)?\s*$/i,
  2363. init: function (width, height, target) {
  2364. if (!width) {
  2365. return;
  2366. }
  2367. this.width = width;
  2368. this.height = height;
  2369. this.target = target;
  2370. this.lastShapeId = null;
  2371. if (target[0]) {
  2372. target = target[0];
  2373. }
  2374. $.data(target, '_jqs_vcanvas', this);
  2375. },
  2376. drawLine: function (x1, y1, x2, y2, lineColor, lineWidth) {
  2377. return this.drawShape([[x1, y1], [x2, y2]], lineColor, lineWidth);
  2378. },
  2379. drawShape: function (path, lineColor, fillColor, lineWidth) {
  2380. return this._genShape('Shape', [path, lineColor, fillColor, lineWidth]);
  2381. },
  2382. drawCircle: function (x, y, radius, lineColor, fillColor, lineWidth) {
  2383. return this._genShape('Circle', [x, y, radius, lineColor, fillColor, lineWidth]);
  2384. },
  2385. drawPieSlice: function (x, y, radius, startAngle, endAngle, lineColor, fillColor) {
  2386. return this._genShape('PieSlice', [x, y, radius, startAngle, endAngle, lineColor, fillColor]);
  2387. },
  2388. drawRect: function (x, y, width, height, lineColor, fillColor) {
  2389. return this._genShape('Rect', [x, y, width, height, lineColor, fillColor]);
  2390. },
  2391. getElement: function () {
  2392. return this.canvas;
  2393. },
  2394. /**
  2395. * Return the most recently inserted shape id
  2396. */
  2397. getLastShapeId: function () {
  2398. return this.lastShapeId;
  2399. },
  2400. /**
  2401. * Clear and reset the canvas
  2402. */
  2403. reset: function () {
  2404. alert('reset not implemented');
  2405. },
  2406. _insert: function (el, target) {
  2407. $(target).html(el);
  2408. },
  2409. /**
  2410. * Calculate the pixel dimensions of the canvas
  2411. */
  2412. _calculatePixelDims: function (width, height, canvas) {
  2413. // XXX This should probably be a configurable option
  2414. var match;
  2415. match = this._pxregex.exec(height);
  2416. if (match) {
  2417. this.pixelHeight = match[1];
  2418. } else {
  2419. this.pixelHeight = $(canvas).height();
  2420. }
  2421. match = this._pxregex.exec(width);
  2422. if (match) {
  2423. this.pixelWidth = match[1];
  2424. } else {
  2425. this.pixelWidth = $(canvas).width();
  2426. }
  2427. },
  2428. /**
  2429. * Generate a shape object and id for later rendering
  2430. */
  2431. _genShape: function (shapetype, shapeargs) {
  2432. var id = shapeCount++;
  2433. shapeargs.unshift(id);
  2434. return new VShape(this, id, shapetype, shapeargs);
  2435. },
  2436. /**
  2437. * Add a shape to the end of the render queue
  2438. */
  2439. appendShape: function (shape) {
  2440. alert('appendShape not implemented');
  2441. },
  2442. /**
  2443. * Replace one shape with another
  2444. */
  2445. replaceWithShape: function (shapeid, shape) {
  2446. alert('replaceWithShape not implemented');
  2447. },
  2448. /**
  2449. * Insert one shape after another in the render queue
  2450. */
  2451. insertAfterShape: function (shapeid, shape) {
  2452. alert('insertAfterShape not implemented');
  2453. },
  2454. /**
  2455. * Remove a shape from the queue
  2456. */
  2457. removeShapeId: function (shapeid) {
  2458. alert('removeShapeId not implemented');
  2459. },
  2460. /**
  2461. * Find a shape at the specified x/y co-ordinates
  2462. */
  2463. getShapeAt: function (el, x, y) {
  2464. alert('getShapeAt not implemented');
  2465. },
  2466. /**
  2467. * Render all queued shapes onto the canvas
  2468. */
  2469. render: function () {
  2470. alert('render not implemented');
  2471. }
  2472. });
  2473. VCanvas_canvas = createClass(VCanvas_base, {
  2474. init: function (width, height, target, interact) {
  2475. VCanvas_canvas._super.init.call(this, width, height, target);
  2476. this.canvas = document.createElement('canvas');
  2477. if (target[0]) {
  2478. target = target[0];
  2479. }
  2480. $.data(target, '_jqs_vcanvas', this);
  2481. $(this.canvas).css({ display: 'inline-block', width: width, height: height, verticalAlign: 'top',marginBottom: '-2px',marginLeft: '-2px' });
  2482. this._insert(this.canvas, target);
  2483. this._calculatePixelDims(width, height, this.canvas);
  2484. this.canvas.width = this.pixelWidth;
  2485. this.canvas.height = this.pixelHeight;
  2486. this.interact = interact;
  2487. this.shapes = {};
  2488. this.shapeseq = [];
  2489. this.currentTargetShapeId = undefined;
  2490. $(this.canvas).css({width: this.pixelWidth, height: this.pixelHeight});
  2491. },
  2492. _getContext: function (lineColor, fillColor, lineWidth) {
  2493. var context = this.canvas.getContext('2d');
  2494. if (lineColor !== undefined) {
  2495. context.strokeStyle = lineColor;
  2496. }
  2497. context.lineWidth = lineWidth === undefined ? 1 : lineWidth;
  2498. if (fillColor !== undefined) {
  2499. context.fillStyle = fillColor;
  2500. }
  2501. return context;
  2502. },
  2503. reset: function () {
  2504. var context = this._getContext();
  2505. context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
  2506. this.shapes = {};
  2507. this.shapeseq = [];
  2508. this.currentTargetShapeId = undefined;
  2509. },
  2510. _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) {
  2511. var context = this._getContext(lineColor, fillColor, lineWidth),
  2512. i, plen;
  2513. context.beginPath();
  2514. context.moveTo(path[0][0] + 0.5, path[0][1] + 0.5);
  2515. for (i = 1, plen = path.length; i < plen; i++) {
  2516. context.lineTo(path[i][0] + 0.5, path[i][1] + 0.5); // the 0.5 offset gives us crisp pixel-width lines
  2517. }
  2518. if (lineColor !== undefined) {
  2519. context.stroke();
  2520. }
  2521. if (fillColor !== undefined) {
  2522. context.fill();
  2523. }
  2524. if (this.targetX !== undefined && this.targetY !== undefined &&
  2525. context.isPointInPath(this.targetX, this.targetY)) {
  2526. this.currentTargetShapeId = shapeid;
  2527. }
  2528. },
  2529. _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) {
  2530. var context = this._getContext(lineColor, fillColor, lineWidth);
  2531. context.beginPath();
  2532. context.arc(x, y, radius, 0, 2 * Math.PI, false);
  2533. if (this.targetX !== undefined && this.targetY !== undefined &&
  2534. context.isPointInPath(this.targetX, this.targetY)) {
  2535. this.currentTargetShapeId = shapeid;
  2536. }
  2537. if (lineColor !== undefined) {
  2538. context.stroke();
  2539. }
  2540. if (fillColor !== undefined) {
  2541. context.fill();
  2542. }
  2543. },
  2544. _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) {
  2545. var context = this._getContext(lineColor, fillColor);
  2546. context.beginPath();
  2547. context.moveTo(x, y);
  2548. context.arc(x, y, radius, startAngle, endAngle, false);
  2549. context.lineTo(x, y);
  2550. context.closePath();
  2551. if (lineColor !== undefined) {
  2552. context.stroke();
  2553. }
  2554. if (fillColor) {
  2555. context.fill();
  2556. }
  2557. if (this.targetX !== undefined && this.targetY !== undefined &&
  2558. context.isPointInPath(this.targetX, this.targetY)) {
  2559. this.currentTargetShapeId = shapeid;
  2560. }
  2561. },
  2562. _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) {
  2563. return this._drawShape(shapeid, [[x, y], [x + width, y], [x + width, y + height], [x, y + height], [x, y]], lineColor, fillColor);
  2564. },
  2565. appendShape: function (shape) {
  2566. this.shapes[shape.id] = shape;
  2567. this.shapeseq.push(shape.id);
  2568. this.lastShapeId = shape.id;
  2569. return shape.id;
  2570. },
  2571. replaceWithShape: function (shapeid, shape) {
  2572. var shapeseq = this.shapeseq,
  2573. i;
  2574. this.shapes[shape.id] = shape;
  2575. for (i = shapeseq.length; i--;) {
  2576. if (shapeseq[i] == shapeid) {
  2577. shapeseq[i] = shape.id;
  2578. }
  2579. }
  2580. delete this.shapes[shapeid];
  2581. },
  2582. replaceWithShapes: function (shapeids, shapes) {
  2583. var shapeseq = this.shapeseq,
  2584. shapemap = {},
  2585. sid, i, first;
  2586. for (i = shapeids.length; i--;) {
  2587. shapemap[shapeids[i]] = true;
  2588. }
  2589. for (i = shapeseq.length; i--;) {
  2590. sid = shapeseq[i];
  2591. if (shapemap[sid]) {
  2592. shapeseq.splice(i, 1);
  2593. delete this.shapes[sid];
  2594. first = i;
  2595. }
  2596. }
  2597. for (i = shapes.length; i--;) {
  2598. shapeseq.splice(first, 0, shapes[i].id);
  2599. this.shapes[shapes[i].id] = shapes[i];
  2600. }
  2601. },
  2602. insertAfterShape: function (shapeid, shape) {
  2603. var shapeseq = this.shapeseq,
  2604. i;
  2605. for (i = shapeseq.length; i--;) {
  2606. if (shapeseq[i] === shapeid) {
  2607. shapeseq.splice(i + 1, 0, shape.id);
  2608. this.shapes[shape.id] = shape;
  2609. return;
  2610. }
  2611. }
  2612. },
  2613. removeShapeId: function (shapeid) {
  2614. var shapeseq = this.shapeseq,
  2615. i;
  2616. for (i = shapeseq.length; i--;) {
  2617. if (shapeseq[i] === shapeid) {
  2618. shapeseq.splice(i, 1);
  2619. break;
  2620. }
  2621. }
  2622. delete this.shapes[shapeid];
  2623. },
  2624. getShapeAt: function (el, x, y) {
  2625. this.targetX = x;
  2626. this.targetY = y;
  2627. this.render();
  2628. return this.currentTargetShapeId;
  2629. },
  2630. render: function () {
  2631. var shapeseq = this.shapeseq,
  2632. shapes = this.shapes,
  2633. shapeCount = shapeseq.length,
  2634. context = this._getContext(),
  2635. shapeid, shape, i;
  2636. context.clearRect(0, 0, this.pixelWidth, this.pixelHeight);
  2637. for (i = 0; i < shapeCount; i++) {
  2638. shapeid = shapeseq[i];
  2639. shape = shapes[shapeid];
  2640. this['_draw' + shape.type].apply(this, shape.args);
  2641. }
  2642. if (!this.interact) {
  2643. // not interactive so no need to keep the shapes array
  2644. this.shapes = {};
  2645. this.shapeseq = [];
  2646. }
  2647. }
  2648. });
  2649. VCanvas_vml = createClass(VCanvas_base, {
  2650. init: function (width, height, target) {
  2651. var groupel;
  2652. VCanvas_vml._super.init.call(this, width, height, target);
  2653. if (target[0]) {
  2654. target = target[0];
  2655. }
  2656. $.data(target, '_jqs_vcanvas', this);
  2657. this.canvas = document.createElement('span');
  2658. $(this.canvas).css({ display: 'inline-block', position: 'relative', overflow: 'hidden', width: width, height: height, margin: '0px', padding: '0px', verticalAlign: 'top'});
  2659. this._insert(this.canvas, target);
  2660. this._calculatePixelDims(width, height, this.canvas);
  2661. this.canvas.width = this.pixelWidth;
  2662. this.canvas.height = this.pixelHeight;
  2663. groupel = '<v:group coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '"' +
  2664. ' style="position:absolute;top:0;left:0;width:' + this.pixelWidth + 'px;height=' + this.pixelHeight + 'px;"></v:group>';
  2665. this.canvas.insertAdjacentHTML('beforeEnd', groupel);
  2666. this.group = $(this.canvas).children()[0];
  2667. this.rendered = false;
  2668. this.prerender = '';
  2669. },
  2670. _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) {
  2671. var vpath = [],
  2672. initial, stroke, fill, closed, vel, plen, i;
  2673. for (i = 0, plen = path.length; i < plen; i++) {
  2674. vpath[i] = '' + (path[i][0]) + ',' + (path[i][1]);
  2675. }
  2676. initial = vpath.splice(0, 1);
  2677. lineWidth = lineWidth === undefined ? 1 : lineWidth;
  2678. stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" ';
  2679. fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
  2680. closed = vpath[0] === vpath[vpath.length - 1] ? 'x ' : '';
  2681. vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' +
  2682. ' id="jqsshape' + shapeid + '" ' +
  2683. stroke +
  2684. fill +
  2685. ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' +
  2686. ' path="m ' + initial + ' l ' + vpath.join(', ') + ' ' + closed + 'e">' +
  2687. ' </v:shape>';
  2688. return vel;
  2689. },
  2690. _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) {
  2691. var stroke, fill, vel;
  2692. x -= radius;
  2693. y -= radius;
  2694. stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" ';
  2695. fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
  2696. vel = '<v:oval ' +
  2697. ' id="jqsshape' + shapeid + '" ' +
  2698. stroke +
  2699. fill +
  2700. ' style="position:absolute;top:' + y + 'px; left:' + x + 'px; width:' + (radius * 2) + 'px; height:' + (radius * 2) + 'px"></v:oval>';
  2701. return vel;
  2702. },
  2703. _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) {
  2704. var vpath, startx, starty, endx, endy, stroke, fill, vel;
  2705. if (startAngle === endAngle) {
  2706. return ''; // VML seems to have problem when start angle equals end angle.
  2707. }
  2708. if ((endAngle - startAngle) === (2 * Math.PI)) {
  2709. startAngle = 0.0; // VML seems to have a problem when drawing a full circle that doesn't start 0
  2710. endAngle = (2 * Math.PI);
  2711. }
  2712. startx = x + Math.round(Math.cos(startAngle) * radius);
  2713. starty = y + Math.round(Math.sin(startAngle) * radius);
  2714. endx = x + Math.round(Math.cos(endAngle) * radius);
  2715. endy = y + Math.round(Math.sin(endAngle) * radius);
  2716. if (startx === endx && starty === endy) {
  2717. if ((endAngle - startAngle) < Math.PI) {
  2718. // Prevent very small slices from being mistaken as a whole pie
  2719. return '';
  2720. }
  2721. // essentially going to be the entire circle, so ignore startAngle
  2722. startx = endx = x + radius;
  2723. starty = endy = y;
  2724. }
  2725. if (startx === endx && starty === endy && (endAngle - startAngle) < Math.PI) {
  2726. return '';
  2727. }
  2728. vpath = [x - radius, y - radius, x + radius, y + radius, startx, starty, endx, endy];
  2729. stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="1px" strokeColor="' + lineColor + '" ';
  2730. fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" ';
  2731. vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' +
  2732. ' id="jqsshape' + shapeid + '" ' +
  2733. stroke +
  2734. fill +
  2735. ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' +
  2736. ' path="m ' + x + ',' + y + ' wa ' + vpath.join(', ') + ' x e">' +
  2737. ' </v:shape>';
  2738. return vel;
  2739. },
  2740. _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) {
  2741. return this._drawShape(shapeid, [[x, y], [x, y + height], [x + width, y + height], [x + width, y], [x, y]], lineColor, fillColor);
  2742. },
  2743. reset: function () {
  2744. this.group.innerHTML = '';
  2745. },
  2746. appendShape: function (shape) {
  2747. var vel = this['_draw' + shape.type].apply(this, shape.args);
  2748. if (this.rendered) {
  2749. this.group.insertAdjacentHTML('beforeEnd', vel);
  2750. } else {
  2751. this.prerender += vel;
  2752. }
  2753. this.lastShapeId = shape.id;
  2754. return shape.id;
  2755. },
  2756. replaceWithShape: function (shapeid, shape) {
  2757. var existing = $('#jqsshape' + shapeid),
  2758. vel = this['_draw' + shape.type].apply(this, shape.args);
  2759. existing[0].outerHTML = vel;
  2760. },
  2761. replaceWithShapes: function (shapeids, shapes) {
  2762. // replace the first shapeid with all the new shapes then toast the remaining old shapes
  2763. var existing = $('#jqsshape' + shapeids[0]),
  2764. replace = '',
  2765. slen = shapes.length,
  2766. i;
  2767. for (i = 0; i < slen; i++) {
  2768. replace += this['_draw' + shapes[i].type].apply(this, shapes[i].args);
  2769. }
  2770. existing[0].outerHTML = replace;
  2771. for (i = 1; i < shapeids.length; i++) {
  2772. $('#jqsshape' + shapeids[i]).remove();
  2773. }
  2774. },
  2775. insertAfterShape: function (shapeid, shape) {
  2776. var existing = $('#jqsshape' + shapeid),
  2777. vel = this['_draw' + shape.type].apply(this, shape.args);
  2778. existing[0].insertAdjacentHTML('afterEnd', vel);
  2779. },
  2780. removeShapeId: function (shapeid) {
  2781. var existing = $('#jqsshape' + shapeid);
  2782. this.group.removeChild(existing[0]);
  2783. },
  2784. getShapeAt: function (el, x, y) {
  2785. var shapeid = el.id.substr(8);
  2786. return shapeid;
  2787. },
  2788. render: function () {
  2789. if (!this.rendered) {
  2790. // batch the intial render into a single repaint
  2791. this.group.innerHTML = this.prerender;
  2792. this.rendered = true;
  2793. }
  2794. }
  2795. });
  2796. }))}(document, Math));