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 { compose } from 'redux';
8 import { Autocomplete } from '~/components/autocomplete/autocomplete';
9 import { Vocabulary } from '~/models/vocabulary';
10 import { PROPERTY_KEY_FIELD_NAME } from '~/views-components/resource-properties-form/property-key-field';
11 import { VocabularyProp, connectVocabulary, buildProps } from '~/views-components/resource-properties-form/property-field-common';
12 import { TAG_VALUE_VALIDATION } from '~/validators/validators';
14 interface PropertyKeyProp {
18 export type PropertyValueFieldProps = VocabularyProp & PropertyKeyProp;
20 export const PROPERTY_VALUE_FIELD_NAME = 'value';
22 export const PropertyValueField = compose(
24 formValues({ propertyKey: PROPERTY_KEY_FIELD_NAME })
26 (props: PropertyValueFieldProps) =>
28 name={PROPERTY_VALUE_FIELD_NAME}
29 component={PropertyValueInput}
30 validate={getValidation(props)}
33 export const PropertyValueInput = ({ vocabulary, propertyKey, ...props }: WrappedFieldProps & PropertyValueFieldProps) =>
36 suggestions={getSuggestions(props.input.value, propertyKey, vocabulary)}
37 {...buildProps(props)}
40 const getValidation = (props: PropertyValueFieldProps) =>
41 isStrictTag(props.propertyKey, props.vocabulary)
42 ? [...TAG_VALUE_VALIDATION, matchTagValues(props)]
43 : TAG_VALUE_VALIDATION;
45 const matchTagValues = ({ vocabulary, propertyKey }: PropertyValueFieldProps) =>
47 getTagValues(propertyKey, vocabulary).find(v => v.label === value)
51 const getSuggestions = (value: string, tagKey: string, vocabulary: Vocabulary) =>
52 getTagValues(tagKey, vocabulary).filter(v => v.label.toLowerCase().includes(value.toLowerCase()));
54 const isStrictTag = (tagKey: string, vocabulary: Vocabulary) => {
55 const tag = vocabulary.tags[getTagID(tagKey, vocabulary)];
56 return tag ? tag.strict : false;
59 const getTagID = (tagKeyLabel:string, vocabulary: Vocabulary) =>
60 Object.keys(vocabulary.tags).find(
61 k => vocabulary.tags[k].labels.find(
62 l => l.label === tagKeyLabel) !== undefined) || tagKeyLabel;
64 const getTagValues = (tagKey: string, vocabulary: Vocabulary) => {
65 const tag = vocabulary.tags[getTagID(tagKey, vocabulary)];
66 const ret = tag && tag.values
67 ? Object.keys(tag.values).map(
68 tagValueID => tag.values![tagValueID].labels
69 ? {"id": tagValueID, "label": tag.values![tagValueID].labels[0].label}
70 : {"id": tagValueID, "label": tagValueID})