nitro-react/src/common/Grid.tsx

67 lines
2.1 KiB
TypeScript
Raw Normal View History

2021-12-04 07:25:47 +01:00
import { CSSProperties, FC, useMemo } from 'react';
import { Base, BaseProps } from './Base';
2022-01-07 22:43:11 +01:00
import { GridContextProvider } from './context/GridContext';
2021-12-04 07:25:47 +01:00
import { SpacingType } from './types/SpacingType';
export interface GridProps extends BaseProps<HTMLDivElement>
{
columnCount?: number;
columnMinWidth?: number;
2021-12-13 06:43:53 +01:00
columnMinHeight?: number;
2021-12-04 07:25:47 +01:00
grow?: boolean;
inline?: boolean;
gap?: SpacingType;
2022-01-07 22:43:11 +01:00
maxContent?: boolean;
2021-12-04 07:25:47 +01:00
}
export const Grid: FC<GridProps> = props =>
{
2022-01-07 22:43:11 +01:00
const { columnCount = 0, columnMinWidth = 40, columnMinHeight = 40, grow = false, inline = false, gap = 2, maxContent = false, 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[] = [];
if(!grow) newClassNames.push('h-100');
2022-01-11 07:38:01 +01:00
else newClassNames.push('flex-basis-fit-content');
2021-12-04 07:25:47 +01:00
if(inline) newClassNames.push('inline-grid');
else newClassNames.push('grid');
if(gap) newClassNames.push('gap-' + gap);
if(classNames.length) newClassNames.push(...classNames);
return newClassNames;
2021-12-09 06:36:35 +01:00
}, [ grow, inline, gap, classNames ]);
2021-12-04 07:25:47 +01:00
const getStyle = useMemo(() =>
{
let newStyle: CSSProperties = {};
if(columnCount)
{
newStyle['--bs-columns'] = columnCount.toString();
}
2022-01-06 03:59:46 +01:00
if(grow && (!columnCount || (columnCount > 1)))
2021-12-04 07:25:47 +01:00
{
newStyle['--nitro-grid-column-min-width'] = (columnMinWidth + 'px');
2021-12-13 06:43:53 +01:00
newStyle['--nitro-grid-column-min-height'] = (columnMinHeight + 'px');
2021-12-04 07:25:47 +01:00
newStyle.gridTemplateColumns = 'repeat(auto-fill, minmax(var(--nitro-grid-column-min-width, 45px), 1fr)';
}
2022-01-07 22:43:11 +01:00
if(maxContent) newStyle.gridTemplateRows = 'max-content';
2021-12-04 07:25:47 +01:00
if(Object.keys(style).length) newStyle = { ...newStyle, ...style };
return newStyle;
2022-01-07 22:43:11 +01:00
}, [ columnCount, columnMinWidth, columnMinHeight, grow, maxContent, style ]);
2021-12-13 06:43:53 +01:00
2022-01-07 22:43:11 +01:00
return (
<GridContextProvider value={ { isCssGrid: true } }>
<Base classNames={ getClassNames } style={ getStyle } { ...rest } />
</GridContextProvider>
);
2021-12-04 07:25:47 +01:00
}