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 { 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 } from '~/views-components/resource-properties-form/property-field-common';
15 interface PropertyKeyProp {
19 type PropertyValueFieldProps = VocabularyProp & PropertyKeyProp;
21 export const PROPERTY_VALUE_FIELD_NAME = 'value';
23 export const PropertyValueField = compose(
25 formValues({ propertyKey: PROPERTY_KEY_FIELD_NAME })
27 (props: PropertyValueFieldProps) =>
29 name={PROPERTY_VALUE_FIELD_NAME}
30 component={PropertyValueInput}
31 validate={getValidation(props)}
34 const PropertyValueInput = ({ input, meta, vocabulary, propertyKey }: WrappedFieldProps & PropertyValueFieldProps) =>
37 onChange={input.onChange}
39 suggestions={getSuggestions(input.value, propertyKey, vocabulary)}
40 items={ITEMS_PLACEHOLDER}
41 onSelect={input.onChange}
42 renderSuggestion={identity}
44 helperText={meta.error}
47 const getValidation = (props: PropertyValueFieldProps) =>
48 isStrictTag(props.propertyKey, props.vocabulary)
49 ? [require, matchTagValues(props)]
52 const matchTagValues = ({ vocabulary, propertyKey }: PropertyValueFieldProps) =>
54 getTagValues(propertyKey, vocabulary).find(v => v.includes(value))
58 const getSuggestions = (value: string, tagName: string, vocabulary: Vocabulary) =>
59 getTagValues(tagName, vocabulary).filter(v => v.includes(value) && v !== value);
61 const isStrictTag = (tagName: string, vocabulary: Vocabulary) => {
62 const tag = vocabulary.tags[tagName];
63 return tag ? tag.strict : false;
66 const getTagValues = (tagName: string, vocabulary: Vocabulary) => {
67 const tag = vocabulary.tags[tagName];
68 return tag && tag.values ? tag.values : [];