import { r as registerInstance, h, H as Host, c as createEvent, g as getElement } from './index-baa5e267.js';
import { ElementIDUtils, ObjectUtils, HTMLBuilder, StringUtils, KeyboardManager } from '@sankhyalabs/core';
import { i as initI18n } from './index-41363fa6.js';
import { C as CustomEditorSource } from './FormLayout-071d324c.js';
import { R as RICH_TOOLBAR_FORMAT_TAGS, a as RICH_TOOLBAR_COMMANDS } from './RichToolbarHelper-f3a149c4.js';
import { p as purify } from './purify-cb5f3256.js';
import { A as ApplicationUtils } from './ApplicationUtils-1569f757.js';
import './DialogType-54a62731.js';
import './CheckMode-bdb2ec19.js';
import './_commonjsHelpers-9943807e.js';

const ezComboBoxListCss = ":host{--ez-combo-box--border-radius:var(--border--radius-medium, 12px);--ez-combo-box--font-size:var(--text--medium, 14px);--ez-combo-box--font-family:var(--font-pattern, Arial);--ez-combo-box--font-weight--large:var(--text-weight--large, 500);--ez-combo-box--font-weight--medium:var(--text-weight--medium, 400);--ez-combo-box--background-color--xlight:var(--background--xlight, #fff);--ez-combo-box--background-medium:var(--background--medium, #f0f3f7);--ez-combo-box--line-height:calc(var(--text--medium, 14px) + 4px);--ez-combo-box__list-title--primary:var(--title--primary, #2B3A54);--ez-combo-box__list-text--primary:var(--text--primary, #626e82);--ez-combo-box__list-height:calc(var(--ez-combo-box--font-size) + var(--ez-combo-box--space--medium) + 4px);--ez-combo-box--space--medium:var(--space--medium, 12px);--ez-combo-box--space--small:var(--space--small, 6px);--ez-combo-box__scrollbar--color-default:var(--scrollbar--default, #626e82);--ez-combo-box__scrollbar--color-background:var(--scrollbar--background, #E5EAF0);--ez-combo-box__scrollbar--color-hover:var(--scrollbar--hover, #2B3A54);--ez-combo-box__scrollbar--color-clicked:var(--scrollbar--clicked, #a2abb9);--ez-combo-box__scrollbar--border-radius:var(--border--radius-small, 6px);--ez-combo-box__scrollbar--width:var(--space--medium, 12px);--ez-combo-box__list-container--padding:var(--space--extra-small, 3px)}.list-container{padding-top:var(--ez-combo-box__list-container--padding)}.list-wrapper{display:flex;flex-direction:column;box-sizing:border-box;width:0;z-index:var(--more-visible, 2);max-height:calc(4*var(--ez-combo-box__list-height) + 2*var(--ez-combo-box--space--small) + 9px);background-color:var(--ez-combo-box--background-color--xlight);border-radius:var(--ez-combo-box--border-radius);box-shadow:var(--shadow--medium, 0 8px 24px 0 rgba(43, 58, 84, 0.10));padding:var(--ez-combo-box--space--small)}.list-options{box-sizing:border-box;width:100%;height:100%;padding:0;margin:0;display:flex;flex-direction:column;scroll-behavior:smooth;overflow:auto;scrollbar-width:thin;gap:3px;scrollbar-color:var(--ez-combo-box__scrollbar--color-clicked) var(--ez-combo-box__scrollbar--color-background)}.list-options::-webkit-scrollbar{background-color:var(--ez-combo-box__scrollbar--color-background);width:var(--ez-combo-box__scrollbar--width);max-width:var(--ez-combo-box__scrollbar--width);min-width:var(--ez-combo-box__scrollbar--width)}.list-options::-webkit-scrollbar-track{background-color:var(--ez-combo-box__scrollbar--color-background);border-radius:var(--ez-combo-box__scrollbar--border-radius)}.list-options::-webkit-scrollbar-thumb{background-color:var(--ez-combo-box__scrollbar--color-default);border-radius:var(--ez-combo-box__scrollbar--border-radius)}.list-options::-webkit-scrollbar-thumb:vertical:hover,.list-options::-webkit-scrollbar-thumb:horizontal:hover{background-color:var(--ez-combo-box__scrollbar--color-hover)}.list-options::-webkit-scrollbar-thumb:vertical:active,.list-options::-webkit-scrollbar-thumb:horizontal:active{background-color:var(--ez-combo-box__scrollbar--color-clicked)}.item{display:flex;align-items:center;width:100%;box-sizing:border-box;list-style-type:none;cursor:pointer;border-radius:var(--ez-combo-box--border-radius-small);padding:var(--ez-combo-box--space--small);min-height:var(--ez-combo-box__list-height);gap:var(--space--small, 6px)}.item__value,.item__label{flex-basis:auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--ez-combo-box__list-title--primary);font-family:var(--ez-combo-box--font-family);font-size:var(--ez-combo-box--font-size);line-height:var(--ez-combo-box--line-height)}.item__label{font-weight:var(--ez-combo-box--font-weight--medium)}.item__label--bold{font-weight:var(--ez-combo-box--font-weight--large)}.item__value{text-align:center;color:var(--ez-combo-box__list-text--primary);font-weight:var(--ez-combo-box--font-weight--large)}.item__value--hidden{visibility:hidden;position:absolute;white-space:nowrap;z-index:-1;top:0;left:0}.item__label{text-align:left}.message{text-align:center;display:flex;justify-content:center;align-items:center;list-style-type:none;min-height:var(--ez-combo-box__list-height)}.message__no-result{color:var(--ez-combo-box__list-title--primary);font-family:var(--ez-combo-box--font-family);font-size:var(--ez-combo-box--font-size)}.message__loading{border-radius:50%;width:14px;height:14px;-webkit-animation:spin 1s linear infinite;animation:spin 1s linear infinite;border:3px solid var(--ez-combo-box__list-title--primary);border-top:3px solid transparent}li:hover{background-color:var(--ez-combo-box--background-medium)}.preselected{background-color:var(--background--medium)}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}";

