"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FieldEditor = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _lodash = require("lodash");
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _i18nReact = require("@kbn/i18n-react");
var _monaco = require("@kbn/monaco");
var _public = require("@kbn/kibana-react-plugin/public");
var _scripting_languages = require("../../scripting_languages");
var _scripting_call_outs = require("./components/scripting_call_outs");
var _scripting_help = require("./components/scripting_help");
var _field_format_editor = require("./components/field_format_editor");
var _constants = require("./constants");
var _lib = require("./lib");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

const getFieldTypeFormatsList = (field, defaultFieldFormat, fieldFormats) => {
  const formatsByType = fieldFormats.getByFieldType(field.type).map(({
    id,
    title
  }) => ({
    id,
    title
  }));
  return [{
    id: '',
    defaultFieldFormat,
    title: _i18n.i18n.translate('indexPatternManagement.defaultFormatDropDown', {
      defaultMessage: '- Default -'
    })
  }, ...formatsByType];
};
class FieldEditor extends _react.PureComponent {
  constructor(props, context) {
    super(props, context);
    (0, _defineProperty2.default)(this, "supportedLangs", []);
    (0, _defineProperty2.default)(this, "deprecatedLangs", []);
    (0, _defineProperty2.default)(this, "onFieldChange", (fieldName, value) => {
      const {
        spec
      } = this.state;
      spec[fieldName] = value;
      this.forceUpdate();
    });
    (0, _defineProperty2.default)(this, "onTypeChange", type => {
      const {
        fieldFormats
      } = this.context.services;
      const {
        spec,
        format
      } = this.state;
      const DefaultFieldFormat = fieldFormats.getDefaultType(type);
      spec.type = type;
      this.setState({
        fieldTypeFormats: getFieldTypeFormatsList(spec, DefaultFieldFormat, fieldFormats),
        fieldFormatId: DefaultFieldFormat.id,
        fieldFormatParams: format.params()
      });
    });
    (0, _defineProperty2.default)(this, "onLangChange", lang => {
      const {
        spec
      } = this.state;
      const fieldTypes = (0, _lodash.get)(_constants.FIELD_TYPES_BY_LANG, lang, _constants.DEFAULT_FIELD_TYPES);
      spec.lang = lang;
      spec.type = fieldTypes.includes(spec.type) ? spec.type : fieldTypes[0];
      this.setState({
        fieldTypes
      });
    });
    (0, _defineProperty2.default)(this, "onFormatChange", (formatId, params) => {
      const {
        fieldTypeFormats
      } = this.state;
      const {
        uiSettings,
        fieldFormats
      } = this.context.services;
      const FieldFormat = fieldFormats.getType(formatId || fieldTypeFormats[0].defaultFieldFormat.id);
      const newFormat = new FieldFormat(params, key => uiSettings.get(key));
      this.setState({
        fieldFormatId: formatId,
        fieldFormatParams: params,
        format: newFormat
      });
    });
    (0, _defineProperty2.default)(this, "onFormatParamsChange", newParams => {
      const {
        fieldFormatId
      } = this.state;
      this.onFormatChange(fieldFormatId, newParams);
    });
    (0, _defineProperty2.default)(this, "onFormatParamsError", error => {
      this.setState({
        hasFormatError: !!error
      });
    });
    (0, _defineProperty2.default)(this, "onScriptChange", value => {
      this.setState({
        hasScriptError: false
      });
      this.onFieldChange('script', value);
    });
    (0, _defineProperty2.default)(this, "showScriptingHelp", () => {
      this.setState({
        showScriptingHelp: true
      });
    });
    (0, _defineProperty2.default)(this, "hideScriptingHelp", () => {
      this.setState({
        showScriptingHelp: false
      });
    });
    (0, _defineProperty2.default)(this, "renderDeleteModal", () => {
      const {
        spec
      } = this.state;
      return this.state.showDeleteModal ? /*#__PURE__*/_react.default.createElement(_eui.EuiConfirmModal, {
        title: _i18n.i18n.translate('indexPatternManagement.deleteFieldHeader', {
          defaultMessage: "Delete field '{fieldName}'",
          values: {
            fieldName: spec.name
          }
        }),
        onCancel: this.hideDeleteModal,
        onConfirm: () => {
          this.hideDeleteModal();
          this.deleteField();
        },
        cancelButtonText: _i18n.i18n.translate('indexPatternManagement.deleteField.cancelButton', {
          defaultMessage: 'Cancel'
        }),
        confirmButtonText: _i18n.i18n.translate('indexPatternManagement.deleteField.deleteButton', {
          defaultMessage: 'Delete'
        }),
        buttonColor: "danger",
        defaultFocusedButton: _eui.EUI_MODAL_CONFIRM_BUTTON
      }, /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "indexPatternManagement.deleteFieldLabel",
        defaultMessage: "You can't recover a deleted field.{separator}Are you sure you want to do this?",
        values: {
          separator: /*#__PURE__*/_react.default.createElement("span", null, /*#__PURE__*/_react.default.createElement("br", null), /*#__PURE__*/_react.default.createElement("br", null))
        }
      }))) : null;
    });
    (0, _defineProperty2.default)(this, "showDeleteModal", () => {
      this.setState({
        showDeleteModal: true
      });
    });
    (0, _defineProperty2.default)(this, "hideDeleteModal", () => {
      this.setState({
        showDeleteModal: false
      });
    });
    (0, _defineProperty2.default)(this, "renderScriptingPanels", () => {
      const {
        scriptingLangs,
        spec,
        showScriptingHelp
      } = this.state;
      if (!spec.scripted) {
        return;
      }
      return /*#__PURE__*/_react.default.createElement(_react.Fragment, null, /*#__PURE__*/_react.default.createElement(_scripting_call_outs.ScriptingDisabledCallOut, {
        isVisible: !scriptingLangs.length
      }), /*#__PURE__*/_react.default.createElement(_scripting_call_outs.ScriptingWarningCallOut, {
        isVisible: true
      }), /*#__PURE__*/_react.default.createElement(_scripting_help.ScriptingHelpFlyout, {
        isVisible: showScriptingHelp,
        onClose: this.hideScriptingHelp,
        indexPattern: this.props.indexPattern,
        lang: spec.lang,
        name: spec.name,
        script: spec.script,
        executeScript: _lib.executeScript
      }));
    });
    (0, _defineProperty2.default)(this, "deleteField", () => {
      const {
        redirectAway,
        indexPatternService
      } = this.props.services;
      const {
        indexPattern
      } = this.props;
      const {
        spec
      } = this.state;
      indexPattern.removeScriptedField(spec.name);
      indexPatternService.updateSavedObject(indexPattern).then(() => {
        const message = _i18n.i18n.translate('indexPatternManagement.deleteField.deletedHeader', {
          defaultMessage: "Deleted '{fieldName}'",
          values: {
            fieldName: spec.name
          }
        });
        this.context.services.notifications.toasts.addSuccess(message);
        redirectAway();
      });
    });
    (0, _defineProperty2.default)(this, "saveField", async () => {
      const field = this.state.spec;
      const {
        indexPattern
      } = this.props;
      const {
        fieldFormatId,
        fieldFormatParams,
        customLabel
      } = this.state;
      if (field.scripted) {
        this.setState({
          isSaving: true
        });
        const isValid = await (0, _lib.isScriptValid)({
          name: field.name,
          script: field.script,
          indexPatternTitle: indexPattern.title,
          http: this.context.services.http
        });
        if (!isValid) {
          this.setState({
            hasScriptError: true,
            isSaving: false
          });
          return;
        }
      }
      const {
        redirectAway,
        indexPatternService
      } = this.props.services;
      const fieldExists = !!indexPattern.fields.getByName(field.name);
      let oldField;
      if (fieldExists) {
        oldField = indexPattern.fields.getByName(field.name).spec;
        indexPattern.fields.update(field);
      } else {
        indexPattern.fields.add(field);
      }
      if (fieldFormatId) {
        indexPattern.setFieldFormat(field.name, {
          id: fieldFormatId,
          params: fieldFormatParams
        });
      } else {
        indexPattern.deleteFieldFormat(field.name);
      }
      if (field.customLabel !== customLabel) {
        field.customLabel = customLabel;
        indexPattern.fields.update(field);
      }
      return indexPatternService.updateSavedObject(indexPattern).then(() => {
        const message = _i18n.i18n.translate('indexPatternManagement.deleteField.savedHeader', {
          defaultMessage: "Saved '{fieldName}'",
          values: {
            fieldName: field.name
          }
        });
        this.context.services.notifications.toasts.addSuccess(message);
        redirectAway();
      }).catch(() => {
        if (oldField) {
          indexPattern.fields.update(oldField);
        } else {
          indexPattern.fields.remove(field);
        }
      });
    });
    const {
      spec: _spec,
      indexPattern: _indexPattern
    } = props;
    this.state = {
      isReady: false,
      isCreating: false,
      isDeprecatedLang: false,
      scriptingLangs: [],
      fieldTypes: [],
      fieldTypeFormats: [],
      existingFieldNames: _indexPattern.fields.getAll().map(f => f.name),
      fieldFormatId: undefined,
      fieldFormatParams: {},
      showScriptingHelp: false,
      showDeleteModal: false,
      hasFormatError: false,
      hasScriptError: false,
      isSaving: false,
      format: props.indexPattern.getFormatterForField(_spec),
      spec: {
        ..._spec
      },
      customLabel: ''
    };
    this.supportedLangs = (0, _scripting_languages.getSupportedScriptingLanguages)();
    this.deprecatedLangs = (0, _scripting_languages.getDeprecatedScriptingLanguages)();
    this.init(context);
  }
  async init(context) {
    var _indexPattern$getForm, _indexPattern$getForm2;
    const {
      http,
      notifications,
      fieldFormats
    } = context.services;
    const {
      format,
      spec
    } = this.state;
    const {
      indexPattern
    } = this.props;
    const enabledLangs = await (0, _scripting_languages.getEnabledScriptingLanguages)(http, notifications.toasts);
    const scriptingLangs = (0, _lodash.intersection)(enabledLangs, (0, _lodash.union)(this.supportedLangs, this.deprecatedLangs));
    spec.lang = spec.lang && scriptingLangs.includes(spec.lang) ? spec.lang : undefined;
    if (spec.scripted && !spec.lang) {
      spec.lang = scriptingLangs[0];
    }
    const fieldTypes = (0, _lodash.get)(_constants.FIELD_TYPES_BY_LANG, spec.lang || '', _constants.DEFAULT_FIELD_TYPES);
    spec.type = fieldTypes.includes(spec.type) ? spec.type : fieldTypes[0];
    const DefaultFieldFormat = fieldFormats.getDefaultType(spec.type, spec.esTypes);
    this.setState({
      isReady: true,
      isCreating: !indexPattern.fields.getByName(spec.name),
      isDeprecatedLang: this.deprecatedLangs.includes(spec.lang || ''),
      errors: [],
      scriptingLangs,
      fieldTypes,
      fieldTypeFormats: getFieldTypeFormatsList(spec, DefaultFieldFormat, fieldFormats),
      fieldFormatId: (_indexPattern$getForm = indexPattern.getFormatterForFieldNoDefault(spec.name)) === null || _indexPattern$getForm === void 0 ? void 0 : (_indexPattern$getForm2 = _indexPattern$getForm.type) === null || _indexPattern$getForm2 === void 0 ? void 0 : _indexPattern$getForm2.id,
      customLabel: spec.customLabel || '',
      fieldFormatParams: format.params()
    });
  }
  isDuplicateName() {
    const {
      isCreating,
      spec,
      existingFieldNames
    } = this.state;
    return isCreating && existingFieldNames.includes(spec.name);
  }
  renderName() {
    var _spec$name;
    const {
      isCreating,
      spec
    } = this.state;
    const starCheck = spec === null || spec === void 0 ? void 0 : (_spec$name = spec.name) === null || _spec$name === void 0 ? void 0 : _spec$name.includes('*');
    const isInvalid = !spec.name || !spec.name.trim() || starCheck;
    return isCreating ? /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
      label: _i18n.i18n.translate('indexPatternManagement.nameLabel', {
        defaultMessage: 'Name'
      }),
      helpText: this.isDuplicateName() ? /*#__PURE__*/_react.default.createElement("span", null, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
        type: "warning",
        color: "warning",
        size: "s"
      }), "\xA0", /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "indexPatternManagement.mappingConflictLabel.mappingConflictDetail",
        defaultMessage: "{mappingConflict} You already have a field with the name {fieldName}. Naming your scripted field with the same name means you won't be able to query both fields at the same time.",
        values: {
          mappingConflict: /*#__PURE__*/_react.default.createElement("strong", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "indexPatternManagement.mappingConflictLabel.mappingConflictLabel",
            defaultMessage: "Mapping Conflict:"
          })),
          fieldName: /*#__PURE__*/_react.default.createElement(_eui.EuiCode, null, spec.name)
        }
      })) : null,
      isInvalid: isInvalid,
      error: isInvalid && (starCheck ? _i18n.i18n.translate('indexPatternManagement.starCharacterNotAllowedValidationErrorMessage', {
        defaultMessage: 'The field cannot have * in the name.'
      }) : _i18n.i18n.translate('indexPatternManagement.nameErrorMessage', {
        defaultMessage: 'Name is required'
      }))
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFieldText, {
      value: spec.name || '',
      placeholder: _i18n.i18n.translate('indexPatternManagement.namePlaceholder', {
        defaultMessage: 'New scripted field'
      }),
      "data-test-subj": "editorFieldName",
      onChange: e => {
        this.onFieldChange('name', e.target.value);
      },
      isInvalid: isInvalid
    })) : null;
  }
  renderLanguage() {
    const {
      spec,
      scriptingLangs,
      isDeprecatedLang
    } = this.state;
    return spec.scripted ? /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
      label: _i18n.i18n.translate('indexPatternManagement.languageLabel', {
        defaultMessage: 'Language'
      }),
      helpText: isDeprecatedLang ? /*#__PURE__*/_react.default.createElement("span", null, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
        type: "warning",
        color: "warning",
        size: "s"
      }), "\xA0", /*#__PURE__*/_react.default.createElement("strong", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "indexPatternManagement.warningHeader",
        defaultMessage: "Deprecation Warning:"
      })), "\xA0", /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "indexPatternManagement.warningLabel.warningDetail",
        defaultMessage: "{language} is deprecated and support will be removed in the next major version of Kibana and Elasticsearch. We recommend using {painlessLink} for new scripted fields.",
        values: {
          language: /*#__PURE__*/_react.default.createElement(_eui.EuiCode, null, spec.lang),
          painlessLink: /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
            target: "_blank",
            href: this.context.services.docLinks.links.scriptedFields.painless
          }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "indexPatternManagement.warningLabel.painlessLinkLabel",
            defaultMessage: "Painless"
          }))
        }
      })) : null
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiSelect, {
      value: spec.lang,
      options: scriptingLangs.map(lang => {
        return {
          value: lang,
          text: lang
        };
      }),
      "data-test-subj": "editorFieldLang",
      onChange: e => {
        this.onLangChange(e.target.value);
      }
    })) : null;
  }
  renderType() {
    const {
      spec,
      fieldTypes
    } = this.state;
    return /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
      label: _i18n.i18n.translate('indexPatternManagement.typeLabel', {
        defaultMessage: 'Type'
      })
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiSelect, {
      value: spec.type,
      disabled: !spec.scripted,
      options: fieldTypes.map(type => {
        return {
          value: type,
          text: type
        };
      }),
      "data-test-subj": "editorFieldType",
      onChange: e => {
        this.onTypeChange(e.target.value);
      }
    }));
  }
  renderCustomLabel() {
    const {
      customLabel,
      spec
    } = this.state;
    return /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
      label: _i18n.i18n.translate('indexPatternManagement.customLabel', {
        defaultMessage: 'Custom label'
      }),
      helpText: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "indexPatternManagement.labelHelpText",
        defaultMessage: "Set a custom label to use when this field is displayed in Discover, Maps, and Visualize. Queries and filters don't currently support a custom label and will use the original field name."
      })
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFieldText, {
      value: customLabel || '',
      placeholder: spec.name,
      "data-test-subj": "editorFieldCustomLabel",
      onChange: e => {
        this.setState({
          customLabel: e.target.value
        });
      }
    }));
  }

  /**
   * renders a warning and a table of conflicting indices
   * in case there are indices with different types
   */
  renderTypeConflict() {
    const {
      spec
    } = this.state;
    if (!spec.conflictDescriptions || typeof spec.conflictDescriptions !== 'object') {
      return null;
    }
    const columns = [{
      field: 'type',
      name: _i18n.i18n.translate('indexPatternManagement.typeLabel', {
        defaultMessage: 'Type'
      }),
      width: '100px'
    }, {
      field: 'indices',
      name: _i18n.i18n.translate('indexPatternManagement.indexNameLabel', {
        defaultMessage: 'Index names'
      })
    }];
    const items = Object.entries(spec.conflictDescriptions).map(([type, indices]) => ({
      type,
      indices: Array.isArray(indices) ? indices.join(', ') : 'Index names unavailable'
    }));
    return /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "m"
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiCallOut, {
      color: "warning",
      iconType: "warning",
      title: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "indexPatternManagement.fieldTypeConflict",
        defaultMessage: "Field type conflict"
      }),
      size: "s"
    }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.multiTypeLabelDesc",
      defaultMessage: "The type of this field changes across indices. It is unavailable for many analysis functions. The indices per type are as follows:"
    })), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "m"
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiBasicTable, {
      items: items,
      columns: columns
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "m"
    }));
  }
  renderFormat() {
    const {
      spec,
      fieldTypeFormats,
      fieldFormatId,
      fieldFormatParams,
      format
    } = this.state;
    const {
      fieldFormatEditors
    } = this.context.services;
    const defaultFormat = fieldTypeFormats[0].defaultFieldFormat.title;
    const label = defaultFormat ? /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.defaultFormatHeader",
      defaultMessage: "Format (Default: {defaultFormat})",
      values: {
        defaultFormat: /*#__PURE__*/_react.default.createElement(_eui.EuiCode, null, defaultFormat)
      }
    }) : /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.formatHeader",
      defaultMessage: "Format"
    });
    return /*#__PURE__*/_react.default.createElement(_react.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
      label: label,
      helpText: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "indexPatternManagement.formatLabel",
        defaultMessage: "Formatting controls how values are displayed. Changing this setting might also affect the field value and highlighting in Discover."
      })
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiSelect, {
      value: fieldFormatId,
      options: fieldTypeFormats.map(fmt => {
        return {
          value: fmt.id || '',
          text: fmt.title
        };
      }),
      "data-test-subj": "editorSelectedFormatId",
      onChange: e => {
        this.onFormatChange(e.target.value);
      }
    })), fieldFormatId ? /*#__PURE__*/_react.default.createElement(_field_format_editor.FieldFormatEditor, {
      fieldType: spec.type,
      fieldFormat: format,
      fieldFormatId: fieldFormatId,
      fieldFormatParams: fieldFormatParams || {},
      fieldFormatEditors: fieldFormatEditors,
      onChange: this.onFormatParamsChange,
      onError: this.onFormatParamsError
    }) : null);
  }
  renderPopularity() {
    const {
      spec
    } = this.state;
    return /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
      label: _i18n.i18n.translate('indexPatternManagement.popularityLabel', {
        defaultMessage: 'Popularity',
        description: '"Popularity" refers to Kibana\'s measurement how popular a field is (i.e. how commonly it is used).'
      })
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFieldNumber, {
      value: spec.count,
      "data-test-subj": "editorFieldCount",
      onChange: e => {
        this.onFieldChange('count', e.target.value ? Number(e.target.value) : '');
      }
    }));
  }
  renderScript() {
    var _spec$script;
    const {
      spec,
      hasScriptError
    } = this.state;
    const isInvalid = !spec.script || !spec.script.trim() || hasScriptError;
    const errorMsg = hasScriptError ? /*#__PURE__*/_react.default.createElement("span", {
      "data-test-subj": "invalidScriptError"
    }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.scriptInvalidErrorMessage",
      defaultMessage: "Script is invalid. View script preview for details"
    })) : /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.scriptRequiredErrorMessage",
      defaultMessage: "Script is required"
    });
    return spec.scripted ? /*#__PURE__*/_react.default.createElement(_react.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
      fullWidth: true,
      label: _i18n.i18n.translate('indexPatternManagement.scriptLabel', {
        defaultMessage: 'Script'
      }),
      isInvalid: isInvalid,
      error: isInvalid ? errorMsg : null
    }, /*#__PURE__*/_react.default.createElement(_public.CodeEditor, {
      languageId: _monaco.PainlessLang.ID,
      width: "100%",
      height: "300px",
      value: (_spec$script = spec.script) !== null && _spec$script !== void 0 ? _spec$script : '',
      onChange: this.onScriptChange,
      "data-test-subj": "editorFieldScript",
      "aria-label": _i18n.i18n.translate('indexPatternManagement.scriptLabelAriaLabel', {
        defaultMessage: 'Script editor'
      })
    })), /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, null, /*#__PURE__*/_react.default.createElement(_react.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiText, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.script.accessWithLabel",
      defaultMessage: "Access fields with {code}.",
      values: {
        code: /*#__PURE__*/_react.default.createElement("code", null, `doc['some_field'].value`)
      }
    })), /*#__PURE__*/_react.default.createElement("br", null), /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
      onClick: this.showScriptingHelp,
      "data-test-subj": "scriptedFieldsHelpLink"
    }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.script.getHelpLabel",
      defaultMessage: "Get help with the syntax and preview the results of your script."
    }))))) : null;
  }
  renderActions() {
    const {
      isCreating,
      spec,
      isSaving
    } = this.state;
    const {
      redirectAway
    } = this.props.services;
    return /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      grow: false
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
      fill: true,
      onClick: this.saveField,
      isDisabled: this.isSavingDisabled(),
      isLoading: isSaving,
      "data-test-subj": "fieldSaveButton"
    }, isCreating ? /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.actions.createButton",
      defaultMessage: "Create field"
    }) : /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.actions.saveButton",
      defaultMessage: "Save field"
    }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      grow: false
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
      onClick: redirectAway,
      "data-test-subj": "fieldCancelButton"
    }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.actions.cancelButton",
      defaultMessage: "Cancel"
    }))), !isCreating && spec.scripted ? /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
      justifyContent: "flexEnd"
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      grow: false
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
      color: "danger",
      onClick: this.showDeleteModal
    }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.actions.deleteButton",
      defaultMessage: "Delete"
    }))))) : null));
  }
  isSavingDisabled() {
    const {
      spec,
      hasFormatError,
      hasScriptError
    } = this.state;
    if (hasFormatError || hasScriptError || !spec.name || !spec.name.trim() || spec.scripted && (!spec.script || !spec.script.trim())) {
      return true;
    }
    return false;
  }
  render() {
    const {
      isReady,
      isCreating,
      spec
    } = this.state;
    return isReady ? /*#__PURE__*/_react.default.createElement("div", null, /*#__PURE__*/_react.default.createElement(_eui.EuiText, null, /*#__PURE__*/_react.default.createElement("h3", null, isCreating ? /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.createHeader",
      defaultMessage: "Create scripted field"
    }) : /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.editHeader",
      defaultMessage: "Edit {fieldName}",
      values: {
        fieldName: spec.name
      }
    }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "m"
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiForm, null, this.renderScriptingPanels(), this.renderName(), this.renderCustomLabel(), this.renderLanguage(), this.renderType(), this.renderTypeConflict(), this.renderFormat(), this.renderPopularity(), this.renderScript(), this.renderActions(), this.renderDeleteModal()), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "l"
    })) : null;
  }
}
exports.FieldEditor = FieldEditor;
(0, _defineProperty2.default)(FieldEditor, "contextType", _public.context);