Skip to content

Commit

Permalink
fix(gatsby-source-wordpress): always hydrate images and use the right…
Browse files Browse the repository at this point in the history
… parent element (#36002)
  • Loading branch information
TylerBarnes authored Jun 29, 2022
1 parent 35ac324 commit 96c28bf
Showing 1 changed file with 27 additions and 16 deletions.
43 changes: 27 additions & 16 deletions packages/gatsby-source-wordpress/src/gatsby-browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,8 @@ import type { GatsbyImageProps } from "gatsby-plugin-image"
import React from "react"

let hydrateRef
let isFirstHydration = true
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent)

export function onRouteUpdate(): void {
if (
process.env.NODE_ENV === `production` &&
isFirstHydration &&
// Safari has a bug that causes images to stay blank when directly loading a page (images load when client-side navigating)
// running this code on first hydration makes images load.
!isSafari
) {
isFirstHydration = false
return
}

if (`requestIdleCallback` in window) {
if (hydrateRef) {
// @ts-ignore cancelIdleCallback is on window object
Expand Down Expand Up @@ -59,7 +46,31 @@ function hydrateImages(): void {
/* webpackChunkName: "gatsby-plugin-image" */ `gatsby-plugin-image`
).then(mod => {
inlineWPimages.forEach(image => {
if (image.dataset && image.dataset.wpInlineImage && image.parentNode) {
// usually this is the right element to hydrate on
const grandParentIsGatsbyImage =
// @ts-ignore-next-line classList is on HTMLElement
image?.parentNode?.parentNode?.classList?.contains(
`gatsby-image-wrapper`
)

// but sometimes this is the right element
const parentIsGatsbyImage =
// @ts-ignore-next-line classList is on HTMLElement
image?.parentNode?.classList?.contains(`gatsby-image-wrapper`)

if (!grandParentIsGatsbyImage && !parentIsGatsbyImage) {
return
}

const gatsbyImageHydrationElement = grandParentIsGatsbyImage
? image.parentNode.parentNode
: image.parentNode

if (
image.dataset &&
image.dataset.wpInlineImage &&
gatsbyImageHydrationElement
) {
const hydrationData = doc.querySelector(
`script[data-wp-inline-image-hydration="${image.dataset.wpInlineImage}"]`
)
Expand All @@ -70,12 +81,12 @@ function hydrateImages(): void {
)

if (ReactDOM.createRoot) {
const root = ReactDOM.createRoot(image.parentNode)
const root = ReactDOM.createRoot(gatsbyImageHydrationElement)
root.render(React.createElement(mod.GatsbyImage, imageProps))
} else {
ReactDOM.hydrate(
React.createElement(mod.GatsbyImage, imageProps),
image.parentNode
gatsbyImageHydrationElement
)
}
}
Expand Down

0 comments on commit 96c28bf

Please sign in to comment.