import { css } from '@emotion/css'; import { noop } from 'lodash'; import pluralize from 'pluralize'; import React, { FC, useCallback, useEffect, useMemo, useState } from 'react'; import { GrafanaTheme2, PanelProps } from '@grafana/data'; import { Icon, useStyles2 } from '@grafana/ui'; import { AlertInstancesTable } from 'app/features/alerting/unified/components/rules/AlertInstancesTable'; import { sortAlerts } from 'app/features/alerting/unified/utils/misc'; import { Alert } from 'app/types/unified-alerting'; import { GroupMode, UnifiedAlertListOptions } from './types'; import { filterAlerts } from './util'; interface Props { alerts: Alert[]; options: PanelProps['options']; } export const AlertInstances: FC = ({ alerts, options }) => { // when custom grouping is enabled, we will always uncollapse the list of alert instances const defaultShowInstances = options.groupMode === GroupMode.Custom ? true : options.showInstances; const [displayInstances, setDisplayInstances] = useState(defaultShowInstances); const styles = useStyles2(getStyles); const toggleDisplayInstances = useCallback(() => { setDisplayInstances((display) => !display); }, []); const filteredAlerts = useMemo( (): Alert[] => filterAlerts(options, sortAlerts(options.sortOrder, alerts)) ?? [], [alerts, options] ); const hiddenInstances = alerts.length - filteredAlerts.length; const uncollapsible = filteredAlerts.length > 0; const toggleShowInstances = uncollapsible ? toggleDisplayInstances : noop; useEffect(() => { if (filteredAlerts.length === 0) { setDisplayInstances(false); } }, [filteredAlerts]); return (
{options.groupMode === GroupMode.Default && (
toggleShowInstances()}> {uncollapsible && } {`${filteredAlerts.length} ${pluralize('instance', filteredAlerts.length)}`} {hiddenInstances > 0 && , {`${hiddenInstances} hidden by filters`}}
)} {displayInstances && }
); }; const getStyles = (_: GrafanaTheme2) => ({ clickable: css` cursor: pointer; `, });