From f38512a88c2b547afe2eab7921e4a98debfe7d6e Mon Sep 17 00:00:00 2001 From: Ash Date: Tue, 1 Oct 2024 10:05:44 +0100 Subject: [PATCH] refactor: adopt `getImageDimensions` --- .../files/ImageInput/usePreviewImageSource.ts | 39 ++++++++----------- 1 file changed, 16 insertions(+), 23 deletions(-) diff --git a/packages/sanity/src/core/form/inputs/files/ImageInput/usePreviewImageSource.ts b/packages/sanity/src/core/form/inputs/files/ImageInput/usePreviewImageSource.ts index 60662266e44c..97d532802ca8 100644 --- a/packages/sanity/src/core/form/inputs/files/ImageInput/usePreviewImageSource.ts +++ b/packages/sanity/src/core/form/inputs/files/ImageInput/usePreviewImageSource.ts @@ -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, imageUrlBuilder, @@ -30,7 +13,7 @@ export function usePreviewImageSource(() => (url ? getImageSize(url) : [0, 0]), [url]) + const dimensions = useMemo( + () => + 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 {