const EzComboBoxList = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.showLoading = undefined;
    this.visibleOptions = undefined;
    this.textEmptyList = undefined;
    this.showOptionValue = undefined;
    this.preSelection = undefined;
    this.maxWidth = undefined;
    this.width = undefined;
    this.onOptionSelect = undefined;
    this.onOptionHover = undefined;
  }
  /**
   * Move a seleção para a próxima opção na lista.
   */
  async nextOption() {
    var _a, _b;
    if (!((_a = this.visibleOptions) === null || _a === void 0 ? void 0 : _a.length))
      return;
    const isAtLastOption = this.preSelection !== undefined && this.preSelection >= this.visibleOptions.length - 1;
    if (!isAtLastOption) {
      this.preSelection = this.preSelection === undefined ? 0 : this.preSelection + 1;
      this.scrollToOption(this.visibleOptions[this.preSelection]);
      (_b = this.onOptionHover) === null || _b === void 0 ? void 0 : _b.call(this, this.preSelection);
    }
  }
  /**
   * Move a seleção para a opção anterior na lista, sem ultrapassar o início.
   */
  async previousOption() {
    var _a, _b;
    if (!((_a = this.visibleOptions) === null || _a === void 0 ? void 0 : _a.length))
      return;
    const isAtFirstOption = this.preSelection !== undefined && this.preSelection <= 0;
    if (!isAtFirstOption) {
      this.preSelection = this.preSelection === undefined ? this.visibleOptions.length - 1 : this.preSelection - 1;
      this.scrollToOption(this.visibleOptions[this.preSelection]);
      (_b = this.onOptionHover) === null || _b === void 0 ? void 0 : _b.call(this, this.preSelection);
    }
  }
  /**
   * Seleciona a opção atualmente pré-selecionada.
   */
  async selectCurrentOption() {
    if (this.preSelection !== undefined) {
      this.onOptionSelect(this.visibleOptions[this.preSelection]);
      this.preSelection = undefined;
    }
  }
  /**
   * Observa mudanças na propriedade `width` e ajusta a largura da lista.
   *
   * @param newValue O novo valor da largura.
   * @param oldValue O valor anterior da largura.
   */
  observeWidth(newValue, oldValue) {
    if (newValue === oldValue)
      return;
    if (!this._listWrapper)
      return;
    this._listWrapper.style.width = `${this.width}px`;
  }
  /**
   * Observa mudanças na propriedade `maxWidth` e ajusta a largura máxima da lista.
   *
   * @param newValue O novo valor da largura máxima.
   * @param oldValue O valor anterior da largura máxima.
   */
  observeMaxWidth(newValue, oldValue) {
    if (newValue === oldValue)
      return;
    if (!this._listWrapper)
      return;
    this._listWrapper.style.maxWidth = this.maxWidth ? `${this.maxWidth}px` : '';
  }
  /**
   * Gerencia a navegação por teclado na lista do combo box.
   *
   * - `ArrowDown`: Move para a próxima opção.
   * - `ArrowUp`: Move para a opção anterior.
   * - `Enter`: Seleciona a opção atual.
   * - `Escape`: Limpa a pré-seleção.
   *
   * @param event O evento de teclado.
   */
  handleKeyDown(event) {
    switch (event.key) {
      case "ArrowDown":
        event.preventDefault();
        event.stopPropagation();
        this.nextOption();
        break;
      case "ArrowUp":
        event.preventDefault();
        event.stopPropagation();
        this.previousOption();
        break;
      case "Enter":
        this.selectCurrentOption();
        break;
      case "Escape":
        this.preSelection = undefined;
        break;
    }
  }
  buildItem(opt, index) {
    const widthValue = this.showOptionValue && this.maxWidth > 0 ? `${this.maxWidth}px` : '';
    opt.label = opt.label || opt.value;
    return h("li", { tabIndex: 1, class: index === this.preSelection ? "item preselected" : "item", id: `item_${opt.value}_${index}`, key: `item_${opt.value}_${index}`, onMouseDown: () => this.onOptionSelect(opt), onMouseOver: () => this.preSelection = index }, this.showOptionValue
      ? h("span", { class: "item__value", title: opt.value, style: { width: widthValue, minWidth: widthValue, maxWidth: widthValue } }, opt.value)
      : undefined, h("span", { class: "item__label " + (this.showOptionValue ? "item__label--bold" : ""), title: opt.label }, opt.label));
  }
  scrollToOption(opt) {
    if (!(opt === null || opt === void 0 ? void 0 : opt.value) || !this._optionsList)
      return;
    const index = this.visibleOptions.indexOf(opt);
    if (index === -1)
      return;
    const liElem = this._optionsList.querySelector(`li#item_${CSS.escape(opt.value)}_${CSS.escape(String(index))}`);
    if (liElem) {
      liElem.scrollIntoView({
        behavior: "smooth",
        block: "nearest"
      });
    }
  }
  async componentWillLoad() {
    this.i18n = await initI18n();
  }
  componentDidLoad() {
    this._listWrapper.style.width = `${this.width}px`;
    this._listWrapper.style.maxWidth = this.maxWidth ? `${this.maxWidth}px` : '';
  }
  componentDidRender() {
    var _a;
    (_a = this._optionsList) === null || _a === void 0 ? void 0 : _a.querySelectorAll(".item").forEach((elem) => {
      ElementIDUtils.addIDInfoIfNotExists(elem, "itemComboBox");
    });
  }
  render() {
    return (h("section", { class: "list-container" }, h("div", { class: "list-wrapper", ref: elem => this._listWrapper = elem }, h("ul", { class: "list-options", ref: elem => this._optionsList = elem }, !this.showLoading && this.visibleOptions.length === 0 && (h("div", { class: "message" }, h("span", { class: "message__no-result" }, this.textEmptyList || this.i18n("ez-combo-box.noResults")))), this.showLoading && (h("div", { class: "message" }, h("div", { class: "message__loading" }))), this.showOptionValue && (h("span", { class: "item__value item__value--hidden" })), !this.showLoading && this.visibleOptions.length > 0 &&
      this.visibleOptions.map((opt, index) => this.buildItem(opt, index))))));
  }
  static get watchers() { return {
    "width": ["observeWidth"],
    "maxWidth": ["observeMaxWidth"]
  }; }
};
EzComboBoxList.style = ezComboBoxListCss;

