-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
hook.ts
85 lines (75 loc) · 2 KB
/
hook.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* External dependencies
*/
import { css } from '@emotion/react';
/**
* WordPress dependencies
*/
import { useMemo } from '@wordpress/element';
/**
* Internal dependencies
*/
import type { WordPressComponentProps } from '../context';
import { useContextSystem } from '../context';
import { getAlignmentProps } from './utils';
import { useResponsiveValue } from '../utils/use-responsive-value';
import CONFIG from '../utils/config-values';
import { useCx } from '../utils/hooks/use-cx';
import type { GridProps } from './types';
export default function useGrid(
props: WordPressComponentProps< GridProps, 'div' >
) {
const {
align,
alignment,
className,
columnGap,
columns = 2,
gap = 3,
isInline = false,
justify,
rowGap,
rows,
templateColumns,
templateRows,
...otherProps
} = useContextSystem( props, 'Grid' );
const columnsAsArray = Array.isArray( columns ) ? columns : [ columns ];
const column = useResponsiveValue( columnsAsArray );
const rowsAsArray = Array.isArray( rows ) ? rows : [ rows ];
const row = useResponsiveValue( rowsAsArray );
const gridTemplateColumns =
templateColumns || ( !! columns && `repeat( ${ column }, 1fr )` );
const gridTemplateRows =
templateRows || ( !! rows && `repeat( ${ row }, 1fr )` );
const cx = useCx();
const classes = useMemo( () => {
const alignmentProps = getAlignmentProps( alignment );
const gridClasses = css( {
alignItems: align,
display: isInline ? 'inline-grid' : 'grid',
gap: `calc( ${ CONFIG.gridBase } * ${ gap } )`,
gridTemplateColumns: gridTemplateColumns || undefined,
gridTemplateRows: gridTemplateRows || undefined,
gridRowGap: rowGap,
gridColumnGap: columnGap,
justifyContent: justify,
verticalAlign: isInline ? 'middle' : undefined,
...alignmentProps,
} );
return cx( gridClasses, className );
}, [
align,
alignment,
className,
columnGap,
cx,
gap,
gridTemplateColumns,
gridTemplateRows,
isInline,
justify,
rowGap,
] );
return { ...otherProps, className: classes };
}