import type { ReactElement, ReactNode } from 'react';
import React, { useMemo } from 'react';
import type { StyleProp, ViewProps, ViewStyle, TextStyle } from 'react-native';
import { StyleSheet } from 'react-native';
import { Box, useTheme } from '@hero-design/rn';
import { generateBorderStyle, generateMarginStyle } from './utils';
interface FormGroupProps extends ViewProps {
/**
* The children of the FormGroup. In order for the group styling to work,
* they must be either HD form components (TextInput, Select, Pickers,...) or enhanced HD input components
* that supports the corresponding interface.
*
* Example:
* const EnhancedTextInput = (props: TextInputProps) => {
* return ;
* };
*
*
*
*
*
*/
children: ReactNode;
/**
* The style of the FormGroup.
*/
style?: StyleProp;
/**
* The testID of the FormGroup.
*/
testID?: string;
}
interface ChildProps extends ViewProps {
textStyle?: TextStyle;
groupStyleEnabled?: boolean;
inputProps?: {
textStyle?: TextStyle;
[key: string]: unknown;
};
}
const FormGroup = ({ children, style, testID, ...props }: FormGroupProps) => {
const theme = useTheme();
const childrenArray = React.Children.toArray(children).filter(
(child): child is ReactElement => React.isValidElement(child)
);
// If there are multiple children, inject styles to group them together.
const groupedChildren = useMemo(
() =>
childrenArray.map((child, index) => {
// Flatten styles to handle array styles
const childStyle = child.props.style
? StyleSheet.flatten(child.props.style)
: undefined;
const childTextStyle = child.props.textStyle
? StyleSheet.flatten(child.props.textStyle)
: undefined;
/**
* Merge the child style with the group injected style.
* Order of precedence:
* 1. Child style.
* 2. Group injected style.
*/
const mergedStyle = {
...(childStyle || {}),
...generateMarginStyle({
index,
length: childrenArray.length,
theme,
}),
};
/**
* Merge the child text style with the group text style.
* Order of precedence:
* 1. Group text style through textStyle prop.
* 2. Child text style.
* 3. Group injected border style.
*/
const mergedTextStyle = {
...(childTextStyle || {}),
...generateBorderStyle({
index,
length: childrenArray.length,
}),
};
return React.cloneElement(child, {
style: mergedStyle,
textStyle: mergedTextStyle,
// Internal text input prop to allow for different styling
groupStyleEnabled: true,
// For HD components that uses FormGroup
inputProps: {
...child.props.inputProps,
textStyle: {
...child.props.inputProps?.textStyle,
...mergedTextStyle,
},
},
});
}),
[childrenArray, theme]
);
return (
{groupedChildren}
);
};
export default FormGroup;