From f4c5ebca9d3c7de2b6788ec133267a4d94e03cc9 Mon Sep 17 00:00:00 2001 From: Jeffrey Chu <56368296+achuguy@users.noreply.github.com> Date: Thu, 1 Oct 2020 11:47:56 -0400 Subject: [PATCH 01/25] [Security Solution]Fix basepath used by endpoint telemetry tests (#79027) * Fix basepath used by endpoint telemetry tests * Linting --- .../services/endpoint_telemetry.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/x-pack/test/security_solution_endpoint/services/endpoint_telemetry.ts b/x-pack/test/security_solution_endpoint/services/endpoint_telemetry.ts index 0f158da5d2f8c..6098404201966 100644 --- a/x-pack/test/security_solution_endpoint/services/endpoint_telemetry.ts +++ b/x-pack/test/security_solution_endpoint/services/endpoint_telemetry.ts @@ -5,10 +5,14 @@ */ import fs from 'fs'; import Path from 'path'; +import { KIBANA_ROOT } from '@kbn/test'; import { FtrProviderContext } from '../ftr_provider_context'; const TELEMETRY_API_ROOT = '/api/stats?extended=true'; -const TELEMETRY_DATA_ROOT = 'test/functional/es_archives/endpoint/telemetry/'; +const TELEMETRY_DATA_ROOT = Path.join( + KIBANA_ROOT, + 'x-pack/test/functional/es_archives/endpoint/telemetry/' +); interface EndpointTelemetry { total_installed: number; From ee7672aaf074dc4ebaf0ffb88d95d5f1bf9e1d18 Mon Sep 17 00:00:00 2001 From: Phillip Burch Date: Thu, 1 Oct 2020 10:51:55 -0500 Subject: [PATCH 02/25] [Metrics UI] Add ability to override datafeeds and job config for partition field (#78875) * Add ability to override datafeeds and job config for partition field * Remove debug * UX cleanup * Fix types, delete dead code --- .../containers/ml/infra_ml_module_types.ts | 4 +- .../containers/ml/infra_ml_setup_state.ts | 289 ------------------ .../metrics_hosts/module_descriptor.ts | 135 +++++--- .../modules/metrics_k8s/module_descriptor.ts | 143 ++++++--- .../anomoly_detection_flyout.tsx | 4 +- .../ml/anomaly_detection/flyout_home.tsx | 113 +++---- .../ml/anomaly_detection/job_setup_screen.tsx | 3 +- 7 files changed, 247 insertions(+), 444 deletions(-) delete mode 100644 x-pack/plugins/infra/public/containers/ml/infra_ml_setup_state.ts diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_types.ts b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_types.ts index a9f2671de8259..e36f38add641a 100644 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_types.ts +++ b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_types.ts @@ -33,11 +33,11 @@ export interface ModuleDescriptor { partitionField?: string ) => Promise; cleanUpModule: (spaceId: string, sourceId: string) => Promise; - validateSetupIndices: ( + validateSetupIndices?: ( indices: string[], timestampField: string ) => Promise; - validateSetupDatasets: ( + validateSetupDatasets?: ( indices: string[], timestampField: string, startTime: number, diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_setup_state.ts b/x-pack/plugins/infra/public/containers/ml/infra_ml_setup_state.ts deleted file mode 100644 index 0dfe3b301f240..0000000000000 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_setup_state.ts +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { isEqual } from 'lodash'; -import { useCallback, useEffect, useMemo, useState } from 'react'; -import { usePrevious } from 'react-use'; -import { - combineDatasetFilters, - DatasetFilter, - filterDatasetFilter, - isExampleDataIndex, -} from '../../../common/infra_ml'; -import { - AvailableIndex, - ValidationIndicesError, - ValidationUIError, -} from '../../components/logging/log_analysis_setup/initial_configuration_step'; -import { useTrackedPromise } from '../../utils/use_tracked_promise'; -import { ModuleDescriptor, ModuleSourceConfiguration } from './infra_ml_module_types'; - -type SetupHandler = ( - indices: string[], - startTime: number | undefined, - endTime: number | undefined, - datasetFilter: DatasetFilter -) => void; - -interface AnalysisSetupStateArguments { - cleanUpAndSetUpModule: SetupHandler; - moduleDescriptor: ModuleDescriptor; - setUpModule: SetupHandler; - sourceConfiguration: ModuleSourceConfiguration; -} - -const fourWeeksInMs = 86400000 * 7 * 4; - -export const useAnalysisSetupState = ({ - cleanUpAndSetUpModule, - moduleDescriptor: { validateSetupDatasets, validateSetupIndices }, - setUpModule, - sourceConfiguration, -}: AnalysisSetupStateArguments) => { - const [startTime, setStartTime] = useState(Date.now() - fourWeeksInMs); - const [endTime, setEndTime] = useState(undefined); - - const isTimeRangeValid = useMemo( - () => (startTime != null && endTime != null ? startTime < endTime : true), - [endTime, startTime] - ); - - const [validatedIndices, setValidatedIndices] = useState( - sourceConfiguration.indices.map((indexName) => ({ - name: indexName, - validity: 'unknown' as const, - })) - ); - - const updateIndicesWithValidationErrors = useCallback( - (validationErrors: ValidationIndicesError[]) => - setValidatedIndices((availableIndices) => - availableIndices.map((previousAvailableIndex) => { - const indexValiationErrors = validationErrors.filter( - ({ index }) => index === previousAvailableIndex.name - ); - - if (indexValiationErrors.length > 0) { - return { - validity: 'invalid', - name: previousAvailableIndex.name, - errors: indexValiationErrors, - }; - } else if (previousAvailableIndex.validity === 'valid') { - return { - ...previousAvailableIndex, - validity: 'valid', - errors: [], - }; - } else { - return { - validity: 'valid', - name: previousAvailableIndex.name, - isSelected: !isExampleDataIndex(previousAvailableIndex.name), - availableDatasets: [], - datasetFilter: { - type: 'includeAll' as const, - }, - }; - } - }) - ), - [] - ); - - const updateIndicesWithAvailableDatasets = useCallback( - (availableDatasets: Array<{ indexName: string; datasets: string[] }>) => - setValidatedIndices((availableIndices) => - availableIndices.map((previousAvailableIndex) => { - if (previousAvailableIndex.validity !== 'valid') { - return previousAvailableIndex; - } - - const availableDatasetsForIndex = availableDatasets.filter( - ({ indexName }) => indexName === previousAvailableIndex.name - ); - const newAvailableDatasets = availableDatasetsForIndex.flatMap( - ({ datasets }) => datasets - ); - - // filter out datasets that have disappeared if this index' datasets were updated - const newDatasetFilter: DatasetFilter = - availableDatasetsForIndex.length > 0 - ? filterDatasetFilter(previousAvailableIndex.datasetFilter, (dataset) => - newAvailableDatasets.includes(dataset) - ) - : previousAvailableIndex.datasetFilter; - - return { - ...previousAvailableIndex, - availableDatasets: newAvailableDatasets, - datasetFilter: newDatasetFilter, - }; - }) - ), - [] - ); - - const validIndexNames = useMemo( - () => validatedIndices.filter((index) => index.validity === 'valid').map((index) => index.name), - [validatedIndices] - ); - - const selectedIndexNames = useMemo( - () => - validatedIndices - .filter((index) => index.validity === 'valid' && index.isSelected) - .map((i) => i.name), - [validatedIndices] - ); - - const datasetFilter = useMemo( - () => - validatedIndices - .flatMap((validatedIndex) => - validatedIndex.validity === 'valid' - ? validatedIndex.datasetFilter - : { type: 'includeAll' as const } - ) - .reduce(combineDatasetFilters, { type: 'includeAll' as const }), - [validatedIndices] - ); - - const [validateIndicesRequest, validateIndices] = useTrackedPromise( - { - cancelPreviousOn: 'resolution', - createPromise: async () => { - return await validateSetupIndices( - sourceConfiguration.indices, - sourceConfiguration.timestampField - ); - }, - onResolve: ({ data: { errors } }) => { - updateIndicesWithValidationErrors(errors); - }, - onReject: () => { - setValidatedIndices([]); - }, - }, - [sourceConfiguration.indices, sourceConfiguration.timestampField] - ); - - const [validateDatasetsRequest, validateDatasets] = useTrackedPromise( - { - cancelPreviousOn: 'resolution', - createPromise: async () => { - if (validIndexNames.length === 0) { - return { data: { datasets: [] } }; - } - - return await validateSetupDatasets( - validIndexNames, - sourceConfiguration.timestampField, - startTime ?? 0, - endTime ?? Date.now() - ); - }, - onResolve: ({ data: { datasets } }) => { - updateIndicesWithAvailableDatasets(datasets); - }, - }, - [validIndexNames, sourceConfiguration.timestampField, startTime, endTime] - ); - - const setUp = useCallback(() => { - return setUpModule(selectedIndexNames, startTime, endTime, datasetFilter); - }, [setUpModule, selectedIndexNames, startTime, endTime, datasetFilter]); - - const cleanUpAndSetUp = useCallback(() => { - return cleanUpAndSetUpModule(selectedIndexNames, startTime, endTime, datasetFilter); - }, [cleanUpAndSetUpModule, selectedIndexNames, startTime, endTime, datasetFilter]); - - const isValidating = useMemo( - () => validateIndicesRequest.state === 'pending' || validateDatasetsRequest.state === 'pending', - [validateDatasetsRequest.state, validateIndicesRequest.state] - ); - - const validationErrors = useMemo(() => { - if (isValidating) { - return []; - } - - return [ - // validate request status - ...(validateIndicesRequest.state === 'rejected' || - validateDatasetsRequest.state === 'rejected' - ? [{ error: 'NETWORK_ERROR' as const }] - : []), - // validation request results - ...validatedIndices.reduce((errors, index) => { - return index.validity === 'invalid' && selectedIndexNames.includes(index.name) - ? [...errors, ...index.errors] - : errors; - }, []), - // index count - ...(selectedIndexNames.length === 0 ? [{ error: 'TOO_FEW_SELECTED_INDICES' as const }] : []), - // time range - ...(!isTimeRangeValid ? [{ error: 'INVALID_TIME_RANGE' as const }] : []), - ]; - }, [ - isValidating, - validateIndicesRequest.state, - validateDatasetsRequest.state, - validatedIndices, - selectedIndexNames, - isTimeRangeValid, - ]); - - const prevStartTime = usePrevious(startTime); - const prevEndTime = usePrevious(endTime); - const prevValidIndexNames = usePrevious(validIndexNames); - - useEffect(() => { - if (!isTimeRangeValid) { - return; - } - - validateIndices(); - }, [isTimeRangeValid, validateIndices]); - - useEffect(() => { - if (!isTimeRangeValid) { - return; - } - - if ( - startTime !== prevStartTime || - endTime !== prevEndTime || - !isEqual(validIndexNames, prevValidIndexNames) - ) { - validateDatasets(); - } - }, [ - endTime, - isTimeRangeValid, - prevEndTime, - prevStartTime, - prevValidIndexNames, - startTime, - validIndexNames, - validateDatasets, - ]); - - return { - cleanUpAndSetUp, - datasetFilter, - endTime, - isValidating, - selectedIndexNames, - setEndTime, - setStartTime, - setUp, - startTime, - validatedIndices, - setValidatedIndices, - validationErrors, - }; -}; diff --git a/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module_descriptor.ts b/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module_descriptor.ts index cec87fb1144e3..711ee76d42a64 100644 --- a/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module_descriptor.ts +++ b/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module_descriptor.ts @@ -10,17 +10,27 @@ import { cleanUpJobsAndDatafeeds } from '../../infra_ml_cleanup'; import { callJobsSummaryAPI } from '../../api/ml_get_jobs_summary_api'; import { callGetMlModuleAPI } from '../../api/ml_get_module'; import { callSetupMlModuleAPI } from '../../api/ml_setup_module_api'; -import { callValidateIndicesAPI } from '../../../logs/log_analysis/api/validate_indices'; -import { callValidateDatasetsAPI } from '../../../logs/log_analysis/api/validate_datasets'; import { metricsHostsJobTypes, getJobId, MetricsHostsJobType, DatasetFilter, bucketSpan, - partitionField, } from '../../../../../common/infra_ml'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import MemoryJob from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_hosts/ml/hosts_memory_usage.json'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import MemoryDatafeed from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_hosts/ml/datafeed_hosts_memory_usage.json'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import NetworkInJob from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_hosts/ml/hosts_network_in.json'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import NetworkInDatafeed from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_hosts/ml/datafeed_hosts_network_in.json'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import NetworkOutJob from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_hosts/ml/hosts_network_out.json'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import NetworkOutDatafeed from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_hosts/ml/datafeed_hosts_network_out.json'; +type JobType = 'hosts_memory_usage' | 'hosts_network_in' | 'hosts_network_out'; const moduleId = 'metrics_ui_hosts'; const moduleName = i18n.translate('xpack.infra.ml.metricsModuleName', { defaultMessage: 'Metrics anomanly detection', @@ -54,23 +64,68 @@ const setUpModule = async ( end: number | undefined, datasetFilter: DatasetFilter, { spaceId, sourceId, indices, timestampField }: ModuleSourceConfiguration, - pField?: string + partitionField?: string ) => { const indexNamePattern = indices.join(','); - const jobIds = ['hosts_memory_usage', 'hosts_network_in', 'hosts_network_out']; - const jobOverrides = jobIds.map((id) => ({ - job_id: id, - data_description: { - time_field: timestampField, - }, - custom_settings: { - metrics_source_config: { - indexPattern: indexNamePattern, - timestampField, - bucketSpan, + const jobIds: JobType[] = ['hosts_memory_usage', 'hosts_network_in', 'hosts_network_out']; + + const jobOverrides = jobIds.map((id) => { + const { job: defaultJobConfig } = getDefaultJobConfigs(id); + + // eslint-disable-next-line @typescript-eslint/naming-convention + const analysis_config = { + ...defaultJobConfig.analysis_config, + }; + + if (partitionField) { + analysis_config.detectors[0].partition_field_name = partitionField; + if (analysis_config.influencers.indexOf(partitionField) === -1) { + analysis_config.influencers.push(partitionField); + } + } + + return { + job_id: id, + data_description: { + time_field: timestampField, + }, + analysis_config, + custom_settings: { + metrics_source_config: { + indexPattern: indexNamePattern, + timestampField, + bucketSpan, + }, + }, + }; + }); + + const datafeedOverrides = jobIds.map((id) => { + const { datafeed: defaultDatafeedConfig } = getDefaultJobConfigs(id); + + if (!partitionField || id === 'hosts_memory_usage') { + // Since the host memory usage doesn't have custom aggs, we don't need to do anything to add a partition field + return defaultDatafeedConfig; + } + + // If we have a partition field, we need to change the aggregation to do a terms agg at the top level + const aggregations = { + [partitionField]: { + terms: { + field: partitionField, + }, + aggregations: { + ...defaultDatafeedConfig.aggregations, + }, }, - }, - })); + }; + + return { + ...defaultDatafeedConfig, + job_id: id, + aggregations, + }; + }); return callSetupMlModuleAPI( moduleId, @@ -80,34 +135,32 @@ const setUpModule = async ( sourceId, indexNamePattern, jobOverrides, - [] + datafeedOverrides ); }; -const cleanUpModule = async (spaceId: string, sourceId: string) => { - return await cleanUpJobsAndDatafeeds(spaceId, sourceId, metricsHostsJobTypes); -}; - -const validateSetupIndices = async (indices: string[], timestampField: string) => { - return await callValidateIndicesAPI(indices, [ - { - name: timestampField, - validTypes: ['date'], - }, - { - name: partitionField, - validTypes: ['keyword'], - }, - ]); +const getDefaultJobConfigs = (jobId: JobType) => { + switch (jobId) { + case 'hosts_memory_usage': + return { + datafeed: MemoryDatafeed, + job: MemoryJob, + }; + case 'hosts_network_in': + return { + datafeed: NetworkInDatafeed, + job: NetworkInJob, + }; + case 'hosts_network_out': + return { + datafeed: NetworkOutDatafeed, + job: NetworkOutJob, + }; + } }; -const validateSetupDatasets = async ( - indices: string[], - timestampField: string, - startTime: number, - endTime: number -) => { - return await callValidateDatasetsAPI(indices, timestampField, startTime, endTime); +const cleanUpModule = async (spaceId: string, sourceId: string) => { + return await cleanUpJobsAndDatafeeds(spaceId, sourceId, metricsHostsJobTypes); }; export const metricHostsModule: ModuleDescriptor = { @@ -121,6 +174,4 @@ export const metricHostsModule: ModuleDescriptor = { getModuleDefinition, setUpModule, cleanUpModule, - validateSetupDatasets, - validateSetupIndices, }; diff --git a/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module_descriptor.ts b/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module_descriptor.ts index cbcff1c307af6..41c6df92fb379 100644 --- a/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module_descriptor.ts +++ b/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module_descriptor.ts @@ -10,17 +10,28 @@ import { cleanUpJobsAndDatafeeds } from '../../infra_ml_cleanup'; import { callJobsSummaryAPI } from '../../api/ml_get_jobs_summary_api'; import { callGetMlModuleAPI } from '../../api/ml_get_module'; import { callSetupMlModuleAPI } from '../../api/ml_setup_module_api'; -import { callValidateIndicesAPI } from '../../../logs/log_analysis/api/validate_indices'; -import { callValidateDatasetsAPI } from '../../../logs/log_analysis/api/validate_datasets'; import { metricsK8SJobTypes, getJobId, MetricK8sJobType, DatasetFilter, bucketSpan, - partitionField, } from '../../../../../common/infra_ml'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import MemoryJob from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_k8s/ml/k8s_memory_usage.json'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import MemoryDatafeed from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_k8s/ml/datafeed_k8s_memory_usage.json'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import NetworkInJob from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_k8s/ml/k8s_network_in.json'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import NetworkInDatafeed from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_k8s/ml/datafeed_k8s_network_in.json'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import NetworkOutJob from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_k8s/ml/k8s_network_out.json'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import NetworkOutDatafeed from '../../../../../../ml/server/models/data_recognizer/modules/metrics_ui_k8s/ml/datafeed_k8s_network_out.json'; +type JobType = 'k8s_memory_usage' | 'k8s_network_in' | 'k8s_network_out'; +export const DEFAULT_K8S_PARTITION_FIELD = 'kubernetes.namespace'; const moduleId = 'metrics_ui_k8s'; const moduleName = i18n.translate('xpack.infra.ml.metricsModuleName', { defaultMessage: 'Metrics anomanly detection', @@ -54,26 +65,72 @@ const setUpModule = async ( end: number | undefined, datasetFilter: DatasetFilter, { spaceId, sourceId, indices, timestampField }: ModuleSourceConfiguration, - pField?: string + partitionField?: string ) => { const indexNamePattern = indices.join(','); - const jobIds = ['k8s_memory_usage', 'k8s_network_in', 'k8s_network_out']; - const jobOverrides = jobIds.map((id) => ({ - job_id: id, - analysis_config: { - bucket_span: `${bucketSpan}ms`, - }, - data_description: { - time_field: timestampField, - }, - custom_settings: { - metrics_source_config: { - indexPattern: indexNamePattern, - timestampField, - bucketSpan, + const jobIds: JobType[] = ['k8s_memory_usage', 'k8s_network_in', 'k8s_network_out']; + const jobOverrides = jobIds.map((id) => { + const { job: defaultJobConfig } = getDefaultJobConfigs(id); + + // eslint-disable-next-line @typescript-eslint/naming-convention + const analysis_config = { + ...defaultJobConfig.analysis_config, + }; + + if (partitionField) { + analysis_config.detectors[0].partition_field_name = partitionField; + if (analysis_config.influencers.indexOf(partitionField) === -1) { + analysis_config.influencers.push(partitionField); + } + } + + return { + job_id: id, + data_description: { + time_field: timestampField, + }, + analysis_config, + custom_settings: { + metrics_source_config: { + indexPattern: indexNamePattern, + timestampField, + bucketSpan, + }, + }, + }; + }); + + const datafeedOverrides = jobIds.map((id) => { + const { datafeed: defaultDatafeedConfig } = getDefaultJobConfigs(id); + + if (!partitionField || id === 'k8s_memory_usage') { + // Since the host memory usage doesn't have custom aggs, we don't need to do anything to add a partition field + return defaultDatafeedConfig; + } + + // Because the ML K8s jobs ship with a default partition field of {kubernetes.namespace}, ignore that agg and wrap it in our own agg. + const innerAggregation = + defaultDatafeedConfig.aggregations[DEFAULT_K8S_PARTITION_FIELD].aggregations; + + // If we have a partition field, we need to change the aggregation to do a terms agg to partition the data at the top level + const aggregations = { + [partitionField]: { + terms: { + field: partitionField, + size: 25, // 25 is arbitratry and only used to keep the number of buckets to a managable level in the event that the user choose a high cardinality partition field. + }, + aggregations: { + ...innerAggregation, + }, }, - }, - })); + }; + + return { + ...defaultDatafeedConfig, + job_id: id, + aggregations, + }; + }); return callSetupMlModuleAPI( moduleId, @@ -83,34 +140,32 @@ const setUpModule = async ( sourceId, indexNamePattern, jobOverrides, - [] + datafeedOverrides ); }; -const cleanUpModule = async (spaceId: string, sourceId: string) => { - return await cleanUpJobsAndDatafeeds(spaceId, sourceId, metricsK8SJobTypes); -}; - -const validateSetupIndices = async (indices: string[], timestampField: string) => { - return await callValidateIndicesAPI(indices, [ - { - name: timestampField, - validTypes: ['date'], - }, - { - name: partitionField, - validTypes: ['keyword'], - }, - ]); +const getDefaultJobConfigs = (jobId: JobType) => { + switch (jobId) { + case 'k8s_memory_usage': + return { + datafeed: MemoryDatafeed, + job: MemoryJob, + }; + case 'k8s_network_in': + return { + datafeed: NetworkInDatafeed, + job: NetworkInJob, + }; + case 'k8s_network_out': + return { + datafeed: NetworkOutDatafeed, + job: NetworkOutJob, + }; + } }; -const validateSetupDatasets = async ( - indices: string[], - timestampField: string, - startTime: number, - endTime: number -) => { - return await callValidateDatasetsAPI(indices, timestampField, startTime, endTime); +const cleanUpModule = async (spaceId: string, sourceId: string) => { + return await cleanUpJobsAndDatafeeds(spaceId, sourceId, metricsK8SJobTypes); }; export const metricHostsModule: ModuleDescriptor = { @@ -124,6 +179,4 @@ export const metricHostsModule: ModuleDescriptor = { getModuleDefinition, setUpModule, cleanUpModule, - validateSetupDatasets, - validateSetupIndices, }; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomoly_detection_flyout.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomoly_detection_flyout.tsx index b063713fa2c97..b5d224910e819 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomoly_detection_flyout.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomoly_detection_flyout.tsx @@ -50,10 +50,10 @@ export const AnomalyDetectionFlyout = () => { return ( <> - + {showFlyout && ( diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/flyout_home.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/flyout_home.tsx index 801dff9c4a17a..5b520084ebb74 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/flyout_home.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/flyout_home.tsx @@ -5,7 +5,7 @@ */ import React, { useState, useCallback, useEffect } from 'react'; -import { EuiFlyoutHeader, EuiTitle, EuiFlyoutBody, EuiTabs, EuiTab, EuiSpacer } from '@elastic/eui'; +import { EuiFlyoutHeader, EuiTitle, EuiFlyoutBody, EuiSpacer } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiText, EuiFlexGroup, EuiFlexItem, EuiCard, EuiIcon } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; @@ -30,7 +30,7 @@ interface Props { } export const FlyoutHome = (props: Props) => { - const [tab, setTab] = useState<'jobs' | 'anomalies'>('jobs'); + const [tab] = useState<'jobs' | 'anomalies'>('jobs'); const { goToSetup } = props; const { fetchJobStatus: fetchHostJobStatus, @@ -56,18 +56,10 @@ export const FlyoutHome = (props: Props) => { goToSetup('kubernetes'); }, [goToSetup]); - const goToJobs = useCallback(() => { - setTab('jobs'); - }, []); - const jobIds = [ ...(k8sJobSummaries || []).map((k) => k.id), ...(hostJobSummaries || []).map((h) => h.id), ]; - const anomaliesUrl = useLinkProps({ - app: 'ml', - pathname: `/explorer?_g=${createResultsUrl(jobIds)}`, - }); useEffect(() => { if (hasInfraMLReadCapabilities) { @@ -105,30 +97,24 @@ export const FlyoutHome = (props: Props) => { - - - - - - - - +
+ +

+ +

+
+
+ {hostJobSummaries.length > 0 && ( <> 0} hasK8sJobs={k8sJobSummaries.length > 0} + jobIds={jobIds} /> @@ -151,6 +137,7 @@ export const FlyoutHome = (props: Props) => { interface CalloutProps { hasHostJobs: boolean; hasK8sJobs: boolean; + jobIds: string[]; } const JobsEnabledCallout = (props: CalloutProps) => { let target = ''; @@ -175,8 +162,34 @@ const JobsEnabledCallout = (props: CalloutProps) => { pathname: '/jobs', }); + const anomaliesUrl = useLinkProps({ + app: 'ml', + pathname: `/explorer?_g=${createResultsUrl(props.jobIds)}`, + }); + return ( <> + + + + + + + + + + + + + + + { } iconType="check" /> - - - - ); }; @@ -211,30 +217,11 @@ interface CreateJobTab { const CreateJobTab = (props: CreateJobTab) => { return ( <> -
- -

- -

-
- -

- -

-
-
- - + {/* */} } // title="Hosts" title={ @@ -245,7 +232,7 @@ const CreateJobTab = (props: CreateJobTab) => { } description={ } @@ -254,7 +241,7 @@ const CreateJobTab = (props: CreateJobTab) => { {props.hasHostJobs && ( @@ -262,7 +249,7 @@ const CreateJobTab = (props: CreateJobTab) => { {!props.hasHostJobs && ( @@ -273,7 +260,7 @@ const CreateJobTab = (props: CreateJobTab) => { } title={ { } description={ } @@ -292,7 +279,7 @@ const CreateJobTab = (props: CreateJobTab) => { {props.hasK8sJobs && ( @@ -300,7 +287,7 @@ const CreateJobTab = (props: CreateJobTab) => { {!props.hasK8sJobs && ( diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/job_setup_screen.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/job_setup_screen.tsx index 428c002da6383..c327d187f6bc2 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/job_setup_screen.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/job_setup_screen.tsx @@ -20,6 +20,7 @@ import { useSourceViaHttp } from '../../../../../../containers/source/use_source import { useMetricK8sModuleContext } from '../../../../../../containers/ml/modules/metrics_k8s/module'; import { useMetricHostsModuleContext } from '../../../../../../containers/ml/modules/metrics_hosts/module'; import { FixedDatePicker } from '../../../../../../components/fixed_datepicker'; +import { DEFAULT_K8S_PARTITION_FIELD } from '../../../../../../containers/ml/modules/metrics_k8s/module_descriptor'; interface Props { jobType: 'hosts' | 'kubernetes'; @@ -107,7 +108,7 @@ export const JobSetupScreen = (props: Props) => { useEffect(() => { if (props.jobType === 'kubernetes') { - setPartitionField(['kubernetes.namespace']); + setPartitionField([DEFAULT_K8S_PARTITION_FIELD]); } }, [props.jobType]); From 6caf6d5080394418fba519166dde58addb5a0bf3 Mon Sep 17 00:00:00 2001 From: Dima Arnautov Date: Thu, 1 Oct 2020 17:54:56 +0200 Subject: [PATCH 03/25] [ML] Model management UI fixes and enhancements (#79072) * [ML] link to edit pipeline * [ML] view training data link * [ML] format stats and configs * [ML] refactor date_utils * [ML] fix types * [ML] change "View" icon and label * [ML] revert label change --- .../util/date_utils.test.ts | 0 .../application => common}/util/date_utils.ts | 11 ++- .../annotation_description_list/index.tsx | 12 +-- .../annotations_table/annotations_table.js | 14 +-- .../anomalies_table_columns.js | 2 +- .../anomalies_table/anomaly_details.js | 2 +- .../components/anomalies_table/links_menu.js | 2 +- .../components/data_grid/common.ts | 2 +- .../components/job_messages/job_messages.tsx | 7 +- .../model_snapshots/model_snapshots_table.tsx | 11 +-- .../revert_model_snapshot_flyout.tsx | 5 +- .../analytics_list/expanded_row.tsx | 2 +- .../models_management/expanded_row.tsx | 91 +++++++++++++++++-- .../models_management/models_list.tsx | 10 +- .../explorer_chart_distribution.js | 2 +- .../explorer_chart_single_metric.js | 2 +- .../explorer/explorer_swimlane.tsx | 2 +- .../reducers/explorer_reducer/reducer.ts | 2 +- .../forecasts_table/forecasts_table.js | 14 +-- .../components/job_details/format_values.js | 5 +- .../charts/event_rate_chart/overlay_range.tsx | 8 +- .../components/analytics_panel/table.tsx | 2 +- .../anomaly_detection_panel/table.tsx | 2 +- .../application/services/job_service.js | 2 +- .../forecasting_modal/forecasts_list.js | 2 +- .../timeseries_chart/timeseries_chart.js | 2 +- x-pack/plugins/ml/public/shared.ts | 2 +- 27 files changed, 138 insertions(+), 80 deletions(-) rename x-pack/plugins/ml/{public/application => common}/util/date_utils.test.ts (100%) rename x-pack/plugins/ml/{public/application => common}/util/date_utils.ts (78%) diff --git a/x-pack/plugins/ml/public/application/util/date_utils.test.ts b/x-pack/plugins/ml/common/util/date_utils.test.ts similarity index 100% rename from x-pack/plugins/ml/public/application/util/date_utils.test.ts rename to x-pack/plugins/ml/common/util/date_utils.test.ts diff --git a/x-pack/plugins/ml/public/application/util/date_utils.ts b/x-pack/plugins/ml/common/util/date_utils.ts similarity index 78% rename from x-pack/plugins/ml/public/application/util/date_utils.ts rename to x-pack/plugins/ml/common/util/date_utils.ts index 21adc0b4b9c66..73ac68b2493f3 100644 --- a/x-pack/plugins/ml/public/application/util/date_utils.ts +++ b/x-pack/plugins/ml/common/util/date_utils.ts @@ -6,10 +6,11 @@ // utility functions for handling dates -// @ts-ignore -import { formatDate } from '@elastic/eui/lib/services/format'; import dateMath from '@elastic/datemath'; -import { TimeRange } from '../../../../../../src/plugins/data/common'; +import { formatDate } from '@elastic/eui'; +import { TimeRange } from '../../../../../src/plugins/data/common'; +import { TIME_FORMAT } from '../constants/time_format'; + export function formatHumanReadableDate(ts: number) { return formatDate(ts, 'MMMM Do YYYY'); } @@ -28,3 +29,7 @@ export function validateTimeRange(time?: TimeRange): boolean { const momentDateTo = dateMath.parse(time.to); return !!(momentDateFrom && momentDateFrom.isValid() && momentDateTo && momentDateTo.isValid()); } + +export const timeFormatter = (value: number) => { + return formatDate(value, TIME_FORMAT); +}; diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotation_description_list/index.tsx b/x-pack/plugins/ml/public/application/components/annotations/annotation_description_list/index.tsx index eee2f8dca244d..156ad72ba9f9f 100644 --- a/x-pack/plugins/ml/public/application/components/annotations/annotation_description_list/index.tsx +++ b/x-pack/plugins/ml/public/application/components/annotations/annotation_description_list/index.tsx @@ -15,7 +15,7 @@ import { EuiDescriptionList } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { Annotation } from '../../../../../common/types/annotations'; -import { formatHumanReadableDateTimeSeconds } from '../../../util/date_utils'; +import { formatHumanReadableDateTimeSeconds } from '../../../../../common/util/date_utils'; interface Props { annotation: Annotation; @@ -61,7 +61,7 @@ export const AnnotationDescriptionList = ({ annotation, detectorDescription }: P defaultMessage: 'Created by', } ), - description: annotation.create_username, + description: annotation.create_username ?? '', }); listItems.push({ title: i18n.translate( @@ -79,7 +79,7 @@ export const AnnotationDescriptionList = ({ annotation, detectorDescription }: P defaultMessage: 'Modified by', } ), - description: annotation.modified_username, + description: annotation.modified_username ?? '', }); } if (detectorDescription !== undefined) { @@ -94,19 +94,19 @@ export const AnnotationDescriptionList = ({ annotation, detectorDescription }: P if (annotation.partition_field_name !== undefined) { listItems.push({ title: annotation.partition_field_name, - description: annotation.partition_field_value, + description: annotation.partition_field_value ?? '', }); } if (annotation.over_field_name !== undefined) { listItems.push({ title: annotation.over_field_name, - description: annotation.over_field_value, + description: annotation.over_field_value ?? '', }); } if (annotation.by_field_name !== undefined) { listItems.push({ title: annotation.by_field_name, - description: annotation.by_field_value, + description: annotation.by_field_value ?? '', }); } diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js b/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js index 0527b8f6d9f60..7eb280c6247c2 100644 --- a/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js +++ b/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js @@ -31,8 +31,6 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { RIGHT_ALIGNMENT } from '@elastic/eui/lib/services'; -import { formatDate } from '@elastic/eui/lib/services/format'; - import { addItemToRecentlyAccessed } from '../../../util/recently_accessed'; import { ml } from '../../../services/ml_api_service'; import { mlJobService } from '../../../services/job_service'; @@ -42,7 +40,6 @@ import { getLatestDataOrBucketTimestamp, isTimeSeriesViewJob, } from '../../../../../common/util/job_utils'; -import { TIME_FORMAT } from '../../../../../common/constants/time_format'; import { annotation$, @@ -56,6 +53,7 @@ import { import { withKibana } from '../../../../../../../../src/plugins/kibana_react/public'; import { ML_APP_URL_GENERATOR, ML_PAGES } from '../../../../../common/constants/ml_url_generator'; import { PLUGIN_ID } from '../../../../../common/constants/app'; +import { timeFormatter } from '../../../../../common/util/date_utils'; const CURRENT_SERIES = 'current_series'; /** @@ -377,10 +375,6 @@ class AnnotationsTableUI extends Component { ); } - function renderDate(date) { - return formatDate(date, TIME_FORMAT); - } - const columns = [ { field: 'annotation', @@ -397,7 +391,7 @@ class AnnotationsTableUI extends Component { defaultMessage: 'From', }), dataType: 'date', - render: renderDate, + render: timeFormatter, sortable: true, }, { @@ -406,7 +400,7 @@ class AnnotationsTableUI extends Component { defaultMessage: 'To', }), dataType: 'date', - render: renderDate, + render: timeFormatter, sortable: true, }, { @@ -415,7 +409,7 @@ class AnnotationsTableUI extends Component { defaultMessage: 'Last modified date', }), dataType: 'date', - render: renderDate, + render: timeFormatter, sortable: true, }, { diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js index 1f8c8633afa47..d2c4122bc1b57 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table_columns.js @@ -16,7 +16,7 @@ import { formatHumanReadableDate, formatHumanReadableDateTime, formatHumanReadableDateTimeSeconds, -} from '../../util/date_utils'; +} from '../../../../common/util/date_utils'; import { DescriptionCell } from './description_cell'; import { DetectorCell } from './detector_cell'; diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/anomaly_details.js b/x-pack/plugins/ml/public/application/components/anomalies_table/anomaly_details.js index cd3875f8cbd2a..a2a3aea5988aa 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/anomaly_details.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/anomaly_details.js @@ -26,7 +26,7 @@ import { EuiTabbedContent, EuiText, } from '@elastic/eui'; -import { formatHumanReadableDateTimeSeconds } from '../../util/date_utils'; +import { formatHumanReadableDateTimeSeconds } from '../../../../common/util/date_utils'; import { EntityCell } from '../entity_cell'; import { diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js b/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js index d898734f34c93..079d56da60e5e 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.js @@ -26,7 +26,7 @@ import { getFieldTypeFromMapping } from '../../services/mapping_service'; import { ml } from '../../services/ml_api_service'; import { mlJobService } from '../../services/job_service'; import { getUrlForRecord, openCustomUrlWindow } from '../../util/custom_url_utils'; -import { formatHumanReadableDateTimeSeconds } from '../../util/date_utils'; +import { formatHumanReadableDateTimeSeconds } from '../../../../common/util/date_utils'; import { getIndexPatternIdFromName } from '../../util/index_utils'; import { replaceStringTokens } from '../../util/string_utils'; import { ML_APP_URL_GENERATOR, ML_PAGES } from '../../../../common/constants/ml_url_generator'; diff --git a/x-pack/plugins/ml/public/application/components/data_grid/common.ts b/x-pack/plugins/ml/public/application/components/data_grid/common.ts index f252729cc20cd..36b0573d609d8 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/common.ts +++ b/x-pack/plugins/ml/public/application/components/data_grid/common.ts @@ -37,7 +37,7 @@ import { OUTLIER_SCORE, TOP_CLASSES, } from '../../data_frame_analytics/common/constants'; -import { formatHumanReadableDateTimeSeconds } from '../../util/date_utils'; +import { formatHumanReadableDateTimeSeconds } from '../../../../common/util/date_utils'; import { getNestedProperty } from '../../util/object_utils'; import { mlFieldFormatService } from '../../services/field_format_service'; diff --git a/x-pack/plugins/ml/public/application/components/job_messages/job_messages.tsx b/x-pack/plugins/ml/public/application/components/job_messages/job_messages.tsx index 798ceae0f0732..f60cd61b25cd4 100644 --- a/x-pack/plugins/ml/public/application/components/job_messages/job_messages.tsx +++ b/x-pack/plugins/ml/public/application/components/job_messages/job_messages.tsx @@ -7,14 +7,13 @@ import React, { FC } from 'react'; import { EuiSpacer, EuiInMemoryTable, EuiButtonIcon, EuiToolTip } from '@elastic/eui'; -// @ts-ignore -import { formatDate } from '@elastic/eui/lib/services/format'; + import { i18n } from '@kbn/i18n'; import theme from '@elastic/eui/dist/eui_theme_light.json'; import { JobMessage } from '../../../../common/types/audit_message'; -import { TIME_FORMAT } from '../../../../common/constants/time_format'; import { JobIcon } from '../job_message_icon'; +import { timeFormatter } from '../../../../common/util/date_utils'; interface JobMessagesProps { messages: JobMessage[]; @@ -55,7 +54,7 @@ export const JobMessages: FC = ({ messages, loading, error, re name: i18n.translate('xpack.ml.jobMessages.timeLabel', { defaultMessage: 'Time', }), - render: (timestamp: number) => formatDate(timestamp, TIME_FORMAT), + render: timeFormatter, width: '120px', sortable: true, }, diff --git a/x-pack/plugins/ml/public/application/components/model_snapshots/model_snapshots_table.tsx b/x-pack/plugins/ml/public/application/components/model_snapshots/model_snapshots_table.tsx index 64fdd97903b60..5b175eb06a4a3 100644 --- a/x-pack/plugins/ml/public/application/components/model_snapshots/model_snapshots_table.tsx +++ b/x-pack/plugins/ml/public/application/components/model_snapshots/model_snapshots_table.tsx @@ -13,7 +13,6 @@ import { EuiInMemoryTable, EuiLoadingSpinner, EuiBasicTableColumn, - formatDate, } from '@elastic/eui'; import { checkPermission } from '../../capabilities/check_capabilities'; @@ -21,12 +20,12 @@ import { EditModelSnapshotFlyout } from './edit_model_snapshot_flyout'; import { RevertModelSnapshotFlyout } from './revert_model_snapshot_flyout'; import { ml } from '../../services/ml_api_service'; import { JOB_STATE, DATAFEED_STATE } from '../../../../common/constants/states'; -import { TIME_FORMAT } from '../../../../common/constants/time_format'; import { CloseJobConfirm } from './close_job_confirm'; import { ModelSnapshot, CombinedJobWithStats, } from '../../../../common/types/anomaly_detection_jobs'; +import { timeFormatter } from '../../../../common/util/date_utils'; interface Props { job: CombinedJobWithStats; @@ -138,7 +137,7 @@ export const ModelSnapshotTable: FC = ({ job, refreshJobList }) => { defaultMessage: 'Date created', }), dataType: 'date', - render: renderDate, + render: timeFormatter, sortable: true, }, { @@ -147,7 +146,7 @@ export const ModelSnapshotTable: FC = ({ job, refreshJobList }) => { defaultMessage: 'Latest timestamp', }), dataType: 'date', - render: renderDate, + render: timeFormatter, sortable: true, }, { @@ -246,10 +245,6 @@ export const ModelSnapshotTable: FC = ({ job, refreshJobList }) => { ); }; -function renderDate(date: number) { - return formatDate(date, TIME_FORMAT); -} - async function getCombinedJobState(jobId: string) { const jobs = await ml.jobs.jobs([jobId]); diff --git a/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/revert_model_snapshot_flyout.tsx b/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/revert_model_snapshot_flyout.tsx index e37efe60f8018..62f5623f67964 100644 --- a/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/revert_model_snapshot_flyout.tsx +++ b/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/revert_model_snapshot_flyout.tsx @@ -32,7 +32,6 @@ import { EuiHorizontalRule, EuiSuperSelect, EuiText, - formatDate, } from '@elastic/eui'; import { @@ -47,8 +46,8 @@ import { LineChartPoint } from '../../../jobs/new_job/common/chart_loader'; import { EventRateChart } from '../../../jobs/new_job/pages/components/charts/event_rate_chart/event_rate_chart'; import { Anomaly } from '../../../jobs/new_job/common/results_loader/results_loader'; import { parseInterval } from '../../../../../common/util/parse_interval'; -import { TIME_FORMAT } from '../../../../../common/constants/time_format'; import { CreateCalendar, CalendarEvent } from './create_calendar'; +import { timeFormatter } from '../../../../../common/util/date_utils'; interface Props { snapshot: ModelSnapshot; @@ -255,7 +254,7 @@ export const RevertModelSnapshotFlyout: FC = ({ snapshot, snapshots, job,
diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row.tsx index 95204f9ba09fc..a0bd437a667a2 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row.tsx @@ -11,7 +11,7 @@ import { EuiIcon, EuiLoadingSpinner, EuiTabbedContent } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { formatHumanReadableDateTimeSeconds } from '../../../../../util/date_utils'; +import { formatHumanReadableDateTimeSeconds } from '../../../../../../../common/util/date_utils'; import { DataFrameAnalyticsListRow } from './common'; import { ExpandedRowDetailsPane, SectionConfig, SectionItem } from './expanded_row_details_pane'; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/models_management/expanded_row.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/models_management/expanded_row.tsx index 7b9329fee783b..803a2523a55e0 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/models_management/expanded_row.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/models_management/expanded_row.tsx @@ -20,16 +20,35 @@ import { EuiHorizontalRule, EuiFlexGroup, EuiTextColor, + EuiButtonEmpty, + EuiBadge, } from '@elastic/eui'; -// @ts-ignore -import { formatDate } from '@elastic/eui/lib/services/format'; +import { EuiDescriptionListProps } from '@elastic/eui/src/components/description_list/description_list'; import { ModelItemFull } from './models_list'; -import { TIME_FORMAT } from '../../../../../../../common/constants/time_format'; +import { useMlKibana } from '../../../../../contexts/kibana'; +import { timeFormatter } from '../../../../../../../common/util/date_utils'; interface ExpandedRowProps { item: ModelItemFull; } +const formatterDictionary: Record JSX.Element | string | undefined> = { + tags: (tags: string[]) => { + if (tags.length === 0) return; + return ( +
+ {tags.map((tag) => ( + + {tag} + + ))} +
+ ); + }, + create_time: timeFormatter, + timestamp: timeFormatter, +}; + export const ExpandedRow: FC = ({ item }) => { const { inference_config: inferenceConfig, @@ -57,19 +76,45 @@ export const ExpandedRow: FC = ({ item }) => { license_level, }; - function formatToListItems(items: Record) { + function formatToListItems(items: Record): EuiDescriptionListProps['listItems'] { return Object.entries(items) .map(([title, value]) => { - if (title.includes('timestamp')) { - value = formatDate(value, TIME_FORMAT); + if (title in formatterDictionary) { + return { + title, + description: formatterDictionary[title](value), + }; } - return { title, description: typeof value === 'object' ? JSON.stringify(value) : value }; + return { + title, + description: + typeof value === 'object' ? ( + + {JSON.stringify(value, null, 2)} + + ) : ( + value + ), + }; }) .filter(({ description }) => { return description !== undefined; }); } + const { + services: { + share, + application: { navigateToUrl }, + }, + } = useMlKibana(); + const tabs = [ { id: 'details', @@ -323,9 +368,35 @@ export const ExpandedRow: FC = ({ item }) => { return ( - -
{pipelineName}
-
+ + + +
{pipelineName}
+
+
+ + { + const ingestPipelinesAppUrlGenerator = share.urlGenerators.getUrlGenerator( + 'INGEST_PIPELINES_APP_URL_GENERATOR' + ); + await navigateToUrl( + await ingestPipelinesAppUrlGenerator.createUrl({ + page: 'pipeline_edit', + pipelineId: pipelineName, + absolute: true, + }) + ); + }} + > + + + +
+ {description && {description}} diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/models_management/models_list.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/models_management/models_list.tsx index dbc7a23f2258b..d5a7ca6e96c06 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/models_management/models_list.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/models_management/models_list.tsx @@ -19,15 +19,13 @@ import { EuiBadge, SearchFilterConfig, } from '@elastic/eui'; -// @ts-ignore -import { formatDate } from '@elastic/eui/lib/services/format'; + import { EuiBasicTableColumn } from '@elastic/eui/src/components/basic_table/basic_table'; import { EuiTableSelectionType } from '@elastic/eui/src/components/basic_table/table_types'; import { Action } from '@elastic/eui/src/components/basic_table/action_types'; import { StatsBar, ModelsBarStats } from '../../../../../components/stats_bar'; import { useInferenceApiService } from '../../../../../services/ml_api_service/inference'; import { ModelsTableToConfigMapping } from './index'; -import { TIME_FORMAT } from '../../../../../../../common/constants/time_format'; import { DeleteModelsModal } from './delete_models_modal'; import { useMlKibana, useMlUrlGenerator, useNotifications } from '../../../../../contexts/kibana'; import { ExpandedRow } from './expanded_row'; @@ -46,6 +44,7 @@ import { useTableSettings } from '../analytics_list/use_table_settings'; import { filterAnalyticsModels, AnalyticsSearchBar } from '../analytics_search_bar'; import { ML_PAGES } from '../../../../../../../common/constants/ml_url_generator'; import { DataFrameAnalysisConfigType } from '../../../../../../../common/types/data_frame_analytics'; +import { timeFormatter } from '../../../../../../../common/util/date_utils'; type Stats = Omit; @@ -277,7 +276,7 @@ export const ModelsList: FC = () => { description: i18n.translate('xpack.ml.inference.modelsList.viewTrainingDataActionLabel', { defaultMessage: 'View training data', }), - icon: 'list', + icon: 'visTable', type: 'icon', available: (item) => item.metadata?.analytics_config?.id, onClick: async (item) => { @@ -290,6 +289,7 @@ export const ModelsList: FC = () => { analysisType: getAnalysisType( item.metadata?.analytics_config.analysis ) as DataFrameAnalysisConfigType, + defaultIsTraining: true, }, }); @@ -375,7 +375,7 @@ export const ModelsList: FC = () => { defaultMessage: 'Created at', }), dataType: 'date', - render: (date: string) => formatDate(date, TIME_FORMAT), + render: timeFormatter, sortable: true, }, { diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js index 00aca5d43be85..994975912cd6f 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_distribution.js @@ -17,7 +17,7 @@ import d3 from 'd3'; import $ from 'jquery'; import moment from 'moment'; -import { formatHumanReadableDateTime } from '../../util/date_utils'; +import { formatHumanReadableDateTime } from '../../../../common/util/date_utils'; import { formatValue } from '../../formatters/format_value'; import { getSeverityColor, getSeverityWithLow } from '../../../../common/util/anomaly_utils'; import { diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js index 0a76211f2e330..606d1c0690422 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_charts/explorer_chart_single_metric.js @@ -17,7 +17,7 @@ import $ from 'jquery'; import moment from 'moment'; import { i18n } from '@kbn/i18n'; -import { formatHumanReadableDateTime } from '../../util/date_utils'; +import { formatHumanReadableDateTime } from '../../../../common/util/date_utils'; import { formatValue } from '../../formatters/format_value'; import { getSeverityColor, diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx b/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx index 359dc11ca08d1..569709d648b3c 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx +++ b/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx @@ -19,7 +19,7 @@ import { i18n } from '@kbn/i18n'; import { Subject, Subscription } from 'rxjs'; import { TooltipValue } from '@elastic/charts'; import { htmlIdGenerator } from '@elastic/eui'; -import { formatHumanReadableDateTime } from '../util/date_utils'; +import { formatHumanReadableDateTime } from '../../../common/util/date_utils'; import { numTicksForDateFormat } from '../util/chart_utils'; import { getSeverityColor } from '../../../common/util/anomaly_utils'; import { mlEscape } from '../util/string_utils'; diff --git a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/reducer.ts b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/reducer.ts index a38044a8b3425..c5fb0175c54e9 100644 --- a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/reducer.ts +++ b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/reducer.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { formatHumanReadableDateTime } from '../../../util/date_utils'; +import { formatHumanReadableDateTime } from '../../../../../common/util/date_utils'; import { getDefaultChartsData } from '../../explorer_charts/explorer_charts_container_service'; import { EXPLORER_ACTION, VIEW_BY_JOB_LABEL } from '../../explorer_constants'; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js index b32070fff73aa..44ebde634714c 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js @@ -16,10 +16,9 @@ import { EuiLink, EuiLoadingSpinner, } from '@elastic/eui'; -import { formatDate, formatNumber } from '@elastic/eui/lib/services/format'; +import { formatNumber } from '@elastic/eui/lib/services/format'; import { FORECAST_REQUEST_STATE } from '../../../../../../../common/constants/states'; -import { TIME_FORMAT } from '../../../../../../../common/constants/time_format'; import { addItemToRecentlyAccessed } from '../../../../../util/recently_accessed'; import { mlForecastService } from '../../../../../services/forecast_service'; import { i18n } from '@kbn/i18n'; @@ -34,6 +33,7 @@ import { ML_PAGES, } from '../../../../../../../common/constants/ml_url_generator'; import { PLUGIN_ID } from '../../../../../../../common/constants/app'; +import { timeFormatter } from '../../../../../../../common/util/date_utils'; const MAX_FORECASTS = 500; @@ -218,7 +218,7 @@ export class ForecastsTableUI extends Component { defaultMessage: 'Created', }), dataType: 'date', - render: (date) => formatDate(date, TIME_FORMAT), + render: timeFormatter, textOnly: true, sortable: true, scope: 'row', @@ -229,7 +229,7 @@ export class ForecastsTableUI extends Component { defaultMessage: 'From', }), dataType: 'date', - render: (date) => formatDate(date, TIME_FORMAT), + render: timeFormatter, textOnly: true, sortable: true, }, @@ -239,7 +239,7 @@ export class ForecastsTableUI extends Component { defaultMessage: 'To', }), dataType: 'date', - render: (date) => formatDate(date, TIME_FORMAT), + render: timeFormatter, textOnly: true, sortable: true, }, @@ -277,7 +277,7 @@ export class ForecastsTableUI extends Component { name: i18n.translate('xpack.ml.jobsList.jobDetails.forecastsTable.expiresLabel', { defaultMessage: 'Expires', }), - render: (date) => formatDate(date, TIME_FORMAT), + render: timeFormatter, textOnly: true, sortable: true, }, @@ -309,7 +309,7 @@ export class ForecastsTableUI extends Component { { defaultMessage: 'View forecast created at {createdDate}', values: { - createdDate: formatDate(forecast.forecast_create_timestamp, TIME_FORMAT), + createdDate: timeFormatter(forecast.forecast_create_timestamp), }, } ); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js index 3fe4f0e5477a2..eff407a41fb0d 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js @@ -5,10 +5,9 @@ */ import numeral from '@elastic/numeral'; -import { formatDate } from '@elastic/eui/lib/services/format'; import { roundToDecimalPlace } from '../../../../formatters/round_to_decimal_place'; import { toLocaleString } from '../../../../util/string_utils'; -import { TIME_FORMAT } from '../../../../../../common/constants/time_format'; +import { timeFormatter } from '../../../../../../common/util/date_utils'; const DATA_FORMAT = '0.0 b'; @@ -29,7 +28,7 @@ export function formatValues([key, value]) { case 'latest_empty_bucket_timestamp': case 'latest_sparse_bucket_timestamp': case 'latest_bucket_timestamp': - value = formatDate(value, TIME_FORMAT); + value = timeFormatter(value); break; // data diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/charts/event_rate_chart/overlay_range.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/charts/event_rate_chart/overlay_range.tsx index a35c2d9c833a8..8ad359251b029 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/charts/event_rate_chart/overlay_range.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/charts/event_rate_chart/overlay_range.tsx @@ -5,12 +5,10 @@ */ import React, { FC } from 'react'; -// @ts-ignore -import { formatDate } from '@elastic/eui/lib/services/format'; import { EuiIcon } from '@elastic/eui'; import { RectAnnotation, LineAnnotation, AnnotationDomainTypes } from '@elastic/charts'; import { LineChartPoint } from '../../../../common/chart_loader'; -import { TIME_FORMAT } from '../../../../../../../../common/constants/time_format'; +import { timeFormatter } from '../../../../../../../../common/util/date_utils'; interface Props { overlayKey: number; @@ -70,9 +68,7 @@ export const OverlayRange: FC = ({
-
- {formatDate(start, TIME_FORMAT)} -
+
{timeFormatter(start)}
) : undefined diff --git a/x-pack/plugins/ml/public/application/overview/components/analytics_panel/table.tsx b/x-pack/plugins/ml/public/application/overview/components/analytics_panel/table.tsx index fc0645a0e9498..4b469a0f5874d 100644 --- a/x-pack/plugins/ml/public/application/overview/components/analytics_panel/table.tsx +++ b/x-pack/plugins/ml/public/application/overview/components/analytics_panel/table.tsx @@ -23,7 +23,7 @@ import { getTaskStateBadge, progressColumn, } from '../../../data_frame_analytics/pages/analytics_management/components/analytics_list/use_columns'; -import { formatHumanReadableDateTimeSeconds } from '../../../util/date_utils'; +import { formatHumanReadableDateTimeSeconds } from '../../../../../common/util/date_utils'; import { ViewLink } from './actions'; diff --git a/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/table.tsx b/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/table.tsx index 8515431d49b17..b95aed01ebae8 100644 --- a/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/table.tsx +++ b/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/table.tsx @@ -20,7 +20,7 @@ import { EuiToolTip, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { formatHumanReadableDateTimeSeconds } from '../../../util/date_utils'; +import { formatHumanReadableDateTimeSeconds } from '../../../../../common/util/date_utils'; import { ExplorerLink } from './actions'; import { getJobsFromGroup } from './utils'; import { GroupsDictionary, Group } from './anomaly_detection_panel'; diff --git a/x-pack/plugins/ml/public/application/services/job_service.js b/x-pack/plugins/ml/public/application/services/job_service.js index 939ad34e77a39..0971b47605135 100644 --- a/x-pack/plugins/ml/public/application/services/job_service.js +++ b/x-pack/plugins/ml/public/application/services/job_service.js @@ -15,7 +15,7 @@ import { isWebUrl } from '../util/url_utils'; import { ML_DATA_PREVIEW_COUNT } from '../../../common/util/job_utils'; import { TIME_FORMAT } from '../../../common/constants/time_format'; import { parseInterval } from '../../../common/util/parse_interval'; -import { validateTimeRange } from '../util/date_utils'; +import { validateTimeRange } from '../../../common/util/date_utils'; let jobs = []; let datafeedIds = {}; diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js index cbc2c324a8bc6..2378d8c835ce9 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasts_list.js @@ -13,7 +13,7 @@ import React from 'react'; import { EuiButtonIcon, EuiIcon, EuiInMemoryTable, EuiText, EuiToolTip } from '@elastic/eui'; -import { formatHumanReadableDateTimeSeconds } from '../../../util/date_utils'; +import { formatHumanReadableDateTimeSeconds } from '../../../../../common/util/date_utils'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js index 1d166b7be9bc1..4c87c3b374ff3 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js @@ -33,7 +33,7 @@ import { showMultiBucketAnomalyMarker, showMultiBucketAnomalyTooltip, } from '../../../util/chart_utils'; -import { formatHumanReadableDateTimeSeconds } from '../../../util/date_utils'; +import { formatHumanReadableDateTimeSeconds } from '../../../../../common/util/date_utils'; import { getTimeBucketsFromCache } from '../../../util/time_buckets'; import { mlTableService } from '../../../services/table_service'; import { ContextChartMask } from '../context_chart_mask'; diff --git a/x-pack/plugins/ml/public/shared.ts b/x-pack/plugins/ml/public/shared.ts index ec884bfac5351..62b8179c9d5b2 100644 --- a/x-pack/plugins/ml/public/shared.ts +++ b/x-pack/plugins/ml/public/shared.ts @@ -20,4 +20,4 @@ export * from '../common/util/validators'; export * from './application/formatters/metric_change_description'; export * from './application/components/data_grid'; export * from './application/data_frame_analytics/common'; -export * from './application/util/date_utils'; +export * from '../common/util/date_utils'; From e248f32111626e0909d3fad4339f3b625bd71493 Mon Sep 17 00:00:00 2001 From: Caroline Horn <549577+cchaos@users.noreply.github.com> Date: Thu, 1 Oct 2020 11:58:23 -0400 Subject: [PATCH 04/25] [Lens] Consistent Drag and Drop styles (#78674) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Remove wrapping div of DragDrop and pass props to child * Using EuiHighlight * Basic styles in for all DnD states * Fixing dimension button styles * Fix FieldButton to accept `…rest` props * A few other minor fixes * Fixed horizontal scroll of error message * Quick fix for invalid link --- .../public/field_button/field_button.tsx | 37 ++- x-pack/plugins/lens/public/_mixins.scss | 36 +++ .../__snapshots__/drag_drop.test.tsx.snap | 18 +- .../lens/public/drag_drop/drag_drop.scss | 55 +++- .../lens/public/drag_drop/drag_drop.test.tsx | 30 +- .../lens/public/drag_drop/drag_drop.tsx | 65 ++-- .../config_panel/config_panel.scss | 2 +- .../config_panel/config_panel.tsx | 6 +- .../config_panel/dimension_container.tsx | 2 +- .../config_panel/layer_panel.scss | 37 ++- .../editor_frame/config_panel/layer_panel.tsx | 302 ++++++++++-------- .../editor_frame/frame_layout.scss | 2 +- .../workspace_panel/workspace_panel.tsx | 12 +- .../workspace_panel_wrapper.scss | 27 +- .../indexpattern_datasource/datapanel.scss | 2 +- .../dimension_panel/dimension_panel.tsx | 22 +- .../indexpattern_datasource/field_item.scss | 20 +- .../indexpattern_datasource/field_item.tsx | 37 +-- .../definitions/shared_components/buckets.tsx | 10 +- .../translations/translations/ja-JP.json | 1 - .../translations/translations/zh-CN.json | 1 - 21 files changed, 431 insertions(+), 293 deletions(-) diff --git a/src/plugins/kibana_react/public/field_button/field_button.tsx b/src/plugins/kibana_react/public/field_button/field_button.tsx index 97d1b32746120..4c0298a65ba5d 100644 --- a/src/plugins/kibana_react/public/field_button/field_button.tsx +++ b/src/plugins/kibana_react/public/field_button/field_button.tsx @@ -19,7 +19,8 @@ import './field_button.scss'; import classNames from 'classnames'; -import React, { ReactNode, HTMLAttributes } from 'react'; +import React, { ReactNode, HTMLAttributes, ButtonHTMLAttributes } from 'react'; +import { CommonProps } from '@elastic/eui'; export interface FieldButtonProps extends HTMLAttributes { /** @@ -56,7 +57,14 @@ export interface FieldButtonProps extends HTMLAttributes { * The component will render a ` ) : ( -
- {fieldIcon && {fieldIcon}} - {fieldName && {fieldName}} - {fieldInfoIcon &&
{fieldInfoIcon}
} +
+ {innerContent}
)} diff --git a/x-pack/plugins/lens/public/_mixins.scss b/x-pack/plugins/lens/public/_mixins.scss index a3cf6caa5a429..0db72d118cef1 100644 --- a/x-pack/plugins/lens/public/_mixins.scss +++ b/x-pack/plugins/lens/public/_mixins.scss @@ -11,3 +11,39 @@ transparentize(red, .9) 100% ); } + +// Static styles for a draggable item +@mixin lnsDraggable { + @include euiSlightShadow; + background: lightOrDarkTheme($euiColorEmptyShade, $euiColorLightestShade); + border: $euiBorderWidthThin dashed transparent; + cursor: grab; +} + +// Static styles for a drop area +@mixin lnsDroppable { + border: $euiBorderWidthThin dashed $euiBorderColor; +} + +// Hovering state for drag item and drop area +@mixin lnsDragDropHover { + &:hover { + border: $euiBorderWidthThin dashed $euiColorMediumShade; + } +} + +// Style for drop area when there's an item being dragged +@mixin lnsDroppableActive { + background-color: transparentize($euiColorVis0, .9); +} + +// Style for drop area while hovering with item +@mixin lnsDroppableActiveHover { + background-color: transparentize($euiColorVis0, .75); + border: $euiBorderWidthThin dashed $euiColorVis0; +} + +// Style for drop area that is not allowed for current item +@mixin lnsDroppableNotAllowed { + opacity: .5; +} diff --git a/x-pack/plugins/lens/public/drag_drop/__snapshots__/drag_drop.test.tsx.snap b/x-pack/plugins/lens/public/drag_drop/__snapshots__/drag_drop.test.tsx.snap index 3581151dd5f76..dc53f3a2bc2a7 100644 --- a/x-pack/plugins/lens/public/drag_drop/__snapshots__/drag_drop.test.tsx.snap +++ b/x-pack/plugins/lens/public/drag_drop/__snapshots__/drag_drop.test.tsx.snap @@ -1,17 +1,17 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`DragDrop droppable is reflected in the className 1`] = ` -
Hello! -
+ `; exports[`DragDrop items that have droppable=false get special styling when another item is dragged 1`] = ` -
Hello! -
+ `; exports[`DragDrop renders if nothing is being dragged 1`] = ` -
Hello! -
+ `; diff --git a/x-pack/plugins/lens/public/drag_drop/drag_drop.scss b/x-pack/plugins/lens/public/drag_drop/drag_drop.scss index c971540e165c1..410aaef9a5195 100644 --- a/x-pack/plugins/lens/public/drag_drop/drag_drop.scss +++ b/x-pack/plugins/lens/public/drag_drop/drag_drop.scss @@ -1,13 +1,54 @@ -.lnsDragDrop-isNotDroppable { - opacity: .5; +@import '../variables'; +@import '../mixins'; + +.lnsDragDrop { + transition: background-color $euiAnimSpeedFast ease-in-out, border-color $euiAnimSpeedFast ease-in-out; +} + +// Draggable item +.lnsDragDrop-isDraggable { + @include lnsDraggable; + @include lnsDragDropHover; + + // Include a possible nested button like when using FieldButton + > .kbnFieldButton__button { + cursor: grab; + } + + &:focus { + @include euiFocusRing; + } +} + +// Draggable item when it is moving +.lnsDragDrop-isHidden { + opacity: 0; +} + +// Drop area +.lnsDragDrop-isDroppable { + @include lnsDroppable; } -// Fix specificity by chaining classes +// Drop area when there's an item being dragged +.lnsDragDrop-isDropTarget { + @include lnsDroppableActive; +} -.lnsDragDrop.lnsDragDrop-isDropTarget { - background-color: transparentize($euiColorSecondary, .9); +// Drop area while hovering with item +.lnsDragDrop-isActiveDropTarget { + @include lnsDroppableActiveHover; +} + +// Drop area that is not allowed for current item +.lnsDragDrop-isNotDroppable { + @include lnsDroppableNotAllowed; } -.lnsDragDrop.lnsDragDrop-isActiveDropTarget { - background-color: transparentize($euiColorSecondary, .75); +// Drop area will be replacing existing content +.lnsDragDrop-isReplacing { + &, + .lnsLayerPanel__triggerLink { + text-decoration: line-through; + } } diff --git a/x-pack/plugins/lens/public/drag_drop/drag_drop.test.tsx b/x-pack/plugins/lens/public/drag_drop/drag_drop.test.tsx index 3240357c254ea..b1cc4c06c2165 100644 --- a/x-pack/plugins/lens/public/drag_drop/drag_drop.test.tsx +++ b/x-pack/plugins/lens/public/drag_drop/drag_drop.test.tsx @@ -15,7 +15,7 @@ describe('DragDrop', () => { test('renders if nothing is being dragged', () => { const component = render( - Hello! + ); @@ -24,7 +24,11 @@ describe('DragDrop', () => { test('dragover calls preventDefault if droppable is true', () => { const preventDefault = jest.fn(); - const component = mount(Hello!); + const component = mount( + + + + ); component.find('[data-test-subj="lnsDragDrop"]').simulate('dragover', { preventDefault }); @@ -33,7 +37,11 @@ describe('DragDrop', () => { test('dragover does not call preventDefault if droppable is false', () => { const preventDefault = jest.fn(); - const component = mount(Hello!); + const component = mount( + + + + ); component.find('[data-test-subj="lnsDragDrop"]').simulate('dragover', { preventDefault }); @@ -51,7 +59,7 @@ describe('DragDrop', () => { const component = mount( - Hello! + ); @@ -74,7 +82,7 @@ describe('DragDrop', () => { const component = mount( - Hello! + ); @@ -98,7 +106,7 @@ describe('DragDrop', () => { const component = mount( - Hello! + ); @@ -121,7 +129,7 @@ describe('DragDrop', () => { }} droppable > - Hello! + ); @@ -132,10 +140,10 @@ describe('DragDrop', () => { const component = mount( {}}> - Ignored + {}} droppable={false}> - Hello! + ); @@ -154,14 +162,14 @@ describe('DragDrop', () => { }} > - Ignored + {}} droppable getAdditionalClassesOnEnter={getAdditionalClasses} > - Hello! + ); diff --git a/x-pack/plugins/lens/public/drag_drop/drag_drop.tsx b/x-pack/plugins/lens/public/drag_drop/drag_drop.tsx index 6941974a63cd3..b36415fee5b15 100644 --- a/x-pack/plugins/lens/public/drag_drop/drag_drop.tsx +++ b/x-pack/plugins/lens/public/drag_drop/drag_drop.tsx @@ -41,9 +41,14 @@ interface BaseProps { value?: unknown; /** - * The React children. + * Optional comparison function to check whether a value is the dragged one */ - children: React.ReactNode; + isValueEqual?: (value1: unknown, value2: unknown) => boolean; + + /** + * The React element which will be passed the draggable handlers + */ + children: React.ReactElement; /** * Indicates whether or not the currently dragged item @@ -60,6 +65,18 @@ interface BaseProps { * The optional test subject associated with this DOM element. */ 'data-test-subj'?: string; + + /** + * Indicates to the user whether the currently dragged item + * will be moved or copied + */ + dragType?: 'copy' | 'move'; + + /** + * Indicates to the user whether the drop action will + * replace something that is existing or add a new one + */ + dropType?: 'add' | 'replace'; } /** @@ -98,12 +115,14 @@ type Props = DraggableProps | NonDraggableProps; export const DragDrop = (props: Props) => { const { dragging, setDragging } = useContext(DragContext); - const { value, draggable, droppable } = props; + const { value, draggable, droppable, isValueEqual } = props; return ( - {children} -
- ); + return React.cloneElement(children, { + 'data-test-subj': props['data-test-subj'] || 'lnsDragDrop', + className: classNames(children.props.className, classes), + onDragOver: dragOver, + onDragLeave: dragLeave, + onDrop: drop, + draggable, + onDragEnd: dragEnd, + onDragStart: dragStart, + }); }); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.scss b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.scss index 1965b51f97034..a58b5c21e7724 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.scss +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.scss @@ -3,5 +3,5 @@ // Remove EuiButton's default shadow to make button more subtle // sass-lint:disable-block no-important box-shadow: none !important; - border: 1px dashed currentColor; + border-color: $euiColorLightShade; } diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx index ad16038f44911..6b7e5ba8ea89d 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/config_panel.tsx @@ -121,6 +121,9 @@ function LayerPanels( { dispatch({ type: 'UPDATE_STATE', diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_container.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_container.tsx index a415eb44cf196..19f4c0428260e 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_container.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_container.tsx @@ -130,7 +130,7 @@ export function DimensionContainer({ return ( <> -
{trigger}
+ {trigger} {flyout} ); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.scss b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.scss index b85c3e843613d..c77db2e65ce2d 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.scss +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.scss @@ -27,36 +27,41 @@ .lnsLayerPanel__dimension { @include euiFontSizeS; - background: lightOrDarkTheme($euiColorEmptyShade, $euiColorLightestShade); border-radius: $euiBorderRadius; display: flex; align-items: center; margin-top: $euiSizeXS; overflow: hidden; -} + width: 100%; + min-height: $euiSizeXXL; -.lnsLayerPanel__dimension-isHidden { - opacity: 0; -} + // NativeRenderer is messing this up + > div { + flex-grow: 1; + } -.lnsLayerPanel__dimension-isReplacing { - text-decoration: line-through; + &:focus, + &:focus-within { + @include euiFocusRing; + } } .lnsLayerPanel__triggerLink { - padding: $euiSizeS; width: 100%; - display: flex; - align-items: center; - min-height: $euiSizeXXL; -} + padding: $euiSizeS; + min-height: $euiSizeXXL - 2; -.lnsLayerPanel__anchor { - width: 100%; + &:focus { + background-color: transparent !important; // sass-lint:disable-line no-important + outline: none !important; // sass-lint:disable-line no-important + } } -.lnsLayerPanel__dndGrab { - padding: $euiSizeS; +.lnsLayerPanel__triggerLinkContent { + // Make EUI button content not centered + justify-content: flex-start; + padding: 0 !important; // sass-lint:disable-line no-important + color: $euiTextSubduedColor; } .lnsLayerPanel__styleEditor { diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx index 46cd0292f2459..ce2955da890d7 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx @@ -17,7 +17,6 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import classNames from 'classnames'; import { NativeRenderer } from '../../../native_renderer'; import { StateSetter, isDraggedOperation } from '../../../types'; import { DragContext, DragDrop, ChildDragDropProvider } from '../../../drag_drop'; @@ -33,6 +32,28 @@ const initialDimensionContainerState = { addingToGroupId: null, }; +function isConfiguration( + value: unknown +): value is { columnId: string; groupId: string; layerId: string } { + return ( + value && + typeof value === 'object' && + 'columnId' in value && + 'groupId' in value && + 'layerId' in value + ); +} + +function isSameConfiguration(config1: unknown, config2: unknown) { + return ( + isConfiguration(config1) && + isConfiguration(config2) && + config1.columnId === config2.columnId && + config1.groupId === config2.groupId && + config1.layerId === config2.layerId + ); +} + export function LayerPanel( props: Exclude & { layerId: string; @@ -203,25 +224,22 @@ export function LayerPanel( return ( { - // If we are dragging another column, add an indication that the behavior will be a replacement' - if ( - isDraggedOperation(dragDropContext.dragging) && - group.groupId !== dragDropContext.dragging.groupId - ) { - return 'lnsLayerPanel__dimension-isReplacing'; - } - return ''; - }} + dragType={ + isDraggedOperation(dragDropContext.dragging) && + accessor === dragDropContext.dragging.columnId + ? 'move' + : 'copy' + } + dropType={ + isDraggedOperation(dragDropContext.dragging) && + group.groupId !== dragDropContext.dragging.groupId + ? 'replace' + : 'add' + } data-test-subj={group.dataTestSubj} draggable={!dimensionContainerState.isOpen} value={{ columnId: accessor, groupId: group.groupId, layerId }} + isValueEqual={isSameConfiguration} label={group.groupLabel} droppable={ Boolean(dragDropContext.dragging) && @@ -254,83 +272,84 @@ export function LayerPanel( } }} > - { - if (dimensionContainerState.isOpen) { - setDimensionContainerState(initialDimensionContainerState); - } else { - setDimensionContainerState({ - isOpen: true, - openId: accessor, - addingToGroupId: null, // not set for existing dimension - }); - } - }, - }} - /> - } - panel={ - <> - {datasourceDimensionEditor} - {visDimensionEditor} - - } - panelTitle={i18n.translate('xpack.lens.configure.configurePanelTitle', { - defaultMessage: '{groupLabel} configuration', - values: { - groupLabel: group.groupLabel, - }, - })} - /> +
+ { + if (dimensionContainerState.isOpen) { + setDimensionContainerState(initialDimensionContainerState); + } else { + setDimensionContainerState({ + isOpen: true, + openId: accessor, + addingToGroupId: null, // not set for existing dimension + }); + } + }, + }} + /> + } + panel={ + <> + {datasourceDimensionEditor} + {visDimensionEditor} + + } + panelTitle={i18n.translate('xpack.lens.configure.configurePanelTitle', { + defaultMessage: '{groupLabel} configuration', + values: { + groupLabel: group.groupLabel, + }, + })} + /> - { - trackUiEvent('indexpattern_dimension_removed'); - props.updateAll( - datasourceId, - layerDatasource.removeColumn({ - layerId, - columnId: accessor, - prevState: layerDatasourceState, - }), - activeVisualization.removeDimension({ - layerId, - columnId: accessor, - prevState: props.visualizationState, - }) - ); - }} - /> + { + trackUiEvent('indexpattern_dimension_removed'); + props.updateAll( + datasourceId, + layerDatasource.removeColumn({ + layerId, + columnId: accessor, + prevState: layerDatasourceState, + }), + activeVisualization.removeDimension({ + layerId, + columnId: accessor, + prevState: props.visualizationState, + }) + ); + }} + /> +
); })} {group.supportsMoreColumns ? ( - +
+ { if (dimensionContainerState.isOpen) { setDimensionContainerState(initialDimensionContainerState); @@ -402,52 +421,51 @@ export function LayerPanel( }); } }} - size="xs" > -
- } - panelTitle={i18n.translate('xpack.lens.configure.configurePanelTitle', { - defaultMessage: '{groupLabel} configuration', - values: { - groupLabel: group.groupLabel, - }, - })} - panel={ - { - props.updateAll( - datasourceId, - newState, - activeVisualization.setDimension({ - layerId, - groupId: group.groupId, - columnId: newId, - prevState: props.visualizationState, - }) - ); - setDimensionContainerState({ - isOpen: true, - openId: newId, - addingToGroupId: null, // clear now that dimension exists - }); - }, - }} - /> - } - /> + setState: (newState: unknown) => { + props.updateAll( + datasourceId, + newState, + activeVisualization.setDimension({ + layerId, + groupId: group.groupId, + columnId: newId, + prevState: props.visualizationState, + }) + ); + setDimensionContainerState({ + isOpen: true, + openId: newId, + addingToGroupId: null, // clear now that dimension exists + }); + }, + }} + /> + } + /> +
) : null} diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/frame_layout.scss b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/frame_layout.scss index bad0563f16f1f..ac52190dc7b0d 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/frame_layout.scss +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/frame_layout.scss @@ -20,7 +20,7 @@ .lnsFrameLayout__pageBody { @include euiScrollBar; min-width: $lnsPanelMinWidth + $euiSizeXL; - overflow: hidden; + overflow: hidden auto; // Leave out bottom padding so the suggestions scrollbar stays flush to window edge // Leave out left padding so the left sidebar's focus states are visible outside of content bounds // This also means needing to add same amount of margin to page content and suggestion items diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel.tsx index e56e55fdd5d6c..2a5798ac6a70c 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel.tsx @@ -221,7 +221,7 @@ export function InnerWorkspacePanel({ )} - + {expression === null && ( <>

@@ -257,7 +257,7 @@ export function InnerWorkspacePanel({ if (localState.expressionBuildError) { return ( - + @@ -283,7 +283,7 @@ export function InnerWorkspacePanel({ onEvent={onEvent} renderError={(errorMessage?: string | null) => { return ( - + @@ -338,8 +338,10 @@ export function InnerWorkspacePanel({ droppable={Boolean(suggestionForDraggedField)} onDrop={onDrop} > - {renderVisualization()} - {Boolean(suggestionForDraggedField) && expression !== null && renderEmptyWorkspace()} +

+ {renderVisualization()} + {Boolean(suggestionForDraggedField) && expression !== null && renderEmptyWorkspace()} +
); diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.scss b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.scss index 7f7385f029ed4..33b9b2fe1dbf0 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.scss +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.scss @@ -1,3 +1,5 @@ +@import '../../../mixins'; + .lnsWorkspacePanelWrapper { @include euiScrollBar; overflow: hidden; @@ -7,6 +9,7 @@ display: flex; flex-direction: column; position: relative; // For positioning the dnd overlay + min-height: $euiSizeXXL * 10; .lnsWorkspacePanelWrapper__pageContentHeader { @include euiTitle('xs'); @@ -25,7 +28,7 @@ display: flex; align-items: stretch; justify-content: stretch; - overflow: hidden; + overflow: auto; > * { flex: 1 1 100%; @@ -41,6 +44,7 @@ // Disable the coloring of the DnD for this element as we'll // Color the whole panel instead background-color: transparent !important; // sass-lint:disable-line no-important + border: none !important; // sass-lint:disable-line no-important } .lnsExpressionRenderer { @@ -60,28 +64,25 @@ display: flex; justify-content: center; align-items: center; - transition: background-color $euiAnimSpeedNormal ease-in-out; + transition: background-color $euiAnimSpeedFast ease-in-out; .lnsDragDrop-isDropTarget & { - background-color: transparentize($euiColorSecondary, .9); + @include lnsDroppable; + @include lnsDroppableActive; p { - transition: filter $euiAnimSpeedNormal ease-in-out; + transition: filter $euiAnimSpeedFast ease-in-out; filter: blur(5px); } } .lnsDragDrop-isActiveDropTarget & { - background-color: transparentize($euiColorSecondary, .75); + @include lnsDroppableActiveHover; .lnsDropIllustration__hand { - animation: pulseArrowContinuous 1.5s ease-in-out 0s infinite normal forwards; + animation: lnsWorkspacePanel__illustrationPulseContinuous 1.5s ease-in-out 0s infinite normal forwards; } } - - &.lnsWorkspacePanel__emptyContent-onTop p { - display: none; - } } .lnsWorkspacePanelWrapper__toolbar { @@ -106,10 +107,10 @@ } .lnsDropIllustration__hand { - animation: pulseArrow 5s ease-in-out 0s infinite normal forwards; + animation: lnsWorkspacePanel__illustrationPulseArrow 5s ease-in-out 0s infinite normal forwards; } -@keyframes pulseArrow { +@keyframes lnsWorkspacePanel__illustrationPulseArrow { 0% { transform: translateY(0%); } 65% { transform: translateY(0%); } 72% { transform: translateY(10%); } @@ -118,7 +119,7 @@ 95% { transform: translateY(0); } } -@keyframes pulseArrowContinuous { +@keyframes lnsWorkspacePanel__illustrationPulseContinuous { 0% { transform: translateY(10%); } 25% { transform: translateY(15%); } 50% { transform: translateY(10%); } diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.scss b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.scss index 155b954e9cf17..df73789eadedf 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.scss +++ b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.scss @@ -12,7 +12,7 @@ .lnsInnerIndexPatternDataPanel__fieldItems { // Quick fix for making sure the shadow and focus rings are visible outside the accordion bounds - padding: $euiSizeXS $euiSizeXS 0; + padding: $euiSizeXS; } .lnsInnerIndexPatternDataPanel__textField { diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx index 6f0a9c2a86acd..12b8d91c35ade 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/dimension_panel.tsx @@ -250,6 +250,10 @@ export const IndexPatternDimensionTriggerComponent = function IndexPatternDimens return null; } + const triggerLinkA11yText = i18n.translate('xpack.lens.configure.editConfig', { + defaultMessage: 'Click to edit configuration or drag to move', + }); + if (currentFieldIsInvalid) { return ( } - anchorClassName="lnsLayerPanel__anchor" + anchorClassName="eui-displayBlock" > @@ -296,12 +296,8 @@ export const IndexPatternDimensionTriggerComponent = function IndexPatternDimens className="lnsLayerPanel__triggerLink" onClick={props.onClick} data-test-subj="lns-dimensionTrigger" - aria-label={i18n.translate('xpack.lens.configure.editConfig', { - defaultMessage: 'Edit configuration', - })} - title={i18n.translate('xpack.lens.configure.editConfig', { - defaultMessage: 'Edit configuration', - })} + aria-label={triggerLinkA11yText} + title={triggerLinkA11yText} > {uniqueLabel} diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.scss b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.scss index d74c332dd42e5..1b55d9623e223 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.scss +++ b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.scss @@ -1,25 +1,25 @@ -.lnsFieldItem--missing { - .lnsFieldItem__info { - background: lightOrDarkTheme(transparentize($euiColorMediumShade, .9), $euiColorEmptyShade); - color: $euiColorDarkShade; - } -} - -.lnsFieldItem__info { +.lnsFieldItem { .lnsFieldItem__infoIcon { visibility: hidden; + opacity: 0; } - &:hover, - &:focus { + &:hover:not([class*='isActive']) { cursor: grab; .lnsFieldItem__infoIcon { visibility: visible; + opacity: 1; + transition: opacity $euiAnimSpeedFast ease-in-out 1s; } } } +.lnsFieldItem--missing { + background: lightOrDarkTheme(transparentize($euiColorMediumShade, .9), $euiColorEmptyShade); + color: $euiColorDarkShade; +} + .lnsFieldItem__topValue { margin-bottom: $euiSizeS; diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx index 7377d15bca6d7..2fbe23f9085f2 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/field_item.tsx @@ -33,6 +33,7 @@ import { } from '@elastic/charts'; import { i18n } from '@kbn/i18n'; import { DataPublicPluginStart } from 'src/plugins/data/public'; +import { EuiHighlight } from '@elastic/eui'; import { Query, KBN_FIELD_TYPES, @@ -102,22 +103,6 @@ export const InnerFieldItem = function InnerFieldItem(props: FieldItemProps) { isLoading: false, }); - const wrappableName = wrapOnDot(field.displayName)!; - const wrappableHighlight = wrapOnDot(highlight); - const highlightIndex = wrappableHighlight - ? wrappableName.toLowerCase().indexOf(wrappableHighlight.toLowerCase()) - : -1; - const wrappableHighlightableFieldName = - highlightIndex < 0 ? ( - wrappableName - ) : ( - - {wrappableName.substr(0, highlightIndex)} - {wrappableName.substr(highlightIndex, wrappableHighlight.length)} - {wrappableName.substr(highlightIndex + wrappableHighlight.length)} - - ); - function fetchData() { if (state.isLoading) { return; @@ -200,22 +185,20 @@ export const InnerFieldItem = function InnerFieldItem(props: FieldItemProps) { ownFocus className="lnsFieldItem__popoverAnchor" display="block" + data-test-subj="lnsFieldListPanelField" container={document.querySelector('.application') || undefined} button={ + {wrapOnDot(field.displayName)} + + } fieldInfoIcon={lensInfoIcon} /> @@ -527,7 +514,7 @@ function FieldItemPopoverContents(props: State & FieldItemProps) {
- + {Math.round((otherCount / props.sampledValues!) * 100)}% diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/shared_components/buckets.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/shared_components/buckets.tsx index 47380f7865578..50471ca84c0d8 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/shared_components/buckets.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/operations/definitions/shared_components/buckets.tsx @@ -96,7 +96,13 @@ export const DraggableBucketContainer = ({ children: React.ReactNode; } & BucketContainerProps) => { return ( - + {(provided) => {children}} ); @@ -134,7 +140,7 @@ export const DragDropBuckets = ({ }; return ( - + {children} diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index ba9d8e364bd17..34c339023171e 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -9464,7 +9464,6 @@ "xpack.lens.configPanel.color.tooltip.custom": "[自動]モードに戻すには、カスタム色をオフにしてください。", "xpack.lens.configPanel.color.tooltip.disabled": "レイヤーに「内訳条件」が含まれている場合は、個別の系列をカスタム色にできません。", "xpack.lens.configPanel.selectVisualization": "ビジュアライゼーションを選択してください", - "xpack.lens.configure.addConfig": "構成を追加", "xpack.lens.configure.editConfig": "構成の編集", "xpack.lens.configure.emptyConfig": "ここにフィールドをドロップ", "xpack.lens.dataPanelWrapper.switchDatasource": "データソースに切り替える", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 5d44e0c635bee..f32b49fd4f2f0 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -9470,7 +9470,6 @@ "xpack.lens.configPanel.color.tooltip.custom": "清除定制颜色以返回到“自动”模式。", "xpack.lens.configPanel.color.tooltip.disabled": "当图层包括“细分依据”,各个系列无法定制颜色。", "xpack.lens.configPanel.selectVisualization": "选择可视化", - "xpack.lens.configure.addConfig": "添加配置", "xpack.lens.configure.editConfig": "编辑配置", "xpack.lens.configure.emptyConfig": "将字段拖放到此处", "xpack.lens.dataPanelWrapper.switchDatasource": "切换到数据源", From 198c5d998816e940e4c8d92979504c86116bcd2d Mon Sep 17 00:00:00 2001 From: Marco Liberati Date: Thu, 1 Oct 2020 18:02:37 +0200 Subject: [PATCH 05/25] [Lens] Fix embeddable title and description for reporting and dashboard tooltip (#78767) Co-authored-by: Elastic Machine --- .../lib/panel/panel_header/panel_header.tsx | 9 ++- .../public/embeddable/visualize_embeddable.ts | 2 +- .../__snapshots__/expression.test.tsx.snap | 4 +- .../datatable_visualization/expression.tsx | 10 ++- .../datatable_visualization/visualization.tsx | 4 +- .../editor_frame/expression_helpers.ts | 9 ++- .../editor_frame/state_helpers.ts | 4 ++ .../embeddable/embeddable.tsx | 6 ++ .../metric_visualization/expression.test.tsx | 69 +++++++++++++++++-- .../metric_visualization/expression.tsx | 24 +++++-- .../lens/public/metric_visualization/types.ts | 2 + .../visualization.test.ts | 8 ++- .../metric_visualization/visualization.tsx | 10 +-- .../public/pie_visualization/expression.tsx | 8 +++ .../pie_visualization/render_function.tsx | 7 +- .../public/pie_visualization/to_expression.ts | 13 ++-- .../lens/public/pie_visualization/types.ts | 2 + x-pack/plugins/lens/public/types.ts | 3 +- .../public/visualization_container.test.tsx | 7 +- .../lens/public/visualization_container.tsx | 11 ++- .../__snapshots__/to_expression.test.ts.snap | 6 ++ .../public/xy_visualization/expression.tsx | 15 +++- .../public/xy_visualization/to_expression.ts | 10 ++- .../lens/public/xy_visualization/types.ts | 2 + 24 files changed, 206 insertions(+), 39 deletions(-) diff --git a/src/plugins/embeddable/public/lib/panel/panel_header/panel_header.tsx b/src/plugins/embeddable/public/lib/panel/panel_header/panel_header.tsx index 7dde84e510535..dea483efb349f 100644 --- a/src/plugins/embeddable/public/lib/panel/panel_header/panel_header.tsx +++ b/src/plugins/embeddable/public/lib/panel/panel_header/panel_header.tsx @@ -109,12 +109,11 @@ function renderTooltip(description: string) { ); } -const VISUALIZE_EMBEDDABLE_TYPE = 'visualization'; -type VisualizeEmbeddable = any; +type EmbeddableWithDescription = IEmbeddable & { getDescription: () => string }; -function getViewDescription(embeddable: IEmbeddable | VisualizeEmbeddable) { - if (embeddable.type === VISUALIZE_EMBEDDABLE_TYPE) { - const description = embeddable.getVisualizationDescription(); +function getViewDescription(embeddable: IEmbeddable | EmbeddableWithDescription) { + if ('getDescription' in embeddable) { + const description = embeddable.getDescription(); if (description) { return description; diff --git a/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts b/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts index c091d396b4924..fe8a9adff4052 100644 --- a/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts +++ b/src/plugins/visualizations/public/embeddable/visualize_embeddable.ts @@ -167,7 +167,7 @@ export class VisualizeEmbeddable typeof inspectorAdapters === 'function' ? inspectorAdapters() : inspectorAdapters; } } - public getVisualizationDescription() { + public getDescription() { return this.vis.description; } diff --git a/x-pack/plugins/lens/public/datatable_visualization/__snapshots__/expression.test.tsx.snap b/x-pack/plugins/lens/public/datatable_visualization/__snapshots__/expression.test.tsx.snap index c0210c3915ce8..9c7bdc3397f9c 100644 --- a/x-pack/plugins/lens/public/datatable_visualization/__snapshots__/expression.test.tsx.snap +++ b/x-pack/plugins/lens/public/datatable_visualization/__snapshots__/expression.test.tsx.snap @@ -1,7 +1,9 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`datatable_expression DatatableComponent it renders the title and value 1`] = ` - + + }; }, - toExpression(state, datasourceLayers): Ast { + toExpression(state, datasourceLayers, { title, description } = {}): Ast { const layer = state.layers[0]; const datasource = datasourceLayers[layer.layerId]; const originalOrder = datasource.getTableSpec().map(({ columnId }) => columnId); @@ -211,6 +211,8 @@ export const datatableVisualization: Visualization type: 'function', function: 'lens_datatable', arguments: { + title: [title || ''], + description: [description || ''], columns: [ { type: 'expression', diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts index 952718e13c8cf..e7568147dc568 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/expression_helpers.ts @@ -73,7 +73,11 @@ export function buildExpression({ datasourceMap, datasourceStates, datasourceLayers, + title, + description, }: { + title?: string; + description?: string; visualization: Visualization | null; visualizationState: unknown; datasourceMap: Record; @@ -89,7 +93,10 @@ export function buildExpression({ if (visualization === null) { return null; } - const visualizationExpression = visualization.toExpression(visualizationState, datasourceLayers); + const visualizationExpression = visualization.toExpression(visualizationState, datasourceLayers, { + title, + description, + }); const completeExpression = prependDatasourceExpression( visualizationExpression, diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/state_helpers.ts b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/state_helpers.ts index 6deb9ffd37a06..1fe5224d0b1b4 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/state_helpers.ts +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/state_helpers.ts @@ -61,6 +61,8 @@ export async function persistedStateToExpression( state: { visualization: visualizationState, datasourceStates: persistedDatasourceStates }, visualizationType, references, + title, + description, } = doc; if (!visualizationType) return null; const visualization = visualizations[visualizationType!]; @@ -78,6 +80,8 @@ export async function persistedStateToExpression( const datasourceLayers = createDatasourceLayers(datasources, datasourceStates); return buildExpression({ + title, + description, visualization, visualizationState, datasourceMap: datasources, diff --git a/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.tsx b/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.tsx index 61a5d8cacdc4f..16b19ca0af849 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/embeddable/embeddable.tsx @@ -295,6 +295,12 @@ export class Embeddable return this.deps.attributeService.getInputAsValueType(input); }; + // same API as Visualize + public getDescription() { + // mind that savedViz is loaded in async way here + return this.savedVis && this.savedVis.description; + } + destroy() { super.destroy(); if (this.domNode) { diff --git a/x-pack/plugins/lens/public/metric_visualization/expression.test.tsx b/x-pack/plugins/lens/public/metric_visualization/expression.test.tsx index 0c92cdb2c31fc..77a8ce64b21a2 100644 --- a/x-pack/plugins/lens/public/metric_visualization/expression.test.tsx +++ b/x-pack/plugins/lens/public/metric_visualization/expression.test.tsx @@ -32,10 +32,21 @@ function sampleArgs() { accessor: 'a', layerId: 'l1', title: 'My fanci metric chart', + description: 'Fancy chart description', + metricTitle: 'My fanci metric chart', mode: 'full', }; - return { data, args }; + const noAttributesArgs: MetricConfig = { + accessor: 'a', + layerId: 'l1', + title: '', + description: '', + metricTitle: 'My fanci metric chart', + mode: 'full', + }; + + return { data, args, noAttributesArgs }; } describe('metric_expression', () => { @@ -53,7 +64,7 @@ describe('metric_expression', () => { }); describe('MetricChart component', () => { - test('it renders the title and value', () => { + test('it renders the all attributes when passed (title, description, metricTitle, value)', () => { const { data, args } = sampleArgs(); expect( @@ -61,6 +72,7 @@ describe('metric_expression', () => { ).toMatchInlineSnapshot(` @@ -90,21 +102,66 @@ describe('metric_expression', () => { `); }); - test('it does not render title in reduced mode', () => { - const { data, args } = sampleArgs(); + test('it renders only chart content when title and description are empty strings', () => { + const { data, noAttributesArgs } = sampleArgs(); expect( shallow( x as IFieldFormat} /> ) ).toMatchInlineSnapshot(` + +
+ 10110 +
+
+ My fanci metric chart +
+
+
+ `); + }); + + test('it does not render metricTitle in reduced mode', () => { + const { data, noAttributesArgs } = sampleArgs(); + + expect( + shallow( + x as IFieldFormat} + /> + ) + ).toMatchInlineSnapshot(` +
+ ); } @@ -119,14 +131,18 @@ export function MetricChart({ } return ( - +
{value}
{mode === 'full' && (
- {title} + {metricTitle}
)}
diff --git a/x-pack/plugins/lens/public/metric_visualization/types.ts b/x-pack/plugins/lens/public/metric_visualization/types.ts index 86a781716b345..c4a3fd094abe6 100644 --- a/x-pack/plugins/lens/public/metric_visualization/types.ts +++ b/x-pack/plugins/lens/public/metric_visualization/types.ts @@ -11,5 +11,7 @@ export interface State { export interface MetricConfig extends State { title: string; + description: string; + metricTitle: string; mode: 'reduced' | 'full'; } diff --git a/x-pack/plugins/lens/public/metric_visualization/visualization.test.ts b/x-pack/plugins/lens/public/metric_visualization/visualization.test.ts index aa3de93013e66..80c7a174b3264 100644 --- a/x-pack/plugins/lens/public/metric_visualization/visualization.test.ts +++ b/x-pack/plugins/lens/public/metric_visualization/visualization.test.ts @@ -171,11 +171,17 @@ describe('metric_visualization', () => { "accessor": Array [ "a", ], + "description": Array [ + "", + ], + "metricTitle": Array [ + "shazm", + ], "mode": Array [ "full", ], "title": Array [ - "shazm", + "", ], }, "function": "lens_metric_chart", diff --git a/x-pack/plugins/lens/public/metric_visualization/visualization.tsx b/x-pack/plugins/lens/public/metric_visualization/visualization.tsx index 72c07bed1acb2..77d189ce53d01 100644 --- a/x-pack/plugins/lens/public/metric_visualization/visualization.tsx +++ b/x-pack/plugins/lens/public/metric_visualization/visualization.tsx @@ -14,7 +14,7 @@ import { State } from './types'; const toExpression = ( state: State, datasourceLayers: Record, - mode: 'reduced' | 'full' = 'full' + attributes?: { mode?: 'reduced' | 'full'; title?: string; description?: string } ): Ast | null => { if (!state.accessor) { return null; @@ -30,9 +30,11 @@ const toExpression = ( type: 'function', function: 'lens_metric_chart', arguments: { - title: [(operation && operation.label) || ''], + title: [attributes?.title || ''], + description: [attributes?.description || ''], + metricTitle: [(operation && operation.label) || ''], accessor: [state.accessor], - mode: [mode], + mode: [attributes?.mode || 'full'], }, }, ], @@ -104,7 +106,7 @@ export const metricVisualization: Visualization = { toExpression, toPreviewExpression: (state, datasourceLayers) => - toExpression(state, datasourceLayers, 'reduced'), + toExpression(state, datasourceLayers, { mode: 'reduced' }), setDimension({ prevState, columnId }) { return { ...prevState, accessor: columnId }; diff --git a/x-pack/plugins/lens/public/pie_visualization/expression.tsx b/x-pack/plugins/lens/public/pie_visualization/expression.tsx index 89d93ab79233f..d93145f29aa89 100644 --- a/x-pack/plugins/lens/public/pie_visualization/expression.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/expression.tsx @@ -37,6 +37,14 @@ export const pie: ExpressionFunctionDefinition< defaultMessage: 'Pie renderer', }), args: { + title: { + types: ['string'], + help: 'The chart title.', + }, + description: { + types: ['string'], + help: '', + }, groups: { types: ['string'], multi: true, diff --git a/x-pack/plugins/lens/public/pie_visualization/render_function.tsx b/x-pack/plugins/lens/public/pie_visualization/render_function.tsx index d97ab146e000d..8de810f9aa5d3 100644 --- a/x-pack/plugins/lens/public/pie_visualization/render_function.tsx +++ b/x-pack/plugins/lens/public/pie_visualization/render_function.tsx @@ -228,7 +228,12 @@ export function PieComponent( ); } return ( - +