'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index$1 = require('./index-a7b0c73d.js');
const core = require('@sankhyalabs/core');
const searchColumn = require('./search-column-00a916ae.js');
const index = require('./index-1be40f19.js');
const FormLayout = require('./FormLayout-18853e70.js');
require('./ApplicationUtils-5cc05979.js');
require('./DialogType-2114c337.js');
require('./CheckMode-ecb90b87.js');

const DETAIL_PATTERN = /child\[([^\]]+)\]/;
const REGEX_DEFAULT_VAR_KEY = /\$\{.+\}/;
class FormMetadata {
  constructor() {
    this._sheets = new Map();
    this._requiredFields = [];
    this._cleanOnCopyFields = [];
    this._defaultValues = {};
  }
  static getDetailName(name) {
    const result = DETAIL_PATTERN.exec(name);
    return result ? result[1] : undefined;
  }
  getSheet(name) {
    return this._sheets.get(name);
  }
  getAllSheets() {
    return this._sheets;
  }
  addSheet(sheet) {
    this._sheets.set(sheet.name, sheet);
  }
  addRequiredFields(fields) {
    this._requiredFields = this._requiredFields.concat(fields);
  }
  getRequiredFields() {
    return this._requiredFields;
  }
  addCleanOnCopyFields(fields) {
    this._cleanOnCopyFields = this._cleanOnCopyFields.concat(fields);
  }
  getCleanOnCopyFields() {
    return this._cleanOnCopyFields;
  }
  addDefaultValues(defaultValues) {
    return this._defaultValues = Object.assign(Object.assign({}, this._defaultValues), defaultValues);
  }
  getDefaultValues() {
    const result = {};
    Object.entries(this._defaultValues).forEach(([key, value]) => {
      if (typeof value === "string") {
        const result = REGEX_DEFAULT_VAR_KEY.exec(value);
        if (result) {
          value = this.getDefaultVar(result[0]);
        }
      }
      result[key] = value;
    });
    return result;
  }
  getDefaultVar(name) {
    if (name === "${data}") {
      return core.DateUtils.getToday();
    }
    if (name === "${datahora}") {
      return core.DateUtils.getToday(true);
    }
    return this._defaultVars ? this._defaultVars.get(name) : undefined;
  }
  setDefaultVars(vars) {
    this._defaultVars = vars;
  }
}
const buildFormConfigFromDataUnit = (dataUnit) => {
  const unitMD = dataUnit.metadata;
  let fields;
  if (unitMD) {
    fields = unitMD.fields
      .filter(descriptor => descriptor.visible !== false)
      .map(descriptor => { return { name: descriptor.name, defaultValue: descriptor.defaultValue }; });
  }
  const config = { emptyConfig: false, fields };
  return config;
};
const buildFormMetadata = (config, dataUnit, includeDetails = false) => {
  var _a, _b;
  if (config == undefined || (config === null || config === void 0 ? void 0 : config.emptyConfig) === true) {
    config = buildFormConfigFromDataUnit(dataUnit);
  }
  const sheets = new Map();
  const hiddenTabs = new Map();
  const requiredFields = [];
  const cleanOnCopyFields = [];
  const defaultValues = {};
  (_a = config === null || config === void 0 ? void 0 : config.tabs) === null || _a === void 0 ? void 0 : _a.forEach((tab) => {
    if (!hiddenTabs.has(tab.label) && tab.visible === false) {
      hiddenTabs.set(tab.label, tab);
    }
  });
  (_b = config === null || config === void 0 ? void 0 : config.fields) === null || _b === void 0 ? void 0 : _b.forEach((field) => {
    var _a, _b, _c;
    if (field.visible !== false) {
      const tabConfig = getTabConfig(field.tab || "__main", sheets, config);
      if (hiddenTabs.has(tabConfig.label)) {
        return;
      }
      const descriptor = dataUnit.getField(field.name);
      const fieldVisible = (descriptor === null || descriptor === void 0 ? void 0 : descriptor.visible) == undefined || (descriptor === null || descriptor === void 0 ? void 0 : descriptor.visible) === true;
      if (descriptor && fieldVisible && tabConfig.visible) {
        if (!sheets.has(tabConfig)) {
          sheets.set(tabConfig, []);
        }
        const formField = searchColumn.buildFieldMetadata(descriptor, field);
        sheets.get(tabConfig).push(formField);
        if (formField.required) {
          requiredFields.push(field.name);
        }
        const cleanOnCopy = field.cleanOnCopy == undefined ? (_a = descriptor.properties) === null || _a === void 0 ? void 0 : _a.cleanOnCopy : field.cleanOnCopy;
        if (cleanOnCopy || ((_b = descriptor.properties) === null || _b === void 0 ? void 0 : _b.cleanOnCopy)) {
          cleanOnCopyFields.push(field.name);
        }
        let defaultValue = field.defaultValue == undefined ? (_c = descriptor.properties) === null || _c === void 0 ? void 0 : _c.defaultValue : field.defaultValue;
        if (defaultValue && defaultValue.value != undefined) {
          const { type, value } = defaultValue;
          if (type) {
            if (type === "V") {
              defaultValue = value;
            }
            else {
              try {
                const parsed = JSON.parse(value);
                if (parsed && "value" in parsed) {
                  defaultValue = parsed;
                }
                else {
                  defaultValue = value;
                }
              }
              catch (_d) { }
            }
          }
          defaultValues[field.name] = defaultValue;
        }
      }
    }
  });
  const metadata = new FormMetadata();
  metadata.setDefaultVars(config.defaultVars);
  if (includeDetails) {
    const unitMD = dataUnit.metadata;
    if (unitMD != undefined && unitMD.children != undefined) {
      unitMD.children.forEach((child) => {
        if (hiddenTabs.has(child.label)) {
          return;
        }
        const tabConfig = getTabFromConfig(child.label, config);
        if (tabConfig) {
          sheets.set(Object.assign(tabConfig, { name: buildChildName(child) }), []);
          return;
        }
        const { label, name, fields } = buildDetailSheet(child);
        sheets.set({ name, label }, fields);
      });
    }
  }
  const i18n = index.getI18n();
  Array.from(sheets.entries())
    .sort(sortTabs)
    .forEach(([key, fields]) => {
    metadata.addSheet({
      label: (key.label === "__main") ? i18n("ez-form.mainTab") : key.label,
      name: key.name || key.label,
      fields
    });
  });
  metadata.addRequiredFields(requiredFields);
  metadata.addCleanOnCopyFields(cleanOnCopyFields);
  metadata.addDefaultValues(defaultValues);
  return metadata;
};
const getTabFromConfig = (tab, config) => {
  var _a;
  if (!config) {
    return;
  }
  return (_a = config.tabs) === null || _a === void 0 ? void 0 : _a.find(t => t.label === tab);
};
const getTabConfig = (tab, sheets, config) => {
  if (typeof tab !== "string") {
    return tab;
  }
  if (config) {
    const tabConfig = getTabFromConfig(tab, config);
    if (tabConfig) {
      return tabConfig;
    }
  }
  const tabConfig = Array.from(sheets.keys()).find(t => t.label === tab);
  return tabConfig || { label: tab, visible: true };
};
function sortTabs(a, b) {
  var _a, _b;
  if (a[0].label === '__main' && b[0].label !== '__main') {
    return -1;
  }
  if (a[0].label !== '__main' && b[0].label === '__main') {
    return 1;
  }
  const aOrder = (_a = a[0].order) !== null && _a !== void 0 ? _a : Number.MAX_VALUE;
  const bOrder = (_b = b[0].order) !== null && _b !== void 0 ? _b : Number.MAX_VALUE;
  return aOrder - bOrder;
}
const buildChildName = (child) => {
  return `child[${child.name}]`;
};
const buildDetailSheet = (child) => {
  return {
    name: buildChildName(child),
    label: child.label,
    fields: []
  };
};

