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 PropertyValueField = compose(
32 connect(mapStateToProps),
33 formValues({ propertyKey: PROPERTY_KEY_FIELD_NAME })
35 (props: PropertyValueFieldProps) =>
38 component={PropertyValueInput}
39 validate={getValidation(props)}
42 const PropertyValueInput = ({ input, meta, vocabulary, propertyKey }: WrappedFieldProps & PropertyValueFieldProps) =>
45 onChange={input.onChange}
47 suggestions={getSuggestions(input.value, propertyKey, vocabulary)}
48 items={ITEMS_PLACEHOLDER}
49 onSelect={input.onChange}
50 renderSuggestion={identity}
52 helperText={meta.error}
55 const getValidation = (props: PropertyValueFieldProps) =>
56 isStrictTag(props.propertyKey, props.vocabulary)
57 ? [require, matchTagValues(props)]
60 const matchTagValues = ({ vocabulary, propertyKey }: PropertyValueFieldProps) =>
62 getTagValues(propertyKey, vocabulary).find(v => v.includes(value))
66 const getSuggestions = (value: string, tagName: string, vocabulary: Vocabulary) =>
67 getTagValues(tagName, vocabulary).filter(v => v.includes(value) && v !== value);
69 const isStrictTag = (tagName: string, vocabulary: Vocabulary) => {
70 const tag = vocabulary.tags[tagName];
71 return tag ? tag.strict : false;
74 const getTagValues = (tagName: string, vocabulary: Vocabulary) => {
75 const tag = vocabulary.tags[tagName];
76 return tag ? tag.values : [];
79 const ITEMS_PLACEHOLDER: string[] = [];