nitro-react/src/common/Base.tsx

74 lines
2.4 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-21 05:28:33 +01:00
import { ColorVariantType, FloatType, 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;
2022-02-21 05:28:33 +01:00
float?: FloatType;
2021-12-04 07:25:47 +01:00
pointer?: boolean;
2022-03-01 09:23:44 +01:00
visible?: 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-03-01 09:23:44 +01:00
const { ref = null, innerRef = null, fit = false, grow = false, shrink = false, fullWidth = false, fullHeight = false, overflow = null, position = null, float = null, pointer = false, visible = null, 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);
2022-02-21 05:28:33 +01:00
if(float) newClassNames.push('float-' + float);
2021-12-04 07:25:47 +01:00
if(pointer) newClassNames.push('cursor-pointer');
2022-03-01 09:23:44 +01:00
if(visible !== null) newClassNames.push(visible ? 'visible' : 'invisible');
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-03-01 09:23:44 +01:00
}, [ fit, grow, shrink, fullWidth, fullHeight, overflow, position, float, pointer, visible, textColor, classNames ]);
2021-12-04 07:25:47 +01:00
const getClassName = useMemo(() =>
{
let newClassName = getClassNames.join(' ');
if(className.length) newClassName += (' ' + className);
2022-02-22 07:40:22 +01:00
return newClassName.trim();
2021-12-04 07:25:47 +01:00
}, [ 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 } />;
}