Skip to content

Commit

Permalink
Impove page url state types.
Browse files Browse the repository at this point in the history
  • Loading branch information
walterra committed Dec 27, 2022
1 parent 65f6884 commit 2f84808
Show file tree
Hide file tree
Showing 16 changed files with 112 additions and 31 deletions.
25 changes: 15 additions & 10 deletions x-pack/packages/ml/url_state/src/url_state.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -228,16 +228,21 @@ export class PageUrlStateService<T> {
}
}

interface PageUrlState {
pageKey: string;
pageUrlState: object;
}

/**
* Hook for managing the URL state of the page.
*/
export const usePageUrlState = <PageUrlState extends object>(
pageKey: string,
defaultState?: PageUrlState
export const usePageUrlState = <T extends PageUrlState>(
pageKey: T['pageKey'],
defaultState?: T['pageUrlState']
): [
PageUrlState,
(update: Partial<PageUrlState>, replaceState?: boolean) => void,
PageUrlStateService<PageUrlState>
T['pageUrlState'],
(update: Partial<T['pageUrlState']>, replaceState?: boolean) => void,
PageUrlStateService<T['pageUrlState']>
] => {
const [appState, setAppState] = useUrlState('_a');
const pageState = appState?.[pageKey];
Expand All @@ -248,9 +253,9 @@ export const usePageUrlState = <PageUrlState extends object>(
setCallback.current = setAppState;
}, [setAppState]);

const prevPageState = useRef<PageUrlState | undefined>();
const prevPageState = useRef<T['pageUrlState'] | undefined>();

const resultPageState: PageUrlState = useMemo(() => {
const resultPageState: T['pageUrlState'] = useMemo(() => {
const result = {
...(defaultState ?? {}),
...(pageState ?? {}),
Expand All @@ -276,7 +281,7 @@ export const usePageUrlState = <PageUrlState extends object>(
}, [pageState]);

const onStateUpdate = useCallback(
(update: Partial<PageUrlState>, replaceState?: boolean) => {
(update: Partial<T['pageUrlState']>, replaceState?: boolean) => {
if (!setCallback?.current) {
throw new Error('Callback for URL state update has not been initialized.');
}
Expand All @@ -293,7 +298,7 @@ export const usePageUrlState = <PageUrlState extends object>(
[pageKey, resultPageState]
);

const pageUrlStateService = useMemo(() => new PageUrlStateService<PageUrlState>(), []);
const pageUrlStateService = useMemo(() => new PageUrlStateService<T['pageUrlState']>(), []);

useEffect(
function updatePageUrlService() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ import { type TimeBuckets, TimeBucketsInterval } from '../../../common/time_buck
import { useDataSource } from '../../hooks/use_data_source';
import { useTimeBuckets } from '../../hooks/use_time_buckets';

export interface ChangePointDetectionPageUrlState {
pageKey: 'changePoint';
pageUrlState: ChangePointDetectionRequestParams;
}

export interface ChangePointDetectionRequestParams {
fn: string;
splitField: string;
Expand Down Expand Up @@ -157,7 +162,7 @@ export const ChangePointDetectionContextProvider: FC = ({ children }) => {
}, [dataView]);

const [requestParamsFromUrl, updateRequestParams] =
usePageUrlState<ChangePointDetectionRequestParams>('changePoint');
usePageUrlState<ChangePointDetectionPageUrlState>('changePoint');

const resultQuery = useMemo<Query>(() => {
return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ const defaultSearchQuery = {
match_all: {},
};

export interface AiOpsPageUrlState {
pageKey: 'AIOPS_INDEX_VIEWER';
pageUrlState: AiOpsIndexBasedAppState;
}

export interface AiOpsIndexBasedAppState {
searchString?: Query['query'];
searchQuery?: Query['query'];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import { DocumentCountContent } from '../document_count_content/document_count_c
import { DatePickerWrapper } from '../date_picker_wrapper';
import { SearchPanel } from '../search_panel';

import { restorableDefaults } from './explain_log_rate_spikes_app_state';
import { restorableDefaults, type AiOpsPageUrlState } from './explain_log_rate_spikes_app_state';
import { ExplainLogRateSpikesAnalysis } from './explain_log_rate_spikes_analysis';
import type { GroupTableItem } from '../spike_analysis_table/types';
import { useSpikeAnalysisTableRowContext } from '../spike_analysis_table/spike_analysis_table_row_provider';
Expand Down Expand Up @@ -79,7 +79,7 @@ export const ExplainLogRateSpikesPage: FC<ExplainLogRateSpikesPageProps> = ({
setSelectedGroup,
} = useSpikeAnalysisTableRowContext();

const [aiopsListState, setAiopsListState] = usePageUrlState(
const [aiopsListState, setAiopsListState] = usePageUrlState<AiOpsPageUrlState>(
'AIOPS_INDEX_VIEWER',
restorableDefaults
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ import type { TotalFieldsStats } from '../../../common/components/stats_table/co
import { OverallStats } from '../../types/overall_stats';
import { IndexBasedDataVisualizerExpandedRow } from '../../../common/components/expanded_row/index_based_expanded_row';
import { DATA_VISUALIZER_INDEX_VIEWER } from '../../constants/index_data_visualizer_viewer';
import { DataVisualizerIndexBasedAppState } from '../../types/index_data_visualizer_state';
import {
DataVisualizerIndexBasedAppState,
DataVisualizerIndexBasedPageUrlState,
} from '../../types/index_data_visualizer_state';
import { SEARCH_QUERY_LANGUAGE, SearchQueryLanguage } from '../../types/combined_query';
import { SupportedFieldType, SavedSearchSavedObject } from '../../../../../common/types';
import { useDataVisualizerKibana } from '../../../kibana_context';
Expand Down Expand Up @@ -143,10 +146,11 @@ export const IndexDataVisualizerView: FC<IndexDataVisualizerViewProps> = (dataVi
const { notifications, uiSettings, data } = services;
const { toasts } = notifications;

const [dataVisualizerListState, setDataVisualizerListState] = usePageUrlState(
DATA_VISUALIZER_INDEX_VIEWER,
restorableDefaults
);
const [dataVisualizerListState, setDataVisualizerListState] =
usePageUrlState<DataVisualizerIndexBasedPageUrlState>(
DATA_VISUALIZER_INDEX_VIEWER,
restorableDefaults
);
const [globalState, setGlobalState] = useUrlState('_g');

const [currentSavedSearch, setCurrentSavedSearch] = useState(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,22 @@ import type { Filter } from '@kbn/es-query';
import type { Query } from '@kbn/data-plugin/common/query';
import type { RandomSamplerOption } from '../constants/random_sampler';
import type { SearchQueryLanguage } from './combined_query';

import type { DATA_VISUALIZER_INDEX_VIEWER } from '../constants/index_data_visualizer_viewer';

export interface DataVisualizerIndexBasedPageUrlState {
pageKey: typeof DATA_VISUALIZER_INDEX_VIEWER;
pageUrlState: Required<DataVisualizerIndexBasedAppState>;
}

export interface ListingPageUrlState {
pageSize: number;
pageIndex: number;
sortField: string;
sortDirection: string;
queryText?: string;
}

export interface DataVisualizerIndexBasedAppState extends Omit<ListingPageUrlState, 'queryText'> {
searchString?: Query['query'];
searchQuery?: Query['query'];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ import { EuiIcon, EuiSelect, EuiToolTip } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { usePageUrlState } from '@kbn/ml-url-state';

interface TableIntervalPageUrlState {
pageKey: 'mlSelectInterval';
pageUrlState: TableInterval;
}

export interface TableInterval {
display: string;
val: string;
Expand Down Expand Up @@ -55,7 +60,7 @@ function optionValueToInterval(value: string) {
export const TABLE_INTERVAL_DEFAULT = optionValueToInterval('auto');

export const useTableInterval = (): [TableInterval, (v: TableInterval) => void] => {
const [interval, updateCallback] = usePageUrlState<TableInterval>(
const [interval, updateCallback] = usePageUrlState<TableIntervalPageUrlState>(
'mlSelectInterval',
TABLE_INTERVAL_DEFAULT
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ const optionsMap = {
[criticalLabel]: ANOMALY_THRESHOLD.CRITICAL,
};

export interface TableSeverityPageUrlState {
pageKey: 'mlSelectSeverity';
pageUrlState: TableSeverity;
}

export interface TableSeverity {
val: number;
display: string;
Expand Down Expand Up @@ -83,7 +88,7 @@ export function optionValueToThreshold(value: number) {
const TABLE_SEVERITY_DEFAULT = SEVERITY_OPTIONS[0];

export const useTableSeverity = () => {
return usePageUrlState<TableSeverity>('mlSelectSeverity', TABLE_SEVERITY_DEFAULT);
return usePageUrlState<TableSeverityPageUrlState>('mlSelectSeverity', TABLE_SEVERITY_DEFAULT);
};

export const getSeverityOptions = () =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,13 @@ export function getDefaultExplorationPageUrlState(
};
}

interface UsePageUrlState {
pageKey: typeof ML_PAGES.DATA_FRAME_ANALYTICS_EXPLORATION;
pageUrlState: ExplorationPageUrlState;
}

export function useExplorationUrlState(overrides?: Partial<ExplorationPageUrlState>) {
return usePageUrlState<ExplorationPageUrlState>(
return usePageUrlState<UsePageUrlState>(
ML_PAGES.DATA_FRAME_ANALYTICS_EXPLORATION,
getDefaultExplorationPageUrlState(overrides)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ import { useMlKibana } from '../../../contexts/kibana';
import { useRefreshAnalyticsList } from '../../common';
import { MlPageHeader } from '../../../components/page_header';

interface PageUrlState {
pageKey: typeof ML_PAGES.DATA_FRAME_ANALYTICS_JOBS_MANAGE;
pageUrlState: ListingPageUrlState;
}

export const getDefaultDFAListState = (): ListingPageUrlState => ({
pageIndex: 0,
pageSize: 10,
Expand All @@ -35,7 +40,7 @@ export const Page: FC = () => {
const [blockRefresh, setBlockRefresh] = useState(false);
const [globalState] = useUrlState('_g');

const [dfaPageState, setDfaPageState] = usePageUrlState(
const [dfaPageState, setDfaPageState] = usePageUrlState<PageUrlState>(
ML_PAGES.DATA_FRAME_ANALYTICS_JOBS_MANAGE,
getDefaultDFAListState()
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,24 @@ import { ML_PAGES } from '../../../../common/constants/locator';

export type AnomalyExplorerUrlStateService = PageUrlStateService<ExplorerAppState>;

interface LegacyExplorerPageUrlState {
pageKey: 'mlExplorerSwimlane';
pageUrlState: ExplorerAppState['mlExplorerSwimlane'];
}

interface ExplorerPageUrlState {
pageKey: typeof ML_PAGES.ANOMALY_EXPLORER;
pageUrlState: ExplorerAppState;
}

export function useExplorerUrlState() {
/**
* Originally `mlExplorerSwimlane` resided directly in the app URL state (`_a` URL state key).
* With current URL structure it has been moved under the `explorer` key of the app state (_a).
*/
const [legacyExplorerState] =
usePageUrlState<ExplorerAppState['mlExplorerSwimlane']>('mlExplorerSwimlane');
const [legacyExplorerState] = usePageUrlState<LegacyExplorerPageUrlState>('mlExplorerSwimlane');

return usePageUrlState<ExplorerAppState>(ML_PAGES.ANOMALY_EXPLORER, {
return usePageUrlState<ExplorerPageUrlState>(ML_PAGES.ANOMALY_EXPLORER, {
mlExplorerSwimlane: legacyExplorerState,
mlExplorerFilter: {},
});
Expand Down
8 changes: 6 additions & 2 deletions x-pack/plugins/ml/public/application/jobs/jobs_list/jobs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

import React, { FC } from 'react';
import { FormattedMessage } from '@kbn/i18n-react';
// @ts-ignore
import { usePageUrlState } from '@kbn/ml-url-state';
import { JobsListView } from './components/jobs_list_view';
import { ML_PAGES } from '../../../../common/constants/locator';
Expand All @@ -18,6 +17,11 @@ import { MlPageHeader } from '../../components/page_header';
import { HeaderMenuPortal } from '../../components/header_menu_portal';
import { JobsActionMenu } from '../components/jobs_action_menu';

interface PageUrlState {
pageKey: typeof ML_PAGES.ANOMALY_DETECTION_JOBS_MANAGE;
pageUrlState: ListingPageUrlState;
}

interface JobsPageProps {
isMlEnabledInSpace?: boolean;
lastRefresh?: number;
Expand All @@ -31,7 +35,7 @@ export const getDefaultAnomalyDetectionJobsListState = (): ListingPageUrlState =
});

export const JobsPage: FC<JobsPageProps> = ({ isMlEnabledInSpace, lastRefresh }) => {
const [pageState, setPageState] = usePageUrlState(
const [pageState, setPageState] = usePageUrlState<PageUrlState>(
ML_PAGES.ANOMALY_DETECTION_JOBS_MANAGE,
getDefaultAnomalyDetectionJobsListState()
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ const levelBadgeMap: Record<MlNotificationMessageLevel, IconColor> = {
[ML_NOTIFICATIONS_MESSAGE_LEVEL.INFO]: 'default',
};

interface PageUrlState {
pageKey: typeof ML_PAGES.NOTIFICATIONS;
pageUrlState: ListingPageUrlState;
}

export const getDefaultNotificationsListState = (): ListingPageUrlState => ({
pageIndex: 0,
pageSize: 25,
Expand Down Expand Up @@ -81,7 +86,7 @@ export const NotificationsList: FC = () => {

const dateFormatter = useFieldFormatter(FIELD_FORMAT_IDS.DATE);

const [pageState, updatePageState] = usePageUrlState(
const [pageState, updatePageState] = usePageUrlState<PageUrlState>(
ML_PAGES.NOTIFICATIONS,
getDefaultNotificationsListState()
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ import { usePageUrlState } from '@kbn/ml-url-state';
import { TimeSeriesExplorerAppState } from '../../../../common/types/locator';
import { ML_PAGES } from '../../../../common/constants/locator';

interface TimeSeriesExplorerPageUrlState {
pageKey: typeof ML_PAGES.SINGLE_METRIC_VIEWER;
pageUrlState: TimeSeriesExplorerAppState;
}

export function useTimeSeriesExplorerUrlState() {
return usePageUrlState<TimeSeriesExplorerAppState>(ML_PAGES.SINGLE_METRIC_VIEWER);
return usePageUrlState<TimeSeriesExplorerPageUrlState>(ML_PAGES.SINGLE_METRIC_VIEWER);
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ export type ModelItem = TrainedModelConfigResponse & {

export type ModelItemFull = Required<ModelItem>;

interface PageUrlState {
pageKey: typeof ML_PAGES.TRAINED_MODELS_MANAGE;
pageUrlState: ListingPageUrlState;
}

export const getDefaultModelsListState = (): ListingPageUrlState => ({
pageIndex: 0,
pageSize: 10,
Expand Down Expand Up @@ -88,7 +93,7 @@ export const ModelsList: FC<Props> = ({
// allow for an internally controlled page state which stores the state in the URL
// or an external page state, which is passed in as a prop.
// external page state is used on the management page.
const [pageStateInternal, updatePageStateInternal] = usePageUrlState(
const [pageStateInternal, updatePageStateInternal] = usePageUrlState<PageUrlState>(
ML_PAGES.TRAINED_MODELS_MANAGE,
getDefaultModelsListState()
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ import { useRefresh } from '../../routing/use_refresh';

export type NodeItem = NodeDeploymentStatsResponse;

interface PageUrlState {
pageKey: typeof ML_PAGES.TRAINED_MODELS_NODES;
pageUrlState: ListingPageUrlState;
}

export const getDefaultNodesListState = (): ListingPageUrlState => ({
pageIndex: 0,
pageSize: 10,
Expand All @@ -55,7 +60,7 @@ export const NodesList: FC<NodesListProps> = ({ compactView = false }) => {
const [itemIdToExpandedRowMap, setItemIdToExpandedRowMap] = useState<Record<string, JSX.Element>>(
{}
);
const [pageState, updatePageState] = usePageUrlState(
const [pageState, updatePageState] = usePageUrlState<PageUrlState>(
ML_PAGES.TRAINED_MODELS_NODES,
getDefaultNodesListState()
);
Expand Down

0 comments on commit 2f84808

Please sign in to comment.