Compare commits

..

2 Commits

Author SHA1 Message Date
Ashley Harrison
e9f164d9f2 undo changes to query library cause i cba dealing with enterprise rn 2026-01-14 17:20:37 +00:00
Ashley Harrison
86fc051c58 ref changes compatible with react 18 + react 19 2026-01-14 17:08:28 +00:00
47 changed files with 76 additions and 449 deletions

View File

@@ -1392,6 +1392,11 @@
"count": 2
}
},
"public/app/features/alerting/unified/components/mute-timings/MuteTimingForm.tsx": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/alerting/unified/components/mute-timings/MuteTimingTimeInterval.tsx": {
"no-restricted-syntax": {
"count": 5
@@ -1516,6 +1521,11 @@
"count": 1
}
},
"public/app/features/alerting/unified/components/rule-editor/alert-rule-form/simplifiedRouting/route-settings/MuteTimingFields.tsx": {
"no-restricted-syntax": {
"count": 1
}
},
"public/app/features/alerting/unified/components/rule-editor/alert-rule-form/simplifiedRouting/route-settings/RouteSettings.tsx": {
"no-restricted-syntax": {
"count": 1

View File

@@ -22,7 +22,7 @@ import { getBarColorByDiff, getBarColorByPackage, getBarColorByValue } from './c
import { CollapseConfig, CollapsedMap, FlameGraphDataContainer, LevelItem } from './dataTransform';
type RenderOptions = {
canvasRef: RefObject<HTMLCanvasElement>;
canvasRef: RefObject<HTMLCanvasElement | null>;
data: FlameGraphDataContainer;
root: LevelItem;
direction: 'children' | 'parents';
@@ -373,7 +373,7 @@ function useColorFunction(
);
}
function useSetupCanvas(canvasRef: RefObject<HTMLCanvasElement>, wrapperWidth: number, numberOfLevels: number) {
function useSetupCanvas(canvasRef: RefObject<HTMLCanvasElement | null>, wrapperWidth: number, numberOfLevels: number) {
const [ctx, setCtx] = useState<CanvasRenderingContext2D>();
useEffect(() => {

View File

@@ -7,7 +7,7 @@ const CAUGHT_KEYS = ['ArrowUp', 'ArrowDown', 'Home', 'End', 'Enter', 'Tab'];
/** @internal */
export interface UseListFocusProps {
localRef: RefObject<HTMLUListElement>;
localRef: RefObject<HTMLUListElement | null>;
options: TimeOption[];
}

View File

@@ -1,7 +1,7 @@
import { RefObject, useRef } from 'react';
export function useFocus(): [RefObject<HTMLInputElement>, () => void] {
const ref = useRef<HTMLInputElement>(null);
export function useFocus(): [RefObject<HTMLInputElement | null>, () => void] {
const ref = useRef<HTMLInputElement | null>(null);
const setFocus = () => {
ref.current && ref.current.focus();
};

View File

@@ -6,7 +6,7 @@ const UNFOCUSED = -1;
/** @internal */
export interface UseMenuFocusProps {
localRef: RefObject<HTMLDivElement>;
localRef: RefObject<HTMLDivElement | null>;
isMenuOpen?: boolean;
close?: () => void;
onOpen?: (focusOnItem: (itemId: number) => void) => void;

View File

@@ -22,7 +22,7 @@ interface Props extends Omit<BoxProps, 'display' | 'direction' | 'element' | 'fl
*
* https://developers.grafana.com/ui/latest/index.html?path=/docs/layout-scrollcontainer--docs
*/
export const ScrollContainer = forwardRef<HTMLDivElement, PropsWithChildren<Props>>(
export const ScrollContainer = forwardRef<HTMLDivElement | null, PropsWithChildren<Props>>(
(
{
children,

View File

@@ -20,7 +20,7 @@ export interface TableCellTooltipProps {
field: Field;
getActions: (field: Field, rowIdx: number) => ActionModel[];
getTextColorForBackground: (bgColor: string) => string;
gridRef: RefObject<DataGridHandle>;
gridRef: RefObject<DataGridHandle | null>;
height: number;
placement?: TableCellTooltipPlacement;
renderer: TableCellRenderer;

View File

@@ -463,7 +463,7 @@ export function useColumnResize(
return dataGridResizeHandler;
}
export function useScrollbarWidth(ref: RefObject<DataGridHandle>, height: number) {
export function useScrollbarWidth(ref: RefObject<DataGridHandle | null>, height: number) {
const [scrollbarWidth, setScrollbarWidth] = useState(0);
useLayoutEffect(() => {

View File

@@ -135,7 +135,7 @@ export const Table = memo((props: Props) => {
// `useTableStateReducer`, which is needed to construct options for `useTable` (the hook that returns
// `toggleAllRowsExpanded`), and if we used a variable, that variable would be undefined at the time
// we initialize `useTableStateReducer`.
const toggleAllRowsExpandedRef = useRef<(value?: boolean) => void>();
const toggleAllRowsExpandedRef = useRef<((value?: boolean) => void) | null>(null);
// Internal react table state reducer
const stateReducer = useTableStateReducer({

View File

@@ -14,8 +14,8 @@ import { GrafanaTableState } from './types';
Select the scrollbar element from the VariableSizeList scope
*/
export function useFixScrollbarContainer(
variableSizeListScrollbarRef: React.RefObject<HTMLDivElement>,
tableDivRef: React.RefObject<HTMLDivElement>
variableSizeListScrollbarRef: React.RefObject<HTMLDivElement | null>,
tableDivRef: React.RefObject<HTMLDivElement | null>
) {
useEffect(() => {
if (variableSizeListScrollbarRef.current && tableDivRef.current) {
@@ -43,7 +43,7 @@ export function useFixScrollbarContainer(
*/
export function useResetVariableListSizeCache(
extendedState: GrafanaTableState,
listRef: React.RefObject<VariableSizeList>,
listRef: React.RefObject<VariableSizeList | null>,
data: DataFrame,
hasUniqueId: boolean
) {

View File

@@ -19,7 +19,7 @@ interface EventsCanvasProps {
}
export function EventsCanvas({ id, events, renderEventMarker, mapEventToXYCoords, config }: EventsCanvasProps) {
const plotInstance = useRef<uPlot>();
const plotInstance = useRef<uPlot | null>(null);
// render token required to re-render annotation markers. Rendering lines happens in uPlot and the props do not change
// so we need to force the re-render when the draw hook was performed by uPlot
const [renderToken, setRenderToken] = useState(0);

View File

@@ -140,7 +140,7 @@ export const TooltipPlugin2 = ({
const [{ plot, isHovering, isPinned, contents, style, dismiss }, setState] = useReducer(mergeState, null, initState);
const sizeRef = useRef<TooltipContainerSize>();
const sizeRef = useRef<TooltipContainerSize | null>(null);
const styles = useStyles2(getStyles, maxWidth);
const renderRef = useRef(render);

View File

@@ -96,7 +96,7 @@ export interface GraphNGState {
export class GraphNG extends Component<GraphNGProps, GraphNGState> {
static contextType = PanelContextRoot;
panelContext: PanelContext = {} as PanelContext;
private plotInstance: React.RefObject<uPlot>;
private plotInstance: React.RefObject<uPlot | null>;
private subscription = new Subscription();

View File

@@ -109,7 +109,7 @@ const defaultMatchers = {
* "Time as X" core component, expects ascending x
*/
export class GraphNG extends Component<GraphNGProps, GraphNGState> {
private plotInstance: React.RefObject<uPlot>;
private plotInstance: React.RefObject<uPlot | null>;
constructor(props: GraphNGProps) {
super(props);

View File

@@ -56,24 +56,6 @@ export const ImportedContactPointAlert = (props: ExtraAlertProps) => {
);
};
export const ImportedTimeIntervalAlert = (props: ExtraAlertProps) => {
return (
<Alert
title={t(
'alerting.provisioning.title-imported-time-interval',
'This time interval was imported and cannot be edited through the UI'
)}
severity="info"
{...props}
>
<Trans i18nKey="alerting.provisioning.body-imported-time-interval">
This time interval was imported from an external Alertmanager and is currently read-only. The time interval will
become editable after the migration process is complete.
</Trans>
</Alert>
);
};
export const ProvisioningBadge = ({
tooltip,
provenance,

View File

@@ -1,130 +0,0 @@
import { render, screen, userEvent } from 'test/test-utils';
import { setupMswServer } from 'app/features/alerting/unified/mockApi';
import { grantUserPermissions } from 'app/features/alerting/unified/mocks';
import { setTimeIntervalsList } from 'app/features/alerting/unified/mocks/server/configure';
import { AlertmanagerProvider } from 'app/features/alerting/unified/state/AlertmanagerContext';
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import { AccessControlAction } from 'app/types/accessControl';
import MuteTimingsSelector from './MuteTimingsSelector';
const renderWithProvider = (alertManagerSource = GRAFANA_RULES_SOURCE_NAME) => {
return render(
<AlertmanagerProvider accessType={'notification'} alertmanagerSourceName={alertManagerSource}>
<MuteTimingsSelector
alertmanager={alertManagerSource}
selectProps={{
onChange: () => {},
}}
/>
</AlertmanagerProvider>
);
};
setupMswServer();
describe('MuteTimingsSelector', () => {
beforeEach(() => {
grantUserPermissions([
AccessControlAction.AlertingNotificationsRead,
AccessControlAction.AlertingNotificationsWrite,
]);
});
it('should show all non-imported time intervals', async () => {
const user = userEvent.setup();
setTimeIntervalsList([
{ name: 'regular-interval', provenance: 'none' },
{ name: 'file-provisioned', provenance: 'file' },
{ name: 'another-regular', provenance: 'none' },
]);
renderWithProvider();
// Click to open the dropdown
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
await user.click(selector);
// All non-imported intervals should be visible
expect(await screen.findByText('regular-interval')).toBeInTheDocument();
expect(screen.getByText('file-provisioned')).toBeInTheDocument();
expect(screen.getByText('another-regular')).toBeInTheDocument();
});
it('should filter out imported time intervals (provenance: converted_prometheus)', async () => {
const user = userEvent.setup();
setTimeIntervalsList([
{ name: 'regular-interval', provenance: 'none' },
{ name: 'imported-interval', provenance: 'converted_prometheus' },
{ name: 'file-provisioned', provenance: 'file' },
]);
renderWithProvider();
// Click to open the dropdown
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
await user.click(selector);
// Regular and file-provisioned should be visible
expect(await screen.findByText('regular-interval')).toBeInTheDocument();
expect(screen.getByText('file-provisioned')).toBeInTheDocument();
// Imported interval should NOT be in the list
expect(screen.queryByText('imported-interval')).not.toBeInTheDocument();
});
it('should show only non-imported intervals when all types are present', async () => {
const user = userEvent.setup();
setTimeIntervalsList([
{ name: 'normal-1', provenance: 'none' },
{ name: 'imported-1', provenance: 'converted_prometheus' },
{ name: 'normal-2', provenance: 'none' },
{ name: 'imported-2', provenance: 'converted_prometheus' },
{ name: 'file-1', provenance: 'file' },
]);
renderWithProvider();
// Click to open the dropdown
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
await user.click(selector);
// Non-imported intervals should be visible
expect(await screen.findByText('normal-1')).toBeInTheDocument();
expect(screen.getByText('normal-2')).toBeInTheDocument();
expect(screen.getByText('file-1')).toBeInTheDocument();
// Imported intervals should NOT be visible
expect(screen.queryByText('imported-1')).not.toBeInTheDocument();
expect(screen.queryByText('imported-2')).not.toBeInTheDocument();
});
it('should handle empty list', async () => {
setTimeIntervalsList([]);
renderWithProvider();
// Selector should be present but have no options
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
expect(selector).toBeInTheDocument();
});
it('should handle list with only imported intervals', async () => {
const user = userEvent.setup();
setTimeIntervalsList([
{ name: 'imported-1', provenance: 'converted_prometheus' },
{ name: 'imported-2', provenance: 'converted_prometheus' },
]);
renderWithProvider();
// Click to open the dropdown
const selector = await screen.findByRole('combobox', { name: /time intervals/i });
await user.click(selector);
// No intervals should be visible
expect(screen.queryByText('imported-1')).not.toBeInTheDocument();
expect(screen.queryByText('imported-2')).not.toBeInTheDocument();
});
});

View File

@@ -1,24 +1,17 @@
import { SelectableValue } from '@grafana/data';
import { t } from '@grafana/i18n';
import { MultiSelect, MultiSelectCommonProps } from '@grafana/ui';
import { MuteTiming, useMuteTimings } from 'app/features/alerting/unified/components/mute-timings/useMuteTimings';
import { useMuteTimings } from 'app/features/alerting/unified/components/mute-timings/useMuteTimings';
import { BaseAlertmanagerArgs } from 'app/features/alerting/unified/types/hooks';
import { timeIntervalToString } from 'app/features/alerting/unified/utils/alertmanager';
import { K8sAnnotations } from 'app/features/alerting/unified/utils/k8s/constants';
import { isImportedResource } from 'app/features/alerting/unified/utils/k8s/utils';
import { MuteTimeInterval } from 'app/plugins/datasource/alertmanager/types';
const mapTimeInterval = ({ name, time_intervals }: MuteTiming): SelectableValue<string> => ({
const mapTimeInterval = ({ name, time_intervals }: MuteTimeInterval): SelectableValue<string> => ({
value: name,
label: name,
description: time_intervals.map((interval) => timeIntervalToString(interval)).join(', AND '),
});
/** Check if a time interval was imported from an external Alertmanager */
const isImportedTimeInterval = (timing: MuteTiming): boolean => {
const provenance = timing.metadata?.annotations?.[K8sAnnotations.Provenance];
return isImportedResource(provenance);
};
/** Provides a MultiSelect with available time intervals for the given alertmanager */
const TimeIntervalSelector = ({
alertmanager,
@@ -26,9 +19,7 @@ const TimeIntervalSelector = ({
}: BaseAlertmanagerArgs & { selectProps: MultiSelectCommonProps<string> }) => {
const { data } = useMuteTimings({ alertmanager, skip: selectProps.disabled });
// Filter out imported time intervals (provenance === 'prometheus_convert')
const availableTimings = data?.filter((timing) => !isImportedTimeInterval(timing)) || [];
const timeIntervalOptions = availableTimings.map((value) => mapTimeInterval(value));
const timeIntervalOptions = data?.map((value) => mapTimeInterval(value)) || [];
return (
<MultiSelect

View File

@@ -3,7 +3,6 @@ import { Navigate } from 'react-router-dom-v5-compat';
import { t } from '@grafana/i18n';
import { useGetMuteTiming } from 'app/features/alerting/unified/components/mute-timings/useMuteTimings';
import { useURLSearchParams } from 'app/features/alerting/unified/hooks/useURLSearchParams';
import { K8sAnnotations } from 'app/features/alerting/unified/utils/k8s/constants';
import { useAlertmanager } from '../../state/AlertmanagerContext';
import { withPageErrorBoundary } from '../../withPageErrorBoundary';
@@ -29,15 +28,13 @@ const EditTimingRoute = () => {
return <Navigate replace to="/alerting/routes" />;
}
const provenance = timeInterval?.metadata?.annotations?.[K8sAnnotations.Provenance];
return (
<MuteTimingForm
editMode
loading={isLoading}
showError={isError}
muteTiming={timeInterval}
provenance={provenance}
provisioned={timeInterval?.provisioned}
/>
);
};

View File

@@ -1,103 +0,0 @@
import { render, screen } from 'test/test-utils';
import { setupMswServer } from 'app/features/alerting/unified/mockApi';
import { grantUserPermissions } from 'app/features/alerting/unified/mocks';
import { AlertmanagerProvider } from 'app/features/alerting/unified/state/AlertmanagerContext';
import { GRAFANA_RULES_SOURCE_NAME } from 'app/features/alerting/unified/utils/datasource';
import { AccessControlAction } from 'app/types/accessControl';
import MuteTimingForm from './MuteTimingForm';
import { muteTimeInterval } from './mocks';
const renderWithProvider = (provenance?: string, editMode = false) => {
return render(
<AlertmanagerProvider accessType={'notification'} alertmanagerSourceName={GRAFANA_RULES_SOURCE_NAME}>
<MuteTimingForm
muteTiming={{ id: 'mock-id', ...muteTimeInterval }}
provenance={provenance}
editMode={editMode}
loading={false}
showError={false}
/>
</AlertmanagerProvider>
);
};
setupMswServer();
describe('MuteTimingForm', () => {
beforeEach(() => {
grantUserPermissions([
AccessControlAction.AlertingNotificationsRead,
AccessControlAction.AlertingNotificationsWrite,
]);
});
it('should not show any alert when provenance is none', async () => {
renderWithProvider('none');
expect(screen.queryByText(/imported and cannot be edited/i)).not.toBeInTheDocument();
expect(screen.queryByText(/provisioned/i)).not.toBeInTheDocument();
});
it('should not show any alert when provenance is undefined', async () => {
renderWithProvider(undefined);
expect(screen.queryByText(/imported and cannot be edited/i)).not.toBeInTheDocument();
expect(screen.queryByText(/provisioned/i)).not.toBeInTheDocument();
});
it('should show imported alert when provenance is converted_prometheus', async () => {
renderWithProvider('converted_prometheus');
expect(
await screen.findByText(/This time interval was imported and cannot be edited through the UI/i)
).toBeInTheDocument();
expect(
screen.getByText(/This time interval was imported from an external Alertmanager and is currently read-only/i)
).toBeInTheDocument();
});
it('should show provisioning alert when provenance is file', async () => {
renderWithProvider('file');
expect(await screen.findByText(/This time interval cannot be edited through the UI/i)).toBeInTheDocument();
expect(
screen.getByText(/This time interval has been provisioned, that means it was created by config/i)
).toBeInTheDocument();
});
it('should show provisioning alert for other provenance types', async () => {
renderWithProvider('api');
expect(await screen.findByText(/This time interval cannot be edited through the UI/i)).toBeInTheDocument();
});
it('should disable form when provenance is converted_prometheus', async () => {
renderWithProvider('converted_prometheus', true);
const nameInput = await screen.findByTestId('mute-timing-name');
expect(nameInput).toBeDisabled();
});
it('should disable form when provenance is file', async () => {
renderWithProvider('file', true);
const nameInput = await screen.findByTestId('mute-timing-name');
expect(nameInput).toBeDisabled();
});
it('should enable form when provenance is none', async () => {
renderWithProvider('none', true);
const nameInput = await screen.findByTestId('mute-timing-name');
expect(nameInput).toBeEnabled();
});
it('should enable form when provenance is undefined', async () => {
renderWithProvider(undefined, true);
const nameInput = await screen.findByTestId('mute-timing-name');
expect(nameInput).toBeEnabled();
});
});

View File

@@ -14,10 +14,9 @@ import {
import { useAlertmanager } from '../../state/AlertmanagerContext';
import { MuteTimingFields } from '../../types/mute-timing-form';
import { isImportedResource, isProvisionedResource } from '../../utils/k8s/utils';
import { makeAMLink } from '../../utils/misc';
import { createMuteTiming, defaultTimeInterval, isTimeIntervalDisabled } from '../../utils/mute-timings';
import { ImportedTimeIntervalAlert, ProvisionedResource, ProvisioningAlert } from '../Provisioning';
import { ProvisionedResource, ProvisioningAlert } from '../Provisioning';
import { MuteTimingTimeInterval } from './MuteTimingTimeInterval';
@@ -25,8 +24,8 @@ interface Props {
muteTiming?: MuteTiming;
showError?: boolean;
loading?: boolean;
/** Provenance of the mute timing - indicates how it was created (e.g., 'file', 'prometheus_convert', 'none') */
provenance?: string;
/** Is the current mute timing provisioned? If so, will disable editing via UI */
provisioned?: boolean;
/** Are we editing an existing time interval? */
editMode?: boolean;
}
@@ -57,7 +56,7 @@ const useDefaultValues = (muteTiming?: MuteTiming): MuteTimingFields => {
};
};
const MuteTimingForm = ({ muteTiming, showError, loading, provenance, editMode }: Props) => {
const MuteTimingForm = ({ muteTiming, showError, loading, provisioned, editMode }: Props) => {
const { selectedAlertmanager } = useAlertmanager();
const hookArgs = { alertmanager: selectedAlertmanager! };
@@ -106,19 +105,14 @@ const MuteTimingForm = ({ muteTiming, showError, loading, provenance, editMode }
);
}
const isProvisioned = isProvisionedResource(provenance);
const isImported = isImportedResource(provenance);
return (
<>
{isProvisioned && isImported && <ImportedTimeIntervalAlert />}
{isProvisioned && !isImported && <ProvisioningAlert resource={ProvisionedResource.MuteTiming} />}
{provisioned && <ProvisioningAlert resource={ProvisionedResource.MuteTiming} />}
<FormProvider {...formApi}>
<form onSubmit={formApi.handleSubmit(onSubmit)} data-testid="mute-timing-form">
<FieldSet disabled={isProvisioned || updating}>
<FieldSet disabled={provisioned || updating}>
<Field
required
noMargin
label={t('alerting.mute-timing-form.label-name', 'Name')}
description={t(
'alerting.time-interval-form.description-unique-time-interval',

View File

@@ -27,7 +27,6 @@ export function MuteTimingFields({ alertmanager }: BaseAlertmanagerArgs) {
)}
className={styles.muteTimingField}
invalid={!!errors.contactPoints?.[alertmanager]?.muteTimeIntervals}
noMargin
>
<Controller
render={({ field: { onChange, ref, ...field } }) => (

View File

@@ -175,36 +175,6 @@ export const setTimeIntervalsListEmpty = () => {
return handler;
};
interface TimeIntervalConfig {
name: string;
provenance?: string;
}
/**
* Makes the mock server respond with custom time intervals
*/
export const setTimeIntervalsList = (intervals: TimeIntervalConfig[]) => {
const listMuteTimingsPath = listNamespacedTimeIntervalHandler().info.path;
const handler = http.get(listMuteTimingsPath, () => {
const items = intervals.map((interval) => ({
metadata: {
annotations: {
'grafana.com/provenance': interval.provenance ?? 'none',
},
name: interval.name,
uid: `uid-${interval.name}`,
namespace: 'default',
resourceVersion: 'e0270bfced786660',
},
spec: { name: interval.name, time_intervals: [] },
}));
return HttpResponse.json(getK8sResponse('TimeIntervalList', items));
});
server.use(handler);
return handler;
};
export function mimirDataSource() {
const dataSource = mockDataSource(
{

View File

@@ -65,7 +65,3 @@ export const stringifyFieldSelector = (fieldSelectors: FieldSelector[]): string
export function isProvisionedResource(provenance?: string): boolean {
return Boolean(provenance && provenance !== KnownProvenance.None);
}
export function isImportedResource(provenance?: string): boolean {
return provenance === KnownProvenance.ConvertedPrometheus;
}

View File

@@ -33,7 +33,7 @@ global.ResizeObserver = jest.fn().mockImplementation((callback) => {
});
// Helper function to assign a mock div to a ref
function assignMockDivToRef(ref: React.RefObject<HTMLDivElement>, mockDiv: HTMLDivElement) {
function assignMockDivToRef(ref: React.RefObject<HTMLDivElement | null>, mockDiv: HTMLDivElement) {
// Use type assertion to bypass readonly restriction in tests
(ref as { current: HTMLDivElement | null }).current = mockDiv;
}

View File

@@ -8,7 +8,7 @@ import grafanaTextLogoDarkSvg from 'img/grafana_text_logo_dark.svg';
import grafanaTextLogoLightSvg from 'img/grafana_text_logo_light.svg';
interface SoloPanelPageLogoProps {
containerRef: React.RefObject<HTMLDivElement>;
containerRef: React.RefObject<HTMLDivElement | null>;
isHovered: boolean;
hideLogo?: UrlQueryValue;
}

View File

@@ -61,7 +61,7 @@ interface State {
class UnThemedTransformationsEditor extends React.PureComponent<TransformationsEditorProps, State> {
subscription?: Unsubscribable;
ref: RefObject<HTMLDivElement>;
ref: RefObject<HTMLDivElement | null>;
constructor(props: TransformationsEditorProps) {
super(props);

View File

@@ -43,7 +43,7 @@ export const LibraryPanelsView = ({
}
);
const asyncDispatch = useMemo(() => asyncDispatcher(dispatch), [dispatch]);
const abortControllerRef = useRef<AbortController>();
const abortControllerRef = useRef<AbortController | null>(null);
useDebounce(
() => {

View File

@@ -12,7 +12,7 @@ export interface Props {}
export const LiveConnectionWarning = memo(function LiveConnectionWarning() {
const [show, setShow] = useState<boolean | undefined>(undefined);
const subscriptionRef = useRef<Unsubscribable>();
const subscriptionRef = useRef<Unsubscribable | null>(null);
const styles = useStyles2(getStyle);
useEffect(() => {

View File

@@ -2,9 +2,8 @@ import { render, screen } from '@testing-library/react';
import { defaultsDeep } from 'lodash';
import { Provider } from 'react-redux';
import { CoreApp, EventBusSrv, FieldType, getDefaultTimeRange, LoadingState } from '@grafana/data';
import { config, PanelDataErrorViewProps } from '@grafana/runtime';
import { usePanelContext } from '@grafana/ui';
import { FieldType, getDefaultTimeRange, LoadingState } from '@grafana/data';
import { PanelDataErrorViewProps } from '@grafana/runtime';
import { configureStore } from 'app/store/configureStore';
import { PanelDataErrorView } from './PanelDataErrorView';
@@ -17,24 +16,7 @@ jest.mock('app/features/dashboard/services/DashboardSrv', () => ({
},
}));
jest.mock('@grafana/ui', () => ({
...jest.requireActual('@grafana/ui'),
usePanelContext: jest.fn(),
}));
const mockUsePanelContext = jest.mocked(usePanelContext);
const RUN_QUERY_MESSAGE = 'Run a query to visualize it here or go to all visualizations to add other panel types';
const panelContextRoot = {
app: CoreApp.Dashboard,
eventsScope: 'global',
eventBus: new EventBusSrv(),
};
describe('PanelDataErrorView', () => {
beforeEach(() => {
mockUsePanelContext.mockReturnValue(panelContextRoot);
});
it('show No data when there is no data', () => {
renderWithProps();
@@ -88,45 +70,6 @@ describe('PanelDataErrorView', () => {
expect(screen.getByText('Query returned nothing')).toBeInTheDocument();
});
it('should show "Run a query..." message when no query is configured and feature toggle is enabled', () => {
mockUsePanelContext.mockReturnValue(panelContextRoot);
const originalFeatureToggle = config.featureToggles.newVizSuggestions;
config.featureToggles.newVizSuggestions = true;
renderWithProps({
data: {
state: LoadingState.Done,
series: [],
timeRange: getDefaultTimeRange(),
},
});
expect(screen.getByText(RUN_QUERY_MESSAGE)).toBeInTheDocument();
config.featureToggles.newVizSuggestions = originalFeatureToggle;
});
it('should show "No data" message when feature toggle is disabled even without queries', () => {
mockUsePanelContext.mockReturnValue(panelContextRoot);
const originalFeatureToggle = config.featureToggles.newVizSuggestions;
config.featureToggles.newVizSuggestions = false;
renderWithProps({
data: {
state: LoadingState.Done,
series: [],
timeRange: getDefaultTimeRange(),
},
});
expect(screen.getByText('No data')).toBeInTheDocument();
expect(screen.queryByText(RUN_QUERY_MESSAGE)).not.toBeInTheDocument();
config.featureToggles.newVizSuggestions = originalFeatureToggle;
});
});
function renderWithProps(overrides?: Partial<PanelDataErrorViewProps>) {

View File

@@ -5,15 +5,14 @@ import {
FieldType,
getPanelDataSummary,
GrafanaTheme2,
PanelData,
PanelDataSummary,
PanelPluginVisualizationSuggestion,
} from '@grafana/data';
import { selectors } from '@grafana/e2e-selectors';
import { t, Trans } from '@grafana/i18n';
import { PanelDataErrorViewProps, locationService, config } from '@grafana/runtime';
import { PanelDataErrorViewProps, locationService } from '@grafana/runtime';
import { VizPanel } from '@grafana/scenes';
import { Icon, usePanelContext, useStyles2 } from '@grafana/ui';
import { usePanelContext, useStyles2 } from '@grafana/ui';
import { CardButton } from 'app/core/components/CardButton';
import { LS_VISUALIZATION_SELECT_TAB_KEY } from 'app/core/constants';
import store from 'app/core/store';
@@ -25,11 +24,6 @@ import { findVizPanelByKey, getVizPanelKeyForPanelId } from 'app/features/dashbo
import { useDispatch } from 'app/types/store';
import { changePanelPlugin } from '../state/actions';
import { hasData } from '../suggestions/utils';
function hasNoQueryConfigured(data: PanelData): boolean {
return !data.request?.targets || data.request.targets.length === 0;
}
export function PanelDataErrorView(props: PanelDataErrorViewProps) {
const styles = useStyles2(getStyles);
@@ -99,14 +93,8 @@ export function PanelDataErrorView(props: PanelDataErrorViewProps) {
}
};
const noData = !hasData(props.data);
const noQueryConfigured = hasNoQueryConfigured(props.data);
const showEmptyState =
config.featureToggles.newVizSuggestions && context.app === CoreApp.PanelEditor && noQueryConfigured && noData;
return (
<div className={styles.wrapper}>
{showEmptyState && <Icon name="chart-line" size="xxxl" className={styles.emptyStateIcon} />}
<div className={styles.message} data-testid={selectors.components.Panels.Panel.PanelDataErrorMessage}>
{message}
</div>
@@ -143,17 +131,7 @@ function getMessageFor(
return message;
}
const noData = !hasData(data);
const noQueryConfigured = hasNoQueryConfigured(data);
if (config.featureToggles.newVizSuggestions && noQueryConfigured && noData) {
return t(
'dashboard.new-panel.empty-state-message',
'Run a query to visualize it here or go to all visualizations to add other panel types'
);
}
if (noData) {
if (!data.series || data.series.length === 0 || data.series.every((frame) => frame.length === 0)) {
return fieldConfig?.defaults.noValue ?? t('panel.panel-data-error-view.no-value.default', 'No data');
}
@@ -198,9 +176,5 @@ const getStyles = (theme: GrafanaTheme2) => {
width: '100%',
maxWidth: '600px',
}),
emptyStateIcon: css({
color: theme.colors.text.secondary,
marginBottom: theme.spacing(2),
}),
};
};

View File

@@ -38,7 +38,7 @@ export function useSearchKeyboardNavigation(
): ItemSelection {
const highlightIndexRef = useRef<ItemSelection>({ x: 0, y: -1 });
const [highlightIndex, setHighlightIndex] = useState<ItemSelection>({ x: 0, y: -1 });
const urlsRef = useRef<Field>();
const urlsRef = useRef<Field | null>(null);
// Clear selection when the search results change
useEffect(() => {

View File

@@ -77,7 +77,7 @@ export const SuggestionsInput = ({
const theme = useTheme2();
const styles = getStyles(theme, inputHeight);
const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement>();
const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement | null>(null);
useEffect(() => {
scrollRef.current?.scrollTo(0, scrollTop);

View File

@@ -11,7 +11,7 @@ import checkboxWhitePng from 'img/checkbox_white.png';
import { ALL_VARIABLE_VALUE } from '../../constants';
export interface Props extends React.HTMLProps<HTMLUListElement>, Themeable2 {
export interface Props extends Omit<React.HTMLProps<HTMLUListElement>, 'onToggle'>, Themeable2 {
multi: boolean;
values: VariableOption[];
selectedValues: VariableOption[];

View File

@@ -20,8 +20,8 @@ interface CodeEditorProps {
export const LogsQLCodeEditor = (props: CodeEditorProps) => {
const { query, datasource, onChange } = props;
const monacoRef = useRef<Monaco>();
const disposalRef = useRef<monacoType.IDisposable>();
const monacoRef = useRef<Monaco | null>(null);
const disposalRef = useRef<monacoType.IDisposable | undefined>(undefined);
const onFocus = useCallback(async () => {
disposalRef.current = await reRegisterCompletionProvider(

View File

@@ -42,8 +42,8 @@ interface LogsCodeEditorProps {
export const PPLQueryEditor = (props: LogsCodeEditorProps) => {
const { query, datasource, onChange } = props;
const monacoRef = useRef<Monaco>();
const disposalRef = useRef<monacoType.IDisposable>();
const monacoRef = useRef<Monaco | null>(null);
const disposalRef = useRef<monacoType.IDisposable | undefined>(undefined);
const onFocus = useCallback(async () => {
disposalRef.current = await reRegisterCompletionProvider(

View File

@@ -20,8 +20,8 @@ interface SQLCodeEditorProps {
export const SQLQueryEditor = (props: SQLCodeEditorProps) => {
const { query, datasource, onChange } = props;
const monacoRef = useRef<Monaco>();
const disposalRef = useRef<monacoType.IDisposable>();
const monacoRef = useRef<Monaco | null>(null);
const disposalRef = useRef<monacoType.IDisposable | undefined>(undefined);
const onFocus = useCallback(async () => {
disposalRef.current = await reRegisterCompletionProvider(

View File

@@ -94,7 +94,7 @@ const EDITOR_HEIGHT_OFFSET = 2;
* Hook that returns function that will set up monaco autocomplete for the label selector
*/
function useAutocomplete(getLabelValues: (label: string) => Promise<string[]>, labels?: string[]) {
const providerRef = useRef<CompletionProvider>();
const providerRef = useRef<CompletionProvider | null>(null);
if (providerRef.current === undefined) {
providerRef.current = new CompletionProvider();
}

View File

@@ -126,7 +126,7 @@ export function LokiContextUi(props: LokiContextUiProps) {
window.localStorage.getItem(SHOULD_INCLUDE_PIPELINE_OPERATIONS) === 'true'
);
const timerHandle = useRef<number>();
const timerHandle = useRef<number | null>(null);
const previousInitialized = useRef<boolean>(false);
const previousContextFilters = useRef<ContextFilter[]>([]);
@@ -191,14 +191,18 @@ export function LokiContextUi(props: LokiContextUiProps) {
}, 1500);
return () => {
clearTimeout(timerHandle.current);
if (timerHandle.current) {
clearTimeout(timerHandle.current);
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [contextFilters, initialized]);
useEffect(() => {
return () => {
clearTimeout(timerHandle.current);
if (timerHandle.current) {
clearTimeout(timerHandle.current);
}
onClose();
};
}, [onClose]);

View File

@@ -52,7 +52,7 @@ export function TraceQLEditor(props: Props) {
const onRunQueryRef = useRef(onRunQuery);
onRunQueryRef.current = onRunQuery;
const errorTimeoutId = useRef<number>();
const errorTimeoutId = useRef<number | null>(null);
return (
<>
@@ -103,7 +103,9 @@ export function TraceQLEditor(props: Props) {
}
// Remove previous callback if existing, to prevent squiggles from been shown while the user is still typing
window.clearTimeout(errorTimeoutId.current);
if (errorTimeoutId.current) {
window.clearTimeout(errorTimeoutId.current);
}
const errorNodes = getErrorNodes(model.getValue());
const cursorPosition = changeEvent.changes[0].rangeOffset;

View File

@@ -1,5 +1,5 @@
export function renderHistogram(
can: React.RefObject<HTMLCanvasElement>,
can: React.RefObject<HTMLCanvasElement | null>,
histCanWidth: number,
histCanHeight: number,
xVals: number[],

View File

@@ -196,7 +196,7 @@ export const LogsPanel = ({
const dataSourcesMap = useDatasourcesFromTargets(panelData.request?.targets);
// Prevents the scroll position to change when new data from infinite scrolling is received
const keepScrollPositionRef = useRef<null | 'infinite-scroll' | 'user'>(null);
let closeCallback = useRef<() => void>();
const closeCallback = useRef<(() => void) | null>(null);
const { app, eventBus, onAddAdHocFilter } = usePanelContext();
useEffect(() => {

View File

@@ -70,7 +70,7 @@ export function useLayout(
const currentSignature = createDataSignature(rawNodes, rawEdges);
const isMounted = useMountedState();
const layoutWorkerCancelRef = useRef<(() => void) | undefined>();
const layoutWorkerCancelRef = useRef<(() => void) | null>(null);
useUnmount(() => {
if (layoutWorkerCancelRef.current) {

View File

@@ -133,7 +133,7 @@ export const AnnotationsPlugin2 = ({
const newRangeRef = useRef(newRange);
newRangeRef.current = newRange;
const xAxisRef = useRef<HTMLDivElement>();
const xAxisRef = useRef<HTMLDivElement | null>(null);
useLayoutEffect(() => {
config.addHook('ready', (u) => {

View File

@@ -23,7 +23,7 @@ export const ExemplarsPlugin = ({
maxHeight,
maxWidth,
}: ExemplarsPluginProps) => {
const plotInstance = useRef<uPlot>();
const plotInstance = useRef<uPlot | null>(null);
const [lockedExemplarRowIndex, setLockedExemplarRowIndex] = useState<number | undefined>();

View File

@@ -11,7 +11,7 @@ interface ThresholdControlsPluginProps {
}
export const OutsideRangePlugin = ({ config, onChangeTimeRange }: ThresholdControlsPluginProps) => {
const plotInstance = useRef<uPlot>();
const plotInstance = useRef<uPlot | null>(null);
const [timevalues, setTimeValues] = useState<number[] | TypedArray>([]);
const [timeRange, setTimeRange] = useState<Scale | undefined>();

View File

@@ -16,7 +16,7 @@ interface ThresholdControlsPluginProps {
}
export const ThresholdControlsPlugin = ({ config, fieldConfig, onThresholdsChange }: ThresholdControlsPluginProps) => {
const plotInstance = useRef<uPlot>();
const plotInstance = useRef<uPlot | null>(null);
const [renderToken, setRenderToken] = useState(0);
useLayoutEffect(() => {

View File

@@ -2178,10 +2178,8 @@
"badge-tooltip-provenance": "This resource has been provisioned via {{provenance}} and cannot be edited through the UI",
"badge-tooltip-standard": "This resource has been provisioned and cannot be edited through the UI",
"body-imported": "This contact point contains integrations that were imported from an external Alertmanager and is currently read-only. The integrations will become editable after the migration process is complete.",
"body-imported-time-interval": "This time interval was imported from an external Alertmanager and is currently read-only. The time interval will become editable after the migration process is complete.",
"body-provisioned": "This {{resource}} has been provisioned, that means it was created by config. Please contact your server admin to update this {{resource}}.",
"title-imported": "This contact point was imported and cannot be edited through the UI",
"title-imported-time-interval": "This time interval was imported and cannot be edited through the UI",
"title-provisioned": "This {{resource}} cannot be edited through the UI"
},
"provisioning-badge": {