Files
ontime/apps/server/src/services/extra-timer-service/ExtraTimerService.ts
T
Carlos Valente 2df3d376ad feat: many timers (#706)
* wip: create simple timer class

* refactor: service to manage extra timers

* wip:ui for controlling the extra timer

---------

Co-authored-by: arc-alex <ac@omnivox.dk>
2024-01-25 16:51:20 +01:00

78 lines
1.8 KiB
TypeScript

import { SimpleDirection, SimpleTimerState } from 'ontime-types';
import { SimpleTimer } from '../../classes/simple-timer/SimpleTimer.js';
import { eventStore } from '../../stores/EventStore.js';
export type EmitFn = (state: SimpleTimerState) => void;
export type GetTimeFn = () => number;
export class ExtraTimerService {
private timer: SimpleTimer;
private interval: NodeJS.Timer;
private emit: EmitFn;
private getTime: GetTimeFn;
constructor(emit: EmitFn, getTime: GetTimeFn) {
this.timer = new SimpleTimer();
this.emit = emit;
this.getTime = getTime;
}
private startInterval() {
this.interval = setInterval(this.update.bind(this), 500);
}
private stopInterval() {
clearInterval(this.interval);
}
@broadcastReturn
setDirection(direction: SimpleDirection) {
return this.timer.setDirection(direction);
}
@broadcastReturn
start() {
this.startInterval();
return this.timer.start(this.getTime());
}
@broadcastReturn
pause() {
return this.timer.pause(this.getTime());
}
@broadcastReturn
stop() {
this.stopInterval();
return this.timer.stop();
}
@broadcastReturn
setTime(duration: number) {
return this.timer.setTime(duration);
}
@broadcastReturn
private update() {
return this.timer.update(this.getTime());
}
}
function broadcastReturn(_target: any, _propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
const result = originalMethod.apply(this, args);
this.emit(result);
return result;
};
return descriptor;
}
const emit = (state: SimpleTimerState) => eventStore.set('timer1', state);
const timeNow = () => Date.now();
export const extraTimerService = new ExtraTimerService(emit, timeNow);