1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import * as React from 'react';
6 import { change, WrappedFieldProps, WrappedFieldMetaProps, WrappedFieldInputProps, 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_ID } from '~/views-components/resource-properties-form/property-key-field';
11 import { VocabularyProp, connectVocabulary, buildProps, PropFieldSuggestion } from '~/views-components/resource-properties-form/property-field-common';
12 import { TAG_VALUE_VALIDATION } from '~/validators/validators';
13 import { COLLECTION_TAG_FORM_NAME } from '~/store/collection-panel/collection-panel-action';
15 interface PropertyKeyProp {
19 export type PropertyValueFieldProps = VocabularyProp & PropertyKeyProp;
21 export const PROPERTY_VALUE_FIELD_NAME = 'value';
22 export const PROPERTY_VALUE_FIELD_ID = 'valueID';
24 export const PropertyValueField = compose(
26 formValues({ propertyKey: PROPERTY_KEY_FIELD_ID })
28 (props: PropertyValueFieldProps) =>
31 name={PROPERTY_VALUE_FIELD_NAME}
32 component={PropertyValueInput}
33 validate={getValidation(props)}
36 name={PROPERTY_VALUE_FIELD_ID}
42 export const PropertyValueInput = ({ vocabulary, propertyKey, ...props }: WrappedFieldProps & PropertyValueFieldProps) =>
45 suggestions={getSuggestions(props.input.value, propertyKey, vocabulary)}
46 onSelect={handleSelect(props.input, props.meta)}
47 {...buildProps(props)}
50 const getValidation = (props: PropertyValueFieldProps) =>
51 isStrictTag(props.propertyKey, props.vocabulary)
52 ? [...TAG_VALUE_VALIDATION, matchTagValues(props)]
53 : TAG_VALUE_VALIDATION;
55 const matchTagValues = ({ vocabulary, propertyKey }: PropertyValueFieldProps) =>
57 getTagValues(propertyKey, vocabulary).find(v => v.label === value)
61 const getSuggestions = (value: string, tagKey: string, vocabulary: Vocabulary) =>
62 getTagValues(tagKey, vocabulary).filter(v => v.label.toLowerCase().includes(value.toLowerCase()));
64 const isStrictTag = (tagKey: string, vocabulary: Vocabulary) => {
65 const tag = vocabulary.tags[tagKey];
66 return tag ? tag.strict : false;
69 const getTagValues = (tagKey: string, vocabulary: Vocabulary) => {
70 const tag = vocabulary.tags[tagKey];
71 const ret = tag && tag.values
72 ? Object.keys(tag.values).map(
73 tagValueID => tag.values![tagValueID].labels
74 ? {"id": tagValueID, "label": tag.values![tagValueID].labels[0].label}
75 : {"id": tagValueID, "label": tagValueID})
80 const handleSelect = (
81 { onChange }: WrappedFieldInputProps,
82 { dispatch }: WrappedFieldMetaProps) => {
83 return (item:PropFieldSuggestion) => {
85 dispatch(change(COLLECTION_TAG_FORM_NAME, PROPERTY_VALUE_FIELD_ID, item.id));