1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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';
14 export const PROPERTY_KEY_FIELD_NAME = 'key';
15 export const PROPERTY_KEY_FIELD_ID = 'keyID';
17 export const PropertyKeyField = connectVocabulary(
18 ({ vocabulary, skipValidation }: VocabularyProp & ValidationProp) =>
19 <span data-cy='property-field-key'>
21 name={PROPERTY_KEY_FIELD_NAME}
22 component={PropertyKeyInput}
23 vocabulary={vocabulary}
24 validate={skipValidation ? undefined : getValidation(vocabulary)} />
28 const PropertyKeyInput = ({ vocabulary, ...props }: WrappedFieldProps & VocabularyProp) =>
29 <FormName children={data => (
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)}
39 const getValidation = memoize(
40 (vocabulary: Vocabulary) =>
41 vocabulary.strict_tags
42 ? [...TAG_KEY_VALIDATION, matchTags(vocabulary)]
43 : TAG_KEY_VALIDATION);
45 const matchTags = (vocabulary: Vocabulary) =>
47 getTags(vocabulary).find(tag => tag.label === value)
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);