forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperiod-processor.ts
More file actions
46 lines (39 loc) · 1.87 KB
/
Copy pathperiod-processor.ts
File metadata and controls
46 lines (39 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { trySendMsg2Runtime } from '@api/sw/common'
import { date2Idx } from "@util/limit"
import { MILL_PER_SECOND } from "@util/time"
import type { LimitReason, ModalContext, Processor } from '../types'
function processRule(rule: tt4b.limit.Rule, nowSeconds: number, context: ModalContext): ReturnType<typeof setTimeout>[] {
const { cond, periods, id } = rule
if (!periods?.length) return []
return periods.flatMap(p => {
const [s, e] = p
const startSeconds = s * 60
const endSeconds = (e + 1) * 60
const reason: LimitReason = { id, cond, type: "PERIOD" }
const timers: ReturnType<typeof setTimeout>[] = []
if (nowSeconds < startSeconds) {
timers.push(setTimeout(() => context.modal.addReason(reason), (startSeconds - nowSeconds) * MILL_PER_SECOND))
timers.push(setTimeout(() => context.modal.removeReason(reason), (endSeconds - nowSeconds) * MILL_PER_SECOND))
} else if (nowSeconds >= startSeconds && nowSeconds <= endSeconds) {
context.modal.addReason(reason)
timers.push(setTimeout(() => context.modal.removeReason(reason), (endSeconds - nowSeconds) * MILL_PER_SECOND))
}
return timers
})
}
class PeriodProcessor implements Processor {
private timers: ReturnType<typeof setTimeout>[] = []
constructor(private readonly context: ModalContext) { }
async onLimitChanged(): Promise<void> {
await this.init()
}
async init(): Promise<void> {
// Clear first
this.timers.forEach(clearTimeout)
this.context.modal.removeReasonsByType("PERIOD")
const rules = await trySendMsg2Runtime('limit.list', { effective: true, url: this.context.url }) ?? []
const nowSeconds = date2Idx(new Date())
this.timers = rules.flatMap(r => processRule(r, nowSeconds, this.context))
}
}
export default PeriodProcessor