Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ML] Single Metric Viewer embeddable in dashboards: moves all config to flyout #182756

Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ const getDefaultFieldConfig = (
interface SeriesControlsProps {
appStateHandler: Function;
bounds: any;
direction?: 'column' | 'row';
functionDescription?: string;
job?: CombinedJob | MlJob;
selectedDetectorIndex: number;
Expand All @@ -89,6 +90,7 @@ export const SeriesControls: FC<PropsWithChildren<SeriesControlsProps>> = ({
appStateHandler,
bounds,
children,
direction = 'row',
functionDescription,
job,
selectedDetectorIndex,
Expand Down Expand Up @@ -297,7 +299,7 @@ export const SeriesControls: FC<PropsWithChildren<SeriesControlsProps>> = ({

return (
<div data-test-subj="mlSingleMetricViewerSeriesControls">
<EuiFlexGroup>
<EuiFlexGroup direction={direction}>
<EuiFlexItem grow={false}>
<EuiFormRow
label={
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,32 @@ export const getSingleMetricViewerEmbeddableFactory = (

const api = buildApi(
{
isEditingEnabled: () => true,
getTypeDisplayName: () =>
i18n.translate('xpack.ml.singleMetricViewerEmbeddable.typeDisplayName', {
defaultMessage: 'Single metric viewer',
darnautov marked this conversation as resolved.
Show resolved Hide resolved
}),
onEdit: async () => {
peteharverson marked this conversation as resolved.
Show resolved Hide resolved
try {
const { resolveEmbeddableSingleMetricViewerUserInput } = await import(
'./single_metric_viewer_setup_flyout'
);
const [coreStart, { data, share }, { mlApiServices }] = services;
const result = await resolveEmbeddableSingleMetricViewerUserInput(
coreStart,
{ data, share },
mlApiServices,
{
...serializeTitles(),
...serializeSingleMetricViewerState(),
}
);

singleMetricViewerControlsApi.updateUserInput(result);
} catch (e) {
return Promise.reject();
}
},
...titlesApi,
...timeRangeApi,
...singleMetricViewerControlsApi,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,64 +6,118 @@
*/

import type { FC } from 'react';
import React, { useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import {
EuiButton,
EuiButtonEmpty,
EuiFlexGroup,
EuiFlexItem,
EuiForm,
EuiFormRow,
EuiModalBody,
EuiModalFooter,
EuiModalHeader,
EuiModalHeaderTitle,
EuiFlyoutBody,
EuiFlyoutFooter,
EuiFlyoutHeader,
EuiTitle,
EuiFieldText,
EuiModal,
EuiSpacer,
} from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n-react';
import useMountedState from 'react-use/lib/useMountedState';
import { extractErrorMessage } from '@kbn/ml-error-utils';
import type { MlJob } from '@elastic/elasticsearch/lib/api/types';
import type { TimeRangeBounds } from '@kbn/ml-time-buckets';
import type { MlApiServices } from '../../application/services/ml_api_service';
import type { SingleMetricViewerEmbeddableInput } from '..';
import { ML_PAGES } from '../../../common/constants/locator';
import { SeriesControls } from '../../application/timeseriesexplorer/components/series_controls';
import {
APP_STATE_ACTION,
type TimeseriesexplorerActionType,
} from '../../application/timeseriesexplorer/timeseriesexplorer_constants';
import { useMlLink } from '../../application/contexts/kibana';
import { JobSelectorControl } from '../../alerting/job_selector';
import type { SingleMetricViewerEmbeddableUserInput, MlEntity } from '..';
import { getDefaultSingleMetricViewerPanelTitle } from './get_default_panel_title';

export interface SingleMetricViewerInitializerProps {
bounds: TimeRangeBounds;
defaultTitle: string;
initialInput?: Partial<SingleMetricViewerEmbeddableInput>;
job: MlJob;
onCreate: (props: Partial<SingleMetricViewerEmbeddableUserInput>) => void;
mlApiServices: MlApiServices;
onCreate: (props: SingleMetricViewerEmbeddableUserInput) => void;
onCancel: () => void;
}

export const SingleMetricViewerInitializer: FC<SingleMetricViewerInitializerProps> = ({
defaultTitle,
bounds,
initialInput,
job,
onCreate,
onCancel,
mlApiServices,
}) => {
const isNewJob = initialInput?.jobIds !== undefined && initialInput?.jobIds[0] !== job.job_id;
const isMounted = useMountedState();
const newJobUrl = useMlLink({ page: ML_PAGES.ANOMALY_DETECTION_CREATE_JOB });
const [jobIds, setJobIds] = useState(initialInput?.jobIds ?? []);

const [panelTitle, setPanelTitle] = useState<string>(defaultTitle);
const initialValuesRef = useRef({
titleManuallyChanged: !!initialInput?.title,
isNewJob:
initialInput?.jobIds !== undefined && jobIds.length && initialInput?.jobIds[0] !== jobIds[0],
});

const [job, setJob] = useState<MlJob | undefined>();
const [panelTitle, setPanelTitle] = useState<string>(initialInput?.title ?? '');
const [functionDescription, setFunctionDescription] = useState<string | undefined>(
initialInput?.functionDescription
);
// Reset detector index and entities if the job has changed
const [selectedDetectorIndex, setSelectedDetectorIndex] = useState<number>(
!isNewJob && initialInput?.selectedDetectorIndex ? initialInput.selectedDetectorIndex : 0
!initialValuesRef.current.isNewJob && initialInput?.selectedDetectorIndex
? initialInput.selectedDetectorIndex
: 0
);
const [selectedEntities, setSelectedEntities] = useState<MlEntity | undefined>(
!isNewJob && initialInput?.selectedEntities ? initialInput.selectedEntities : undefined
!initialValuesRef.current.isNewJob && initialInput?.selectedEntities
? initialInput.selectedEntities
: undefined
);

const [errorMessage, setErrorMessage] = useState<string | undefined>();
const isPanelTitleValid = panelTitle.length > 0;

useEffect(
function setUpPanel() {
if (isMounted()) {
darnautov marked this conversation as resolved.
Show resolved Hide resolved
async function fetchJob() {
const { jobs } = await mlApiServices.getJobs({ jobId: jobIds.join(',') });

if (jobs.length > 0) {
darnautov marked this conversation as resolved.
Show resolved Hide resolved
// Reset values if the job has changed
if (initialValuesRef.current.isNewJob) {
setSelectedDetectorIndex(0);
setSelectedEntities(undefined);
setFunctionDescription(undefined);
}

setJob(jobs[0]);
setErrorMessage(undefined);
}
}
darnautov marked this conversation as resolved.
Show resolved Hide resolved

if (jobIds.length === 1) {
if (!initialValuesRef.current.titleManuallyChanged) {
setPanelTitle(getDefaultSingleMetricViewerPanelTitle(jobIds[0]));
}
if (mlApiServices && jobIds.length === 1 && jobIds[0] !== job?.job_id) {
fetchJob().catch((error) => {
const errorMsg = extractErrorMessage(error);
setErrorMessage(errorMsg);
});
}
}
}
},
[isMounted, jobIds, mlApiServices, panelTitle, initialValuesRef.current.isNewJob, job?.job_id]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just realized, both here and in the anomaly swim lane initializer, we need to introduce a debounce on job IDs change.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤔 I'm not sure we do in this case since we only do the fetch if a new job has been selected (that hasn't already been loaded). Also - are people rapidly clicking around a ton on job ids? I think the dropdown closes after each selection (at least on single selection) so it would be difficult for a user to be changing job ids extremely quickly.

);

const handleStateUpdate = (
action: TimeseriesexplorerActionType,
payload: string | number | MlEntity
Expand All @@ -84,23 +138,31 @@ export const SingleMetricViewerInitializer: FC<SingleMetricViewerInitializerProp
};

return (
<EuiModal
maxWidth={false}
initialFocus="[name=panelTitle]"
onClose={onCancel}
data-test-subj={'mlSingleMetricViewerEmbeddableInitializer'}
>
<EuiModalHeader>
<EuiModalHeaderTitle>
<FormattedMessage
id="xpack.ml.SingleMetricViewerEmbeddable.setupModal.title"
defaultMessage="Single metric viewer configuration"
/>
</EuiModalHeaderTitle>
</EuiModalHeader>
<>
<EuiFlyoutHeader>
<EuiTitle>
<h2>
<FormattedMessage
id="xpack.ml.SingleMetricViewerEmbeddable.setupModal.title"
defaultMessage="Single metric viewer configuration"
/>
</h2>
</EuiTitle>
</EuiFlyoutHeader>

<EuiModalBody>
<EuiFlyoutBody>
<EuiForm>
<JobSelectorControl
adJobsApiService={mlApiServices.jobs}
createJobUrl={newJobUrl}
jobsAndGroupIds={jobIds}
onChange={(update) => {
initialValuesRef.current.isNewJob =
update?.jobIds !== undefined && update.jobIds[0] !== jobIds[0];
setJobIds([...(update?.jobIds ?? []), ...(update?.groupIds ?? [])]);
}}
{...(errorMessage && { errors: [errorMessage] })}
/>
<EuiFormRow
label={
<FormattedMessage
Expand All @@ -109,58 +171,70 @@ export const SingleMetricViewerInitializer: FC<SingleMetricViewerInitializerProp
/>
}
isInvalid={!isPanelTitleValid}
fullWidth
>
<EuiFieldText
data-test-subj="panelTitleInput"
id="panelTitle"
name="panelTitle"
value={panelTitle}
onChange={(e) => setPanelTitle(e.target.value)}
onChange={(e) => {
initialValuesRef.current.titleManuallyChanged = true;
setPanelTitle(e.target.value);
}}
isInvalid={!isPanelTitleValid}
fullWidth
/>
</EuiFormRow>
<EuiSpacer />
<SeriesControls
selectedJobId={job.job_id}
job={job}
appStateHandler={handleStateUpdate}
selectedDetectorIndex={selectedDetectorIndex}
selectedEntities={selectedEntities}
bounds={bounds}
functionDescription={functionDescription}
setFunctionDescription={setFunctionDescription}
/>
{job && job.job_id && jobIds.length && jobIds[0] === job.job_id ? (
<SeriesControls
selectedJobId={jobIds[0]}
job={job}
direction="column"
appStateHandler={handleStateUpdate}
selectedDetectorIndex={selectedDetectorIndex}
selectedEntities={selectedEntities}
bounds={bounds}
functionDescription={functionDescription}
setFunctionDescription={setFunctionDescription}
/>
) : null}
</EuiForm>
</EuiModalBody>

<EuiModalFooter>
<EuiButtonEmpty
onClick={onCancel}
data-test-subj="mlsingleMetricViewerInitializerCancelButton"
>
<FormattedMessage
id="xpack.ml.singleMetricViewerEmbeddable.setupModal.cancelButtonLabel"
defaultMessage="Cancel"
/>
</EuiButtonEmpty>

<EuiButton
data-test-subj="mlSingleMetricViewerInitializerConfirmButton"
isDisabled={!isPanelTitleValid}
onClick={onCreate.bind(null, {
functionDescription,
panelTitle,
selectedDetectorIndex,
selectedEntities,
})}
fill
>
<FormattedMessage
id="xpack.ml.singleMetricViewerEmbeddable.setupModal.confirmButtonLabel"
defaultMessage="Confirm configurations"
/>
</EuiButton>
</EuiModalFooter>
</EuiModal>
</EuiFlyoutBody>
<EuiFlyoutFooter>
<EuiFlexGroup justifyContent={'spaceBetween'}>
<EuiFlexItem grow={false}>
<EuiButtonEmpty
onClick={onCancel}
data-test-subj="mlsingleMetricViewerInitializerCancelButton"
>
<FormattedMessage
id="xpack.ml.singleMetricViewerEmbeddable.CancelButtonLabel"
peteharverson marked this conversation as resolved.
Show resolved Hide resolved
defaultMessage="Cancel"
/>
</EuiButtonEmpty>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiButton
isDisabled={!isPanelTitleValid || errorMessage !== undefined || !jobIds.length}
onClick={onCreate.bind(null, {
jobIds,
functionDescription,
panelTitle,
selectedDetectorIndex,
selectedEntities,
})}
fill
>
<FormattedMessage
id="xpack.ml.singleMetricViewerEmbeddable.setupModal.confirmButtonLabel"
defaultMessage="Confirm"
/>
</EuiButton>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlyoutFooter>
</>
);
};
Loading