21700: Install Bundler system-wide in Rails postinst
[arvados.git] / services / workbench2 / src / views-components / resource-properties-form / property-field-common.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { connect } from 'react-redux';
6 import { change, WrappedFieldMetaProps, WrappedFieldInputProps, WrappedFieldProps } from 'redux-form';
7 import { Vocabulary, PropFieldSuggestion } from 'models/vocabulary';
8 import { RootState } from 'store/store';
9 import { getVocabulary } from 'store/vocabulary/vocabulary-selectors';
10
11 export interface VocabularyProp {
12     vocabulary: Vocabulary;
13 }
14
15 export interface ValidationProp {
16     skipValidation?: boolean;
17     clearPropertyKeyOnSelect?: boolean;
18 }
19
20 export const mapStateToProps = (state: RootState, ownProps: ValidationProp): VocabularyProp & ValidationProp => ({
21     skipValidation: ownProps.skipValidation,
22     vocabulary: getVocabulary(state.properties),
23 });
24
25 export const connectVocabulary = connect(mapStateToProps);
26
27 export const ITEMS_PLACEHOLDER: string[] = [];
28
29 export const hasError = ({ touched, invalid }: WrappedFieldMetaProps) =>
30     touched && invalid;
31
32 export const getErrorMsg = (meta: WrappedFieldMetaProps) =>
33     hasError(meta)
34         ? meta.error
35         : '';
36
37 export const buildProps = ({ input, meta }: WrappedFieldProps) => {
38     return {
39         value: input.value,
40         items: ITEMS_PLACEHOLDER,
41         renderSuggestion: (item: PropFieldSuggestion) => item.label,
42         error: hasError(meta),
43         helperText: getErrorMsg(meta),
44     };
45 };
46
47 // Attempts to match a manually typed value label with a value ID, when the user
48 // doesn't select the value from the suggestions list.
49 export const handleBlur = (
50     fieldName: string,
51     formName: string,
52     { dispatch }: WrappedFieldMetaProps,
53     { onBlur, value }: WrappedFieldInputProps,
54     fieldValue: string) =>
55     () => {
56         dispatch(change(formName, fieldName, fieldValue));
57         onBlur(value);
58     };
59
60 // When selecting a property value, save its ID for later usage.
61 export const handleSelect = (
62     fieldName: string,
63     formName: string,
64     { onChange }: WrappedFieldInputProps,
65     { dispatch }: WrappedFieldMetaProps) =>
66     (item: PropFieldSuggestion) => {
67         if (item) {
68             onChange(item.label);
69             dispatch(change(formName, fieldName, item.id));
70         }
71     };