GithubHelp home page GithubHelp logo

borgfriend / gatsby-remark-embed-video Goto Github PK

View Code? Open in Web Editor NEW
39.0 1.0 25.0 1.56 MB

An easy way to display videos in Markdown For Gatsby.JS

License: MIT License

TypeScript 96.35% JavaScript 3.65%

gatsby-remark-embed-video's Introduction

gatsby-remark-embed-video

Embed a Youtube Video in your Markdown

Usage

# Look at this Video:

`video: https://www.youtube.com/embed/2Xc9gXyf2G4`
`youtube: https://www.youtube.com/watch?v=2Xc9gXyf2G4`
`youtube: 2Xc9gXyf2G4`

`vimeo: https://vimeo.com/5299404`
`vimeo: 5299404`

`videoPress: https://videopress.com/v/kUJmAcSf`
`videoPress: kUJmAcSf`

`twitch: https://player.twitch.tv/?channel=dakotaz`
`twitch: https://player.twitch.tv/?autoplay=false&video=v273436948`
`twitch: 273436948`
`twitchLive: dakotaz`

Additional Features

Add Custom CSS Styling

You can style the videoIframe using .embedVideo-container or by specifying a custom class

  1. Restart gatsby.

A11y support

video: [VideoTitle](https://www.youtube.com/embed/2Xc9gXyf2G4) youtube: [Cool Youtube Video](https://www.youtube.com/watch?v=2Xc9gXyf2G4)

Install

npm i gatsby-remark-embed-video

yarn add gatsby-remark-embed-video

Configuration Markdown with MDX

Example Configuration

import type { GatsbyConfig } from "gatsby";

const config: GatsbyConfig = {
  siteMetadata: {
    title: `My Gatsby Site`,
    siteUrl: `https://www.yourdomain.tld`,
  },
  // More easily incorporate content into your pages through automatic TypeScript type generation and better GraphQL IntelliSense.
  // If you use VSCode you can also use the GraphQL plugin
  // Learn more at: https://gatsby.dev/graphql-typegen
  graphqlTypegen: true,
  plugins: [
    "gatsby-plugin-react-helmet",
    "gatsby-plugin-sitemap",
    {
      resolve: "gatsby-plugin-mdx",
      options: {
        gatsbyRemarkPlugins: [
          {
            resolve: "gatsby-remark-embed-video",
            options: {
              width: 800,
              ratio: 1.77, // Optional: Defaults to 16/9 = 1.77
              height: 400, // Optional: Overrides optional.ratio
              related: false, //Optional: Will remove related videos from the end of an embedded YouTube video.
              noIframeBorder: true, //Optional: Disable insertion of <style> border: 0
              loadingStrategy: "lazy", //Optional: Enable support for lazy-load offscreen iframes. Default is disabled.
              urlOverrides: [
                {
                  id: "youtube",
                  embedURL: (videoId: string) =>
                    `https://www.youtube-nocookie.com/embed/${videoId}`,
                },
              ], //Optional: Override URL of a service provider, e.g to enable youtube-nocookie support
              containerClass: "embedVideo-container", //Optional: Custom CSS class for iframe container, for multiple classes separate them by space
              iframeId: false, //Optional: if true, iframe's id will be set to what is provided after 'video:' (YouTube IFrame player API requires iframe id)
              sandbox: 'allow-same-origin allow-scripts allow-presentation', // Optional: iframe sandbox options - Default: undefined
            },
          },
           "gatsby-remark-responsive-iframe", //Optional: Must be loaded after gatsby-remark-embed-video
        ],
      },
    },
    {
      resolve: "gatsby-plugin-manifest",
      options: {
        icon: "src/images/icon.png",
      },
    },

    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "pages",
        path: "./src/pages/",
      },
      __key: "pages",
    },
  ],
};

export default config;

Configuration Markdown (without MDX)

  1. Add following to your gatsby-config.js:
