2021-01-05 13:46:09 +00:00
|
|
|
import {Dispatch, SetStateAction, useEffect, useMemo, useState} from "react";
|
2021-01-10 15:13:15 +00:00
|
|
|
import {RegistryValueType, settings, RegistryKey, ValuedRegistryKey} from "tc-shared/settings";
|
2020-12-07 18:37:06 +00:00
|
|
|
|
|
|
|
export function useDependentState<S>(
|
|
|
|
factory: (prevState?: S) => S,
|
|
|
|
inputs: ReadonlyArray<any>,
|
|
|
|
): [S, Dispatch<SetStateAction<S>>] {
|
|
|
|
let skipCalculation = false;
|
|
|
|
|
|
|
|
let [state, setState] = useState<S>(() => {
|
|
|
|
skipCalculation = true;
|
|
|
|
return factory(undefined);
|
|
|
|
});
|
|
|
|
|
|
|
|
useMemo(() => {
|
|
|
|
if(skipCalculation) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const newState = factory(state);
|
|
|
|
if (newState !== state) {
|
|
|
|
setState(state = newState);
|
|
|
|
}
|
|
|
|
}, inputs);
|
|
|
|
|
|
|
|
return [state, setState];
|
2020-12-18 18:18:01 +00:00
|
|
|
}
|
|
|
|
|
2020-12-22 12:32:56 +00:00
|
|
|
export function useTr(message: string) : string {
|
|
|
|
return /* @tr-ignore */ tr(message);
|
|
|
|
}
|
|
|
|
|
2020-12-18 18:18:01 +00:00
|
|
|
export function joinClassList(...classes: any[]) : string {
|
|
|
|
return classes.filter(value => typeof value === "string" && value.length > 0).join(" ");
|
2021-01-05 13:46:09 +00:00
|
|
|
}
|
|
|
|
|
2021-01-10 15:13:15 +00:00
|
|
|
export function useGlobalSetting<V extends RegistryValueType, DV>(key: RegistryKey<V>, defaultValue: DV) : V | DV;
|
|
|
|
export function useGlobalSetting<V extends RegistryValueType>(key: ValuedRegistryKey<V>, defaultValue?: V) : V;
|
|
|
|
export function useGlobalSetting<V extends RegistryValueType, DV>(key: RegistryKey<V>, defaultValue: DV) : V | DV {
|
|
|
|
const [ value, setValue ] = useState(settings.getValue(key, defaultValue));
|
2021-01-05 13:46:09 +00:00
|
|
|
useEffect(() => settings.globalChangeListener(key, value => setValue(value)), []);
|
|
|
|
|
|
|
|
return value;
|
2020-12-07 18:37:06 +00:00
|
|
|
}
|