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