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) =>
20 name={PROPERTY_KEY_FIELD_NAME}
21 component={PropertyKeyInput}
22 vocabulary={vocabulary}
23 validate={skipValidation ? undefined : getValidation(vocabulary)} />
26 const PropertyKeyInput = ({ vocabulary, ...props }: WrappedFieldProps & VocabularyProp) =>
27 <FormName children={data => (
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)}
37 const getValidation = memoize(
38 (vocabulary: Vocabulary) =>
39 vocabulary.strict_tags
40 ? [...TAG_KEY_VALIDATION, matchTags(vocabulary)]
41 : TAG_KEY_VALIDATION);
43 const matchTags = (vocabulary: Vocabulary) =>
45 getTags(vocabulary).find(tag => tag.label === value)
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);