nitro-react/src/common/Base.tsx

68 lines
2.1 KiB
TypeScript
Raw Normal View History

2021-12-04 07:25:47 +01:00
import { CSSProperties, DetailedHTMLProps, FC, HTMLAttributes, LegacyRef, useMemo } from 'react';
2022-02-09 04:25:01 +01:00
import { ColorVariantType, OverflowType, PositionType } from './types';
2021-12-04 07:25:47 +01:00
export interface BaseProps<T = HTMLElement> extends DetailedHTMLProps<HTMLAttributes<T>, T>
{
innerRef?: LegacyRef<T>;
fit?: boolean;
2022-01-06 03:59:46 +01:00
grow?: boolean;
shrink?: boolean;
2021-12-04 07:25:47 +01:00
fullWidth?: boolean;
fullHeight?: boolean;
overflow?: OverflowType;
position?: PositionType;
pointer?: boolean;
2022-01-07 22:43:11 +01:00
textColor?: ColorVariantType;
2021-12-04 07:25:47 +01:00
classNames?: string[];
}
export const Base: FC<BaseProps<HTMLDivElement>> = props =>
{
2022-01-07 22:43:11 +01:00
const { ref = null, innerRef = null, fit = false, grow = false, shrink = false, fullWidth = false, fullHeight = false, overflow = null, position = null, pointer = false, textColor = null, classNames = [], className = '', style = {}, ...rest } = props;
2021-12-04 07:25:47 +01:00
const getClassNames = useMemo(() =>
{
const newClassNames: string[] = [];
if(fit || fullWidth) newClassNames.push('w-100');
if(fit || fullHeight) newClassNames.push('h-100');
2022-01-06 03:59:46 +01:00
if(grow) newClassNames.push('flex-grow-1');
if(shrink) newClassNames.push('flex-shrink-0');
2021-12-04 07:25:47 +01:00
if(overflow) newClassNames.push('overflow-' + overflow);
if(position) newClassNames.push('position-' + position);
if(pointer) newClassNames.push('cursor-pointer');
2022-01-07 22:43:11 +01:00
if(textColor) newClassNames.push('text-' + textColor);
2021-12-04 07:25:47 +01:00
if(classNames.length) newClassNames.push(...classNames);
return newClassNames;
2022-01-07 22:43:11 +01:00
}, [ fit, grow, shrink, fullWidth, fullHeight, overflow, position, pointer, textColor, classNames ]);
2021-12-04 07:25:47 +01:00
const getClassName = useMemo(() =>
{
let newClassName = getClassNames.join(' ');
if(className.length) newClassName += (' ' + className);
return newClassName;
}, [ getClassNames, className ]);
const getStyle = useMemo(() =>
{
let newStyle: CSSProperties = {};
if(Object.keys(style).length) newStyle = { ...newStyle, ...style };
return newStyle;
}, [ style ]);
return <div ref={ innerRef } className={ getClassName } style={ getStyle } { ...rest } />;
}