Skip to content

Commit

Permalink
[Console] Clean up use of any (#95065)
Browse files Browse the repository at this point in the history
* cleaned up autocomplete.ts and get_endpoint_from_postition.ts of anys

* general clean up of lowering hanging fruit

* cleaned up remaining anys, still need to test

* fix remaining TS compilation issues

* also tidy up use of "as any" and some more ": any"

* addressed type issues and introduced the default editor settings object

* clean up @ts-ignore

* added comments to interface

Co-authored-by: Kibana Machine <[email protected]>
  • Loading branch information
jloleysens and kibanamachine authored Mar 24, 2021
1 parent 6295ae7 commit edfdb78
Show file tree
Hide file tree
Showing 52 changed files with 402 additions and 219 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { i18n } from '@kbn/i18n';
interface Props {
getCurl: () => Promise<string>;
getDocumentation: () => Promise<string | null>;
autoIndent: (ev?: React.MouseEvent) => void;
autoIndent: (ev: React.MouseEvent) => void;
addNotification?: (opts: { title: string }) => void;
}

Expand Down Expand Up @@ -84,8 +84,7 @@ export class ConsoleMenu extends Component<Props, State> {
window.open(documentation, '_blank');
};

// Using `any` here per this issue: https://github.com/elastic/eui/issues/2265
autoIndent: any = (event: React.MouseEvent) => {
autoIndent = (event: React.MouseEvent) => {
this.closePopover();
this.props.autoIndent(event);
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export type AutocompleteOptions = 'fields' | 'indices' | 'templates';
interface Props {
onSaveSettings: (newSettings: DevToolsSettings) => void;
onClose: () => void;
refreshAutocompleteSettings: (selectedSettings: any) => void;
refreshAutocompleteSettings: (selectedSettings: DevToolsSettings['autocomplete']) => void;
settings: DevToolsSettings;
}

Expand Down Expand Up @@ -233,7 +233,7 @@ export function DevToolsSettingsModal(props: Props) {
return rest;
})}
idToSelectedMap={checkboxIdToSelectedMap}
onChange={(e: any) => {
onChange={(e: unknown) => {
onAutocompleteChange(e as AutocompleteOptions);
}}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export function ConsoleHistory({ close }: Props) {
const selectedReq = useRef<any>(null);

const describeReq = useMemo(() => {
const _describeReq = (req: any) => {
const _describeReq = (req: { endpoint: string; time: string }) => {
const endpoint = req.endpoint;
const date = moment(req.time);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { applyCurrentSettings } from '../editor/legacy/console_editor/apply_edit

interface Props {
settings: DevToolsSettings;
req: any | null;
req: { method: string; endpoint: string; data: string; time: string } | null;
}

export function HistoryViewer({ settings, req }: Props) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export function applyCurrentSettings(
editor: CoreEditor | CustomAceEditor,
settings: DevToolsSettings
) {
if ((editor as any).setStyles) {
if ((editor as { setStyles?: Function }).setStyles) {
(editor as CoreEditor).setStyles({
wrapLines: settings.wrapMode,
fontSize: settings.fontSize + 'px',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
// Mocked functions
import { sendRequestToES } from '../../../../hooks/use_send_current_request_to_es/send_request_to_es';
import { getEndpointFromPosition } from '../../../../../lib/autocomplete/get_endpoint_from_position';

import type { DevToolsSettings } from '../../../../../services';
import * as consoleMenuActions from '../console_menu_actions';
import { Editor } from './editor';

Expand All @@ -40,7 +40,7 @@ describe('Legacy (Ace) Console Editor Component Smoke Test', () => {
<I18nProvider>
<ServicesContextProvider value={mockedAppContextValue}>
<RequestContextProvider>
<EditorContextProvider settings={{} as any}>
<EditorContextProvider settings={({} as unknown) as DevToolsSettings}>
<Editor initialTextValue="" />
</EditorContextProvider>
</RequestContextProvider>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ function EditorUI({ initialTextValue }: EditorProps) {
getDocumentation={() => {
return getDocumentation(editorInstanceRef.current!, docLinkVersion);
}}
autoIndent={(event: any) => {
autoIndent={(event) => {
autoIndent(editorInstanceRef.current!, event);
}}
addNotification={({ title }) => notifications.toasts.add({ title })}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import { getEndpointFromPosition } from '../../../../lib/autocomplete/get_endpoint_from_position';
import { SenseEditor } from '../../../models/sense_editor';

export async function autoIndent(editor: SenseEditor, event: Event) {
export async function autoIndent(editor: SenseEditor, event: React.MouseEvent) {
event.preventDefault();
await editor.autoIndent();
editor.getCoreEditor().getContainer().focus();
Expand Down
22 changes: 14 additions & 8 deletions src/plugins/console/public/application/containers/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,20 @@ import { retrieveAutoCompleteInfo } from '../../lib/mappings/mappings';
import { useServicesContext, useEditorActionContext } from '../contexts';
import { DevToolsSettings, Settings as SettingsService } from '../../services';

const getAutocompleteDiff = (newSettings: DevToolsSettings, prevSettings: DevToolsSettings) => {
const getAutocompleteDiff = (
newSettings: DevToolsSettings,
prevSettings: DevToolsSettings
): AutocompleteOptions[] => {
return Object.keys(newSettings.autocomplete).filter((key) => {
// @ts-ignore
return prevSettings.autocomplete[key] !== newSettings.autocomplete[key];
});
}) as AutocompleteOptions[];
};

const refreshAutocompleteSettings = (settings: SettingsService, selectedSettings: any) => {
const refreshAutocompleteSettings = (
settings: SettingsService,
selectedSettings: DevToolsSettings['autocomplete']
) => {
retrieveAutoCompleteInfo(settings, selectedSettings);
};

Expand All @@ -44,12 +50,12 @@ const fetchAutocompleteSettingsIfNeeded = (
if (isSettingsChanged) {
// If the user has changed one of the autocomplete settings, then we'll fetch just the
// ones which have changed.
const changedSettings: any = autocompleteDiff.reduce(
(changedSettingsAccum: any, setting: string): any => {
changedSettingsAccum[setting] = newSettings.autocomplete[setting as AutocompleteOptions];
const changedSettings: DevToolsSettings['autocomplete'] = autocompleteDiff.reduce(
(changedSettingsAccum, setting) => {
changedSettingsAccum[setting] = newSettings.autocomplete[setting];
return changedSettingsAccum;
},
{}
{} as DevToolsSettings['autocomplete']
);
retrieveAutoCompleteInfo(settings, changedSettings);
} else if (isPollingChanged && newSettings.polling) {
Expand Down Expand Up @@ -89,7 +95,7 @@ export function Settings({ onClose }: Props) {
<DevToolsSettingsModal
onClose={onClose}
onSaveSettings={onSaveSettings}
refreshAutocompleteSettings={(selectedSettings: any) =>
refreshAutocompleteSettings={(selectedSettings) =>
refreshAutocompleteSettings(settings, selectedSettings)
}
settings={settings.toJSON()}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ import * as editor from '../../stores/editor';
import { DevToolsSettings } from '../../../services';
import { createUseContext } from '../create_use_context';

const EditorReadContext = createContext<editor.Store>(null as any);
const EditorActionContext = createContext<Dispatch<editor.Action>>(null as any);
const EditorReadContext = createContext<editor.Store>(editor.initialValue);
const EditorActionContext = createContext<Dispatch<editor.Action>>(() => {});

export interface EditorContextArgs {
children: any;
children: JSX.Element;
settings: DevToolsSettings;
}

Expand All @@ -25,7 +25,7 @@ export function EditorContextProvider({ children, settings }: EditorContextArgs)
settings,
}));
return (
<EditorReadContext.Provider value={state as any}>
<EditorReadContext.Provider value={state}>
<EditorActionContext.Provider value={dispatch}>{children}</EditorActionContext.Provider>
</EditorReadContext.Provider>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import React, { createContext, useReducer, Dispatch } from 'react';
import { createUseContext } from './create_use_context';
import * as store from '../stores/request';

const RequestReadContext = createContext<store.Store>(null as any);
const RequestActionContext = createContext<Dispatch<store.Actions>>(null as any);
const RequestReadContext = createContext<store.Store>(store.initialValue);
const RequestActionContext = createContext<Dispatch<store.Actions>>(() => {});

export function RequestContextProvider({ children }: { children: React.ReactNode }) {
const [state, dispatch] = useReducer(store.reducer, store.initialValue);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import { notificationServiceMock } from '../../../../../core/public/mocks';
import { httpServiceMock } from '../../../../../core/public/mocks';

import type { ObjectStorageClient } from '../../../common/types';
import { HistoryMock } from '../../services/history.mock';
import { SettingsMock } from '../../services/settings.mock';
import { StorageMock } from '../../services/storage.mock';
Expand All @@ -18,7 +19,7 @@ import { ContextValue } from './services_context';

export const serviceContextMock = {
create: (): ContextValue => {
const storage = new StorageMock({} as any, 'test');
const storage = new StorageMock(({} as unknown) as Storage, 'test');
const http = httpServiceMock.createSetupContract();
const api = createApi({ http });
const esHostService = createEsHostService({ api });
Expand All @@ -31,7 +32,7 @@ export const serviceContextMock = {
settings: new SettingsMock(storage),
history: new HistoryMock(storage),
notifications: notificationServiceMock.createSetupContract(),
objectStorageClient: {} as any,
objectStorageClient: ({} as unknown) as ObjectStorageClient,
},
docLinkVersion: 'NA',
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ export interface ContextValue {

interface ContextProps {
value: ContextValue;
children: any;
children: JSX.Element;
}

const ServicesContext = createContext<ContextValue>(null as any);
const ServicesContext = createContext<ContextValue | null>(null);

export function ServicesContextProvider({ children, value }: ContextProps) {
useEffect(() => {
Expand All @@ -46,8 +46,8 @@ export function ServicesContextProvider({ children, value }: ContextProps) {

export const useServicesContext = () => {
const context = useContext(ServicesContext);
if (context === undefined) {
if (context == null) {
throw new Error('useServicesContext must be used inside the ServicesContextProvider.');
}
return context;
return context!;
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,10 @@
*/

import RowParser from '../../../lib/row_parser';
import { ESRequest } from '../../../types';
import { SenseEditor } from '../../models/sense_editor';
/**
* This function is considered legacy and should not be changed or updated before we have editor
* interfaces in place (it's using a customized version of Ace directly).
*/
export function restoreRequestFromHistory(editor: SenseEditor, req: any) {

export function restoreRequestFromHistory(editor: SenseEditor, req: ESRequest) {
const coreEditor = editor.getCoreEditor();
let pos = coreEditor.getCurrentPosition();
let prefix = '';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@

import { useCallback } from 'react';
import { instance as registry } from '../../contexts/editor_context/editor_registry';
import { ESRequest } from '../../../types';
import { restoreRequestFromHistory } from './restore_request_from_history';

export const useRestoreRequestFromHistory = () => {
return useCallback((req: any) => {
return useCallback((req: ESRequest) => {
const editor = registry.getInputEditor();
restoreRequestFromHistory(editor, req);
}, []);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,14 @@

import { extractWarningMessages } from '../../../lib/utils';
import { XJson } from '../../../../../es_ui_shared/public';
const { collapseLiteralStrings } = XJson;
// @ts-ignore
import * as es from '../../../lib/es/es';
import { BaseResponseType } from '../../../types';

export interface EsRequestArgs {
requests: any;
}
const { collapseLiteralStrings } = XJson;

export interface ESRequestObject {
path: string;
data: any;
method: string;
export interface EsRequestArgs {
requests: Array<{ url: string; method: string; data: string[] }>;
}

export interface ESResponseObject<V = unknown> {
Expand All @@ -32,7 +27,7 @@ export interface ESResponseObject<V = unknown> {
}

export interface ESRequestResult<V = unknown> {
request: ESRequestObject;
request: { data: string; method: string; path: string };
response: ESResponseObject<V>;
}

Expand Down Expand Up @@ -61,7 +56,7 @@ export function sendRequestToES(args: EsRequestArgs): Promise<ESRequestResult[]>
resolve(results);
return;
}
const req = requests.shift();
const req = requests.shift()!;
const esPath = req.url;
const esMethod = req.method;
let esData = collapseLiteralStrings(req.data.join('\n'));
Expand All @@ -71,7 +66,7 @@ export function sendRequestToES(args: EsRequestArgs): Promise<ESRequestResult[]>

const startTime = Date.now();
es.send(esMethod, esPath, esData).always(
(dataOrjqXHR: any, textStatus: string, jqXhrORerrorThrown: any) => {
(dataOrjqXHR, textStatus: string, jqXhrORerrorThrown) => {
if (reqId !== CURRENT_REQ_ID) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ import { SenseEditor } from '../../models/sense_editor';
import { getEndpointFromPosition } from '../../../lib/autocomplete/get_endpoint_from_position';
import { MetricsTracker } from '../../../types';

export const track = (requests: any[], editor: SenseEditor, trackUiMetric: MetricsTracker) => {
export const track = (
requests: Array<{ method: string }>,
editor: SenseEditor,
trackUiMetric: MetricsTracker
) => {
const coreEditor = editor.getCoreEditor();
// `getEndpointFromPosition` gets values from the server-side generated JSON files which
// are a combination of JS, automatically generated JSON and manual overrides. That means
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ import { useSendCurrentRequestToES } from './use_send_current_request_to_es';

describe('useSendCurrentRequestToES', () => {
let mockContextValue: ContextValue;
let dispatch: (...args: any[]) => void;
const contexts = ({ children }: { children?: any }) => (
let dispatch: (...args: unknown[]) => void;
const contexts = ({ children }: { children: JSX.Element }) => (
<ServicesContextProvider value={mockContextValue}>{children}</ServicesContextProvider>
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@
import { useCallback } from 'react';
import { useEditorActionContext } from '../contexts/editor_context';
import { instance as registry } from '../contexts/editor_context/editor_registry';
import { SenseEditor } from '../models';

export const useSetInputEditor = () => {
const dispatch = useEditorActionContext();

return useCallback(
(editor: any) => {
(editor: SenseEditor) => {
dispatch({ type: 'setInputEditor', payload: editor });
registry.setInputEditor(editor);
},
Expand Down
4 changes: 2 additions & 2 deletions src/plugins/console/public/application/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { HttpSetup, NotificationsSetup } from 'src/core/public';
import { HttpSetup, NotificationsSetup, I18nStart } from 'src/core/public';
import { ServicesContextProvider, EditorContextProvider, RequestContextProvider } from './contexts';
import { Main } from './containers';
import { createStorage, createHistory, createSettings } from '../services';
Expand All @@ -20,7 +20,7 @@ import { createApi, createEsHostService } from './lib';
export interface BootDependencies {
http: HttpSetup;
docLinkVersion: string;
I18nContext: any;
I18nContext: I18nStart['Context'];
notifications: NotificationsSetup;
usageCollection?: UsageCollectionSetup;
element: HTMLElement;
Expand Down
Loading

0 comments on commit edfdb78

Please sign in to comment.