xref: /MusicFree/src/core/persistStatus.ts (revision 1057be29f489db78617b3c76a26abb6f7589db3b)
1import getOrCreateMMKV from '@/utils/getOrCreateMMKV';
2import safeParse from '@/utils/safeParse';
3import {useEffect, useState} from 'react';
4
5// Internal Method
6const getStore = () => {
7    return getOrCreateMMKV(`App.PersistStatus`);
8};
9
10interface IPersistConfig {
11    /** 当前的音乐 */
12    'music.musicItem': IMusic.IMusicItem;
13    /** 进度 */
14    'music.progress': number;
15    /** 模式 */
16    'music.repeatMode': string;
17    /** 列表 */
18    'music.playList': IMusic.IMusicItem[];
19    /** 速度 */
20    'music.rate': number;
21    /** 音质 */
22    'music.quality': IMusic.IQualityKey;
23    /** app */
24    'app.skipVersion': string;
25    /** 歌词-是否启用翻译 */
26    'lyric.showTranslation': boolean;
27}
28
29function set<K extends keyof IPersistConfig>(
30    key: K,
31    value: IPersistConfig[K] | undefined,
32) {
33    const store = getStore();
34    if (value === undefined) {
35        store.delete(key);
36    } else {
37        store.set(key, JSON.stringify(value));
38    }
39}
40
41function get<K extends keyof IPersistConfig>(key: K): IPersistConfig[K] | null {
42    const store = getStore();
43    const raw = store.getString(key);
44    if (raw) {
45        return safeParse(raw) as IPersistConfig[K];
46    }
47    return null;
48}
49
50function useValue<K extends keyof IPersistConfig>(
51    key: K,
52    defaultValue?: IPersistConfig[K],
53): IPersistConfig[K] | null {
54    const [state, setState] = useState<IPersistConfig[K] | null>(
55        get(key) ?? defaultValue ?? null,
56    );
57
58    useEffect(() => {
59        const store = getStore();
60        const sub = store.addOnValueChangedListener(changedKey => {
61            if (key === changedKey) {
62                setState(get(key));
63            }
64        });
65
66        return () => {
67            sub.remove();
68        };
69    }, []);
70
71    return state;
72}
73
74const PersistStatus = {
75    get,
76    set,
77    useValue,
78};
79
80export default PersistStatus;
81