module.exports = {
  plugins: [
    {
      resolve: "gatsby-transformer-remark",
      options: {
        plugins: [
          {
            resolve: "gatsby-remark-embed-video",
            options: {
              width: 800,
              ratio: 1.77, // Optional: Defaults to 16/9 = 1.77
              height: 400, // Optional: Overrides optional.ratio
              related: false, //Optional: Will remove related videos from the end of an embedded YouTube video.
              noIframeBorder: true, //Optional: Disable insertion of <style> border: 0
              loadingStrategy: 'lazy', //Optional: Enable support for lazy-load offscreen iframes. Default is disabled.
              urlOverrides: [
                {
                  id: "youtube",
                  embedURL: videoId =>
                    `https://www.youtube-nocookie.com/embed/${videoId}`,
                },
              ], //Optional: Override URL of a service provider, e.g to enable youtube-nocookie support
              containerClass: "embedVideo-container", //Optional: Custom CSS class for iframe container, for multiple classes separate them by space
              iframeId: false, //Optional: if true, iframe's id will be set to what is provided after 'video:' (YouTube IFrame player API requires iframe id)
            },
             "gatsby-remark-responsive-iframe", //Optional: Must be loaded after gatsby-remark-embed-video
          },
        ],
      },
    },
  ],
};

Make the iFrame Responsive

I would recommend the plugin gatsby-remark-responsive-iframe

Install it with npm i gatsby-remark-responsive-iframe

When using this plugin you must ensure that in the sequence of plugins gatsby-remark-embed-video runs before gatsby-remark-responsive-iframe.

Troubleshooting

if you also rely on gatsby-remark-responsive-iframe, gatsby-remark-images, or gatsby-remark-prismjs, you have to define the embed-youtube plugin first:

plugins: [
  "gatsby-remark-embed-video",
  "gatsby-remark-responsive-iframe",
  "gatsby-remark-prismjs",
  "gatsby-remark-images"
]

Special Thanks

Inspired by gatsby-remark-embed-youtube

License

MIT

gatsby-remark-embed-video's People

Contributors

borgfriend avatar byeokim avatar d4rekanguok avatar dependabot-preview[bot] avatar estshy avatar johno avatar mathieusteele avatar ntwcklng avatar stephanschubert avatar trend-kevin-c-chen avatar weakish avatar yannick-cw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

gatsby-remark-embed-video's Issues

Adding support for custom markers

Hi Neal, thanks for the awesome plugin!

I wanted to use the plugin using a different syntax other than code block ``, since it prevents netlifyCMS to correctly parse & display a preview, described in this stackoverflow question. It might also helps with #13 if I understand that one correctly.

I have been writing a custom tokenizer plugin for remark, aiming to make it easier to write custom static component for markdown in gatsby. I implemented the feature using my plugin here.

With this, it allows user to use self-defined syntax, such as

[[youtube: gdviJzEwShE]]

or

---youtube: gdviJzEwShE---

It still support the inline code syntax `youtube: gdviJzEwShE`, and will not invoke the custom parser unless user specifies a custom syntax.

edit: Here's a test gatsby site

Within Gatsby's eco system, using inline code will cause no issues, so I understand this is a niche usage. If you like what I've done, I would love to send over a PR & discuss further. If not, I'd like to ask for your permission to publish my fork as a separate package on npm.

Thanks again!

Uncaught DOMException: Failed to construct 'PresentationRequest': The document is sandboxed and lacks the 'allow-presentation' flag.

After update to the 3.1.1 version I got the following error when using the plugin with youtube videos:

Uncaught DOMException: Failed to construct 'PresentationRequest': The document is sandboxed and lacks the 'allow-presentation' flag.

To solve the issue the allow-presentation value needs to be added to the sandbox attribute in the iframe.

Could that attribute be added? Or maybe make a new option, where we would be able to set our own values for that attribute.

Support for lazy-load offscreen iframes

Hi, as browser-level lazy-loading for iframes is now supported in Chrome and Chromium-based browsers, by any chance we can add the support to configure of the new loading attribute for the iframe tags?

<iframe src="https://www.youtube.com/..." 
        loading="lazy" <--- new loading attribute
        ...></iframe>

I.e. adding a configurable attribute to:
https://github.com/borgfriend/gatsby-remark-embed-video/blob/master/src/EmbedVideo.ts#L71

This can be considered and applied as a progressive enhancement, since the loading attribute will be safely ignored in browsers which do not support it yet and browsers which support loading=lazy on iframes will lazy-load the iframe.

Considerations for this feature request and feedbacks are much appreciated, thank you!

Use with gatsby-remark-prismjs

