Extract PROPERTY_KEY_FIELD_NAME to keep consistency between fields
[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 { connect } from 'react-redux';
8 import { identity, memoize } from 'lodash';
9 import { RootState } from '~/store/store';
10 import { getVocabulary } from '~/store/vocabulary/vocabulary-selctors';
11 import { Autocomplete } from '~/components/autocomplete/autocomplete';
12 import { Vocabulary } from '~/models/vocabulary';
13 import { require } from '~/validators/require';
14
15 interface VocabularyProp {
16     vocabulary: Vocabulary;
17 }
18
19 const mapStateToProps = (state: RootState): VocabularyProp => ({
20     vocabulary: getVocabulary(state.properties),
21 });
22
23 export const PROPERTY_KEY_FIELD_NAME = 'key';
24
25 export const PropertyKeyField = connect(mapStateToProps)(
26     ({ vocabulary }: VocabularyProp) =>
27         <Field
28             name={PROPERTY_KEY_FIELD_NAME}
29             component={PropertyKeyInput}
30             vocabulary={vocabulary}
31             validate={getValidation(vocabulary)} />);
32
33 const PropertyKeyInput = ({ input, meta, vocabulary }: WrappedFieldProps & VocabularyProp) =>
34     <Autocomplete
35         value={input.value}
36         onChange={input.onChange}
37         label='Key'
38         suggestions={getSuggestions(input.value, vocabulary)}
39         items={ITEMS_PLACEHOLDER}
40         onSelect={input.onChange}
41         renderSuggestion={identity}
42         error={meta.invalid}
43         helperText={meta.error}
44     />;
45
46 const getValidation = memoize(
47     (vocabulary: Vocabulary) =>
48         vocabulary.strict
49             ? [require, matchTags(vocabulary)]
50             : [require]);
51
52 const matchTags = (vocabulary: Vocabulary) =>
53     (value: string) =>
54         getTagsList(vocabulary).find(tag => tag.includes(value))
55             ? undefined
56             : 'Incorrect key';
57
58 const getSuggestions = (value: string, vocabulary: Vocabulary) =>
59     getTagsList(vocabulary).filter(tag => tag.includes(value) && tag !== value);
60
61 const getTagsList = ({ tags }: Vocabulary) =>
62     Object.keys(tags);
63
64 const ITEMS_PLACEHOLDER: string[] = [];