import { _ as _applyDecoratedDescriptor, a as _initializerDefineProperty } from '../_rollupPluginBabelHelpers-9wjJaosZ.js';
import { setComponentTemplate } from '@ember/component';
import { precompileTemplate } from '@ember/template-compilation';
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { helper } from '@ember/component/helper';
import { hash } from '@ember/helper';
import { action } from '@ember/object';
import didInsert from '@ember/render-modifiers/modifiers/did-insert';
import { scheduleOnce } from '@ember/runloop';
import onKey from 'ember-keyboard/modifiers/on-key';
import { modifier } from 'ember-modifier';
import set from 'ember-set-helper/helpers/set';
import style from 'ember-style-modifier/modifiers/style';
import { or, and, eq, not } from 'ember-truth-helpers';
import EuiCodeBlockControls from './eui-code-block/controls.js';
import FullScreenDisplay from './eui-code-block/full-screen-display.js';
import EuiCodeBlockVirtualizedComponent from './eui-code-block/virtualized.js';
import EuiImage from './eui-inner-text.js';
import classNames from '../helpers/class-names.js';
import mutationObserver from '../modifiers/mutation-observer.js';
import ResizeObserver from '../modifiers/resize-observer.js';
import { checkSupportedLanguage, highlightByLine, getHtmlContent } from '../utils/code/utils.js';

