"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.SavedSearchEmbeddable = void 0; var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _rxjs = require("rxjs"); var _esQuery = require("@kbn/es-query"); var _react = _interopRequireDefault(require("react")); var _reactDom = _interopRequireWildcard(require("react-dom")); var _i18n = require("@kbn/i18n"); var _lodash = require("lodash"); var _public = require("@kbn/embeddable-plugin/public"); var _common = require("@kbn/inspector-plugin/common"); var _public2 = require("@kbn/data-plugin/public"); var _reactKibanaContextRender = require("@kbn/react-kibana-context-render"); var _public3 = require("@kbn/kibana-react-plugin/public"); var _analytics = require("@kbn/analytics"); var _cellActions = require("@kbn/cell-actions"); var _searchResponseWarnings = require("@kbn/search-response-warnings"); var _discoverUtils = require("@kbn/discover-utils"); var _constants = require("../../common/constants"); var _sorting = require("../utils/sorting"); var _constants2 = require("./constants"); var _saved_search_embeddable_component = require("./saved_search_embeddable_component"); var columnActions = _interopRequireWildcard(require("../components/doc_table/actions/columns")); var _state_helpers = require("../utils/state_helpers"); var _update_search_source = require("./utils/update_search_source"); var _field_stats_table = require("../application/main/components/field_stats_table"); var _is_text_based_query = require("../application/main/utils/is_text_based_query"); var _get_valid_view_mode = require("../application/main/utils/get_valid_view_mode"); var _fetch_sql = require("../application/main/utils/fetch_sql"); var _constants3 = require("../constants"); var _get_discover_locator_params = require("./get_discover_locator_params"); 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. */ class SavedSearchEmbeddable extends _public.Embeddable { constructor({ editable, services, executeTriggerActions }, initialInput, parent) { super(initialInput, { editApp: 'discover', editable }, parent); (0, _defineProperty2.default)(this, "type", _constants2.SEARCH_EMBEDDABLE_TYPE); (0, _defineProperty2.default)(this, "deferEmbeddableLoad", true); (0, _defineProperty2.default)(this, "services", void 0); (0, _defineProperty2.default)(this, "executeTriggerActions", void 0); (0, _defineProperty2.default)(this, "attributeService", void 0); (0, _defineProperty2.default)(this, "inspectorAdapters", void 0); (0, _defineProperty2.default)(this, "subscription", void 0); (0, _defineProperty2.default)(this, "abortController", void 0); (0, _defineProperty2.default)(this, "savedSearch", void 0); (0, _defineProperty2.default)(this, "panelTitle", ''); (0, _defineProperty2.default)(this, "filtersSearchSource", void 0); (0, _defineProperty2.default)(this, "prevTimeRange", void 0); (0, _defineProperty2.default)(this, "prevFilters", void 0); (0, _defineProperty2.default)(this, "prevQuery", void 0); (0, _defineProperty2.default)(this, "prevSort", void 0); (0, _defineProperty2.default)(this, "prevSearchSessionId", void 0); (0, _defineProperty2.default)(this, "searchProps", void 0); (0, _defineProperty2.default)(this, "initialized", void 0); (0, _defineProperty2.default)(this, "node", void 0); (0, _defineProperty2.default)(this, "isTextBasedSearch", savedSearch => { const query = savedSearch.searchSource.getField('query'); return (0, _is_text_based_query.isTextBasedQuery)(query); }); (0, _defineProperty2.default)(this, "fetch", async () => { var _this$abortController; const savedSearch = this.savedSearch; const searchProps = this.searchProps; if (!savedSearch || !searchProps) { return; } const searchSessionId = this.input.searchSessionId; const useNewFieldsApi = !this.services.uiSettings.get(_discoverUtils.SEARCH_FIELDS_FROM_SOURCE, false); const currentAbortController = new AbortController(); // Abort any in-progress requests (_this$abortController = this.abortController) === null || _this$abortController === void 0 ? void 0 : _this$abortController.abort(); this.abortController = currentAbortController; (0, _update_search_source.updateSearchSource)(savedSearch.searchSource, searchProps.dataView, searchProps.sort, useNewFieldsApi, { sampleSize: this.services.uiSettings.get(_discoverUtils.SAMPLE_SIZE_SETTING), defaultSort: this.services.uiSettings.get(_discoverUtils.SORT_DEFAULT_ORDER_SETTING) }); // Log request to inspector this.inspectorAdapters.requests.reset(); searchProps.isLoading = true; searchProps.interceptedWarnings = undefined; const wasAlreadyRendered = this.getOutput().rendered; this.updateOutput({ ...this.getOutput(), loading: true, rendered: false, error: undefined }); if (wasAlreadyRendered && this.node) { // to show a loading indicator during a refetch, we need to rerender here this.render(this.node); } const parentContext = this.input.executionContext; const child = { type: this.type, name: 'discover', id: savedSearch.id, description: this.output.title || this.output.defaultTitle || '', url: this.output.editUrl }; const executionContext = parentContext ? { ...parentContext, child } : child; const query = savedSearch.searchSource.getField('query'); const dataView = savedSearch.searchSource.getField('index'); const useSql = this.isTextBasedSearch(savedSearch); try { // Request SQL data if (useSql && query) { const result = await (0, _fetch_sql.fetchSql)(savedSearch.searchSource.getField('query'), dataView, this.services.data, this.services.expressions, this.services.inspector, this.input.filters, this.input.query); this.updateOutput({ ...this.getOutput(), loading: false }); searchProps.rows = result.records; searchProps.totalHitCount = result.records.length; searchProps.isLoading = false; searchProps.isPlainRecord = true; searchProps.showTimeCol = false; searchProps.isSortEnabled = true; return; } // Request document data const { rawResponse: resp } = await (0, _rxjs.lastValueFrom)(savedSearch.searchSource.fetch$({ abortSignal: currentAbortController.signal, sessionId: searchSessionId, inspector: { adapter: this.inspectorAdapters.requests, title: _i18n.i18n.translate('discover.embeddable.inspectorRequestDataTitle', { defaultMessage: 'Data' }), description: _i18n.i18n.translate('discover.embeddable.inspectorRequestDescription', { defaultMessage: 'This request queries Elasticsearch to fetch the data for the search.' }) }, executionContext, disableShardFailureWarning: _constants.DISABLE_SHARD_FAILURE_WARNING })); if (this.inspectorAdapters.requests) { searchProps.interceptedWarnings = (0, _searchResponseWarnings.getSearchResponseInterceptedWarnings)({ services: this.services, adapter: this.inspectorAdapters.requests, options: { disableShardFailureWarning: _constants.DISABLE_SHARD_FAILURE_WARNING } }); } this.updateOutput({ ...this.getOutput(), loading: false }); searchProps.rows = resp.hits.hits.map(hit => (0, _discoverUtils.buildDataTableRecord)(hit, searchProps.dataView)); searchProps.totalHitCount = resp.hits.total; searchProps.isLoading = false; } catch (error) { const cancelled = !!(currentAbortController !== null && currentAbortController !== void 0 && currentAbortController.signal.aborted); if (!this.destroyed && !cancelled) { this.updateOutput({ ...this.getOutput(), loading: false, error }); searchProps.isLoading = false; } } }); this.services = services; this.executeTriggerActions = executeTriggerActions; this.attributeService = services.savedSearch.byValue.attributeService; this.inspectorAdapters = { requests: new _common.RequestAdapter() }; this.subscription = this.getUpdated$().subscribe(() => { const titleChanged = this.output.title && this.panelTitle !== this.output.title; if (titleChanged) { this.panelTitle = this.output.title || ''; } if (!this.searchProps) { return; } const isFetchRequired = this.isFetchRequired(this.searchProps); const isRerenderRequired = this.isRerenderRequired(this.searchProps); if (titleChanged || isFetchRequired || isRerenderRequired) { this.reload(isFetchRequired); } }); this.initializeSavedSearch(initialInput).then(() => { this.initializeSearchEmbeddableProps(); }); } getCurrentTitle() { var _ref, _this$input$title, _this$savedSearch; return this.input.hidePanelTitles ? '' : (_ref = (_this$input$title = this.input.title) !== null && _this$input$title !== void 0 ? _this$input$title : (_this$savedSearch = this.savedSearch) === null || _this$savedSearch === void 0 ? void 0 : _this$savedSearch.title) !== null && _ref !== void 0 ? _ref : ''; } async initializeSavedSearch(input) { try { const unwrapResult = await this.attributeService.unwrapAttributes(input); if (this.destroyed) { return; } this.savedSearch = await this.services.savedSearch.byValue.toSavedSearch(input === null || input === void 0 ? void 0 : input.savedObjectId, unwrapResult); this.panelTitle = this.getCurrentTitle(); await this.initializeOutput(); // deferred loading of this embeddable is complete this.setInitializationFinished(); this.initialized = true; } catch (e) { this.onFatalError(e); } } async initializeOutput() { var _input$description; const savedSearch = this.savedSearch; if (!savedSearch) { return; } const dataView = savedSearch.searchSource.getField('index'); const indexPatterns = dataView ? [dataView] : []; const input = this.getInput(); const title = this.getCurrentTitle(); const description = input.hidePanelTitles ? '' : (_input$description = input.description) !== null && _input$description !== void 0 ? _input$description : savedSearch.description; const savedObjectId = input.savedObjectId; const locatorParams = (0, _get_discover_locator_params.getDiscoverLocatorParams)({ input, savedSearch }); // We need to use a redirect URL if this is a by value saved search using // an ad hoc data view to ensure the data view spec gets encoded in the URL const useRedirect = !savedObjectId && !(dataView !== null && dataView !== void 0 && dataView.isPersisted()); const editUrl = useRedirect ? this.services.locator.getRedirectUrl(locatorParams) : await this.services.locator.getUrl(locatorParams); const editPath = this.services.core.http.basePath.remove(editUrl); const editApp = useRedirect ? 'r' : 'discover'; this.updateOutput({ ...this.getOutput(), defaultTitle: savedSearch.title, defaultDescription: savedSearch.description, title, description, editApp, editPath, editUrl, indexPatterns }); } inputIsRefType(input) { return this.attributeService.inputIsRefType(input); } async getInputAsValueType() { return this.attributeService.getInputAsValueType(this.getExplicitInput()); } async getInputAsRefType() { return this.attributeService.getInputAsRefType(this.getExplicitInput(), { showSaveModal: true, saveModalTitle: this.getTitle() }); } reportsEmbeddableLoad() { return true; } getSort(sort, dataView) { return (0, _sorting.getSortForEmbeddable)(sort, dataView, this.services.uiSettings); } initializeSearchEmbeddableProps() { const savedSearch = this.savedSearch; if (!savedSearch) { return; } const dataView = savedSearch.searchSource.getField('index'); if (!dataView) { return; } if (!dataView.isPersisted()) { var _this$services$trackU, _this$services; // one used adhoc data view (_this$services$trackU = (_this$services = this.services).trackUiMetric) === null || _this$services$trackU === void 0 ? void 0 : _this$services$trackU.call(_this$services, _analytics.METRIC_TYPE.COUNT, _constants3.ADHOC_DATA_VIEW_RENDER_EVENT); } const props = { columns: savedSearch.columns, savedSearchId: savedSearch.id, filters: savedSearch.searchSource.getField('filter'), dataView, isLoading: false, sort: this.getSort(savedSearch.sort, dataView), rows: [], searchDescription: savedSearch.description, description: savedSearch.description, inspectorAdapters: this.inspectorAdapters, searchTitle: savedSearch.title, services: this.services, onAddColumn: columnName => { if (!props.columns) { return; } const updatedColumns = columnActions.addColumn(props.columns, columnName, true); this.updateInput({ columns: updatedColumns }); }, onRemoveColumn: columnName => { if (!props.columns) { return; } const updatedColumns = columnActions.removeColumn(props.columns, columnName, true); this.updateInput({ columns: updatedColumns }); }, onMoveColumn: (columnName, newIndex) => { if (!props.columns) { return; } const columns = columnActions.moveColumn(props.columns, columnName, newIndex); this.updateInput({ columns }); }, onSetColumns: columns => { this.updateInput({ columns }); }, onSort: nextSort => { const sortOrderArr = []; nextSort.forEach(arr => { sortOrderArr.push(arr); }); this.updateInput({ sort: sortOrderArr }); }, sampleSize: this.services.uiSettings.get(_discoverUtils.SAMPLE_SIZE_SETTING), onFilter: async (field, value, operator) => { let filters = (0, _public2.generateFilters)(this.services.filterManager, // @ts-expect-error field, value, operator, dataView); filters = filters.map(filter => ({ ...filter, $state: { store: _esQuery.FilterStateStore.APP_STATE } })); await this.executeTriggerActions(_public2.APPLY_FILTER_TRIGGER, { embeddable: this, filters }); }, useNewFieldsApi: !this.services.uiSettings.get(_discoverUtils.SEARCH_FIELDS_FROM_SOURCE, false), showTimeCol: !this.services.uiSettings.get(_discoverUtils.DOC_HIDE_TIME_COLUMN_SETTING, false), ariaLabelledBy: 'documentsAriaLabel', rowHeightState: this.input.rowHeight || savedSearch.rowHeight, onUpdateRowHeight: rowHeight => { this.updateInput({ rowHeight }); }, rowsPerPageState: this.input.rowsPerPage || savedSearch.rowsPerPage, onUpdateRowsPerPage: rowsPerPage => { this.updateInput({ rowsPerPage }); }, cellActionsTriggerId: _constants2.SEARCH_EMBEDDABLE_CELL_ACTIONS_TRIGGER_ID }; const timeRangeSearchSource = savedSearch.searchSource.create(); timeRangeSearchSource.setField('filter', () => { const timeRange = this.getTimeRange(); if (!this.searchProps || !timeRange) return; return this.services.timefilter.createFilter(dataView, timeRange); }); this.filtersSearchSource = savedSearch.searchSource.create(); this.filtersSearchSource.setParent(timeRangeSearchSource); savedSearch.searchSource.setParent(this.filtersSearchSource); this.load(props); props.isLoading = true; if (savedSearch.grid) { props.settings = savedSearch.grid; } } getTimeRange() { return this.input.timeslice !== undefined ? { from: new Date(this.input.timeslice[0]).toISOString(), to: new Date(this.input.timeslice[1]).toISOString(), mode: 'absolute' } : this.input.timeRange; } isFetchRequired(searchProps) { if (!searchProps || !searchProps.dataView) { return false; } return !(0, _esQuery.onlyDisabledFiltersChanged)(this.input.filters, this.prevFilters) || !(0, _lodash.isEqual)(this.prevQuery, this.input.query) || !(0, _lodash.isEqual)(this.prevTimeRange, this.getTimeRange()) || !(0, _lodash.isEqual)(this.prevSort, this.input.sort) || this.prevSearchSessionId !== this.input.searchSessionId; } isRerenderRequired(searchProps) { if (!searchProps) { return false; } return this.input.rowsPerPage !== searchProps.rowsPerPageState || this.input.columns && !(0, _lodash.isEqual)(this.input.columns, searchProps.columns); } async pushContainerStateParamsToProps(searchProps, { forceFetch = false } = { forceFetch: false }) { const savedSearch = this.savedSearch; if (!savedSearch) { return; } const isFetchRequired = this.isFetchRequired(searchProps); // If there is column or sort data on the panel, that means the original // columns or sort settings have been overridden in a dashboard. const columnState = (0, _state_helpers.handleSourceColumnState)({ columns: this.input.columns || savedSearch.columns }, this.services.core.uiSettings); searchProps.columns = columnState.columns; searchProps.sort = this.getSort(this.input.sort || savedSearch.sort, searchProps === null || searchProps === void 0 ? void 0 : searchProps.dataView); searchProps.sharedItemTitle = this.panelTitle; searchProps.searchTitle = this.panelTitle; searchProps.rowHeightState = this.input.rowHeight || savedSearch.rowHeight; searchProps.rowsPerPageState = this.input.rowsPerPage || savedSearch.rowsPerPage; searchProps.filters = savedSearch.searchSource.getField('filter'); searchProps.savedSearchId = savedSearch.id; if (forceFetch || isFetchRequired) { var _this$input$query, _this$input$filters; this.filtersSearchSource.setField('filter', this.input.filters); this.filtersSearchSource.setField('query', this.input.query); if ((_this$input$query = this.input.query) !== null && _this$input$query !== void 0 && _this$input$query.query || (_this$input$filters = this.input.filters) !== null && _this$input$filters !== void 0 && _this$input$filters.length) { this.filtersSearchSource.setField('highlightAll', true); } else { this.filtersSearchSource.removeField('highlightAll'); } this.prevFilters = this.input.filters; this.prevQuery = this.input.query; this.prevTimeRange = this.getTimeRange(); this.prevSearchSessionId = this.input.searchSessionId; this.prevSort = this.input.sort; this.searchProps = searchProps; await this.fetch(); } else if (this.searchProps && this.node) { this.searchProps = searchProps; } } async render(domNode) { this.node = domNode; if (!this.searchProps || !this.initialized || this.destroyed) { return; } super.render(domNode); this.renderReactComponent(this.node, this.searchProps); } renderReactComponent(domNode, searchProps) { const savedSearch = this.savedSearch; if (!searchProps || !savedSearch) { return; } const viewMode = (0, _get_valid_view_mode.getValidViewMode)({ viewMode: savedSearch.viewMode, isTextBasedQueryMode: this.isTextBasedSearch(savedSearch) }); if (this.services.uiSettings.get(_discoverUtils.SHOW_FIELD_STATISTICS) === true && viewMode === _constants.VIEW_MODE.AGGREGATED_LEVEL && searchProps.services && searchProps.dataView && Array.isArray(searchProps.columns)) { _reactDom.default.render( /*#__PURE__*/_react.default.createElement(_reactKibanaContextRender.KibanaRenderContextProvider, { theme: searchProps.services.core.theme, i18n: searchProps.services.core.i18n }, /*#__PURE__*/_react.default.createElement(_public3.KibanaContextProvider, { services: searchProps.services }, /*#__PURE__*/_react.default.createElement(_field_stats_table.FieldStatisticsTable, { dataView: searchProps.dataView, columns: searchProps.columns, savedSearch: savedSearch, filters: this.input.filters, query: this.input.query, onAddFilter: searchProps.onFilter, searchSessionId: this.input.searchSessionId }))), domNode); this.updateOutput({ ...this.getOutput(), rendered: true }); return; } const useLegacyTable = this.services.uiSettings.get(_discoverUtils.DOC_TABLE_LEGACY); const query = savedSearch.searchSource.getField('query'); const props = { savedSearch, searchProps, useLegacyTable, query }; if (searchProps.services) { const { getTriggerCompatibleActions } = searchProps.services.uiActions; _reactDom.default.render( /*#__PURE__*/_react.default.createElement(_reactKibanaContextRender.KibanaRenderContextProvider, { theme: searchProps.services.core.theme, i18n: searchProps.services.core.i18n }, /*#__PURE__*/_react.default.createElement(_public3.KibanaContextProvider, { services: searchProps.services }, /*#__PURE__*/_react.default.createElement(_cellActions.CellActionsProvider, { getTriggerCompatibleActions: getTriggerCompatibleActions }, /*#__PURE__*/_react.default.createElement(_saved_search_embeddable_component.SavedSearchEmbeddableComponent, props)))), domNode); const hasError = this.getOutput().error !== undefined; if (this.searchProps.isLoading === false && props.searchProps.rows !== undefined) { this.renderComplete.dispatchComplete(); this.updateOutput({ ...this.getOutput(), rendered: true }); } else if (hasError) { this.renderComplete.dispatchError(); this.updateOutput({ ...this.getOutput(), rendered: true }); } } } async load(searchProps, forceFetch = false) { await this.pushContainerStateParamsToProps(searchProps, { forceFetch }); if (this.node) { this.render(this.node); } } reload(forceFetch = true) { if (this.searchProps && this.initialized && !this.destroyed) { this.load(this.searchProps, forceFetch); } } getSavedSearch() { if (!this.savedSearch) { throw new Error('Saved search not defined'); } return this.savedSearch; } getInspectorAdapters() { return this.inspectorAdapters; } /** * @returns Local/panel-level array of filters for Saved Search embeddable */ async getFilters() { var _ref2, _this$savedSearch2; return (0, _public2.mapAndFlattenFilters)((_ref2 = (_this$savedSearch2 = this.savedSearch) === null || _this$savedSearch2 === void 0 ? void 0 : _this$savedSearch2.searchSource.getFields().filter) !== null && _ref2 !== void 0 ? _ref2 : []); } /** * @returns Local/panel-level query for Saved Search embeddable */ async getQuery() { var _this$savedSearch3; return (_this$savedSearch3 = this.savedSearch) === null || _this$savedSearch3 === void 0 ? void 0 : _this$savedSearch3.searchSource.getFields().query; } destroy() { var _this$subscription, _this$abortController2; super.destroy(); if (this.searchProps) { delete this.searchProps; } if (this.node) { (0, _reactDom.unmountComponentAtNode)(this.node); } (_this$subscription = this.subscription) === null || _this$subscription === void 0 ? void 0 : _this$subscription.unsubscribe(); (_this$abortController2 = this.abortController) === null || _this$abortController2 === void 0 ? void 0 : _this$abortController2.abort(); } hasTimeRange() { return this.getTimeRange() !== undefined; } } exports.SavedSearchEmbeddable = SavedSearchEmbeddable;