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

Image Pipeline Update #95

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 52 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Source plugin for pulling data from [Sanity.io](https://www.sanity.io/) into [Gatsby](https://www.gatsbyjs.org/) websites. Develop with real-time preview of all content changes. Compatible with `gatsby-image`.

Get up and running in minutes with a fully configured starter project:
Get up and running in minutes with a fully configured starter project:
* [Blog with Gatsby](https://www.sanity.io/create?template=sanity-io/sanity-template-gatsby-blog)
* [Portfolio with Gatsby](https://www.sanity.io/create?template=sanity-io/sanity-template-gatsby-portfolio).

Expand Down Expand Up @@ -197,6 +197,57 @@ const fluidProps = getFluidGatsbyImage(imageAssetId, {maxWidth: 1024}, sanityCon
<Img fluid={fluidProps} />
```

### Interacting with the Image Pipeline

As part of its [Image Pipeline](https://www.sanity.io/docs/presenting-images), Sanity provides many useful [options for transforming images](https://www.sanity.io/docs/image-urls) by manipulating their URL when requesting them from the Sanity CDN.

In this package we expose a subset of the options available for Sanity Image Transformations. We dont supply definition for the full list of options due to much of the work in these functions being specific to resizing and anticipating image dimensions for responsive sizing. That is, we don't want to allow customization here that may impact expected image ratios when generating the fixed/fluid images for Gatsby.

The exposed options are: `bg`, `blur`, `fm`, `invert`, `q`, `sat`, and `sharpen`. You can read more about each of these options in the [Image URL documentation](https://www.sanity.io/docs/image-urls).

##### Usage with GraphQL

To pass these arguments using the GraphQL API, you may include an additional argument, `imagePipelineArgs`, block when calling both `fixed` and `fluid`. For example, the following query will add Image Pipeline arguments, passing `q` to specify an image quality:

```js
export const query = graphql`
query PersonQuery {
sanityPerson {
name
profileImage {
asset {
fixed(
width: 400
imagePipelineArgs: {
q: 30
}
) {
...GatsbySanityImageFixed
}
}
}
}
}
`
```

##### Usage outside of GraphQL

Likewise, to pass Image Pipeline arguments with using `getFixedGatsbyImage` or `getFluidGatsbyImage`, you may include an additional argument, `imagePipelineArgs`, block when calling either utility function. For example, the following query will add Image Pipeline arguments, passing `q` to specify an image quality:

```js
const fluidProps = getFluidGatsbyImage(
imageAssetId,
{
maxWidth: 1024,
imagePipelineArgs: {
q: 30
}
},
sanityConfig
)
```

## Generating pages

Sanity does not have any concept of a "page", since it's built to be totally agnostic to how you want to present your content and in which medium, but since you're using Gatsby, you'll probably want some pages!
Expand Down
15 changes: 10 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
"version": "6.0.4",
"author": "Sanity.io <hello@sanity.io>",
"contributors": [
{
"name": "Henrique Doro",
"email": "opensource@hdoro.dev"
}
"Henrique Doro <opensource@hdoro.dev>"
],
"engines": {
"node": ">=8.0.0"
},
"repository": "https://github.com/sanity-io/gatsby-source-sanity",
"repository": {
"type": "git",
"url": "git+https://github.com/sanity-io/gatsby-source-sanity.git"
},
"homepage": "https://github.com/sanity-io/gatsby-source-sanity#readme",
"license": "MIT",
"bugs": {
Expand Down Expand Up @@ -57,6 +57,7 @@
"@types/lodash": "^4.14.162",
"@types/node": "^14.14.3",
"@types/pump": "^1.0.1",
"@types/react-dom": "^16.9.9",
"@types/split2": "^2.1.6",
"@types/through2": "^2.0.36",
"eslint": "^7.12.0",
Expand All @@ -70,5 +71,9 @@
},
"peerDependencies": {
"gatsby": "^2.2.0"
},
"directories": {
"lib": "lib",
"test": "test"
}
}
35 changes: 35 additions & 0 deletions src/images/extendImageNode.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import {
GraphQLBoolean,
GraphQLObjectType,
GraphQLString,
GraphQLFloat,
GraphQLInt,
GraphQLEnumType,
GraphQLNonNull,
GraphQLFieldConfig,
GraphQLInputObjectType,
} from 'gatsby/graphql'
import {PluginConfig} from '../gatsby-node'
import {getCacheKey, CACHE_KEYS} from '../util/cache'
Expand All @@ -29,6 +31,33 @@ const ImageFormatType = new GraphQLEnumType({
},
})

const ImagePipelineType = new GraphQLInputObjectType({
name: "SanityImagePipelineArgsFormat",
fields: {
bg: {
type: GraphQLString,
},
blur: {
type: GraphQLInt,
},
fm: {
type: GraphQLString,
},
invert: {
type: GraphQLBoolean,
},
q: {
type: GraphQLInt,
},
sat: {
type: GraphQLInt,
},
sharpen: {
type: GraphQLInt,
},
}
})

const extensions = new Map()

export function extendImageNode(
Expand Down Expand Up @@ -72,6 +101,9 @@ function getExtension(config: PluginConfig) {
type: ImageFormatType,
defaultValue: '',
},
imagePipelineArgs: {
type: ImagePipelineType
}
},
resolve: (image: ImageNode, args: FixedArgs) => getFixedGatsbyImage(image, args, location),
}
Expand Down Expand Up @@ -104,6 +136,9 @@ function getExtension(config: PluginConfig) {
type: ImageFormatType,
defaultValue: '',
},
imagePipelineArgs: {
type: ImagePipelineType
},
},
resolve: (image: ImageNode, args: FluidArgs) => getFluidGatsbyImage(image, args, location),
}
Expand Down
42 changes: 32 additions & 10 deletions src/images/getGatsbyImageProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,17 +66,29 @@ type ImageObject = {
asset: ImageRef | ImageAsset
}

export type SanityImagePipelineArgs = {
bg?: string,
blur?: number,
fm?: string,
invert?: boolean,
q?: number,
sat?: number,
sharpen?: number
}

export type FluidArgs = {
maxWidth?: number
maxHeight?: number
sizes?: string
toFormat?: ImageFormat
toFormat?: ImageFormat,
imagePipelineArgs?: SanityImagePipelineArgs
}

export type FixedArgs = {
width?: number
height?: number
toFormat?: ImageFormat
toFormat?: ImageFormat,
imagePipelineArgs?: SanityImagePipelineArgs
}

type SanityLocation = {
Expand Down Expand Up @@ -193,13 +205,18 @@ export function getFixedGatsbyImage(
forceConvert = 'jpg'
}

const sanityImagePipelineArgs = args.imagePipelineArgs || {}
const sanityImagePipelineParams = Object.keys(sanityImagePipelineArgs).map(
key => key + '=' + (sanityImagePipelineArgs as any)[key]
).join('&')

const hasOriginalRatio = desiredAspectRatio === dimensions.aspectRatio
const outputHeight = Math.round(height ? height : width / desiredAspectRatio)
const imgUrl =
isOriginalSize(width, outputHeight) ||
(hasOriginalRatio && width > dimensions.width && outputHeight > dimensions.height)
? url
: `${url}?w=${width}&h=${outputHeight}&fit=crop`
? `${url}${sanityImagePipelineParams ? ("?" + sanityImagePipelineParams) : ""}`
: `${url}?w=${width}&h=${outputHeight}&fit=crop${sanityImagePipelineParams ? ("&" + sanityImagePipelineParams) : ""}`

const widths = sizeMultipliersFixed.map((scale) => Math.round(width * scale))
const initial = {webp: [] as string[], base: [] as string[]}
Expand All @@ -209,8 +226,8 @@ export function getFixedGatsbyImage(
const resolution = `${sizeMultipliersFixed[i]}x`
const currentHeight = Math.round(currentWidth / desiredAspectRatio)
const imgUrl = isOriginalSize(currentWidth, currentHeight)
? url
: `${url}?w=${currentWidth}&h=${currentHeight}&fit=crop`
? `${url}${sanityImagePipelineParams ? ("?" + sanityImagePipelineParams) : ""}`
: `${url}?w=${currentWidth}&h=${currentHeight}&fit=crop${sanityImagePipelineParams ? ("&" + sanityImagePipelineParams) : ""}`

const webpUrl = convertToFormat(imgUrl, 'webp')
const baseUrl = convertToFormat(imgUrl, forceConvert || props.extension)
Expand Down Expand Up @@ -267,11 +284,16 @@ export function getFluidGatsbyImage(
forceConvert = 'jpg'
}

const sanityImagePipelineArgs = args.imagePipelineArgs || {};
const sanityImagePipelineParams = Object.keys(sanityImagePipelineArgs).map(
key => key + '=' + (sanityImagePipelineArgs as any)[key]
).join('&');

const baseSrc =
isOriginalSize(maxWidth, maxHeight) ||
(maxWidth >= dimensions.width && maxHeight >= dimensions.height)
? url
: `${url}?w=${maxWidth}&h=${maxHeight}&fit=crop`
? `${url}${sanityImagePipelineParams ? ("?" + sanityImagePipelineParams) : ""}`
: `${url}?w=${maxWidth}&h=${maxHeight}&fit=crop${sanityImagePipelineParams ? ("&" + sanityImagePipelineParams) : ""}`

const src = convertToFormat(baseSrc, forceConvert || extension)
const srcWebp = convertToFormat(baseSrc, 'webp')
Expand All @@ -288,8 +310,8 @@ export function getFluidGatsbyImage(
.reduce((acc, currentWidth) => {
const currentHeight = Math.round(currentWidth / desiredAspectRatio)
const imgUrl = isOriginalSize(currentWidth, currentHeight)
? url
: `${url}?w=${currentWidth}&h=${currentHeight}&fit=crop`
? `${url}${sanityImagePipelineParams ? ("?" + sanityImagePipelineParams) : ""}`
: `${url}?w=${currentWidth}&h=${currentHeight}&fit=crop${sanityImagePipelineParams ? ("&" + sanityImagePipelineParams) : ""}`

const webpUrl = convertToFormat(imgUrl, 'webp')
const baseUrl = convertToFormat(imgUrl, forceConvert || props.extension)
Expand Down