Skip to content

Instantly share code, notes, and snippets.

@bzerangue
Last active November 17, 2021 15:06
Show Gist options
  • Save bzerangue/eb1ae389f4644d9fbf51a20f9c907c0f to your computer and use it in GitHub Desktop.
Save bzerangue/eb1ae389f4644d9fbf51a20f9c907c0f to your computer and use it in GitHub Desktop.
videoEmbed.js contentType - preview component for Sanity.io CMS richText PortableText editor - based off of Knut's YouTube Preview, https://www.youtube.com/watch?v=kLsER_zHiS4
import React from 'react'
const VideoEmbedPreview = ({ value }) => {
const url = value.url
const responsiveVideoContainer = {
padding: "56.25% 0 0 0",
position: "relative"
}
const responsiveVideoPlayer = {
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%"
}
if (url) {
// install https://www.npmjs.com/package/get-video-id, to get Vimeo or YouTube IDs
const getVideoId = require('get-video-id')
const id = getVideoId(url).id
const service = getVideoId(url).service
const vimeoEmbedUrl = 'https://player.vimeo.com/video/' + id
const youtubeEmbedUrl = 'https://www.youtube.com/embed/' + id
if (!id) {
return <div>Missing YouTube or Vimeo URL</div>
}
if (service === 'vimeo') {
return (
<div style={responsiveVideoContainer}>
<iframe src={vimeoEmbedUrl} style={responsiveVideoPlayer} frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
</div>
)
}
if (service === 'youtube') {
return (
<div style={responsiveVideoContainer}>
<iframe src={youtubeEmbedUrl} style={responsiveVideoPlayer} frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
)
}
}
return <div></div>
}
export default {
name: 'videoEmbed',
type: 'object',
title: 'Video Embed',
fields: [
{
name: 'url',
type: 'url',
title: 'URL'
}
],
preview: {
select: {
url: 'url'
},
component: VideoEmbedPreview
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment