From 7a2ea6b6903ca72bc1bb37dd6d5d5fa6981a6ca3 Mon Sep 17 00:00:00 2001 From: TheoryOfNekomata Date: Sun, 12 Mar 2023 15:31:10 +0800 Subject: [PATCH] Minor refactor Isolate generic input setting value to its own function. --- src/index.ts | 44 +++++++++++++++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/src/index.ts b/src/index.ts index 0376d76..781bb4d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -684,18 +684,41 @@ const getInputFieldValue = ( break; } - // don't force returning `null` for custom elements supporting setting values. return inputEl.value; }; +/** + * Sets the value of a generic `` element. + * @param inputEl - The element. + * @param value - Value of the input element. + * @param nthOfName - What order is this field in with respect to fields of the same name? + * @param elementsWithSameName - How many fields with the same name are in the form? + */ +const setInputGenericFieldValue = ( + inputEl: HTMLInputElement, + value: unknown, + nthOfName: number, + elementsWithSameName: HTMLInputElement[], +) => { + if (Array.isArray(value) && elementsWithSameName.length > 1) { + // eslint-disable-next-line no-param-reassign + inputEl.value = value[nthOfName]; + return; + } + + // eslint-disable-next-line no-param-reassign + inputEl.value = value as string; +}; + /** * Sets the value of an `` element. + * + * **Note:** This function is a noop for `` because by design, file inputs are + * not assignable programmatically. * @param inputEl - The element. * @param value - Value of the input element. * @param nthOfName - What order is this field in with respect to fields of the same name? * @param elementsWithSameName - How many fields with the same name are in the form? - * @note This function is a noop for `` because by design, file inputs are not - * assignable programmatically. */ const setInputFieldValue = ( inputEl: HTMLInputElement, @@ -745,14 +768,7 @@ const setInputFieldValue = ( break; } - if (Array.isArray(value) && elementsWithSameName.length > 1) { - // eslint-disable-next-line no-param-reassign - inputEl.value = value[nthOfName]; - return; - } - - // eslint-disable-next-line no-param-reassign - inputEl.value = value as string; + setInputGenericFieldValue(inputEl, value, nthOfName, elementsWithSameName); }; /** @@ -984,6 +1000,12 @@ export const getFormValues = (form: HTMLFormElement, options = {} as GetFormValu return fieldValues; }; +/** + * Normalizes input for setting form values. + * @param values - The values as they are provided to set. + * @returns The normalized values. + * @see setFormValues + */ const normalizeValues = (values: unknown): Record => { if (typeof values === 'string') { return Object.fromEntries(new URLSearchParams(values).entries());