Hi,

Thanks for this plugin I now have a nice embed, but now no code highlighting ๐Ÿ™ƒ

When I configured Prism more (I was just using the default config) I get this:

image

So it's being treated as inline code now...

Is there a way to use both without them clashing?

Add support for YouTube link with set start time

I am moving my legacy blog over and would like to be able to embed with a timestamp so the video starts at the specific time.

For instance linking to a section near the end of a 2 hour video:

youtube: https://www.youtube.com/watch?time_continue=6732&v=tC3P333iptk

Error Persisting State

So I'm getting this error while developing and building Gatsby.

warning Error persisting state: function plugin({ 
  beginMarker,
  endMarker,
  pattyName = 'patty',
  onlyRunWithMarker = false, 
  insertBef...<omitted>...
} could not be cloned.

This comes from the remark-burger dependency. Is there a way to remove this warning?

Support for Contentful?

I'm using Contentful to grab pages and posts for a website. One page has this markdown:

## Heading One

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris placerat finibus enim, ac consequat augue pharetra vel. Nam vulputate sapien in tempus egestas.

`video: https://videos.ctfassets.net/dbpftxjar4kc/4hFiurjbgcC60IaK8MsScM/88f040511911066c625d7875e315a593/wavepump.mp4`

### Heading Two

Curabitur eleifend vehicula quam nec hendrerit. Suspendisse bibendum in tellus sit amet tempus. Aliquam vitae imperdiet libero, id porttitor orci. Suspendisse potenti.

I installed and configured gatsby-remark-embed-video. It compiles fine but in the browser I just get a red p saying Error: Id could not be processed where the video should be. Anyway to fix this?

Permission denied when installing package

The package archive for this library (as published on NPM) cannot be unpacked, because its contents are as follows:

$ tar tvf gatsby-remark-embed-video-1.2.0.tgz
drw-rw-rw- 0/0               0 2018-04-20 10:09 package
-rw-rw-rw- 0/0             855 2018-04-20 09:52 package/CHANGELOG.MD
-rw-rw-rw- 0/0            3835 2018-04-20 10:10 package/index.js
-rw-rw-rw- 0/0            3201 2018-04-20 10:09 package/index.ts
-rw-rw-rw- 0/0             868 2018-04-20 10:10 package/package.json
-rw-rw-rw- 0/0            1486 2018-03-29 23:42 package/readme.md
-rw-rw-rw- 0/0            5197 2018-04-20 10:09 package/tsconfig.json

When running yarn add, this is the output:

10:25:05 PM: error An unexpected error occurred: "https://registry.yarnpkg.com/gatsby-remark-embed-video/-/gatsby-remark-embed-video-1.2.0.tgz: EACCES: permission denied, open '/opt/build/.yarn_cache/npm-gatsby-remark-embed-video-1.2.0-c38dd6a6055c9c1a2e02937cf95d2eed3a5201cf/CHANGELOG.MD'".
10:25:05 PM: info If you think this is a bug, please open a bug report with the information provided in "/opt/build/repo/yarn-error.log".
10:25:05 PM: info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

The reason is that there is an entry for the package directory with rw permissions only. The directory needs to have rwx permissions (execute bit means that a directory is browsable in UNIX) or not even be in the tar archive to begin with. Compare with the lodash package:

$ tar tvf lodash-4.17.10.tgz                                   
-rw-r--r-- 0/0             662 1985-10-26 09:15 package/package.json
-rw-r--r-- 0/0             714 1985-10-26 09:15 package/_apply.js
-rw-r--r-- 0/0             684 1985-10-26 09:15 package/_arrayAggregator.js
-rw-r--r-- 0/0             537 1985-10-26 09:15 package/_arrayEach.js
-rw-r--r-- 0/0             528 1985-10-26 09:15 package/_arrayEachRight.j

Note that there is no entry for package!

GDPR consent before loading video

Hey there,

thanks for the plugin, it works like a charm!
Is there any guidance on how not to show the video until a cookie consent is given?

Can't get video to appear in Gatsby v3 MDX blog post

Hello, I am having trouble getting a YouTube video to appear. I see only the call code, not the video itself!

Screen Shot 2021-08-27 at 1 07 17 PM

Here is how I have it in gastby-config:

module.exports = {
  siteMetadata: {
    siteUrl: "https://piya.party",
    title: "Portfolio",
    author: "Piya Willwerth"
  },
  plugins: [
    {
      resolve: "gatsby-transformer-remark",
      options: {
        plugins: [
          {
            resolve: "gatsby-remark-embed-video",
            options: {
              width: 800,
              ratio: 1.77, // Optional: Defaults to 16/9 = 1.77
              height: 400, // Optional: Overrides optional.ratio
              related: false, //Optional: Will remove related videos from the end of an embedded YouTube video.
              noIframeBorder: true, //Optional: Disable insertion of <style> border: 0
              loadingStrategy: 'lazy', //Optional: Enable support for lazy-load offscreen iframes. Default is disabled.
              urlOverrides: [
                {
                  id: "youtube",
                  embedURL: videoId =>
                    `https://www.youtube-nocookie.com/embed/${videoId}`,
                },
              ], //Optional: Override URL of a service provider, e.g to enable youtube-nocookie support
              containerClass: "embedVideo-container", //Optional: Custom CSS class for iframe container, for multiple classes separate them by space
              iframeId: false, //Optional: if true, iframe's id will be set to what is provided after 'video:' (YouTube IFrame player API requires iframe id)
            },
          },
          "gatsby-remark-images",
          "gatsby-remark-responsive-iframe",
        ],
      },
    },
    "gatsby-plugin-image",
    "gatsby-remark-relative-images",
    "gatsby-plugin-react-helmet",
    "gatsby-plugin-sass",
    "gatsby-plugin-sitemap",
    "gatsby-transformer-sharp",
    "gatsby-plugin-sharp",
    {
      resolve: `gatsby-plugin-google-fonts-v2`,
      options: {
        fonts: [
          {
            family: 'BioRhyme',
            weights: ['300', '700']
          },
          {
            family: 'Montserrat',
            weights: ['400', '700']
          },
        ]
      }
    },
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: "Piya Willwerth",
        short_name: "piyawill",
        start_url: "/",
        background_color: "#E5E7EB",
        theme_color: "#4B5563",
        display: "standalone",
        icon: `src/images/favicon.png`,
      }
    },
    {
      resolve: `gatsby-plugin-mdx`,
      options: {
        gatsbyRemarkPlugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 750,
              linkImagesToOriginal: false
            },
          },
        ],
      },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: {
        name: "src",
        path: `${__dirname}/src/`,
      },
    },
    {
      resolve: "gatsby-plugin-react-svg",
      options: {
        rule: {
          include: /assets/,
        },
      },
    },
  ],
};

