Create PropertyKeyField
[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 PropertyKeyField = connect(mapStateToProps)(
24     ({ vocabulary }: VocabularyProp) =>
25         <Field
26             name='key'
27             component={PropertyKeyInput}
28             vocabulary={vocabulary}
29             validate={getValidation(vocabulary)} />);
30
31 const PropertyKeyInput = ({ input, meta, vocabulary }: WrappedFieldProps & VocabularyProp) =>
32     <Autocomplete
33         value={input.value}
34         onChange={input.onChange}
35         label='Key'
36         suggestions={getSuggestions(input.value, vocabulary)}
37         items={ITEMS_PLACEHOLDER}
38         onSelect={input.onChange}
39         renderSuggestion={identity}
40         error={meta.invalid}
41         helperText={meta.error}
42     />;
43
44 const getValidation = memoize(
45     (vocabulary: Vocabulary) =>
46         vocabulary.strict
47             ? [require, matchTags(vocabulary)]
48             : [require]);
49
50 const matchTags = (vocabulary: Vocabulary) =>
51     (value: string) =>
52         getTagsList(vocabulary).find(tag => tag.includes(value))
53             ? undefined
54             : 'Incorrect key';
55
56 const getSuggestions = (value: string, vocabulary: Vocabulary) => 
57     getTagsList(vocabulary).filter(tag => tag.includes(value) && tag !== value);
58
59 const getTagsList = ({ tags }: Vocabulary) =>
60     Object.keys(tags);
61
62 const ITEMS_PLACEHOLDER: string[] = [];