Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add default view option #137

Merged
merged 21 commits into from
Oct 24, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

- Add yearly view (#134)
- Add internationalization(Spanish, French, German, and Chinese) i18n (#135)
- Add default view option (#137)

## 2.2.0 (2023-10-06)

Expand Down
2 changes: 1 addition & 1 deletion src/components/BigCalendar/BigCalendar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export const BigCalendar: React.FC<Props> = ({ height, events, timeRange, onChan
/**
* Manage calendar time range and view
*/
const { date, view, onChangeView, onNavigate } = useCalendarRange(timeRange, onChangeTimeRange);
const { date, view, onChangeView, onNavigate } = useCalendarRange(timeRange, onChangeTimeRange, options.defaultView);

/**
* Is Selected View Exist
Expand Down
177 changes: 177 additions & 0 deletions src/components/DefaultViewEditor/DefaultViewEditor.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { getJestSelectors } from '@volkovlabs/jest-selectors';
import React from 'react';
import { DefaultView, TestIds } from '../../constants';
import { View } from '../../types';
import { DefaultViewEditor } from './DefaultViewEditor';

/**
* Mock @grafana/ui
*/
jest.mock('@grafana/ui', () => ({
Select: jest.fn(({ options, onChange, value, ...restProps }) => (
<select
onChange={(event: any) => {
if (onChange) {
const option = options.find((option: any) => {
/**
* Jest convert number to string, so just using not strict comparison
*/
// eslint-disable-next-line eqeqeq
return option.value == event.target.value;
});

if (option) {
onChange(option);
}
}
}}
/**
* Fix jest warnings because null value.
* For Select component in @grafana/ui should be used null to reset value.
*/
value={value === null ? '' : value}
{...restProps}
>
{options.map(({ label, value }: any) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
)),
}));

/**
* Component Props
*/
type Props = React.ComponentProps<typeof DefaultViewEditor>;

/**
* Default View Editor
*/
describe('Default View Editor', () => {
/**
* Selectors
*/
const getSelectors = getJestSelectors(TestIds.defaultViewEditor);
const selectors = getSelectors(screen);

/**
* Get Tested Component
* @param props
*/
const getComponent = (props: Partial<Props>) => {
return <DefaultViewEditor {...(props as any)} />;
};

it('Should update value', () => {
const onChange = jest.fn();

render(
getComponent({
value: View.YEAR,
context: { options: { views: [View.MONTH, View.YEAR] } as any } as any,
onChange,
})
);

expect(selectors.field()).toHaveValue(View.YEAR);

/**
* Change value
*/
fireEvent.change(selectors.field(), { target: { value: View.MONTH } });

expect(onChange).toHaveBeenCalledWith(View.MONTH);
});

it('Should filter available options', () => {
const onChange = jest.fn();

render(
getComponent({
value: View.YEAR,
context: { options: { views: [View.MONTH, View.YEAR] } as any } as any,
onChange,
})
);

expect(selectors.field()).toHaveValue(View.YEAR);

/**
* Change on unavailable value
*/
fireEvent.change(selectors.field(), { target: { value: View.DAY } });

expect(onChange).not.toHaveBeenCalled();
});

it('Should use first available option if value unavailable ', () => {
const onChange = jest.fn();

const { rerender } = render(
getComponent({
value: View.YEAR,
context: { options: { views: [View.WEEK, View.YEAR] } as any } as any,
onChange,
})
);

expect(selectors.field()).toHaveValue(View.YEAR);

/**
* Re-render
*/
rerender(
getComponent({
value: View.YEAR,
context: { options: { views: [View.WEEK] } as any } as any,
onChange,
})
);

expect(onChange).toHaveBeenCalledWith(View.WEEK);
});

it('Should not use first available option if value available ', () => {
const onChange = jest.fn();

const { rerender } = render(
getComponent({
value: View.YEAR,
context: { options: { views: [View.WEEK, View.YEAR] } as any } as any,
onChange,
})
);

expect(selectors.field()).toHaveValue(View.YEAR);

/**
* Re-render
*/
rerender(
getComponent({
value: View.YEAR,
context: { options: { views: [View.YEAR] } as any } as any,
onChange,
})
);

expect(onChange).not.toHaveBeenCalled();
});

it('Should use default value if no options', () => {
const onChange = jest.fn();

render(
getComponent({
value: View.YEAR,
context: { options: { views: [] } as any } as any,
onChange,
})
);

expect(onChange).toHaveBeenCalledWith(DefaultView);
});
});
50 changes: 50 additions & 0 deletions src/components/DefaultViewEditor/DefaultViewEditor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import React, { useEffect, useMemo } from 'react';
import { StandardEditorProps } from '@grafana/data';
import { Select } from '@grafana/ui';
import { useTranslation } from 'react-i18next';
import { CalendarViewOptions, DefaultView, TestIds } from '../../constants';
import { CalendarOptions, View } from '../../types';

/**
* Properties
*/
interface Props extends StandardEditorProps<View, null, CalendarOptions> {}

/**
* Default View Editor
*/
export const DefaultViewEditor: React.FC<Props> = ({ onChange, value, context }) => {
/**
* Translation
*/
const { t } = useTranslation();

/**
* Available options
*/
const options = useMemo(() => {
const allOptions = CalendarViewOptions(t);

return allOptions.filter((option) => context.options?.views?.includes(option.value));
}, [context.options?.views, t]);

/**
* Use first option if selectedValue is unavailable
*/
useEffect(() => {
if (!options.some((option) => option.value === value)) {
onChange(options[0]?.value || DefaultView);
}
}, [onChange, options, value]);

return (
<Select
onChange={(event) => {
onChange(event.value);
}}
options={options}
value={value}
aria-label={TestIds.defaultViewEditor.field}
/>
);
};
1 change: 1 addition & 0 deletions src/components/DefaultViewEditor/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './DefaultViewEditor';
3 changes: 2 additions & 1 deletion src/components/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './BigToolbar';
export * from './CalendarPanel';
export * from './DefaultViewEditor';
export * from './MultiFieldEditor';
export * from './BigToolbar';
5 changes: 5 additions & 0 deletions src/constants/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,8 @@ export const DefaultOptions: CalendarOptions = {
* Default Views
*/
export const DefaultViews = [View.DAY, View.WEEK, View.MONTH];

/**
* Default View
*/
export const DefaultView = View.MONTH;
3 changes: 1 addition & 2 deletions src/constants/options.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { SelectableValue } from '@grafana/data';
import { TFunction } from 'i18next';
import { CalendarType, View } from '../types';

Expand Down Expand Up @@ -79,7 +78,7 @@ export const AnnotationsTypeOptions = (t: TFunction) => [
/**
* Calendar View Options
*/
export const CalendarViewOptions = (t: TFunction): Array<SelectableValue<View>> => [
export const CalendarViewOptions = (t: TFunction) => [
{ value: View.DAY, label: t('panelOptions.views.options.day') },
{ value: View.WEEK, label: t('panelOptions.views.options.week') },
{ value: View.WORK_WEEK, label: t('panelOptions.views.options.workWeek') },
Expand Down
3 changes: 3 additions & 0 deletions src/constants/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,7 @@ export const TestIds = {
date: (day: number) => `data-testid year-view date-${day}`,
currentDate: 'data-testid year-view current-date',
},
defaultViewEditor: {
field: 'default-view-editor field',
},
};
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import dayjs from 'dayjs';
import React from 'react';
import { dateTime, TimeRange } from '@grafana/data';
import { act, renderHook } from '@testing-library/react';
import { act, render, renderHook, screen } from '@testing-library/react';
import dayjs from 'dayjs';
import { View } from '../types';
import { getUnitType, useCalendarRange } from './useCalendarRange';

Expand Down Expand Up @@ -31,25 +32,76 @@ describe('Use Calendar Range', () => {
onChangeTimeRange.mockClear();
});

it('Should set last month for initial date', () => {
it('Should set last month for initial date if month by default', () => {
const last3Months = dayjs(getSafeDate()).subtract(3, 'month');
const timeRange = {
...defaultTimeRange,
from: dateTime(last3Months.toDate()),
};
const { result } = renderHook(() => useCalendarRange(timeRange, onChangeTimeRange));
const { result } = renderHook(() => useCalendarRange(timeRange, onChangeTimeRange, View.MONTH));

expect(result.current.date.toISOString()).toEqual(new Date('2023-02-01 12:00').toISOString());
});

it('Should set last week for initial date if week by default', () => {
const last3Months = dayjs(getSafeDate()).subtract(3, 'month');
const timeRange = {
...defaultTimeRange,
from: dateTime(last3Months.toDate()),
};
const { result } = renderHook(() => useCalendarRange(timeRange, onChangeTimeRange, View.WEEK));

expect(result.current.date.toISOString()).toEqual(new Date('2023-01-31 00:00').toISOString());
});

it('Should set last day for initial date if day by default', () => {
const last3Months = dayjs(getSafeDate()).subtract(3, 'month');
const timeRange = {
...defaultTimeRange,
from: dateTime(last3Months.toDate()),
};
const { result } = renderHook(() => useCalendarRange(timeRange, onChangeTimeRange, View.DAY));

expect(result.current.date.toISOString()).toEqual(new Date('2023-02-02 00:00').toISOString());
});

it('Should update calendar dates on time range update', () => {
const last3Months = dayjs(getSafeDate()).subtract(3, 'month');
const timeRange = {
...defaultTimeRange,
from: dateTime(last3Months.toDate()),
};

/**
* Component to test re-render
* @param timeRange
* @constructor
*/
const Component = ({ timeRange }: any) => {
const { date } = useCalendarRange(timeRange, onChangeTimeRange, View.DAY);
return <div data-testid="date">{date.toISOString()}</div>;
};

const { rerender } = render(<Component timeRange={timeRange} />);

expect(screen.getByTestId('date')).toHaveTextContent('2023-02-02T00:00:00.000Z');

/**
* Re-render with updated timeRange
*/
rerender(<Component timeRange={{ ...timeRange, from: dateTime(last3Months.subtract(1, 'month').toDate()) }} />);

expect(screen.getByTestId('date')).toHaveTextContent('2022-12-02T12:00:00.000Z');
});

describe('Navigate', () => {
it('Should apply new range based on view', async () => {
const last3Months = dayjs(getSafeDate()).subtract(3, 'month');
const timeRange = {
...defaultTimeRange,
from: dateTime(last3Months.toDate()),
};
const { result } = renderHook(() => useCalendarRange(timeRange, onChangeTimeRange));
const { result } = renderHook(() => useCalendarRange(timeRange, onChangeTimeRange, View.MONTH));

/**
* Month
Expand Down
Loading
Loading