1f92118885690992b19cb6c81e5a88eaea47c959
[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, FormName } from 'redux-form';
7 import { memoize } from 'lodash';
8 import { Autocomplete } from '~/components/autocomplete/autocomplete';
9 import { Vocabulary, getTags, getTagKeyID } from '~/models/vocabulary';
10 import { handleSelect, handleBlur, connectVocabulary, VocabularyProp, ValidationProp, buildProps } from '~/views-components/resource-properties-form/property-field-common';
11 import { TAG_KEY_VALIDATION } from '~/validators/validators';
12 import { escapeRegExp } from '~/common/regexp.ts';
13
14 export const PROPERTY_KEY_FIELD_NAME = 'key';
15 export const PROPERTY_KEY_FIELD_ID = 'keyID';
16
17 export const PropertyKeyField = connectVocabulary(
18     ({ vocabulary, skipValidation }: VocabularyProp & ValidationProp) =>
19         <Field
20             name={PROPERTY_KEY_FIELD_NAME}
21             component={PropertyKeyInput}
22             vocabulary={vocabulary}
23             validate={skipValidation ? undefined : getValidation(vocabulary)} />
24 );
25
26 const PropertyKeyInput = ({ vocabulary, ...props }: WrappedFieldProps & VocabularyProp) =>
27     <FormName children={data => (
28         <Autocomplete
29             label='Key'
30             suggestions={getSuggestions(props.input.value, vocabulary)}
31             onSelect={handleSelect(PROPERTY_KEY_FIELD_ID, data.form, props.input, props.meta)}
32             onBlur={handleBlur(PROPERTY_KEY_FIELD_ID, data.form, props.meta, props.input, getTagKeyID(props.input.value, vocabulary))}
33             {...buildProps(props)}
34         />
35     )} />;
36
37 const getValidation = memoize(
38     (vocabulary: Vocabulary) =>
39         vocabulary.strict_tags
40             ? [...TAG_KEY_VALIDATION, matchTags(vocabulary)]
41             : TAG_KEY_VALIDATION);
42
43 const matchTags = (vocabulary: Vocabulary) =>
44     (value: string) =>
45         getTags(vocabulary).find(tag => tag.label === value)
46             ? undefined
47             : 'Incorrect key';
48
49 const getSuggestions = (value: string, vocabulary: Vocabulary) => {
50     const re = new RegExp(escapeRegExp(value), "i");
51     return getTags(vocabulary).filter(tag => re.test(tag.label) && tag.label !== value);
52 };