var _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7;
const fontSizeToRowHeightMap = {
  s: 18,
  m: 21,
  l: 24
};
const highlightTargetModifier = modifier((_e, _pos, {
  element: targetEle,
  language = 'text',
  lineNumbersConfig = {
    start: 1,
    show: false
  },
  onChange
}) => {
  let observer;
  const getHighlighedHtml = () => {
    const html = (targetEle?.textContent ? targetEle.textContent : '').trim();
    let data;
    if (typeof html !== 'string') {
      data = [];
    } else {
      data = highlightByLine(html, language, lineNumbersConfig);
    }
    return {
      data,
      element: getHtmlContent(data).element
    };
  };
  const setupObserver = () => {
    const newObserver = new MutationObserver(mutationsList => {
      if (mutationsList.length) {
        onChange(getHighlighedHtml());
      }
    });
    if (targetEle) {
      onChange(getHighlighedHtml());
      newObserver.observe(targetEle, {
        characterData: true,
        subtree: true,
        childList: true
      });
    }
    return newObserver;
  };
  if (targetEle) {
    observer = setupObserver();
  }
  return () => {
    observer?.disconnect();
  };
});
const cleanTextHelper = helper(function ([text]) {
  return text?.replace(/[\r\n?]{2}|\n\n/g, '\n') || '';
});
const textToCopyHelper = helper(function (_pos, {
  isVirtualized,
  element,
  innerText
}) {
  if (element) {
    return isVirtualized ? element.textContent ? element.textContent : '' : innerText;
  }
  return '';
});
let EuiCodeBlockComponent = setComponentTemplate(precompileTemplate(`
    {{! DO NOT FORMAT AT ALL, PRE TAGS RESPECT WHITESPACE LITERALLY }}
    {{! DO NOT FORMAT AT ALL, PRE TAGS RESPECT WHITESPACE LITERALLY }}
    {{! DO NOT FORMAT AT ALL, PRE TAGS RESPECT WHITESPACE LITERALLY }}
    {{! DO NOT FORMAT AT ALL, PRE TAGS RESPECT WHITESPACE LITERALLY }}
    {{! DO NOT FORMAT AT ALL, PRE TAGS RESPECT WHITESPACE LITERALLY }}
    {{! DO NOT FORMAT AT ALL, PRE TAGS RESPECT WHITESPACE LITERALLY }}
    {{! DO NOT FORMAT AT ALL, PRE TAGS RESPECT WHITESPACE LITERALLY }}
    {{! DO NOT FORMAT AT ALL, PRE TAGS RESPECT WHITESPACE LITERALLY }}
    {{! DO NOT FORMAT AT ALL, PRE TAGS RESPECT WHITESPACE LITERALLY }}
    {{#if this.codeTarget}}
      {{#in-element this.codeTarget}}
        {{yield}}
      {{/in-element}}
    {{/if}}
    <EuiInnerText as |setInnerTextRef innerText|>
      {{#let
        (classNames
          "euiCodeBlock"
          (if
            (or this.showCopyButton this.showFullScreenButton)
            "euiCodeBlock--hasControl"
          )
          (if
            (and this.showCopyButton this.showFullScreenButton)
            "euiCodeBlock--hasBothControls"
          )
          (if this.lineNumbersConfig.show "euiCodeBlock--hasLineNumbers")
          @className
        )
        (classNames
          "euiCodeBlock__pre"
          (if
            (or (eq this.whiteSpace "pre") this.isVirtualized)
            "euiCodeBlock__pre--whiteSpacePre"
          )
          (if
            (and (eq this.whiteSpace "pre-wrap") (not this.isVirtualized))
            "euiCodeBlock__pre--whiteSpacePreWrap"
          )
          (if this.isVirtualized "euiCodeBlock__pre--isVirtualized")
        )
        as |wrapperClasses preClasses|
      }}
        <div
          class={{classNames
            wrapperClasses
            (if
              this.transparentBackground "euiCodeBlock--transparentBackground"
            )
            componentName="EuiCodeBlock"
            fontSize=this.fontSize
            paddingSize=this.paddingSize
          }}
          {{style this.optionalStyles}}
          {{highlightTargetModifier
            element=this.codeTarget
            language=this.language
            lineNumbersConfig=this.lineNumbersConfig
            onChange=this.updateCode
          }}
        >
          {{#if this.isVirtualized}}
            {{!virtualized}}
            <VirtualizedCodeBlock
              class={{preClasses}}
              tabindex="0"
              {{onKey "Escape" this.closeFullScreen}}
              @language={{this.language}}
              @data={{this.data.data}}
              @rowHeight={{this.rowHeight}}
            />
          {{else}}
            {{!template-lint-disable}}
            <pre
              class={{preClasses}}
              {{style this.optionalStyles}}
              tabindex={{this.tabIndex}}
              {{didInsert (set this "wrapperRef")}}
              {{resizeObserver onResize=this.doesOverflow}}
              {{mutationObserver
                onMutation=this.doesOverflow
                observerOptions=(hash subtree=true childList=true)
              }}
              {{didInsert setInnerTextRef}}
            ><code
                class="euiCodeBlock__code"
                data-code-language={{this.language}}
                {{didInsert (set this "code")}}
                ...attributes
              ></code></pre>

          {{/if}}

          <Controls
            @isFullScreen={{this.isFullScreen}}
            @showFullScreenButton={{this.showFullScreenButton}}
            @toggleFullScreen={{this.toggleFullScreen}}
            @showCopyButton={{this.showCopyButton}}
            @textToCopy={{textToCopyHelper
              isVirtualized=this.isVirtualized
              innerText=(cleanTextHelper innerText)
              element=this.data.element
            }}
          />

          {{#if this.isFullScreen}}
            <FullScreenDisplay class={{wrapperClasses}}>
              {{#if this.isVirtualized}}
                <VirtualizedCodeBlock
                  class={{preClasses}}
                  tabindex="0"
                  {{onKey "Escape" this.closeFullScreen}}
                  @language={{this.language}}
                  @data={{this.data.data}}
                  @rowHeight={{fontSizeToRowHeightMap.l}}
                />
              {{else}}
                <pre
                  class={{preClasses}}
                  tabindex="0"
                  {{onKey "Escape" this.closeFullScreen}}
                ><code
                    class="euiCodeBlock__code"
                    data-code-language={{this.language}}
                    {{didInsert (set this "codeFullScreen")}}
                  ></code></pre>
              {{/if}}
              <Controls
                @isFullScreen={{this.isFullScreen}}
                @showFullScreenButton={{this.showFullScreenButton}}
                @showCopyButton={{this.showCopyButton}}
                @toggleFullScreen={{this.toggleFullScreen}}
                @textToCopy={{textToCopyHelper
                  isVirtualized=this.isVirtualized
                  innerText=(cleanTextHelper innerText)
                  element=this.data.element
                }}
              />
            </FullScreenDisplay>
          {{/if}}
        </div>
      {{/let}}
    </EuiInnerText>
  `, {
  strictMode: true,
  scope: () => ({
    EuiInnerText: EuiImage,
    classNames,
    or,
    and,
    eq,
    not,
    style,
    highlightTargetModifier,
    VirtualizedCodeBlock: EuiCodeBlockVirtualizedComponent,
    onKey,
    didInsert,
    set,
    resizeObserver: ResizeObserver,
    mutationObserver,
    hash,
    Controls: EuiCodeBlockControls,
    textToCopyHelper,
    cleanTextHelper,
    FullScreenDisplay,
    fontSizeToRowHeightMap
  })
}), (_class = class EuiCodeBlockComponent extends Component {
  get language() {
    return checkSupportedLanguage(this.args.language || '');
  }
  get transparentBackground() {
    return this.args.transparentBackground ?? false;
  }
  get paddingSize() {
    return this.args.paddingSize ?? 'l';
  }
  get fontSize() {
    return this.args.fontSize ?? 's';
  }
  get isCopyable() {
    return this.args.isCopyable ?? false;
  }
  get whiteSpace() {
    return this.args.whiteSpace ?? 'pre-wrap';
  }
  get isVirtualized() {
    return !!(this.args.isVirtualized && Array.isArray(this.data?.data));
  }
  get lineNumbers() {
    return this.args.lineNumbers ?? false;
  }
  get lineNumbersConfig() {
    const {
      lineNumbers
    } = this;
    const config = typeof lineNumbers === 'object' ? lineNumbers : {};
    return lineNumbers ? {
      start: 1,
      show: true,
      ...config
    } : {
      start: 1,
      show: false
    };
  }
  get optionalStyles() {
    const overflowHeight = this.args.overflowHeight;
    if (overflowHeight) {
      const property = typeof overflowHeight === 'string' ? 'height' : 'maxHeight';
      return {
        [property]: typeof overflowHeight === 'string' ? overflowHeight : `${overflowHeight}px`
      };
    }
    return {};
  }
  get showCopyButton() {
    return this.isCopyable && true;
  }
  get rowHeight() {
    return fontSizeToRowHeightMap[this.fontSize];
  }
  get showFullScreenButton() {
    return !!this.args.overflowHeight;
  }
  constructor(owner, args) {
    super(owner, args);
    //fake element where yield writes to, so we can observe and clone a highlighted version to code and codeFullSceen
    _initializerDefineProperty(this, "codeTarget", _descriptor, this);
    //<code> Element for non fullscreen
    _initializerDefineProperty(this, "code", _descriptor2, this);
    //<code> Element for fullscreen modal
    _initializerDefineProperty(this, "codeFullScreen", _descriptor3, this);
    _initializerDefineProperty(this, "wrapperRef", _descriptor4, this);
    _initializerDefineProperty(this, "tabIndex", _descriptor5, this);
    _initializerDefineProperty(this, "isFullScreen", _descriptor6, this);
    _initializerDefineProperty(this, "data", _descriptor7, this);
    this.codeTarget = document.createElement('div');
  }
  toggleFullScreen() {
    this.isFullScreen = !this.isFullScreen;
  }
  closeFullScreen(e) {
    e.preventDefault();
    e.stopPropagation();
    this.isFullScreen = false;
  }
  doesOverflow() {
    if (!this.wrapperRef) return;
    const {
      clientWidth,
      clientHeight,
      scrollWidth,
      scrollHeight
    } = this.wrapperRef;
    const doesOverflow = scrollHeight > clientHeight || scrollWidth > clientWidth;
    this.tabIndex = doesOverflow ? 0 : -1;
  }
  updateCode(resp) {
    const render = () => {
      const code = this.code;
      const codeFullScreen = this.codeFullScreen;
      if (code && !this.isFullScreen) {
        this.data = resp;
        code.innerHTML = resp.element.innerHTML;
      }
      if (codeFullScreen && this.isFullScreen) {
        this.data = resp;
        codeFullScreen.innerHTML = resp.element.innerHTML;
      }
    };
    scheduleOnce('afterRender', this, render);
  }
  willDestroy() {
    super.willDestroy();
    this.codeTarget = undefined;
    this.code = undefined;
    this.codeFullScreen = undefined;
    this.wrapperRef = undefined;
  }
}, (_descriptor = _applyDecoratedDescriptor(_class.prototype, "codeTarget", [tracked], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: null
}), _descriptor2 = _applyDecoratedDescriptor(_class.prototype, "code", [tracked], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: null
}), _descriptor3 = _applyDecoratedDescriptor(_class.prototype, "codeFullScreen", [tracked], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: null
}), _descriptor4 = _applyDecoratedDescriptor(_class.prototype, "wrapperRef", [tracked], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: null
}), _descriptor5 = _applyDecoratedDescriptor(_class.prototype, "tabIndex", [tracked], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: function () {
    return 1;
  }
}), _descriptor6 = _applyDecoratedDescriptor(_class.prototype, "isFullScreen", [tracked], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: function () {
    return false;
  }
}), _descriptor7 = _applyDecoratedDescriptor(_class.prototype, "data", [tracked], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: null
}), _applyDecoratedDescriptor(_class.prototype, "toggleFullScreen", [action], Object.getOwnPropertyDescriptor(_class.prototype, "toggleFullScreen"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "closeFullScreen", [action], Object.getOwnPropertyDescriptor(_class.prototype, "closeFullScreen"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "doesOverflow", [action], Object.getOwnPropertyDescriptor(_class.prototype, "doesOverflow"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "updateCode", [action], Object.getOwnPropertyDescriptor(_class.prototype, "updateCode"), _class.prototype)), _class));

export { EuiCodeBlockComponent as default };
//# sourceMappingURL=eui-code-block.js.map
