nitro-react/src/common/Grid.tsx

64 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-03-01 09:23:44 +01:00
import { CSSProperties, FC, useMemo } from 'react';
2021-12-04 07:25:47 +01:00
import { Base, BaseProps } from './Base';
2022-02-09 04:25:01 +01:00
import { GridContextProvider } from './GridContext';
2022-02-21 05:28:33 +01:00
import { AlignItemType, AlignSelfType, JustifyContentType, SpacingType } from './types';
2021-12-04 07:25:47 +01:00
export interface GridProps extends BaseProps<HTMLDivElement>
{
inline?: boolean;
gap?: SpacingType;
2022-01-07 22:43:11 +01:00
maxContent?: boolean;
2022-02-16 07:40:54 +01:00
columnCount?: number;
2022-02-21 05:28:33 +01:00
center?: boolean;
alignSelf?: AlignSelfType;
alignItems?: AlignItemType;
justifyContent?: JustifyContentType;
2021-12-04 07:25:47 +01:00
}
export const Grid: FC<GridProps> = props =>
{
2022-02-21 05:28:33 +01:00
const { inline = false, gap = 2, maxContent = false, columnCount = 0, center = false, alignSelf = null, alignItems = null, justifyContent = null, fullHeight = true, classNames = [], style = {}, ...rest } = props;
2021-12-04 07:25:47 +01:00
const getClassNames = useMemo(() =>
{
2021-12-09 06:36:35 +01:00
const newClassNames: string[] = [];
2021-12-04 07:25:47 +01:00
if(inline) newClassNames.push('inline-grid');
else newClassNames.push('grid');
if(gap) newClassNames.push('gap-' + gap);
2022-01-12 05:01:59 +01:00
else if(gap === 0) newClassNames.push('gap-0');
2021-12-04 07:25:47 +01:00
2022-02-16 18:09:38 +01:00
if(maxContent) newClassNames.push('flex-basis-max-content');
2022-02-21 05:28:33 +01:00
if(alignSelf) newClassNames.push('align-self-' + alignSelf);
if(alignItems) newClassNames.push('align-items-' + alignItems);
if(justifyContent) newClassNames.push('justify-content-' + justifyContent);
if(!alignItems && !justifyContent && center) newClassNames.push('align-items-center', 'justify-content-center');
2021-12-04 07:25:47 +01:00
if(classNames.length) newClassNames.push(...classNames);
return newClassNames;
2022-02-21 05:28:33 +01:00
}, [ inline, gap, maxContent, alignSelf, alignItems, justifyContent, center, classNames ]);
2021-12-04 07:25:47 +01:00
const getStyle = useMemo(() =>
{
let newStyle: CSSProperties = {};
2022-02-16 07:40:54 +01:00
if(columnCount) newStyle['--bs-columns'] = columnCount.toString();
2021-12-04 07:25:47 +01:00
if(Object.keys(style).length) newStyle = { ...newStyle, ...style };
return newStyle;
2022-02-16 18:09:38 +01:00
}, [ columnCount, style ]);
2021-12-13 06:43:53 +01:00
2022-01-07 22:43:11 +01:00
return (
<GridContextProvider value={ { isCssGrid: true } }>
2022-02-16 07:40:54 +01:00
<Base fullHeight={ fullHeight } classNames={ getClassNames } style={ getStyle } { ...rest } />
2022-01-07 22:43:11 +01:00
</GridContextProvider>
);
2021-12-04 07:25:47 +01:00
}