const EzCustomFormInput = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.gui = undefined;
    this.customEditor = undefined;
    this.formViewField = undefined;
    this.value = undefined;
    this.detailContext = undefined;
    this.builderFallback = undefined;
    this.selectedRecord = undefined;
  }
  /**
   * Aplica foco no campo.
   */
  async setFocus() {
    var _a, _b;
    (_b = (_a = this.gui) === null || _a === void 0 ? void 0 : _a["setFocus"]) === null || _b === void 0 ? void 0 : _b.call(_a);
  }
  /**
   * Remove o foco do campo.
   */
  async setBlur() {
    var _a, _b;
    (_b = (_a = this.gui) === null || _a === void 0 ? void 0 : _a["setBlur"]) === null || _b === void 0 ? void 0 : _b.call(_a);
  }
  /**
   * Retorna se o conteúdo é inválido.
   */
  async isInvalid() {
    var _a, _b;
    return ((_b = (_a = this.gui) === null || _a === void 0 ? void 0 : _a["isInvalid"]) === null || _b === void 0 ? void 0 : _b.call(_a)) || false;
  }
  watchValue() {
    this.handleValue(this.gui);
  }
  watchCustomEditor() {
    this.getContent();
  }
  watchFormViewField(newValue, oldValue) {
    if (!ObjectUtils.equals(newValue, oldValue))
      this.getContent();
  }
  watchDetailContext() {
    this.getContent();
  }
  watchBuilderFallback() {
    this.getContent();
  }
  watchSelectedRecord(newValue, oldValue) {
    const newRecordId = newValue === null || newValue === void 0 ? void 0 : newValue['__record__id__'];
    const oldRecordId = oldValue === null || oldValue === void 0 ? void 0 : oldValue['__record__id__'];
    if (newRecordId !== oldRecordId) {
      this.getContent();
    }
  }
  getContent() {
    var _a, _b, _c, _d, _e;
    const fieldProps = new Map();
    for (const prop in this.formViewField.props) {
      fieldProps.set(prop, this.formViewField.props[prop]);
    }
    const params = {
      value: this.value,
      name: this.formViewField.name,
      currentEditor: this.builderFallback(this.formViewField),
      setValue: (value) => this.setValue(value),
      getValue: this.getValue,
      record: this.selectedRecord,
      editorMetadata: {
        label: this.formViewField.label,
        hidden: ((_a = this.formViewField.props) === null || _a === void 0 ? void 0 : _a.visible) === false,
        userInterface: this.formViewField.userInterface,
        options: (_b = this.formViewField.props) === null || _b === void 0 ? void 0 : _b.options,
        props: this.formViewField.props ? fieldProps : undefined,
        optionLoader: this.formViewField.optionLoader
      },
      source: CustomEditorSource.FORM,
      detailContext: this.detailContext
    };
    let gui = this.customEditor.getEditorElement(params);
    if (!gui) {
      gui = this.builderFallback(this.formViewField);
      this.handleValue(gui);
      this.gui = gui;
      return;
    }
    if (!(gui instanceof HTMLElement) && typeof gui !== 'string') {
      this.handleValue(gui);
      this.gui = gui;
      return;
    }
    if (typeof gui === 'string') {
      gui = HTMLBuilder.parseElement(gui);
    }
    const value = (_e = (_d = (_c = this.value) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : this.value) !== null && _e !== void 0 ? _e : '';
    gui.setAttribute('value', value);
    this.gui = h("div", { key: StringUtils.generateUUID(), ref: el => el && el.appendChild(gui) });
  }
  setValue(value) {
    this.value = value;
  }
  getValue() {
    return this.value;
  }
  handleValue(gui) {
    var _a;
    //@ts-ignore
    (_a = gui.$children$) === null || _a === void 0 ? void 0 : _a.forEach((child) => {
      child.$attrs$.value = this.value;
    });
  }
  componentWillLoad() {
    this.getContent();
  }
  render() {
    return (h(Host, null, this.gui));
  }
  static get watchers() { return {
    "value": ["watchValue"],
    "customEditor": ["watchCustomEditor"],
    "formViewField": ["watchFormViewField"],
    "detailContext": ["watchDetailContext"],
    "builderFallback": ["watchBuilderFallback"],
    "selectedRecord": ["watchSelectedRecord"]
  }; }
};

