"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Field = exports.makeFieldInputEventHandler = void 0;
const identity_1 = require("../util/identity");
const element_1 = require("./element");
const propHandler_1 = require("./propHandler");
const style_1 = require("./style");
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);
    };
}
exports.makeFieldInputEventHandler = makeFieldInputEventHandler;
class Field extends element_1.Element {
    constructor($props, $system, $element, opt) {
        super($props, $system);
        const { valueKey, defaultStyle, defaultValue = '', processValue = ($element, value) => value, } = opt;
        let { style = {}, value = defaultValue } = $props;
        style = Object.assign(Object.assign({}, defaultStyle), style);
        this.$element = $element;
        this.$element[valueKey] = value;
        (0, style_1.applyStyle)($element, style);
        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._prop_handler = Object.assign(Object.assign({}, (0, propHandler_1.htmlPropHandler)(this, this.$element, defaultStyle)), (isInput
            ? (0, propHandler_1.inputPropHandler)(this.$element, valueKey, defaultValue)
            : {
                value: (value) => {
                    this.$element[valueKey] = value;
                },
            }));
    }
    onPropChanged(prop, current) {
        this._prop_handler[prop](current);
    }
}
exports.Field = Field;
//# sourceMappingURL=field.js.map