"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.DONT_CLOSE_DIMENSION_CONTAINER_ON_CLICK_CLASS = void 0; exports.containsDynamicMath = containsDynamicMath; exports.extractReferencesFromState = extractReferencesFromState; exports.getActiveDatasourceIdFromDoc = getActiveDatasourceIdFromDoc; exports.getActiveVisualizationIdFromDoc = getActiveVisualizationIdFromDoc; exports.getIndexPatternsIds = getIndexPatternsIds; exports.getIndexPatternsObjects = getIndexPatternsObjects; exports.getInitialDataViewsObject = getInitialDataViewsObject; exports.getInitialDatasourceId = void 0; exports.getRemoveOperation = getRemoveOperation; exports.getSearchWarningMessages = exports.getResolvedDateRange = void 0; exports.getTimeZone = getTimeZone; exports.getUniqueLabelGenerator = getUniqueLabelGenerator; exports.getVisualizeGeoFieldMessage = getVisualizeGeoFieldMessage; exports.inferTimeField = inferTimeField; exports.isDraggedDataViewField = isDraggedDataViewField; exports.isDraggedField = isDraggedField; exports.isOperationFromTheSameGroup = exports.isOperationFromCompatibleGroup = void 0; exports.nonNullable = nonNullable; exports.refreshIndexPatternsList = refreshIndexPatternsList; exports.renewIDs = renewIDs; exports.reorderElements = reorderElements; exports.shouldRemoveSource = shouldRemoveSource; exports.sortDataViewRefs = void 0; var _saferLodashSet = require("@kbn/safer-lodash-set"); var _lodash = require("lodash"); var _i18n = require("@kbn/i18n"); var _momentTimezone = _interopRequireDefault(require("moment-timezone")); var _visualizationUiComponents = require("@kbn/visualization-ui-components"); var _types = require("./types"); /* * 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; you may not use this file except in compliance with the Elastic License * 2.0. */ function getVisualizeGeoFieldMessage(fieldType) { return _i18n.i18n.translate('xpack.lens.visualizeGeoFieldMessage', { defaultMessage: `Lens cannot visualize {fieldType} fields`, values: { fieldType } }); } const getResolvedDateRange = function (timefilter) { const { from, to } = timefilter.getTime(); const { min, max } = timefilter.calculateBounds({ from, to }); return { fromDate: (min === null || min === void 0 ? void 0 : min.toISOString()) || from, toDate: (max === null || max === void 0 ? void 0 : max.toISOString()) || to }; }; exports.getResolvedDateRange = getResolvedDateRange; function containsDynamicMath(dateMathString) { return dateMathString.includes('now'); } function getTimeZone(uiSettings) { const configuredTimeZone = uiSettings.get('dateFormat:tz'); if (configuredTimeZone === 'Browser') { return _momentTimezone.default.tz.guess(); } return configuredTimeZone; } function getActiveDatasourceIdFromDoc(doc) { if (!doc) { return null; } const [firstDatasourceFromDoc] = Object.keys(doc.state.datasourceStates); return firstDatasourceFromDoc || null; } function getActiveVisualizationIdFromDoc(doc) { if (!doc) { return null; } return doc.visualizationType || null; } const getInitialDatasourceId = (datasourceMap, doc) => { return doc && getActiveDatasourceIdFromDoc(doc) || Object.keys(datasourceMap)[0] || null; }; exports.getInitialDatasourceId = getInitialDatasourceId; function getInitialDataViewsObject(indexPatterns, indexPatternRefs) { return { indexPatterns, indexPatternRefs }; } async function refreshIndexPatternsList({ activeDatasources, indexPatternService, indexPatternId, indexPatternsCache }) { // collect all the onRefreshIndex callbacks from datasources const onRefreshCallbacks = Object.values(activeDatasources).map(datasource => datasource === null || datasource === void 0 ? void 0 : datasource.onRefreshIndexPattern).filter(Boolean); const newlyMappedIndexPattern = await indexPatternService.loadIndexPatterns({ cache: {}, patterns: [indexPatternId], onIndexPatternRefresh: () => onRefreshCallbacks.forEach(fn => fn()) }); const indexPattern = newlyMappedIndexPattern[indexPatternId]; indexPatternService.updateDataViewsState({ indexPatterns: { ...indexPatternsCache, [indexPatternId]: indexPattern } }); } function extractReferencesFromState({ activeDatasources, datasourceStates, visualizationState, activeVisualization }) { const references = []; Object.entries(activeDatasources).forEach(([id, datasource]) => { const { savedObjectReferences } = datasource.getPersistableState(datasourceStates[id].state); references.push(...savedObjectReferences); }); if (activeVisualization !== null && activeVisualization !== void 0 && activeVisualization.getPersistableState) { const { savedObjectReferences } = activeVisualization.getPersistableState(visualizationState); references.push(...savedObjectReferences); } return references; } function getIndexPatternsIds({ activeDatasources, datasourceStates, visualizationState, activeVisualization }) { const references = extractReferencesFromState({ activeDatasources, datasourceStates, visualizationState, activeVisualization }); const currentIndexPatternId = Object.entries(activeDatasources).reduce((currentId, [id, datasource]) => { if (currentId == null) { return datasource.getUsedDataView(datasourceStates[id].state); } return currentId; }, undefined); const referencesIds = references.filter(({ type }) => type === 'index-pattern').map(({ id }) => id); if (currentIndexPatternId) { referencesIds.unshift(currentIndexPatternId); } return (0, _lodash.uniq)(referencesIds); } async function getIndexPatternsObjects(ids, dataViews) { const responses = await Promise.allSettled(ids.map(id => dataViews.get(id))); const fullfilled = responses.filter(response => response.status === 'fulfilled'); const rejectedIds = responses.map((_response, i) => ids[i]).filter((id, i) => responses[i].status === 'rejected'); // return also the rejected ids in case we want to show something later on return { indexPatterns: fullfilled.map(response => response.value), rejectedIds }; } function getRemoveOperation(activeVisualization, visualizationState, layerId, layerCount) { if (activeVisualization.getRemoveOperation) { return activeVisualization.getRemoveOperation(visualizationState, layerId); } // fallback to generic count check return layerCount === 1 ? 'clear' : 'remove'; } function getTablesAndColumnsFromContext(event) { // if it's a negated filter, never respect bound time field if ('negate' in event.data && event.data.negate) { return []; } if ((0, _types.isLensBrushEvent)(event)) { return [{ table: event.data.table, column: event.data.column }]; } if ((0, _types.isLensMultiFilterEvent)(event)) { return event.data.data.map(({ table, cells }) => ({ table, column: cells[0].column })); } if ((0, _types.isLensFilterEvent)(event)) { return event.data.data; } return event.data; } function inferTimeField(datatableUtilities, event) { const tablesAndColumns = getTablesAndColumnsFromContext(event); return !Array.isArray(tablesAndColumns) ? [tablesAndColumns] : tablesAndColumns.map(({ table, column }) => { var _datatableUtilities$g; const tableColumn = table.columns[column]; const hasTimeRange = Boolean(tableColumn && ((_datatableUtilities$g = datatableUtilities.getDateHistogramMeta(tableColumn)) === null || _datatableUtilities$g === void 0 ? void 0 : _datatableUtilities$g.timeRange)); if (hasTimeRange) { return tableColumn.meta.field; } }).find(Boolean); } function renewIDs(obj, forRenewIds, getNewId) { obj = (0, _lodash.cloneDeep)(obj); const recursiveFn = (item, parent, key) => { if (typeof item === 'object') { if (Array.isArray(item)) { item.forEach((a, k, ref) => recursiveFn(a, ref, k)); } else { if (item) { Object.keys(item).forEach(k => { let newId = k; if (forRenewIds.includes(k)) { var _getNewId; newId = (_getNewId = getNewId(k)) !== null && _getNewId !== void 0 ? _getNewId : k; item[newId] = item[k]; delete item[k]; } recursiveFn(item[newId], item, newId); }); } } } else if (parent && key !== undefined && typeof item === 'string' && forRenewIds.includes(item)) { var _getNewId2; (0, _saferLodashSet.set)(parent, key, (_getNewId2 = getNewId(item)) !== null && _getNewId2 !== void 0 ? _getNewId2 : item); } }; recursiveFn(obj); return obj; } /** * The dimension container is set up to close when it detects a click outside it. * Use this CSS class to exclude particular elements from this behavior. */ const DONT_CLOSE_DIMENSION_CONTAINER_ON_CLICK_CLASS = 'lensDontCloseDimensionContainerOnClick'; exports.DONT_CLOSE_DIMENSION_CONTAINER_ON_CLICK_CLASS = DONT_CLOSE_DIMENSION_CONTAINER_ON_CLICK_CLASS; function isDraggedField(fieldCandidate) { return typeof fieldCandidate === 'object' && fieldCandidate !== null && ['id', 'field'].every(prop => prop in fieldCandidate); } function isDraggedDataViewField(fieldCandidate) { return typeof fieldCandidate === 'object' && fieldCandidate !== null && ['id', 'field', 'indexPatternId'].every(prop => prop in fieldCandidate); } const isOperationFromCompatibleGroup = (op1, op2) => { return (0, _types.isOperation)(op1) && (0, _types.isOperation)(op2) && op1.columnId !== op2.columnId && op1.groupId === op2.groupId && op1.layerId !== op2.layerId; }; exports.isOperationFromCompatibleGroup = isOperationFromCompatibleGroup; const isOperationFromTheSameGroup = (op1, op2) => { return (0, _types.isOperation)(op1) && (0, _types.isOperation)(op2) && op1.columnId !== op2.columnId && op1.groupId === op2.groupId && op1.layerId === op2.layerId; }; exports.isOperationFromTheSameGroup = isOperationFromTheSameGroup; const sortDataViewRefs = dataViewRefs => dataViewRefs.sort((a, b) => { return a.title.localeCompare(b.title); }); exports.sortDataViewRefs = sortDataViewRefs; const getSearchWarningMessages = (adapter, datasource, state, deps) => { const warningsMap = new Map(); deps.searchService.showWarnings(adapter, (warning, meta) => { var _datasource$getSearch; const { request, response, requestId } = meta; const warningMessages = (_datasource$getSearch = datasource.getSearchWarningMessages) === null || _datasource$getSearch === void 0 ? void 0 : _datasource$getSearch.call(datasource, state, warning, request, response); if (warningMessages !== null && warningMessages !== void 0 && warningMessages.length) { var _ref, _warning$reason; const key = (_ref = (requestId !== null && requestId !== void 0 ? requestId : '') + warning.type + ((_warning$reason = warning.reason) === null || _warning$reason === void 0 ? void 0 : _warning$reason.type)) !== null && _ref !== void 0 ? _ref : ''; if (!warningsMap.has(key)) { warningsMap.set(key, warningMessages); } return true; } return false; }); return [...warningsMap.values()].flat(); }; exports.getSearchWarningMessages = getSearchWarningMessages; function getSafeLabel(label) { return label.trim().length ? label : _visualizationUiComponents.emptyTitleText; } function getUniqueLabelGenerator() { const counts = {}; return function makeUnique(label) { let uniqueLabel = getSafeLabel(label); while (counts[uniqueLabel] >= 0) { const num = ++counts[uniqueLabel]; uniqueLabel = _i18n.i18n.translate('xpack.lens.uniqueLabel', { defaultMessage: '{label} [{num}]', values: { label: getSafeLabel(label), num } }); } counts[uniqueLabel] = 0; return uniqueLabel; }; } function nonNullable(v) { return v != null; } function reorderElements(items, targetId, sourceId) { const result = items.filter(c => c !== sourceId); const targetIndex = items.findIndex(c => c === sourceId); const sourceIndex = items.findIndex(c => c === targetId); const targetPosition = result.indexOf(targetId); result.splice(targetIndex < sourceIndex ? targetPosition + 1 : targetPosition, 0, sourceId); return result; } function shouldRemoveSource(source, dropType) { return (0, _types.isOperation)(source) && (dropType === 'move_compatible' || dropType === 'move_incompatible' || dropType === 'combine_incompatible' || dropType === 'combine_compatible' || dropType === 'replace_compatible' || dropType === 'replace_incompatible'); }