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 'lyric.detailFontSize': number; 29} 30 31function set<K extends keyof IPersistConfig>( 32 key: K, 33 value: IPersistConfig[K] | undefined, 34) { 35 const store = getStore(); 36 if (value === undefined) { 37 store.delete(key); 38 } else { 39 store.set(key, JSON.stringify(value)); 40 } 41} 42 43function get<K extends keyof IPersistConfig>(key: K): IPersistConfig[K] | null { 44 const store = getStore(); 45 const raw = store.getString(key); 46 if (raw) { 47 return safeParse(raw) as IPersistConfig[K]; 48 } 49 return null; 50} 51 52function useValue<K extends keyof IPersistConfig>( 53 key: K, 54 defaultValue?: IPersistConfig[K], 55): IPersistConfig[K] | null { 56 const [state, setState] = useState<IPersistConfig[K] | null>( 57 get(key) ?? defaultValue ?? null, 58 ); 59 60 useEffect(() => { 61 const store = getStore(); 62 const sub = store.addOnValueChangedListener(changedKey => { 63 if (key === changedKey) { 64 setState(get(key)); 65 } 66 }); 67 68 return () => { 69 sub.remove(); 70 }; 71 }, []); 72 73 return state; 74} 75 76const PersistStatus = { 77 get, 78 set, 79 useValue, 80}; 81 82export default PersistStatus; 83