15840: Project panel uses collection attributes for file count and size
[arvados.git] / 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 const mapStateToProps = (state: RootState): VocabularyProp => ({
16     vocabulary: getVocabulary(state.properties),
17 });
18
19 export const connectVocabulary = connect(mapStateToProps);
20
21 export const ITEMS_PLACEHOLDER: string[] = [];
22
23 export const hasError = ({ touched, invalid }: WrappedFieldMetaProps) =>
24     touched && invalid;
25
26 export const getErrorMsg = (meta: WrappedFieldMetaProps) =>
27     hasError(meta)
28         ? meta.error
29         : '';
30
31 export const buildProps = ({ input, meta }: WrappedFieldProps) => {
32     return {
33         value: input.value,
34         onChange: input.onChange,
35         items: ITEMS_PLACEHOLDER,
36         renderSuggestion: (item:PropFieldSuggestion) => item.label,
37         error: hasError(meta),
38         helperText: getErrorMsg(meta),
39     };
40 };
41
42 // Attempts to match a manually typed value label with a value ID, when the user
43 // doesn't select the value from the suggestions list.
44 export const handleBlur = (
45     fieldName: string,
46     formName: string,
47     { dispatch }: WrappedFieldMetaProps,
48     { onBlur, value }: WrappedFieldInputProps,
49     fieldValue: string) =>
50         () => {
51             dispatch(change(formName, fieldName, fieldValue));
52             onBlur(value);
53         };
54
55 // When selecting a property value, save its ID for later usage.
56 export const handleSelect = (
57     fieldName: string,
58     formName: string,
59     { onChange }: WrappedFieldInputProps,
60     { dispatch }: WrappedFieldMetaProps ) =>
61         (item:PropFieldSuggestion) => {
62             if (item) {
63                 onChange(item.label);
64                 dispatch(change(formName, fieldName, item.id));
65             }
66         };