import {compose, EventEmitter, Property} from '@avocado/core'; import {Ticker} from './ticker'; export function TimedIndexMixin (indexName = 'index') { return (Superclass) => { const _indexCount = `${indexName}Count`; const _indexRate = `${indexName}Rate`; const decorate = compose( EventEmitter, Property('index', { default: 0, track: true, }), Property('isTicking', { default: true, }), Property(_indexCount, { default: 0, }), Property(_indexRate, { default: 100, }), ); return class TimedIndex extends decorate(Superclass) { constructor(...args) { super(...args); this.ticker = new Ticker(); this.ticker.frequency = this[_indexRate]; this.ticker.on('tick', this.onTick, this); } destroy() { if (super.destroy) { super.destroy(); } this.ticker.off('tick', this.onTick); } get index() { return super.index; } set index(index) { super.index = 0 === this[_indexCount] ? 0 : index % this[_indexCount]; } onTick() { const index = this.index + 1; if (index >= this[_indexCount]) { this.emit('rollingOver'); } this.index = index; } reset() { this.ticker.reset(); } start() { this.isTicking = true; } stop() { this.isTicking = false; } tick(elapsed) { if (this.isTicking) { this.ticker.tick(elapsed); } } } } }