/src/js/Rickshaw.Graph.Axis.Time.js

http://github.com/shutterstock/rickshaw · JavaScript · 85 lines · 55 code · 30 blank · 0 comment · 8 complexity · 360afb9354dfa65b83609ed2930b4493 MD5 · raw file

  1. Rickshaw.namespace('Rickshaw.Graph.Axis.Time');
  2. Rickshaw.Graph.Axis.Time = function(args) {
  3. var self = this;
  4. this.graph = args.graph;
  5. this.elements = [];
  6. this.ticksTreatment = args.ticksTreatment || 'plain';
  7. this.fixedTimeUnit = args.timeUnit;
  8. var time = args.timeFixture || new Rickshaw.Fixtures.Time();
  9. this.appropriateTimeUnit = function() {
  10. var unit;
  11. var units = time.units;
  12. var domain = this.graph.x.domain();
  13. var rangeSeconds = domain[1] - domain[0];
  14. units.forEach( function(u) {
  15. if (Math.floor(rangeSeconds / u.seconds) >= 2) {
  16. unit = unit || u;
  17. }
  18. } );
  19. return (unit || time.units[time.units.length - 1]);
  20. };
  21. this.tickOffsets = function() {
  22. var domain = this.graph.x.domain();
  23. var unit = this.fixedTimeUnit || this.appropriateTimeUnit();
  24. var count = Math.ceil((domain[1] - domain[0]) / unit.seconds);
  25. var runningTick = domain[0];
  26. var offsets = [];
  27. for (var i = 0; i < count; i++) {
  28. var tickValue = time.ceil(runningTick, unit);
  29. runningTick = tickValue + unit.seconds / 2;
  30. offsets.push( { value: tickValue, unit: unit } );
  31. }
  32. return offsets;
  33. };
  34. this.render = function() {
  35. this.elements.forEach( function(e) {
  36. e.parentNode.removeChild(e);
  37. } );
  38. this.elements = [];
  39. var offsets = this.tickOffsets();
  40. offsets.forEach( function(o) {
  41. if (self.graph.x(o.value) > self.graph.x.range()[1]) return;
  42. var element = document.createElement('div');
  43. element.style.left = self.graph.x(o.value) + 'px';
  44. element.classList.add('x_tick');
  45. element.classList.add(self.ticksTreatment);
  46. var title = document.createElement('div');
  47. title.classList.add('title');
  48. title.innerHTML = o.unit.formatter(new Date(o.value * 1000));
  49. element.appendChild(title);
  50. self.graph.element.appendChild(element);
  51. self.elements.push(element);
  52. } );
  53. };
  54. this.graph.onUpdate( function() { self.render() } );
  55. };