Skip to content

Commit

Permalink
Fix(gatsby-plugin-image): Render LayoutWrapper prior to loading of la…
Browse files Browse the repository at this point in the history
…zy-hydrate (#28841)

* add layoutwrapper to intial render when lazy-hydrate hasn't yet run

* calculate sizer string
  • Loading branch information
LB authored Jan 7, 2021
1 parent 1769fc3 commit 78e5e47
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
import { PlaceholderProps } from "./placeholder"
import { MainImageProps } from "./main-image"
import { Layout } from "../image-utils"
import { getSizer } from "./layout-wrapper"

// eslint-disable-next-line @typescript-eslint/interface-name-prefix
export interface GatsbyImageProps
Expand Down Expand Up @@ -193,6 +194,8 @@ export const GatsbyImageHydrator: FunctionComponent<GatsbyImageProps> = function
props,
])

const sizer = getSizer(layout, width, height)

return (
<Type
{...wrapperProps}
Expand All @@ -203,7 +206,9 @@ export const GatsbyImageHydrator: FunctionComponent<GatsbyImageProps> = function
}}
className={`${wClass}${className ? ` ${className}` : ``}`}
ref={root}
dangerouslySetInnerHTML={{ __html: `` }}
dangerouslySetInnerHTML={{
__html: sizer,
}}
suppressHydrationWarning
/>
)
Expand Down
18 changes: 17 additions & 1 deletion packages/gatsby-plugin-image/src/components/layout-wrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,23 @@ if (hasNativeLazyLoadSupport) {
/>
)

export function getSizer(
layout: Layout,
width: number,
height: number
): string {
let sizer: string | null = null
if (layout === `fluid`) {
sizer = `<div aria-hidden="true" style="padding-top: ${
(height / width) * 100
}%;"></div>`
}
if (layout === `constrained`) {
sizer = `<div style="max-width: ${width}px; display: block;"><img alt="" role="presentation" aria-hidden="true" src="data:image/svg+xml;charset=utf-8,%3Csvg height='${height}' width='${width}' xmlns='http://www.w3.org/2000/svg' version='1.1'%3E%3C/svg%3E" style="max-width: 100%; display: block; position: static;"></div>`
}
return sizer
}

export const LayoutWrapper: FunctionComponent<ILayoutWrapperProps> = function LayoutWrapper({
layout,
width,
Expand Down Expand Up @@ -68,7 +85,6 @@ export const LayoutWrapper: FunctionComponent<ILayoutWrapperProps> = function La
</div>
)
}

return (
<Fragment>
{sizer}
Expand Down

0 comments on commit 78e5e47

Please sign in to comment.