15067: Generalizes handleSelect & handleBlur on property form fields.
[arvados.git] / src / views-components / resource-properties-form / property-value-field.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
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, 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';
14
15 interface PropertyKeyProp {
16     propertyKey: string;
17 }
18
19 export type PropertyValueFieldProps = VocabularyProp & PropertyKeyProp;
20
21 export const PROPERTY_VALUE_FIELD_NAME = 'value';
22 export const PROPERTY_VALUE_FIELD_ID = 'valueID';
23
24 export const PropertyValueField = compose(
25     connectVocabulary,
26     formValues({ propertyKey: PROPERTY_KEY_FIELD_ID })
27 )(
28     (props: PropertyValueFieldProps) =>
29         <Field
30             name={PROPERTY_VALUE_FIELD_NAME}
31             component={PropertyValueInput}
32             validate={getValidation(props)}
33             {...props} />
34 );
35
36 export const PropertyValueInput = ({ vocabulary, propertyKey, ...props }: WrappedFieldProps & PropertyValueFieldProps) =>
37     <FormName children={data => (
38         <Autocomplete
39             label='Value'
40             suggestions={getSuggestions(props.input.value, propertyKey, vocabulary)}
41             onSelect={handleSelect(PROPERTY_VALUE_FIELD_ID, data.form, props.input, props.meta)}
42             onBlur={handleBlur(PROPERTY_VALUE_FIELD_ID, data.form, props.meta, props.input, getTagValueID(propertyKey, props.input.value, vocabulary))}
43             {...buildProps(props)}
44         />
45     )}/>;
46
47 const getValidation = (props: PropertyValueFieldProps) =>
48     isStrictTag(props.propertyKey, props.vocabulary)
49         ? [...TAG_VALUE_VALIDATION, matchTagValues(props)]
50         : TAG_VALUE_VALIDATION;
51
52 const matchTagValues = ({ vocabulary, propertyKey }: PropertyValueFieldProps) =>
53     (value: string) =>
54         getTagValues(propertyKey, vocabulary).find(v => v.label === value)
55             ? undefined
56             : 'Incorrect value';
57
58 const getSuggestions = (value: string, tagName: string, vocabulary: Vocabulary) => {
59     const re = new RegExp(escapeRegExp(value), "i");
60     return getTagValues(tagName, vocabulary).filter(v => re.test(v.label) && v.label !== value);
61 };
62