Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(gatsby-plugin-image): Add resolver helper and improve custom hook #29342

Merged
merged 14 commits into from
Feb 10, 2021

Conversation

ascorbic
Copy link
Contributor

@ascorbic ascorbic commented Feb 5, 2021

This PR adds a getGatsbyImageResolver helper, which is designed to be used with createResolvers. It creates the full field config, with the required args defined. You pass it the actual resolver function. This is easier to use than the current helper, which is based on the old sharp and Contentful resolvers which use the deprecated setFieldsOnGraphQLNodeType API. Usage for the new helper is:

import { getGatsbyImageResolver } from "gatsby-plugin-image/graphql-utils"

const resolveGatsbyImageData = async (image, options) => {
  const { filename, ...sourceMetadata } = getBasicImageProps(image, options)

  const generateImageSource = (imageName, width, height, format) => {
    const src = `https://myexamplehost.com/${width}x${height}/${imageName}.${format}`
    return { src, width, height, format }
  }

  return generateImageData({
    ...options,
    pluginName: `gatsby-source-myexample`,
    sourceMetadata,
    filename,
    generateImageSource,
  })
}

exports.createResolvers = ({ createResolvers }) => {
  createResolvers({
    ProductImage: {
      gatsbyImageData: getGatsbyImageResolver(resolveGatsbyImageData),
    },
  })
}

This PR also simplifies the useGatsbyImage hook, which is a helper to allow image hosts with URL APIs to create custom hooks and components supporting gatsby-plugin-image. The main requirement is for a URL builder function which can generate an image URL when given a base URL and dimensions.

The following is an example using the imgix rendering API. It defines a useImgix hook that returns an object which can be passed to <GatsbyImage>:

import { useGatsbyImage } from "gatsby-plugin-image";

function urlBuilder({ baseUrl, width, height, options }) {
    const props = {
        fit: "min",
        auto: "format",
        ...options,
        w: width,
        h: height,
    };
    const params = new URLSearchParams(Object.entries(props).map(([key, val]) => [key, val.toString()]));
    return `${baseUrl}?${params.toString()}`;
}

export function useImgix(props) {
    return useGatsbyImage({ pluginName: "useImgix", ...props, urlBuilder });
}

This can then be used like this:

export function Hat() {
  const image = useImgix({
    baseUrl: "https://assets.imgix.net/examples/hat.jpg",
    layout: "fullWidth",
    aspectRatio: 16 / 9,
  });

  return <GatsbyImage image={image} alt="Hat" />
}

It can also be used to create custom image components:

export function ImgixImage({
  src,
  width,
  height,
  layout,
  sourceWidth,
  sourceHeight,
  options,
  aspectRatio,
  backgroundColor,
  placeholderURL,
  pluginName = "ImgixImage",
  ...props
}) {
  const image = useImgix({
    baseUrl: src,
    width,
    height,
    layout,
    sourceWidth,
    sourceHeight,
    options,
    aspectRatio,
    backgroundColor,
    placeholderURL,
    pluginName,
  });
  return <GatsbyImage image={image} {...props} />;
};

...which can be used like this:

        <ImgixImage
          src="https://images.unsplash.com/34/BA1yLjNnQCI1yisIZGEi_2013-07-16_1922_IMG_9873.jpg"
          layout="constrained"
          width={800}
          height={600}
          alt="Mountains"
        />

@gatsbot gatsbot bot added the status: triage needed Issue or pull request that need to be triaged and assigned to a reviewer label Feb 5, 2021
@ascorbic ascorbic added topic: media Related to gatsby-plugin-image, or general image/media processing topics and removed status: triage needed Issue or pull request that need to be triaged and assigned to a reviewer labels Feb 5, 2021
@ascorbic ascorbic marked this pull request as draft February 5, 2021 13:39
@ascorbic ascorbic changed the title feat(gatsby-plugin-image): Add image url builder helper hook feat(gatsby-plugin-image): Add resolver helper improve custom hook hook Feb 9, 2021
@ascorbic ascorbic marked this pull request as ready for review February 9, 2021 16:24
@ascorbic ascorbic changed the title feat(gatsby-plugin-image): Add resolver helper improve custom hook hook feat(gatsby-plugin-image): Add resolver helper and improve custom hook hook Feb 9, 2021
@ascorbic ascorbic changed the title feat(gatsby-plugin-image): Add resolver helper and improve custom hook hook feat(gatsby-plugin-image): Add resolver helper and improve custom hook Feb 10, 2021
Copy link
Contributor

@laurieontech laurieontech left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me. Left one recommendation. The text is lifted from stuff we've already reviewed, so assuming that's boilerplate.

packages/gatsby-plugin-image/src/image-utils.ts Outdated Show resolved Hide resolved
Co-authored-by: LB <laurie@gatsbyjs.com>
Copy link
Contributor

@laurieontech laurieontech left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@ascorbic ascorbic merged commit e567aa8 into master Feb 10, 2021
@ascorbic ascorbic deleted the feat/image-url-builder branch February 10, 2021 16:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic: media Related to gatsby-plugin-image, or general image/media processing topics
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants