plugin.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. /**
  2. * plugin.js
  3. *
  4. * Copyright, Moxiecode Systems AB
  5. * Released under LGPL License.
  6. *
  7. * License: http://www.tinymce.com/license
  8. * Contributing: http://www.tinymce.com/contributing
  9. */
  10. /*jshint maxlen:255 */
  11. /*eslint max-len:0 */
  12. /*global tinymce:true */
  13. tinymce.PluginManager.add('media', function(editor, url) {
  14. var urlPatterns = [
  15. {regex: /youtu\.be\/([\w\-.]+)/, type: 'iframe', w: 425, h: 350, url: '//www.youtube.com/embed/$1'},
  16. {regex: /youtube\.com(.+)v=([^&]+)/, type: 'iframe', w: 425, h: 350, url: '//www.youtube.com/embed/$2'},
  17. {regex: /vimeo\.com\/([0-9]+)/, type: 'iframe', w: 425, h: 350, url: '//player.vimeo.com/video/$1?title=0&byline=0&portrait=0&color=8dc7dc'},
  18. {regex: /maps\.google\.([a-z]{2,3})\/maps\/(.+)msid=(.+)/, type: 'iframe', w: 425, h: 350, url: '//maps.google.com/maps/ms?msid=$2&output=embed"'}
  19. ];
  20. function guessMime(url) {
  21. if (url.indexOf('.mp3') != -1) {
  22. return 'audio/mpeg';
  23. }
  24. if (url.indexOf('.wav') != -1) {
  25. return 'audio/wav';
  26. }
  27. if (url.indexOf('.mp4') != -1) {
  28. return 'video/mp4';
  29. }
  30. if (url.indexOf('.webm') != -1) {
  31. return 'video/webm';
  32. }
  33. if (url.indexOf('.ogg') != -1) {
  34. return 'video/ogg';
  35. }
  36. if (url.indexOf('.swf') != -1) {
  37. return 'application/x-shockwave-flash';
  38. }
  39. return '';
  40. }
  41. function getVideoScriptMatch(src) {
  42. var prefixes = editor.settings.media_scripts;
  43. if (prefixes) {
  44. for (var i = 0; i < prefixes.length; i++) {
  45. if (src.indexOf(prefixes[i].filter) !== -1) {
  46. return prefixes[i];
  47. }
  48. }
  49. }
  50. }
  51. function showDialog() {
  52. var win, width, height, data;
  53. var generalFormItems = [
  54. {name: 'source1', type: 'filepicker', filetype: 'media', size: 40, autofocus: true, label: 'Source'}
  55. ];
  56. function recalcSize(e) {
  57. var widthCtrl, heightCtrl, newWidth, newHeight;
  58. widthCtrl = win.find('#width')[0];
  59. heightCtrl = win.find('#height')[0];
  60. newWidth = widthCtrl.value();
  61. newHeight = heightCtrl.value();
  62. if (win.find('#constrain')[0].checked() && width && height && newWidth && newHeight) {
  63. if (e.control == widthCtrl) {
  64. newHeight = Math.round((newWidth / width) * newHeight);
  65. heightCtrl.value(newHeight);
  66. } else {
  67. newWidth = Math.round((newHeight / height) * newWidth);
  68. widthCtrl.value(newWidth);
  69. }
  70. }
  71. width = newWidth;
  72. height = newHeight;
  73. }
  74. if (editor.settings.media_alt_source !== false) {
  75. generalFormItems.push({name: 'source2', type: 'filepicker', filetype: 'media', size: 40, label: 'Alternative source'});
  76. }
  77. if (editor.settings.media_poster !== false) {
  78. generalFormItems.push({name: 'poster', type: 'filepicker', filetype: 'image', size: 40, label: 'Poster'});
  79. }
  80. if (editor.settings.media_dimensions !== false) {
  81. generalFormItems.push({
  82. type: 'container',
  83. label: 'Dimensions',
  84. layout: 'flex',
  85. align: 'center',
  86. spacing: 5,
  87. items: [
  88. {name: 'width', type: 'textbox', maxLength: 3, size: 3, onchange: recalcSize},
  89. {type: 'label', text: 'x'},
  90. {name: 'height', type: 'textbox', maxLength: 3, size: 3, onchange: recalcSize},
  91. {name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions'}
  92. ]
  93. });
  94. }
  95. data = getData(editor.selection.getNode());
  96. width = data.width;
  97. height = data.height;
  98. win = editor.windowManager.open({
  99. title: 'Insert/edit video',
  100. data: data,
  101. bodyType: 'tabpanel',
  102. body: [
  103. {
  104. title: 'General',
  105. type: "form",
  106. onShowTab: function() {
  107. data = htmlToData(this.next().find('#embed').value());
  108. this.fromJSON(data);
  109. },
  110. items: generalFormItems
  111. },
  112. {
  113. title: 'Embed',
  114. type: "panel",
  115. layout: 'flex',
  116. direction: 'column',
  117. align: 'stretch',
  118. padding: 10,
  119. spacing: 10,
  120. onShowTab: function() {
  121. this.find('#embed').value(dataToHtml(this.parent().toJSON()));
  122. },
  123. items: [
  124. {
  125. type: 'label',
  126. text: 'Paste your embed code below:',
  127. forId: 'mcemediasource'
  128. },
  129. {
  130. id: 'mcemediasource',
  131. type: 'textbox',
  132. flex: 1,
  133. name: 'embed',
  134. value: getSource(),
  135. multiline: true,
  136. label: 'Source'
  137. }
  138. ]
  139. }
  140. ],
  141. onSubmit: function() {
  142. editor.insertContent(dataToHtml(this.toJSON()));
  143. }
  144. });
  145. }
  146. function getSource() {
  147. var elm = editor.selection.getNode();
  148. if (elm.getAttribute('data-mce-object')) {
  149. return editor.selection.getContent();
  150. }
  151. }
  152. function dataToHtml(data) {
  153. var html = '';
  154. if (!data.source1) {
  155. tinymce.extend(data, htmlToData(data.embed));
  156. if (!data.source1) {
  157. return '';
  158. }
  159. }
  160. if (!data.source2) {
  161. data.source2 = '';
  162. }
  163. if (!data.poster) {
  164. data.poster = '';
  165. }
  166. data.source1 = editor.convertURL(data.source1, "source");
  167. data.source2 = editor.convertURL(data.source2, "source");
  168. data.source1mime = guessMime(data.source1);
  169. data.source2mime = guessMime(data.source2);
  170. data.poster = editor.convertURL(data.poster, "poster");
  171. data.flashPlayerUrl = editor.convertURL(url + '/moxieplayer.swf', "movie");
  172. if (data.embed) {
  173. html = updateHtml(data.embed, data, true);
  174. } else {
  175. tinymce.each(urlPatterns, function(pattern) {
  176. var match, i, url;
  177. if ((match = pattern.regex.exec(data.source1))) {
  178. url = pattern.url;
  179. for (i = 0; match[i]; i++) {
  180. /*jshint loopfunc:true*/
  181. /*eslint no-loop-func:0 */
  182. url = url.replace('$' + i, function() {
  183. return match[i];
  184. });
  185. }
  186. data.source1 = url;
  187. data.type = pattern.type;
  188. data.width = data.width || pattern.w;
  189. data.height = data.height || pattern.h;
  190. }
  191. });
  192. var videoScript = getVideoScriptMatch(data.source1);
  193. if (videoScript) {
  194. data.type = 'script';
  195. data.width = videoScript.width;
  196. data.height = videoScript.height;
  197. }
  198. data.width = data.width || 300;
  199. data.height = data.height || 150;
  200. tinymce.each(data, function(value, key) {
  201. data[key] = editor.dom.encode(value);
  202. });
  203. if (data.type == "iframe") {
  204. html += '<iframe src="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '"></iframe>';
  205. } else if (data.source1mime == "application/x-shockwave-flash") {
  206. html += '<object data="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '" type="application/x-shockwave-flash">';
  207. if (data.poster) {
  208. html += '<img src="' + data.poster + '" width="' + data.width + '" height="' + data.height + '" />';
  209. }
  210. html += '</object>';
  211. } else if (data.source1mime.indexOf('audio') != -1) {
  212. if (editor.settings.audio_template_callback) {
  213. html = editor.settings.audio_template_callback(data);
  214. } else {
  215. html += (
  216. '<audio controls="controls" src="' + data.source1 + '">' +
  217. (data.source2 ? '\n<source src="' + data.source2 + '"' + (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') +
  218. '</audio>'
  219. );
  220. }
  221. } else if (data.type == "script") {
  222. html += '<script src="' + data.source1 + '"></script>';
  223. } else {
  224. if (editor.settings.video_template_callback) {
  225. html = editor.settings.video_template_callback(data);
  226. } else {
  227. html = (
  228. '<video width="' + data.width + '" height="' + data.height + '"' + (data.poster ? ' poster="' + data.poster + '"' : '') + ' controls="controls">\n' +
  229. '<source src="' + data.source1 + '"' + (data.source1mime ? ' type="' + data.source1mime + '"' : '') + ' />\n' +
  230. (data.source2 ? '<source src="' + data.source2 + '"' + (data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') +
  231. '</video>'
  232. );
  233. }
  234. }
  235. }
  236. return html;
  237. }
  238. function htmlToData(html) {
  239. var data = {};
  240. new tinymce.html.SaxParser({
  241. validate: false,
  242. allow_conditional_comments: true,
  243. special: 'script,noscript',
  244. start: function(name, attrs) {
  245. if (!data.source1 && name == "param") {
  246. data.source1 = attrs.map.movie;
  247. }
  248. if (name == "iframe" || name == "object" || name == "embed" || name == "video" || name == "audio") {
  249. if (!data.type) {
  250. data.type = name;
  251. }
  252. data = tinymce.extend(attrs.map, data);
  253. }
  254. if (name == "script") {
  255. var videoScript = getVideoScriptMatch(attrs.map.src);
  256. if (!videoScript) {
  257. return;
  258. }
  259. data = {
  260. type: "script",
  261. source1: attrs.map.src,
  262. width: videoScript.width,
  263. height: videoScript.height
  264. };
  265. }
  266. if (name == "source") {
  267. if (!data.source1) {
  268. data.source1 = attrs.map.src;
  269. } else if (!data.source2) {
  270. data.source2 = attrs.map.src;
  271. }
  272. }
  273. if (name == "img" && !data.poster) {
  274. data.poster = attrs.map.src;
  275. }
  276. }
  277. }).parse(html);
  278. data.source1 = data.source1 || data.src || data.data;
  279. data.source2 = data.source2 || '';
  280. data.poster = data.poster || '';
  281. return data;
  282. }
  283. function getData(element) {
  284. if (element.getAttribute('data-mce-object')) {
  285. return htmlToData(editor.serializer.serialize(element, {selection: true}));
  286. }
  287. return {};
  288. }
  289. function updateHtml(html, data, updateAll) {
  290. var writer = new tinymce.html.Writer();
  291. var sourceCount = 0, hasImage;
  292. function setAttributes(attrs, updatedAttrs) {
  293. var name, i, value, attr;
  294. for (name in updatedAttrs) {
  295. value = "" + updatedAttrs[name];
  296. if (attrs.map[name]) {
  297. i = attrs.length;
  298. while (i--) {
  299. attr = attrs[i];
  300. if (attr.name == name) {
  301. if (value) {
  302. attrs.map[name] = value;
  303. attr.value = value;
  304. } else {
  305. delete attrs.map[name];
  306. attrs.splice(i, 1);
  307. }
  308. }
  309. }
  310. } else if (value) {
  311. attrs.push({
  312. name: name,
  313. value: value
  314. });
  315. attrs.map[name] = value;
  316. }
  317. }
  318. }
  319. new tinymce.html.SaxParser({
  320. validate: false,
  321. allow_conditional_comments: true,
  322. special: 'script,noscript',
  323. comment: function(text) {
  324. writer.comment(text);
  325. },
  326. cdata: function(text) {
  327. writer.cdata(text);
  328. },
  329. text: function(text, raw) {
  330. writer.text(text, raw);
  331. },
  332. start: function(name, attrs, empty) {
  333. switch (name) {
  334. case "video":
  335. case "object":
  336. case "embed":
  337. case "img":
  338. case "iframe":
  339. setAttributes(attrs, {
  340. width: data.width,
  341. height: data.height
  342. });
  343. break;
  344. }
  345. if (updateAll) {
  346. switch (name) {
  347. case "video":
  348. setAttributes(attrs, {
  349. poster: data.poster,
  350. src: ""
  351. });
  352. if (data.source2) {
  353. setAttributes(attrs, {
  354. src: ""
  355. });
  356. }
  357. break;
  358. case "iframe":
  359. setAttributes(attrs, {
  360. src: data.source1
  361. });
  362. break;
  363. case "source":
  364. sourceCount++;
  365. if (sourceCount <= 2) {
  366. setAttributes(attrs, {
  367. src: data["source" + sourceCount],
  368. type: data["source" + sourceCount + "mime"]
  369. });
  370. if (!data["source" + sourceCount]) {
  371. return;
  372. }
  373. }
  374. break;
  375. case "img":
  376. if (!data.poster) {
  377. return;
  378. }
  379. hasImage = true;
  380. break;
  381. }
  382. }
  383. writer.start(name, attrs, empty);
  384. },
  385. end: function(name) {
  386. if (name == "video" && updateAll) {
  387. for (var index = 1; index <= 2; index++) {
  388. if (data["source" + index]) {
  389. var attrs = [];
  390. attrs.map = {};
  391. if (sourceCount < index) {
  392. setAttributes(attrs, {
  393. src: data["source" + index],
  394. type: data["source" + index + "mime"]
  395. });
  396. writer.start("source", attrs, true);
  397. }
  398. }
  399. }
  400. }
  401. if (data.poster && name == "object" && updateAll && !hasImage) {
  402. var imgAttrs = [];
  403. imgAttrs.map = {};
  404. setAttributes(imgAttrs, {
  405. src: data.poster,
  406. width: data.width,
  407. height: data.height
  408. });
  409. writer.start("img", imgAttrs, true);
  410. }
  411. writer.end(name);
  412. }
  413. }, new tinymce.html.Schema({})).parse(html);
  414. return writer.getContent();
  415. }
  416. editor.on('ResolveName', function(e) {
  417. var name;
  418. if (e.target.nodeType == 1 && (name = e.target.getAttribute("data-mce-object"))) {
  419. e.name = name;
  420. }
  421. });
  422. editor.on('preInit', function() {
  423. // Make sure that any messy HTML is retained inside these
  424. var specialElements = editor.schema.getSpecialElements();
  425. tinymce.each('video audio iframe object'.split(' '), function(name) {
  426. specialElements[name] = new RegExp('<\/' + name + '[^>]*>','gi');
  427. });
  428. // Allow elements
  429. //editor.schema.addValidElements('object[id|style|width|height|classid|codebase|*],embed[id|style|width|height|type|src|*],video[*],audio[*]');
  430. // Set allowFullscreen attribs as boolean
  431. var boolAttrs = editor.schema.getBoolAttrs();
  432. tinymce.each('webkitallowfullscreen mozallowfullscreen allowfullscreen'.split(' '), function(name) {
  433. boolAttrs[name] = {};
  434. });
  435. // Converts iframe, video etc into placeholder images
  436. editor.parser.addNodeFilter('iframe,video,audio,object,embed,script', function(nodes, name) {
  437. var i = nodes.length, ai, node, placeHolder, attrName, attrValue, attribs, innerHtml;
  438. var videoScript;
  439. while (i--) {
  440. node = nodes[i];
  441. if (node.name == 'script') {
  442. videoScript = getVideoScriptMatch(node.attr('src'));
  443. if (!videoScript) {
  444. continue;
  445. }
  446. }
  447. placeHolder = new tinymce.html.Node('img', 1);
  448. placeHolder.shortEnded = true;
  449. if (videoScript) {
  450. if (videoScript.width) {
  451. node.attr('width', videoScript.width.toString());
  452. }
  453. if (videoScript.height) {
  454. node.attr('height', videoScript.height.toString());
  455. }
  456. }
  457. // Prefix all attributes except width, height and style since we
  458. // will add these to the placeholder
  459. attribs = node.attributes;
  460. ai = attribs.length;
  461. while (ai--) {
  462. attrName = attribs[ai].name;
  463. attrValue = attribs[ai].value;
  464. if (attrName !== "width" && attrName !== "height" && attrName !== "style") {
  465. if (attrName == "data" || attrName == "src") {
  466. attrValue = editor.convertURL(attrValue, attrName);
  467. }
  468. placeHolder.attr('data-mce-p-' + attrName, attrValue);
  469. }
  470. }
  471. // Place the inner HTML contents inside an escaped attribute
  472. // This enables us to copy/paste the fake object
  473. innerHtml = node.firstChild && node.firstChild.value;
  474. if (innerHtml) {
  475. placeHolder.attr("data-mce-html", escape(innerHtml));
  476. placeHolder.firstChild = null;
  477. }
  478. placeHolder.attr({
  479. width: node.attr('width') || "300",
  480. height: node.attr('height') || (name == "audio" ? "30" : "150"),
  481. style: node.attr('style'),
  482. src: tinymce.Env.transparentSrc,
  483. "data-mce-object": name,
  484. "class": "mce-object mce-object-" + name
  485. });
  486. node.replace(placeHolder);
  487. }
  488. });
  489. // Replaces placeholder images with real elements for video, object, iframe etc
  490. editor.serializer.addAttributeFilter('data-mce-object', function(nodes, name) {
  491. var i = nodes.length, node, realElm, ai, attribs, innerHtml, innerNode, realElmName;
  492. while (i--) {
  493. node = nodes[i];
  494. realElmName = node.attr(name);
  495. realElm = new tinymce.html.Node(realElmName, 1);
  496. // Add width/height to everything but audio
  497. if (realElmName != "audio" && realElmName != "script") {
  498. realElm.attr({
  499. width: node.attr('width'),
  500. height: node.attr('height')
  501. });
  502. }
  503. realElm.attr({
  504. style: node.attr('style')
  505. });
  506. // Unprefix all placeholder attributes
  507. attribs = node.attributes;
  508. ai = attribs.length;
  509. while (ai--) {
  510. var attrName = attribs[ai].name;
  511. if (attrName.indexOf('data-mce-p-') === 0) {
  512. realElm.attr(attrName.substr(11), attribs[ai].value);
  513. }
  514. }
  515. if (realElmName == "script") {
  516. realElm.attr('type', 'text/javascript');
  517. }
  518. // Inject innerhtml
  519. innerHtml = node.attr('data-mce-html');
  520. if (innerHtml) {
  521. innerNode = new tinymce.html.Node('#text', 3);
  522. innerNode.raw = true;
  523. innerNode.value = unescape(innerHtml);
  524. realElm.append(innerNode);
  525. }
  526. node.replace(realElm);
  527. }
  528. });
  529. });
  530. editor.on('ObjectSelected', function(e) {
  531. var objectType = e.target.getAttribute('data-mce-object');
  532. if (objectType == "audio" || objectType == "script") {
  533. e.preventDefault();
  534. }
  535. });
  536. editor.on('objectResized', function(e) {
  537. var target = e.target, html;
  538. if (target.getAttribute('data-mce-object')) {
  539. html = target.getAttribute('data-mce-html');
  540. if (html) {
  541. html = unescape(html);
  542. target.setAttribute('data-mce-html', escape(
  543. updateHtml(html, {
  544. width: e.width,
  545. height: e.height
  546. })
  547. ));
  548. }
  549. }
  550. });
  551. editor.addButton('media', {
  552. tooltip: 'Insert/edit video',
  553. onclick: showDialog,
  554. stateSelector: ['img[data-mce-object=video]', 'img[data-mce-object=iframe]']
  555. });
  556. editor.addMenuItem('media', {
  557. icon: 'media',
  558. text: 'Insert video',
  559. onclick: showDialog,
  560. context: 'insert',
  561. prependToContext: true
  562. });
  563. });