Skip to content
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 .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,7 @@ src/platform/packages/shared/response-ops/alerts-delete @elastic/response-ops
src/platform/packages/shared/response-ops/alerts-fields-browser @elastic/response-ops
src/platform/packages/shared/response-ops/alerts-filters-form @elastic/response-ops
src/platform/packages/shared/response-ops/alerts-table @elastic/response-ops
src/platform/packages/shared/response-ops/recurring-schedule-form @elastic/response-ops
src/platform/packages/shared/response-ops/rule_form @elastic/response-ops
src/platform/packages/shared/response-ops/rule_params @elastic/response-ops
src/platform/packages/shared/response-ops/rules-apis @elastic/response-ops
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -794,6 +794,7 @@
"@kbn/response-ops-alerts-fields-browser": "link:src/platform/packages/shared/response-ops/alerts-fields-browser",
"@kbn/response-ops-alerts-filters-form": "link:src/platform/packages/shared/response-ops/alerts-filters-form",
"@kbn/response-ops-alerts-table": "link:src/platform/packages/shared/response-ops/alerts-table",
"@kbn/response-ops-recurring-schedule-form": "link:src/platform/packages/shared/response-ops/recurring-schedule-form",
"@kbn/response-ops-rule-form": "link:src/platform/packages/shared/response-ops/rule_form",
"@kbn/response-ops-rule-params": "link:src/platform/packages/shared/response-ops/rule_params",
"@kbn/response-ops-rules-apis": "link:src/platform/packages/shared/response-ops/rules-apis",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# @kbn/response-ops-recurring-schedule-form

