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 } from 'redux-form';
7 import { memoize } from 'lodash';
8 import { Autocomplete } from '~/components/autocomplete/autocomplete';
9 import { Vocabulary, getTags, getTagKeyID, PropFieldSuggestion } from '~/models/vocabulary';
10 import { connectVocabulary, VocabularyProp, buildProps } from '~/views-components/resource-properties-form/property-field-common';
11 import { TAG_KEY_VALIDATION } from '~/validators/validators';
12 import { COLLECTION_TAG_FORM_NAME } from '~/store/collection-panel/collection-panel-action';
14 export const PROPERTY_KEY_FIELD_NAME = 'key';
15 export const PROPERTY_KEY_FIELD_ID = 'keyID';
17 export const PropertyKeyField = connectVocabulary(
18 ({ vocabulary }: VocabularyProp) =>
21 name={PROPERTY_KEY_FIELD_NAME}
22 component={PropertyKeyInput}
23 vocabulary={vocabulary}
24 validate={getValidation(vocabulary)} />
26 name={PROPERTY_KEY_FIELD_ID}
32 export const PropertyKeyInput = ({ vocabulary, ...props }: WrappedFieldProps & VocabularyProp) =>
35 suggestions={getSuggestions(props.input.value, vocabulary)}
36 onSelect={handleSelect(props.input, props.meta)}
37 {...buildProps(props)}
38 onBlur={handleBlur(props.meta, props.input, vocabulary)}
41 const getValidation = memoize(
42 (vocabulary: Vocabulary) =>
43 vocabulary.strict_tags
44 ? [...TAG_KEY_VALIDATION, matchTags(vocabulary)]
45 : TAG_KEY_VALIDATION);
47 const matchTags = (vocabulary: Vocabulary) =>
49 getTags(vocabulary).find(tag => tag.label === value)
53 const getSuggestions = (value: string, vocabulary: Vocabulary) =>
54 getTags(vocabulary).filter(tag => tag.label.toLowerCase().includes(value.toLowerCase()));
56 // Attempts to match a manually typed key label with a key ID, when the user
57 // doesn't select the key from the suggestions list.
59 { dispatch }: WrappedFieldMetaProps,
60 { onBlur, value }: WrappedFieldInputProps,
61 vocabulary: Vocabulary) =>
63 dispatch(change(COLLECTION_TAG_FORM_NAME, PROPERTY_KEY_FIELD_ID, getTagKeyID(value, vocabulary)));
67 // When selecting a property key, save its ID for later usage.
68 const handleSelect = (
69 { onChange }: WrappedFieldInputProps,
70 { dispatch }: WrappedFieldMetaProps) => {
71 return (item:PropFieldSuggestion) => {
73 dispatch(change(COLLECTION_TAG_FORM_NAME, PROPERTY_KEY_FIELD_ID, item.id));