import { defineField , defineType } from "sanity" ;
import { YoutubeWidget } from "@/app/components/shared/YoutubeWidget" ;
import { BiLogoYoutube } from "react-icons/bi" ;
export const youtube = defineType ( {
name : "youtube" ,
title : "Youtube" ,
type : "object" ,
icon : BiLogoYoutube ,
fields : [
defineField ( {
name : "title" ,
title : "Title" ,
type : "string" ,
initialValue : "Youtube Video" ,
} ) ,
defineField ( {
name : "url" ,
title : "URL" ,
type : "url" ,
} ) ,
] ,
preview : {
select : {
title : "title" ,
url : "url" ,
} ,
} ,
components : {
preview : YoutubeWidget ,
} ,
} ) ;
export default function getYoutubeId ( url : any ) {
const regex =
/ ( y o u t u .* b e .* ) \/ ( w a t c h \? v = | e m b e d \/ | v | s h o r t s | ) ( .* ?( (? = [ & # ? ] ) | $ ) ) / gm;
const match = regex . exec ( url ) ;
if ( ! match ) {
return null ;
}
return match [ 3 ] ;
}
Sanity YouTube Upload Widget
import getYoutubeId from "@/app/utils/get-youtubeId" ;
import { BiLogoYoutube } from "react-icons/bi" ;
import YoutubeIframe from "./YoutubeIframe" ;
export function YoutubeWidget ( props : any ) {
const { url, actions, schemaType } = props ;
const id = getYoutubeId ( url ) ;
return (
< div className = "pt-1 relative" >
{ url ? (
< >
{ props . renderDefault ( props ) }
< YoutubeIframe videoId = { id } />
</ >
) : (
< div className = "flex items-center justify-center gap-x-2 my-3" >
< BiLogoYoutube className = "text-[red] text-lg" />
< span > Add YouTube URL</ span >
</ div >
) }
</ div >
) ;
}
export default function YoutubeIframe ( { videoId } : { videoId : string | null } ) {
if ( ! videoId ) {
return null ;
}
return (
< iframe
className = "aspect-video"
width = "100%"
height = "100%"
src = { `https://www.youtube.com/embed/${ videoId } ` }
title = "YouTube video player"
allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowFullScreen
> </ iframe >
) ;
}