UNPKG

@orca-fe/x-map

Version:
112 lines (111 loc) 3.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Transition = exports.mixObj = exports.mix = void 0; const events_1 = require("events"); function mix(start, end, rate) { return start * (1 - rate) + end * rate; } exports.mix = mix; function mixObj(start, end, rate) { const target = Object.assign(Object.assign({}, start), end); const result = {}; Object.entries(start).forEach(([key, value]) => { result[key] = mix(start[key], target[key], rate); }); return result; } exports.mixObj = mixObj; class Transition extends events_1.EventEmitter { constructor() { super(...arguments); this._duration = 1000; this.easingFn = a => a; this.timer = -1; this.rate = 0; this.lastTime = -1; this.running = false; this.duration = (duration) => { this._duration = duration; return this; }; this.easing = (easing) => { this.easingFn = easing; return this; }; this.from = (fromState) => { this.fromState = fromState; return this; }; this.to = (toState) => { this.toState = toState; return this; }; this.onInterval = (callback) => { this.on('interval', callback); return this; }; this.offInterval = (callback) => { this.off('interval', callback); return this; }; this.start = () => { this.lastTime = -1; this.resume(); return this; }; this.resume = () => { this.running = true; this.run(); return this; }; this.run = () => { if (!this.running) return; this.timer = requestAnimationFrame((time) => { this.run(); if (this.lastTime < 0) { // firstTime this.rate = 0; } else { this.rate += (time - this.lastTime) / this._duration; } this.lastTime = time; this.rate = Math.min(1, this.rate); const acRate = this.easingFn(this.rate); const canMix = this.fromState != null && this.toState != null; this.emit('interval', acRate, canMix ? mixObj(this.fromState, this.toState, acRate) : undefined, this.rate); if (this.rate >= 1) { this.emit('finish'); this.stop(); } }); }; this.cancel = () => { this.stop(); this.emit('cancel'); }; this.stop = () => { this.running = false; cancelAnimationFrame(this.timer); return this; }; } construct() { } } exports.Transition = Transition; function transition(options) { const transition = new Transition().duration(options.duration); if (options.from) { transition.from(options.from); } if (options.to) { transition.to(options.to); } if (options.easing) { transition.easing(options.easing); } transition.start(); return transition; } exports.default = transition;