|
|
|
@ -1,13 +1,14 @@
|
|
|
|
|
import { LOG } from "@/utilities/console";
|
|
|
|
|
import {
|
|
|
|
|
createContext,
|
|
|
|
|
FunctionComponent,
|
|
|
|
|
useCallback,
|
|
|
|
|
useContext,
|
|
|
|
|
useEffect,
|
|
|
|
|
useMemo,
|
|
|
|
|
useRef,
|
|
|
|
|
useState,
|
|
|
|
|
} from "react";
|
|
|
|
|
import { enabledLanguageKey, languageProfileKey } from "../keys";
|
|
|
|
|
|
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
|
|
|
type HookType = (value: any) => unknown;
|
|
|
|
@ -50,20 +51,40 @@ export function useSubmitHooks() {
|
|
|
|
|
return context;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useSubmitHookWith(key: string, fn?: HookType) {
|
|
|
|
|
const fnRef = useRef(fn);
|
|
|
|
|
fnRef.current = fn;
|
|
|
|
|
|
|
|
|
|
const hooks = useSubmitHooks();
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
const currentFn = fnRef.current;
|
|
|
|
|
if (currentFn) {
|
|
|
|
|
LOG("info", "Adding submit hook for", key);
|
|
|
|
|
hooks.add(key, currentFn);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
LOG("info", "Removing submit hook for", key);
|
|
|
|
|
hooks.remove(key);
|
|
|
|
|
};
|
|
|
|
|
}, [key, hooks]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useSubmitHooksSource(): SubmitHookModifierType {
|
|
|
|
|
const [submitHooks, setSubmitHooks] = useState<SubmitHookType>({
|
|
|
|
|
[languageProfileKey]: (value) => JSON.stringify(value),
|
|
|
|
|
[enabledLanguageKey]: (value: Language.Info[]) => value.map((v) => v.code2),
|
|
|
|
|
});
|
|
|
|
|
const [submitHooks, setSubmitHooks] = useState<SubmitHookType>({});
|
|
|
|
|
const hooksRef = useRef(submitHooks);
|
|
|
|
|
hooksRef.current = submitHooks;
|
|
|
|
|
|
|
|
|
|
const invokeHooks = useCallback((settings: LooseObject) => {
|
|
|
|
|
const hooks = hooksRef.current;
|
|
|
|
|
for (const key in settings) {
|
|
|
|
|
if (key in hooks) {
|
|
|
|
|
LOG("info", "Running submit hook for", key, settings[key]);
|
|
|
|
|
const value = settings[key];
|
|
|
|
|
const fn = hooks[key];
|
|
|
|
|
settings[key] = fn(value);
|
|
|
|
|
LOG("info", "Finish submit hook", key, settings[key]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}, []);
|
|
|
|
@ -78,7 +99,10 @@ export function useSubmitHooksSource(): SubmitHookModifierType {
|
|
|
|
|
const removeHook = useCallback((key: string) => {
|
|
|
|
|
setSubmitHooks((hooks) => {
|
|
|
|
|
const newHooks = { ...hooks };
|
|
|
|
|
delete newHooks[key];
|
|
|
|
|
|
|
|
|
|
if (key in newHooks) {
|
|
|
|
|
delete newHooks[key];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return newHooks;
|
|
|
|
|
});
|
|
|
|
|