"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DiscoverSidebarResponsive = DiscoverSidebarResponsive;
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _public = require("@kbn/unified-search-plugin/public");
var _unifiedFieldList = require("@kbn/unified-field-list");
var _common = require("../../../../../common");
var _use_discover_services = require("../../../../hooks/use_discover_services");
var _discover_data_state_container = require("../../services/discover_data_state_container");
var _calc_field_counts = require("../../utils/calc_field_counts");
var _types = require("../../../types");
var _discover_tour = require("../../../../components/discover_tour");
var _kibana_services = require("../../../../kibana_services");
var _sidebar_reducer = require("./lib/sidebar_reducer");
var _customizations = require("../../../../customizations");
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 EMPTY_FIELD_COUNTS = {};
const getCreationOptions = () => {
  return {
    originatingApp: _common.PLUGIN_ID,
    localStorageKeyPrefix: 'discover',
    compressed: true,
    showSidebarToggleButton: true,
    disableFieldsExistenceAutoFetching: true,
    buttonAddFieldVariant: 'toolbar',
    buttonPropsToTriggerFlyout: {
      contentProps: {
        id: _discover_tour.DISCOVER_TOUR_STEP_ANCHOR_IDS.addFields
      }
    },
    buttonAddFieldToWorkspaceProps: {
      'aria-label': _i18n.i18n.translate('discover.fieldChooser.discoverField.addFieldTooltip', {
        defaultMessage: 'Add field as column'
      })
    },
    buttonRemoveFieldFromWorkspaceProps: {
      'aria-label': _i18n.i18n.translate('discover.fieldChooser.discoverField.removeFieldTooltip', {
        defaultMessage: 'Remove field from table'
      })
    },
    onOverrideFieldGroupDetails: groupName => {
      if (groupName === _unifiedFieldList.FieldsGroupNames.AvailableFields) {
        return {
          helpText: _i18n.i18n.translate('discover.fieldChooser.availableFieldsTooltip', {
            defaultMessage: 'Fields available for display in the table.'
          })
        };
      }
    },
    dataTestSubj: {
      fieldListAddFieldButtonTestSubj: 'dataView-add-field_btn',
      fieldListSidebarDataTestSubj: 'discover-sidebar',
      fieldListItemStatsDataTestSubj: 'dscFieldStats',
      fieldListItemDndDataTestSubjPrefix: 'dscFieldListPanelField',
      fieldListItemPopoverDataTestSubj: 'discoverFieldListPanelPopover',
      fieldListItemPopoverHeaderDataTestSubjPrefix: 'discoverFieldListPanel'
    }
  };
};
/**
 * Component providing 2 different renderings for the sidebar depending on available screen space
 * Desktop: Sidebar view, all elements are visible
 * Mobile: Data view selector is visible and a button to trigger a flyout with all elements
 */
