Skip to content

Commit

Permalink
refactor: adopt getImageDimensions
Browse files Browse the repository at this point in the history
  • Loading branch information
juice49 committed Oct 1, 2024
1 parent 2eb20ff commit f38512a
Showing 1 changed file with 16 additions and 23 deletions.
Original file line number Diff line number Diff line change
@@ -1,27 +1,10 @@
import {isImageSource} from '@sanity/asset-utils'
import {getImageDimensions, isImageSource, type SanityImageDimensions} from '@sanity/asset-utils'
import {type CSSProperties, useMemo} from 'react'
import {useDevicePixelRatio} from 'use-device-pixel-ratio'

import {type ImageUrlBuilder} from '../types'
import {type BaseImageInputValue} from './types'

type Dimensions = [width: number, height: number]

/*
Used for setting the initial image height - specifically for images
that are small and so can take less space in the document
*/
const getImageSize = (src: string): Dimensions => {
const imageUrlParams = new URLSearchParams(src.split('?')[1])
const rect = imageUrlParams.get('rect')

if (rect) {
return [rect.split(',')[2], rect.split(',')[3]].map(Number) as Dimensions
}

return src.split('-')[1].split('.')[0].split('x').map(Number) as Dimensions
}

export function usePreviewImageSource<Value extends BaseImageInputValue | undefined>({
value,
imageUrlBuilder,
Expand All @@ -30,7 +13,7 @@ export function usePreviewImageSource<Value extends BaseImageInputValue | undefi
imageUrlBuilder: ImageUrlBuilder
}): {
url: Value extends undefined ? undefined : string
dimensions: Dimensions
dimensions: SanityImageDimensions
customProperties: CSSProperties
} {
const dpr = useDevicePixelRatio()
Expand All @@ -43,15 +26,25 @@ export function usePreviewImageSource<Value extends BaseImageInputValue | undefi
[dpr, imageUrlBuilder, value],
) as Value extends undefined ? undefined : string

const dimensions = useMemo<Dimensions>(() => (url ? getImageSize(url) : [0, 0]), [url])
const dimensions = useMemo<SanityImageDimensions>(
() =>
url
? getImageDimensions(url)
: {
width: 0,
height: 0,
aspectRatio: 0,
},
[url],
)

const customProperties = useMemo(
() =>
({
'--image-width': dimensions[0],
'--image-height': dimensions[1],
'--image-width': dimensions.width,
'--image-height': dimensions.height,
}) as CSSProperties,
[dimensions],
[dimensions.width, dimensions.height],
)

return {
Expand Down

0 comments on commit f38512a

Please sign in to comment.