/**
 * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
 *
 * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
 * during build.
 * @param {number} code
 */
function formatProdErrorMessage(code) {
  return "Minified Redux error #" + code + "; visit https://redux.js.org/Errors?code=" + code + " for the full message or " + 'use the non-minified dev environment for full errors. ';
}

// Inlined version of the `symbol-observable` polyfill
var $$observable = (function () {
  return typeof Symbol === 'function' && Symbol.observable || '@@observable';
})();

/**
 * These are private action types reserved by Redux.
 * For any unknown actions, you must return the current state.
 * If the current state is undefined, you must return the initial state.
 * Do not reference these action types directly in your code.
 */
var randomString = function randomString() {
  return Math.random().toString(36).substring(7).split('').join('.');
};

var ActionTypes = {
  INIT: "@@redux/INIT" + randomString(),
  REPLACE: "@@redux/REPLACE" + randomString(),
  PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
    return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
  }
};

/**
 * @param {any} obj The object to inspect.
 * @returns {boolean} True if the argument appears to be a plain object.
 */
function isPlainObject(obj) {
  if (typeof obj !== 'object' || obj === null) return false;
  var proto = obj;

  while (Object.getPrototypeOf(proto) !== null) {
    proto = Object.getPrototypeOf(proto);
  }

  return Object.getPrototypeOf(obj) === proto;
}