function DiscoverSidebarResponsive(props) {
  const services = (0, _use_discover_services.useDiscoverServices)();
  const {
    fieldListVariant,
    selectedDataView,
    columns,
    trackUiMetric,
    onAddFilter,
    onFieldEdited,
    onDataViewCreated,
    onChangeDataView,
    onAddField,
    onRemoveField,
    unifiedFieldListSidebarContainerApi,
    setUnifiedFieldListSidebarContainerApi
  } = props;
  const [sidebarState, dispatchSidebarStateAction] = (0, _react.useReducer)(_sidebar_reducer.discoverSidebarReducer, selectedDataView, _sidebar_reducer.getInitialState);
  const selectedDataViewRef = (0, _react.useRef)(selectedDataView);
  const showFieldList = sidebarState.status !== _sidebar_reducer.DiscoverSidebarReducerStatus.INITIAL;
  (0, _react.useEffect)(() => {
    const subscription = props.documents$.subscribe(documentState => {
      const isPlainRecordType = documentState.recordRawType === _discover_data_state_container.RecordRawType.PLAIN;
      switch (documentState === null || documentState === void 0 ? void 0 : documentState.fetchStatus) {
        case _types.FetchStatus.UNINITIALIZED:
          dispatchSidebarStateAction({
            type: _sidebar_reducer.DiscoverSidebarReducerActionType.RESET,
            payload: {
              dataView: selectedDataViewRef.current
            }
          });
          break;
        case _types.FetchStatus.LOADING:
          dispatchSidebarStateAction({
            type: _sidebar_reducer.DiscoverSidebarReducerActionType.DOCUMENTS_LOADING,
            payload: {
              isPlainRecord: isPlainRecordType
            }
          });
          break;
        case _types.FetchStatus.COMPLETE:
          dispatchSidebarStateAction({
            type: _sidebar_reducer.DiscoverSidebarReducerActionType.DOCUMENTS_LOADED,
            payload: {
              dataView: selectedDataViewRef.current,
              fieldCounts: isPlainRecordType ? EMPTY_FIELD_COUNTS : (0, _calc_field_counts.calcFieldCounts)(documentState.result),
              textBasedQueryColumns: documentState.textBasedQueryColumns,
              isPlainRecord: isPlainRecordType
            }
          });
          break;
        case _types.FetchStatus.ERROR:
          dispatchSidebarStateAction({
            type: _sidebar_reducer.DiscoverSidebarReducerActionType.DOCUMENTS_LOADED,
            payload: {
              dataView: selectedDataViewRef.current,
              fieldCounts: EMPTY_FIELD_COUNTS,
              isPlainRecord: isPlainRecordType
            }
          });
          break;
        default:
          break;
      }
    });
    return () => subscription.unsubscribe();
  }, [props.documents$, dispatchSidebarStateAction, selectedDataViewRef]);
  (0, _react.useEffect)(() => {
    if (selectedDataView !== selectedDataViewRef.current) {
      dispatchSidebarStateAction({
        type: _sidebar_reducer.DiscoverSidebarReducerActionType.DATA_VIEW_SWITCHED,
        payload: {
          dataView: selectedDataView
        }
      });
      selectedDataViewRef.current = selectedDataView;
    }
  }, [selectedDataView, dispatchSidebarStateAction, selectedDataViewRef]);
  const refetchFieldsExistenceInfo = unifiedFieldListSidebarContainerApi === null || unifiedFieldListSidebarContainerApi === void 0 ? void 0 : unifiedFieldListSidebarContainerApi.refetchFieldsExistenceInfo;
  const scheduleFieldsExistenceInfoFetchRef = (0, _react.useRef)(false);

  // Refetch fields existence info only after the fetch completes
  (0, _react.useEffect)(() => {
    scheduleFieldsExistenceInfoFetchRef.current = false;
    if (sidebarState.status !== _sidebar_reducer.DiscoverSidebarReducerStatus.COMPLETED) {
      return;
    }

    // refetching info only if status changed to completed

    if (refetchFieldsExistenceInfo) {
      refetchFieldsExistenceInfo();
    } else {
      scheduleFieldsExistenceInfoFetchRef.current = true;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sidebarState.status, scheduleFieldsExistenceInfoFetchRef]);

  // As unifiedFieldListSidebarContainerRef ref can be empty in the beginning,
  // we need to fetch the data once API becomes available and after documents are fetched
  const initializeUnifiedFieldListSidebarContainerApi = (0, _react.useCallback)(api => {
    if (!api) {
      return;
    }
    if (scheduleFieldsExistenceInfoFetchRef.current) {
      scheduleFieldsExistenceInfoFetchRef.current = false;
      api.refetchFieldsExistenceInfo();
    }
    setUnifiedFieldListSidebarContainerApi(api);
  }, [setUnifiedFieldListSidebarContainerApi, scheduleFieldsExistenceInfoFetchRef]);
  const closeDataViewEditor = (0, _react.useRef)();
  (0, _react.useEffect)(() => {
    const cleanup = () => {
      if (closeDataViewEditor !== null && closeDataViewEditor !== void 0 && closeDataViewEditor.current) {
        closeDataViewEditor === null || closeDataViewEditor === void 0 ? void 0 : closeDataViewEditor.current();
      }
    };
    return () => {
      // Make sure to close the editor when unmounting
      cleanup();
    };
  }, []);
  const setDataViewEditorRef = (0, _react.useCallback)(ref => {
    closeDataViewEditor.current = ref;
  }, []);
  const {
    dataViewEditor
  } = services;
  const {
    availableFields$
  } = props;
  (0, _react.useEffect)(() => {
    // For an external embeddable like the Field stats
    // it is useful to know what fields are populated in the docs fetched
    // or what fields are selected by the user

    const availableFields = props.columns.length > 0 ? props.columns : Object.keys(sidebarState.fieldCounts || {});
    availableFields$.next({
      fetchStatus: _types.FetchStatus.COMPLETE,
      fields: availableFields
    });
  }, [selectedDataView, sidebarState.fieldCounts, props.columns, availableFields$]);
  const canEditDataView = Boolean(dataViewEditor === null || dataViewEditor === void 0 ? void 0 : dataViewEditor.userPermissions.editDataView()) || Boolean(selectedDataView && !selectedDataView.isPersisted());
  const closeFieldListFlyout = unifiedFieldListSidebarContainerApi === null || unifiedFieldListSidebarContainerApi === void 0 ? void 0 : unifiedFieldListSidebarContainerApi.closeFieldListFlyout;
  const createNewDataView = (0, _react.useMemo)(() => canEditDataView ? () => {
    const ref = dataViewEditor.openEditor({
      onSave: async dataView => {
        onDataViewCreated(dataView);
      }
    });
    if (setDataViewEditorRef) {
      setDataViewEditorRef(ref);
    }
    closeFieldListFlyout === null || closeFieldListFlyout === void 0 ? void 0 : closeFieldListFlyout();
  } : undefined, [canEditDataView, dataViewEditor, setDataViewEditorRef, onDataViewCreated, closeFieldListFlyout]);
  const fieldListSidebarServices = (0, _react.useMemo)(() => ({
    ...services,
    uiActions: (0, _kibana_services.getUiActions)()
  }), [services]);
  const searchBarCustomization = (0, _customizations.useDiscoverCustomization)('search_bar');
  const CustomDataViewPicker = searchBarCustomization === null || searchBarCustomization === void 0 ? void 0 : searchBarCustomization.CustomDataViewPicker;
  const createField = unifiedFieldListSidebarContainerApi === null || unifiedFieldListSidebarContainerApi === void 0 ? void 0 : unifiedFieldListSidebarContainerApi.createField;
  const prependDataViewPickerForMobile = (0, _react.useCallback)(() => {
    return selectedDataView ? CustomDataViewPicker ? /*#__PURE__*/_react.default.createElement(CustomDataViewPicker, null) : /*#__PURE__*/_react.default.createElement(_public.DataViewPicker, {
      currentDataViewId: selectedDataView.id,
      onChangeDataView: onChangeDataView,
      onAddField: createField,
      onDataViewCreated: createNewDataView,
      trigger: {
        label: (selectedDataView === null || selectedDataView === void 0 ? void 0 : selectedDataView.getName()) || '',
        'data-test-subj': 'dataView-switch-link',
        title: (selectedDataView === null || selectedDataView === void 0 ? void 0 : selectedDataView.getIndexPattern()) || '',
        fullWidth: true
      }
    }) : null;
  }, [selectedDataView, createNewDataView, onChangeDataView, createField, CustomDataViewPicker]);
  const onAddFieldToWorkspace = (0, _react.useCallback)(field => {
    onAddField(field.name);
  }, [onAddField]);
  const onRemoveFieldFromWorkspace = (0, _react.useCallback)(field => {
    onRemoveField(field.name);
  }, [onRemoveField]);
  if (!selectedDataView) {
    return null;
  }
  return /*#__PURE__*/_react.default.createElement(_unifiedFieldList.UnifiedFieldListSidebarContainer, {
    ref: initializeUnifiedFieldListSidebarContainerApi,
    variant: fieldListVariant,
    getCreationOptions: getCreationOptions,
    services: fieldListSidebarServices,
    dataView: selectedDataView,
    trackUiMetric: trackUiMetric,
    allFields: sidebarState.allFields,
    showFieldList: showFieldList,
    workspaceSelectedFieldNames: columns,
    fullWidth: true,
    onAddFieldToWorkspace: onAddFieldToWorkspace,
    onRemoveFieldFromWorkspace: onRemoveFieldFromWorkspace,
    onAddFilter: onAddFilter,
    onFieldEdited: onFieldEdited,
    prependInFlyout: prependDataViewPickerForMobile
  });
}