Line data Source code
1 : package hooks
2 :
3 : import (
4 : "time"
5 :
6 : "github.com/kijimaD/ruins/internal/inputmapper"
7 : )
8 :
9 : // timerState はタイマーの内部状態
10 : type timerState struct {
11 : StartedAt time.Time
12 : Active bool
13 : }
14 :
15 : // UseTimer は再利用可能なタイマー状態管理を提供する
16 : // 戻り値:
17 : // - expired: タイマーが期限切れかどうか
18 : // - start: タイマーを開始する関数
19 : // - reset: タイマーをリセットする関数
20 : func UseTimer(store *Store, key string, duration time.Duration) (expired bool, start func(), reset func()) {
21 1 : return UseTimerAt(store, key, duration, time.Now())
22 1 : }
23 :
24 : // UseTimerAt は指定した時刻を基準にタイマー状態を管理する
25 : // テスト用に時刻を注入可能にするためのバージョン
26 : func UseTimerAt(store *Store, key string, duration time.Duration, now time.Time) (expired bool, start func(), reset func()) {
27 1 : state := UseState(store, key, timerState{}, func(v timerState, _ inputmapper.ActionID) timerState {
28 1 : return v // アクションでは変更しない
29 1 : })
30 :
31 1 : expired = state.Active && !state.StartedAt.IsZero() && now.Sub(state.StartedAt) >= duration
32 1 :
33 1 : start = func() {
34 1 : store.set(key, timerState{
35 1 : StartedAt: now,
36 1 : Active: true,
37 1 : })
38 1 : }
39 :
40 1 : reset = func() {
41 1 : store.set(key, timerState{
42 1 : StartedAt: time.Time{},
43 1 : Active: false,
44 1 : })
45 1 : }
46 :
47 1 : return
48 : }
|