Skip to content

Instantly share code, notes, and snippets.

@Evavic44
Last active June 5, 2024 00:10
Show Gist options
  • Save Evavic44/f63e5cfa50ee52d2289d03b83eb398a5 to your computer and use it in GitHub Desktop.
Save Evavic44/f63e5cfa50ee52d2289d03b83eb398a5 to your computer and use it in GitHub Desktop.

Sanity YouTube Schema

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,
  },
});

Get Id from YouTube URL

export default function getYoutubeId(url: any) {
  const regex =
    /(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))/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>
  );
}

Sanity YouTube Iframe

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>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment