1
|
|
|
/** |
2
|
|
|
* SCEditor Auto Youtube Plugin |
3
|
|
|
* http://www.sceditor.com/ |
4
|
|
|
* |
5
|
|
|
* Copyright (C) 2016, Sam Clarke (samclarke.com) |
6
|
|
|
* |
7
|
|
|
* SCEditor is licensed under the MIT license: |
8
|
|
|
* http://www.opensource.org/licenses/mit-license.php |
9
|
|
|
* |
10
|
|
|
* @author Sam Clarke |
11
|
|
|
*/ |
12
|
|
|
(function (document, sceditor) { |
13
|
|
|
'use strict'; |
14
|
|
|
|
15
|
|
|
var dom = sceditor.dom; |
16
|
|
|
|
17
|
|
|
/* |
18
|
|
|
(^|\s) Start of line or space |
19
|
|
|
(?:https?:\/\/)? Optional scheme like http:// |
20
|
|
|
(?:www\.)? Optional www. prefix |
21
|
|
|
(?: |
22
|
|
|
youtu\.be\/ Ends with .be/ so whatever comes next is the ID |
23
|
|
|
| |
24
|
|
|
youtube\.com\/watch\?v= Matches the .com version |
25
|
|
|
) |
26
|
|
|
([^"&?\/ ]{11}) The actual YT ID |
27
|
|
|
(?:\&[\&_\?0-9a-z\#]+)? Any extra URL params |
28
|
|
|
(\s|$) End of line or space |
29
|
|
|
*/ |
30
|
|
|
var ytUrlRegex = /(^|\s)(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/watch\?v=)([^"&?\/ ]{11})(?:\&[\&_\?0-9a-z\#]+)?(\s|$)/i; |
31
|
|
|
|
32
|
|
|
function youtubeEmbedCode(id) { |
33
|
|
|
return '<div class="videocontainer"><div><iframe frameborder="0" ' + |
34
|
|
|
'src="https://www.youtube-nocookie.com/embed/' + id + '" ' + |
35
|
|
|
'data-youtube-id="' + id + '" allowfullscreen></iframe></div></div>'; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
function convertYoutubeLinks(root) { |
39
|
|
|
var node = root.firstChild; |
40
|
|
|
|
41
|
|
|
while (node) { |
42
|
|
|
// 3 is TextNodes |
43
|
|
|
if (node.nodeType === 3) { |
44
|
|
|
var text = node.nodeValue; |
45
|
|
|
var parent = node.parentNode; |
46
|
|
|
var match = text.match(ytUrlRegex); |
47
|
|
|
|
48
|
|
|
if (match) { |
49
|
|
|
parent.insertBefore(document.createTextNode( |
50
|
|
|
text.substr(0, match.index) + match[1] |
51
|
|
|
), node); |
52
|
|
|
|
53
|
|
|
parent.insertBefore( |
54
|
|
|
dom.parseHTML(youtubeEmbedCode(match[2])), node |
55
|
|
|
); |
56
|
|
|
|
57
|
|
|
node.nodeValue = match[3] + |
58
|
|
|
text.substr(match.index + match[0].length); |
59
|
|
|
} |
60
|
|
|
} else { |
61
|
|
|
// TODO: Make this tag configurable. |
62
|
|
|
if (!dom.is(node, 'code')) { |
63
|
|
|
convertYoutubeLinks(node); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
node = node.nextSibling; |
68
|
|
|
} |
69
|
|
|
}; |
70
|
|
|
|
71
|
|
|
sceditor.plugins.autoyoutube = function () { |
72
|
|
|
this.signalPasteRaw = function (data) { |
73
|
|
|
// TODO: Make this tag configurable. |
74
|
|
|
// Skip code tags |
75
|
|
|
if (dom.closest(this.currentNode(), 'code')) { |
76
|
|
|
return; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
if (data.text) { |
80
|
|
|
var html = document.createElement('div'); |
81
|
|
|
|
82
|
|
|
html.textContent = data.text; |
83
|
|
|
|
84
|
|
|
convertYoutubeLinks(html); |
85
|
|
|
|
86
|
|
|
data.html = html.innerHTML; |
87
|
|
|
} |
88
|
|
|
}; |
89
|
|
|
}; |
90
|
|
|
})(document, sceditor); |
91
|
|
|
|