const ezRichTextCss = ".sc-ez-rich-text-h{display:block;width:100%;font-family:Roboto;--ez-rich-text--box-shadow:0 0 3px 0 #DCE0E8;--ez-rich-text--shadow--outline:var(--shadow--outline) var(--color--strokes)}.editor-container.sc-ez-rich-text{width:100%;overflow:hidden;border-radius:12px;border:1px solid #DCE0E8}ez-text-area.sc-ez-rich-text{--text-area__input--border:1px solid}.preview.sc-ez-rich-text{min-height:20px;padding:12px;resize:both;overflow:auto;max-width:100%;border-top:1px solid #DCE0E8}";

const EzRichText = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ezChange = createEvent(this, "ezChange", 7);
    this.historyStack = [];
    this.historyIndex = -1;
    this.previewMode = false;
    this.showPreview = true;
    this.value = '';
    this.label = undefined;
    this.mode = "regular";
    this.enabled = true;
    this.rows = 6;
    this.errorMessage = undefined;
    this.canShowError = true;
    this.showConfigs = true;
    this.showTextFormat = true;
    this.showUndoRedo = true;
  }
  observeValue(newValue, oldValue) {
    if (ObjectUtils.equals(newValue, oldValue))
      return;
    this.ezChange.emit(newValue);
  }
  observeErrorMessage(newValue) {
    if (newValue && this.previewMode) {
      this.previewMode = false;
    }
  }
  async handleExecuteToolbarCommand(event) {
    const { command, value } = event.detail;
    await this.executeCommand(command, value);
  }
  /**
   * Aplica o foco no campo.
   */
  async setFocus() {
    this.handleFocus();
  }
  /**
   * Remove o foco do campo.
   */
  async setBlur() {
    var _a;
    await ((_a = this.textAreaRef) === null || _a === void 0 ? void 0 : _a.setBlur());
  }
  /**
   * Retorna se o conteúdo é inválido.
   */
  async isInvalid() {
    return typeof this.errorMessage === 'string' && this.errorMessage.trim() !== '';
  }
  bindPreview() {
    if (!this._keyboardManager || !this.showPreview)
      return;
    this._keyboardManager
      .bind('ctrl + p', async () => {
      await this.togglePreview();
    }, { description: 'Entra em modo de pré visualização.', element: this.element });
  }
  bindConfigs() {
    if (!this._keyboardManager || !this.showConfigs)
      return;
    this._keyboardManager
      .bind('ctrl + l', async () => {
      await this.handleFormatSelection(RICH_TOOLBAR_FORMAT_TAGS.LIST);
    }, { description: this.i18n("ez-rich-text.listShortcut"), element: this.element })
      .bind('ctrl + k', async () => {
      await this.handleLink();
    }, { description: this.i18n("ez-rich-text.linkShortcut"), element: this.element })
      .bind('ctrl + o', async () => {
      await this.handleImage();
    }, { description: this.i18n("ez-rich-text.imageShortcut"), element: this.element });
  }
  bindTextFormat() {
    if (!this._keyboardManager || !this.showTextFormat)
      return;
    this._keyboardManager
      .bind('ctrl + b', async () => {
      await this.handleFormatSelection(RICH_TOOLBAR_FORMAT_TAGS.BOLD);
    }, { description: this.i18n("ez-rich-text.boldShortcut"), element: this.element })
      .bind('ctrl + i', async () => {
      await this.handleFormatSelection(RICH_TOOLBAR_FORMAT_TAGS.ITALIC);
    }, { description: this.i18n("ez-rich-text.italicShortcut"), element: this.element })
      .bind('ctrl + u', async () => {
      await this.handleFormatSelection(RICH_TOOLBAR_FORMAT_TAGS.UNDERLINE);
    }, { description: this.i18n("ez-rich-text.underlineShortcut"), element: this.element });
  }
  initKeyboardManager() {
    this._keyboardManager = new KeyboardManager({ propagate: false, element: this.element });
    this._keyboardManager
      .bind('ctrl + Enter', async () => {
      await this.handleFormatSelection(RICH_TOOLBAR_FORMAT_TAGS.BREAK_LINE);
    }, { description: this.i18n("ez-rich-text.breakLineShortcut"), element: this.element })
      .bind('ctrl + z', async () => {
      await this.handleUndo();
    }, { description: this.i18n("ez-rich-text.undoShortcut"), element: this.element })
      .bind('ctrl + x', async () => {
      await this.handleRedo();
    }, { description: this.i18n("ez-rich-text.redoShortcut"), element: this.element });
    this.bindPreview();
    this.bindConfigs();
    this.bindTextFormat();
  }
  async executeCommand(command, value) {
    switch (command) {
      case RICH_TOOLBAR_COMMANDS.FOCUS:
        this.handleFocus();
        break;
      case RICH_TOOLBAR_COMMANDS.PREVIEW:
        await this.togglePreview();
        break;
      case RICH_TOOLBAR_COMMANDS.FORMAT:
        await this.handleFormatSelection(value);
        break;
      case RICH_TOOLBAR_COMMANDS.UNDO:
        await this.handleUndo();
        break;
      case RICH_TOOLBAR_COMMANDS.REDO:
        await this.handleRedo();
        break;
      case RICH_TOOLBAR_COMMANDS.LINK:
        await this.handleLink();
        break;
      case RICH_TOOLBAR_COMMANDS.IMAGE:
        await this.handleImage();
        break;
    }
  }
  handleFocus() {
    this.previewMode = false;
    requestAnimationFrame(async () => {
      await this.textAreaRef.setFocus();
    });
  }
  async handleLink() {
    this.previewMode = false;
    requestAnimationFrame(async () => {
      await this.linkBuilderRef.show(this.getSelectedText());
    });
  }
  async handleImage() {
    this.previewMode = false;
    await this.imageUploaderRef.show();
  }
  async handleRedo() {
    this.previewMode = false;
    requestAnimationFrame(async () => {
      this.redo();
      await this.textAreaRef.setFocus();
    });
  }
  async handleUndo() {
    this.previewMode = false;
    requestAnimationFrame(async () => {
      this.undo();
      await this.textAreaRef.setFocus();
    });
  }
  async handleFormatSelection(value) {
    if (!value)
      return;
    this.previewMode = false;
    requestAnimationFrame(async () => {
      await this.formatSelection(value);
      await this.textAreaRef.setFocus();
    });
  }
  async togglePreview() {
    this.previewMode = !this.previewMode;
    if (this.previewMode) {
      await this.textAreaRef.setFocus();
    }
  }
  getSelectedText() {
    const textarea = this.getTextAreaElement();
    if (!textarea)
      return undefined;
    const selectionStart = textarea.selectionStart;
    const selectionEnd = textarea.selectionEnd;
    const currentValue = this.textAreaRef.value || '';
    return currentValue.substring(selectionStart, selectionEnd);
  }
  getTextAreaElement() {
    const textAreaElement = this.element.querySelector('ez-text-area');
    return textAreaElement.shadowRoot.querySelector('textarea');
  }
  async formatSelection(htmlTag) {
    if (!this.textAreaRef)
      return;
    const formattedHtml = htmlTag.replace('$selection', this.getSelectedText() || '');
    await this.textAreaRef.appendTextToSelection(formattedHtml);
    this.value = this.textAreaRef.value;
    this.addToHistory(this.value);
  }
  addToHistory(content) {
    // Só adiciona ao histórico se for diferente do estado atual
    if (this.historyIndex >= 0 && content === this.historyStack[this.historyIndex]) {
      return;
    }
    //se o tamanho do histórico chegou ao máximo, faz um splice mantendo os últimos 49 elementos
    if (this.historyStack.length >= 50) {
      this.historyStack.splice(0, this.historyStack.length - 49);
    }
    //Adiciona novo estado ao histórico
    this.historyStack.push(content);
    this.historyIndex = this.historyStack.length - 1;
  }
  undo() {
    if (!this.canExecuteUndo())
      return;
    this.historyIndex--;
    const content = this.historyStack[this.historyIndex];
    this.value = content;
    this.textAreaRef.value = content;
  }
  canExecuteUndo() {
    return this.historyIndex > 0;
  }
  redo() {
    if (!this.canExecuteRedo())
      return;
    this.historyIndex++;
    this.getValueFromHistory();
  }
  canExecuteRedo() {
    return this.historyIndex < this.historyStack.length - 1;
  }
  getValueFromHistory() {
    const content = this.historyStack[this.historyIndex];
    this.value = content;
    this.textAreaRef.value = content;
  }
  handleTextAreaChanged(event) {
    this.value = event.detail;
    this.addToHistory(this.value);
  }
  async removeShortcuts() {
    var _a;
    (_a = this._keyboardManager) === null || _a === void 0 ? void 0 : _a.unbindAllShortcutKeys();
  }
  async componentWillLoad() {
    this.i18n = await initI18n();
  }
  componentDidLoad() {
    this.initKeyboardManager();
    this.addToHistory(this.value);
  }
  async disconnectedCallback() {
    await this.removeShortcuts();
  }
  getSanitizedValue() {
    return purify.sanitize(this.value, {
      ADD_ATTR: ['target', 'rel']
    });
  }
  renderContent() {
    if (this.previewMode) {
      return (h("div", { id: 'rich-text-preview-container', class: "preview", innerHTML: this.getSanitizedValue() }));
    }
    return h("ez-text-area", { ref: (el) => this.textAreaRef = el, label: this.label, value: this.value, enabled: this.enabled, rows: this.rows, mode: this.mode, canShowError: this.canShowError, errorMessage: this.errorMessage, onEzChange: this.handleTextAreaChanged.bind(this) });
  }
  render() {
    return (h(Host, null, h("div", { class: 'editor-container bordered' }, h("ez-rich-toolbar", { isPreviewMode: this.previewMode, showPreview: this.showPreview, showConfigs: this.showConfigs && this.enabled, showTextFormat: this.showTextFormat && this.enabled, showUndoRedo: this.showUndoRedo && this.enabled }), this.renderContent()), h("ez-link-builder", { ref: (el) => this.linkBuilderRef = el }), h("ez-simple-image-uploader", { ref: (el) => this.imageUploaderRef = el })));
  }
  get element() { return getElement(this); }
  static get watchers() { return {
    "value": ["observeValue"],
    "errorMessage": ["observeErrorMessage"]
  }; }
};
EzRichText.style = ezRichTextCss;

