Browse Source

Make delegate change event more adaptable

Allow delegate change event to other elements like select and textarea.
pull/1/head
TheoryOfNekomata 1 year ago
parent
commit
96c93cc7d6
1 changed files with 21 additions and 9 deletions
  1. +21
    -9
      packages/web/kitchen-sink/react-next/src/utils/event.ts

+ 21
- 9
packages/web/kitchen-sink/react-next/src/utils/event.ts View File

@@ -1,13 +1,25 @@
const TAG_NAME_ELEMENT_CONSTRUCTOR = {
'INPUT': window.HTMLInputElement,
'SELECT': window.HTMLSelectElement,
'TEXTAREA': window.HTMLTextAreaElement,
} as const;

export const delegateTriggerChangeEvent = <T extends HTMLElement>(target: T, value?: unknown) => {
if (target.tagName === 'INPUT') {
const inputTarget = target as unknown as HTMLInputElement;
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;
if (nativeInputValueSetter) {
if (inputTarget.type !== 'file') {
nativeInputValueSetter.call(inputTarget, value);
}
const simulatedEvent = new Event('change', {bubbles: true});
inputTarget.dispatchEvent(simulatedEvent);
const { [target.tagName as keyof typeof TAG_NAME_ELEMENT_CONSTRUCTOR]: elementCtor } = TAG_NAME_ELEMENT_CONSTRUCTOR;

if (!elementCtor) {
return;
}

const nativeInputValueSetter = Object.getOwnPropertyDescriptor(elementCtor.prototype, 'value')?.set;
if (nativeInputValueSetter) {
if (
(target.tagName === 'INPUT' && (target as unknown as HTMLInputElement).type !== 'file')
|| target.tagName !== 'INPUT'
) {
nativeInputValueSetter.call(target, value);
}
const simulatedEvent = new Event('change', { bubbles: true });
target.dispatchEvent(simulatedEvent);
}
}

Loading…
Cancel
Save