2022-01-05 11:34:43 +01:00
|
|
|
import { useRef, useCallback, useMemo, useState } from 'react';
|
|
|
|
import { fire } from '@utils';
|
2021-06-09 17:13:26 +02:00
|
|
|
|
|
|
|
export function useDeferredSubmit(input) {
|
|
|
|
const calledRef = useRef(false);
|
|
|
|
const awaitFormSubmit = useCallback(
|
|
|
|
(callback) => {
|
2021-07-06 15:06:38 +02:00
|
|
|
const form = input?.form;
|
2021-06-09 17:13:26 +02:00
|
|
|
if (!form) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const interceptFormSubmit = (event) => {
|
|
|
|
event.preventDefault();
|
|
|
|
runCallback();
|
|
|
|
form.submit();
|
|
|
|
};
|
|
|
|
calledRef.current = false;
|
|
|
|
form.addEventListener('submit', interceptFormSubmit);
|
|
|
|
const runCallback = () => {
|
|
|
|
form.removeEventListener('submit', interceptFormSubmit);
|
|
|
|
clearTimeout(timer);
|
|
|
|
if (!calledRef.current) {
|
|
|
|
callback();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
const timer = setTimeout(runCallback, 400);
|
|
|
|
},
|
|
|
|
[input]
|
|
|
|
);
|
|
|
|
awaitFormSubmit.done = () => {
|
|
|
|
calledRef.current = true;
|
|
|
|
};
|
|
|
|
return awaitFormSubmit;
|
|
|
|
}
|
2022-01-05 11:34:43 +01:00
|
|
|
|
|
|
|
export function groupId(id) {
|
|
|
|
return `#champ-${id.replace(/-input$/, '')}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function useHiddenField(group, name = 'value') {
|
|
|
|
const hiddenField = useMemo(
|
|
|
|
() => selectInputInGroup(group, name),
|
|
|
|
[group, name]
|
|
|
|
);
|
|
|
|
const [value, setValue] = useState(() => hiddenField?.value);
|
|
|
|
|
|
|
|
return [
|
|
|
|
value,
|
|
|
|
(value) => {
|
|
|
|
if (hiddenField) {
|
|
|
|
hiddenField.setAttribute('value', value);
|
|
|
|
setValue(value);
|
|
|
|
fire(hiddenField, 'autosave:trigger');
|
|
|
|
}
|
|
|
|
},
|
|
|
|
hiddenField
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
function selectInputInGroup(group, name) {
|
|
|
|
if (group) {
|
|
|
|
return document.querySelector(
|
|
|
|
`${group} input[type="hidden"][name$="[${name}]"], ${group} input[type="hidden"][name="${name}"]`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|