import { HTMLFieldElement } from "../types/dom";
const DataMappers = {
'text' : (x: string) => x,
'number' : (x: string) => Number(x),
'date' : (x: string) => new Date(x),
} as const;
const ElementMappers = {
'text' : (e: HTMLInputElement) => e.value ?? e.innerText,
'number' : (e: HTMLInputElement) => e.valueAsNumber,
'range' : (e: HTMLInputElement) => e.valueAsNumber,
'date' : (e: HTMLInputElement) => e.valueAsDate,
'datetime-local' : (e: HTMLInputElement) => new Date(e.value),
'checkbox' : (e: HTMLInputElement) => e.checked,
'radio' : (e: HTMLInputElement) => e.checked && (DataMappers[e.dataset.type as keyof typeof DataMappers]?.(e.value) ?? e.value) || undefined,
'select-one' : (e: HTMLSelectElement) => DataMappers[(e.options[e.selectedIndex].dataset.type ?? e.dataset.type) as keyof typeof DataMappers]?.(e.value) ?? e.value,
'select-multiple' : (e: HTMLSelectElement) => [...e.options].filter(o => o.selected).map(o => (DataMappers[o.dataset.type as keyof typeof DataMappers ?? e.dataset.type as keyof typeof DataMappers] ?? DataMappers.text)(o.value)),
} as const;
/**
* Get the value of an element matching its type:
* boolean, number, date or string,
* or innerText if it's any other (e.g.: [contenteditable]) element
**/
export const autoValue = (e: HTMLFieldElement) =>
(ElementMappers[(e.type ?? (e as HTMLFieldElement).dataset?.type) as keyof typeof ElementMappers] ?? ElementMappers.text)
(e as HTMLInputElement & HTMLSelectElement)
;