/**
 * @deprecated
 *
 * **We recommend using the `configureStore` method
 * of the `@reduxjs/toolkit` package**, which replaces `createStore`.
 *
 * Redux Toolkit is our recommended approach for writing Redux logic today,
 * including store setup, reducers, data fetching, and more.
 *
 * **For more details, please read this Redux docs page:**
 * **https://redux.js.org/introduction/why-rtk-is-redux-today**
 *
 * `configureStore` from Redux Toolkit is an improved version of `createStore` that
 * simplifies setup and helps avoid common bugs.
 *
 * You should not be using the `redux` core package by itself today, except for learning purposes.
 * The `createStore` method from the core `redux` package will not be removed, but we encourage
 * all users to migrate to using Redux Toolkit for all Redux code.
 *
 * If you want to use `createStore` without this visual deprecation warning, use
 * the `legacy_createStore` import instead:
 *
 * `import { legacy_createStore as createStore} from 'redux'`
 *
 */

function createStore(reducer, preloadedState, enhancer) {
  var _ref2;

  if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {
    throw new Error(formatProdErrorMessage(0) );
  }

  if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
    enhancer = preloadedState;
    preloadedState = undefined;
  }

  if (typeof enhancer !== 'undefined') {
    if (typeof enhancer !== 'function') {
      throw new Error(formatProdErrorMessage(1) );
    }

    return enhancer(createStore)(reducer, preloadedState);
  }

  if (typeof reducer !== 'function') {
    throw new Error(formatProdErrorMessage(2) );
  }

  var currentReducer = reducer;
  var currentState = preloadedState;
  var currentListeners = [];
  var nextListeners = currentListeners;
  var isDispatching = false;
  /**
   * This makes a shallow copy of currentListeners so we can use
   * nextListeners as a temporary list while dispatching.
   *
   * This prevents any bugs around consumers calling
   * subscribe/unsubscribe in the middle of a dispatch.
   */

  function ensureCanMutateNextListeners() {
    if (nextListeners === currentListeners) {
      nextListeners = currentListeners.slice();
    }
  }
  /**
   * Reads the state tree managed by the store.
   *
   * @returns {any} The current state tree of your application.
   */


  function getState() {
    if (isDispatching) {
      throw new Error(formatProdErrorMessage(3) );
    }

    return currentState;
  }
  /**
   * Adds a change listener. It will be called any time an action is dispatched,
   * and some part of the state tree may potentially have changed. You may then
   * call `getState()` to read the current state tree inside the callback.
   *
   * You may call `dispatch()` from a change listener, with the following
   * caveats:
   *
   * 1. The subscriptions are snapshotted just before every `dispatch()` call.
   * If you subscribe or unsubscribe while the listeners are being invoked, this
   * will not have any effect on the `dispatch()` that is currently in progress.
   * However, the next `dispatch()` call, whether nested or not, will use a more
   * recent snapshot of the subscription list.
   *
   * 2. The listener should not expect to see all state changes, as the state
   * might have been updated multiple times during a nested `dispatch()` before
   * the listener is called. It is, however, guaranteed that all subscribers
   * registered before the `dispatch()` started will be called with the latest
   * state by the time it exits.
   *
   * @param {Function} listener A callback to be invoked on every dispatch.
   * @returns {Function} A function to remove this change listener.
   */


  function subscribe(listener) {
    if (typeof listener !== 'function') {
      throw new Error(formatProdErrorMessage(4) );
    }

    if (isDispatching) {
      throw new Error(formatProdErrorMessage(5) );
    }

    var isSubscribed = true;
    ensureCanMutateNextListeners();
    nextListeners.push(listener);
    return function unsubscribe() {
      if (!isSubscribed) {
        return;
      }

      if (isDispatching) {
        throw new Error(formatProdErrorMessage(6) );
      }

      isSubscribed = false;
      ensureCanMutateNextListeners();
      var index = nextListeners.indexOf(listener);
      nextListeners.splice(index, 1);
      currentListeners = null;
    };
  }
  /**
   * Dispatches an action. It is the only way to trigger a state change.
   *
   * The `reducer` function, used to create the store, will be called with the
   * current state tree and the given `action`. Its return value will
   * be considered the **next** state of the tree, and the change listeners
   * will be notified.
   *
   * The base implementation only supports plain object actions. If you want to
   * dispatch a Promise, an Observable, a thunk, or something else, you need to
   * wrap your store creating function into the corresponding middleware. For
   * example, see the documentation for the `redux-thunk` package. Even the
   * middleware will eventually dispatch plain object actions using this method.
   *
   * @param {Object} action A plain object representing “what changed”. It is
   * a good idea to keep actions serializable so you can record and replay user
   * sessions, or use the time travelling `redux-devtools`. An action must have
   * a `type` property which may not be `undefined`. It is a good idea to use
   * string constants for action types.
   *
   * @returns {Object} For convenience, the same action object you dispatched.
   *
   * Note that, if you use a custom middleware, it may wrap `dispatch()` to
   * return something else (for example, a Promise you can await).
   */


  function dispatch(action) {
    if (!isPlainObject(action)) {
      throw new Error(formatProdErrorMessage(7) );
    }

    if (typeof action.type === 'undefined') {
      throw new Error(formatProdErrorMessage(8) );
    }

    if (isDispatching) {
      throw new Error(formatProdErrorMessage(9) );
    }

    try {
      isDispatching = true;
      currentState = currentReducer(currentState, action);
    } finally {
      isDispatching = false;
    }

    var listeners = currentListeners = nextListeners;

    for (var i = 0; i < listeners.length; i++) {
      var listener = listeners[i];
      listener();
    }

    return action;
  }
  /**
   * Replaces the reducer currently used by the store to calculate the state.
   *
   * You might need this if your app implements code splitting and you want to
   * load some of the reducers dynamically. You might also need this if you
   * implement a hot reloading mechanism for Redux.
   *
   * @param {Function} nextReducer The reducer for the store to use instead.
   * @returns {void}
   */


  function replaceReducer(nextReducer) {
    if (typeof nextReducer !== 'function') {
      throw new Error(formatProdErrorMessage(10) );
    }

    currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.
    // Any reducers that existed in both the new and old rootReducer
    // will receive the previous state. This effectively populates
    // the new state tree with any relevant data from the old one.

    dispatch({
      type: ActionTypes.REPLACE
    });
  }
  /**
   * Interoperability point for observable/reactive libraries.
   * @returns {observable} A minimal observable of state changes.
   * For more information, see the observable proposal:
   * https://github.com/tc39/proposal-observable
   */


  function observable() {
    var _ref;

    var outerSubscribe = subscribe;
    return _ref = {
      /**
       * The minimal observable subscription method.
       * @param {Object} observer Any object that can be used as an observer.
       * The observer object should have a `next` method.
       * @returns {subscription} An object with an `unsubscribe` method that can
       * be used to unsubscribe the observable from the store, and prevent further
       * emission of values from the observable.
       */
      subscribe: function subscribe(observer) {
        if (typeof observer !== 'object' || observer === null) {
          throw new Error(formatProdErrorMessage(11) );
        }

        function observeState() {
          if (observer.next) {
            observer.next(getState());
          }
        }

        observeState();
        var unsubscribe = outerSubscribe(observeState);
        return {
          unsubscribe: unsubscribe
        };
      }
    }, _ref[$$observable] = function () {
      return this;
    }, _ref;
  } // When a store is created, an "INIT" action is dispatched so that every
  // reducer returns their initial state. This effectively populates
  // the initial state tree.


  dispatch({
    type: ActionTypes.INIT
  });
  return _ref2 = {
    dispatch: dispatch,
    subscribe: subscribe,
    getState: getState,
    replaceReducer: replaceReducer
  }, _ref2[$$observable] = observable, _ref2;
}

