Skip to content

Commit

Permalink
[react@18] Fix useCallback breaking type changes (#182344)
Browse files Browse the repository at this point in the history
## Summary

Prep work for React@18 bump
#138222

In React@18 `useCallback` types has changed that introduced breaking
changes:
DefinitelyTyped/DefinitelyTyped#46691

Fixed using:

https://github.com/eps1lon/types-react-codemod?tab=readme-ov-file#usecallback-implicit-any

**Tried to do my best with fixing the types, but if you disagree or have
a better idea how it should be solved feel free to suggest changes or
commit directly to the branch 🙏**

---------

Co-authored-by: Sergi Massaneda <sergi.massaneda@elastic.co>
Co-authored-by: Sébastien Loix <sabee77@gmail.com>
Co-authored-by: Nick Peihl <nick.peihl@elastic.co>
Co-authored-by: Stratoula Kalafateli <efstratia.kalafateli@elastic.co>
Co-authored-by: Felix Stürmer <felix.stuermer@elastic.co>
Co-authored-by: nickofthyme <nicholas.partridge@elastic.co>
Co-authored-by: Davis McPhee <davis.mcphee@elastic.co>
Co-authored-by: Vitalii Dmyterko <92328789+vitaliidm@users.noreply.github.com>
Co-authored-by: Maxim Palenov <maxim.palenov@elastic.co>
Co-authored-by: Christos Nasikas <christos.nasikas@elastic.co>
Co-authored-by: Anton Dosov <anton.dosov@elastic.co>
  • Loading branch information
12 people committed Aug 28, 2024
1 parent 97b5479 commit 2d1d592
Show file tree
Hide file tree
Showing 432 changed files with 1,250 additions and 875 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,15 @@

import { i18n } from '@kbn/i18n';
import useUpdateEffect from 'react-use/lib/useUpdateEffect';
import React, { useState, useCallback, Dispatch, FocusEvent, useContext, useMemo } from 'react';
import React, {
useState,
useCallback,
Dispatch,
FocusEvent,
useContext,
useMemo,
ChangeEventHandler,
} from 'react';
import { css } from '@emotion/react';

import {
Expand Down Expand Up @@ -126,9 +134,9 @@ export function ColorRangeItem({
[colorRange.start, colorRanges, dispatch, index, popoverInFocus, dataBounds, palettes, isLast]
);

const onValueChange = useCallback(
const onValueChange = useCallback<ChangeEventHandler<HTMLInputElement>>(
({ target: { value: targetValue } }) => {
setLocalValue(targetValue);
setLocalValue(+targetValue);
dispatch({
type: 'updateValue',
payload: { index, value: targetValue, accessor, dataBounds, palettes },
Expand All @@ -138,7 +146,7 @@ export function ColorRangeItem({
);

const onUpdateColor = useCallback(
(color) => {
(color: string) => {
dispatch({ type: 'updateColor', payload: { index, color, dataBounds, palettes } });
},
[dispatch, index, dataBounds, palettes]
Expand Down
1 change: 1 addition & 0 deletions packages/kbn-dom-drag-drop/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export {
type DraggingIdentifier,
type DragDropAction,
type DropOverlayWrapperProps,
type DroppableProps,
Draggable,
Droppable,
useDragDropContext,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ const GroupPanelComponent = <T,>({
);

const onToggle = useCallback(
(isOpen) => {
(isOpen: boolean) => {
if (onToggleGroup) {
onToggleGroup(isOpen, groupBucket);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/kbn-grouping/src/hooks/use_grouping.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export type DynamicGroupingProps<T> = Pick<
/** Interface for configuring grouping package where T is the consumer `GroupingAggregation`
* @interface GroupingArgs<T>
*/
interface GroupingArgs<T> {
export interface GroupingArgs<T> {
componentProps: StaticGroupingProps<T>;
defaultGroupingOptions: GroupOption[];
fields: FieldSpec[];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export const CodeEditor = ({ onChange, type, isReadOnly, name, ...props }: CodeE
editorModel.setValue(trimmedValue);
}, []);

const editorDidMount = useCallback(
const editorDidMount = useCallback<NonNullable<KibanaReactCodeEditorProps['editorDidMount']>>(
(editor) => {
setEditorCalculatedHeight(editor);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { getFieldInputValue } from '@kbn/management-settings-utilities';
import { useUpdate } from '@kbn/management-settings-utilities';

import { debounce } from 'lodash';
import { OnInputChangeFn } from '@kbn/management-settings-types';
import { useServices } from '../services';
import { InputProps } from '../types';
import { TEST_SUBJ_PREFIX_FIELD } from '.';
Expand All @@ -39,7 +40,7 @@ export const ArrayInput = ({
const onUpdate = useUpdate({ onInputChange, field });

const updateValue = useCallback(
async (newValue: string, onUpdateFn) => {
async (newValue: string, onUpdateFn: OnInputChangeFn<'array'>) => {
const parsedValue = newValue
.replace(REGEX, ',')
.split(',')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { EuiFieldNumber, EuiFieldNumberProps } from '@elastic/eui';
import { getFieldInputValue, useUpdate } from '@kbn/management-settings-utilities';

import { debounce } from 'lodash';
import { OnInputChangeFn } from '@kbn/management-settings-types';
import { InputProps } from '../types';
import { TEST_SUBJ_PREFIX_FIELD } from '.';
import { useServices } from '../services';
Expand All @@ -36,7 +37,7 @@ export const NumberInput = ({
const onUpdate = useUpdate({ onInputChange, field });

const updateValue = useCallback(
async (newValue: number, onUpdateFn) => {
async (newValue: number, onUpdateFn: OnInputChangeFn<'number'>) => {
const validationResponse = await validateChange(field.id, newValue);
if (validationResponse.successfulValidation && !validationResponse.valid) {
onUpdateFn({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export const AutocompleteFieldListsComponent: React.FC<AutocompleteFieldListsPro
largeLists: [],
});
const { loading, result, start } = useFindListsBySize();
const getLabel = useCallback(({ name }) => name, []);
const getLabel = useCallback(({ name }: ListSchema) => name, []);

const optionsMemo = useMemo(
() => filterFieldToList(listData, selectedField),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const OperatorComponent: React.FC<OperatorState> = ({
selectedField,
'aria-label': ariaLabel,
}): JSX.Element => {
const getLabel = useCallback(({ message }): string => message, []);
const getLabel = useCallback(({ message }: OperatorOption): string => message, []);
const optionsMemo = useMemo(
(): OperatorOption[] =>
operatorOptions != null && operatorOptions.length > 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import React, { useCallback } from 'react';
import type { FC } from 'react';

import type { IconType, SearchFilterConfig } from '@elastic/eui';
import type { EuiSearchBarProps, IconType, SearchFilterConfig } from '@elastic/eui';
import { EuiFlexGroup, EuiFlexItem, EuiButton, EuiSearchBar } from '@elastic/eui';
import type { ExceptionListTypeEnum } from '@kbn/securitysolution-io-ts-list-types';
import type { GetExceptionItemProps } from '../types';
Expand Down Expand Up @@ -73,7 +73,7 @@ const SearchBarComponent: FC<SearchBarProps> = ({
onSearch,
onAddExceptionClick,
}) => {
const handleOnSearch = useCallback(
const handleOnSearch = useCallback<NonNullable<EuiSearchBarProps['onChange']>>(
({ queryText }): void => {
onSearch({ search: queryText });
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { EuiFormRow, EuiHorizontalRule, EuiRange } from '@elastic/eui';
import { EuiFormRow, EuiHorizontalRule, EuiRange, EuiRangeProps } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { debounce } from 'lodash';
import { RowHeightSettings, RowHeightSettingsProps } from './row_height_settings';
Expand Down Expand Up @@ -63,9 +63,9 @@ export const UnifiedDataTableAdditionalDisplaySettings: React.FC<
[onChangeSampleSize]
);

const onChangeActiveSampleSize = useCallback(
const onChangeActiveSampleSize = useCallback<NonNullable<EuiRangeProps['onChange']>>(
(event) => {
if (!event.target.value) {
if (!('value' in event.target) || !event.target.value) {
setActiveSampleSize('');
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ const tooltipContent = {
}),
};

export interface ColorPickerProps {
overwriteColor?: string | null;
defaultColor?: string | null;
isClearable?: boolean;
setConfig: (config: { color?: string }) => void;
label?: string;
disableHelpTooltip?: boolean;
disabledMessage?: string;
showAlpha?: boolean;
}

export const ColorPicker = ({
overwriteColor,
defaultColor,
Expand All @@ -37,16 +48,7 @@ export const ColorPicker = ({
disableHelpTooltip,
disabledMessage,
showAlpha,
}: {
overwriteColor?: string | null;
defaultColor?: string | null;
isClearable?: boolean;
setConfig: (config: { color?: string }) => void;
label?: string;
disableHelpTooltip?: boolean;
disabledMessage?: string;
showAlpha?: boolean;
}) => {
}: ColorPickerProps) => {
const [colorText, setColorText] = useState(overwriteColor || defaultColor);
const [validatedColor, setValidatedColor] = useState(overwriteColor || defaultColor);
const [currentColorAlpha, setCurrentColorAlpha] = useState(getColorAlpha(colorText));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,18 @@ export const defaultFilter: Query = {
language: 'kuery',
};

export interface FilterQueryInputProps {
inputFilter: Query | undefined;
onChange: (query: Query) => void;
dataView: DataViewBase;
helpMessage?: string | null;
label?: string;
initiallyOpen?: boolean;
['data-test-subj']?: string;
queryInputServices: QueryInputServices;
appName: string;
}

export function FilterQueryInput({
inputFilter,
onChange,
Expand All @@ -43,17 +55,7 @@ export function FilterQueryInput({
['data-test-subj']: dataTestSubj,
queryInputServices,
appName,
}: {
inputFilter: Query | undefined;
onChange: (query: Query) => void;
dataView: DataViewBase;
helpMessage?: string | null;
label?: string;
initiallyOpen?: boolean;
['data-test-subj']?: string;
queryInputServices: QueryInputServices;
appName: string;
}) {
}: FilterQueryInputProps) {
const [filterPopoverOpen, setFilterPopoverOpen] = useState(Boolean(initiallyOpen));

const onClosePopup: EuiPopoverProps['closePopover'] = useCallback(() => {
Expand Down
1 change: 1 addition & 0 deletions packages/kbn-visualization-ui-components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export type {
IconSet,
AccessorConfig,
QueryInputServices,
ColorPickerProps,
} from './components';

export type { FormatFactory, LineStyle } from './types';
2 changes: 1 addition & 1 deletion packages/react/kibana_mount/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const useIfMounted = () => {
[]
);

const ifMounted = useCallback((func) => {
const ifMounted = useCallback((func?: () => void) => {
if (isMounted.current && func) {
func();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ export const GaugeComponent: FC<GaugeRenderProps> = ({

const getColor = useCallback(
(
value,
value: number,
paletteConfig: PaletteOutput<CustomPaletteState>,
bands: number[],
percentageMode?: boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import {
Wordcloud,
RenderChangeListener,
LEGACY_LIGHT_THEME,
ElementClickListener,
WordCloudElementEvent,
} from '@elastic/charts';
import { EmptyPlaceholder } from '@kbn/charts-plugin/public';
import {
Expand Down Expand Up @@ -190,13 +192,13 @@ export const TagCloudChart = ({
[]
);

const handleWordClick = useCallback(
const handleWordClick = useCallback<ElementClickListener>(
(elements) => {
if (!bucket) {
return;
}
const termsBucketId = getColumnByAccessor(bucket, visData.columns)!.id;
const clickedValue = elements[0][0].text;
const clickedValue = (elements[0] as WordCloudElementEvent)[0].text;

const columnIndex = visData.columns.findIndex((col) => col.id === termsBucketId);
if (columnIndex < 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { animationFrameScheduler } from 'rxjs';
import { useCallback, useEffect, RefObject } from 'react';
import { filter, debounceTime } from 'rxjs';

import type { Chart } from '@elastic/charts';
import type { Chart, PointerUpdateListener } from '@elastic/charts';

import { parseSyncOptions } from './active_cursor_utils';

Expand All @@ -24,9 +24,9 @@ export const useActiveCursor = (
activeCursor: ActiveCursor,
chartRef: RefObject<Chart>,
syncOptions: ActiveCursorSyncOption
) => {
): PointerUpdateListener => {
const { accessors, isDateHistogram } = parseSyncOptions(syncOptions);
const handleCursorUpdate = useCallback(
const handleCursorUpdate = useCallback<PointerUpdateListener>(
(cursor) => {
activeCursor.activeCursor$?.next({
cursor,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ export const OptionsListPopoverSuggestions = ({
}, [loadMoreSuggestions, totalCardinality]);

const renderOption = useCallback(
(option, searchStringValue) => {
(option: EuiSelectableOption, searchStringValue: string) => {
if (!allowExpensiveQueries || searchTechnique === 'exact') return option.label;

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ const IndexPatternEditorFlyoutContentComponent = ({
const getRollupIndices = (rollupCaps: RollupIndicesCapsResponse) => Object.keys(rollupCaps);

const onTypeChange = useCallback(
(newType) => {
(newType: INDEX_PATTERN_TYPE) => {
form.setFieldValue('title', '');
form.setFieldValue('name', '');
form.setFieldValue('timestampField', '');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* Side Public License, v 1.
*/

import React, { Fragment, useCallback, useMemo, useState, FC, PropsWithChildren } from 'react';
import React, { Fragment, useCallback, useMemo, useState, FC } from 'react';
import { FormattedMessage } from '@kbn/i18n-react';
import { EuiSpacer, EuiText, useEuiPaddingSize } from '@elastic/eui';
import { css } from '@emotion/react';
Expand Down Expand Up @@ -241,7 +241,7 @@ export function ContextAppContent({
);
}

const WrapperWithPadding: FC<PropsWithChildren<unknown>> = ({ children }) => {
const WrapperWithPadding: FC = ({ children }) => {
const padding = useEuiPaddingSize('s');

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ export function DiscoverSidebarResponsive(props: DiscoverSidebarResponsiveProps)
// As unifiedFieldListSidebarContainerRef ref can be empty in the beginning,
// we need to fetch the data once API becomes available and after documents are fetched
const initializeUnifiedFieldListSidebarContainerApi = useCallback(
(api) => {
(api: UnifiedFieldListSidebarContainerApi) => {
if (!api) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { EuiFormRow, EuiSelect } from '@elastic/eui';

import { FieldHook, getFieldValidityAndErrorMessage } from '../../hook_form_lib';

interface Props {
export interface Props {
field: FieldHook;
euiFieldProps: {
options: Array<
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export const DashboardLinkDestinationPicker = ({
);

const renderOption = useCallback(
(option, searchValue, contentClassName) => {
(option: DashboardComboBoxOption, searchValue: string, contentClassName: string) => {
const { label, key: dashboardId } = option;
return (
<EuiFlexGroup gutterSize="s" alignItems="center" className={contentClassName}>
Expand Down
3 changes: 2 additions & 1 deletion src/plugins/links/public/components/editor/links_editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import useMountedState from 'react-use/lib/useMountedState';

import {
DropResult,
EuiButton,
EuiButtonEmpty,
EuiButtonGroup,
Expand Down Expand Up @@ -101,7 +102,7 @@ const LinksEditor = ({
}, [initialLinks]);

const onDragEnd = useCallback(
({ source, destination }) => {
({ source, destination }: DropResult) => {
if (source && destination) {
const newList = euiDragDropReorder(orderedLinks, source.index, destination.index).map(
(link, i) => {
Expand Down
Loading

0 comments on commit 2d1d592

Please sign in to comment.