16118: Adds test checking writable/readonly collection UI changes.
[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         <span data-cy='property-field-key'>
20         <Field
21             name={PROPERTY_KEY_FIELD_NAME}
22             component={PropertyKeyInput}
23             vocabulary={vocabulary}
24             validate={skipValidation ? undefined : getValidation(vocabulary)} />
25         </span>
26 );
27
28 const PropertyKeyInput = ({ vocabulary, ...props }: WrappedFieldProps & VocabularyProp) =>
29     <FormName children={data => (
30         <Autocomplete
31             label='Key'
32             suggestions={getSuggestions(props.input.value, vocabulary)}
33             onSelect={handleSelect(PROPERTY_KEY_FIELD_ID, data.form, props.input, props.meta)}
34             onBlur={handleBlur(PROPERTY_KEY_FIELD_ID, data.form, props.meta, props.input, getTagKeyID(props.input.value, vocabulary))}
35             {...buildProps(props)}
36         />
37     )} />;
38
39 const getValidation = memoize(
40     (vocabulary: Vocabulary) =>
41         vocabulary.strict_tags
42             ? [...TAG_KEY_VALIDATION, matchTags(vocabulary)]
43             : TAG_KEY_VALIDATION);
44
45 const matchTags = (vocabulary: Vocabulary) =>
46     (value: string) =>
47         getTags(vocabulary).find(tag => tag.label === value)
48             ? undefined
49             : 'Incorrect key';
50
51 const getSuggestions = (value: string, vocabulary: Vocabulary) => {
52     const re = new RegExp(escapeRegExp(value), "i");
53     return getTags(vocabulary).filter(tag => re.test(tag.label) && tag.label !== value);
54 };