const ezTextEditCss = ":host{display:flex;align-items:center;gap:5px}.text-edit__form-input{width:auto;--ez-text-input__input--padding:0px}.text-edit__hidden-value{visibility:hidden;position:absolute;white-space:nowrap;z-index:-1;top:0;left:0}";

const EzTextEdit = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.saveEdition = createEvent(this, "saveEdition", 7);
    this.cancelEdition = createEvent(this, "cancelEdition", 7);
    this._newValue = undefined;
    this.value = undefined;
    this.styled = undefined;
  }
  /**
   * Aplica foco no campo.
   */
  async applyFocusSelect() {
    this.calcSizeInput(this.value, true);
  }
  calcSizeInput(value, setSelect = false) {
    var _a, _b;
    const textInput = (_b = (_a = this._inputElement) === null || _a === void 0 ? void 0 : _a.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelector('input');
    if (textInput != undefined) {
      const sizeText = this.getWidthValue(value);
      textInput.style.width = sizeText + 'px';
      if (setSelect) {
        setTimeout(() => textInput.select(), 100);
      }
    }
  }
  getWidthValue(value) {
    if (this._valueBasis != undefined) {
      const span = this._valueBasis;
      if (value != undefined) {
        const cursorSpace = 2;
        span.innerHTML = value;
        return span.clientWidth > 0 ? (span.clientWidth + cursorSpace) : cursorSpace;
      }
      else {
        span.innerHTML = "";
      }
    }
    return 0;
  }
  setStyledInput() {
    var _a, _b;
    let fontSize = "";
    let fontWeight = "";
    let fontFamily = "";
    if (this.styled != undefined) {
      fontSize = this.styled.fontSize;
      fontWeight = this.styled.fontWeight;
      fontFamily = this.styled.fontFamily;
    }
    const textInput = (_b = (_a = this._inputElement) === null || _a === void 0 ? void 0 : _a.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelector('input');
    if (textInput != undefined) {
      textInput.style.fontSize = fontSize;
      textInput.style.fontWeight = fontWeight;
      textInput.style.fontFamily = fontFamily;
    }
    const span = this._valueBasis;
    if (span != undefined) {
      span.style.fontSize = fontSize;
      span.style.fontWeight = fontWeight;
      span.style.fontFamily = fontFamily;
    }
  }
  handleSaveEdition() {
    if (!this._newValue) {
      ApplicationUtils.alert(this.i18n("app.warning"), this.i18n("ez-text-edit.emptyFieldWarning")).then(() => {
        this.setNewValue(this.value, true);
      });
      return;
    }
    this.saveEdition.emit({ value: this.value, newValue: this._newValue });
  }
  handleCancelEdition() {
    this.cancelEdition.emit();
  }
  setNewValue(value, setSelect = false) {
    this._newValue = value;
    this.calcSizeInput(this._newValue, setSelect);
  }
  async componentWillLoad() {
    this.i18n = await initI18n();
  }
  componentDidLoad() {
    this.applyFocusSelect();
    this.setNewValue(this.value);
  }
  componentDidRender() {
    this.setStyledInput();
  }
  render() {
    ElementIDUtils.addIDInfoIfNotExists(this._element, 'input');
    return (h(Host, null, h("span", { class: "text-edit__hidden-value", ref: elem => this._valueBasis = elem }), h("ez-text-input", { "data-element-id": ElementIDUtils.getInternalIDInfo("textInput"), onInput: () => { this.calcSizeInput(this._newValue); }, class: "text-edit__form-input", value: this._newValue, ref: (elem) => this._inputElement = elem, mode: "slim", onEzChange: (evt) => this.setNewValue(evt === null || evt === void 0 ? void 0 : evt.detail), noBorder: true }), h("ez-button", { class: "text-edit__icon-check", mode: "icon", iconName: "check", size: "small", onClick: () => { this.handleSaveEdition(); } }), h("ez-button", { class: "text-edit__icon-close", mode: "icon", iconName: "close", size: "small", onClick: () => { this.handleCancelEdition(); } })));
  }
  get _element() { return getElement(this); }
};
EzTextEdit.style = ezTextEditCss;

export { EzComboBoxList as ez_combo_box_list, EzCustomFormInput as ez_custom_form_input, EzRichText as ez_rich_text, EzTextEdit as ez_text_edit };
