Skip to content

Commit

Permalink
[react@18] (Part 2) fix useCallback breaking type changes (elastic#19…
Browse files Browse the repository at this point in the history
…1659)

## Summary

This is a prep for elastic#138222 and
follow up to elastic#182344. These are
post-merge leftovers and new instances from the previous
[run](elastic#182344)

In React@18 useCallback types have changed that introducing breaking
changes:
DefinitelyTyped/DefinitelyTyped#46691

Found potential issues using:

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

I tried to do my best to fix the type where possible, but there are some
complicated cases where I kept `any` after some struggling. Please feel
free to push improvements directly.

---------
Co-authored-by: Jatin Kathuria <jtn.kathuria@gmail.com>
  • Loading branch information
Dosant and logeekal committed Sep 4, 2024
1 parent 243de82 commit 8199dd0
Show file tree
Hide file tree
Showing 78 changed files with 237 additions and 173 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import React, {
useState,
} from 'react';
import type { Filter } from '@kbn/es-query';
import { isNoneGroup, useGrouping } from '@kbn/grouping';
import { GroupOption, isNoneGroup, useGrouping } from '@kbn/grouping';
import { isEqual } from 'lodash/fp';
import { i18n } from '@kbn/i18n';
import { useAlertsDataView } from '@kbn/alerts-ui-shared/src/common/hooks/use_alerts_data_view';
Expand Down Expand Up @@ -89,7 +89,7 @@ const AlertsGroupingInternal = <T extends BaseAlertsGroupAggregations>(
) as [number[], Dispatch<SetStateAction<number[]>>, () => void];

const onOptionsChange = useCallback(
(options) => {
(options: GroupOption[]) => {
// useGrouping > useAlertsGroupingState options sync
// the available grouping options change when the user selects
// a new field not in the default ones
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export const RuleActionsAlertsFilterTimeframe: React.FC<RuleActionsAlertsFilterT
);

const onChangeTimezone = useCallback(
(value) => {
(value: Array<{ label: string }>) => {
setSelectedTimezone(value);
if (value[0].label) updateTimeframe({ timezone: value[0].label });
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export const RuleDefinition = () => {
}, [selectedRuleTypeModel, docLinks]);

const onChangeMetaData = useCallback(
(newMetadata) => {
(newMetadata: Record<string, unknown>) => {
dispatch({
type: 'setMetadata',
payload: newMetadata,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,18 @@ export const RuleSettingsFlappingInputs = (props: RuleSettingsFlappingInputsProp
onStatusChangeThresholdChange,
} = props;

const internalOnLookBackWindowChange = useCallback(
const internalOnLookBackWindowChange = useCallback<
NonNullable<React.ComponentProps<typeof RuleSettingsRangeInput>['onChange']>
>(
(e) => {
onLookBackWindowChange(parseInt(e.currentTarget.value, 10));
},
[onLookBackWindowChange]
);

const internalOnStatusChangeThresholdChange = useCallback(
const internalOnStatusChangeThresholdChange = useCallback<
NonNullable<React.ComponentProps<typeof RuleSettingsRangeInput>['onChange']>
>(
(e) => {
onStatusChangeThresholdChange(parseInt(e.currentTarget.value, 10));
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export const FieldDescriptionContent: React.FC<
);

const truncateFieldDescription = useCallback(
(nextValue) => {
(nextValue: boolean) => {
setIsTruncated(nextValue);
setShouldTruncateByDefault(nextValue);
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export const CodeEditorInput = ({
const onUpdate = useUpdate({ onInputChange, field });

const updateValue = useCallback(
async (newValue: string, onUpdateFn) => {
async (newValue: string, onUpdateFn: typeof onUpdate) => {
let parsedValue;

// Validate JSON syntax
Expand Down
15 changes: 12 additions & 3 deletions packages/kbn-text-based-editor/src/text_based_languages_editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,17 @@ export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
const containerRef = useRef<HTMLElement>(null);

// When the editor is on full size mode, the user can resize the height of the editor.
const onMouseDownResizeHandler = useCallback(
const onMouseDownResizeHandler = useCallback<
React.ComponentProps<typeof ResizableButton>['onMouseDownResizeHandler']
>(
(mouseDownEvent) => {
function isMouseEvent(e: React.TouchEvent | React.MouseEvent): e is React.MouseEvent {
return e && 'pageY' in e;
}
const startSize = editorHeight;
const startPosition = mouseDownEvent.pageY;
const startPosition = isMouseEvent(mouseDownEvent)
? mouseDownEvent?.pageY
: mouseDownEvent?.touches[0].pageY;

function onMouseMove(mouseMoveEvent: MouseEvent) {
const height = startSize - startPosition + mouseMoveEvent.pageY;
Expand All @@ -265,7 +272,9 @@ export const TextBasedLanguagesEditor = memo(function TextBasedLanguagesEditor({
[editorHeight]
);

const onKeyDownResizeHandler = useCallback(
const onKeyDownResizeHandler = useCallback<
React.ComponentProps<typeof ResizableButton>['onKeyDownResizeHandler']
>(
(keyDownEvent) => {
let height = editorHeight;
if (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export const useSelectedDocs = (docMap: Map<string, DataTableRecord>): UseSelect
const selectedDocsCount = selectedDocIds.length;

const getCountOfFilteredSelectedDocs = useCallback(
(docIds) => {
(docIds: string[]) => {
if (!selectedDocsCount) {
return 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export const OptionsListPopoverSuggestions = ({
}, [api.loadMoreSubject, stateManager.requestSize, 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 @@ -14,6 +14,7 @@ import { i18n } from '@kbn/i18n';
import { ElasticRequestState } from '@kbn/unified-doc-viewer';
import { useEsDocSearch } from '@kbn/unified-doc-viewer-plugin/public';
import type { EsDocSearchProps } from '@kbn/unified-doc-viewer-plugin/public/types';
import type { DataTableRecord } from '@kbn/discover-utils/types';
import { setBreadcrumbs } from '../../../utils/breadcrumbs';
import { useDiscoverServices } from '../../../hooks/use_discover_services';
import { SingleDocViewer } from './single_doc_viewer';
Expand Down Expand Up @@ -43,7 +44,7 @@ export function Doc(props: DocProps) {
}, [profilesManager, core, dataView]);

const onProcessRecord = useCallback(
(record) => {
(record: DataTableRecord) => {
return profilesManager.resolveDocumentProfile({ record });
},
[profilesManager]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
SmartFieldFallbackTooltip,
} from '@kbn/unified-field-list';
import type { DataVisualizerTableItem } from '@kbn/data-visualizer-plugin/public/application/common/components/stats_table/types';
import type { DataVisualizerTableState } from '@kbn/data-visualizer-plugin/common/types';
import { isOfAggregateQueryType } from '@kbn/es-query';
import { useDiscoverServices } from '../../../../hooks/use_discover_services';
import { FIELD_STATISTICS_LOADED } from './constants';
Expand Down Expand Up @@ -146,7 +147,7 @@ export const FieldStatisticsTable = React.memo((props: FieldStatisticsTableProps
);

const updateState = useCallback(
(changes) => {
(changes: Partial<DataVisualizerTableState>) => {
if (changes.showDistributions !== undefined && stateContainer) {
stateContainer.appState.update({ hideAggregatedPreview: !changes.showDistributions }, true);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export default function ESQLToDataViewTransitionModal({
onClose,
}: ESQLToDataViewTransitionModalProps) {
const [dismissModalChecked, setDismissModalChecked] = useState(false);
const onTransitionModalDismiss = useCallback((e) => {
const onTransitionModalDismiss = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
setDismissModalChecked(e.target.checked);
}, []);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { KibanaRenderContextProvider } from '@kbn/react-kibana-context-render';
import { VIEW_MODE } from '@kbn/saved-search-plugin/common';
import { SearchResponseIncompleteWarning } from '@kbn/search-response-warnings/src/types';

import type { DocViewFilterFn } from '@kbn/unified-doc-viewer/types';
import { getValidViewMode } from '../application/main/utils/get_valid_view_mode';
import { DiscoverServices } from '../build_services';
import { SearchEmbeddablFieldStatsTableComponent } from './components/search_embeddable_field_stats_table_component';
Expand Down Expand Up @@ -242,9 +243,9 @@ export const getSearchEmbeddableFactory = ({
return dataViews![0];
}, [dataViews]);

const onAddFilter = useCallback(
const onAddFilter = useCallback<DocViewFilterFn>(
async (field, value, operator) => {
if (!dataView) return;
if (!dataView || !field) return;

let newFilters = generateFilters(
discoverServices.filterManager,
Expand Down
5 changes: 3 additions & 2 deletions src/plugins/esql_datagrid/public/data_grid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
DataLoadingState,
type SortOrder,
renderCustomToolbar,
UnifiedDataTableRenderCustomToolbarProps,
} from '@kbn/unified-data-table';
import { i18n } from '@kbn/i18n';
import { EuiLink, EuiText, EuiIcon } from '@elastic/eui';
Expand Down Expand Up @@ -67,7 +68,7 @@ const DataGrid: React.FC<ESQLDataGridProps> = (props) => {
);
const [rowsPerPage, setRowsPerPage] = useState(DEFAULT_ROWS_PER_PAGE);

const onSetColumns = useCallback((columns) => {
const onSetColumns = useCallback((columns: string[]) => {
setActiveColumns(columns);
}, []);

Expand Down Expand Up @@ -146,7 +147,7 @@ const DataGrid: React.FC<ESQLDataGridProps> = (props) => {
}, [props.share?.url.locators]);

const renderToolbar = useCallback(
(customToolbarProps) => {
(customToolbarProps: UnifiedDataTableRenderCustomToolbarProps) => {
const discoverLink = discoverLocator?.getRedirectUrl({
dataViewSpec: props.dataView.toSpec(),
timeRange: props.data.query.timefilter.timefilter.getTime(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
useResizeObserver,
EuiSwitch,
useEuiTheme,
EuiSwitchEvent,
} from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { css } from '@emotion/react';
Expand Down Expand Up @@ -367,7 +368,7 @@ export const DocViewerTable = ({
);

const onHideNullValuesChange = useCallback(
(e) => {
(e: EuiSwitchEvent) => {
setAreNullValuesHidden(e.target.checked);
},
[setAreNullValuesHidden]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
Placement,
Tooltip,
LegendValue,
BrushEndListener,
} from '@elastic/charts';
import { EuiTitle } from '@elastic/eui';
import { RangeFilterParams } from '@kbn/es-query';
Expand Down Expand Up @@ -120,7 +121,7 @@ export const TimelionVisComponent = ({
isDateHistogram: true,
});

const brushEndListener = useCallback(
const brushEndListener = useCallback<BrushEndListener>(
({ x }) => {
if (!x) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export const AssistantHeader: React.FC<Props> = ({
const showDestroyModal = useCallback(() => setIsResetConversationModalVisible(true), []);

const onConversationChange = useCallback(
(updatedConversation) => {
(updatedConversation: Conversation) => {
onConversationSelected({
cId: updatedConversation.id,
cTitle: updatedConversation.title,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@ export const useSessionPagination = ({
);

const onTableChange = useCallback(
({ page, sort }) => {
({
page,
sort,
}: // eslint-disable-next-line @typescript-eslint/no-explicit-any
any) => {
setSessionStorageTableOptions({
page,
sort,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ export const ConversationSelectorSettings: React.FC<Props> = React.memo(

// Callback for when user types to create a new conversation
const onCreateOption = useCallback(
(searchValue, flattenedOptions = []) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(searchValue: any, flattenedOptions: any = []) => {
if (!searchValue || !searchValue.trim().toLowerCase()) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { Conversation } from '../../../..';
import * as i18n from './translations';
import * as i18nModel from '../../../connectorland/models/model_selector/translations';

import { ConnectorSelector } from '../../../connectorland/connector_selector';
import { AIConnector, ConnectorSelector } from '../../../connectorland/connector_selector';
import { SelectSystemPrompt } from '../../prompt_editor/system_prompt/select_system_prompt';
import { ModelSelector } from '../../../connectorland/models/model_selector/model_selector';
import { useLoadConnectors } from '../../../connectorland/use_load_connectors';
Expand Down Expand Up @@ -140,7 +140,7 @@ export const ConversationSettingsEditor: React.FC<ConversationSettingsEditorProp
[selectedConversation]
);
const handleOnConnectorSelectionChange = useCallback(
(connector) => {
(connector: AIConnector) => {
if (selectedConversation != null) {
const config = getGenAiConfig(connector);
const updatedConversation = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ const ConversationSettingsManagementComponent: React.FC<Props> = ({
);

const setAssistantStreamingEnabled = useCallback(
(value) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(value: any) => {
setHasPendingChanges(true);
setUpdatedAssistantStreamingEnabled(value);
},
Expand Down Expand Up @@ -259,11 +260,10 @@ const ConversationSettingsManagementComponent: React.FC<Props> = ({
const columns = useMemo(
() =>
getColumns({
conversations: conversationSettings,
onDeleteActionClicked,
onEditActionClicked,
}),
[conversationSettings, getColumns, onDeleteActionClicked, onEditActionClicked]
[getColumns, onDeleteActionClicked, onEditActionClicked]
);

const confirmationTitle = useMemo(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ export const useConversationsTable = () => {
({
onDeleteActionClicked,
onEditActionClicked,
}: {
onDeleteActionClicked: (conversation: ConversationTableItem) => void;
onEditActionClicked: (conversation: ConversationTableItem) => void;
}): Array<EuiBasicTableColumn<ConversationTableItem>> => {
return [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ const SelectSystemPromptComponent: React.FC<Props> = ({
);

const onChange = useCallback(
async (selectedSystemPromptId) => {
async (selectedSystemPromptId: string) => {
if (selectedSystemPromptId === ADD_NEW_SYSTEM_PROMPT) {
setIsSettingsModalVisible(true);
setSelectedSettingsTab(SYSTEM_PROMPTS_TAB);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ export const SystemPromptEditorComponent: React.FC<Props> = ({
);

const handleNewConversationDefaultChange = useCallback(
(e) => {
(e: React.ChangeEvent<HTMLInputElement>) => {
const isChecked = e.target.checked;
const defaultNewSystemPrompts = systemPromptSettings.filter(
(p) => p.isNewConversationDefault
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ export const SystemPromptSelector: React.FC<Props> = React.memo(

// Callback for when user types to create a new system prompt
const onCreateOption = useCallback(
(searchValue, flattenedOptions = []) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(searchValue: any, flattenedOptions: any[] = []) => {
if (!searchValue || !searchValue.trim().toLowerCase()) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ export const DefaultConversationsColumn: React.FC<Props> = React.memo(
: Math.min(maxConversationsToShow, defaultConversations.length);
const itemsToDisplay = defaultConversations.slice(0, currentDisplaying - 1);

const toggleContent = useCallback((prev) => {
setIsExpanded(!prev);
}, []);
const toggleContent = useCallback(() => {
setIsExpanded(!isExpanded);
}, [isExpanded]);

if (!defaultConversations || defaultConversations?.length === 0) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ export const PromptTextArea = forwardRef<HTMLTextAreaElement, Props>(
);

const onKeyDown = useCallback(
(event) => {
(event: React.KeyboardEvent<HTMLTextAreaElement>) => {
// keyCode 13 is needed in case of IME input
if (event.keyCode === 13 && !event.shiftKey) {
event.preventDefault();

if (value.trim().length) {
onPromptSubmit(event.target.value?.trim());
onPromptSubmit(event.currentTarget.value?.trim());
setUserPrompt('');
} else {
event.stopPropagation();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ export const QuickPromptSelector: React.FC<Props> = React.memo(

// Callback for when user types to create a new quick prompt
const onCreateOption = useCallback(
(searchValue, flattenedOptions = []) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(searchValue: any, flattenedOptions: any[] = []) => {
if (!searchValue || !searchValue.trim().toLowerCase()) {
return;
}
Expand Down
Loading

0 comments on commit 8199dd0

Please sign in to comment.