"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 });
const React = __importStar(require("react"));
const react_dom_1 = require("react-dom");
const PropTypes = __importStar(require("prop-types"));
const validation_1 = __importStar(require("../validation"));
const validation_2 = require("../validation");
const components_1 = require("./components");
const utils_1 = require("../utils");
const equals = require("deep-equal");
const validator_ajv6_1 = __importDefault(require("@rjsf/validator-ajv6"));
const deepmerge_1 = __importDefault(require("deepmerge"));
const ReactContext_1 = __importDefault(require("../ReactContext"));
const stub_1 = __importDefault(require("../themes/stub"));
const core_1 = __importDefault(require("@rjsf/core"));
const ApiClient_1 = __importDefault(require("../ApiClient"));
const Context_1 = __importDefault(require("../Context"));
const translations_json_1 = __importDefault(require("../translations.json"));
const key_handler_service_1 = __importDefault(require("../services/key-handler-service"));
const settings_service_1 = __importDefault(require("../services/settings-service"));
const focus_service_1 = __importDefault(require("../services/focus-service"));
const blocker_service_1 = __importDefault(require("../services/blocker-service"));
const custom_event_service_1 = __importDefault(require("../services/custom-event-service"));
const submit_hook_service_1 = __importDefault(require("../services/submit-hook-service"));
const dom_id_service_1 = __importDefault(require("../services/dom-id-service"));
const id_service_1 = __importDefault(require("../services/id-service"));
const root_instance_service_1 = __importDefault(require("../services/root-instance-service"));
const singleton_map_service_1 = __importDefault(require("../services/singleton-map-service"));
const multi_active_array_service_1 = __importDefault(require("../services/multi-active-array-service"));
const fields = __importStar(require("./fields"));
const widgets = __importStar(require("./widgets"));
const templates = __importStar(require("./templates"));
const mac_shortcuts_json_1 = __importDefault(require("../mac-shortcuts.json"));
// Each form should have a unique id to keep Context private.
let id = 0;
function getNewId() {
    const _id = id;
    id++;
    return _id;
}
class LajiForm extends React.Component {
    constructor(props) {
        super(props);
        this.translations = this.constructTranslations();
        this.bgJobRef = React.createRef();
        this.shortcutHelpRef = React.createRef();
        this.propagateSubmit = true;
        this.formRef = React.createRef();
        this.validating = false;
        this.eventListeners = [];
        this.timeouts = [];
        this.onSubmitHooksChange = (submitHooks, callback) => {
            this.setState({ submitHooks }, callback);
        };
        this.getDefaultNotifier = () => {
            if (this.defaultNotifier)
                return this.defaultNotifier;
            this.defaultNotifier = ["success", "info", "warning", "error"].reduce((notifier, method) => {
                notifier[method] = msg => console.warn(`Notification component not specified for LajiForm! Got '${method}'notification: '${msg}'`);
                return notifier;
            }, {});
            return this.defaultNotifier;
        };
        this.onChange = ({ formData }) => {
            this.setState({ formData }, () => {
                if (this.props.onChange) {
                    const _formData = this.props.optimizeOnChange
                        ? formData
                        : this.memoizedFormContext.services.ids.removeLajiFormIds(formData);
                    this.props.onChange(_formData);
                }
                this.memoizedFormContext.services.ids.setFormData(formData);
                this.memoizedFormContext.services.rootInstance.setFormData(formData);
                !this.validating && this.validate(true, false);
            });
        };
        this.getFields = (_fields) => (Object.assign(Object.assign({}, fields), (_fields || {})));
        this.getWidgets = (_widgets) => (Object.assign(Object.assign({}, widgets), (_widgets || {})));
        this.getTemplates = (_templates) => (Object.assign(Object.assign({}, templates), (_templates || {})));
        this.getContext = (props, context) => {
            const nextKey = ["theme"].reduce((key, prop) => {
                key[prop] = props[prop];
                return key;
            }, {});
            if (this.contextMemoizeKey && Object.keys(this.contextMemoizeKey).every(k => this.contextMemoizeKey[k] === nextKey[k])) {
                return this.memoizedContext;
            }
            else {
                this.contextMemoizeKey = nextKey;
                this.memoizedContext = {
                    theme: props.theme || (context === null || context === void 0 ? void 0 : context.theme) || stub_1.default,
                };
                return this.memoizedContext;
            }
        };
        this.renderSubmitHooks = () => {
            if (!this.state || !this.state.submitHooks)
                return;
            const jobsAmount = this.state.submitHooks.filter(({ failed }) => !failed).length;
            const runningAmount = this.state.submitHooks.reduce((count, { running }) => running ? count + 1 : count, 0);
            if (!this.state.runningSubmitHooks)
                return null;
            const { ProgressBar } = this.getContext(this.props, this.context).theme;
            return (React.createElement("div", { className: "running-jobs" },
                this.state.formContext.translations.PendingRunningJobs,
                "... (",
                jobsAmount - runningAmount + 1,
                " / ",
                jobsAmount,
                ")",
                React.createElement(ProgressBar, { now: 100 / jobsAmount * (jobsAmount - runningAmount) })));
        };
        this.validateAndSubmit = (warnings = true, onlySchema = false) => {
            const { formData } = this.state;
            const { onValidationError, onSubmit } = this.props;
            this.setState({ externalErrors: undefined });
            return this.validate(warnings, true, onlySchema).then(valid => {
                if (formData !== this.state.formData) {
                    this.validateAndSubmit(warnings, onlySchema);
                }
                else if (valid) {
                    onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit({ formData: removeUndefinedFromArrays(this.memoizedFormContext.services.ids.removeLajiFormIds(formData)) });
                }
                else {
                    onValidationError && onValidationError(this.state.extraErrors);
                }
            });
        };
        this.validate = (warnings = true, nonlive = true, onlySchema = false) => {
            this.validating = true;
            let live = true;
            if (onlySchema) {
                warnings = false;
                nonlive = false;
                live = false;
            }
            const block = nonlive || onlySchema;
            const { formData } = this.state;
            const { live: liveErrorValidators, rest: errorValidators } = splitLive(this.props.validators, this.props.schema.properties);
            const { live: liveWarningValidators, rest: warningValidators } = splitLive(this.props.warnings, this.props.schema.properties);
            let liveValidations = { errors: liveErrorValidators };
            const validations = {};
            if (!onlySchema && nonlive) {
                validations.errors = errorValidators;
            }
            if (!onlySchema && warnings) {
                liveValidations.warnings = liveWarningValidators;
                if (nonlive) {
                    validations.warnings = warningValidators;
                }
            }
            if (!live) {
                liveValidations = {};
            }
            const schemaErrors = nonlive || onlySchema
                ? this.getSchemaValidationErrors(formData)
                : {};
            block && this.memoizedFormContext.services.blocker.push();
            return new Promise(resolve => Promise.all([(0, validation_1.default)(validations, formData), (0, validation_1.default)(liveValidations, formData)]).then(([_validations, _liveValidations]) => {
                if (nonlive || onlySchema) {
                    this.cachedNonliveValidations = (0, deepmerge_1.default)(schemaErrors, _validations);
                    block && this.memoizedFormContext.services.blocker.pop();
                }
                const mergedInternalErrors = (0, deepmerge_1.default)(_liveValidations, !nonlive
                    ? (this.cachedNonliveValidations || {})
                    : (0, deepmerge_1.default)(_validations, schemaErrors));
                const mergedAll = (0, deepmerge_1.default)(this.state.externalErrors || {}, mergedInternalErrors);
                this.validating = false;
                resolve(!Object.keys(mergedAll).length);
                if (!equals((this.state.extraErrors || {}), mergedAll)) {
                    this.setState({ extraErrors: mergedAll }, this.popErrorListIfNeeded);
                }
            }).catch((e) => {
                block && this.memoizedFormContext.services.blocker.pop();
                throw e;
            }));
            function splitLive(validators = {}, schema, live = {}, rest = {}) {
                Object.keys(validators).forEach(key => {
                    if (schema[key]) {
                        live[key] = {};
                        rest[key] = {};
                        splitLive(validators[key], schema[key], live[key], rest[key]);
                        if (Object.keys(live[key]).length === 0)
                            delete live[key];
                        if (Object.keys(rest[key]).length === 0)
                            delete rest[key];
                    }
                    else {
                        const container = validators[key].options && validators[key].options._live ? live : rest;
                        container[key] = validators[key];
                    }
                });
                return { live, rest };
            }
        };
        this.onSubmit = (onlySchemaValidations) => {
            const _onlySchemaValidations = onlySchemaValidations === "onlySchemaValidations";
            const { uiSchema } = this.props;
            if (uiSchema["ui:disabled"] || uiSchema["ui:readonly"]) {
                return false;
            }
            this.memoizedFormContext.services.blocker.push();
            this.setState({ runningSubmitHooks: true });
            this.memoizedFormContext.services.submitHooks.checkHooks().then(() => {
                this.memoizedFormContext.services.blocker.pop();
                this.setState({ runningSubmitHooks: false });
                this.validateAndSubmit(!_onlySchemaValidations, _onlySchemaValidations);
            }).catch(() => {
                var _a;
                this.setState({ runningSubmitHooks: false });
                this.memoizedFormContext.services.blocker.pop();
                (0, utils_1.highlightElem)((0, react_dom_1.findDOMNode)((_a = this.bgJobRef) === null || _a === void 0 ? void 0 : _a.current));
            });
            return undefined;
        };
        this.popErrorListIfNeeded = () => {
            const errorList = this.memoizedFormContext.services.rootInstance.getErrorListInstance();
            let errorListElem;
            try {
                errorListElem = (0, react_dom_1.findDOMNode)(errorList);
            }
            catch (e) {
                // Empty
            }
            if (!errorListElem)
                return;
            const wouldScrollTo = (0, utils_1.getScrollPositionForScrollIntoViewIfNeeded)(errorListElem, this.props.topOffset, this.props.bottomOffset) || 0;
            const scrollAmount = wouldScrollTo - (0, utils_1.getWindowScrolled)();
            if (!errorList.state.poppedTouched && scrollAmount !== 0) {
                errorList.expand();
            }
            (0, utils_1.highlightElem)(errorListElem);
        };
        this._onDefaultSubmit = (e) => {
            e.preventDefault();
            this.submit();
        };
        this.submit = () => {
            this.onSubmit();
        };
        this.submitOnlySchemaValidations = () => {
            this.onSubmit("onlySchemaValidations");
        };
        this.getShorcutButtonTooltip = () => {
            const { translations } = this.state.formContext;
            if (this.keyCombo) {
                return (0, utils_1.translate)(translations, "ShortcutHelp", { key: (0, utils_1.stringifyKeyCombo)(this.keyCombo) });
            }
            return undefined;
        };
        this.toggleHelp = (e) => {
            this.helpVisible ? this.dismissHelp(e) : this.showHelp();
        };
        this.showHelp = () => {
            const node = (0, react_dom_1.findDOMNode)(this.shortcutHelpRef.current);
            if (!this.helpVisible) {
                if (node)
                    node.className = node.className.replace(" hidden", "");
                this.helpVisible = true;
            }
        };
        this.dismissHelp = (e) => {
            const node = (0, react_dom_1.findDOMNode)(this.shortcutHelpRef.current);
            e.preventDefault();
            e.stopPropagation();
            if (this.helpVisible && node) {
                node.className += " hidden";
            }
            this.helpVisible = false;
            this.helpStarted = false;
            document.removeEventListener("keyup", this.dismissHelp);
            window.removeEventListener("blur", this.dismissHelp);
            clearTimeout(this.helpTimeout);
        };
        this.keyFunctions = {
            navigate: (e, { reverse }) => {
                return this.memoizedFormContext.services.focus.focusNextInput(reverse);
            },
            help: (e, { delay }) => {
                if (this.helpStarted)
                    return false;
                this.helpStarted = true;
                this.helpTimeout = window.setTimeout(() => {
                    this.showHelp();
                }, delay * 1000);
                this.addEventListener(document, "keyup", this.dismissHelp);
                this.addEventListener(window, "blur", this.dismissHelp);
                return false;
            },
            revalidate: () => {
                this.submit();
            }
        };
        this.pushBlockingLoader = () => {
            this.memoizedFormContext.services.blocker.push();
        };
        this.popBlockingLoader = () => {
            this.memoizedFormContext.services.blocker.pop();
        };
        this.focusField = (fieldName) => {
            const id = (0, utils_1.JSONPointerToId)(fieldName);
            this.memoizedFormContext.services.focus.focus("root_" + id);
        };
        this.openAllMultiActiveArrays = () => {
            this.memoizedFormContext.services.multiActiveArray.openAll();
        };
        this.closeAllMultiActiveArrays = () => {
            this.memoizedFormContext.services.multiActiveArray.closeAll();
        };
        this.onSettingsChange = (settings) => {
            if (this.props.onSettingsChange)
                this.props.onSettingsChange(settings);
        };
        this.addEventListener = (target, name, fn) => {
            target.addEventListener(name, fn);
            this.eventListeners.push([target, name, fn]);
        };
        this.setTimeout = (fn, time = 0) => {
            const timeout = window.setTimeout(fn, time);
            this.timeouts.push(timeout);
            return timeout;
        };
        this.destroy = () => {
            if (this.eventListeners)
                this.eventListeners.forEach(([target, name, fn]) => {
                    target.removeEventListener(name, fn);
                });
            if (this.timeouts)
                this.timeouts.forEach((timeout) => {
                    clearTimeout(timeout);
                });
            this.eventListeners = [];
        };
        this.getSchemaValidationErrors = (formData) => {
            const errors = validator_ajv6_1.default.validateFormData(removeUndefinedFromArrays(formData), this.props.schema, undefined, ((e) => (0, validation_2.transformErrors)(this.state.formContext.translations, e))).errors;
            return (0, validation_1.toErrorSchema)(errors);
        };
        if (props.apiClient) {
            this.apiClient = new ApiClient_1.default(props.apiClient, props.lang, this.translations);
        }
        (0, validation_2.initializeValidation)(this.apiClient);
        this._id = getNewId();
        this.getMemoizedFormContext(props); // Initialize form context.
        this.resetShortcuts(getShortcuts(props.uiSchema));
        this.state = this.getStateFromProps(props);
    }
    UNSAFE_componentWillReceiveProps(props) {
        if (props.apiClient && props.apiClient !== this.apiClient.apiClient) {
            this.apiClient = new ApiClient_1.default(props.apiClient, props.lang, this.translations);
        }
        if (this.apiClient && "lang" in props && this.props.lang !== props.lang) {
            this.apiClient.setLang(props.lang);
        }
        this.setState(this.getStateFromProps(props), this.popErrorListIfNeeded);
    }
    getStateFromProps(props) {
        var _a;
        const state = {
            formContext: this.getMemoizedFormContext(props),
            externalErrors: props.extraErrors,
            extraErrors: ((_a = this.state) === null || _a === void 0 ? void 0 : _a.extraErrors)
                ? (0, deepmerge_1.default)(this.state.extraErrors, props.extraErrors || {})
                : props.extraErrors
        };
        if (((!this.state && props.schema && Object.keys(props.schema).length) || (this.state && !("formData" in this.state))) || ("formData" in props && props.formData !== this.props.formData)) {
            state.formData = state.formContext.services.ids.addLajiFormIds((0, utils_1.getDefaultFormState)(props.schema, props.formData, props.schema))[0];
        }
        else if (this.state && this.formRef.current) {
            state.formData = this.formRef.current.state.formData;
        }
        if (this.state && props.schema !== this.props.schema) {
            state.extraErrors = {};
        }
        this.memoizedFormContext.services.ids.setFormData(state.formData);
        this.memoizedFormContext.services.rootInstance.setFormData(state.formData);
        return state;
    }
    getMemoizedFormContext(props) {
        const nextKey = ["lang", "topOffset", "bottomOffset", "formContext", "settings", "schema", "uiSchemaContext", "mediaMetadata", "lajiGeoServerAddress"].reduce((key, prop) => {
            key[prop] = props[prop];
            return key;
        }, {});
        if (this.contextFormMemoizeKey && Object.keys(this.contextFormMemoizeKey).every(k => this.contextFormMemoizeKey[k] === nextKey[k])) {
            return this.memoizedFormContext;
        }
        else {
            this.contextFormMemoizeKey = nextKey;
            const { services } = this.memoizedFormContext || {};
            this.memoizedFormContext = Object.assign(Object.assign({}, props.formContext), { translations: this.translations[props.lang], lang: props.lang, uiSchemaContext: props.uiSchemaContext || {}, topOffset: props.topOffset || 0, bottomOffset: props.bottomOffset || 0, contextId: this._id, formID: props.id, googleApiKey: props.googleApiKey, notifier: props.notifier || this.getDefaultNotifier(), apiClient: this.apiClient, Label: (props.fields || {}).Label || components_1.Label, mediaMetadata: props.mediaMetadata, setTimeout: this.setTimeout, services: {}, formRef: this.formRef, lajiGeoServerAddress: props.lajiGeoServerAddress, globals: (0, Context_1.default)(this._id) });
            this.memoizedFormContext.utils = (0, utils_1.ReactUtils)(this.memoizedFormContext);
            if (services) {
                this.memoizedFormContext.services = services;
                services.keyHandler.setFormContext(this.memoizedFormContext);
                services.focus.setFormContext(this.memoizedFormContext);
                services.settings.setSettings(props.settings);
                services.ids.setSchema(props.schema);
                services.rootInstance.setSchema(props.schema);
            }
            else {
                this.memoizedFormContext.services.keyHandler = new key_handler_service_1.default(this.memoizedFormContext);
                this.memoizedFormContext.services.settings = new settings_service_1.default(this.onSettingsChange, props.settings);
                this.memoizedFormContext.services.focus = new focus_service_1.default(this.memoizedFormContext);
                this.memoizedFormContext.services.blocker = new blocker_service_1.default(this.memoizedFormContext);
                this.memoizedFormContext.services.customEvents = new custom_event_service_1.default();
                this.memoizedFormContext.services.submitHooks = new submit_hook_service_1.default(this.onSubmitHooksChange);
                this.memoizedFormContext.services.DOMIds = new dom_id_service_1.default();
                this.memoizedFormContext.services.ids = new id_service_1.default(props.schema, props.formData);
                this.memoizedFormContext.services.rootInstance = new root_instance_service_1.default(props.schema, props.formData, (formData) => this.onChange({ formData }), this.validate, () => this.validateAndSubmit(false));
                this.memoizedFormContext.services.singletonMap = new singleton_map_service_1.default();
                this.memoizedFormContext.services.multiActiveArray = new multi_active_array_service_1.default();
            }
            return this.memoizedFormContext;
        }
    }
    componentDidMount() {
        this.mounted = true;
        this.memoizedFormContext.services.rootInstance.setIsMounted(true);
        this.props.autoFocus && this.memoizedFormContext.utils.focusById("root");
        Object.keys(this.memoizedFormContext.services).forEach(service => {
            var _a, _b;
            (_b = (_a = this.memoizedFormContext.services[service]).initialize) === null || _b === void 0 ? void 0 : _b.call(_a);
        });
        if (this.props.componentDidMount)
            this.props.componentDidMount();
    }
    componentWillUnmount() {
        this.mounted = false;
        this.memoizedFormContext.services.rootInstance.setIsMounted(false);
        Object.keys(this.memoizedFormContext.services).forEach(service => {
            var _a, _b;
            (_b = (_a = this.memoizedFormContext.services[service]).destroy) === null || _b === void 0 ? void 0 : _b.call(_a);
        });
    }
    componentDidCatch(e, i) {
        this.setState({ error: true });
        if (this.props.onError) {
            this.props.onError(e, i);
        }
    }
    componentDidUpdate(prevProps) {
        if ((prevProps.uiSchema || {})["ui:shortcuts"] !== (this.props.uiSchema || {})["ui:shortcuts"]) {
            this.resetShortcuts(getShortcuts(this.props.uiSchema));
        }
    }
    resetShortcuts(shortcuts = {}) {
        this.memoizedFormContext.services.keyHandler.setShortcuts(shortcuts, this.keyFunctions);
        Object.keys(shortcuts).some(keyCombo => {
            if (shortcuts[keyCombo].fn == "help") {
                this.keyCombo = keyCombo;
                return true;
            }
            return false;
        });
    }
    constructTranslations() {
        return (0, utils_1.constructTranslations)(translations_json_1.default);
    }
    render() {
        if (this.state.error)
            return null;
        const { translations } = this.state.formContext;
        const { "ui:showShortcutsButton": showShortcutsButton = true, "ui:readonly": readonly, "ui:disabled": disabled } = this.props.uiSchema;
        const shortcuts = getShortcuts(this.props.uiSchema);
        const uiSchema = Object.assign(Object.assign({}, this.props.uiSchema), { "ui:submitButtonOptions": {
                norender: true
            } });
        return (React.createElement(ReactContext_1.default.Provider, { value: this.getContext(this.props, this.context) },
            React.createElement("div", { className: "laji-form" },
                showShortcutsButton && this.props.showShortcutButton !== false && shortcuts && (React.createElement(components_1.TooltipComponent, { tooltip: this.getShorcutButtonTooltip() },
                    React.createElement(components_1.Button, { variant: undefined, onClick: this.toggleHelp }, translations.Shortcuts))),
                React.createElement(components_1.FailedBackgroundJobsPanel, { jobs: this.state.submitHooks, schema: this.props.schema, uiSchema: uiSchema, formContext: this.state.formContext, errorClickHandler: this.memoizedFormContext.services.focus.focus, ref: this.bgJobRef }),
                React.createElement(core_1.default, Object.assign({}, this.props, { formData: this.state.formData, uiSchema: uiSchema, ref: this.formRef, onChange: this.onChange, onSubmit: this.onSubmit, fields: this.getFields(this.props.fields), widgets: this.getWidgets(this.props.widgets), templates: this.getTemplates(this.props.templates), formContext: this.state.formContext, validator: validator_ajv6_1.default, noValidate: true, extraErrors: this.state.extraErrors || {}, noHtml5Validate: true, liveValidate: true, autoComplete: "off", tagName: "div", readonly: readonly, disabled: disabled }), this.props.children),
                (!this.props.children && this.props.renderSubmit !== false) ? (React.createElement(components_1.Button, { id: "submit", onClick: this.submit, disabled: readonly || disabled }, this.props.submitText || translations.Submit)) : null,
                shortcuts &&
                    React.createElement(components_1.ShortcutsPanel, { ref: this.shortcutHelpRef, shortcuts: shortcuts, formContext: this.state.formContext, onClose: this.dismissHelp }),
                this.renderSubmitHooks())));
    }
    getSettings() {
        return this.memoizedFormContext.services.settings.getSettings();
    }
}
LajiForm.contextType = ReactContext_1.default;
LajiForm.propTypes = {
    uiSchemaContext: PropTypes.object,
    settings: PropTypes.object,
    validators: PropTypes.object,
    warnings: PropTypes.object,
};
LajiForm.defaultProps = {
    lang: "en",
    schema: {},
    uiSchema: {}
};
exports.default = LajiForm;
const removeUndefinedFromArrays = (formData) => {
    if ((0, utils_1.isObject)(formData)) {
        return Object.keys(formData).reduce((obj, k) => {
            obj[k] = removeUndefinedFromArrays(formData[k]);
            return obj;
        }, {});
    }
    else if (Array.isArray(formData)) {
        return formData.reduce((filtered, i) => {
            if (i === undefined || i === null || i === "") {
                return filtered;
            }
            filtered.push(removeUndefinedFromArrays(i));
            return filtered;
        }, []);
    }
    return formData;
};
const getShortcuts = (uiSchema) => {
    var _a, _b;
    if ((_b = (_a = window.navigator) === null || _a === void 0 ? void 0 : _a.platform) === null || _b === void 0 ? void 0 : _b.includes("Mac")) {
        return mac_shortcuts_json_1.default;
    }
    const { "ui:shortcuts": shortcuts } = uiSchema || {};
    return shortcuts;
};
