Skip to content

Commit

Permalink
Only load default view if there is no state from anywhere else.
Browse files Browse the repository at this point in the history
  • Loading branch information
phillipb committed Jun 26, 2020
1 parent ffd1d40 commit c6d3784
Show file tree
Hide file tree
Showing 12 changed files with 112 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ export const metricsExplorerViewSavedObjectType: SavedObjectsType = {
aggregation: {
type: 'keyword',
},
source: {
type: 'keyword',
},
},
},
chartOptions: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,8 @@ export function SavedViewsToolbarControls<ViewState>(props: Props<ViewState>) {
<EuiDescriptionListDescription>
{currentView
? currentView.name
: i18n.translate('xpack.infra.savedView.defaultView', {
defaultMessage: 'Default view',
: i18n.translate('xpack.infra.savedView.unknownView', {
defaultMessage: 'Unknown',
})}
</EuiDescriptionListDescription>
</EuiDescriptionList>
Expand All @@ -190,6 +190,7 @@ export function SavedViewsToolbarControls<ViewState>(props: Props<ViewState>) {
<EuiListGroupItem
iconType={'refresh'}
onClick={openUpdateModal}
disabled={!currentView || currentView.id === '0'}
label={i18n.translate('xpack.infra.savedView.updateView', {
defaultMessage: 'Update view',
})}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ function isMetricExplorerOptions(subject: any): subject is MetricsExplorerOption
limit: t.number,
groupBy: t.string,
filterQuery: t.string,
source: t.string,
});

const Options = t.intersection([OptionsRequired, OptionsOptional]);
Expand Down Expand Up @@ -156,6 +157,7 @@ const mapToUrlState = (value: any): MetricsExplorerUrlState | undefined => {
const finalState = {};
if (value) {
if (value.options && isMetricExplorerOptions(value.options)) {
value.options.source = 'url';
set(finalState, 'options', value.options);
}
if (value.timerange && isMetricExplorerTimeOption(value.timerange)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export const useSavedView = (props: Props) => {
const setDefault = useCallback(() => {
setCurrentView({
name: i18n.translate('xpack.infra.savedView.defaultViewNameHosts', {
defaultMessage: 'Hosts',
defaultMessage: 'Default view',
}),
id: '0',
isDefault: !defaultViewId || defaultViewId === '0', // If there is no default view then hosts is the default
Expand All @@ -209,11 +209,11 @@ export const useSavedView = (props: Props) => {
useEffect(() => {
const shouldLoadDefault = props.shouldLoadDefault;

if (loadingDefaultView || currentView) {
if (loadingDefaultView || currentView || !shouldLoadDefault) {
return;
}

if (shouldLoadDefault && !currentView && defaultViewId !== '0') {
if (defaultViewId !== '0') {
loadDefaultView();
} else {
setDefault();
Expand Down Expand Up @@ -242,6 +242,7 @@ export const useSavedView = (props: Props) => {
errorOnUpdate,
errorOnFind,
errorOnCreate: createError,
shouldLoadDefault: props.shouldLoadDefault,
makeDefault,
deleteView,
loadingDefaultView,
Expand Down
43 changes: 29 additions & 14 deletions x-pack/plugins/infra/public/pages/metrics/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@

import { i18n } from '@kbn/i18n';

import React from 'react';
import React, { useContext } from 'react';
import { Route, RouteComponentProps, Switch } from 'react-router-dom';

import { EuiErrorBoundary, EuiFlexItem, EuiFlexGroup, EuiButtonEmpty } from '@elastic/eui';
import { IIndexPattern } from 'src/plugins/data/common';
import { DocumentTitle } from '../../components/document_title';
import { HelpCenterContent } from '../../components/help_center_content';
import { RoutedTabs } from '../../components/navigation/routed_tabs';
Expand All @@ -35,6 +36,7 @@ import { WaffleFiltersProvider } from './inventory_view/hooks/use_waffle_filters
import { InventoryAlertDropdown } from '../../alerting/inventory/components/alert_dropdown';
import { MetricsAlertDropdown } from '../../alerting/metric_threshold/components/alert_dropdown';
import { SavedView } from '../../containers/saved_view/saved_view';
import { SourceConfigurationFields } from '../../graphql/types';

const ADD_DATA_LABEL = i18n.translate('xpack.infra.metricsHeaderAddDataButtonLabel', {
defaultMessage: 'Add data',
Expand Down Expand Up @@ -137,19 +139,10 @@ export const InfrastructurePage = ({ match }: RouteComponentProps) => {
<MetricsExplorerOptionsContainer.Provider>
<WithMetricsExplorerOptionsUrlState />
{configuration ? (
<SavedView.Provider
shouldLoadDefault={
true /* TODO need to look at the URL and make sure there is no state already there.*/
}
viewType={'metrics-explorer-view'}
defaultViewState={DEFAULT_METRICS_EXPLORER_VIEW_STATE}
>
<MetricsExplorerPage
derivedIndexPattern={createDerivedIndexPattern('metrics')}
source={configuration}
{...props}
/>
</SavedView.Provider>
<PageContent
configuration={configuration}
createDerivedIndexPattern={createDerivedIndexPattern}
/>
) : (
<SourceLoadingPage />
)}
Expand All @@ -168,3 +161,25 @@ export const InfrastructurePage = ({ match }: RouteComponentProps) => {
</EuiErrorBoundary>
);
};

const PageContent = (props: {
configuration: SourceConfigurationFields.Fragment;
createDerivedIndexPattern: (type: 'logs' | 'metrics' | 'both') => IIndexPattern;
}) => {
const { createDerivedIndexPattern, configuration } = props;
const { options } = useContext(MetricsExplorerOptionsContainer.Context);

return (
<SavedView.Provider
shouldLoadDefault={options.source === 'default'}
viewType={'metrics-explorer-view'}
defaultViewState={DEFAULT_METRICS_EXPLORER_VIEW_STATE}
>
<MetricsExplorerPage
derivedIndexPattern={createDerivedIndexPattern('metrics')}
source={configuration}
{...props}
/>
</SavedView.Provider>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import { SavedViewsToolbarControls } from '../../../../components/saved_views/to

export const Layout = () => {
const { sourceId, source } = useSourceContext();
const { currentView } = useSavedViewContext();
const { currentView, shouldLoadDefault } = useSavedViewContext();
const {
metric,
groupBy,
Expand Down Expand Up @@ -90,11 +90,11 @@ export const Layout = () => {
}, [currentView, onViewChange]);

useEffect(() => {
// load snapshot data after default view loaded
if (currentView != null) {
// load snapshot data after default view loaded, unless we're not loading a view
if (currentView != null || !shouldLoadDefault) {
reload();
}
}, [reload, currentView]);
}, [reload, currentView, shouldLoadDefault]);

return (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export const DEFAULT_WAFFLE_OPTIONS_STATE: WaffleOptionsState = {
steps: 10,
reverseColors: false,
},
source: 'default',
sort: { by: 'name', direction: 'desc' },
};

Expand Down Expand Up @@ -153,36 +154,44 @@ export const WaffleSortOptionRT = rt.type({
direction: rt.keyof({ asc: null, desc: null }),
});

export const WaffleOptionsStateRT = rt.type({
metric: SnapshotMetricInputRT,
groupBy: SnapshotGroupByRT,
nodeType: ItemTypeRT,
view: rt.string,
customOptions: rt.array(
rt.type({
text: rt.string,
field: rt.string,
})
),
boundsOverride: rt.type({
min: rt.number,
max: rt.number,
export const WaffleOptionsStateRT = rt.intersection([
rt.type({
metric: SnapshotMetricInputRT,
groupBy: SnapshotGroupByRT,
nodeType: ItemTypeRT,
view: rt.string,
customOptions: rt.array(
rt.type({
text: rt.string,
field: rt.string,
})
),
boundsOverride: rt.type({
min: rt.number,
max: rt.number,
}),
autoBounds: rt.boolean,
accountId: rt.string,
region: rt.string,
customMetrics: rt.array(SnapshotCustomMetricInputRT),
legend: WaffleLegendOptionsRT,
sort: WaffleSortOptionRT,
}),
autoBounds: rt.boolean,
accountId: rt.string,
region: rt.string,
customMetrics: rt.array(SnapshotCustomMetricInputRT),
legend: WaffleLegendOptionsRT,
sort: WaffleSortOptionRT,
});
rt.partial({ source: rt.string }),
]);

export type WaffleSortOption = rt.TypeOf<typeof WaffleSortOptionRT>;
export type WaffleOptionsState = rt.TypeOf<typeof WaffleOptionsStateRT>;
const encodeUrlState = (state: WaffleOptionsState) => {
return WaffleOptionsStateRT.encode(state);
};
const decodeUrlState = (value: unknown) =>
pipe(WaffleOptionsStateRT.decode(value), fold(constant(undefined), identity));
const decodeUrlState = (value: unknown) => {
const state = pipe(WaffleOptionsStateRT.decode(value), fold(constant(undefined), identity));
if (state) {
state.source = 'url';
}
return state;
};

export const WaffleOptions = createContainer(useWaffleOptions);
export const [WaffleOptionsProvider, useWaffleOptionsContext] = WaffleOptions;
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { Layout } from './components/layout';
import { useLinkProps } from '../../../hooks/use_link_props';
import { SavedView } from '../../../containers/saved_view/saved_view';
import { DEFAULT_WAFFLE_VIEW_STATE } from './hooks/use_waffle_view_state';
import { useHistory } from '../../../utils/history_context';
import { useWaffleOptionsContext } from './hooks/use_waffle_options';

export const SnapshotPage = () => {
const uiCapabilities = useKibana().services.application?.capabilities;
Expand All @@ -39,10 +39,7 @@ export const SnapshotPage = () => {
} = useContext(Source.Context);
useTrackPageview({ app: 'infra_metrics', path: 'inventory' });
useTrackPageview({ app: 'infra_metrics', path: 'inventory', delay: 15000 });

const history = useHistory();
const getQueryStringFromLocation = (location: Location) => location.search.substring(1);
const queryString = history?.location ? getQueryStringFromLocation(history.location) : '';
const { source: optionsSource } = useWaffleOptionsContext();

const tutorialLinkProps = useLinkProps({
app: 'home',
Expand All @@ -68,7 +65,7 @@ export const SnapshotPage = () => {
<>
<FilterBar />
<SavedView.Provider
shouldLoadDefault={!queryString}
shouldLoadDefault={optionsSource === 'default'}
viewType={'inventory-view'}
defaultViewState={DEFAULT_WAFFLE_VIEW_STATE}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ export interface MetricExplorerViewState {

export const useMetricsExplorerState = (
source: SourceQuery.Query['source']['configuration'],
derivedIndexPattern: IIndexPattern
derivedIndexPattern: IIndexPattern,
shouldLoadImmediately = true
) => {
const [refreshSignal, setRefreshSignal] = useState(0);
const [afterKey, setAfterKey] = useState<string | null | Record<string, string | null>>(null);
Expand All @@ -40,13 +41,15 @@ export const useMetricsExplorerState = (
setTimeRange,
setOptions,
} = useContext(MetricsExplorerOptionsContainer.Context);
const { loading, error, data } = useMetricsExplorerData(
const { loading, error, data, loadData } = useMetricsExplorerData(
options,
source,
derivedIndexPattern,
currentTimerange,
afterKey,
refreshSignal
refreshSignal,
undefined,
shouldLoadImmediately
);

const handleRefresh = useCallback(() => {
Expand Down Expand Up @@ -144,7 +147,7 @@ export const useMetricsExplorerState = (
handleLoadMore: setAfterKey,
defaultViewState,
onViewStateChange,

loadData,
refreshSignal,
afterKey,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import DateMath from '@elastic/datemath';
import { isEqual } from 'lodash';
import { useEffect, useState } from 'react';
import { useEffect, useState, useCallback } from 'react';
import { HttpHandler } from 'src/core/public';
import { IIndexPattern } from 'src/plugins/data/public';
import { SourceQuery } from '../../../../../common/graphql/types';
Expand All @@ -30,7 +30,8 @@ export function useMetricsExplorerData(
timerange: MetricsExplorerTimeOptions,
afterKey: string | null | Record<string, string | null>,
signal: any,
fetch?: HttpHandler
fetch?: HttpHandler,
shouldLoadImmediately = true
) {
const kibana = useKibana();
const fetchFn = fetch ? fetch : kibana.services.http?.fetch;
Expand All @@ -40,7 +41,7 @@ export function useMetricsExplorerData(
const [lastOptions, setLastOptions] = useState<MetricsExplorerOptions | null>(null);
const [lastTimerange, setLastTimerange] = useState<MetricsExplorerTimeOptions | null>(null);

useEffect(() => {
const loadData = useCallback(() => {
(async () => {
setLoading(true);
try {
Expand Down Expand Up @@ -112,9 +113,15 @@ export function useMetricsExplorerData(
}
setLoading(false);
})();

// TODO: fix this dependency list while preserving the semantics
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [options, source, timerange, signal, afterKey]);
return { error, loading, data };

useEffect(() => {
if (!shouldLoadImmediately) {
return;
}

loadData();
}, [loadData, shouldLoadImmediately]);
return { error, loading, data, loadData };
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export interface MetricsExplorerOptions {
aggregation: MetricsExplorerAggregation;
forceInterval?: boolean;
dropLastBucket?: boolean;
source?: string;
}

export interface MetricsExplorerTimeOptions {
Expand Down Expand Up @@ -83,6 +84,7 @@ export const DEFAULT_METRICS: MetricsExplorerOptionsMetric[] = [
export const DEFAULT_OPTIONS: MetricsExplorerOptions = {
aggregation: 'avg',
metrics: DEFAULT_METRICS,
source: 'default',
};

export const DEFAULT_METRICS_EXPLORER_VIEW_STATE = {
Expand Down
Loading

0 comments on commit c6d3784

Please sign in to comment.