Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,21 @@ export const sloDetailsHistoryLocatorID = 'SLO_DETAILS_HISTORY_LOCATOR';
export const sloEditLocatorID = 'SLO_EDIT_LOCATOR';
export const sloListLocatorID = 'SLO_LIST_LOCATOR';

export const OVERVIEW_TAB_ID = 'overview';
export const HISTORY_TAB_ID = 'history';
export const DEFINITION_TAB_ID = 'definition';
export const ALERTS_TAB_ID = 'alerts';

export type SloTabId =
| typeof OVERVIEW_TAB_ID
| typeof ALERTS_TAB_ID
| typeof HISTORY_TAB_ID
| typeof DEFINITION_TAB_ID;

export interface SloDetailsLocatorParams extends SerializableRecord {
sloId?: string;
sloId: string;
instanceId?: string;
tabId?: SloTabId;
}

export interface SloDetailsHistoryLocatorParams extends SerializableRecord {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,10 @@ import {
import { i18n } from '@kbn/i18n';
import type { SLOWithSummaryResponse } from '@kbn/slo-schema';
import React, { useState } from 'react';
import type { SloTabId } from '@kbn/deeplinks-observability';
import { OVERVIEW_TAB_ID } from '@kbn/deeplinks-observability';
import { HeaderTitle } from '../../../pages/slo_details/components/header_title';
import type { SloTabId } from '../../../pages/slo_details/components/slo_details';
import { OVERVIEW_TAB_ID, SloDetails } from '../../../pages/slo_details/components/slo_details';
import { SloDetails } from '../../../pages/slo_details/components/slo_details';
import { useSloDetailsTabs } from '../../../pages/slo_details/hooks/use_slo_details_tabs';
import { getSloFormattedSummary } from '../../../pages/slos/hooks/use_slo_summary';
import { useKibana } from '../../../hooks/use_kibana';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,6 @@ import { SloDetailsLocatorDefinition } from './slo_details';
describe('SloDetailsLocator', () => {
const locator = new SloDetailsLocatorDefinition();

it('returns correct url when empty params are provided', async () => {
const location = await locator.getLocation({});
expect(location.app).toEqual('slo');
expect(location.path).toEqual('/');
});

it('returns correct url when sloId is provided', async () => {
const location = await locator.getLocation({ sloId: 'foo' });
expect(location.path).toEqual('/foo');
Expand All @@ -36,4 +30,21 @@ describe('SloDetailsLocator', () => {
});
expect(location.path).toEqual('/some-slo_id');
});

it('returns correct url when instanceId and tabId are specified', async () => {
const location = await locator.getLocation({
sloId: 'slo_id',
instanceId: 'instance_id',
tabId: 'history',
});
expect(location.path).toEqual('/slo_id/history?instanceId=instance_id');
});

it('returns correct url when tabId is specified', async () => {
const location = await locator.getLocation({
sloId: 'slo_id',
tabId: 'history',
});
expect(location.path).toEqual('/slo_id/history');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ import { ALL_VALUE } from '@kbn/slo-schema/src/schema/common';
export class SloDetailsLocatorDefinition implements LocatorDefinition<SloDetailsLocatorParams> {
public readonly id = sloDetailsLocatorID;

public readonly getLocation = async ({ sloId, instanceId }: SloDetailsLocatorParams) => {
const queryParams =
!!instanceId && instanceId !== ALL_VALUE
? `?instanceId=${encodeURIComponent(instanceId)}`
: '';
const path = !!sloId ? `/${encodeURIComponent(sloId)}${queryParams}` : '/';
public readonly getLocation = async ({ sloId, instanceId, tabId }: SloDetailsLocatorParams) => {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kdelemme I saw you had refactored the locator here, so I decided to bring that part as well

const qs = new URLSearchParams();
if (!!instanceId && instanceId !== ALL_VALUE) qs.append('instanceId', instanceId);

let path = `/${encodeURIComponent(sloId)}${formatQueryParams(qs)}`;
if (tabId) {
path = `/${encodeURIComponent(sloId)}/${tabId}${formatQueryParams(qs)}`;
}

return {
app: 'slo',
Expand All @@ -26,3 +28,10 @@ export class SloDetailsLocatorDefinition implements LocatorDefinition<SloDetails
};
};
}

function formatQueryParams(qs: URLSearchParams): string {
if (qs.size === 0) {
return '';
}
return `?${qs.toString()}`;
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,62 +7,61 @@

import { EuiButton, EuiFlexGroup, EuiText } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import type { SLOWithSummaryResponse } from '@kbn/slo-schema';
import moment from 'moment';
import React, { useState } from 'react';
import { toDuration } from '../../../../utils/slo/duration';
import React from 'react';
import type { TimeBounds } from '../../types';

interface Props {
slo: SLOWithSummaryResponse;
period: 'week' | 'month';
range: TimeBounds;
onChange: (range: TimeBounds) => void;
}

export function CalendarPeriodPicker({ slo, onChange }: Props) {
const [periodOffset, setPeriodOffset] = useState<number>(0);
export function CalendarPeriodPicker({ period, range, onChange }: Props) {
const isWeeklyPeriod = period === 'week';
const durationUnit = isWeeklyPeriod ? 'week' : 'month';
const unit = isWeeklyPeriod ? 'isoWeek' : 'month';

function handleChangePeriod(offset: number) {
const now = moment();
const duration = toDuration(slo.timeWindow.duration);
const unit = duration.unit === 'w' ? 'isoWeek' : 'month';
const durationUnit = duration.unit === 'w' ? 'week' : 'month';

setPeriodOffset((curr) => {
const newOffset = curr + offset;

onChange({
from: moment.utc(now).subtract(newOffset, durationUnit).startOf(unit).toDate(),
to: moment.utc(now).subtract(newOffset, durationUnit).endOf(unit).toDate(),
});
function handlePrevious() {
const start = moment.utc(range.from).subtract(1, durationUnit);
onChange({
from: start.startOf(unit).toDate(),
to: start.endOf(unit).toDate(),
});
}

return newOffset;
function handleNext() {
const start = moment.utc(range.from).add(1, durationUnit);
onChange({
from: start.startOf(unit).toDate(),
to: start.endOf(unit).toDate(),
});
}

function getCalendarPeriodLabel() {
const start = moment.utc(range.from);
return `${start.startOf(unit).format('ll')} - ${start.endOf(unit).format('ll')}`;
}

return (
<EuiFlexGroup direction="row" justifyContent="spaceEvenly" alignItems="center">
<EuiButton
size="s"
data-test-subj="sloSloDetailsHistoryPreviousButton"
onClick={() => {
handleChangePeriod(+1);
}}
onClick={() => handlePrevious()}
iconType="arrowLeft"
>
{i18n.translate('xpack.slo.sloDetailsHistory.previousPeriodButtonLabel', {
defaultMessage: 'Previous',
})}
</EuiButton>
<EuiText size="s" textAlign="center">
<p>{getCalendarPeriodLabel(slo, periodOffset)}</p>
<p>{getCalendarPeriodLabel()}</p>
</EuiText>
<EuiButton
size="s"
data-test-subj="sloSloDetailsHistoryNextButton"
disabled={periodOffset <= 0}
onClick={() => {
handleChangePeriod(-1);
}}
onClick={() => handleNext()}
iconType="arrowRight"
iconSide="right"
>
Expand All @@ -73,20 +72,3 @@ export function CalendarPeriodPicker({ slo, onChange }: Props) {
</EuiFlexGroup>
);
}

function getCalendarPeriodLabel(slo: SLOWithSummaryResponse, calendarPeriod: number): string {
const duration = toDuration(slo.timeWindow.duration);
const isWeeklyCalendarAligned = duration.unit === 'w';
const now = moment().utc();

const start = now
.clone()
.subtract(calendarPeriod, isWeeklyCalendarAligned ? 'week' : 'month')
.startOf(isWeeklyCalendarAligned ? 'isoWeek' : 'month');
const end = now
.clone()
.subtract(calendarPeriod, isWeeklyCalendarAligned ? 'week' : 'month')
.endOf(isWeeklyCalendarAligned ? 'isoWeek' : 'month');

return `${start.format('ll')} - ${end.format('ll')}`;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import DateMath from '@kbn/datemath';
import { createKbnUrlStateStorage } from '@kbn/kibana-utils-plugin/public';
import type { SLODefinitionResponse, SLOWithSummaryResponse } from '@kbn/slo-schema';
import type { RecursivePartial } from '@kbn/utility-types';
import deepmerge from 'deepmerge';
import moment from 'moment';
import { useEffect, useRef, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { toDuration } from '../../../../../utils/slo/duration';

const SLO_HISTORY_URL_STORAGE_KEY = '_a';

interface AppState {
range: {
from: Date;
to: Date;
};
}

interface SerializedAppState {
range: {
from: string;
to: string;
};
}

const DEFAULT_STATE: AppState = {
range: {
from: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
to: new Date(),
},
};

export function useUrlAppState(slo: SLOWithSummaryResponse | SLODefinitionResponse): {
state: AppState;
updateState: (state: AppState) => void;
} {
const [state, setState] = useState<AppState>(() => {
const initialState = {
...DEFAULT_STATE,
range: getDefaultRangeFromSlo(slo),
};
return initialState;
});

const history = useHistory();
const urlStateStorage = useRef(
createKbnUrlStateStorage({
history,
useHash: false,
useHashQuery: false,
})
);

useEffect(() => {
setState(
toAppState(
urlStateStorage.current?.get<SerializedAppState>(SLO_HISTORY_URL_STORAGE_KEY) ?? {},
slo
)
);
}, [urlStateStorage, slo]);

const updateState = (newState: AppState) => {
setState((prevState) => {
const updatedState = deepmerge(prevState, newState);
urlStateStorage.current?.set(SLO_HISTORY_URL_STORAGE_KEY, updatedState, {
replace: true,
});

return updatedState;
});
};

return {
state: deepmerge(DEFAULT_STATE, state),
updateState,
};
}

function getDefaultRangeFromSlo(
slo: SLOWithSummaryResponse | SLODefinitionResponse
): AppState['range'] {
if (slo.timeWindow.type === 'calendarAligned') {
const now = moment();
const duration = toDuration(slo.timeWindow.duration);
const unit = duration.unit === 'w' ? 'isoWeek' : 'month';

return {
from: moment.utc(now).startOf(unit).toDate(),
to: moment.utc(now).endOf(unit).toDate(),
};
}

return {
from: new Date(DateMath.parse(`now-${slo.timeWindow.duration}`)!.valueOf()),
to: new Date(DateMath.parse('now', { roundUp: true })!.valueOf()),
};
}

function toAppState(
urlState: RecursivePartial<SerializedAppState>,
slo: SLOWithSummaryResponse | SLODefinitionResponse
): AppState {
return {
...DEFAULT_STATE,
range:
urlState.range && urlState.range.from && urlState.range.to
? {
from: new Date(urlState.range.from),
to: new Date(urlState.range.to),
}
: getDefaultRangeFromSlo(slo),
};
}
Loading