2022-06-30 15:35:23 +00:00
|
|
|
import { LOG } from "@/utilities/console";
|
2022-09-20 20:50:18 +00:00
|
|
|
import type { UseFormReturnType } from "@mantine/form";
|
2022-05-31 15:49:04 +00:00
|
|
|
import { createContext, useCallback, useContext, useRef } from "react";
|
|
|
|
|
2022-09-20 20:50:18 +00:00
|
|
|
export const FormContext = createContext<UseFormReturnType<FormValues> | null>(
|
|
|
|
null
|
|
|
|
);
|
2022-05-31 15:49:04 +00:00
|
|
|
|
|
|
|
export function useFormValues() {
|
|
|
|
const context = useContext(FormContext);
|
|
|
|
|
|
|
|
if (context === null) {
|
|
|
|
throw new Error("useFormValues must be used within a FormContext");
|
|
|
|
}
|
|
|
|
|
|
|
|
return context;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function useStagedValues() {
|
|
|
|
const form = useFormValues();
|
2022-11-20 16:23:55 +00:00
|
|
|
return { ...form.values.settings };
|
2022-05-31 15:49:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function useFormActions() {
|
|
|
|
const form = useFormValues();
|
|
|
|
|
|
|
|
const formRef = useRef(form);
|
|
|
|
formRef.current = form;
|
|
|
|
|
2022-11-20 16:23:55 +00:00
|
|
|
const update = useCallback((object: LooseObject) => {
|
|
|
|
LOG("info", `Updating values`, object);
|
|
|
|
formRef.current.setValues((values) => {
|
|
|
|
const changes = { ...values.settings, ...object };
|
|
|
|
return { ...values, settings: changes };
|
|
|
|
});
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
const setValue = useCallback((v: unknown, key: string) => {
|
|
|
|
LOG("info", `Updating value of ${key}`, v);
|
|
|
|
formRef.current.setValues((values) => {
|
|
|
|
const changes = { ...values.settings, [key]: v };
|
|
|
|
return { ...values, settings: changes };
|
|
|
|
});
|
|
|
|
}, []);
|
2022-05-31 15:49:04 +00:00
|
|
|
|
|
|
|
return { update, setValue };
|
|
|
|
}
|
|
|
|
|
|
|
|
export type FormKey = keyof FormValues;
|
|
|
|
export type FormValues = {
|
|
|
|
// Settings that saved to the backend
|
|
|
|
settings: LooseObject;
|
|
|
|
// Settings that saved to the frontend
|
2022-11-20 16:23:55 +00:00
|
|
|
// storages: LooseObject;
|
2022-05-31 15:49:04 +00:00
|
|
|
};
|