1import React, { useMemo } from 'react';
2import { SelectableValue } from '@grafana/data';
3import { Select } from '@grafana/ui';
4import { ALIGNMENT_PERIODS } from '../constants';
5import { MetricQuery, SLOQuery } from '../types';
6
7export interface Props<TQuery> {
8  onChange(query: TQuery): void;
9  query: TQuery;
10  templateVariableOptions: Array<SelectableValue<string>>;
11  selectWidth?: number;
12}
13
14export function AlignmentPeriod<TQuery extends MetricQuery | SLOQuery>({
15  templateVariableOptions,
16  onChange,
17  query,
18  selectWidth,
19}: Props<TQuery>) {
20  const options = useMemo(
21    () =>
22      ALIGNMENT_PERIODS.map((ap) => ({
23        ...ap,
24        label: ap.text,
25      })),
26    []
27  );
28  const visibleOptions = useMemo(() => options.filter((ap) => !ap.hidden), [options]);
29
30  return (
31    <Select
32      menuShouldPortal
33      width={selectWidth}
34      onChange={({ value }) => onChange({ ...query, alignmentPeriod: value! })}
35      value={[...options, ...templateVariableOptions].find((s) => s.value === query.alignmentPeriod)}
36      options={[
37        {
38          label: 'Template Variables',
39          options: templateVariableOptions,
40        },
41        {
42          label: 'Aggregations',
43          expanded: true,
44          options: visibleOptions,
45        },
46      ]}
47      placeholder="Select Alignment"
48    ></Select>
49  );
50}
51