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