Giter Site home page Giter Site logo

eloquence / markdown-it-html5-media Goto Github PK

View Code? Open in Web Editor NEW
23.0 4.0 4.0 832 KB

Minimalist <video>/<audio> plugin for markdown-it, using image syntax

License: Creative Commons Zero v1.0 Universal

JavaScript 100.00%
markdown-it markdown html5 video audio commonmark

markdown-it-html5-media's Introduction

markdown-it-html5-media

Minimalist <video>/<audio> plugin for markdown-it, using image syntax.

Inspired by markdown-it-html5-embed. Key differences:

  • Only supports image syntax: ![descriptive text](video.mp4), which is what the CommonMark folks seem to favor
  • Tokenizes video and audio to tokens of the 'video' and 'audio' type (useful for working with, e.g., rich text editors that process these tokens)
  • No library dependency for file type detection, just a simple extension check for commonly used video/audio formats.
  • Transpiled version: 10KB unminified vs. 169KB unminified

Basic usage

const md = require('markdown-it')();
// Destructuring assignment; we also export UI messages & media type detection
const { html5Media } = require('markdown-it-html5-media');
md.use(html5Media);
console.log(md.render('![text](video.mp4)'));

Output:

<p><video src="video.mp4" controls class="html5-video-player">
Your browser does not support playing HTML5 video.
You can <a href="video.mp4" download>download the file</a> instead.
Here is a description of the content: text
</video></p>

Custom attributes

You can pass any string that will be rendered instead of the default attributes shown above.

// Init as above
md.use(html5Media, {
  videoAttrs: 'class="my-video-css"',
  audioAttrs: 'class="my-audio-css" data-collapse'
});
console.log(md.render('![](video.mp4)'));
console.log(md.render('![](audio.mp3)'));

Output:

<p><video src="video.mp4" class="my-video-css">
Your browser does not support playing HTML5 video.
You can <a href="video.mp4" download>download the file</a> instead.
</video></p>
<p><audio src="audio.mp3" class="my-audio-css" data-collapse>
Your browser does not support playing HTML5 audio.
You can <a href="audio.mp3" download>download the file</a> instead.
</audio></p>

Media type detection

This module detects the media type by examining the file extension (case-insensitive). The valid audio and video extensions are defined here.

If you need to perform an identical media type detection outside the module, you can import the guessMediaType function (docs):

const { guessMediaType } = require('markdown-it-html5-media');

Custom messages

You can customize the fallback text. This text will only be shown to users whose browser does not support HTML5 video or audio at all. %s is used as a substitution marker for the filename or the description.

// Init as above
md.use(html5Media, {
  messages: {
    en: {
      'html5 video not supported':
        'Cannot play video.',
      'html5 audio not supported':
        'Cannot play audio.',
      'html5 media fallback link':
        'Download <a href="%s">file</a>.',
      'html5 media description':
        'Description: %s'      
    }
  }
});
console.log(md.render('![text](video.mp4)'));

Output:

<p><video src="video.mp4" controls class="html5-video-player">
Cannot play video.
Download <a href="video.mp4">file</a>.
Description: text
</video></p>

If you only want to change some of the text, you can import the messages object from the module and partially alter its contents:

const { html5Media, messages } = require('markdown-it-html5-media');
messages.en['html5 vide not supported'] = 'Cannot play video.';

Translation

Markdown-It supports passing along environment options, like so:

md.render('![some text](video.mp4)', {
  language: 'en'
});

This library will look up messages using the language key as in the example provided, or 'en' if none is provided. Only English messages are included with the library, and the built-in translation function falls back to English if a translation cannot be found.

You can provide additional translations using the approach in the previous example, or you can override the internal translation function, like so:

md.use(html5Media, { translateFn: someFunction });

Function documentation:

/**
 * @param {String} language
 *  a language code, typically an ISO 639-[1-3] code.
 * @param {String} messageKey
 *  an identifier for the message, typically a short descriptive text
 * @param {String[]} messageParams
 *  Strings to be substituted into the message using some pattern, e.g., %s or
 *  %1$s, %2$s. By default we only use a simple %s pattern.
 * @returns {String}
 *  the translation to use
 */
function translateFn(language, messageKey, messageParams) {
  // Your code here
}

Anything else?

The module is written in modern JavaScript. The version in dist/ is transpiled down to ES5 compatible with recent browsers. Use npm run build to update the build (does not change contents of dist; use npm run dist to build & dist).

You can find the automatically generated documentation here. Use npm run docs to regenerate it (changes contents of docs, which is tracked).

This library overrides Markdown-It's image tokenizer, which means that it duplicates portions of that particular Markdown-It code. If you can think of a better way to do what it does without scanning the whole token stream, please go ahead and file an issue or send a PR.

Strings should be escaped where they ought to be, but see the provided tests for yourself. Use at your own risk. :)

markdown-it-html5-media's People

Contributors

dependabot[bot] avatar eloquence avatar snyk-bot 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

Watchers

 avatar  avatar  avatar  avatar

markdown-it-html5-media's Issues

Captioning

Is it possible to add captioning to the HTML media elements?

HTML has the <track> element to accommodate this, which you can add as a child element to <video> and <audio>. So Iโ€™m wondering if it could be possible to write something like:

![Alt text](/path/to/video.webv en="/path/to/video.en.vtt")

which would compile to something like:

<video controls src="/path/to/video.webv">
  <track kind="captions" srclang="en" src="/path/to/video.en.vtt" />
  Alt Text
  Download the
  <a href="/path/to/video.webm">WEBM video</a>, and the
  <a href="/path/to/video.en.vtt">English subtitles</a>.
</video>

Captioning media elements is a pretty important accessibility features which allows users who have trouble following along the audio track for some reason and gives them an option to read subtitles as the video plays.

Note. I left a comment on the commonmark thread regarding this

Feature Request: Start and End Time

It would be practical and time efficient if videos could be started at some time defined as parameters given to the markdown.

ideas to implement it

![start:1m25s end:2m0s](./Video.mp4 "Video Title")
![](./Video.mp4#t=85,180 "Video Title")

plugin.apply is not a function

When trying to use this as a proper es6 module, IE import markdown_it_html5_media from "markdown-it-html5-media";, I get the following error:

/home/xxx/git/lemmy-ui/node_modules/markdown-it/lib/index.js:497
  plugin.apply(plugin, args);
         ^

TypeError: plugin.apply is not a function
    at MarkdownIt.use (/home/xxx/git/lemmy-ui/node_modules/markdown-it/lib/index.js:497:10)

Improvements to URL matching in guessMediaType()

function guessMediaType(url) {
  const extensionMatch = url.match(/\.([^/.]+)$/);
  if (extensionMatch === null)
    return 'image';
  const extension = extensionMatch[1];
  // ...
}

That means the plugin is currently looking for a dot . followed by anything but a dot or slash before the end of the URL. If I'm not mistaken, this should yield unwanted results in these example cases:

  • http://example.mov -- match is mov, which could be a recognized video file extension and is a valid TLD
  • video.mp4?t=1m30s -- match is mp4?t=1m30s, not mp4 as intended
  • audio.mp3#chapter4 -- match is mp3#chapter4, not mp3 as intended

I'm not sure if it's usable yet, but URL.pathname should strip out host, query and hash automatically. Otherwise you could also consider them manually.

  const extensionMatch = url.match(/\/.*\.([^/.]+)(?:\?[^?]*)?(?:#[^#]*)?$/);

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.