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
34 changed files with 50 additions and 44 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -463,7 +463,7 @@ export function useColumnResize(
return dataGridResizeHandler; return dataGridResizeHandler;
} }
export function useScrollbarWidth(ref: RefObject<DataGridHandle>, height: number) { export function useScrollbarWidth(ref: RefObject<DataGridHandle | null>, height: number) {
const [scrollbarWidth, setScrollbarWidth] = useState(0); const [scrollbarWidth, setScrollbarWidth] = useState(0);
useLayoutEffect(() => { 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 // `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 // `toggleAllRowsExpanded`), and if we used a variable, that variable would be undefined at the time
// we initialize `useTableStateReducer`. // we initialize `useTableStateReducer`.
const toggleAllRowsExpandedRef = useRef<(value?: boolean) => void>(); const toggleAllRowsExpandedRef = useRef<((value?: boolean) => void) | null>(null);
// Internal react table state reducer // Internal react table state reducer
const stateReducer = useTableStateReducer({ const stateReducer = useTableStateReducer({

View File

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

View File

@@ -19,7 +19,7 @@ interface EventsCanvasProps {
} }
export function EventsCanvas({ id, events, renderEventMarker, mapEventToXYCoords, config }: 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 // 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 // so we need to force the re-render when the draw hook was performed by uPlot
const [renderToken, setRenderToken] = useState(0); 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 [{ 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 styles = useStyles2(getStyles, maxWidth);
const renderRef = useRef(render); const renderRef = useRef(render);

View File

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

View File

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

View File

@@ -33,7 +33,7 @@ global.ResizeObserver = jest.fn().mockImplementation((callback) => {
}); });
// Helper function to assign a mock div to a ref // 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 // Use type assertion to bypass readonly restriction in tests
(ref as { current: HTMLDivElement | null }).current = mockDiv; (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'; import grafanaTextLogoLightSvg from 'img/grafana_text_logo_light.svg';
interface SoloPanelPageLogoProps { interface SoloPanelPageLogoProps {
containerRef: React.RefObject<HTMLDivElement>; containerRef: React.RefObject<HTMLDivElement | null>;
isHovered: boolean; isHovered: boolean;
hideLogo?: UrlQueryValue; hideLogo?: UrlQueryValue;
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -11,7 +11,7 @@ import checkboxWhitePng from 'img/checkbox_white.png';
import { ALL_VARIABLE_VALUE } from '../../constants'; 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; multi: boolean;
values: VariableOption[]; values: VariableOption[];
selectedValues: VariableOption[]; selectedValues: VariableOption[];

View File

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

View File

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

View File

@@ -20,8 +20,8 @@ interface SQLCodeEditorProps {
export const SQLQueryEditor = (props: SQLCodeEditorProps) => { export const SQLQueryEditor = (props: SQLCodeEditorProps) => {
const { query, datasource, onChange } = props; const { query, datasource, onChange } = props;
const monacoRef = useRef<Monaco>(); const monacoRef = useRef<Monaco | null>(null);
const disposalRef = useRef<monacoType.IDisposable>(); const disposalRef = useRef<monacoType.IDisposable | undefined>(undefined);
const onFocus = useCallback(async () => { const onFocus = useCallback(async () => {
disposalRef.current = await reRegisterCompletionProvider( 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 * Hook that returns function that will set up monaco autocomplete for the label selector
*/ */
function useAutocomplete(getLabelValues: (label: string) => Promise<string[]>, labels?: string[]) { function useAutocomplete(getLabelValues: (label: string) => Promise<string[]>, labels?: string[]) {
const providerRef = useRef<CompletionProvider>(); const providerRef = useRef<CompletionProvider | null>(null);
if (providerRef.current === undefined) { if (providerRef.current === undefined) {
providerRef.current = new CompletionProvider(); providerRef.current = new CompletionProvider();
} }

View File

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

View File

@@ -52,7 +52,7 @@ export function TraceQLEditor(props: Props) {
const onRunQueryRef = useRef(onRunQuery); const onRunQueryRef = useRef(onRunQuery);
onRunQueryRef.current = onRunQuery; onRunQueryRef.current = onRunQuery;
const errorTimeoutId = useRef<number>(); const errorTimeoutId = useRef<number | null>(null);
return ( 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 // 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 errorNodes = getErrorNodes(model.getValue());
const cursorPosition = changeEvent.changes[0].rangeOffset; const cursorPosition = changeEvent.changes[0].rangeOffset;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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