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 date filter #747

Merged
merged 3 commits into from
Oct 12, 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
71 changes: 71 additions & 0 deletions packages/common/src/components/Filter/DateFilter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import React, { FormEvent, useState } from 'react';

import { DatePicker, InputGroup, ToolbarFilter } from '@patternfly/react-core';

import { changeFormatToISODate, isValidDate, parseISOtoJSDate, toISODate } from '../../utils';

import { FilterTypeProps } from './types';

/**
* This Filter type enables selecting a single date (a day).
*
* **FilterTypeProps are interpreted as follows**:<br>
* 1) selectedFilters - dates in YYYY-MM-DD format (ISO date format).<br>
* 2) onFilterUpdate - accepts the list of dates.<br>
*
* [<img src="static/media/src/components-stories/assets/github-logo.svg"><i class="fi fi-brands-github">
* <font color="green">View component source on GitHub</font>](https://github.com/kubev2v/forklift-console-plugin/blob/main/packages/common/src/components/Filter/DateFilter.tsx)
*/
export const DateFilter = ({
selectedFilters = [],
onFilterUpdate,
title,
filterId,
placeholderLabel,
showFilter = true,
}: FilterTypeProps) => {
const validFilters = selectedFilters?.map(changeFormatToISODate)?.filter(Boolean) ?? [];

// internal state - stored as ISO date string (no time)
const [date, setDate] = useState(toISODate(new Date()));

const clearSingleDate = (option) => {
onFilterUpdate([...validFilters.filter((d) => d !== option)]);
};

const onDateChange = (even: FormEvent<HTMLInputElement>, value: string) => {
// require full format "YYYY-MM-DD" although partial date is also accepted
// i.e. YYYY-MM gets parsed as YYYY-MM-01 and results in auto completing the date
// unfortunately due to auto-complete user cannot delete the date char after char
if (value?.length === 10 && isValidDate(value)) {
const targetDate = changeFormatToISODate(value);
setDate(targetDate);
onFilterUpdate([...validFilters.filter((d) => d !== targetDate), targetDate]);
}
};

return (
<ToolbarFilter
key={filterId}
chips={validFilters}
deleteChip={(category, option) => clearSingleDate(option)}
deleteChipGroup={() => onFilterUpdate([])}
categoryName={title}
showToolbarItem={showFilter}
>
<InputGroup>
<DatePicker
value={date}
dateFormat={toISODate}
dateParse={parseISOtoJSDate}
onChange={onDateChange}
aria-label={title}
placeholder={placeholderLabel}
invalidFormatText={placeholderLabel}
// default value ("parent") creates collision with sticky table header
appendTo={document.body}
/>
</InputGroup>
</ToolbarFilter>
);
};
1 change: 1 addition & 0 deletions packages/common/src/components/Filter/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// @index(['./*', /__/g], f => `export * from '${f.path}';`)
export * from './DateFilter';
export * from './EnumFilter';
export * from './FreetextFilter';
export * from './GroupedEnumFilter';
Expand Down
11 changes: 9 additions & 2 deletions packages/common/src/components/FilterGroup/matchers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import jsonpath from 'jsonpath';

import { ResourceField } from '../../utils';
import { EnumFilter, FreetextFilter, GroupedEnumFilter, SwitchFilter } from '../Filter';
import { areSameDayInUTCZero, ResourceField } from '../../utils';
import { DateFilter, EnumFilter, FreetextFilter, GroupedEnumFilter, SwitchFilter } from '../Filter';

import { FilterRenderer, ValueMatcher } from './types';

Expand Down Expand Up @@ -96,6 +96,11 @@ const groupedEnumMatcher = {
matchValue: enumMatcher.matchValue,
};

const dateMatcher = {
filterType: 'date',
matchValue: (value: string) => (filter: string) => areSameDayInUTCZero(value, filter),
};

