Extract property-field-common module
[arvados-workbench2.git] / src / views-components / resource-properties-form / property-key-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 } from 'redux-form';
7 import { identity, memoize } from 'lodash';
8 import { Autocomplete } from '~/components/autocomplete/autocomplete';
9 import { Vocabulary } from '~/models/vocabulary';
10 import { require } from '~/validators/require';
11 import { ITEMS_PLACEHOLDER, connectVocabulary, VocabularyProp } from '~/views-components/resource-properties-form/property-field-common';
12
13 export const PROPERTY_KEY_FIELD_NAME = 'key';
14
15 export const PropertyKeyField = connectVocabulary(
16     ({ vocabulary }: VocabularyProp) =>
17         <Field
18             name={PROPERTY_KEY_FIELD_NAME}
19             component={PropertyKeyInput}
20             vocabulary={vocabulary}
21             validate={getValidation(vocabulary)} />);
22
23 const PropertyKeyInput = ({ input, meta, vocabulary }: WrappedFieldProps & VocabularyProp) =>
24     <Autocomplete
25         value={input.value}
26         onChange={input.onChange}
27         label='Key'
28         suggestions={getSuggestions(input.value, vocabulary)}
29         items={ITEMS_PLACEHOLDER}
30         onSelect={input.onChange}
31         renderSuggestion={identity}
32         error={meta.invalid}
33         helperText={meta.error}
34     />;
35
36 const getValidation = memoize(
37     (vocabulary: Vocabulary) =>
38         vocabulary.strict
39             ? [require, matchTags(vocabulary)]
40             : [require]);
41
42 const matchTags = (vocabulary: Vocabulary) =>
43     (value: string) =>
44         getTagsList(vocabulary).find(tag => tag.includes(value))
45             ? undefined
46             : 'Incorrect key';
47
48 const getSuggestions = (value: string, vocabulary: Vocabulary) =>
49     getTagsList(vocabulary).filter(tag => tag.includes(value) && tag !== value);
50
51 const getTagsList = ({ tags }: Vocabulary) =>
52     Object.keys(tags);