Skip to content

Commit

Permalink
Make a unique imageLoader for each image
Browse files Browse the repository at this point in the history
Sanity’s asset-utils were not able to prase a URL with rect instrcutions back to hotspot and crop
  • Loading branch information
weotch committed Aug 21, 2023
1 parent fbf6a85 commit e34521a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 14 deletions.
4 changes: 2 additions & 2 deletions packages/sanity-next/src/SanityNextVisual.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { ReactElement } from 'react'
import NextVisual from '@react-visual/next'
import { makeImageUrl, makeFileUrl, imageLoader } from './lib/urlBuilding'
import { makeImageUrl, makeFileUrl, makeImageLoader } from './lib/urlBuilding'
import {
aspectRatioFromSource,
altTextFromSource,
Expand Down Expand Up @@ -42,7 +42,7 @@ export default function SanityNextVisual(

// Props that are calculated from Sanity data (mostly images)
image={ makeImageUrl(image) }
imageLoader={ imageLoader }
imageLoader={ makeImageLoader(image) }
video={ makeFileUrl(video) }
aspect={ aspect || aspectRatioFromSource(image) }
position={ position || objectPositionFromSource(image) }
Expand Down
23 changes: 11 additions & 12 deletions packages/sanity-next/src/lib/urlBuilding.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import createImageUrlBuilder from '@sanity/image-url'
import {
getFileAsset,
getImage,
type SanityFileSource
} from '@sanity/asset-utils'
import { getFileAsset, type SanityFileSource } from '@sanity/asset-utils'
import type { ImageUrlBuilder } from '@sanity/image-url/lib/types/builder'
import type { ImageLoaderProps } from 'next/image'
import type { ImageLoader, ImageLoaderProps } from 'next/image'
import type { SanityImageSource } from '@sanity/image-url/lib/types/types'
import { ObjectFit } from '@react-visual/next'

Expand Down Expand Up @@ -54,12 +50,15 @@ export function makeImageBuilder(source: SanityImageSource, {
}

// Make a next/image url loader
export function imageLoader(
{ src, width, quality }: ImageLoaderProps
): string {
const builder = makeImageBuilder(getImage(src)).width(width)
if (quality) builder.quality(quality)
return builder.url()
export function makeImageLoader(
source?: SanityImageSource
): ImageLoader | undefined {
if (!source) return undefined
return ({ width, quality }: ImageLoaderProps): string => {
let builder = makeImageBuilder(source, { width })
if (quality) builder = builder.quality(quality)
return builder.url()
}
}

// Return the URL of an asset
Expand Down

0 comments on commit e34521a

Please sign in to comment.