"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TagInputComponent = void 0;
const React = __importStar(require("react"));
const react_dom_1 = require("react-dom");
const PropTypes = __importStar(require("prop-types"));
const utils_1 = require("../../utils");
const memoizee_1 = __importDefault(require("memoizee"));
class TagArrayField extends React.Component {
    render() {
        const { FieldTemplate } = this.props.registry.templates;
        const { uiSchema } = this.props;
        return (React.createElement(FieldTemplate, Object.assign({}, this.props, { forceDisplayLabel: true, rawHelp: uiSchema["ui:help"], description: uiSchema["ui:description"], rawErrors: [], id: this.props.idSchema.$id }),
            React.createElement(TagInputComponent, Object.assign({}, this.props, { id: this.props.idSchema.$id, tags: this.props.formData }))));
    }
}
TagArrayField.propTypes = {
    uiSchema: PropTypes.shape({
        "ui:options": PropTypes.shape({
            separatorKeys: PropTypes.arrayOf(PropTypes.string),
            showDeleteButton: PropTypes.bool,
            showAsLink: PropTypes.bool,
            linkPrefix: PropTypes.string,
            replacements: PropTypes.arrayOf(PropTypes.shape({
                searchRegexp: PropTypes.string.isRequired,
                replaceValue: PropTypes.string.isRequired
            }))
        })
    }),
    schema: PropTypes.shape({
        type: PropTypes.oneOf(["array"])
    }).isRequired,
    formData: PropTypes.array
};
exports.default = TagArrayField;
class TagInputComponent extends React.Component {
    constructor(props) {
        super(props);
        this.getStateFromProps = ({ value }) => {
            return { value };
        };
        this.getSeparatorKeys = (uiSchema) => {
            const { separatorKeys = ["Enter", ",", ";"] } = (0, utils_1.getUiOptions)(uiSchema);
            return separatorKeys;
        };
        this.onKeyDown = (e) => {
            const value = this.processValue(this.state.value);
            const { tags = [] } = this.props;
            const separatorKeys = this.getSeparatorKeys(this.props.uiSchema);
            if (separatorKeys.includes(e.key) && !(0, utils_1.isEmptyString)(value)) {
                this.props.onChange([...tags, value], "enter");
                e.stopPropagation();
                e.preventDefault();
            }
            else if (e.key === "Backspace" && (0, utils_1.isEmptyString)(value) && tags.length) {
                this.onRemove(tags.length - 1)();
            }
            (0, utils_1.triggerParentComponent)("onKeyDown", e, this.props);
        };
        this.onRemove = (0, memoizee_1.default)((idx) => () => {
            const tags = [...(this.props.tags || [])];
            tags.splice(idx, 1);
            this.props.onChange(tags, "remove");
        });
        this.onFocus = (e) => {
            this.setState({ focused: true }, () => {
                (0, utils_1.triggerParentComponent)("onFocus", e, this.props);
            });
        };
        this.onBlur = (e) => {
            this.setState({ focused: false });
            (0, utils_1.triggerParentComponent)("onBlur", e, this.props);
            const value = this.processValue(this.state.value);
            if (!(0, utils_1.isEmptyString)(value)) {
                this.props.onChange([...(this.props.tags || []), value], "blur");
            }
        };
        this.setInputRef = (ref) => {
            this.inputRef = ref;
        };
        this.onClick = () => {
            (0, react_dom_1.findDOMNode)(this.inputRef).focus();
        };
        this.onInputChange = (e) => {
            const { onInputChange } = this.props;
            onInputChange && e.persist();
            const { target: { value } } = e;
            const separatorKeys = this.getSeparatorKeys(this.props.uiSchema);
            const splitted = separatorKeys.reduce((splitted, separator) => splitted.reduce((_splitted, i) => ([..._splitted, ...i.split(separator)]), []), [value]).map(s => this.processValue(s)).filter(s => !(0, utils_1.isEmptyString)(s));
            this.setState({ value }, () => {
                onInputChange && this.props.onInputChange(e);
                if (splitted.length > 1) {
                    this.props.onChange([...(this.props.tags || []), ...splitted]);
                }
            });
        };
        this.onTagClick = (0, memoizee_1.default)((idx) => (e) => {
            const { onTagClick } = (0, utils_1.getUiOptions)(this.props.uiSchema);
            onTagClick === null || onTagClick === void 0 ? void 0 : onTagClick(idx, e);
        });
        this.state = this.getStateFromProps(props);
    }
    UNSAFE_componentWillReceiveProps(props) {
        this.setState(this.getStateFromProps(props));
    }
    processValue(value) {
        if (!value) {
            return value;
        }
        value = value.trim();
        const { replacements = [] } = (0, utils_1.getUiOptions)(this.props.uiSchema);
        replacements.forEach(replacement => {
            value = value.replace(new RegExp(replacement.searchRegexp), replacement.replaceValue);
        });
        return value;
    }
    render() {
        let { tags = [], InputComponent, readonly, disabled, uiSchema } = this.props;
        tags = tags.filter(s => !(0, utils_1.isEmptyString)(s));
        const { value = "" } = this.state;
        const inputProps = Object.assign(Object.assign({ type: "text", className: "rw-input-reset", ref: this.setInputRef, value: value, onChange: this.onInputChange, id: this.props.id }, this.props.inputProps), { onFocus: this.onFocus, onBlur: this.onBlur, onKeyDown: this.onKeyDown });
        const { showDeleteButton = true, showAsLink = false, linkPrefix = "" } = (0, utils_1.getUiOptions)(uiSchema);
        const tagElems = tags.map(item => {
            if (showAsLink) {
                return React.createElement("a", { href: `${linkPrefix}${item}`, target: "_blank", rel: "noopener noreferrer" }, item);
            }
            return item;
        });
        return (React.createElement("div", { className: `rw-multiselect rw-widget${this.state.focused ? " rw-state-focus" : ""}${(readonly || disabled) ? " rw-state-disabled" : ""}`, onClick: this.onClick },
            React.createElement("div", { className: "rw-widget-input rw-widget-picked rw-widget-container" },
                React.createElement("ul", { className: "rw-multiselect-taglist" }, tagElems.map((item, idx) => React.createElement("li", { key: idx, className: "rw-multiselect-tag", onClick: this.onTagClick(idx) },
                    item,
                    showDeleteButton ? React.createElement("span", { className: "rw-tag-btn", onClick: this.onRemove(idx), tabIndex: 0, onKeyDown: this.props.formContext.utils.keyboardClick(this.onRemove(idx)) }, "\u00D7") : ""))),
                InputComponent ? React.createElement(InputComponent, Object.assign({}, inputProps)) : React.createElement("input", Object.assign({}, inputProps, { disabled: disabled || readonly })))));
    }
}
exports.TagInputComponent = TagInputComponent;
