Merge branch '15736-site-mgr' refs #15736
[arvados-workbench2.git] / src / views-components / resource-properties-form / property-value-field.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
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';
13 import { escapeRegExp } from '~/common/regexp.ts';
14
15 interface PropertyKeyProp {
16     propertyKey: string;
17 }
18
19 export type PropertyValueFieldProps = VocabularyProp & PropertyKeyProp;
20
21 export const PROPERTY_VALUE_FIELD_NAME = 'value';
22
23 export const PropertyValueField = compose(
24     connectVocabulary,
25     formValues({ propertyKey: PROPERTY_KEY_FIELD_NAME })
26 )(
27     (props: PropertyValueFieldProps) =>
28         <Field
29             name={PROPERTY_VALUE_FIELD_NAME}
30             component={PropertyValueInput}
31             validate={getValidation(props)}
32             {...props} />);
33
34 export const PropertyValueInput = ({ vocabulary, propertyKey, ...props }: WrappedFieldProps & PropertyValueFieldProps) =>
35     <Autocomplete
36         label='Value'
37         suggestions={getSuggestions(props.input.value, propertyKey, vocabulary)}
38         {...buildProps(props)}
39     />;
40
41 const getValidation = (props: PropertyValueFieldProps) =>
42     isStrictTag(props.propertyKey, props.vocabulary)
43         ? [...TAG_VALUE_VALIDATION, matchTagValues(props)]
44         : TAG_VALUE_VALIDATION;
45
46 const matchTagValues = ({ vocabulary, propertyKey }: PropertyValueFieldProps) =>
47     (value: string) =>
48         getTagValues(propertyKey, vocabulary).find(v => v.includes(value))
49             ? undefined
50             : 'Incorrect value';
51
52 const getSuggestions = (value: string, tagName: string, vocabulary: Vocabulary) => {
53     const re = new RegExp(escapeRegExp(value), "i");
54     return getTagValues(tagName, vocabulary).filter(v => re.test(v) && v !== value);
55 };
56
57 const isStrictTag = (tagName: string, vocabulary: Vocabulary) => {
58     const tag = vocabulary.tags[tagName];
59     return tag ? tag.strict : false;
60 };
61
62 const getTagValues = (tagName: string, vocabulary: Vocabulary) => {
63     const tag = vocabulary.tags[tagName];
64     return tag && tag.values ? tag.values : [];
65 };