|
1 | | -import React, { ElementType } from 'react' |
| 1 | +import React, { ElementType, useContext } from 'react' |
2 | 2 | import styled from 'styled-components' |
3 | 3 | import { PC, PP, PR } from '../../types/PolymorphicElementProps' |
| 4 | +import { TableContext } from './TableContext' |
4 | 5 | import { TableRowGroupContext } from './TableRowGroupContext' |
5 | 6 |
|
6 | | -const TableHeadContainer = styled.thead` |
| 7 | +export interface TableHeadContainerProps { |
| 8 | + sticky: boolean | number | string |
| 9 | +} |
| 10 | + |
| 11 | +const getStickyValue = (sticky: boolean | number | string): string => { |
| 12 | + if (typeof sticky === 'number') { |
| 13 | + return `${sticky}px` |
| 14 | + } |
| 15 | + if (typeof sticky === 'string') { |
| 16 | + return sticky |
| 17 | + } |
| 18 | + return '0' |
| 19 | +} |
| 20 | + |
| 21 | +const TableHeadContainer = styled.thead<TableHeadContainerProps>` |
7 | 22 | display: table-header-group; |
8 | | - text-align: center; |
9 | | - font-weight: 700; |
| 23 | + ${({ sticky }) => |
| 24 | + (typeof sticky !== 'boolean' || sticky === true) && |
| 25 | + `position: sticky; top: ${getStickyValue(sticky)};`} |
10 | 26 | ` |
11 | 27 |
|
12 | | -export const TableHead: PC<'thead'> = React.forwardRef( |
13 | | - <T extends ElementType>(props: PP<T>, ref?: PR<T>) => { |
14 | | - const { as = 'thead', ...rest } = props |
| 28 | +export interface TableHeadProps { |
| 29 | + sticky?: boolean | number | string |
| 30 | +} |
| 31 | + |
| 32 | +export const TableHead: PC<'thead', TableHeadProps> = React.forwardRef( |
| 33 | + <T extends ElementType>(props: PP<T, TableHeadProps>, ref?: PR<T>) => { |
| 34 | + const tableContext = useContext(TableContext) |
| 35 | + const { sticky = tableContext.sticky, as = 'thead', ...rest } = props |
15 | 36 |
|
16 | 37 | return ( |
17 | 38 | <TableRowGroupContext.Provider value={{ header: true }}> |
18 | | - <TableHeadContainer ref={ref} as={as} {...rest} /> |
| 39 | + <TableHeadContainer sticky={sticky} ref={ref} as={as} {...rest} /> |
19 | 40 | </TableRowGroupContext.Provider> |
20 | 41 | ) |
21 | 42 | } |
|
0 commit comments