karusic/front2/src/components/form/Formidable.tsx
2024-09-01 16:08:06 +02:00

74 lines
2.0 KiB
TypeScript

import { useCallback, useMemo, useState } from 'react';
const getDifferences = (obj1: any, obj2: any): { [key: string]: boolean } => {
const result: { [key: string]: boolean } = {};
for (const key in obj1) {
if (obj1.hasOwnProperty(key)) {
result[key] = obj1[key] !== obj2[key];
}
}
return result;
};
const hasAnyTrue = (obj: { [key: string]: boolean }): boolean => {
for (const key in obj) {
if (obj.hasOwnProperty(key) && obj[key] === true) {
return true;
}
}
return false;
};
// const onChangeValue = (key: string, data) => {
// console.log(`[${key}] data: ${data}`);
// setNewData((previous) => {
// if (previous === undefined) {
// return previous;
// }
// if (previous[key] === data) {
// return previous;
// }
// const tmp = { ...previous };
// tmp[key] = data;
// console.log(`data = ${JSON.stringify(tmp, null, 2)}`);
// return tmp;
// });
// };
export const useFormidable = <TYPE = object,>({
initialValues = {} as TYPE,
}: {
initialValues?: TYPE;
}) => {
const [values, setValues] = useState<TYPE>({ ...initialValues } as TYPE);
const initialData = useMemo<TYPE>(() => {
setValues({ ...initialValues } as TYPE);
return { ...initialValues } as TYPE;
}, [initialValues, setValues]);
const [valueChange, setValueChange] = useState<{ [key: string]: boolean }>(
{}
);
const [isFormModified, setIsFormModified] = useState<boolean>(false);
const setValuesExternal = useCallback(
(data: object) => {
setValues((previous) => {
const newValues = { ...previous, ...data };
const ret = getDifferences(initialData, values);
setValueChange(ret);
setIsFormModified(hasAnyTrue(ret));
console.log(
` ppppppppppppppppppp ${JSON.stringify(ret, null, 2)} ==> ${hasAnyTrue(ret)}`
);
return newValues;
});
},
[setValues, initialData]
);
return {
values,
valueChange,
isFormModified,
setValues: setValuesExternal,
};
};