import * as React from "react"; import styled, { StyledFunction, css } from "styled-components"; import * as tokens from "@tokens"; import { dim } from "@dim"; import { mq } from "@tokensDir/media-query"; import { BlockProps } from "./interface"; // Interface used only in media query so hacked around passing "any" down const Section: StyledFunction = styled.section; const getDisplayName = (children: any) => { const [child] = children; const { type: { displayName } } = child; return displayName; } const Grid = Section` display: grid; grid-template-rows: repeat(${props => props.count}, 1fr); ${({ children }: BlockProps) => getDisplayName(children) === 'StoryAnchorItem' && css` grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr; border-top: 1px solid ${tokens.colorGrey15}; border-bottom: 1px solid ${tokens.colorGrey15}; padding: ${dim(2)} 0; `} ${mq.md` display: grid; grid-template-columns: repeat(12, 1fr); grid-template-rows: 1fr; grid-column-gap: ${dim(4)}; padding: ${dim(2)} 0; text-align: center; ${({ children }: BlockProps) => getDisplayName(children) === 'StoryAnchorItem' && css` grid-template-rows: 1fr; `} `} `; const getLayout = { 1: [{column: '5 / span 4'}], 2: [{ column: '4 / span 3'}, { column: '7 / span 3' }], 3: [{ column: '1 / span 4'}, { column: '5 / span 4'}, { column: '9 / span 4' }], 4: [{ column: '1 / span 3'}, { column: '4 / span 3'}, { column: '7 / span 3' }, { column: '10 / span 3' }] }; const Block: React.FC<{}> = ({ children }) => { const count = React.Children.count(children); const columns = count <= 4 ? count : 4; const layout = getLayout[count]; const clones = React.Children.map(children, (child: any, i: number) => React.cloneElement(child, layout[i])); return { clones }; }; export default Block;