1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import React from 'react';
6 import { WrappedFieldProps, Field, FormName, reset, change, WrappedFieldInputProps, WrappedFieldMetaProps } from 'redux-form';
7 import { memoize } from 'lodash';
8 import { Autocomplete } from 'components/autocomplete/autocomplete';
9 import { Vocabulary, getTags, getTagKeyID, getTagKeyLabel } from 'models/vocabulary';
17 } from 'views-components/resource-properties-form/property-field-common';
18 import { TAG_KEY_VALIDATION } from 'validators/validators';
19 import { escapeRegExp } from 'common/regexp';
20 import { ChangeEvent } from 'react';
22 export const PROPERTY_KEY_FIELD_NAME = 'key';
23 export const PROPERTY_KEY_FIELD_ID = 'keyID';
25 export const PropertyKeyField = connectVocabulary(
26 ({ vocabulary, skipValidation }: VocabularyProp & ValidationProp) =>
27 <span data-cy='property-field-key'>
29 name={PROPERTY_KEY_FIELD_NAME}
30 component={PropertyKeyInput}
31 vocabulary={vocabulary}
32 validate={skipValidation ? undefined : getValidation(vocabulary)} />
36 const PropertyKeyInput = ({ vocabulary, ...props }: WrappedFieldProps & VocabularyProp) =>
37 <FormName children={data => (
40 suggestions={getSuggestions(props.input.value, vocabulary)}
41 onSelect={handleSelect(PROPERTY_KEY_FIELD_ID, data.form, props.input, props.meta)}
43 // Case-insensitive search for the key in the vocabulary
44 const foundKeyID = getTagKeyID(props.input.value, vocabulary);
45 if (foundKeyID !== '') {
46 props.input.value = getTagKeyLabel(foundKeyID, vocabulary);
48 handleBlur(PROPERTY_KEY_FIELD_ID, data.form, props.meta, props.input, foundKeyID)();
50 onChange={(e: ChangeEvent<HTMLInputElement>) => {
51 const newValue = e.currentTarget.value;
52 handleChange(data.form, props.input, props.meta, newValue);
54 {...buildProps(props)}
58 const getValidation = memoize(
59 (vocabulary: Vocabulary) =>
60 vocabulary.strict_tags
61 ? [...TAG_KEY_VALIDATION, matchTags(vocabulary)]
62 : TAG_KEY_VALIDATION);
64 const matchTags = (vocabulary: Vocabulary) =>
66 getTags(vocabulary).find(tag => tag.label === value)
70 const getSuggestions = (value: string, vocabulary: Vocabulary) => {
71 const re = new RegExp(escapeRegExp(value), "i");
72 return getTags(vocabulary).filter(tag => re.test(tag.label) && tag.label !== value);
75 const handleChange = (
77 { onChange }: WrappedFieldInputProps,
78 { dispatch }: WrappedFieldMetaProps,
80 // Properties' values are dependant on the keys, if any value is
81 // pre-existant, a change on the property key should mean that the
82 // previous value is invalid, so we better reset the whole form before
83 // setting the new tag key.
84 dispatch(reset(formName));
87 dispatch(change(formName, PROPERTY_KEY_FIELD_NAME, value));