forked from CenterForOpenScience/markdown-it-video
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (67 loc) · 2.43 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Process @[youtube](youtubeVideoID)
// Process @[vimeo](vimeoVideoID)
'use strict';
var EMBED_REGEX = /@\[([a-zA-Z].+)\]\([\s]*(.*?)[\s]*[\)]/im;
function video_embed(md, options) {
function video_return(state, silent) {
var serviceEnd,
serviceStart,
token,
oldPos = state.pos;
if (state.src.charCodeAt(oldPos) !== 0x40/* @ */ || state.src.charCodeAt(oldPos + 1) !== 0x5B/* [ */) {
return false;
}
var match = EMBED_REGEX.exec(state.src);
if (!match || match.length < 3) {
return false;
}
var service = match[1].toLowerCase();
var videoID = match[2];
// If the videoID field is empty, regex currently make it the close parenthesis.
if (videoID === ')') {
videoID = '';
}
serviceStart = oldPos + 2;
serviceEnd = md.helpers.parseLinkLabel(state, oldPos + 1, false);
//
// We found the end of the link, and know for a fact it's a valid link;
// so all that's left to do is to call tokenizer.
if (!silent) {
state.pos = serviceStart;
state.posMax = serviceEnd;
state.service = state.src.slice(serviceStart, serviceEnd);
var newState = new state.md.inline.State(service, state.md, state.env, []);
newState.md.inline.tokenize(newState);
token = state.push('video', '');
token.videoID = videoID;
token.service = service;
token.level = state.level;
}
state.pos = state.pos + state.src.indexOf(')', state.pos);
state.posMax = state.tokens.length;
return true;
}
return video_return;
}
function video_url(service, videoID) {
switch (service) {
case 'youtube':
return '//www.youtube.com/embed/' + videoID;
case 'vimeo':
return '//player.vimeo.com/video/' + videoID;
}
}
function tokenize_video(md, options) {
function tokenize_return(tokens, idx) {
var videoID = md.utils.escapeHtml(tokens[idx].videoID);
var service = md.utils.escapeHtml(tokens[idx].service).toLowerCase();
return videoID === '' ? '' :
'<div class="video-wrapper"><iframe src="' + video_url(service, videoID, options) +
'" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>';
}
return tokenize_return;
}
module.exports = function video_plugin(md, options) {
md.renderer.rules.video = tokenize_video(md, options);
md.inline.ruler.before('emphasis', 'video', video_embed(md, options));
}