2 var util = require('util')
3 var TrackerBase = require('./tracker-base.js')
4 var Tracker = require('./tracker.js')
5 var TrackerStream = require('./tracker-stream.js')
7 var TrackerGroup = module.exports = function (name) {
8 TrackerBase.call(this, name)
9 this.parentGroup = null
15 this.bubbleChange = bubbleChange(this)
17 util.inherits(TrackerGroup, TrackerBase)
19 function bubbleChange (trackerGroup) {
20 return function (name, completed, tracker) {
21 trackerGroup.completion[tracker.id] = completed
22 if (trackerGroup.finished) return
23 trackerGroup.emit('change', name || trackerGroup.name, trackerGroup.completed(), trackerGroup)
27 TrackerGroup.prototype.nameInTree = function () {
31 names.unshift(from.name)
32 from = from.parentGroup
34 return names.join('/')
37 TrackerGroup.prototype.addUnit = function (unit, weight) {
41 if (unit === toTest) {
43 'Attempted to add tracker group ' +
44 unit.name + ' to tree that already includes it ' +
45 this.nameInTree(this))
47 toTest = toTest.parentGroup
49 unit.parentGroup = this
51 this.weight[unit.id] = weight || 1
52 this.totalWeight += this.weight[unit.id]
53 this.trackers.push(unit)
54 this.completion[unit.id] = unit.completed()
55 unit.on('change', this.bubbleChange)
56 if (!this.finished) this.emit('change', unit.name, this.completion[unit.id], unit)
60 TrackerGroup.prototype.completed = function () {
61 if (this.trackers.length === 0) return 0
62 var valPerWeight = 1 / this.totalWeight
64 for (var ii = 0; ii < this.trackers.length; ii++) {
65 var trackerId = this.trackers[ii].id
66 completed += valPerWeight * this.weight[trackerId] * this.completion[trackerId]
71 TrackerGroup.prototype.newGroup = function (name, weight) {
72 return this.addUnit(new TrackerGroup(name), weight)
75 TrackerGroup.prototype.newItem = function (name, todo, weight) {
76 return this.addUnit(new Tracker(name, todo), weight)
79 TrackerGroup.prototype.newStream = function (name, todo, weight) {
80 return this.addUnit(new TrackerStream(name, todo), weight)
83 TrackerGroup.prototype.finish = function () {
85 if (!this.trackers.length) this.addUnit(new Tracker(), 1, true)
86 for (var ii = 0; ii < this.trackers.length; ii++) {
87 var tracker = this.trackers[ii]
89 tracker.removeListener('change', this.bubbleChange)
91 this.emit('change', this.name, 1, this)
95 TrackerGroup.prototype.debug = function (depth) {
97 var indent = depth ? buffer.substr(0, depth) : ''
98 var output = indent + (this.name || 'top') + ': ' + this.completed() + '\n'
99 this.trackers.forEach(function (tracker) {
100 if (tracker instanceof TrackerGroup) {
101 output += tracker.debug(depth + 1)
103 output += indent + ' ' + tracker.name + ': ' + tracker.completed() + '\n'