const inicialState = {};
///////////////////////////////     REDUCERS     ///////////////////////////////
function formReducer(state = inicialState, action) {
  switch (action.type) {
    case FormActions.METADATA_LOADED:
      return Object.assign(Object.assign({}, state), { formMetadata: action.payload, currentSheet: undefined });
    case FormActions.CHANGE_TAB:
      return Object.assign(Object.assign({}, state), { currentSheet: action.payload });
    default:
      return state;
  }
}
/////////////////////////////// ACTION CREATORS ///////////////////////////////
function loadMetadata(formMetadata) {
  return {
    type: FormActions.METADATA_LOADED,
    payload: formMetadata
  };
}
function changeTab(currentSheet) {
  return {
    type: FormActions.CHANGE_TAB,
    payload: typeof currentSheet === "string" ? currentSheet : currentSheet.tabKey
  };
}
///////////////////////////////    SELECTORS    ///////////////////////////////
function selectFormMetadata(state) {
  return state.formMetadata;
}
function selectCurrentSheetId(state) {
  return state.currentSheet;
}
function selectCurrentSheet(state) {
  const currentSheetId = selectCurrentSheetId(state);
  return currentSheetId ? state.formMetadata.getSheet(currentSheetId) : Array.from(state.formMetadata.getAllSheets().values())[0];
}
///////////////////////////////      TYPES      ///////////////////////////////
var FormActions;
(function (FormActions) {
  FormActions["METADATA_LOADED"] = "FORM/METADATA_LOADED";
  FormActions["CHANGE_TAB"] = "FORM/CHANGE_TAB";
})(FormActions || (FormActions = {}));

