1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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 import { PROPERTY_KEY_FIELD_NAME } from '~/views-components/resource-properties-form/property-key-field';
17 interface VocabularyProp {
18 vocabulary: Vocabulary;
21 interface PropertyKeyProp {
25 type PropertyValueFieldProps = VocabularyProp & PropertyKeyProp;
27 const mapStateToProps = (state: RootState): VocabularyProp => ({
28 vocabulary: getVocabulary(state.properties),
31 export const PROPERTY_VALUE_FIELD_NAME = 'value';
33 export const PropertyValueField = compose(
34 connect(mapStateToProps),
35 formValues({ propertyKey: PROPERTY_KEY_FIELD_NAME })
37 (props: PropertyValueFieldProps) =>
39 name={PROPERTY_VALUE_FIELD_NAME}
40 component={PropertyValueInput}
41 validate={getValidation(props)}
44 const PropertyValueInput = ({ input, meta, vocabulary, propertyKey }: WrappedFieldProps & PropertyValueFieldProps) =>
47 onChange={input.onChange}
49 suggestions={getSuggestions(input.value, propertyKey, vocabulary)}
50 items={ITEMS_PLACEHOLDER}
51 onSelect={input.onChange}
52 renderSuggestion={identity}
54 helperText={meta.error}
57 const getValidation = (props: PropertyValueFieldProps) =>
58 isStrictTag(props.propertyKey, props.vocabulary)
59 ? [require, matchTagValues(props)]
62 const matchTagValues = ({ vocabulary, propertyKey }: PropertyValueFieldProps) =>
64 getTagValues(propertyKey, vocabulary).find(v => v.includes(value))
68 const getSuggestions = (value: string, tagName: string, vocabulary: Vocabulary) =>
69 getTagValues(tagName, vocabulary).filter(v => v.includes(value) && v !== value);
71 const isStrictTag = (tagName: string, vocabulary: Vocabulary) => {
72 const tag = vocabulary.tags[tagName];
73 return tag ? tag.strict : false;
76 const getTagValues = (tagName: string, vocabulary: Vocabulary) => {
77 const tag = vocabulary.tags[tagName];
78 return tag ? tag.values : [];
81 const ITEMS_PLACEHOLDER: string[] = [];