React18: Update useCallback arg types where needed (#57084)

This commit is contained in:
kay delaney
2022-10-17 14:52:12 +01:00
committed by GitHub
parent b1128e0b8c
commit 5d53a983d8
21 changed files with 64 additions and 58 deletions

View File

@@ -1528,20 +1528,18 @@ exports[`better eslint`] = {
[0, 0, 0, "Do not use any type assertions.", "0"] [0, 0, 0, "Do not use any type assertions.", "0"]
], ],
"packages/grafana-ui/src/components/Table/Table.tsx:5381": [ "packages/grafana-ui/src/components/Table/Table.tsx:5381": [
[0, 0, 0, "Unexpected any. Specify a different type.", "0"], [0, 0, 0, "Do not use any type assertions.", "0"],
[0, 0, 0, "Do not use any type assertions.", "1"], [0, 0, 0, "Unexpected any. Specify a different type.", "1"],
[0, 0, 0, "Unexpected any. Specify a different type.", "2"], [0, 0, 0, "Do not use any type assertions.", "2"],
[0, 0, 0, "Do not use any type assertions.", "3"], [0, 0, 0, "Unexpected any. Specify a different type.", "3"],
[0, 0, 0, "Do not use any type assertions.", "4"], [0, 0, 0, "Do not use any type assertions.", "4"],
[0, 0, 0, "Unexpected any. Specify a different type.", "5"], [0, 0, 0, "Do not use any type assertions.", "5"],
[0, 0, 0, "Do not use any type assertions.", "6"], [0, 0, 0, "Do not use any type assertions.", "6"],
[0, 0, 0, "Do not use any type assertions.", "7"], [0, 0, 0, "Do not use any type assertions.", "7"],
[0, 0, 0, "Do not use any type assertions.", "8"], [0, 0, 0, "Do not use any type assertions.", "8"],
[0, 0, 0, "Do not use any type assertions.", "9"], [0, 0, 0, "Do not use any type assertions.", "9"],
[0, 0, 0, "Do not use any type assertions.", "10"], [0, 0, 0, "Do not use any type assertions.", "10"],
[0, 0, 0, "Do not use any type assertions.", "11"], [0, 0, 0, "Do not use any type assertions.", "11"]
[0, 0, 0, "Do not use any type assertions.", "12"],
[0, 0, 0, "Do not use any type assertions.", "13"]
], ],
"packages/grafana-ui/src/components/Table/TableCell.tsx:5381": [ "packages/grafana-ui/src/components/Table/TableCell.tsx:5381": [
[0, 0, 0, "Do not use any type assertions.", "0"], [0, 0, 0, "Do not use any type assertions.", "0"],

View File

@@ -1,7 +1,6 @@
import React, { FC, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import React, { CSSProperties, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { import {
Cell, Cell,
Column,
TableState, TableState,
useAbsoluteLayout, useAbsoluteLayout,
useFilters, useFilters,
@@ -29,6 +28,7 @@ import {
TableSortByActionCallback, TableSortByActionCallback,
TableSortByFieldState, TableSortByFieldState,
TableFooterCalc, TableFooterCalc,
GrafanaTableColumn,
} from './types'; } from './types';
import { getColumns, sortCaseInsensitive, sortNumber, getFooterItems, createFooterCalculationValues } from './utils'; import { getColumns, sortCaseInsensitive, sortNumber, getFooterItems, createFooterCalculationValues } from './utils';
@@ -55,7 +55,7 @@ export interface Props {
function useTableStateReducer({ onColumnResize, onSortByChange, data }: Props) { function useTableStateReducer({ onColumnResize, onSortByChange, data }: Props) {
return useCallback( return useCallback(
(newState: TableState, action: any) => { (newState: TableState, action: { type: string }) => {
switch (action.type) { switch (action.type) {
case 'columnDoneResizing': case 'columnDoneResizing':
if (onColumnResize) { if (onColumnResize) {
@@ -99,7 +99,7 @@ function useTableStateReducer({ onColumnResize, onSortByChange, data }: Props) {
); );
} }
function getInitialState(initialSortBy: Props['initialSortBy'], columns: Column[]): Partial<TableState> { function getInitialState(initialSortBy: Props['initialSortBy'], columns: GrafanaTableColumn[]): Partial<TableState> {
const state: Partial<TableState> = {}; const state: Partial<TableState> = {};
if (initialSortBy) { if (initialSortBy) {
@@ -108,7 +108,7 @@ function getInitialState(initialSortBy: Props['initialSortBy'], columns: Column[
for (const sortBy of initialSortBy) { for (const sortBy of initialSortBy) {
for (const col of columns) { for (const col of columns) {
if (col.Header === sortBy.displayName) { if (col.Header === sortBy.displayName) {
state.sortBy.push({ id: col.id as string, desc: sortBy.desc }); state.sortBy.push({ id: col.id!, desc: sortBy.desc });
} }
} }
} }
@@ -117,7 +117,7 @@ function getInitialState(initialSortBy: Props['initialSortBy'], columns: Column[
return state; return state;
} }
export const Table: FC<Props> = memo((props: Props) => { export const Table = memo((props: Props) => {
const { const {
ariaLabel, ariaLabel,
data, data,
@@ -284,7 +284,7 @@ export const Table: FC<Props> = memo((props: Props) => {
}); });
const RenderRow = React.useCallback( const RenderRow = React.useCallback(
({ index: rowIndex, style }) => { ({ index: rowIndex, style }: { index: number; style: CSSProperties }) => {
let row = rows[rowIndex]; let row = rows[rowIndex];
if (enablePagination) { if (enablePagination) {
row = page[rowIndex]; row = page[rowIndex];

View File

@@ -31,7 +31,7 @@ export interface QueryOperationRowRenderProps {
onClose: () => void; onClose: () => void;
} }
export const QueryOperationRow: React.FC<QueryOperationRowProps> = ({ export function QueryOperationRow({
children, children,
actions, actions,
title, title,
@@ -43,7 +43,7 @@ export const QueryOperationRow: React.FC<QueryOperationRowProps> = ({
draggable, draggable,
index, index,
id, id,
}: QueryOperationRowProps) => { }: QueryOperationRowProps) {
const [isContentVisible, setIsContentVisible] = useState(isOpen !== undefined ? isOpen : true); const [isContentVisible, setIsContentVisible] = useState(isOpen !== undefined ? isOpen : true);
const theme = useTheme(); const theme = useTheme();
const styles = getQueryOperationRowStyles(theme); const styles = getQueryOperationRowStyles(theme);
@@ -51,7 +51,7 @@ export const QueryOperationRow: React.FC<QueryOperationRowProps> = ({
setIsContentVisible(!isContentVisible); setIsContentVisible(!isContentVisible);
}, [isContentVisible, setIsContentVisible]); }, [isContentVisible, setIsContentVisible]);
const reportDragMousePosition = useCallback((e) => { const reportDragMousePosition = useCallback((e: React.MouseEvent) => {
// When drag detected react-beautiful-dnd will preventDefault the event // When drag detected react-beautiful-dnd will preventDefault the event
// Ref: https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/guides/how-we-use-dom-events.md#a-mouse-drag-has-started-and-the-user-is-now-dragging // Ref: https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/guides/how-we-use-dom-events.md#a-mouse-drag-has-started-and-the-user-is-now-dragging
if (e.defaultPrevented) { if (e.defaultPrevented) {
@@ -141,7 +141,7 @@ export const QueryOperationRow: React.FC<QueryOperationRowProps> = ({
{isContentVisible && <div className={styles.content}>{children}</div>} {isContentVisible && <div className={styles.content}>{children}</div>}
</div> </div>
); );
}; }
const getQueryOperationRowStyles = stylesFactory((theme: GrafanaTheme) => { const getQueryOperationRowStyles = stylesFactory((theme: GrafanaTheme) => {
return { return {

View File

@@ -14,7 +14,7 @@ export interface Props {
const AlertRuleItem = ({ rule, search, onTogglePause }: Props) => { const AlertRuleItem = ({ rule, search, onTogglePause }: Props) => {
const ruleUrl = `${rule.url}?editPanel=${rule.panelId}&tab=alert`; const ruleUrl = `${rule.url}?editPanel=${rule.panelId}&tab=alert`;
const renderText = useCallback( const renderText = useCallback(
(text) => ( (text: string) => (
<Highlighter <Highlighter
key={text} key={text}
highlightClassName="highlight-search-match" highlightClassName="highlight-search-match"

View File

@@ -18,7 +18,7 @@ export const BackgroundSizeEditor: FC<StandardEditorProps<string, undefined, und
const imageSize = value ?? BackgroundImageSize.Cover; const imageSize = value ?? BackgroundImageSize.Cover;
const onImageSizeChange = useCallback( const onImageSizeChange = useCallback(
(size) => { (size: string) => {
onChange(size); onChange(size);
}, },
[onChange] [onChange]

View File

@@ -32,7 +32,7 @@ export const ResourceDimensionEditor: FC<
const labelWidth = 9; const labelWidth = 9;
const onModeChange = useCallback( const onModeChange = useCallback(
(mode) => { (mode: ResourceDimensionMode) => {
onChange({ onChange({
...value, ...value,
mode, mode,
@@ -42,7 +42,7 @@ export const ResourceDimensionEditor: FC<
); );
const onFieldChange = useCallback( const onFieldChange = useCallback(
(field) => { (field = '') => {
onChange({ onChange({
...value, ...value,
field, field,

View File

@@ -54,7 +54,7 @@ export const ScalarDimensionEditor: FC<StandardEditorProps<ScalarDimensionConfig
); );
const onModeChange = useCallback( const onModeChange = useCallback(
(mode) => { (mode: ScalarDimensionMode) => {
onChange({ onChange({
...value, ...value,
mode, mode,

View File

@@ -31,7 +31,7 @@ export const TextDimensionEditor: FC<StandardEditorProps<TextDimensionConfig, Te
const labelWidth = 9; const labelWidth = 9;
const onModeChange = useCallback( const onModeChange = useCallback(
(mode) => { (mode: TextDimensionMode) => {
onChange({ onChange({
...value, ...value,
mode, mode,
@@ -41,7 +41,7 @@ export const TextDimensionEditor: FC<StandardEditorProps<TextDimensionConfig, Te
); );
const onFieldChange = useCallback( const onFieldChange = useCallback(
(field) => { (field?: string) => {
onChange({ onChange({
...value, ...value,
field, field,
@@ -51,7 +51,7 @@ export const TextDimensionEditor: FC<StandardEditorProps<TextDimensionConfig, Te
); );
const onFixedChange = useCallback( const onFixedChange = useCallback(
(fixed) => { (fixed = '') => {
onChange({ onChange({
...value, ...value,
fixed, fixed,

View File

@@ -1,4 +1,5 @@
import { css } from '@emotion/css'; import { css } from '@emotion/css';
import { Placement, Rect } from '@popperjs/core';
import React, { useCallback, useRef, useState } from 'react'; import React, { useCallback, useRef, useState } from 'react';
import SVG from 'react-inlinesvg'; import SVG from 'react-inlinesvg';
import { usePopper } from 'react-popper'; import { usePopper } from 'react-popper';
@@ -34,15 +35,18 @@ export function SearchCard({ editable, item, onTagSelected, onToggleChecked, onC
const timeout = useRef<number | null>(null); const timeout = useRef<number | null>(null);
// Popper specific logic // Popper specific logic
const offsetCallback = useCallback(({ placement, reference, popper }) => { const offsetCallback = useCallback(
let result: [number, number] = [0, 0]; ({ placement, reference, popper }: { placement: Placement; reference: Rect; popper: Rect }) => {
if (placement === 'bottom' || placement === 'top') { let result: [number, number] = [0, 0];
result = [0, -(reference.height + popper.height) / 2]; if (placement === 'bottom' || placement === 'top') {
} else if (placement === 'left' || placement === 'right') { result = [0, -(reference.height + popper.height) / 2];
result = [-(reference.width + popper.width) / 2, 0]; } else if (placement === 'left' || placement === 'right') {
} result = [-(reference.width + popper.width) / 2, 0];
return result; }
}, []); return result;
},
[]
);
const [markerElement, setMarkerElement] = React.useState<HTMLDivElement | null>(null); const [markerElement, setMarkerElement] = React.useState<HTMLDivElement | null>(null);
const [popperElement, setPopperElement] = React.useState<HTMLDivElement | null>(null); const [popperElement, setPopperElement] = React.useState<HTMLDivElement | null>(null);
const { styles: popperStyles, attributes } = usePopper(markerElement, popperElement, { const { styles: popperStyles, attributes } = usePopper(markerElement, popperElement, {

View File

@@ -1,6 +1,6 @@
/* eslint-disable react/jsx-no-undef */ /* eslint-disable react/jsx-no-undef */
import { css } from '@emotion/css'; import { css } from '@emotion/css';
import React, { useEffect, useRef, useCallback, useState } from 'react'; import React, { useEffect, useRef, useCallback, useState, CSSProperties } from 'react';
import { FixedSizeList } from 'react-window'; import { FixedSizeList } from 'react-window';
import InfiniteLoader from 'react-window-infinite-loader'; import InfiniteLoader from 'react-window-infinite-loader';
@@ -41,7 +41,7 @@ export const SearchResultsCards = React.memo(
}, [response, listEl]); }, [response, listEl]);
const RenderRow = useCallback( const RenderRow = useCallback(
({ index: rowIndex, style }) => { ({ index: rowIndex, style }: { index: number; style: CSSProperties }) => {
const meta = response.view.dataFrame.meta?.custom as SearchResultMeta; const meta = response.view.dataFrame.meta?.custom as SearchResultMeta;
let className = ''; let className = '';

View File

@@ -1,6 +1,6 @@
/* eslint-disable react/jsx-no-undef */ /* eslint-disable react/jsx-no-undef */
import { css } from '@emotion/css'; import { css } from '@emotion/css';
import React, { useEffect, useMemo, useRef, useCallback, useState } from 'react'; import React, { useEffect, useMemo, useRef, useCallback, useState, CSSProperties } from 'react';
import { useTable, Column, TableOptions, Cell, useAbsoluteLayout } from 'react-table'; import { useTable, Column, TableOptions, Cell, useAbsoluteLayout } from 'react-table';
import { FixedSizeList } from 'react-window'; import { FixedSizeList } from 'react-window';
import InfiniteLoader from 'react-window-infinite-loader'; import InfiniteLoader from 'react-window-infinite-loader';
@@ -103,7 +103,7 @@ export const SearchResultsTable = React.memo(
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable(options, useAbsoluteLayout); const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable(options, useAbsoluteLayout);
const RenderRow = useCallback( const RenderRow = useCallback(
({ index: rowIndex, style }) => { ({ index: rowIndex, style }: { index: number; style: CSSProperties }) => {
const row = rows[rowIndex]; const row = rows[rowIndex];
prepareRow(row); prepareRow(row);

View File

@@ -200,7 +200,7 @@ export const SearchView = ({
}; };
const getStarredItems = useCallback( const getStarredItems = useCallback(
(e) => { (e: React.FormEvent<HTMLInputElement>) => {
onStarredFilterChange(e); onStarredFilterChange(e);
}, },
[onStarredFilterChange] [onStarredFilterChange]

View File

@@ -58,7 +58,7 @@ export const FilterByValueFilterEditor = (props: Props) => {
); );
const onChangeMatcherOptions = useCallback( const onChangeMatcherOptions = useCallback(
(options) => { (options: unknown) => {
onChange({ onChange({
...filter, ...filter,
config: { config: {

View File

@@ -21,11 +21,11 @@ const fieldNamePickerSettings: StandardEditorsRegistryItem<string, FieldNamePick
settings: { width: 24 }, settings: { width: 24 },
} as any; } as any;
export const ConvertFieldTypeTransformerEditor: React.FC<TransformerUIProps<ConvertFieldTypeTransformerOptions>> = ({ export const ConvertFieldTypeTransformerEditor = ({
input, input,
options, options,
onChange, onChange,
}) => { }: TransformerUIProps<ConvertFieldTypeTransformerOptions>) => {
const allTypes: Array<SelectableValue<FieldType>> = [ const allTypes: Array<SelectableValue<FieldType>> = [
{ value: FieldType.number, label: 'Numeric' }, { value: FieldType.number, label: 'Numeric' },
{ value: FieldType.string, label: 'String' }, { value: FieldType.string, label: 'String' },
@@ -35,7 +35,7 @@ export const ConvertFieldTypeTransformerEditor: React.FC<TransformerUIProps<Conv
]; ];
const onSelectField = useCallback( const onSelectField = useCallback(
(idx) => (value: string | undefined) => { (idx: number) => (value: string | undefined) => {
const conversions = options.conversions; const conversions = options.conversions;
conversions[idx] = { ...conversions[idx], targetField: value ?? '' }; conversions[idx] = { ...conversions[idx], targetField: value ?? '' };
onChange({ onChange({
@@ -47,7 +47,7 @@ export const ConvertFieldTypeTransformerEditor: React.FC<TransformerUIProps<Conv
); );
const onSelectDestinationType = useCallback( const onSelectDestinationType = useCallback(
(idx) => (value: SelectableValue<FieldType>) => { (idx: number) => (value: SelectableValue<FieldType>) => {
const conversions = options.conversions; const conversions = options.conversions;
conversions[idx] = { ...conversions[idx], destinationType: value.value }; conversions[idx] = { ...conversions[idx], destinationType: value.value };
onChange({ onChange({
@@ -59,7 +59,7 @@ export const ConvertFieldTypeTransformerEditor: React.FC<TransformerUIProps<Conv
); );
const onInputFormat = useCallback( const onInputFormat = useCallback(
(idx) => (e: ChangeEvent<HTMLInputElement>) => { (idx: number) => (e: ChangeEvent<HTMLInputElement>) => {
const conversions = options.conversions; const conversions = options.conversions;
conversions[idx] = { ...conversions[idx], dateFormat: e.currentTarget.value }; conversions[idx] = { ...conversions[idx], dateFormat: e.currentTarget.value };
onChange({ onChange({
@@ -81,7 +81,7 @@ export const ConvertFieldTypeTransformerEditor: React.FC<TransformerUIProps<Conv
}, [onChange, options]); }, [onChange, options]);
const onRemoveConvertFieldType = useCallback( const onRemoveConvertFieldType = useCallback(
(idx) => { (idx: number) => {
const removed = options.conversions; const removed = options.conversions;
removed.splice(idx, 1); removed.splice(idx, 1);
onChange({ onChange({

View File

@@ -29,7 +29,11 @@ export const CanvasContextMenu = ({ scene }: Props) => {
const selectedElements = scene.selecto?.getSelectedTargets(); const selectedElements = scene.selecto?.getSelectedTargets();
const handleContextMenu = useCallback( const handleContextMenu = useCallback(
(event) => { (event: Event) => {
if (!(event instanceof MouseEvent)) {
return;
}
event.preventDefault(); event.preventDefault();
const shouldSelectElement = event.currentTarget !== scene.div; const shouldSelectElement = event.currentTarget !== scene.div;
if (shouldSelectElement) { if (shouldSelectElement) {

View File

@@ -45,7 +45,7 @@ export function APIEditor({ value, context, onChange }: Props) {
const labelWidth = 9; const labelWidth = 9;
const onEndpointChange = useCallback( const onEndpointChange = useCallback(
(endpoint) => { (endpoint = '') => {
onChange({ onChange({
...value, ...value,
endpoint, endpoint,
@@ -55,7 +55,7 @@ export function APIEditor({ value, context, onChange }: Props) {
); );
const onDataChange = useCallback( const onDataChange = useCallback(
(data) => { (data?: string) => {
onChange({ onChange({
...value, ...value,
data, data,

View File

@@ -1,6 +1,6 @@
import { css } from '@emotion/css'; import { css } from '@emotion/css';
import { Global } from '@emotion/react'; import { Global } from '@emotion/react';
import Tree from 'rc-tree'; import Tree, { TreeNodeProps } from 'rc-tree';
import React, { Key, useEffect, useMemo, useState } from 'react'; import React, { Key, useEffect, useMemo, useState } from 'react';
import { GrafanaTheme2, SelectableValue, StandardEditorProps } from '@grafana/data'; import { GrafanaTheme2, SelectableValue, StandardEditorProps } from '@grafana/data';
@@ -87,7 +87,7 @@ export const TreeNavigationEditor = ({ item }: StandardEditorProps<any, TreeView
setAutoExpandParent(false); setAutoExpandParent(false);
}; };
const switcherIcon = (obj: { isLeaf: boolean; expanded: boolean }) => { const switcherIcon = (obj: TreeNodeProps) => {
if (obj.isLeaf) { if (obj.isLeaf) {
// TODO: Implement element specific icons // TODO: Implement element specific icons
return <></>; return <></>;

View File

@@ -26,7 +26,7 @@ export const GeomapStyleRulesEditor: FC<StandardEditorProps<FeatureStyleConfig[]
}, [onChange, value, theme.visualization]); }, [onChange, value, theme.visualization]);
const onRuleChange = useCallback( const onRuleChange = useCallback(
(idx) => (style: FeatureStyleConfig | undefined) => { (idx: number) => (style: FeatureStyleConfig | undefined) => {
const copyStyles = [...value]; const copyStyles = [...value];
if (style) { if (style) {
copyStyles[idx] = style; copyStyles[idx] = style;

View File

@@ -38,7 +38,7 @@ export const Legend = function Legend(props: Props) {
const colorItems = getColorLegendItems(nodes, theme); const colorItems = getColorLegendItems(nodes, theme);
const onClick = useCallback( const onClick = useCallback(
(item) => { (item: VizLegendItem<ItemData>) => {
onSort({ onSort({
field: item.data!.field, field: item.data!.field,
ascending: item.data!.field === sort?.field ? !sort?.ascending : false, ascending: item.data!.field === sort?.field ? !sort?.ascending : false,

View File

@@ -182,7 +182,7 @@ export function NodeGraph({ getLinks, dataFrames, nodeLimit }: Props) {
// This cannot be inline func or it will create infinite render cycle. // This cannot be inline func or it will create infinite render cycle.
const topLevelRef = useCallback( const topLevelRef = useCallback(
(r) => { (r: HTMLDivElement) => {
measureRef(r); measureRef(r);
(zoomRef as MutableRefObject<HTMLElement | null>).current = r; (zoomRef as MutableRefObject<HTMLElement | null>).current = r;
}, },

View File

@@ -27,7 +27,7 @@ export function useContextMenu(
const [menu, setMenu] = useState<JSX.Element | undefined>(undefined); const [menu, setMenu] = useState<JSX.Element | undefined>(undefined);
const onNodeOpen = useCallback( const onNodeOpen = useCallback(
(event, node) => { (event: MouseEvent<SVGElement>, node: NodeDatum) => {
const extraNodeItem = config.gridLayout const extraNodeItem = config.gridLayout
? [ ? [
{ {
@@ -57,7 +57,7 @@ export function useContextMenu(
); );
const onEdgeOpen = useCallback( const onEdgeOpen = useCallback(
(event, edge) => { (event: MouseEvent<SVGElement>, edge: EdgeDatum) => {
const renderer = getItemsRenderer(getLinks(edges, edge.dataFrameRowIndex), edge); const renderer = getItemsRenderer(getLinks(edges, edge.dataFrameRowIndex), edge);
if (renderer) { if (renderer) {