And here is how I'm calling it:

`youtube: https://www.youtube.com/watch?v=4TUeuYcdniU`

Can you let me know what I'm doing wrong?

Sandbox Options Don't Get Set Correctly

Implementing the example code in gatsby-config.js:
sandbox: 'allow-same-origin allow-scripts allow-presentation', // Optional: iframe sandbox options - Default: undefined
yields the following result in the iframe:
<iframe title="" width="1000" height="565" src="https://www.youtube-nocookie.com/embed/svhxNRC_rnc?rel=0" class="embedVideo-iframe" style="border:0" sandbox="allow-same-origin" allow-scripts allow-presentation loading="lazy" allowfullscreen=""></iframe>
Only the first option is contained in quotes. The other two dangle and aren't recognized, causing errors.

HTML 5 Video Tag Element

Add support for HTML 5 native video embeds.

  • should provide standard HTML 5 video element
  • follow best practices from web.dev
  • should provide html template override

Using with gatsby-mdx

Hi,
Thanks for this plugin.
I'm trying to use your plugin with gatsby-mdx.
I have 2 warnings and I'd like to ask if it's something with my config or plugin bug.

gatsby config:

resolve: `gatsby-mdx`,
      options: {
        gatsbyRemarkPlugins: [
          {
            resolve: "gatsby-remark-images",
            options: {
              maxWidth: 1035,
              sizeByPixelDensity: true,
              withWebp: true,
              linkImagesToOriginal: false
            }
          },
          {
            resolve: `gatsby-remark-embed-video`,
            options: {
              width: 800,
              height: 400, // Optional: Overrides optional.ratio
              related: false, //Optional: Will remove related videos from the end of an embedded YouTube video.
              noIframeBorder: true //Optional: Disable insertion of <style> border: 0
            }
          }
        ]
      }
    },

