|
| 1 | +/** |
| 2 | + * The Spacer component is responsible for handling the space UI. |
| 3 | + * This component can create 3 types of spaces that is flex, preset and pixel type. |
| 4 | + * You should avoid using "size" prop that allow input in units of pixels for coherent spatial processing. |
| 5 | + */ |
| 6 | + |
| 7 | +import React from 'react'; |
| 8 | +import { View, ViewStyle } from 'react-native'; |
| 9 | +import { Spacing, spacing } from '../../theme'; |
| 10 | +import { isNilOrEmpty } from '../../utils'; |
| 11 | + |
| 12 | +interface SpacerDirection { |
| 13 | + direction?: 'both' | 'vertical' | 'horizontal'; |
| 14 | +} |
| 15 | + |
| 16 | +interface FlexSpacerProps extends SpacerDirection { |
| 17 | + /** |
| 18 | + * flex type is joint 1st place priority. Strictly speaking, this is First. |
| 19 | + * If you don't know flex layout, Reference https://reactnative.dev/docs/flexbox. |
| 20 | + */ |
| 21 | + flex: number; |
| 22 | + /** |
| 23 | + * When using the above props, you should never use any other props. |
| 24 | + */ |
| 25 | + preset?: never; |
| 26 | + size?: never; |
| 27 | +} |
| 28 | + |
| 29 | +interface PresetSpacerProps extends SpacerDirection { |
| 30 | + /** |
| 31 | + * preset Type is joint 1st place priority. |
| 32 | + */ |
| 33 | + preset: Spacing; |
| 34 | + /** |
| 35 | + * When using the above props, you should never use any other props. |
| 36 | + */ |
| 37 | + flex?: never; |
| 38 | + size?: never; |
| 39 | +} |
| 40 | + |
| 41 | +interface SizeSpacerProps extends SpacerDirection { |
| 42 | + /** |
| 43 | + * size has the lowest priority. |
| 44 | + * because The use of size is not recommended because UI & UX quality is often poor. |
| 45 | + */ |
| 46 | + size?: number; |
| 47 | + /** |
| 48 | + * When using the above props, you should never use any other props. |
| 49 | + */ |
| 50 | + preset?: never; |
| 51 | + flex?: never; |
| 52 | +} |
| 53 | + |
| 54 | +type SpacerProps = PresetSpacerProps | FlexSpacerProps | SizeSpacerProps; |
| 55 | + |
| 56 | +export function Spacer(props: SpacerProps) { |
| 57 | + const { direction = 'both', flex, preset, size: pixelSize, ...rest } = props; |
| 58 | + |
| 59 | + // @ts-ignore |
| 60 | + const presetSize = spacing[preset]; |
| 61 | + const value = presetSize ? presetSize : pixelSize; |
| 62 | + |
| 63 | + const style: ViewStyle = { |
| 64 | + flex: flex ? flex : undefined, |
| 65 | + width: |
| 66 | + direction === 'both' || direction === 'horizontal' ? value : undefined, |
| 67 | + height: |
| 68 | + direction === 'both' || direction === 'vertical' ? value : undefined, |
| 69 | + }; |
| 70 | + |
| 71 | + if (__DEV__ && isNilOrEmpty(value)) { |
| 72 | + console.warn(`Spacer component's value is nil or empty!`); |
| 73 | + } |
| 74 | + |
| 75 | + return <View style={style} {...rest} />; |
| 76 | +} |
0 commit comments