/*
 * Copyright (c) 2018-present, Revolut LTD.
 *
 * This source code is licensed under the Apache 2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import * as React from 'react'
import styled from 'styled-components'
import { space } from '../../style/utils'
import { SpaceProps } from 'styled-system'

type InjectorProps = {
  className?: string
  children: React.ReactElement<any> | React.ReactText
}

const Injector = styled(({ children, className }) =>
  // @ts-ignore
  React.cloneElement(children, { className }),
)<InjectorProps>`
  ${space};
`
/** Injects margins and padding to underlying descendant components without adding DOMElement container. Perfect for spacing management */
export const Space: React.FC<
  {
    children: React.ReactNode
  } & SpaceProps
> = ({ children, ...props }) => (
  <>
    {React.Children.map(children, child => (
      <Injector {...props}>{child as React.ReactElement}</Injector>
    ))}
  </>
)
