* 全局持久化的状态
*/
import getOrCreateMMKV from "@/utils/getOrCreateMMKV";
import { useEffect, useState } from "react";
import { safeParse } from "./jsonUtil";
const getStore = () => {
return getOrCreateMMKV("App.PersistStatus");
};
interface IPersistStatus {
"music.musicItem": IMusic.IMusicItem;
"music.progress": number;
"music.repeatMode": string;
"music.playList": IMusic.IMusicItem[];
"music.rate": number;
"music.quality": IMusic.IQualityKey;
"app.skipVersion": string;
"app.skipBootstrapStorageDialog": boolean;
"app.language": string;
"app.pluginUpdateTime": number;
"app.scheduleCloseTime": number;
"lyric.showTranslation": boolean;
"lyric.detailFontSize": number;
}
function set<K extends keyof IPersistStatus>(
key: K,
value: IPersistStatus[K] | undefined,
) {
const store = getStore();
if (value === undefined) {
store.delete(key);
} else {
store.set(key, JSON.stringify(value));
}
}
function get<K extends keyof IPersistStatus>(key: K): IPersistStatus[K] | null {
const store = getStore();
const raw = store.getString(key);
if (raw) {
return safeParse(raw) as IPersistStatus[K];
}
return null;
}
function useValue<K extends keyof IPersistStatus>(
key: K,
defaultValue?: IPersistStatus[K],
): IPersistStatus[K] | null {
const [state, setState] = useState<IPersistStatus[K] | null>(
get(key) ?? defaultValue ?? null,
);
useEffect(() => {
const store = getStore();
const sub = store.addOnValueChangedListener(changedKey => {
if (key === changedKey) {
setState(get(key));
}
});
return () => {
sub.remove();
};
}, []);
return state;
}
const PersistStatus = {
get,
set,
useValue,
};
export default PersistStatus;