[Form lib](https://docs.elastic.dev/form-lib/welcome) fields to create RRule recurring schedules.

## Usage

In your form schema, add a `recurringSchedule` field:

```tsx
const form = useForm({
schema: {
recurringSchedule: getRecurringScheduleFormSchema(),
}
});
```

And render `RecurringScheduleFormFields` in your form:

```tsx
<RecurringScheduleFormFields
startDate={startDate}
endDate={endDate}
timezone={timezone}
/>
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
/*
* 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", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import React, { PropsWithChildren } from 'react';
import { fireEvent, render, within, screen } from '@testing-library/react';
import { useForm, Form } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib';
import { Frequency } from '@kbn/rrule';
import type { RecurringSchedule } from '../types';
import { getRecurringScheduleFormSchema } from '../schemas/recurring_schedule_form_schema';
import { CustomRecurringSchedule } from './custom_recurring_schedule';
import { RecurrenceEnd } from '../constants';

interface FormValue {
recurringSchedule: RecurringSchedule;
}

const initialValue: FormValue = {
recurringSchedule: {
frequency: 'CUSTOM',
ends: RecurrenceEnd.NEVER,
},
};

const TestWrapper = ({ children, iv = initialValue }: PropsWithChildren<{ iv?: FormValue }>) => {
const { form } = useForm<FormValue>({
defaultValue: iv,
options: { stripEmptyFields: false },
schema: { recurringSchedule: getRecurringScheduleFormSchema() },
});

return <Form form={form}>{children}</Form>;
};

describe('CustomRecurringSchedule', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('renders all form fields', async () => {
render(
<TestWrapper>
<CustomRecurringSchedule />
</TestWrapper>
);

expect(screen.getByTestId('interval-field')).toBeInTheDocument();
expect(screen.getByTestId('custom-frequency-field')).toBeInTheDocument();
expect(screen.getByTestId('byweekday-field')).toBeInTheDocument();
expect(screen.queryByTestId('bymonth-field')).not.toBeInTheDocument();
});

it('renders byweekday field if custom frequency = weekly', async () => {
render(
<TestWrapper>
<CustomRecurringSchedule />
</TestWrapper>
);

fireEvent.change(
within(screen.getByTestId('custom-frequency-field')).getByTestId(
'customRecurringScheduleFrequencySelect'
),
{
target: { value: Frequency.WEEKLY },
}
);
expect(await screen.findByTestId('byweekday-field')).toBeInTheDocument();
});

it('renders byweekday field if frequency = daily', async () => {
const iv: FormValue = {
recurringSchedule: {
...initialValue,
frequency: Frequency.DAILY,
ends: RecurrenceEnd.NEVER,
},
};
render(
<TestWrapper iv={iv}>
<CustomRecurringSchedule />
</TestWrapper>
);

expect(screen.getByTestId('byweekday-field')).toBeInTheDocument();
});

it('renders bymonth field if custom frequency = monthly', async () => {
render(
<TestWrapper>
<CustomRecurringSchedule />
</TestWrapper>
);

fireEvent.change(
within(screen.getByTestId('custom-frequency-field')).getByTestId(
'customRecurringScheduleFrequencySelect'
),
{
target: { value: Frequency.MONTHLY },
}
);
expect(await screen.findByTestId('bymonth-field')).toBeInTheDocument();
});

it('should initialize the form when no initialValue provided', () => {
render(
<TestWrapper>
<CustomRecurringSchedule />
</TestWrapper>
);

const frequencyInput = within(screen.getByTestId('custom-frequency-field')).getByTestId(
'customRecurringScheduleFrequencySelect'
);
const intervalInput = within(screen.getByTestId('interval-field')).getByTestId(
'customRecurringScheduleIntervalInput'
);

expect(frequencyInput).toHaveValue('2');
expect(intervalInput).toHaveValue(1);
});

it('should prefill the form when provided with initialValue', () => {
const iv: FormValue = {
recurringSchedule: {
...initialValue,
frequency: 'CUSTOM',
ends: RecurrenceEnd.NEVER,
customFrequency: Frequency.WEEKLY,
interval: 3,
byweekday: { 1: false, 2: false, 3: true, 4: true, 5: false, 6: false, 7: false },
},
};
render(
<TestWrapper iv={iv}>
<CustomRecurringSchedule />
</TestWrapper>
);

const frequencyInput = within(screen.getByTestId('custom-frequency-field')).getByTestId(
'customRecurringScheduleFrequencySelect'
);
const intervalInput = within(screen.getByTestId('interval-field')).getByTestId(
'customRecurringScheduleIntervalInput'
);
const input3 = within(screen.getByTestId('byweekday-field'))
.getByTestId('isoWeekdays3')
.getAttribute('aria-pressed');
const input4 = within(screen.getByTestId('byweekday-field'))
.getByTestId('isoWeekdays4')
.getAttribute('aria-pressed');
expect(frequencyInput).toHaveValue('2');
expect(intervalInput).toHaveValue(3);
expect(input3).toBe('true');
expect(input4).toBe('true');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
/*
* 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", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import React, { useMemo } from 'react';
import { Frequency } from '@kbn/rrule';
import moment from 'moment';
import { css } from '@emotion/react';
import {
FIELD_TYPES,
getUseField,
useFormData,
} from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib';
import type { MultiButtonGroupFieldValue } from '@kbn/es-ui-shared-plugin/static/forms/components';
import { Field } from '@kbn/es-ui-shared-plugin/static/forms/components';
import { EuiFlexGroup, EuiFlexItem, EuiFormLabel, EuiSpacer } from '@elastic/eui';
import { RECURRING_SCHEDULE_FORM_CUSTOM_FREQUENCY, WEEKDAY_OPTIONS } from '../constants';
import { getInitialByWeekday } from '../utils/get_initial_by_weekday';
import { parseSchedule } from '../utils/parse_schedule';
import { getWeekdayInfo } from '../utils/get_weekday_info';
import { RecurringSchedule } from '../types';
import {
RECURRING_SCHEDULE_FORM_CUSTOM_REPEAT_MONTHLY_ON_DAY,
RECURRING_SCHEDULE_FORM_WEEKDAY_SHORT,
RECURRING_SCHEDULE_FORM_INTERVAL_EVERY,
RECURRING_SCHEDULE_FORM_BYWEEKDAY_REQUIRED,
} from '../translations';

const UseField = getUseField({ component: Field });

const styles = {
flexField: css`
.euiFormRow__labelWrapper {
margin-bottom: unset;
}
`,
};

export interface CustomRecurringScheduleProps {
startDate?: string;
}

export const CustomRecurringSchedule: React.FC = React.memo(
({ startDate }: CustomRecurringScheduleProps) => {
const [{ recurringSchedule }] = useFormData<{ recurringSchedule: RecurringSchedule }>({
watch: [
'recurringSchedule.frequency',
'recurringSchedule.interval',
'recurringSchedule.customFrequency',
],
});

const parsedSchedule = useMemo(() => {
return parseSchedule(recurringSchedule);
}, [recurringSchedule]);

const frequencyOptions = useMemo(
() => RECURRING_SCHEDULE_FORM_CUSTOM_FREQUENCY(parsedSchedule?.interval),
[parsedSchedule?.interval]
);

const bymonthOptions = useMemo(() => {
if (!startDate) return [];
const date = moment(startDate);
const { dayOfWeek, nthWeekdayOfMonth, isLastOfMonth } = getWeekdayInfo(date, 'ddd');
return [
{
id: 'day',
label: RECURRING_SCHEDULE_FORM_CUSTOM_REPEAT_MONTHLY_ON_DAY(date),
},
{
id: 'weekday',
label:
RECURRING_SCHEDULE_FORM_WEEKDAY_SHORT(dayOfWeek)[isLastOfMonth ? 0 : nthWeekdayOfMonth],
},
];
}, [startDate]);

const defaultByWeekday = useMemo(() => getInitialByWeekday([], moment(startDate)), [startDate]);

return (
<>
{parsedSchedule?.frequency !== Frequency.DAILY ? (
<>
<EuiSpacer size="s" />
<EuiFlexGroup gutterSize="s" alignItems="flexStart">
<EuiFlexItem>
<UseField
path="recurringSchedule.interval"
css={styles.flexField}
componentProps={{
'data-test-subj': 'interval-field',
id: 'interval',
euiFieldProps: {
'data-test-subj': 'customRecurringScheduleIntervalInput',
min: 1,
prepend: (
<EuiFormLabel htmlFor={'interval'}>
{RECURRING_SCHEDULE_FORM_INTERVAL_EVERY}
</EuiFormLabel>
),
},
}}
/>
</EuiFlexItem>
<EuiFlexItem>
<UseField
path="recurringSchedule.customFrequency"
componentProps={{
'data-test-subj': 'custom-frequency-field',
euiFieldProps: {
'data-test-subj': 'customRecurringScheduleFrequencySelect',
options: frequencyOptions,
},
}}
/>
</EuiFlexItem>
</EuiFlexGroup>
<EuiSpacer size="s" />
</>
) : null}
{Number(parsedSchedule?.customFrequency) === Frequency.WEEKLY ||
parsedSchedule?.frequency === Frequency.DAILY ? (
<UseField
path="recurringSchedule.byweekday"
config={{
type: FIELD_TYPES.MULTI_BUTTON_GROUP,
label: '',
validations: [
{
validator: ({ value }) => {
if (
Object.values(value as MultiButtonGroupFieldValue).every((v) => v === false)
) {
return {
message: RECURRING_SCHEDULE_FORM_BYWEEKDAY_REQUIRED,
};
}
},
},
],
defaultValue: defaultByWeekday,
}}
componentProps={{
'data-test-subj': 'byweekday-field',
euiFieldProps: {
'data-test-subj': 'customRecurringScheduleByWeekdayButtonGroup',
legend: 'Repeat on weekday',
options: WEEKDAY_OPTIONS,
},
}}
/>
) : null}

{Number(parsedSchedule?.customFrequency) === Frequency.MONTHLY ? (
<UseField
path="recurringSchedule.bymonth"
componentProps={{
'data-test-subj': 'bymonth-field',
euiFieldProps: {
legend: 'Repeat on weekday or month day',
options: bymonthOptions,
},
}}
/>
) : null}
</>
);
}
);

CustomRecurringSchedule.displayName = 'CustomRecurringSchedule';
Loading