const ezFormCss = ".sc-ez-form-h{display:flex;flex-direction:column;width:100%}.dynamic-content.sc-ez-form ez-collapsible-box.sc-ez-form{--ez-collapsible-box__header--padding-right:var(--space-small, 6px);--ez-collapsible-box__header--padding-left:var(--space-small, 6px)}";

const EzForm = class {
  constructor(hostRef) {
    index$1.registerInstance(this, hostRef);
    this.ezFormRequestClearFieldToFocus = index$1.createEvent(this, "ezFormRequestClearFieldToFocus", 7);
    this.ezFormSetFields = index$1.createEvent(this, "ezFormSetFields", 7);
    this.ezReady = index$1.createEvent(this, "ezReady", 7);
    this.formItemsReady = index$1.createEvent(this, "formItemsReady", 7);
    this._customEditors = new Map();
    this._application = core.ApplicationContext.getContextValue("__SNK__APPLICATION__");
    this.onDataUnitAction = (action) => {
      if (action.type === core.Action.METADATA_LOADED) {
        this.processMetadata();
      }
    };
    this._fieldsProps = new Map();
    this._singleColumn = false;
    this.dataUnit = undefined;
    this.config = undefined;
    this.recordsValidator = undefined;
    this.fieldToFocus = undefined;
    this.onlyStaticFields = false;
    this.useSearchField = true;
    this.elementFocusSearchField = undefined;
  }
  /**
   * Realiza validação no conteúdo de todos os campos.
   */
  validate() {
    return this._dataBinder.validate();
  }
  /**
   * Registra um editor customizado para campos da grade e formulário.
   */
  async addCustomEditor(fieldName, customEditor, detailContext) {
    if (this._formView) {
      this._formView.addCustomEditor(fieldName, customEditor, detailContext);
      return;
    }
    const newCustomEditors = new Map(this._customEditors);
    newCustomEditors.set(fieldName, { customEditor, detailContext });
    this._customEditors = newCustomEditors;
  }
  observeConfig() {
    this.processMetadata();
  }
  /**
   * Altera/adiciona uma propriedade nos metadados do campo.
   */
  async setFieldProp(fieldName, propName, value) {
    const newCustomFieldProps = new Map(this._fieldsProps);
    const currentProps = this._fieldsProps.get(fieldName);
    newCustomFieldProps.set(fieldName, Object.assign(Object.assign({}, currentProps), { [propName]: value }));
    this._fieldsProps = newCustomFieldProps;
  }
  getDynamicContent() {
    var _a;
    const formMD = selectFormMetadata(this._store.getState());
    if (!formMD) {
      return null;
    }
    const allSheets = Array.from(formMD.getAllSheets().values());
    const currentSheet = selectCurrentSheet((_a = this._store) === null || _a === void 0 ? void 0 : _a.getState());
    let result = [];
    if (allSheets.length > 1) {
      const tabs = allSheets.map((sheet, index) => {
        return { tabKey: sheet.name, label: sheet.label, index };
      });
      const idTabSelector = `selector`;
      result.push(index$1.h("ez-tabselector", { tabs: this.buildIdTabSelector(tabs), onEzChange: (evt) => this._store.dispatch(changeTab(evt.detail)), selectedTab: currentSheet.name, "data-element-id": idTabSelector }));
    }
    result = result.concat(this.buildFormContent(currentSheet));
    return result;
  }
  buildFormContent(currentSheet) {
    const fields = currentSheet === null || currentSheet === void 0 ? void 0 : currentSheet.fields;
    if (currentSheet == undefined) {
      return;
    }
    this.ezFormSetFields.emit(fields);
    const idFormSheet = `${core.StringUtils.replaceAccentuatedChars(core.StringUtils.toCamelCase(currentSheet === null || currentSheet === void 0 ? void 0 : currentSheet.label), false)}_selectorContainer`;
    return (index$1.h("div", { class: "dynamic-content ez-box--no-outline", "data-element-id": idFormSheet, ref: elem => (this._container = elem), tabindex: "0" }, index$1.h("ez-popover", { ref: elem => (this._ezPopoverSearchField = elem), overlayType: "none" }, this.renderFieldColumn()), index$1.h("ez-form-view", { ref: (element) => (this._formView = element), class: "ez-row ez-padding-vertical--small", fields: fields, singleColumn: this._singleColumn, selectedRecord: this.dataUnit.getSelectedRecord() })));
  }
  renderFieldColumn() {
    if (this._fieldSearch != undefined) {
      return this._fieldSearch;
    }
    this._fieldSearch = searchColumn.buildFieldSearch({
      value: core.StringUtils.generateUUID(),
      label: this._i18n("ez-form.labelSearchField"),
    }, ({ argument }) => this.fieldsOptionLoader(argument), (option) => this.onSelectField(option));
    return this._fieldSearch;
  }
  getFormFields() {
    var _a;
    return (_a = this.config) === null || _a === void 0 ? void 0 : _a.fields;
  }
  fieldsOptionLoader(argument) {
    const searchTerm = argument === null || argument === void 0 ? void 0 : argument.toLowerCase();
    const allFields = this.getFormFields().map(field => { var _a; return (_a = this.dataUnit) === null || _a === void 0 ? void 0 : _a.getField(field.name); });
    const filteredFields = allFields.filter(field => {
      var _a, _b;
      return ((_a = field.name) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes(searchTerm)) ||
        ((_b = field.label) === null || _b === void 0 ? void 0 : _b.toLowerCase().includes(searchTerm));
    });
    const options = filteredFields.map(field => ({ value: field.name, label: field.label }));
    return Promise.resolve(options);
  }
  onSelectField(option) {
    if (option == undefined || option.value == undefined) {
      this.fieldToFocus = "";
      return;
    }
    this.fieldToFocus = option.value;
    this._ezPopoverSearchField.hide();
  }
  async initKeyboardManager() {
    var _a, _b;
    this._keyboardManager = new core.KeyboardManager({ propagate: false, element: (_a = this.elementFocusSearchField) !== null && _a !== void 0 ? _a : this._element });
    if (this.useSearchField) {
      this._keyboardManager.bind(searchColumn.SHORTCUT_SEARCH_FIELD, async () => {
        if (!this._container || !this._ezPopoverSearchField)
          return;
        const container = this._container.getBoundingClientRect();
        await searchColumn.focusOnFieldSerch(this._fieldSearch);
        this._ezPopoverSearchField.showUnder(this._container, { horizontalGap: container.width - (searchColumn.SEARCH_FIELD_FULL_WIDTH), verticalGap: container.height * -1 });
      }, { description: this._i18n("ez-form.labelSearchField"), element: (_b = this.elementFocusSearchField) !== null && _b !== void 0 ? _b : this._element });
    }
  }
  componentDidLoad() {
    this.initKeyboardManager();
  }
  processMetadata() {
    if (this.bindFields() && this.dataUnit && this._store) {
      const metadata = buildFormMetadata(this.config, this.dataUnit);
      this._store.dispatch(loadMetadata(metadata));
    }
  }
  isStatic() {
    var _a;
    return ((_a = this._staticFields) === null || _a === void 0 ? void 0 : _a.length) > 0;
  }
  bindFields() {
    return !this.isStatic() || this.onlyStaticFields === false;
  }
  async componentWillLoad() {
    var _a;
    if (this.dataUnit === undefined) {
      this.dataUnit = new core.DataUnit("ez-form");
    }
    this.dataUnit.unsubscribe(this.onDataUnitAction);
    this.dataUnit.subscribe(this.onDataUnitAction);
    this._dataBinder = new searchColumn.DataBinder(this.dataUnit);
    this._store = createStore(formReducer);
    this._store.subscribe(() => index$1.forceUpdate(this));
    this._staticFields = Array.from(this._element.querySelectorAll("[data-field-name]"));
    this.processMetadata();
    const dataInfo = { dataUnit: this.dataUnit };
    core.ElementIDUtils.addIDInfo(this._element, null, dataInfo);
    const layoutFormConfig = await ((_a = this._application) === null || _a === void 0 ? void 0 : _a.getLayoutFormConfig());
    this.setSingleColumn(layoutFormConfig);
    this.registerNotifyListeners(layoutFormConfig);
    this._i18n = await index.initI18n();
  }
  async setSingleColumn(layoutFormConfig) {
    this._singleColumn = (layoutFormConfig === null || layoutFormConfig === void 0 ? void 0 : layoutFormConfig.config) === FormLayout.FormLayout.CASCADE;
  }
  async registerNotifyListeners(layoutFormConfig) {
    if (!layoutFormConfig)
      return;
    layoutFormConfig.onConfigChange((config) => {
      if (config === FormLayout.FormLayout.CASCADE) {
        this._singleColumn = true;
      }
      else {
        this._singleColumn = false;
      }
    });
  }
  componentDidRender() {
    const metadata = selectFormMetadata(this._store.getState());
    metadata.addRequiredFields(this._staticFields.filter(f => f.dataset.required).map(f => f.dataset.fieldName));
    this._dataBinder.bind(Array.from(this._element.querySelectorAll("[data-field-name]")), this.dataUnit.dataUnitId, metadata, this.recordsValidator);
    this.ezReady.emit();
    this.handleFieldToFocus();
    this.setCustomEditors();
    this.setFieldsProps();
  }
  setCustomEditors() {
    if (!this._formView) {
      return;
    }
    for (const [fieldName, customEditorProps] of this._customEditors) {
      this._formView.addCustomEditor(fieldName, customEditorProps.customEditor, customEditorProps.detailContext);
      this._customEditors.delete(fieldName);
    }
  }
  handleFieldToFocus() {
    var _a;
    if (this.fieldToFocus == undefined) {
      return;
    }
    const currentSheet = selectCurrentSheet((_a = this._store) === null || _a === void 0 ? void 0 : _a.getState());
    const fields = currentSheet === null || currentSheet === void 0 ? void 0 : currentSheet.fields;
    if (!fields.some(item => item.name === this.fieldToFocus)) {
      return;
    }
    requestAnimationFrame(() => {
      this._dataBinder.setFocus(this.fieldToFocus);
      this.ezFormRequestClearFieldToFocus.emit();
      this.fieldToFocus = null;
    });
  }
  setFieldsProps() {
    if (!this._formView) {
      return;
    }
    for (const [fieldName, props] of this._fieldsProps) {
      for (const prop in props) {
        this._formView.setFieldProp(fieldName, prop, props[prop]);
      }
      this._fieldsProps.delete(fieldName);
    }
  }
  disconnectedCallback() {
    var _a;
    this.dataUnit.unsubscribe(this.onDataUnitAction);
    this._dataBinder.onDisconnectedCallback();
    (_a = this._keyboardManager) === null || _a === void 0 ? void 0 : _a.unbindAllShortcutKeys();
  }
  buildIdTabSelector(tabs) {
    if (tabs) {
      tabs.forEach(tab => tab[core.ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME] = core.StringUtils.toCamelCase(tab.label));
    }
    return tabs;
  }
  render() {
    return (index$1.h(index$1.Host, null, this.isStatic() ? null : this.getDynamicContent()));
  }
  get _element() { return index$1.getElement(this); }
  static get watchers() { return {
    "config": ["observeConfig"]
  }; }
};
EzForm.style = ezFormCss;

exports.ez_form = EzForm;
