Merge branch '14393-vocabulary'
[arvados-workbench2.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 } from 'redux-form';
7 import { compose } from 'redux';
8 import { Autocomplete } from '~/components/autocomplete/autocomplete';
9 import { Vocabulary } from '~/models/vocabulary';
10 import { PROPERTY_KEY_FIELD_NAME } from '~/views-components/resource-properties-form/property-key-field';
11 import { VocabularyProp, connectVocabulary, buildProps } from '~/views-components/resource-properties-form/property-field-common';
12 import { TAG_VALUE_VALIDATION } from '~/validators/validators';
13
14 interface PropertyKeyProp {
15     propertyKey: string;
16 }
17
18 type PropertyValueFieldProps = VocabularyProp & PropertyKeyProp;
19
20 export const PROPERTY_VALUE_FIELD_NAME = 'value';
21
22 export const PropertyValueField = compose(
23     connectVocabulary,
24     formValues({ propertyKey: PROPERTY_KEY_FIELD_NAME })
25 )(
26     (props: PropertyValueFieldProps) =>
27         <Field
28             name={PROPERTY_VALUE_FIELD_NAME}
29             component={PropertyValueInput}
30             validate={getValidation(props)}
31             {...props} />);
32
33 const PropertyValueInput = ({ vocabulary, propertyKey, ...props }: WrappedFieldProps & PropertyValueFieldProps) =>
34     <Autocomplete
35         label='Value'
36         suggestions={getSuggestions(props.input.value, propertyKey, vocabulary)}
37         {...buildProps(props)}
38     />;
39
40 const getValidation = (props: PropertyValueFieldProps) =>
41     isStrictTag(props.propertyKey, props.vocabulary)
42         ? [...TAG_VALUE_VALIDATION, matchTagValues(props)]
43         : TAG_VALUE_VALIDATION;
44
45 const matchTagValues = ({ vocabulary, propertyKey }: PropertyValueFieldProps) =>
46     (value: string) =>
47         getTagValues(propertyKey, vocabulary).find(v => v.includes(value))
48             ? undefined
49             : 'Incorrect value';
50
51 const getSuggestions = (value: string, tagName: string, vocabulary: Vocabulary) =>
52     getTagValues(tagName, vocabulary).filter(v => v.includes(value) && v !== value);
53
54 const isStrictTag = (tagName: string, vocabulary: Vocabulary) => {
55     const tag = vocabulary.tags[tagName];
56     return tag ? tag.strict : false;
57 };
58
59 const getTagValues = (tagName: string, vocabulary: Vocabulary) => {
60     const tag = vocabulary.tags[tagName];
61     return tag && tag.values ? tag.values : [];
62 };