Skip to content

Instantly share code, notes, and snippets.

@SimeonGriggs
Created September 11, 2023 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SimeonGriggs/d0796ae39e07cc025d9cbb40c6d94e3e to your computer and use it in GitHub Desktop.
Save SimeonGriggs/d0796ae39e07cc025d9cbb40c6d94e3e to your computer and use it in GitHub Desktop.
An extended image asset schema with a custom input to watch the value and update the image's fields with values from the asset itself
import {useEffect, useState} from 'react'
import {ImageAsset, ObjectInputProps, Reference, set, unset, useClient} from 'sanity'
type ExtendedImageValue = {
asset: Reference
lqip?: string
blurHash?: string
}
export default function ImageExtendedInput(props: ObjectInputProps<ExtendedImageValue>) {
const {value, onChange, path} = props
const client = useClient({apiVersion: `2023-09-01`})
const [asset, setAsset] = useState<ImageAsset | null>(null)
useEffect(() => {
async function updateExtendedFields(id: string) {
const asset = await client.fetch<ImageAsset>(`*[_id == $id][0]`, {id})
setAsset(asset)
if (asset.metadata.lqip) {
onChange(set(asset.metadata.lqip, ['lqip']))
}
if (asset.metadata.blurHash) {
onChange(set(asset.metadata.blurHash, ['blurHash']))
}
}
// Set extended fields if asset is set
if (value?.asset?._ref && !asset) {
updateExtendedFields(value.asset._ref)
}
// Reset local state if image removed
if (!value?.asset?._ref && asset) {
setAsset(null)
}
// Unset extended fields if asset is unset
if ((value?.lqip || value?.blurHash) && !value?.asset?._ref) {
onChange([unset(['lqip']), unset(['blurHash'])])
}
}, [value, client, onChange, path, asset])
return props.renderDefault(props)
}
import {defineField, defineType} from 'sanity'
import ImageExtendedInput from './ImageExtendedInput'
export const imageExtendedType = defineType({
name: 'imageExtended',
type: 'image',
components: {
input: ImageExtendedInput,
},
fields: [
defineField({
name: 'lqip',
title: 'LQIP',
type: 'string',
readOnly: true
}),
defineField({
name: 'blurHash',
type: 'string',
readOnly: true
}),
],
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment