xref: /MusicFree/src/core/persistStatus.ts (revision 5589cdf32b2bb0f641e5ac7bf1f6152cd6b9b70e)
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    'app.pluginUpdateTime': number;
27    /** 歌词-是否启用翻译 */
28    'lyric.showTranslation': boolean;
29    /** 歌词-详情页字体大小 */
30    'lyric.detailFontSize': number;
31}
32
33function set<K extends keyof IPersistConfig>(
34    key: K,
35    value: IPersistConfig[K] | undefined,
36) {
37    const store = getStore();
38    if (value === undefined) {
39        store.delete(key);
40    } else {
41        store.set(key, JSON.stringify(value));
42    }
43}
44
45function get<K extends keyof IPersistConfig>(key: K): IPersistConfig[K] | null {
46    const store = getStore();
47    const raw = store.getString(key);
48    if (raw) {
49        return safeParse(raw) as IPersistConfig[K];
50    }
51    return null;
52}
53
54function useValue<K extends keyof IPersistConfig>(
55    key: K,
56    defaultValue?: IPersistConfig[K],
57): IPersistConfig[K] | null {
58    const [state, setState] = useState<IPersistConfig[K] | null>(
59        get(key) ?? defaultValue ?? null,
60    );
61
62    useEffect(() => {
63        const store = getStore();
64        const sub = store.addOnValueChangedListener(changedKey => {
65            if (key === changedKey) {
66                setState(get(key));
67            }
68        });
69
70        return () => {
71            sub.remove();
72        };
73    }, []);
74
75    return state;
76}
77
78const PersistStatus = {
79    get,
80    set,
81    useValue,
82};
83
84export default PersistStatus;
85