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, formValues, FormName } from 'redux-form';
7 import { compose } from 'redux';
8 import { Autocomplete } from '~/components/autocomplete/autocomplete';
9 import { Vocabulary, isStrictTag, getTagValues, getTagValueID } from '~/models/vocabulary';
10 import { PROPERTY_KEY_FIELD_ID } from '~/views-components/resource-properties-form/property-key-field';
11 import { handleSelect, handleBlur, VocabularyProp, ValidationProp, connectVocabulary, buildProps } from '~/views-components/resource-properties-form/property-field-common';
12 import { TAG_VALUE_VALIDATION } from '~/validators/validators';
13 import { escapeRegExp } from '~/common/regexp.ts';
15 interface PropertyKeyProp {
19 type PropertyValueFieldProps = VocabularyProp & PropertyKeyProp & ValidationProp;
21 export const PROPERTY_VALUE_FIELD_NAME = 'value';
22 export const PROPERTY_VALUE_FIELD_ID = 'valueID';
24 const connectVocabularyAndPropertyKey = compose(
26 formValues({ propertyKey: PROPERTY_KEY_FIELD_ID }),
29 export const PropertyValueField = connectVocabularyAndPropertyKey(
30 ({ skipValidation, ...props }: PropertyValueFieldProps) =>
31 <span data-cy='property-field-value'>
33 name={PROPERTY_VALUE_FIELD_NAME}
34 component={PropertyValueInput}
35 validate={skipValidation ? undefined : getValidation(props)}
40 const PropertyValueInput = ({ vocabulary, propertyKey, ...props }: WrappedFieldProps & PropertyValueFieldProps) =>
41 <FormName children={data => (
44 suggestions={getSuggestions(props.input.value, propertyKey, vocabulary)}
45 onSelect={handleSelect(PROPERTY_VALUE_FIELD_ID, data.form, props.input, props.meta)}
46 onBlur={handleBlur(PROPERTY_VALUE_FIELD_ID, data.form, props.meta, props.input, getTagValueID(propertyKey, props.input.value, vocabulary))}
47 {...buildProps(props)}
51 const getValidation = (props: PropertyValueFieldProps) =>
52 isStrictTag(props.propertyKey, props.vocabulary)
53 ? [...TAG_VALUE_VALIDATION, matchTagValues(props)]
54 : TAG_VALUE_VALIDATION;
56 const matchTagValues = ({ vocabulary, propertyKey }: PropertyValueFieldProps) =>
58 getTagValues(propertyKey, vocabulary).find(v => v.label === value)
62 const getSuggestions = (value: string, tagName: string, vocabulary: Vocabulary) => {
63 const re = new RegExp(escapeRegExp(value), "i");
64 return getTagValues(tagName, vocabulary).filter(v => re.test(v.label) && v.label !== value);