Skip to content

[Image] Allow adjustment of aspect ratio #22

@Dangoo

Description

@Dangoo

Is your feature request related to a problem? Please describe.
Currently the Image component parses the originalWidth and originalHeight from the Storyblok image URL within getImageProps and returns them for imageProps as width and height:

const originalWidth = parseInt(dimensions?.[1]);
const originalHeight = parseInt(dimensions?.[2]);

These are then used for the dummy element spanning the container for the aspect ratio, which makes it impossible to adjust the aspect ratio from the outside:

paddingTop: `${(imageProps.height / imageProps.width) * 100}%`,

Describe the solution you'd like
Do you see a way to provide a desired aspect ratio through props or inferring them from fluid or fixed props when they contain width && height?
Maybe even the handling of the aspect ratio itself could be improved by using CSS aspect-ratio:

const supportsAspectRatio = CSS?.supports('aspect-ratio: 1/1') || false

const pictureStyles: CSSProperties = {
  /* ... */
  ...supportsAspectRatio && {aspectRatio: `${aspectRatio[0]} / ${aspectRatio[1]}`}
}

return (
  <Wrapper style={{ height, width }}>
    {!supportsAspectRatio && (
      <div
        aria-hidden
        style={{
          paddingTop: `${(imageProps.height / imageProps.width) * 100}%`,
        }}
      />
    )}
    <Picture
      {...pictureProps}
      style={{
        ...pictureStyles,
        /* ... */
      }}
    />
    ...
  </Wrapper>
)

Describe alternatives you've considered
For now we had to patch it from the outside using a custom wrapper:

export const PatchedImage: React.FC<ImageProps & {aspectRatio: [number, number]}> = ({
  aspectRatio,
  height,
  width,
  ...restProps
}) => {
  return (
    <div style={{ aspectRatio: `${aspectRatio[0]} / ${aspectRatio[1]}` }}>
      <Image {...restProps} fluid={[width, height]} width="100%" height="100%" />
    </div>
  )
}

Let me know what you think, happy to discuss the details or helping with the implementation :)

/cc @martinjuhasz

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions