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';
16 interface VocabularyProp {
17 vocabulary: Vocabulary;
20 interface PropertyKeyProp {
24 type PropertyValueFieldProps = VocabularyProp & PropertyKeyProp;
26 const mapStateToProps = (state: RootState): VocabularyProp => ({
27 vocabulary: getVocabulary(state.properties),
30 export const PropertyValueField = compose(
31 connect(mapStateToProps),
32 formValues({ propertyKey: 'key' })
34 (props: PropertyValueFieldProps) =>
37 component={PropertyValueInput}
38 validate={getValidation(props)}
41 const PropertyValueInput = ({ input, meta, vocabulary, propertyKey }: WrappedFieldProps & PropertyValueFieldProps) =>
44 onChange={input.onChange}
46 suggestions={getSuggestions(input.value, propertyKey, vocabulary)}
47 items={ITEMS_PLACEHOLDER}
48 onSelect={input.onChange}
49 renderSuggestion={identity}
51 helperText={meta.error}
54 const getValidation = (props: PropertyValueFieldProps) =>
55 isStrictTag(props.propertyKey, props.vocabulary)
56 ? [require, matchTagValues(props)]
59 const matchTagValues = ({ vocabulary, propertyKey }: PropertyValueFieldProps) =>
61 getTagValues(propertyKey, vocabulary).find(v => v.includes(value))
65 const getSuggestions = (value: string, tagName: string, vocabulary: Vocabulary) =>
66 getTagValues(tagName, vocabulary).filter(v => v.includes(value) && v !== value);
68 const isStrictTag = (tagName: string, vocabulary: Vocabulary) => {
69 const tag = vocabulary.tags[tagName];
70 return tag ? tag.strict : false;
73 const getTagValues = (tagName: string, vocabulary: Vocabulary) => {
74 const tag = vocabulary.tags[tagName];
75 return tag ? tag.values : [];
78 const ITEMS_PLACEHOLDER: string[] = [];