File size: 1,459 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client"

import { Children, forwardRef } from "react"
import {
  type ConditionalValue,
  type HTMLChakraProps,
  chakra,
  defineStyle,
} from "../../styled-system"
import { cx, mapObject } from "../../utils"

export interface AspectRatioProps
  extends Omit<HTMLChakraProps<"div">, "aspectRatio"> {
  /**
   * The aspect ratio of the Box. Common values are:
   *
   * `21/9`, `16/9`, `9/16`, `4/3`, `1.85/1`
   */
  ratio?: ConditionalValue<number> | undefined
}

const baseStyle = defineStyle({
  "& > *:not(style)": {
    overflow: "hidden",
    position: "absolute",
    top: "0",
    right: "0",
    bottom: "0",
    left: "0",
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    width: "100%",
    height: "100%",
  },
  "& > img, & > video": {
    objectFit: "cover",
  },
})

export const AspectRatio = forwardRef<HTMLDivElement, AspectRatioProps>(
  function AspectRatio(props, ref) {
    const { ratio = 4 / 3, children, className, ...rest } = props
    const child = Children.only(children)

    return (
      <chakra.div
        ref={ref}
        position="relative"
        className={cx("chakra-aspect-ratio", className)}
        _before={{
          height: 0,
          content: `""`,
          display: "block",
          paddingBottom: mapObject(ratio, (r) => `${(1 / r) * 100}%`),
        }}
        {...rest}
        css={[baseStyle, props.css]}
      >
        {child}
      </chakra.div>
    )
  },
)