Line data Source code
1 : package hooks
2 :
3 : import "github.com/kijimaD/ruins/internal/inputmapper"
4 :
5 : // mountPropsKey は props を Store に載せるときの予約キー。props も version 追跡に乗せ変更検知を
6 : // 1系統にする。UseState キーと衝突しないよう制御文字始まりにする。
7 : const mountPropsKey = "\x00mount.props"
8 :
9 : // Mount はProps + Stateを管理し変更を検出する。描画は担当しない。
10 : // props も store に載るので、変更検知は store.Version の差だけで済む。
11 : type Mount[Props any] struct {
12 : store *Store
13 : lastStoreVersion uint64
14 : }
15 :
16 : // NewMount は新しいMountを生成する
17 : func NewMount[Props any]() *Mount[Props] {
18 1 : return &Mount[Props]{
19 1 : store: NewStore(),
20 1 : // 初回は必ず描画させる。実在しない version にしておき、最初の Update で必ず差を出す
21 1 : lastStoreVersion: ^uint64(0),
22 1 : }
23 : }
24 :
25 : // SetProps は外部からPropsを設定する。値が実際に変わったときだけ store の version が動く
26 : func (m *Mount[Props]) SetProps(props Props) {
27 1 : m.store.set(mountPropsKey, props)
28 1 : }
29 :
30 : // GetProps は現在のPropsを返す。未設定ならゼロ値
31 : func (m *Mount[Props]) GetProps() Props {
32 1 : v, _ := GetStoreState[Props](m.store, mountPropsKey)
33 1 : return v
34 1 : }
35 :
36 : // Store はStoreを返す
37 : // UseStateやUseTabMenuを呼び出すために使用する
38 : func (m *Mount[Props]) Store() *Store {
39 1 : return m.store
40 1 : }
41 :
42 : // Dispatch は全ての State に Action を送る。状態が変われば store.Version が動き次の Update が拾う
43 : func (m *Mount[Props]) Dispatch(action inputmapper.ActionID) {
44 1 : m.store.Dispatch(action)
45 1 : }
46 :
47 : // GetState は指定したキーのStateを取得する
48 : func GetState[T any, Props any](m *Mount[Props], key string) (T, bool) {
49 1 : return GetStoreState[T](m.store, key)
50 1 : }
51 :
52 : // Update は前回からの変更の有無を返す。props も store 状態も store.Version に集約されるので
53 : // 版差だけで判定する。初回は sentinel 初期化で必ず true になる。
54 : func (m *Mount[Props]) Update() bool {
55 1 : v := m.store.Version()
56 1 : changed := v != m.lastStoreVersion
57 1 : m.lastStoreVersion = v
58 1 : return changed
59 1 : }
|