Files
superset2/superset-frontend/src/explore/components/controls/MetricControl/MetricsControl.tsx
2026-05-08 10:42:07 -07:00

357 lines
10 KiB
TypeScript

/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { ensureIsArray, usePrevious } from '@superset-ui/core';
import { t } from '@apache-superset/core/translation';
import { isEqual } from 'lodash';
import ControlHeader from 'src/explore/components/ControlHeader';
import { Icons } from '@superset-ui/core/components/Icons';
import {
AddIconButton,
AddControlLabel,
HeaderContainer,
LabelsContainer,
} from 'src/explore/components/controls/OptionControls';
import MetricDefinitionValue from './MetricDefinitionValue';
import AdhocMetric from './AdhocMetric';
import AdhocMetricPopoverTrigger from './AdhocMetricPopoverTrigger';
const defaultProps = {
onChange: () => {},
clearable: true,
savedMetrics: [],
columns: [],
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getOptionsForSavedMetrics(
savedMetrics: any,
currentMetricValues: any,
currentMetric: any,
) {
return (
savedMetrics?.filter((savedMetric: { metric_name: string }) =>
Array.isArray(currentMetricValues)
? !currentMetricValues.includes(savedMetric.metric_name) ||
savedMetric.metric_name === currentMetric
: savedMetric,
) ?? []
);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isDictionaryForAdhocMetric(value: any) {
return value && !(value instanceof AdhocMetric) && value.expressionType;
}
// adhoc metrics are stored as dictionaries in URL params. We convert them back into the
// AdhocMetric class for typechecking, consistency and instance method access.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function coerceAdhocMetrics(value: any) {
if (!value) {
return [];
}
if (!Array.isArray(value)) {
if (isDictionaryForAdhocMetric(value)) {
return [new AdhocMetric(value)];
}
return [value];
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return value.map((val: any) => {
if (isDictionaryForAdhocMetric(val)) {
return new AdhocMetric(val);
}
return val;
});
}
const emptySavedMetric = { metric_name: '', expression: '' };
// TODO: use typeguards to distinguish saved metrics from adhoc metrics
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getMetricsMatchingCurrentDataset = (
value: any,
columns: any,
savedMetrics: any,
) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ensureIsArray(value).filter((metric: any) => {
if (typeof metric === 'string' || metric.metric_name) {
return savedMetrics?.some(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(savedMetric: any) =>
savedMetric.metric_name === metric ||
savedMetric.metric_name === metric.metric_name,
);
}
return columns?.some(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(column: any) =>
!metric.column || metric.column.column_name === column.column_name,
);
});
export interface MetricsControlProps {
name: string;
onChange: (value: unknown) => void;
multi?: boolean;
value?: unknown;
columns?: unknown[];
savedMetrics?: unknown[];
datasource?: unknown;
clearable?: boolean;
isLoading?: boolean;
[key: string]: unknown;
}
const MetricsControl = ({
onChange,
multi,
value: propsValue,
columns,
savedMetrics,
datasource,
...props
}: MetricsControlProps) => {
const [value, setValue] = useState(coerceAdhocMetrics(propsValue));
const prevColumns = usePrevious(columns);
const prevSavedMetrics = usePrevious(savedMetrics);
const handleChange = useCallback(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(opts: any) => {
// if clear out options
if (opts === null) {
onChange(null);
return;
}
const transformedOpts = ensureIsArray(opts);
const optionValues = transformedOpts
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.map((option: any) => {
// pre-defined metric
if (option.metric_name) {
return option.metric_name;
}
return option;
})
.filter((option: unknown) => option);
onChange(multi ? optionValues : optionValues[0]);
},
[multi, onChange],
);
const onNewMetric = useCallback(
(newMetric: unknown) => {
const newValue = [...value, newMetric];
setValue(newValue);
handleChange(newValue);
},
[handleChange, value],
);
const onMetricEdit = useCallback(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(changedMetric: any, oldMetric: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const newValue = value.map((val: any) => {
if (
// compare saved metrics
val === oldMetric.metric_name ||
// compare adhoc metrics
typeof val.optionName !== 'undefined'
? val.optionName === oldMetric.optionName
: false
) {
return changedMetric;
}
return val;
});
setValue(newValue);
handleChange(newValue);
},
[handleChange, value],
);
const onRemoveMetric = useCallback(
(index: number) => {
if (!Array.isArray(value)) {
return;
}
const valuesCopy = [...value];
valuesCopy.splice(index, 1);
setValue(valuesCopy);
handleChange(valuesCopy);
},
[handleChange, value],
);
const moveLabel = useCallback(
(dragIndex: number, hoverIndex: number) => {
const newValues = [...value];
[newValues[hoverIndex], newValues[dragIndex]] = [
newValues[dragIndex],
newValues[hoverIndex],
];
setValue(newValues);
},
[value],
);
const isAddNewMetricDisabled = useCallback(
() => !multi && value.length > 0,
[multi, value.length],
);
const savedMetricOptions = useMemo(
() => getOptionsForSavedMetrics(savedMetrics, propsValue, null),
[propsValue, savedMetrics],
);
const newAdhocMetric = useMemo(() => new AdhocMetric({}), [value]);
const addNewMetricPopoverTrigger = useCallback(
(trigger: React.ReactNode) => {
if (isAddNewMetricDisabled()) {
return trigger;
}
return (
<AdhocMetricPopoverTrigger
adhocMetric={newAdhocMetric}
onMetricEdit={onNewMetric}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
columns={columns as any}
savedMetricsOptions={savedMetricOptions}
savedMetric={emptySavedMetric}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
datasource={datasource as any}
isNew
>
{trigger}
</AdhocMetricPopoverTrigger>
);
},
[
columns,
datasource,
isAddNewMetricDisabled,
newAdhocMetric,
onNewMetric,
savedMetricOptions,
],
);
useEffect(() => {
// Remove selected custom metrics that do not exist in the dataset anymore
// Remove selected adhoc metrics that use columns which do not exist in the dataset anymore
if (
propsValue &&
(!isEqual(prevColumns, columns) ||
!isEqual(prevSavedMetrics, savedMetrics))
) {
const matchingMetrics = getMetricsMatchingCurrentDataset(
propsValue,
columns,
savedMetrics,
);
if (!isEqual(matchingMetrics, propsValue)) {
handleChange(matchingMetrics);
}
}
}, [columns, handleChange, savedMetrics]);
useEffect(() => {
setValue(coerceAdhocMetrics(propsValue));
}, [propsValue]);
const onDropLabel = useCallback(
() => handleChange(value),
[handleChange, value],
);
const valueRenderer = useCallback(
(option: unknown, index: number) => (
<MetricDefinitionValue
key={index}
index={index}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
option={option as any}
onMetricEdit={onMetricEdit}
onRemoveMetric={onRemoveMetric}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
columns={columns as any}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
datasource={datasource as any}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
savedMetrics={savedMetrics as any}
savedMetricsOptions={getOptionsForSavedMetrics(
savedMetrics,
value,
value?.[index],
)}
onMoveLabel={moveLabel}
onDropLabel={onDropLabel}
multi={multi}
/>
),
[
columns,
datasource,
moveLabel,
multi,
onDropLabel,
onMetricEdit,
onRemoveMetric,
savedMetrics,
value,
],
);
return (
<div className="metrics-select">
<HeaderContainer>
<ControlHeader {...props} />
{addNewMetricPopoverTrigger(
<AddIconButton
disabled={isAddNewMetricDisabled()}
data-test="add-metric-button"
>
<Icons.PlusOutlined iconSize="m" />
</AddIconButton>,
)}
</HeaderContainer>
<LabelsContainer>
{value.length > 0
? value.map((value, index) => valueRenderer(value, index))
: addNewMetricPopoverTrigger(
<AddControlLabel>
<Icons.PlusOutlined iconSize="m" />
{t('Add metric')}
</AddControlLabel>,
)}
</LabelsContainer>
</div>
);
};
MetricsControl.defaultProps = defaultProps;
export default MetricsControl;