DataPresentation.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. // wrapped by build app
  2. define("dojox/widget/DataPresentation", ["dijit","dojo","dojox","dojo/require!dojox/grid/DataGrid,dojox/charting/Chart2D,dojox/charting/widget/Legend,dojox/charting/action2d/Tooltip,dojox/charting/action2d/Highlight,dojo/colors,dojo/data/ItemFileWriteStore"], function(dijit,dojo,dojox){
  3. dojo.provide("dojox.widget.DataPresentation");
  4. dojo.experimental("dojox.widget.DataPresentation");
  5. dojo.require("dojox.grid.DataGrid");
  6. dojo.require("dojox.charting.Chart2D");
  7. dojo.require("dojox.charting.widget.Legend");
  8. dojo.require("dojox.charting.action2d.Tooltip");
  9. dojo.require("dojox.charting.action2d.Highlight");
  10. dojo.require("dojo.colors");
  11. dojo.require("dojo.data.ItemFileWriteStore");
  12. (function(){
  13. // sort out the labels for the independent axis of the chart
  14. var getLabels = function(range, labelMod, charttype, domNode){
  15. // prepare labels for the independent axis
  16. var labels = [];
  17. // add empty label, hack
  18. labels[0] = {value: 0, text: ''};
  19. var nlabels = range.length;
  20. // auto-set labelMod for horizontal charts if the labels will otherwise collide
  21. if((charttype !== "ClusteredBars") && (charttype !== "StackedBars")){
  22. var cwid = domNode.offsetWidth;
  23. var tmp = ("" + range[0]).length * range.length * 7; // *assume* 7 pixels width per character ( was 9 )
  24. if(labelMod == 1){
  25. for(var z = 1; z < 500; ++z){
  26. if((tmp / z) < cwid){
  27. break;
  28. }
  29. ++labelMod;
  30. }
  31. }
  32. }
  33. // now set the labels
  34. for(var i = 0; i < nlabels; i++){
  35. //sparse labels
  36. labels.push({
  37. value: i + 1,
  38. text: (!labelMod || i % labelMod) ? "" : range[i]
  39. });
  40. }
  41. // add empty label again, hack
  42. labels.push({value: nlabels + 1, text:''});
  43. return labels;
  44. };
  45. // get the configuration of an independent axis for the chart
  46. var getIndependentAxisArgs = function(charttype, labels){
  47. var args = { vertical: false, labels: labels, min: 0, max: labels.length-1, majorTickStep: 1, minorTickStep: 1 };
  48. // clustered or stacked bars have a vertical independent axis
  49. if((charttype === "ClusteredBars") || (charttype === "StackedBars")){
  50. args.vertical = true;
  51. }
  52. // lines, areas and stacked areas don't need the extra slots at each end
  53. if((charttype === "Lines") || (charttype === "Areas") || (charttype === "StackedAreas")){
  54. args.min++;
  55. args.max--;
  56. }
  57. return args;
  58. };
  59. // get the configuration of a dependent axis for the chart
  60. var getDependentAxisArgs = function(charttype, axistype, minval, maxval){
  61. var args = { vertical: true, fixLower: "major", fixUpper: "major", natural: true };
  62. // secondary dependent axis is not left-bottom
  63. if(axistype === "secondary"){
  64. args.leftBottom = false;
  65. }
  66. // clustered or stacked bars have horizontal dependent axes
  67. if((charttype === "ClusteredBars") || (charttype === "StackedBars")){
  68. args.vertical = false;
  69. }
  70. // ensure axis does not "collapse" for flat series
  71. if(minval == maxval){
  72. args.min = minval - 1;
  73. args.max = maxval + 1;
  74. }
  75. return args;
  76. };
  77. // get the configuration of a plot for the chart
  78. var getPlotArgs = function(charttype, axistype, animate){
  79. var args = { type: charttype, hAxis: "independent", vAxis: "dependent-" + axistype, gap: 4, lines: false, areas: false, markers: false };
  80. // clustered or stacked bars have horizontal dependent axes
  81. if((charttype === "ClusteredBars") || (charttype === "StackedBars")){
  82. args.hAxis = args.vAxis;
  83. args.vAxis = "independent";
  84. }
  85. // turn on lines for Lines, Areas and StackedAreas
  86. if((charttype === "Lines") || (charttype === "Hybrid-Lines") || (charttype === "Areas") || (charttype === "StackedAreas")){
  87. args.lines = true;
  88. }
  89. // turn on areas for Areas and StackedAreas
  90. if((charttype === "Areas") || (charttype === "StackedAreas")){
  91. args.areas = true;
  92. }
  93. // turn on markers and shadow for Lines
  94. if(charttype === "Lines"){
  95. args.markers = true;
  96. }
  97. // turn on shadow for Hybrid-Lines
  98. // also, Hybrid-Lines is not a true chart type: use Lines for the actual plot
  99. if(charttype === "Hybrid-Lines"){
  100. args.shadows = {dx: 2, dy: 2, dw: 2};
  101. args.type = "Lines";
  102. }
  103. // also, Hybrid-ClusteredColumns is not a true chart type: use ClusteredColumns for the actual plot
  104. if(charttype === "Hybrid-ClusteredColumns"){
  105. args.type = "ClusteredColumns";
  106. }
  107. // enable animation on the plot if animation is requested
  108. if(animate){
  109. args.animate = animate;
  110. }
  111. return args;
  112. };
  113. // set up a chart presentation
  114. var setupChart = function(/*DomNode*/domNode, /*Object?*/chart, /*String*/type, /*Boolean*/reverse, /*Object*/animate, /*Integer*/labelMod, /*String*/theme, /*String*/tooltip, /*Object?*/store, /*String?*/query, /*String?*/queryOptions){
  115. var _chart = chart;
  116. if(!_chart){
  117. domNode.innerHTML = ""; // any other content in the node disrupts the chart rendering
  118. _chart = new dojox.charting.Chart2D(domNode);
  119. }
  120. // set the theme
  121. if(theme){
  122. // workaround for a theme bug: its _clone method
  123. // does not transfer the markers, so we repair
  124. // that omission here
  125. // FIXME this should be removed once the theme bug is fixed
  126. theme._clone = function(){
  127. var result = new dojox.charting.Theme({
  128. chart: this.chart,
  129. plotarea: this.plotarea,
  130. axis: this.axis,
  131. series: this.series,
  132. marker: this.marker,
  133. antiAlias: this.antiAlias,
  134. assignColors: this.assignColors,
  135. assignMarkers: this.assigneMarkers,
  136. colors: dojo.delegate(this.colors)
  137. });
  138. result.markers = this.markers;
  139. result._buildMarkerArray();
  140. return result;
  141. };
  142. _chart.setTheme(theme);
  143. }
  144. var range = store.series_data[0].slice(0);
  145. // reverse the labels if requested
  146. if(reverse){
  147. range.reverse();
  148. }
  149. var labels = getLabels(range, labelMod, type, domNode);
  150. // collect details of whether primary and/or secondary axes are required
  151. // and what plots we have instantiated using each type of axis
  152. var plots = {};
  153. // collect maximum and minimum data values
  154. var maxval = null;
  155. var minval = null;
  156. var seriestoremove = {};
  157. for(var sname in _chart.runs){
  158. seriestoremove[sname] = true;
  159. }
  160. // set x values & max data value
  161. var nseries = store.series_name.length;
  162. for(var i = 0; i < nseries; i++){
  163. // only include series with chart=true and with some data values in
  164. if(store.series_chart[i] && (store.series_data[i].length > 0)){
  165. var charttype = type;
  166. var axistype = store.series_axis[i];
  167. if(charttype == "Hybrid"){
  168. if(store.series_charttype[i] == 'line'){
  169. charttype = "Hybrid-Lines";
  170. }else{
  171. charttype = "Hybrid-ClusteredColumns";
  172. }
  173. }
  174. // ensure we have recorded that we are using this axis type
  175. if(!plots[axistype]){
  176. plots[axistype] = {};
  177. }
  178. // ensure we have the correct type of plot for this series
  179. if(!plots[axistype][charttype]){
  180. var axisname = axistype + "-" + charttype;
  181. // create the plot and enable tooltips
  182. _chart.addPlot(axisname, getPlotArgs(charttype, axistype, animate));
  183. var tooltipArgs = {};
  184. if(typeof tooltip == 'string'){
  185. tooltipArgs.text = function(o){
  186. var substitutions = [o.element, o.run.name, range[o.index], ((charttype === "ClusteredBars") || (charttype === "StackedBars")) ? o.x : o.y];
  187. return dojo.replace(tooltip, substitutions); // from Dojo 1.4 onward
  188. //return tooltip.replace(/\{([^\}]+)\}/g, function(_, token){ return dojo.getObject(token, false, substitutions); }); // prior to Dojo 1.4
  189. }
  190. }else if(typeof tooltip == 'function'){
  191. tooltipArgs.text = tooltip;
  192. }
  193. new dojox.charting.action2d.Tooltip(_chart, axisname, tooltipArgs);
  194. // add highlighting, except for lines
  195. if(charttype !== "Lines" && charttype !== "Hybrid-Lines"){
  196. new dojox.charting.action2d.Highlight(_chart, axisname);
  197. }
  198. // record that this plot type is now created
  199. plots[axistype][charttype] = true;
  200. }
  201. // extract the series values
  202. var xvals = [];
  203. var valen = store.series_data[i].length;
  204. for(var j = 0; j < valen; j++){
  205. var val = store.series_data[i][j];
  206. xvals.push(val);
  207. if(maxval === null || val > maxval){
  208. maxval = val;
  209. }
  210. if(minval === null || val < minval){
  211. minval = val;
  212. }
  213. }
  214. // reverse the values if requested
  215. if(reverse){
  216. xvals.reverse();
  217. }
  218. var seriesargs = { plot: axistype + "-" + charttype };
  219. if(store.series_linestyle[i]){
  220. seriesargs.stroke = { style: store.series_linestyle[i] };
  221. }
  222. _chart.addSeries(store.series_name[i], xvals, seriesargs);
  223. delete seriestoremove[store.series_name[i]];
  224. }
  225. }
  226. // remove any series that are no longer needed
  227. for(sname in seriestoremove){
  228. _chart.removeSeries(sname);
  229. }
  230. // create axes
  231. _chart.addAxis("independent", getIndependentAxisArgs(type, labels));
  232. _chart.addAxis("dependent-primary", getDependentAxisArgs(type, "primary", minval, maxval));
  233. _chart.addAxis("dependent-secondary", getDependentAxisArgs(type, "secondary", minval, maxval));
  234. return _chart;
  235. };
  236. // set up a legend presentation
  237. var setupLegend = function(/*DomNode*/domNode, /*Legend*/legend, /*Chart2D*/chart, /*Boolean*/horizontal){
  238. // destroy any existing legend and recreate
  239. var _legend = legend;
  240. if(!_legend){
  241. _legend = new dojox.charting.widget.Legend({ chart: chart, horizontal: horizontal }, domNode);
  242. }else{
  243. _legend.refresh();
  244. }
  245. return _legend;
  246. };
  247. // set up a grid presentation
  248. var setupGrid = function(/*DomNode*/domNode, /*Object?*/grid, /*Object?*/store, /*String?*/query, /*String?*/queryOptions){
  249. var _grid = grid || new dojox.grid.DataGrid({}, domNode);
  250. _grid.startup();
  251. _grid.setStore(store, query, queryOptions);
  252. var structure = [];
  253. for(var ser = 0; ser < store.series_name.length; ser++){
  254. // only include series with grid=true and with some data values in
  255. if(store.series_grid[ser] && (store.series_data[ser].length > 0)){
  256. structure.push({ field: "data." + ser, name: store.series_name[ser], width: "auto", formatter: store.series_gridformatter[ser] });
  257. }
  258. }
  259. _grid.setStructure(structure);
  260. return _grid;
  261. };
  262. // set up a title presentation
  263. var setupTitle = function(/*DomNode*/domNode, /*object*/store){
  264. if(store.title){
  265. domNode.innerHTML = store.title;
  266. }
  267. };
  268. // set up a footer presentation
  269. var setupFooter = function(/*DomNode*/domNode, /*object*/store){
  270. if(store.footer){
  271. domNode.innerHTML = store.footer;
  272. }
  273. };
  274. // obtain a subfield from a field specifier which may contain
  275. // multiple levels (eg, "child.foo[36].manacle")
  276. var getSubfield = function(/*Object*/object, /*String*/field){
  277. var result = object;
  278. if(field){
  279. var fragments = field.split(/[.\[\]]+/);
  280. for(var frag = 0, l = fragments.length; frag < l; frag++){
  281. if(result){
  282. result = result[fragments[frag]];
  283. }
  284. }
  285. }
  286. return result;
  287. };
  288. dojo.declare("dojox.widget.DataPresentation", null, {
  289. // summary:
  290. //
  291. // DataPresentation
  292. //
  293. // A widget that connects to a data store in a simple manner,
  294. // and also provides some additional convenience mechanisms
  295. // for connecting to common data sources without needing to
  296. // explicitly construct a Dojo data store. The widget can then
  297. // present the data in several forms: as a graphical chart,
  298. // as a tabular grid, or as display panels presenting meta-data
  299. // (title, creation information, etc) from the data. The
  300. // widget can also create and manage several of these forms
  301. // in one simple construction.
  302. //
  303. // Note: this is a first experimental draft and any/all details
  304. // are subject to substantial change in later drafts.
  305. //
  306. // example:
  307. //
  308. // var pres = new dojox.data.DataPresentation("myChartNode", {
  309. // type: "chart",
  310. // url: "/data/mydata",
  311. // gridNode: "myGridNode"
  312. // });
  313. //
  314. // properties:
  315. //
  316. // store: Object
  317. // Dojo data store used to supply data to be presented. This may
  318. // be supplied on construction or created implicitly based on
  319. // other construction parameters ('data', 'url').
  320. //
  321. // query: String
  322. // Query to apply to the Dojo data store used to supply data to
  323. // be presented.
  324. //
  325. // queryOptions: String
  326. // Query options to apply to the Dojo data store used to supply
  327. // data to be presented.
  328. //
  329. // data: Object
  330. // Data to be presented. If supplied on construction this property
  331. // will override any value supplied for the 'store' property.
  332. //
  333. // url: String
  334. // URL to fetch data from in JSON format. If supplied on
  335. // construction this property will override any values supplied
  336. // for the 'store' and/or 'data' properties. Note that the data
  337. // can also be comment-filtered JSON, although this will trigger
  338. // a warning message in the console unless djConfig.useCommentedJson
  339. // has been set to true.
  340. //
  341. // urlContent: Object
  342. // Content to be passed to the URL when fetching data. If a URL has
  343. // not been supplied, this value is ignored.
  344. //
  345. // urlError: function
  346. // A function to be called if an error is encountered when fetching
  347. // data from the supplied URL. This function will be supplied with
  348. // two parameters exactly as the error function supplied to the
  349. // dojo.xhrGet function. This function may be called multiple times
  350. // if a refresh interval has been supplied.
  351. //
  352. // refreshInterval: Number
  353. // the time interval in milliseconds after which the data supplied
  354. // via the 'data' property or fetched from a URL via the 'url'
  355. // property should be regularly refreshed. This property is
  356. // ignored if neither the 'data' nor 'url' property has been
  357. // supplied. If the refresh interval is zero, no regular refresh is done.
  358. //
  359. // refreshIntervalPending:
  360. // the JavaScript set interval currently in progress, if any
  361. //
  362. // series: Array
  363. // an array of objects describing the data series to be included
  364. // in the data presentation. Each object may contain the
  365. // following fields:
  366. // datapoints: the name of the field from the source data which
  367. // contains an array of the data points for this data series.
  368. // If not supplied, the source data is assumed to be an array
  369. // of data points to be used.
  370. // field: the name of the field within each data point which
  371. // contains the data for this data series. If not supplied,
  372. // each data point is assumed to be the value for the series.
  373. // name: a name for the series, used in the legend and grid headings
  374. // namefield: the name of the field from the source data which
  375. // contains the name the series, used in the legend and grid
  376. // headings. If both name and namefield are supplied, name takes
  377. // precedence. If neither are supplied, a default name is used.
  378. // chart: true if the series should be included in a chart presentation (default: true)
  379. // charttype: the type of presentation of the series in the chart, which can be
  380. // "range", "line", "bar" (default: "bar")
  381. // linestyle: the stroke style for lines (if applicable) (default: "Solid")
  382. // axis: the dependant axis to which the series will be attached in the chart,
  383. // which can be "primary" or "secondary"
  384. // grid: true if the series should be included in a data grid presentation (default: true)
  385. // gridformatter: an optional formatter to use for this series in the data grid
  386. //
  387. // a call-back function may alternatively be supplied. The function takes
  388. // a single parameter, which will be the data (from the 'data' field or
  389. // loaded from the value in the 'url' field), and should return the array
  390. // of objects describing the data series to be included in the data
  391. // presentation. This enables the series structures to be built dynamically
  392. // after data load, and rebuilt if necessary on data refresh. The call-back
  393. // function will be called each time new data is set, loaded or refreshed.
  394. // A call-back function cannot be used if the data is supplied directly
  395. // from a Dojo data store.
  396. //
  397. // type: String
  398. // the type of presentation to be applied at the DOM attach point.
  399. // This can be 'chart', 'legend', 'grid', 'title', 'footer'. The
  400. // default type is 'chart'.
  401. type: "chart",
  402. //
  403. // chartType: String
  404. // the type of chart to display. This can be 'clusteredbars',
  405. // 'areas', 'stackedcolumns', 'stackedbars', 'stackedareas',
  406. // 'lines', 'hybrid'. The default type is 'bar'.
  407. chartType: "clusteredBars",
  408. //
  409. // reverse: Boolean
  410. // true if the chart independant axis should be reversed.
  411. reverse: false,
  412. //
  413. // animate: Object
  414. // if an object is supplied, then the chart bars or columns will animate
  415. // into place. If the object contains a field 'duration' then the value
  416. // supplied is the duration of the animation in milliseconds, otherwise
  417. // a default duration is used. A boolean value true can alternatively be
  418. // supplied to enable animation with the default duration.
  419. // The default is null (no animation).
  420. animate: null,
  421. //
  422. // labelMod: Integer
  423. // the frequency of label annotations to be included on the
  424. // independent axis. 1=every label. 0=no labels. The default is 1.
  425. labelMod: 1,
  426. //
  427. // tooltip: String | Function
  428. // a string pattern defining the tooltip text to be applied to chart
  429. // data points, or a function which takes a single parameter and returns
  430. // the tooltip text to be applied to chart data points. The string pattern
  431. // will have the following substitutions applied:
  432. // {0} - the type of chart element ('bar', 'surface', etc)
  433. // {1} - the name of the data series
  434. // {2} - the independent axis value at the tooltip data point
  435. // {3} - the series value at the tooltip data point point
  436. // The function, if supplied, will receive a single parameter exactly
  437. // as per the dojox.charting.action2D.Tooltip class. The default value
  438. // is to apply the default tooltip as defined by the
  439. // dojox.charting.action2D.Tooltip class.
  440. //
  441. // legendHorizontal: Boolean | Number
  442. // true if the legend should be rendered horizontally, or a number if
  443. // the legend should be rendered as horizontal rows with that number of
  444. // items in each row, or false if the legend should be rendered
  445. // vertically (same as specifying 1). The default is true (legend
  446. // rendered horizontally).
  447. legendHorizontal: true,
  448. //
  449. // theme: String|Theme
  450. // a theme to use for the chart, or the name of a theme.
  451. //
  452. // chartNode: String|DomNode
  453. // an optional DOM node or the id of a DOM node to receive a
  454. // chart presentation of the data. Supply only when a chart is
  455. // required and the type is not 'chart'; when the type is
  456. // 'chart' this property will be set to the widget attach point.
  457. //
  458. // legendNode: String|DomNode
  459. // an optional DOM node or the id of a DOM node to receive a
  460. // chart legend for the data. Supply only when a legend is
  461. // required and the type is not 'legend'; when the type is
  462. // 'legend' this property will be set to the widget attach point.
  463. //
  464. // gridNode: String|DomNode
  465. // an optional DOM node or the id of a DOM node to receive a
  466. // grid presentation of the data. Supply only when a grid is
  467. // required and the type is not 'grid'; when the type is
  468. // 'grid' this property will be set to the widget attach point.
  469. //
  470. // titleNode: String|DomNode
  471. // an optional DOM node or the id of a DOM node to receive a
  472. // title for the data. Supply only when a title is
  473. // required and the type is not 'title'; when the type is
  474. // 'title' this property will be set to the widget attach point.
  475. //
  476. // footerNode: String|DomNode
  477. // an optional DOM node or the id of a DOM node to receive a
  478. // footer presentation of the data. Supply only when a footer is
  479. // required and the type is not 'footer'; when the type is
  480. // 'footer' this property will be set to the widget attach point.
  481. //
  482. // chartWidget: Object
  483. // the chart widget, if any
  484. //
  485. // legendWidget: Object
  486. // the legend widget, if any
  487. //
  488. // gridWidget: Object
  489. // the grid widget, if any
  490. constructor: function(node, args){
  491. // summary:
  492. // Set up properties and initialize.
  493. //
  494. // arguments:
  495. // node: DomNode
  496. // The node to attach the data presentation to.
  497. // kwArgs: Object (see above)
  498. // apply arguments directly
  499. dojo.mixin(this, args);
  500. // store our DOM attach point
  501. this.domNode = dojo.byId(node);
  502. // also apply the DOM attach point as the node for the presentation type
  503. this[this.type + "Node"] = this.domNode;
  504. // load the theme if provided by name
  505. if(typeof this.theme == 'string'){
  506. this.theme = dojo.getObject(this.theme);
  507. }
  508. // resolve any the nodes that were supplied as ids
  509. this.chartNode = dojo.byId(this.chartNode);
  510. this.legendNode = dojo.byId(this.legendNode);
  511. this.gridNode = dojo.byId(this.gridNode);
  512. this.titleNode = dojo.byId(this.titleNode);
  513. this.footerNode = dojo.byId(this.footerNode);
  514. // we used to support a 'legendVertical' so for now
  515. // at least maintain backward compatibility
  516. if(this.legendVertical){
  517. this.legendHorizontal = !this.legendVertical;
  518. }
  519. if(this.url){
  520. this.setURL(null, null, this.refreshInterval);
  521. }
  522. else{
  523. if(this.data){
  524. this.setData(null, this.refreshInterval);
  525. }
  526. else{
  527. this.setStore();
  528. }
  529. }
  530. },
  531. setURL: function(/*String?*/url, /*Object?*/ urlContent, /*Number?*/refreshInterval){
  532. // summary:
  533. // Sets the URL to fetch data from, with optional content
  534. // supplied with the request, and an optional
  535. // refresh interval in milliseconds (0=no refresh)
  536. // if a refresh interval is supplied we will start a fresh
  537. // refresh after storing the supplied url
  538. if(refreshInterval){
  539. this.cancelRefresh();
  540. }
  541. this.url = url || this.url;
  542. this.urlContent = urlContent || this.urlContent;
  543. this.refreshInterval = refreshInterval || this.refreshInterval;
  544. var me = this;
  545. dojo.xhrGet({
  546. url: this.url,
  547. content: this.urlContent,
  548. handleAs: 'json-comment-optional',
  549. load: function(response, ioArgs){
  550. me.setData(response);
  551. },
  552. error: function(xhr, ioArgs){
  553. if(me.urlError && (typeof me.urlError == "function")){
  554. me.urlError(xhr, ioArgs);
  555. }
  556. }
  557. });
  558. if(refreshInterval && (this.refreshInterval > 0)){
  559. this.refreshIntervalPending = setInterval(function(){
  560. me.setURL();
  561. }, this.refreshInterval);
  562. }
  563. },
  564. setData: function(/*Object?*/data, /*Number?*/refreshInterval){
  565. // summary:
  566. // Sets the data to be presented, and an optional
  567. // refresh interval in milliseconds (0=no refresh)
  568. // if a refresh interval is supplied we will start a fresh
  569. // refresh after storing the supplied data reference
  570. if(refreshInterval){
  571. this.cancelRefresh();
  572. }
  573. this.data = data || this.data;
  574. this.refreshInterval = refreshInterval || this.refreshInterval;
  575. // TODO if no 'series' property was provided, build one intelligently here
  576. // (until that is done, a 'series' property must be supplied)
  577. var _series = (typeof this.series == 'function') ? this.series(this.data) : this.series;
  578. var datasets = [],
  579. series_data = [],
  580. series_name = [],
  581. series_chart = [],
  582. series_charttype = [],
  583. series_linestyle = [],
  584. series_axis = [],
  585. series_grid = [],
  586. series_gridformatter = [],
  587. maxlen = 0;
  588. // identify the dataset arrays in which series values can be found
  589. for(var ser = 0; ser < _series.length; ser++){
  590. datasets[ser] = getSubfield(this.data, _series[ser].datapoints);
  591. if(datasets[ser] && (datasets[ser].length > maxlen)){
  592. maxlen = datasets[ser].length;
  593. }
  594. series_data[ser] = [];
  595. // name can be specified in series structure, or by field in series structure, otherwise use a default
  596. series_name[ser] = _series[ser].name || (_series[ser].namefield ? getSubfield(this.data, _series[ser].namefield) : null) || ("series " + ser);
  597. series_chart[ser] = (_series[ser].chart !== false);
  598. series_charttype[ser] = _series[ser].charttype || "bar";
  599. series_linestyle[ser] = _series[ser].linestyle;
  600. series_axis[ser] = _series[ser].axis || "primary";
  601. series_grid[ser] = (_series[ser].grid !== false);
  602. series_gridformatter[ser] = _series[ser].gridformatter;
  603. }
  604. // create an array of data points by sampling the series
  605. // and an array of series arrays by collecting the series
  606. // each data point has an 'index' item containing a sequence number
  607. // and items named "data.0", "data.1", ... containing the series samples
  608. // and the first data point also has items named "name.0", "name.1", ... containing the series names
  609. // and items named "series.0", "series.1", ... containing arrays with the complete series in
  610. var point, datapoint, datavalue, fdatavalue;
  611. var datapoints = [];
  612. for(point = 0; point < maxlen; point++){
  613. datapoint = { index: point };
  614. for(ser = 0; ser < _series.length; ser++){
  615. if(datasets[ser] && (datasets[ser].length > point)){
  616. datavalue = getSubfield(datasets[ser][point], _series[ser].field);
  617. if(series_chart[ser]){
  618. // convert the data value to a float if possible
  619. fdatavalue = parseFloat(datavalue);
  620. if(!isNaN(fdatavalue)){
  621. datavalue = fdatavalue;
  622. }
  623. }
  624. datapoint["data." + ser] = datavalue;
  625. series_data[ser].push(datavalue);
  626. }
  627. }
  628. datapoints.push(datapoint);
  629. }
  630. if(maxlen <= 0){
  631. datapoints.push({index: 0});
  632. }
  633. // now build a prepared store from the data points we've constructed
  634. var store = new dojo.data.ItemFileWriteStore({ data: { identifier: 'index', items: datapoints }});
  635. if(this.data.title){
  636. store.title = this.data.title;
  637. }
  638. if(this.data.footer){
  639. store.footer = this.data.footer;
  640. }
  641. store.series_data = series_data;
  642. store.series_name = series_name;
  643. store.series_chart = series_chart;
  644. store.series_charttype = series_charttype;
  645. store.series_linestyle = series_linestyle;
  646. store.series_axis = series_axis;
  647. store.series_grid = series_grid;
  648. store.series_gridformatter = series_gridformatter;
  649. this.setPreparedStore(store);
  650. if(refreshInterval && (this.refreshInterval > 0)){
  651. var me = this;
  652. this.refreshIntervalPending = setInterval(function(){
  653. me.setData();
  654. }, this.refreshInterval);
  655. }
  656. },
  657. refresh: function(){
  658. // summary:
  659. // If a URL or data has been supplied, refreshes the
  660. // presented data from the URL or data. If a refresh
  661. // interval is also set, the periodic refresh is
  662. // restarted. If a URL or data was not supplied, this
  663. // method has no effect.
  664. if(this.url){
  665. this.setURL(this.url, this.urlContent, this.refreshInterval);
  666. }else if(this.data){
  667. this.setData(this.data, this.refreshInterval);
  668. }
  669. },
  670. cancelRefresh: function(){
  671. // summary:
  672. // Cancels any and all outstanding data refreshes
  673. if(this.refreshIntervalPending){
  674. // cancel existing refresh
  675. clearInterval(this.refreshIntervalPending);
  676. this.refreshIntervalPending = undefined;
  677. }
  678. },
  679. setStore: function(/*Object?*/store, /*String?*/query, /*Object?*/queryOptions){
  680. // FIXME build a prepared store properly -- this requires too tight a convention to be followed to be useful
  681. this.setPreparedStore(store, query, queryOptions);
  682. },
  683. setPreparedStore: function(/*Object?*/store, /*String?*/query, /*Object?*/queryOptions){
  684. // summary:
  685. // Sets the store and query.
  686. //
  687. this.preparedstore = store || this.store;
  688. this.query = query || this.query;
  689. this.queryOptions = queryOptions || this.queryOptions;
  690. if(this.preparedstore){
  691. if(this.chartNode){
  692. this.chartWidget = setupChart(this.chartNode, this.chartWidget, this.chartType, this.reverse, this.animate, this.labelMod, this.theme, this.tooltip, this.preparedstore, this.query, this,queryOptions);
  693. this.renderChartWidget();
  694. }
  695. if(this.legendNode){
  696. this.legendWidget = setupLegend(this.legendNode, this.legendWidget, this.chartWidget, this.legendHorizontal);
  697. }
  698. if(this.gridNode){
  699. this.gridWidget = setupGrid(this.gridNode, this.gridWidget, this.preparedstore, this.query, this.queryOptions);
  700. this.renderGridWidget();
  701. }
  702. if(this.titleNode){
  703. setupTitle(this.titleNode, this.preparedstore);
  704. }
  705. if(this.footerNode){
  706. setupFooter(this.footerNode, this.preparedstore);
  707. }
  708. }
  709. },
  710. renderChartWidget: function(){
  711. // summary:
  712. // Renders the chart widget (if any). This method is
  713. // called whenever a chart widget is created or
  714. // configured, and may be connected to.
  715. if(this.chartWidget){
  716. this.chartWidget.render();
  717. }
  718. },
  719. renderGridWidget: function(){
  720. // summary:
  721. // Renders the grid widget (if any). This method is
  722. // called whenever a grid widget is created or
  723. // configured, and may be connected to.
  724. if(this.gridWidget){
  725. this.gridWidget.render();
  726. }
  727. },
  728. getChartWidget: function(){
  729. // summary:
  730. // Returns the chart widget (if any) created if the type
  731. // is "chart" or the "chartNode" property was supplied.
  732. return this.chartWidget;
  733. },
  734. getGridWidget: function(){
  735. // summary:
  736. // Returns the grid widget (if any) created if the type
  737. // is "grid" or the "gridNode" property was supplied.
  738. return this.gridWidget;
  739. },
  740. destroy: function(){
  741. // summary:
  742. // Destroys the widget and all components and resources.
  743. // cancel any outstanding refresh requests
  744. this.cancelRefresh();
  745. if(this.chartWidget){
  746. this.chartWidget.destroy();
  747. delete this.chartWidget;
  748. }
  749. if(this.legendWidget){
  750. // no legend.destroy()
  751. delete this.legendWidget;
  752. }
  753. if(this.gridWidget){
  754. // no grid.destroy()
  755. delete this.gridWidget;
  756. }
  757. if(this.chartNode){
  758. this.chartNode.innerHTML = "";
  759. }
  760. if(this.legendNode){
  761. this.legendNode.innerHTML = "";
  762. }
  763. if(this.gridNode){
  764. this.gridNode.innerHTML = "";
  765. }
  766. if(this.titleNode){
  767. this.titleNode.innerHTML = "";
  768. }
  769. if(this.footerNode){
  770. this.footerNode.innerHTML = "";
  771. }
  772. }
  773. });
  774. })();
  775. });