MDX:

---
title: 'text'
---
text

`youtube: someID`

text2

Warning 1:

index.js:2177 Warning: validateDOMNesting(...): <div> cannot appear as a descendant of <p>.

Warning 2:

Warning: The tag <undefined> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.

In the html output I see:

<p> <undefined>
        <div class="embedVideo-container">
            <iframe width="800" height="400" src="https://www.youtube.com/embed/id?rel=0" class="embedVideo-iframe" allowfullscreen="" style="border-width: 0px;"></iframe>
        </div></undefined></p>

Feature Request: Provide iframe title (A11y Improvement)

First off, thanks for the plugin! It was a life saver when we first switched to Gatsby and I didn't know a JSX component from a hole in the ground.

Best practice for accessibility is to have a unique title for iframes, and my Gatsby-build documentation needs to be accessible. I'm thinking that the syntax to add this could be something like:

`video: https://path.to/video "This is the video title"`

I'd be happy to help implement this, for what little that's worth (I'm a technical writer not a dev).

Thanks in advance for the attention to this! I'd much prefer this over making another custom component to do the same things plus a title.

Warn about missing `width` option

I accidentally deleted the options from my configuration:

{
  resolve: `gatsby-remark-embed-video`,
  options: {
  }
}

And instead of warning me about it the transformed <iframe> tags had a width attribute of undefined and height of NaN.

Autoplay Youtube videos

Hello,

How can I sent autoplay and mute parameters on url to autoplay it?

Below example doesn't work.
youtube: https://www.youtube.com/watch?v=8hv-lS1ge_A&autoplay=1&mute=1

Thank you,
Ibrahim

Build warning: Error persisting state.

Hi,

I get the following error when building.

warning Error persisting state: function plugin({ 
  beginMarker,
  endMarker,
  pattyName = 'patty',
  onlyRunWithMarker = false, 
  insertBef...<omitted>...
} could not be cloned.

I have tracked down the code from the error message to remark-burger which is only imported by gatsby-remark-embed-video in my project.

Add YouTube no-coookie support

It would be nice if gatsby-remark-embed-video respected the nocookie variants of YouTube embeds, i.e.

video: https://youtube-nocookie.com/embed/someVideoId

rather than the regular

video: https://youtube.com/embed/someVideoId

get-video-id always returns a result, breaking explicit embed type

If you have markdown like `youtube: AAAAAAAA` then readVideoId calls the videoIdProcessors starting with get-video-id. It tests for success with Object.keys(videoId).length !== 0, but get-video-id always returns a KV: https://github.com/radiovisual/get-video-id/blob/master/src/index.js#L35 . On failure, it returns a KV where id and service are null. So readVideoId declares success, returns to embedVideoHTML, and that calls getVideoService(null, ...)

This results in Error: VideoService could not be found

As it stands right now, it is only possible to embed videos whose service is dynamically determined by get-video-id. The built-in twitch and nicovideo processors will never be called, and explicit user-supplied services will not be used.

Youtube embedding not working.

I followed the exact things as mentioned in the readme.md not sure where it is going wrong. Let me share my configs and see any of you can help me figure this out

Version

image

gatsby-config.js

    {
      resolve: "gatsby-remark-embed-video",
      options: {
        width: 800,
        ratio: 1.77, // Optional: Defaults to 16/9 = 1.77
        height: 400, // Optional: Overrides optional.ratio
        related: false, //Optional: Will remove related videos from the end of an embedded YouTube video.
        noIframeBorder: true, //Optional: Disable insertion of <style> border: 0
      }
    },
    {
      resolve: "@weknow/gatsby-remark-twitter",
      options: {
        debug: true,
        align: 'center'
      }
    },
    "gatsby-remark-responsive-iframe",
    "gatsby-remark-images",

Blog file

---
slug: "test-blog"
published_date: 2019-11-13
created_date: 2019-11-13
title: "Testing"
template: "post"
draft: false
description: 
subtitle: 
tags: []
featuredImgPath: 
---
Testing the embedd 

`youtube: https://www.youtube.com/watch?v=nG5TXyyaeDs`

Output

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.