xref: /MusicFree/src/utils/stateMapper.ts (revision 91c8197380501f56579772c90297157d6f3c3aab)
1233cafa6S猫头猫import {useEffect, useState} from 'react';
2233cafa6S猫头猫
3233cafa6S猫头猫export default class StateMapper<T> {
4233cafa6S猫头猫    private getFun: () => T;
5233cafa6S猫头猫    private cbs: Set<Function> = new Set([]);
6233cafa6S猫头猫    constructor(getFun: () => T) {
7233cafa6S猫头猫        this.getFun = getFun;
8233cafa6S猫头猫    }
9233cafa6S猫头猫
10233cafa6S猫头猫    notify = () => {
11233cafa6S猫头猫        this.cbs.forEach(_ => _?.());
124060c00aS猫头猫    };
13233cafa6S猫头猫
14233cafa6S猫头猫    useMappedState = () => {
15233cafa6S猫头猫        const [_state, _setState] = useState<T>(this.getFun);
16233cafa6S猫头猫        const updateState = () => {
17233cafa6S猫头猫            _setState(this.getFun());
18233cafa6S猫头猫        };
19233cafa6S猫头猫        useEffect(() => {
20233cafa6S猫头猫            this.cbs.add(updateState);
21233cafa6S猫头猫            return () => {
22233cafa6S猫头猫                this.cbs.delete(updateState);
23233cafa6S猫头猫            };
24233cafa6S猫头猫        }, []);
25233cafa6S猫头猫        return _state;
264060c00aS猫头猫    };
27233cafa6S猫头猫}
2850800d1bS猫头猫
2950800d1bS猫头猫export class GlobalState<T> {
3050800d1bS猫头猫    private value: T;
3150800d1bS猫头猫    private stateMapper: StateMapper<T>;
3250800d1bS猫头猫
3350800d1bS猫头猫    constructor(initValue: T) {
3450800d1bS猫头猫        this.value = initValue;
3550800d1bS猫头猫        this.stateMapper = new StateMapper(this.getValue);
3650800d1bS猫头猫    }
3750800d1bS猫头猫
3850800d1bS猫头猫    public getValue = () => {
3950800d1bS猫头猫        return this.value;
4050800d1bS猫头猫    };
4150800d1bS猫头猫
42*91c81973S猫头猫    public useValue = () => {
4350800d1bS猫头猫        return this.stateMapper.useMappedState();
44*91c81973S猫头猫    };
4550800d1bS猫头猫
46*91c81973S猫头猫    public setValue = (value: T) => {
4750800d1bS猫头猫        this.value = value;
4850800d1bS猫头猫        this.stateMapper.notify();
49*91c81973S猫头猫    };
5050800d1bS猫头猫}
51