"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Field = void 0;
exports.makeFieldInputEventHandler = makeFieldInputEventHandler;
const identity_1 = require("../util/identity");
const html_1 = require("./html");
const propHandler_1 = require("./propHandler");
function makeFieldInputEventHandler(component, keyName = 'value', processValue = identity_1.identity) {
    return function (event) {
        const value = this[keyName];
        event.preventDefault();
        event.stopImmediatePropagation();
        const nextValue = processValue(component.$element, value);
        component.set('value', nextValue);
        component.dispatchEvent(event.type, nextValue);
    };
}
class Field extends html_1.default {
    constructor($props, $system, $element, opt) {
        super($props, $system, $element, opt.defaultStyle);
        const { valueKey, defaultStyle, defaultValue = '', processValue = ($element, value) => value, parseValue = identity_1.identity, } = opt;
        let { style, attr, value = defaultValue } = $props;
        style = { ...defaultStyle, ...style };
        this.$element[valueKey] = value;
        const isInput = $element instanceof HTMLInputElement ||
            $element instanceof HTMLTextAreaElement ||
            $element instanceof HTMLSelectElement;
        const inputEventHandler = makeFieldInputEventHandler(this, valueKey, processValue);
        this.$element.addEventListener('change', inputEventHandler);
        this.$element.addEventListener('input', inputEventHandler);
        this.$propHandler = {
            ...this.$propHandler,
            ...(isInput
                ? (0, propHandler_1.inputPropHandler)(this.$element, valueKey, defaultValue, parseValue)
                : {
                    value: (value) => {
                        const value_ = parseValue(value);
                        this.$element[valueKey] = value_ !== null && value_ !== void 0 ? value_ : '';
                    },
                }),
        };
    }
}
exports.Field = Field;
//# sourceMappingURL=field.js.map