1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import * as React from 'react';
6 import { change, WrappedFieldProps, WrappedFieldMetaProps, WrappedFieldInputProps,
7 Field, formValues, FormName } from 'redux-form';
8 import { compose } from 'redux';
9 import { Autocomplete } from '~/components/autocomplete/autocomplete';
10 import { Vocabulary, getTagValueID, isStrictTag, getTagValues, PropFieldSuggestion } from '~/models/vocabulary';
11 import { PROPERTY_KEY_FIELD_ID } from '~/views-components/resource-properties-form/property-key-field';
12 import { VocabularyProp, connectVocabulary, buildProps } from '~/views-components/resource-properties-form/property-field-common';
13 import { TAG_VALUE_VALIDATION } from '~/validators/validators';
14 import { escapeRegExp } from '~/common/regexp.ts';
16 interface PropertyKeyProp {
20 export type PropertyValueFieldProps = VocabularyProp & PropertyKeyProp;
22 export const PROPERTY_VALUE_FIELD_NAME = 'value';
23 export const PROPERTY_VALUE_FIELD_ID = 'valueID';
25 export const PropertyValueField = compose(
27 formValues({ propertyKey: PROPERTY_KEY_FIELD_ID })
29 (props: PropertyValueFieldProps) =>
31 name={PROPERTY_VALUE_FIELD_NAME}
32 component={PropertyValueInput}
33 validate={getValidation(props)}
37 export const PropertyValueInput = ({ vocabulary, propertyKey, ...props }: WrappedFieldProps & PropertyValueFieldProps) =>
38 <FormName children={data => (
41 suggestions={getSuggestions(props.input.value, propertyKey, vocabulary)}
42 onSelect={handleSelect(data.form, props.input, props.meta)}
43 {...buildProps(props)}
44 onBlur={handleBlur(data.form, props.meta, props.input, vocabulary, propertyKey)}
48 const getValidation = (props: PropertyValueFieldProps) =>
49 isStrictTag(props.propertyKey, props.vocabulary)
50 ? [...TAG_VALUE_VALIDATION, matchTagValues(props)]
51 : TAG_VALUE_VALIDATION;
53 const matchTagValues = ({ vocabulary, propertyKey }: PropertyValueFieldProps) =>
55 getTagValues(propertyKey, vocabulary).find(v => v.label === value)
59 const getSuggestions = (value: string, tagName: string, vocabulary: Vocabulary) => {
60 const re = new RegExp(escapeRegExp(value), "i");
61 return getTagValues(tagName, vocabulary).filter(v => re.test(v.label) && v.label !== value);
64 // Attempts to match a manually typed value label with a value ID, when the user
65 // doesn't select the value from the suggestions list.
68 { dispatch }: WrappedFieldMetaProps,
69 { onBlur, value }: WrappedFieldInputProps,
70 vocabulary: Vocabulary,
73 dispatch(change(formName, PROPERTY_VALUE_FIELD_ID, getTagValueID(tagKeyID, value, vocabulary)));
77 // When selecting a property value, save its ID for later usage.
78 const handleSelect = (
80 { onChange }: WrappedFieldInputProps,
81 { dispatch }: WrappedFieldMetaProps) => {
82 return (item:PropFieldSuggestion) => {
84 dispatch(change(formName, PROPERTY_VALUE_FIELD_ID, item.id));