2024-03-02 17:29:18 +02:00
|
|
|
import { OnClick, OnInputChange } from './types';
|
2023-08-21 17:01:20 +02:00
|
|
|
import { useEffect } from 'react';
|
|
|
|
|
2024-03-02 17:29:18 +02:00
|
|
|
const useItemEventHandlers = (rootElement: HTMLDivElement, itemElement: HTMLDivElement, onInputChange: OnInputChange, onClick: OnClick) => {
|
2023-08-21 17:01:20 +02:00
|
|
|
useEffect(() => {
|
|
|
|
if (!itemElement) return () => {};
|
|
|
|
|
|
|
|
const inputs = itemElement.getElementsByTagName('input');
|
|
|
|
|
2024-03-02 17:29:18 +02:00
|
|
|
const processedCheckboxes: HTMLInputElement[] = [];
|
|
|
|
const processedTextInputs: HTMLInputElement[] = [];
|
2023-08-21 17:01:20 +02:00
|
|
|
|
|
|
|
for (const input of inputs) {
|
|
|
|
if (input.type === 'checkbox') {
|
2023-09-18 18:40:36 +02:00
|
|
|
input.addEventListener('change', onInputChange as any);
|
2024-03-02 17:29:18 +02:00
|
|
|
processedCheckboxes.push(input);
|
2023-09-18 18:40:36 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if (input.type === 'text') {
|
|
|
|
input.addEventListener('change', onInputChange as any);
|
2024-03-02 17:29:18 +02:00
|
|
|
processedTextInputs.push(input);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const buttons = itemElement.getElementsByTagName('button');
|
|
|
|
const processedButtons: HTMLButtonElement[] = [];
|
|
|
|
|
|
|
|
if (onClick) {
|
|
|
|
for (const button of buttons) {
|
|
|
|
button.addEventListener('click', onClick as any);
|
|
|
|
processedButtons.push(button);
|
2023-08-21 17:01:20 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return () => {
|
2024-03-02 17:29:18 +02:00
|
|
|
for (const input of processedCheckboxes) {
|
2023-09-18 18:40:36 +02:00
|
|
|
input.removeEventListener('change', onInputChange as any);
|
|
|
|
}
|
|
|
|
|
2024-03-02 17:29:18 +02:00
|
|
|
for (const input of processedTextInputs) {
|
2023-09-18 18:40:36 +02:00
|
|
|
input.removeEventListener('change', onInputChange as any);
|
2023-08-21 17:01:20 +02:00
|
|
|
}
|
2024-03-02 17:29:18 +02:00
|
|
|
|
|
|
|
for (const button of processedButtons) {
|
|
|
|
button.removeEventListener('click', onClick as any);
|
|
|
|
}
|
2023-08-21 17:01:20 +02:00
|
|
|
};
|
2024-03-02 17:29:18 +02:00
|
|
|
}, [itemElement, rootElement, onInputChange, onClick]);
|
2023-08-21 17:01:20 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
export default useItemEventHandlers;
|