import type { ImageUrlBuilder } from '@sanity/image-url/lib/types/builder' import type { FitMode, SanityImageDimensions } from '@sanity/image-url/lib/types/types' import type { ComputedRef, InjectionKey, Ref } from 'vue' import { computed, inject } from 'vue' export const imageBuilderSymbol: InjectionKey = Symbol('Sanity image URL builder') export interface ResolvedSanityImage { url: string dimensions?: SanityImageDimensions } interface ImageOptions { dpr?: number quality?: number fit?: FitMode } /** * * WARNING. Work in progress. API may change. */ export function useSanityImage( image: Ref, options?: Partial, widths: number[] = [300, 600, 1200, 1920], ): ComputedRef<{ src: string, srcset: string, placeholder: string }> { const builder = inject(imageBuilderSymbol) if (!builder) { throw new Error( 'You must call useSanityClient before using sanity resources in this project.', ) } function getImageUrl( image: Required, width: number, { quality = 82, fit = 'min' }: ImageOptions, ): string { return (builder as ImageUrlBuilder) .image(image.url) .width(Math.round(width)) .quality(quality) .fit(fit) .url() } const result = computed(() => ({ src: image.value.url, ...(image.value.dimensions ? { srcset: [ ...widths.map( width => `${getImageUrl( image.value as Required, width, options || {}, )} ${width}w`, ), `${image.value.url} ${image.value.dimensions.width}w`, ].join(', '), placeholder: '', } : { srcset: [ ...widths.map( width => `${getImageUrl( image.value as Required, width, options || {}, )} ${width}w`, ), ].join(', '), placeholder: '', }), })) return result }