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