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';
13 import { escapeRegExp } from '~/common/regexp.ts';
15 export const PROPERTY_KEY_FIELD_NAME = 'key';
16 export const PROPERTY_KEY_FIELD_ID = 'keyID';
18 export const PropertyKeyField = connectVocabulary(
19 ({ vocabulary }: VocabularyProp) =>
22 name={PROPERTY_KEY_FIELD_NAME}
23 component={PropertyKeyInput}
24 vocabulary={vocabulary}
25 validate={getValidation(vocabulary)} />
27 name={PROPERTY_KEY_FIELD_ID}
33 export const PropertyKeyInput = ({ vocabulary, ...props }: WrappedFieldProps & VocabularyProp) =>
36 suggestions={getSuggestions(props.input.value, vocabulary)}
37 onSelect={handleSelect(props.input, props.meta)}
38 {...buildProps(props)}
39 onBlur={handleBlur(props.meta, props.input, vocabulary)}
42 const getValidation = memoize(
43 (vocabulary: Vocabulary) =>
44 vocabulary.strict_tags
45 ? [...TAG_KEY_VALIDATION, matchTags(vocabulary)]
46 : TAG_KEY_VALIDATION);
48 const matchTags = (vocabulary: Vocabulary) =>
50 getTags(vocabulary).find(tag => tag.label === value)
54 const getSuggestions = (value: string, vocabulary: Vocabulary) => {
55 const re = new RegExp(escapeRegExp(value), "i");
56 return getTags(vocabulary).filter(tag => re.test(tag.label) && tag.label !== value);
59 // Attempts to match a manually typed key label with a key ID, when the user
60 // doesn't select the key from the suggestions list.
62 { dispatch }: WrappedFieldMetaProps,
63 { onBlur, value }: WrappedFieldInputProps,
64 vocabulary: Vocabulary) =>
66 dispatch(change(COLLECTION_TAG_FORM_NAME, PROPERTY_KEY_FIELD_ID, getTagKeyID(value, vocabulary)));
70 // When selecting a property key, save its ID for later usage.
71 const handleSelect = (
72 { onChange }: WrappedFieldInputProps,
73 { dispatch }: WrappedFieldMetaProps) => {
74 return (item:PropFieldSuggestion) => {
76 dispatch(change(COLLECTION_TAG_FORM_NAME, PROPERTY_KEY_FIELD_ID, item.id));