const sliderMatcher = {
filterType: 'slider',
matchValue: (value: string) => (filter: string) => Boolean(value).toString() === filter || !value,
Expand All @@ -106,9 +111,11 @@ export const defaultValueMatchers: ValueMatcher[] = [
enumMatcher,
groupedEnumMatcher,
sliderMatcher,
dateMatcher,
];

export const defaultSupportedFilters: Record<string, FilterRenderer> = {
date: DateFilter,
enum: EnumFilter,
freetext: FreetextFilter,
groupedEnum: GroupedEnumFilter,
Expand Down
77 changes: 77 additions & 0 deletions packages/common/src/utils/__tests__/dates.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import {
areSameDayInUTCZero,
changeFormatToISODate,
changeTimeZoneToUTCZero,
isValidDate,
parseISOtoJSDate,
toISODate,
} from '../dates';

describe('changeTimeZoneToUTCZero', () => {
test('from UTC+02:00', () => {
expect(changeTimeZoneToUTCZero('2023-10-31T01:30:00.000+02:00')).toBe(
'2023-10-30T23:30:00.000Z',
);
});
test('invalid input', () => {
expect(changeTimeZoneToUTCZero('2023-broken-10-31T01:30:00.000+02:00')).toBe(undefined);
});
});

describe('changeFormatToISODate', () => {
test('from ISO date time with zone', () => {
expect(changeFormatToISODate('2023-10-31T01:30:00.000+02:00')).toBe('2023-10-31');
});
test('invalid input', () => {
expect(changeFormatToISODate('2023-broken-10-31T01:30:00.000+02:00')).toBe(undefined);
});
});

describe('toISODate', () => {
test('unix epoch', () => {
expect(toISODate(new Date(0))).toBe('1970-01-01');
});
test('missing date', () => {
expect(toISODate(undefined)).toBe(undefined);
});
test('invalid date', () => {
expect(toISODate(new Date('foo'))).toBe(undefined);
});
});

describe('isValidDate', () => {
test('2023-10-31T01:30:00.000+02:00', () => {
expect(isValidDate('2023-10-31T01:30:00.000+02:00')).toBeTruthy();
});
test('invalid string', () => {
expect(isValidDate('2023-broken-10-31')).toBeFalsy();
});
test('invalid number of days', () => {
expect(isValidDate('2023-10-60')).toBeFalsy();
});
});

describe('parseISOtoJSDate', () => {
test('2023-10-31T01:30:00.000+02:00', () => {
const date = parseISOtoJSDate('2023-10-31T01:30:00.000+02:00');
expect(date.toUTCString()).toBe('Mon, 30 Oct 2023 23:30:00 GMT');
});
test('invalid input', () => {
expect(parseISOtoJSDate('2023-broken-10-31T01:30:00.000+02:00')).toBe(undefined);
});
});

describe('areSameDayInUTCZero', () => {
test('the same date', () => {
expect(areSameDayInUTCZero('2023-10-31T01:30:00.000+02:00', '2023-10-30')).toBeTruthy();
});
test('the different dates', () => {
expect(areSameDayInUTCZero('2023-10-31T01:30:00.000+02:00', '2023-10-31')).toBeFalsy();
});
test('one date invalid', () => {
expect(areSameDayInUTCZero('2023-10-31T10:00:00.000+02:00', '2023-foo')).toBeFalsy();
});
test('one date missing, one invalid', () => {
expect(areSameDayInUTCZero(undefined, '2023-foo')).toBeFalsy();
});
});
58 changes: 58 additions & 0 deletions packages/common/src/utils/dates.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { DateTime } from 'luxon';

/**
* Converts a given ISO date time string to UTC+00:00 time zone.
*
* @param {string} isoDateString - The ISO date time string
* @returns {string} The equivalent UTC+00:00 date time ISO string if input is valid or undefined otherwise.
*/
export function changeTimeZoneToUTCZero(isoDateString: string): string | undefined {
const date = DateTime.fromISO(isoDateString);
return date.isValid ? date.toUTC().toISO() : undefined;
}

/**
* Converts a given ISO date time string to ISO date string(no time).
*
* @param {string} isoDateString - The ISO date time string
* @returns {string} The equivalent ISO date string if input is valid or undefined otherwise.
*/
export const changeFormatToISODate = (isoDateString: string): string | undefined => {
// preserve the original zone
const date = DateTime.fromISO(isoDateString, { setZone: true, zone: 'utc' });
return date.isValid ? date.toISODate() : undefined;
};

/**
* Prints JS Date instance as ISO date format (no time)
* @param date
* @returns ISO date string if input is valid or undefined otherwise.
*/
export const toISODate = (date: Date): string => {
const dt = DateTime.fromJSDate(date);
return dt.isValid ? dt.toISODate() : undefined;
};

export const isValidDate = (isoDateString: string) => DateTime.fromISO(isoDateString).isValid;

/**
*
* @param isoDateString
* @returns JS Date instance if input is valid or undefined otherwise.
*/
export const parseISOtoJSDate = (isoDateString: string) => {
const date = DateTime.fromISO(isoDateString);
return date.isValid ? date.toJSDate() : undefined;
};

/**
*
* @param dateTime ISO date time formatted string (with time zone)
* @param calendarDate local date as ISO date formatted string (no time, no time zone)
* @returns true if both dates are on the same day in UTC+00:00
*/
export const areSameDayInUTCZero = (dateTime: string, calendarDate: string): boolean => {
// calendar date has no zone - during conversion to UTC the local zone is used
// which results in shifting to previous day for zones with positive offsets
return DateTime.fromISO(dateTime).toUTC().hasSame(DateTime.fromISO(calendarDate), 'day');
};
1 change: 1 addition & 0 deletions packages/common/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// @index(['./*', /__/g], f => `export * from '${f.path}';`)
export * from './constants';
export * from './dates';
export * from './localCompare';
export * from './localStorage';
export * from './types';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@
"Migration networks maps are used to map network interfaces between source and target workloads.": "Migration networks maps are used to map network interfaces between source and target workloads.",
"Migration plans are used to plan migration or virtualization workloads from source providers to target providers.": "Migration plans are used to plan migration or virtualization workloads from source providers to target providers.",
"Migration plans are used to plan migration or virtualization workloads from source providers to target providers. At least one source and one target provider must be available in order to create a migration plan, <2>Learn more</2>.": "Migration plans are used to plan migration or virtualization workloads from source providers to target providers. At least one source and one target provider must be available in order to create a migration plan, <2>Learn more</2>.",
"Migration started": "Migration started",
"Migration storage maps are used to map storage interfaces between source and target workloads, at least one source and one target provider must be available in order to create a migration plan, <2>Learn more</2>.": "Migration storage maps are used to map storage interfaces between source and target workloads, at least one source and one target provider must be available in order to create a migration plan, <2>Learn more</2>.",
"Migration storage maps are used to map storage interfaces between source and target workloads.": "Migration storage maps are used to map storage interfaces between source and target workloads.",
"Migration Toolkit for Virtualization": "Migration Toolkit for Virtualization",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';

import { ResourceLinkProps } from '@openshift-console/dynamic-plugin-sdk';
import { ResourceLinkProps, TimestampProps } from '@openshift-console/dynamic-plugin-sdk';

export const ResourceLink = ({
name,
Expand All @@ -23,3 +23,7 @@ export const BlueInfoCircleIcon = () => <div data-test-element-name="BlueInfoCir
export const useModal = (props) => <div data-test-element-name="useModal" {...props} />;
export const ActionService = () => <div data-test-element-name="ActionService" />;
export const ActionServiceProvider = () => <div data-test-element-name="ActionServiceProvider" />;

export const Timestamp = ({ timestamp }: TimestampProps) => (
Copy link
Member

Choose a reason for hiding this comment

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

Nice!

<div data-test-element-name="Timestamp">{timestamp}</div>
);
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ import { MigrateOrCutoverButton } from '@kubev2v/legacy/Plans/components/Migrate
import { PlanNameNavLink as Link } from '@kubev2v/legacy/Plans/components/PlanStatusNavLink';
import { ScheduledCutoverTime } from '@kubev2v/legacy/Plans/components/ScheduledCutoverTime';
import { StatusIcon } from '@migtools/lib-ui';
import { K8sGroupVersionKind, ResourceLink } from '@openshift-console/dynamic-plugin-sdk';
import {
K8sGroupVersionKind,
ResourceLink,
Timestamp,
} from '@openshift-console/dynamic-plugin-sdk';
import {
Flex,
FlexItem,
Expand Down Expand Up @@ -192,6 +196,7 @@ const cellCreator: Record<string, (props: CellProps) => JSX.Element> = {
<VirtualMachineIcon /> {value}
</RouterLink>
),
[C.MIGRATION_STARTED]: ({ value }: CellProps) => <Timestamp timestamp={value} />,
};

const PlanRow = ({
Expand Down
10 changes: 10 additions & 0 deletions packages/forklift-console-plugin/src/modules/Plans/PlansPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ export const fieldsMetadataFactory: ResourceFieldFactory = (t) => [
},
sortable: true,
},
{
resourceFieldId: C.MIGRATION_STARTED,
label: t('Migration started'),
isVisible: true,
filter: {
type: 'date',
placeholderLabel: 'YYYY-MM-DD',
},
sortable: true,
},
{
resourceFieldId: C.SOURCE,
label: t('Source provider'),
Expand Down
Loading
Loading