PR fixes, extract format start and finished dates
[arvados-workbench2.git] / src / views-components / resource-properties-form / property-key-field.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import * as React from 'react';
6 import { WrappedFieldProps, Field } from 'redux-form';
7 import { memoize } from 'lodash';
8 import { Autocomplete } from '~/components/autocomplete/autocomplete';
9 import { Vocabulary } from '~/models/vocabulary';
10 import { connectVocabulary, VocabularyProp, buildProps } from '~/views-components/resource-properties-form/property-field-common';
11 import { TAG_KEY_VALIDATION } from '~/validators/validators';
12
13 export const PROPERTY_KEY_FIELD_NAME = 'key';
14
15 export const PropertyKeyField = connectVocabulary(
16     ({ vocabulary }: VocabularyProp) =>
17         <Field
18             name={PROPERTY_KEY_FIELD_NAME}
19             component={PropertyKeyInput}
20             vocabulary={vocabulary}
21             validate={getValidation(vocabulary)} />);
22
23 const PropertyKeyInput = ({ vocabulary, ...props }: WrappedFieldProps & VocabularyProp) =>
24     <Autocomplete
25         label='Key'
26         suggestions={getSuggestions(props.input.value, vocabulary)}
27         {...buildProps(props)}
28     />;
29
30 const getValidation = memoize(
31     (vocabulary: Vocabulary) =>
32         vocabulary.strict
33             ? [...TAG_KEY_VALIDATION, matchTags(vocabulary)]
34             : TAG_KEY_VALIDATION);
35
36 const matchTags = (vocabulary: Vocabulary) =>
37     (value: string) =>
38         getTagsList(vocabulary).find(tag => tag.includes(value))
39             ? undefined
40             : 'Incorrect key';
41
42 const getSuggestions = (value: string, vocabulary: Vocabulary) =>
43     getTagsList(vocabulary).filter(tag => tag.includes(value) && tag !== value);
44
45 const getTagsList = ({ tags }: Vocabulary) =>
46     Object.keys(tags);