This commit is contained in:
2025-10-22 15:39:40 +08:00
commit b0b510fac1
2720 changed files with 415933 additions and 0 deletions

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<title>Media Demo Page</title>
</head>
<body>
<h2>Media Demo Page</h2>
<div id="ephox-ui">
<textarea name="" id="" cols="30" rows="10" class="tinymce"></textarea>
</div>
<script src="../../../../../js/tinymce/tinymce.js"></script>
<script src="../../../../../scratch/demos/plugins/media/demo.js"></script>
</body>
</html>

View File

@@ -0,0 +1,36 @@
/**
* Demo.js
*
* Released under LGPL License.
* Copyright (c) 1999-2016 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
declare let tinymce: any;
tinymce.init({
selector: 'textarea.tinymce',
theme: 'modern',
skin_url: '../../../../../js/tinymce/skins/lightgray',
plugins: 'media code',
toolbar: 'undo redo | media code',
// media_dimensions: false,
// media_live_embeds: false,
file_picker_callback (callback, value, meta) {
// Provide alternative source and posted for the media dialog
if (meta.filetype === 'media') {
callback('https://youtu.be/a4tNU2jgTZU');
}
},
// media_url_resolver: function (data, resolve) {
// setTimeout(function () {
// resolve({
// html: '<div style="max-width: 650px;" data-ephox-embed-iri="https://youtu.be/a4tNU2jgTZU"><iframe src="https://www.youtube.com/embed/a4tNU2jgTZU?feature=oembed" width="612" height="344" frameborder="0" allowfullscreen="allowfullscreen"></iframe></div>' });
// }, 500);
// },
height: 600
});
export {};

View File

@@ -0,0 +1,25 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import PluginManager from 'tinymce/core/api/PluginManager';
import Api from './api/Api';
import Commands from './api/Commands';
import FilterContent from './core/FilterContent';
import ResolveName from './core/ResolveName';
import Selection from './core/Selection';
import Buttons from './ui/Buttons';
PluginManager.add('media', function (editor) {
Commands.register(editor);
Buttons.register(editor);
ResolveName.setup(editor);
FilterContent.setup(editor);
Selection.setup(editor);
return Api.get(editor);
});
export default function () { }

View File

@@ -0,0 +1,22 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Dialog from '../ui/Dialog';
const get = function (editor) {
const showDialog = function () {
Dialog.showDialog(editor);
};
return {
showDialog
};
};
export default {
get
};

View File

@@ -0,0 +1,20 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Dialog from '../ui/Dialog';
const register = function (editor) {
const showDialog = function () {
Dialog.showDialog(editor);
};
editor.addCommand('mceMedia', showDialog);
};
export default {
register
};

View File

@@ -0,0 +1,54 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const getScripts = function (editor) {
return editor.getParam('media_scripts');
};
const getAudioTemplateCallback = function (editor) {
return editor.getParam('audio_template_callback');
};
const getVideoTemplateCallback = function (editor) {
return editor.getParam('video_template_callback');
};
const hasLiveEmbeds = function (editor) {
return editor.getParam('media_live_embeds', true);
};
const shouldFilterHtml = function (editor) {
return editor.getParam('media_filter_html', true);
};
const getUrlResolver = function (editor) {
return editor.getParam('media_url_resolver');
};
const hasAltSource = function (editor) {
return editor.getParam('media_alt_source', true);
};
const hasPoster = function (editor) {
return editor.getParam('media_poster', true);
};
const hasDimensions = function (editor) {
return editor.getParam('media_dimensions', true);
};
export default {
getScripts,
getAudioTemplateCallback,
getVideoTemplateCallback,
hasLiveEmbeds,
shouldFilterHtml,
getUrlResolver,
hasAltSource,
hasPoster,
hasDimensions
};

View File

@@ -0,0 +1,140 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Tools from 'tinymce/core/api/util/Tools';
import Settings from '../api/Settings';
import HtmlToData from './HtmlToData';
import Mime from './Mime';
import UpdateHtml from './UpdateHtml';
import * as UrlPatterns from './UrlPatterns';
import VideoScript from './VideoScript';
const getIframeHtml = function (data) {
const allowFullscreen = data.allowFullscreen ? ' allowFullscreen="1"' : '';
return '<iframe src="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '"' + allowFullscreen + '></iframe>';
};
const getFlashHtml = function (data) {
let html = '<object data="' + data.source1 + '" width="' + data.width + '" height="' + data.height + '" type="application/x-shockwave-flash">';
if (data.poster) {
html += '<img src="' + data.poster + '" width="' + data.width + '" height="' + data.height + '" />';
}
html += '</object>';
return html;
};
const getAudioHtml = function (data, audioTemplateCallback) {
if (audioTemplateCallback) {
return audioTemplateCallback(data);
} else {
return (
'<audio controls="controls" src="' + data.source1 + '">' +
(
data.source2 ?
'\n<source src="' + data.source2 + '"' +
(data.source2mime ? ' type="' + data.source2mime + '"' : '') +
' />\n' : '') +
'</audio>'
);
}
};
const getVideoHtml = function (data, videoTemplateCallback) {
if (videoTemplateCallback) {
return videoTemplateCallback(data);
} else {
return (
'<video width="' + data.width +
'" height="' + data.height + '"' +
(data.poster ? ' poster="' + data.poster + '"' : '') + ' controls="controls">\n' +
'<source src="' + data.source1 + '"' +
(data.source1mime ? ' type="' + data.source1mime + '"' : '') + ' />\n' +
(data.source2 ? '<source src="' + data.source2 + '"' +
(data.source2mime ? ' type="' + data.source2mime + '"' : '') + ' />\n' : '') +
'</video>'
);
}
};
const getScriptHtml = function (data) {
return '<script src="' + data.source1 + '"></script>';
};
const dataToHtml = function (editor, dataIn) {
const data = Tools.extend({}, dataIn);
if (!data.source1) {
Tools.extend(data, HtmlToData.htmlToData(Settings.getScripts(editor), data.embed));
if (!data.source1) {
return '';
}
}
if (!data.source2) {
data.source2 = '';
}
if (!data.poster) {
data.poster = '';
}
data.source1 = editor.convertURL(data.source1, 'source');
data.source2 = editor.convertURL(data.source2, 'source');
data.source1mime = Mime.guess(data.source1);
data.source2mime = Mime.guess(data.source2);
data.poster = editor.convertURL(data.poster, 'poster');
const pattern = UrlPatterns.matchPattern(data.source1);
if (pattern) {
data.source1 = pattern.url;
data.type = pattern.type;
data.allowFullscreen = pattern.allowFullscreen;
data.width = data.width || pattern.w;
data.height = data.height || pattern.h;
}
if (data.embed) {
return UpdateHtml.updateHtml(data.embed, data, true);
} else {
const videoScript = VideoScript.getVideoScriptMatch(Settings.getScripts(editor), data.source1);
if (videoScript) {
data.type = 'script';
data.width = videoScript.width;
data.height = videoScript.height;
}
const audioTemplateCallback = Settings.getAudioTemplateCallback(editor);
const videoTemplateCallback = Settings.getVideoTemplateCallback(editor);
data.width = data.width || 300;
data.height = data.height || 150;
Tools.each(data, function (value, key) {
data[key] = editor.dom.encode(value);
});
if (data.type === 'iframe') {
return getIframeHtml(data);
} else if (data.source1mime === 'application/x-shockwave-flash') {
return getFlashHtml(data);
} else if (data.source1mime.indexOf('audio') !== -1) {
return getAudioHtml(data, audioTemplateCallback);
} else if (data.type === 'script') {
return getScriptHtml(data);
} else {
return getVideoHtml(data, videoTemplateCallback);
}
}
};
export default {
dataToHtml
};

View File

@@ -0,0 +1,123 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Node from 'tinymce/core/api/html/Node';
import Tools from 'tinymce/core/api/util/Tools';
import Nodes from './Nodes';
import Sanitize from './Sanitize';
declare let unescape: any;
const setup = function (editor) {
editor.on('preInit', function () {
// Make sure that any messy HTML is retained inside these
const specialElements = editor.schema.getSpecialElements();
Tools.each('video audio iframe object'.split(' '), function (name) {
specialElements[name] = new RegExp('<\/' + name + '[^>]*>', 'gi');
});
// Allow elements
// editor.schema.addValidElements(
// 'object[id|style|width|height|classid|codebase|*],embed[id|style|width|height|type|src|*],video[*],audio[*]'
// );
// Set allowFullscreen attribs as boolean
const boolAttrs = editor.schema.getBoolAttrs();
Tools.each('webkitallowfullscreen mozallowfullscreen allowfullscreen'.split(' '), function (name) {
boolAttrs[name] = {};
});
// Converts iframe, video etc into placeholder images
editor.parser.addNodeFilter('iframe,video,audio,object,embed,script',
Nodes.placeHolderConverter(editor));
// Replaces placeholder images with real elements for video, object, iframe etc
editor.serializer.addAttributeFilter('data-mce-object', function (nodes, name) {
let i = nodes.length;
let node;
let realElm;
let ai;
let attribs;
let innerHtml;
let innerNode;
let realElmName;
let className;
while (i--) {
node = nodes[i];
if (!node.parent) {
continue;
}
realElmName = node.attr(name);
realElm = new Node(realElmName, 1);
// Add width/height to everything but audio
if (realElmName !== 'audio' && realElmName !== 'script') {
className = node.attr('class');
if (className && className.indexOf('mce-preview-object') !== -1) {
realElm.attr({
width: node.firstChild.attr('width'),
height: node.firstChild.attr('height')
});
} else {
realElm.attr({
width: node.attr('width'),
height: node.attr('height')
});
}
}
realElm.attr({
style: node.attr('style')
});
// Unprefix all placeholder attributes
attribs = node.attributes;
ai = attribs.length;
while (ai--) {
const attrName = attribs[ai].name;
if (attrName.indexOf('data-mce-p-') === 0) {
realElm.attr(attrName.substr(11), attribs[ai].value);
}
}
if (realElmName === 'script') {
realElm.attr('type', 'text/javascript');
}
// Inject innerhtml
innerHtml = node.attr('data-mce-html');
if (innerHtml) {
innerNode = new Node('#text', 3);
innerNode.raw = true;
innerNode.value = Sanitize.sanitize(editor, unescape(innerHtml));
realElm.append(innerNode);
}
node.replace(realElm);
}
});
});
editor.on('setContent', function () {
// TODO: This shouldn't be needed there should be a way to mark bogus
// elements so they are never removed except external save
editor.$('span.mce-preview-object').each(function (index, elm) {
const $elm = editor.$(elm);
if ($elm.find('span.mce-shim', elm).length === 0) {
$elm.append('<span class="mce-shim"></span>');
}
});
});
};
export default {
setup
};

View File

@@ -0,0 +1,100 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Tools from 'tinymce/core/api/util/Tools';
import SaxParser from 'tinymce/core/api/html/SaxParser';
import DOMUtils from 'tinymce/core/api/dom/DOMUtils';
import VideoScript from './VideoScript';
import Size from './Size';
const DOM = DOMUtils.DOM;
const getEphoxEmbedIri = function (elm) {
return DOM.getAttrib(elm, 'data-ephox-embed-iri');
};
const isEphoxEmbed = function (html) {
const fragment = DOM.createFragment(html);
return getEphoxEmbedIri(fragment.firstChild) !== '';
};
const htmlToDataSax = function (prefixes, html) {
let data: any = {};
SaxParser({
validate: false,
allow_conditional_comments: true,
special: 'script,noscript',
start (name, attrs) {
if (!data.source1 && name === 'param') {
data.source1 = attrs.map.movie;
}
if (name === 'iframe' || name === 'object' || name === 'embed' || name === 'video' || name === 'audio') {
if (!data.type) {
data.type = name;
}
data = Tools.extend(attrs.map, data);
}
if (name === 'script') {
const videoScript = VideoScript.getVideoScriptMatch(prefixes, attrs.map.src);
if (!videoScript) {
return;
}
data = {
type: 'script',
source1: attrs.map.src,
width: videoScript.width,
height: videoScript.height
};
}
if (name === 'source') {
if (!data.source1) {
data.source1 = attrs.map.src;
} else if (!data.source2) {
data.source2 = attrs.map.src;
}
}
if (name === 'img' && !data.poster) {
data.poster = attrs.map.src;
}
}
}).parse(html);
data.source1 = data.source1 || data.src || data.data;
data.source2 = data.source2 || '';
data.poster = data.poster || '';
return data;
};
const ephoxEmbedHtmlToData = function (html) {
const fragment = DOM.createFragment(html);
const div = fragment.firstChild;
return {
type: 'ephox-embed-iri',
source1: getEphoxEmbedIri(div),
source2: '',
poster: '',
width: Size.getMaxWidth(div),
height: Size.getMaxHeight(div)
};
};
const htmlToData = function (prefixes, html) {
return isEphoxEmbed(html) ? ephoxEmbedHtmlToData(html) : htmlToDataSax(prefixes, html);
};
export default {
htmlToData
};

View File

@@ -0,0 +1,25 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const guess = function (url) {
const mimes = {
mp3: 'audio/mpeg',
wav: 'audio/wav',
mp4: 'video/mp4',
webm: 'video/webm',
ogg: 'video/ogg',
swf: 'application/x-shockwave-flash'
};
const fileEnd = url.toLowerCase().split('.').pop();
const mime = mimes[fileEnd];
return mime ? mime : '';
};
export default {
guess
};

View File

@@ -0,0 +1,167 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Env from 'tinymce/core/api/Env';
import Node from 'tinymce/core/api/html/Node';
import Settings from '../api/Settings';
import Sanitize from './Sanitize';
import VideoScript from './VideoScript';
import { Editor } from 'tinymce/core/api/Editor';
declare let escape: any;
const createPlaceholderNode = function (editor: Editor, node: Node) {
let placeHolder;
const name = node.name;
placeHolder = new Node('img', 1);
placeHolder.shortEnded = true;
retainAttributesAndInnerHtml(editor, node, placeHolder);
placeHolder.attr({
'width': node.attr('width') || '300',
'height': node.attr('height') || (name === 'audio' ? '30' : '150'),
'style': node.attr('style'),
'src': Env.transparentSrc,
'data-mce-object': name,
'class': 'mce-object mce-object-' + name
});
return placeHolder;
};
const createPreviewIframeNode = function (editor: Editor, node: Node) {
let previewWrapper;
let previewNode;
let shimNode;
const name = node.name;
previewWrapper = new Node('span', 1);
previewWrapper.attr({
'contentEditable': 'false',
'style': node.attr('style'),
'data-mce-object': name,
'class': 'mce-preview-object mce-object-' + name
});
retainAttributesAndInnerHtml(editor, node, previewWrapper);
previewNode = new Node(name, 1);
previewNode.attr({
src: node.attr('src'),
allowfullscreen: node.attr('allowfullscreen'),
style: node.attr('style'),
class: node.attr('class'),
width: node.attr('width'),
height: node.attr('height'),
frameborder: '0'
});
shimNode = new Node('span', 1);
shimNode.attr('class', 'mce-shim');
previewWrapper.append(previewNode);
previewWrapper.append(shimNode);
return previewWrapper;
};
const retainAttributesAndInnerHtml = function (editor: Editor, sourceNode: Node, targetNode: Node) {
let attrName;
let attrValue;
let attribs;
let ai;
let innerHtml;
// Prefix all attributes except width, height and style since we
// will add these to the placeholder
attribs = sourceNode.attributes;
ai = attribs.length;
while (ai--) {
attrName = attribs[ai].name;
attrValue = attribs[ai].value;
if (attrName !== 'width' && attrName !== 'height' && attrName !== 'style') {
if (attrName === 'data' || attrName === 'src') {
attrValue = editor.convertURL(attrValue, attrName);
}
targetNode.attr('data-mce-p-' + attrName, attrValue);
}
}
// Place the inner HTML contents inside an escaped attribute
// This enables us to copy/paste the fake object
innerHtml = sourceNode.firstChild && sourceNode.firstChild.value;
if (innerHtml) {
targetNode.attr('data-mce-html', escape(Sanitize.sanitize(editor, innerHtml)));
targetNode.firstChild = null;
}
};
const isWithinEphoxEmbed = function (node: Node) {
while ((node = node.parent)) {
if (node.attr('data-ephox-embed-iri')) {
return true;
}
}
return false;
};
const placeHolderConverter = function (editor: Editor) {
return function (nodes) {
let i = nodes.length;
let node;
let videoScript;
while (i--) {
node = nodes[i];
if (!node.parent) {
continue;
}
if (node.parent.attr('data-mce-object')) {
continue;
}
if (node.name === 'script') {
videoScript = VideoScript.getVideoScriptMatch(Settings.getScripts(editor), node.attr('src'));
if (!videoScript) {
continue;
}
}
if (videoScript) {
if (videoScript.width) {
node.attr('width', videoScript.width.toString());
}
if (videoScript.height) {
node.attr('height', videoScript.height.toString());
}
}
if (node.name === 'iframe' && Settings.hasLiveEmbeds(editor) && Env.ceFalse) {
if (!isWithinEphoxEmbed(node)) {
node.replace(createPreviewIframeNode(editor, node));
}
} else {
if (!isWithinEphoxEmbed(node)) {
node.replace(createPlaceholderNode(editor, node));
}
}
}
};
};
export default {
createPreviewIframeNode,
createPlaceholderNode,
placeHolderConverter
};

View File

@@ -0,0 +1,20 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const setup = function (editor) {
editor.on('ResolveName', function (e) {
let name;
if (e.target.nodeType === 1 && (name = e.target.getAttribute('data-mce-object'))) {
e.name = name;
}
});
};
export default {
setup
};

View File

@@ -0,0 +1,73 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import SaxParser from 'tinymce/core/api/html/SaxParser';
import Schema from 'tinymce/core/api/html/Schema';
import Writer from 'tinymce/core/api/html/Writer';
import Settings from '../api/Settings';
const sanitize = function (editor, html) {
if (Settings.shouldFilterHtml(editor) === false) {
return html;
}
const writer = Writer();
let blocked;
SaxParser({
validate: false,
allow_conditional_comments: false,
special: 'script,noscript',
comment (text) {
writer.comment(text);
},
cdata (text) {
writer.cdata(text);
},
text (text, raw) {
writer.text(text, raw);
},
start (name, attrs, empty) {
blocked = true;
if (name === 'script' || name === 'noscript') {
return;
}
for (let i = 0; i < attrs.length; i++) {
if (attrs[i].name.indexOf('on') === 0) {
return;
}
if (attrs[i].name === 'style') {
attrs[i].value = editor.dom.serializeStyle(editor.dom.parseStyle(attrs[i].value), name);
}
}
writer.start(name, attrs, empty);
blocked = false;
},
end (name) {
if (blocked) {
return;
}
writer.end(name);
}
}, Schema({})).parse(html);
return writer.getContent();
};
export default {
sanitize
};

View File

@@ -0,0 +1,53 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import UpdateHtml from './UpdateHtml';
declare let escape: any;
declare let unescape: any;
const setup = function (editor) {
editor.on('click keyup', function () {
const selectedNode = editor.selection.getNode();
if (selectedNode && editor.dom.hasClass(selectedNode, 'mce-preview-object')) {
if (editor.dom.getAttrib(selectedNode, 'data-mce-selected')) {
selectedNode.setAttribute('data-mce-selected', '2');
}
}
});
editor.on('ObjectSelected', function (e) {
const objectType = e.target.getAttribute('data-mce-object');
if (objectType === 'audio' || objectType === 'script') {
e.preventDefault();
}
});
editor.on('objectResized', function (e) {
const target = e.target;
let html;
if (target.getAttribute('data-mce-object')) {
html = target.getAttribute('data-mce-html');
if (html) {
html = unescape(html);
target.setAttribute('data-mce-html', escape(
UpdateHtml.updateHtml(html, {
width: e.width,
height: e.height
})
));
}
}
});
};
export default {
setup
};

View File

@@ -0,0 +1,57 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Promise from 'tinymce/core/api/util/Promise';
import Settings from '../api/Settings';
import DataToHtml from './DataToHtml';
const cache = {};
const embedPromise = function (data, dataToHtml, handler) {
return new Promise<{url: string, html: string}>(function (res, rej) {
const wrappedResolve = function (response) {
if (response.html) {
cache[data.source1] = response;
}
return res({
url: data.source1,
html: response.html ? response.html : dataToHtml(data)
});
};
if (cache[data.source1]) {
wrappedResolve(cache[data.source1]);
} else {
handler({ url: data.source1 }, wrappedResolve, rej);
}
});
};
const defaultPromise = function (data, dataToHtml) {
return new Promise<{url: string, html: string}>(function (res) {
res({ html: dataToHtml(data), url: data.source1 });
});
};
const loadedData = function (editor) {
return function (data) {
return DataToHtml.dataToHtml(editor, data);
};
};
const getEmbedHtml = function (editor, data) {
const embedHandler = Settings.getUrlResolver(editor);
return embedHandler ? embedPromise(data, loadedData(editor), embedHandler) : defaultPromise(data, loadedData(editor));
};
const isCached = function (url) {
return cache.hasOwnProperty(url);
};
export default {
getEmbedHtml,
isCached
};

View File

@@ -0,0 +1,35 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const trimPx = function (value) {
return value.replace(/px$/, '');
};
const addPx = function (value) {
return /^[0-9.]+$/.test(value) ? (value + 'px') : value;
};
const getSize = function (name) {
return function (elm) {
return elm ? trimPx(elm.style[name]) : '';
};
};
const setSize = function (name) {
return function (elm, value) {
if (elm) {
elm.style[name] = addPx(value);
}
};
};
export default {
getMaxWidth: getSize('maxWidth'),
getMaxHeight: getSize('maxHeight'),
setMaxWidth: setSize('maxWidth'),
setMaxHeight: setSize('maxHeight')
};

View File

@@ -0,0 +1,206 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Writer from 'tinymce/core/api/html/Writer';
import SaxParser from 'tinymce/core/api/html/SaxParser';
import Schema from 'tinymce/core/api/html/Schema';
import DOMUtils from 'tinymce/core/api/dom/DOMUtils';
import Size from './Size';
import { Element } from '@ephox/dom-globals';
const DOM = DOMUtils.DOM;
const setAttributes = function (attrs, updatedAttrs) {
let name;
let i;
let value;
let attr;
for (name in updatedAttrs) {
value = '' + updatedAttrs[name];
if (attrs.map[name]) {
i = attrs.length;
while (i--) {
attr = attrs[i];
if (attr.name === name) {
if (value) {
attrs.map[name] = value;
attr.value = value;
} else {
delete attrs.map[name];
attrs.splice(i, 1);
}
}
}
} else if (value) {
attrs.push({
name,
value
});
attrs.map[name] = value;
}
}
};
const normalizeHtml = function (html) {
const writer = Writer();
const parser = SaxParser(writer);
parser.parse(html);
return writer.getContent();
};
const updateHtmlSax = function (html, data, updateAll?) {
const writer = Writer();
let sourceCount = 0;
let hasImage;
SaxParser({
validate: false,
allow_conditional_comments: true,
special: 'script,noscript',
comment (text) {
writer.comment(text);
},
cdata (text) {
writer.cdata(text);
},
text (text, raw) {
writer.text(text, raw);
},
start (name, attrs, empty) {
switch (name) {
case 'video':
case 'object':
case 'embed':
case 'img':
case 'iframe':
if (data.height !== undefined && data.width !== undefined) {
setAttributes(attrs, {
width: data.width,
height: data.height
});
}
break;
}
if (updateAll) {
switch (name) {
case 'video':
setAttributes(attrs, {
poster: data.poster,
src: ''
});
if (data.source2) {
setAttributes(attrs, {
src: ''
});
}
break;
case 'iframe':
setAttributes(attrs, {
src: data.source1
});
break;
case 'source':
sourceCount++;
if (sourceCount <= 2) {
setAttributes(attrs, {
src: data['source' + sourceCount],
type: data['source' + sourceCount + 'mime']
});
if (!data['source' + sourceCount]) {
return;
}
}
break;
case 'img':
if (!data.poster) {
return;
}
hasImage = true;
break;
}
}
writer.start(name, attrs, empty);
},
end (name) {
if (name === 'video' && updateAll) {
for (let index = 1; index <= 2; index++) {
if (data['source' + index]) {
const attrs: any = [];
attrs.map = {};
if (sourceCount < index) {
setAttributes(attrs, {
src: data['source' + index],
type: data['source' + index + 'mime']
});
writer.start('source', attrs, true);
}
}
}
}
if (data.poster && name === 'object' && updateAll && !hasImage) {
const imgAttrs: any = [];
imgAttrs.map = {};
setAttributes(imgAttrs, {
src: data.poster,
width: data.width,
height: data.height
});
writer.start('img', imgAttrs, true);
}
writer.end(name);
}
}, Schema({})).parse(html);
return writer.getContent();
};
const isEphoxEmbed = function (html) {
const fragment = DOM.createFragment(html);
return DOM.getAttrib(fragment.firstChild, 'data-ephox-embed-iri') !== '';
};
const updateEphoxEmbed = function (html, data) {
const fragment = DOM.createFragment(html);
const div = fragment.firstChild as Element;
Size.setMaxWidth(div, data.width);
Size.setMaxHeight(div, data.height);
return normalizeHtml(div.outerHTML);
};
const updateHtml = function (html, data, updateAll?) {
return isEphoxEmbed(html) ? updateEphoxEmbed(html, data) : updateHtmlSax(html, data, updateAll);
};
export default {
updateHtml
};

View File

@@ -0,0 +1,94 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Tools from 'tinymce/core/api/util/Tools';
export interface UrlPattern {
regex: RegExp;
type: string;
w: number;
h: number;
url: string;
allowFullscreen: boolean;
}
const urlPatterns: UrlPattern[] = [
{
regex: /youtu\.be\/([\w\-_\?&=.]+)/i,
type: 'iframe', w: 560, h: 314,
url: '//www.youtube.com/embed/$1',
allowFullscreen: true
},
{
regex: /youtube\.com(.+)v=([^&]+)(&([a-z0-9&=\-_]+))?/i,
type: 'iframe', w: 560, h: 314,
url: '//www.youtube.com/embed/$2?$4',
allowFullscreen: true
},
{
regex: /youtube.com\/embed\/([a-z0-9\?&=\-_]+)/i,
type: 'iframe', w: 560, h: 314,
url: '//www.youtube.com/embed/$1',
allowFullscreen: true
},
{
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',
allowFullscreen: true
},
{
regex: /vimeo\.com\/(.*)\/([0-9]+)/,
type: 'iframe', w: 425, h: 350,
url: '//player.vimeo.com/video/$2?title=0&amp;byline=0',
allowFullscreen: true
},
{
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"',
allowFullscreen: false
},
{
regex: /dailymotion\.com\/video\/([^_]+)/,
type: 'iframe', w: 480, h: 270,
url: '//www.dailymotion.com/embed/video/$1',
allowFullscreen: true
},
{
regex: /dai\.ly\/([^_]+)/,
type: 'iframe', w: 480, h: 270,
url: '//www.dailymotion.com/embed/video/$1',
allowFullscreen: true
}
];
const getUrl = (pattern: UrlPattern, url: string) => {
const match = pattern.regex.exec(url);
let newUrl = pattern.url;
for (let i = 0; i < match.length; i++) {
newUrl = newUrl.replace('$' + i, () => {
return match[i] ? match[i] : '';
});
}
return newUrl.replace(/\?$/, '');
};
const matchPattern = (url: string): UrlPattern => {
const pattern = urlPatterns.filter((pattern) => pattern.regex.test(url));
if (pattern.length > 0) {
return Tools.extend({}, pattern[0], { url: getUrl(pattern[0], url) });
} else {
return null;
}
};
export {
matchPattern
};

View File

@@ -0,0 +1,21 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const getVideoScriptMatch = function (prefixes, src) {
// var prefixes = Settings.getScripts(editor);
if (prefixes) {
for (let i = 0; i < prefixes.length; i++) {
if (src.indexOf(prefixes[i].filter) !== -1) {
return prefixes[i];
}
}
}
};
export default {
getVideoScriptMatch
};

View File

@@ -0,0 +1,26 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const register = function (editor) {
editor.addButton('media', {
tooltip: 'Insert/edit media',
cmd: 'mceMedia',
stateSelector: ['img[data-mce-object]', 'span[data-mce-object]', 'div[data-ephox-embed-iri]']
});
editor.addMenuItem('media', {
icon: 'media',
text: 'Media',
cmd: 'mceMedia',
context: 'insert',
prependToContext: true
});
};
export default {
register
};

View File

@@ -0,0 +1,234 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Env from 'tinymce/core/api/Env';
import Tools from 'tinymce/core/api/util/Tools';
import Settings from '../api/Settings';
import HtmlToData from '../core/HtmlToData';
import Service from '../core/Service';
import Size from '../core/Size';
import UpdateHtml from '../core/UpdateHtml';
import SizeManager from './SizeManager';
const embedChange = (Env.ie && Env.ie <= 8) ? 'onChange' : 'onInput';
const handleError = function (editor) {
return function (error) {
const errorMessage = error && error.msg ?
'Media embed handler error: ' + error.msg :
'Media embed handler threw unknown error.';
editor.notificationManager.open({ type: 'error', text: errorMessage });
};
};
const getData = function (editor) {
const element = editor.selection.getNode();
const dataEmbed = element.getAttribute('data-ephox-embed-iri');
if (dataEmbed) {
return {
'source1': dataEmbed,
'data-ephox-embed-iri': dataEmbed,
'width': Size.getMaxWidth(element),
'height': Size.getMaxHeight(element)
};
}
return element.getAttribute('data-mce-object') ?
HtmlToData.htmlToData(Settings.getScripts(editor), editor.serializer.serialize(element, { selection: true })) :
{};
};
const getSource = function (editor) {
const elm = editor.selection.getNode();
if (elm.getAttribute('data-mce-object') || elm.getAttribute('data-ephox-embed-iri')) {
return editor.selection.getContent();
}
};
const addEmbedHtml = function (win, editor) {
return function (response) {
const html = response.html;
const embed = win.find('#embed')[0];
const data = Tools.extend(HtmlToData.htmlToData(Settings.getScripts(editor), html), { source1: response.url });
win.fromJSON(data);
if (embed) {
embed.value(html);
SizeManager.updateSize(win);
}
};
};
const selectPlaceholder = function (editor, beforeObjects) {
let i;
let y;
const afterObjects = editor.dom.select('img[data-mce-object]');
// Find new image placeholder so we can select it
for (i = 0; i < beforeObjects.length; i++) {
for (y = afterObjects.length - 1; y >= 0; y--) {
if (beforeObjects[i] === afterObjects[y]) {
afterObjects.splice(y, 1);
}
}
}
editor.selection.select(afterObjects[0]);
};
const handleInsert = function (editor, html) {
const beforeObjects = editor.dom.select('img[data-mce-object]');
editor.insertContent(html);
selectPlaceholder(editor, beforeObjects);
editor.nodeChanged();
};
const submitForm = function (win, editor) {
const data = win.toJSON();
data.embed = UpdateHtml.updateHtml(data.embed, data);
if (data.embed && Service.isCached(data.source1)) {
handleInsert(editor, data.embed);
} else {
Service.getEmbedHtml(editor, data)
.then(function (response) {
handleInsert(editor, response.html);
}).catch(handleError(editor));
}
};
const populateMeta = function (win, meta) {
Tools.each(meta, function (value, key) {
win.find('#' + key).value(value);
});
};
const showDialog = function (editor) {
let win;
let data;
const generalFormItems: any[] = [
{
name: 'source1',
type: 'filepicker',
filetype: 'media',
size: 40,
autofocus: true,
label: 'Source',
onpaste () {
setTimeout(function () {
Service.getEmbedHtml(editor, win.toJSON())
.then(
addEmbedHtml(win, editor)
).catch(handleError(editor));
}, 1);
},
onchange (e) {
Service.getEmbedHtml(editor, win.toJSON())
.then(
addEmbedHtml(win, editor)
).catch(handleError(editor));
populateMeta(win, e.meta);
},
onbeforecall (e) {
e.meta = win.toJSON();
}
}
];
const advancedFormItems = [];
const reserialise = function (update) {
update(win);
data = win.toJSON();
win.find('#embed').value(UpdateHtml.updateHtml(data.embed, data));
};
if (Settings.hasAltSource(editor)) {
advancedFormItems.push({ name: 'source2', type: 'filepicker', filetype: 'media', size: 40, label: 'Alternative source' });
}
if (Settings.hasPoster(editor)) {
advancedFormItems.push({ name: 'poster', type: 'filepicker', filetype: 'image', size: 40, label: 'Poster' });
}
if (Settings.hasDimensions(editor)) {
const control = SizeManager.createUi(reserialise);
generalFormItems.push(control);
}
data = getData(editor);
const embedTextBox = {
id: 'mcemediasource',
type: 'textbox',
flex: 1,
name: 'embed',
value: getSource(editor),
multiline: true,
rows: 5,
label: 'Source'
};
const updateValueOnChange = function () {
data = Tools.extend({}, HtmlToData.htmlToData(Settings.getScripts(editor), this.value()));
this.parent().parent().fromJSON(data);
};
embedTextBox[embedChange] = updateValueOnChange;
const body = [
{
title: 'General',
type: 'form',
items: generalFormItems
},
{
title: 'Embed',
type: 'container',
layout: 'flex',
direction: 'column',
align: 'stretch',
padding: 10,
spacing: 10,
items: [
{
type: 'label',
text: 'Paste your embed code below:',
forId: 'mcemediasource'
},
embedTextBox
]
}
];
if (advancedFormItems.length > 0) {
body.push({ title: 'Advanced', type: 'form', items: advancedFormItems });
}
win = editor.windowManager.open({
title: 'Insert/edit media',
data,
bodyType: 'tabpanel',
body,
onSubmit () {
SizeManager.updateSize(win);
submitForm(win, editor);
}
});
SizeManager.syncSize(win);
};
export default {
showDialog
};

View File

@@ -0,0 +1,86 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const doSyncSize = function (widthCtrl, heightCtrl) {
widthCtrl.state.set('oldVal', widthCtrl.value());
heightCtrl.state.set('oldVal', heightCtrl.value());
};
const doSizeControls = function (win, f) {
const widthCtrl = win.find('#width')[0];
const heightCtrl = win.find('#height')[0];
const constrained = win.find('#constrain')[0];
if (widthCtrl && heightCtrl && constrained) {
f(widthCtrl, heightCtrl, constrained.checked());
}
};
const doUpdateSize = function (widthCtrl, heightCtrl, isContrained) {
const oldWidth = widthCtrl.state.get('oldVal');
const oldHeight = heightCtrl.state.get('oldVal');
let newWidth = widthCtrl.value();
let newHeight = heightCtrl.value();
if (isContrained && oldWidth && oldHeight && newWidth && newHeight) {
if (newWidth !== oldWidth) {
newHeight = Math.round((newWidth / oldWidth) * newHeight);
if (!isNaN(newHeight)) {
heightCtrl.value(newHeight);
}
} else {
newWidth = Math.round((newHeight / oldHeight) * newWidth);
if (!isNaN(newWidth)) {
widthCtrl.value(newWidth);
}
}
}
doSyncSize(widthCtrl, heightCtrl);
};
const syncSize = function (win) {
doSizeControls(win, doSyncSize);
};
const updateSize = function (win) {
doSizeControls(win, doUpdateSize);
};
const createUi = function (onChange) {
const recalcSize = function () {
onChange(function (win) {
updateSize(win);
});
};
return {
type: 'container',
label: 'Dimensions',
layout: 'flex',
align: 'center',
spacing: 5,
items: [
{
name: 'width', type: 'textbox', maxLength: 5, size: 5,
onchange: recalcSize, ariaLabel: 'Width'
},
{ type: 'label', text: 'x' },
{
name: 'height', type: 'textbox', maxLength: 5, size: 5,
onchange: recalcSize, ariaLabel: 'Height'
},
{ name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions' }
]
};
};
export default {
createUi,
syncSize,
updateSize
};

View File

@@ -0,0 +1,39 @@
import HtmlToData from 'tinymce/plugins/media/core/HtmlToData';
import { RawAssertions } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
UnitTest.test('atomic.core.HtmlToDataTest', function () {
const testHtmlToData = function (html, expected) {
const actual = HtmlToData.htmlToData([], html);
RawAssertions.assertEq('Assert equal', expected, actual);
};
testHtmlToData('<div data-ephox-embed-iri="a"></div>', {
type: 'ephox-embed-iri',
source1: 'a',
source2: '',
poster: '',
width: '',
height: ''
});
testHtmlToData('<div data-ephox-embed-iri="a" style="max-width: 300px; max-height: 200px"></div>', {
type: 'ephox-embed-iri',
source1: 'a',
source2: '',
poster: '',
width: '300',
height: '200'
});
testHtmlToData('<iframe src="//www.youtube.com/embed/b3XFjWInBog" width="560" height="314" allowFullscreen="1"></iframe>', {
src: '//www.youtube.com/embed/b3XFjWInBog',
width: '560',
height: '314',
allowfullscreen: '1',
type: 'iframe',
source1: '//www.youtube.com/embed/b3XFjWInBog',
source2: '',
poster: ''
});
});

View File

@@ -0,0 +1,38 @@
import { UnitTest, assert } from '@ephox/bedrock';
import * as UrlPatterns from 'tinymce/plugins/media/core/UrlPatterns';
UnitTest.test('atomic.core.UrlPatternsTest', function () {
const check = (url, expected) => {
const pattern = UrlPatterns.matchPattern(url);
assert.eq(expected, pattern.url);
};
check(
'https://www.youtube.com/watch?v=cOTbVN2qZBY&t=30s&index=2&list=PLfQW7NTMsSA1dTqk1dMEanFLovB4-C0FT',
'//www.youtube.com/embed/cOTbVN2qZBY?t=30s&index=2&list=PLfQW7NTMsSA1dTqk1dMEanFLovB4-C0FT'
);
check(
'https://www.youtube.com/watch?v=b3XFjWInBog',
'//www.youtube.com/embed/b3XFjWInBog'
);
check(
'https://vimeo.com/12345',
'//player.vimeo.com/video/12345?title=0&byline=0&portrait=0&color=8dc7dc'
);
check(
'https://vimeo.com/channels/staffpicks/12345',
'//player.vimeo.com/video/12345?title=0&amp;byline=0'
);
check(
'http://www.dailymotion.com/video/x5iscr6',
'//www.dailymotion.com/embed/video/x5iscr6'
);
check(
'http://www.dai.ly/x5iscr6',
'//www.dailymotion.com/embed/video/x5iscr6'
);
});

View File

@@ -0,0 +1,191 @@
import { Pipeline } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { LegacyUnit, TinyLoader } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/media/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
UnitTest.asynctest('browser.tinymce.plugins.media.ContentFormatsTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
const suite = LegacyUnit.createSuite();
Plugin();
Theme();
suite.test('Object retain as is', function (editor) {
editor.setContent(
'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="355">' +
'<param name="movie" value="someurl">' +
'<param name="wmode" value="transparent">' +
'<embed src="someurl" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355" />' +
'</object>'
);
LegacyUnit.equal(editor.getContent(),
'<p><object width="425" height="355" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000">' +
'<param name="movie" value="someurl" />' +
'<param name="wmode" value="transparent" />' +
'<embed src="someurl" type="application/x-shockwave-flash" wmode="transparent" width="425" height="355" />' +
'</object></p>'
);
});
suite.test('Embed retain as is', function (editor) {
editor.setContent(
'<embed src="320x240.ogg" width="100" height="200">text<a href="#">link</a></embed>'
);
LegacyUnit.equal(
editor.getContent(),
'<p><embed src="320x240.ogg" width="100" height="200"></embed>text<a href="#">link</a></p>'
);
});
suite.test('Video retain as is', function (editor) {
editor.setContent(
'<video src="320x240.ogg" autoplay loop controls>text<a href="#">link</a></video>'
);
LegacyUnit.equal(
editor.getContent(),
'<p><video src="320x240.ogg" autoplay="autoplay" loop="loop" controls="controls" width="300" height="150">text<a href="#">link</a></video></p>'
);
});
suite.test('Iframe retain as is', function (editor) {
editor.setContent(
'<iframe src="320x240.ogg" allowfullscreen>text<a href="#">link</a></iframe>'
);
LegacyUnit.equal(editor.getContent(),
'<p><iframe src="320x240.ogg" allowfullscreen="allowfullscreen">text<a href="#">link</a></iframe></p>'
);
});
suite.test('Audio retain as is', function (editor) {
editor.setContent(
'<audio src="sound.mp3">' +
'<track kind="captions" src="foo.en.vtt" srclang="en" label="English">' +
'<track kind="captions" src="foo.sv.vtt" srclang="sv" label="Svenska">' +
'text<a href="#">link</a>' +
'</audio>'
);
LegacyUnit.equal(editor.getContent(),
'<p>' +
'<audio src="sound.mp3">' +
'<track kind="captions" src="foo.en.vtt" srclang="en" label="English" />' +
'<track kind="captions" src="foo.sv.vtt" srclang="sv" label="Svenska" />' +
'text<a href="#">link</a>' +
'</audio>' +
'</p>'
);
});
suite.test('Resize complex object', function (editor) {
editor.setContent(
'<video width="300" height="150" controls="controls">' +
'<source src="s" />' +
'<object type="application/x-shockwave-flash" data="../../js/tinymce/plugins/media/moxieplayer.swf" width="300" height="150">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="video_src=s" />' +
'<!--[if IE]><param name="movie" value="../../js/tinymce/plugins/media/moxieplayer.swf" /><![endif]-->' +
'</object>' +
'</video>'
);
const placeholderElm = editor.getBody().firstChild.firstChild;
placeholderElm.width = 100;
placeholderElm.height = 200;
editor.fire('objectResized', { target: placeholderElm, width: placeholderElm.width, height: placeholderElm.height });
editor.settings.media_filter_html = false;
LegacyUnit.equal(editor.getContent(),
'<p>' +
'<video controls="controls" width="100" height="200">' +
'<source src="s" />' +
'<object type="application/x-shockwave-flash" data="../../js/tinymce/plugins/media/moxieplayer.swf" width="100" height="200">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="video_src=s" />' +
'<!-- [if IE]>' +
'<param name="movie" value="../../js/tinymce/plugins/media/moxieplayer.swf" />' +
'<![endif]-->' +
'</object>' +
'</video>' +
'</p>'
);
delete editor.settings.media_filter_html;
});
suite.test('Media script elements', function (editor) {
editor.setContent(
'<script src="http://media1.tinymce.com/123456"></sc' + 'ript>' +
'<script src="http://media2.tinymce.com/123456"></sc' + 'ript>'
);
LegacyUnit.equal(editor.getBody().getElementsByTagName('img')[0].className, 'mce-object mce-object-script');
LegacyUnit.equal(editor.getBody().getElementsByTagName('img')[0].width, 300);
LegacyUnit.equal(editor.getBody().getElementsByTagName('img')[0].height, 150);
LegacyUnit.equal(editor.getBody().getElementsByTagName('img')[1].className, 'mce-object mce-object-script');
LegacyUnit.equal(editor.getBody().getElementsByTagName('img')[1].width, 100);
LegacyUnit.equal(editor.getBody().getElementsByTagName('img')[1].height, 200);
LegacyUnit.equal(editor.getContent(),
'<p>\n' +
'<script src="http://media1.tinymce.com/123456" type="text/javascript"></sc' + 'ript>\n' +
'<script src="http://media2.tinymce.com/123456" type="text/javascript"></sc' + 'ript>\n' +
'</p>'
);
});
suite.test('XSS content', function (editor) {
function testXss(input, expectedOutput) {
editor.setContent(input);
LegacyUnit.equal(editor.getContent(), expectedOutput);
}
testXss('<video><a href="javascript:alert(1);">a</a></video>', '<p><video width="300" height="150"><a>a</a></video></p>');
testXss('<video><img src="x" onload="alert(1)"></video>', '<p><video width="300" height=\"150\"></video></p>');
testXss('<video><img src="x"></video>', '<p><video width="300" height="150"><img src="x" /></video></p>');
testXss('<video><!--[if IE]><img src="x"><![endif]--></video>', '<p><video width="300" height="150"><!-- [if IE]><img src="x"><![endif]--></video></p>');
testXss('<p><p><audio><audio src=x onerror=alert(1)>', '<p><audio></audio></p>');
testXss('<p><html><audio><br /><audio src=x onerror=alert(1)></p>', '');
testXss('<p><audio><img src="javascript:alert(1)"></audio>', '<p><audio><img /></audio></p>');
testXss('<p><audio><img src="x" style="behavior:url(x); width: 1px"></audio>', '<p><audio><img src="x" style="width: 1px;" /></audio></p>');
testXss(
'<p><video><noscript><svg onload="javascript:alert(1)"></svg></noscript></video>',
'<p><video width="300" height="150"></video></p>'
);
testXss(
'<p><video><script><svg onload="javascript:alert(1)"></svg></s' + 'cript></video>',
'<p><video width="300" height="150"></video></p>'
);
testXss(
'<p><audio><noscript><svg onload="javascript:alert(1)"></svg></noscript></audio>',
'<p><audio></audio></p>'
);
testXss(
'<p><audio><script><svg onload="javascript:alert(1)"></svg></s' + 'cript></audio>',
'<p><audio></audio></p>'
);
});
TinyLoader.setup(function (editor, onSuccess, onFailure) {
Pipeline.async({}, suite.toSteps(editor), onSuccess, onFailure);
}, {
plugins: 'media',
toolbar: 'media',
skin_url: '/project/js/tinymce/skins/lightgray',
live_embeds: false,
document_base_url: '/tinymce/tinymce/trunk/tests/',
extended_valid_elements: 'script[src|type]',
media_scripts: [
{ filter: 'http://media1.tinymce.com' },
{ filter: 'http://media2.tinymce.com', width: 100, height: 200 }
]
}, success, failure);
});

View File

@@ -0,0 +1,70 @@
import { GeneralSteps, Pipeline } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyApis, TinyLoader, TinyUi } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/media/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import Utils from '../module/test/Utils';
UnitTest.asynctest('browser.core.DataAttributeTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
Plugin();
Theme();
const sTestEmbedContentFromUrlWithAttribute = function (ui, url, content) {
return GeneralSteps.sequence([
Utils.sOpenDialog(ui),
Utils.sPasteSourceValue(ui, url),
Utils.sAssertEmbedContent(ui, content),
Utils.sSubmitAndReopen(ui),
Utils.sAssertSourceValue(ui, url),
Utils.sCloseDialog(ui)
]);
};
const sTestEmbedContentFromUrl2 = function (ui, url, url2, content, content2) {
return GeneralSteps.sequence([
Utils.sOpenDialog(ui),
Utils.sPasteSourceValue(ui, url),
Utils.sAssertEmbedContent(ui, content),
Utils.sSubmitAndReopen(ui),
Utils.sAssertSourceValue(ui, url),
Utils.sPasteSourceValue(ui, url2),
Utils.sAssertEmbedContent(ui, content2),
Utils.sCloseDialog(ui)
]);
};
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const ui = TinyUi(editor);
const api = TinyApis(editor);
Pipeline.async({}, [
sTestEmbedContentFromUrlWithAttribute(ui,
'a',
'<div data-ephox-embed-iri="a" style="max-width: 300px; max-height: 150px"></div>'
),
sTestEmbedContentFromUrl2(ui, 'a', 'b',
'<div data-ephox-embed-iri="a" style="max-width: 300px; max-height: 150px"></div>',
'<div data-ephox-embed-iri="b" style="max-width: 300px; max-height: 150px"></div>'
),
Utils.sTestEmbedContentFromUrl(ui,
'a',
'<div data-ephox-embed-iri="a" style="max-width: 300px; max-height: 150px"></div>'
),
Utils.sAssertSizeRecalcConstrained(ui),
Utils.sAssertSizeRecalcUnconstrained(ui),
api.sSetContent(''),
Utils.sAssertSizeRecalcConstrainedReopen(ui)
], onSuccess, onFailure);
}, {
plugins: ['media'],
toolbar: 'media',
media_url_resolver (data, resolve) {
resolve({ html: '<div data-ephox-embed-iri="' + data.url + '" style="max-width: 300px; max-height: 150px"></div>' });
},
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,79 @@
import { ApproxStructure, Assertions, Pipeline, Waiter } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyLoader } from '@ephox/mcagar';
import { Element } from '@ephox/sugar';
import DataToHtml from 'tinymce/plugins/media/core/DataToHtml';
import Plugin from 'tinymce/plugins/media/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
UnitTest.asynctest('browser.core.DataToHtmlTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
Plugin();
Theme();
const sTestDataToHtml = function (editor, data, expected) {
const actual = Element.fromHtml(DataToHtml.dataToHtml(editor, data));
return Waiter.sTryUntil('Wait for structure check',
Assertions.sAssertStructure('Assert equal', expected, actual),
10, 500);
};
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const videoStruct = ApproxStructure.build(function (s, str/*, arr*/) {
return s.element('video', {
children: [
s.text(str.is('\n')),
s.element('source', {
attrs: {
src: str.is('a')
}
}),
s.text(str.is('\n'))
],
attrs: {
height: str.is('150'),
width: str.is('300')
}
});
});
const iframeStruct = ApproxStructure.build(function (s, str/*, arr*/) {
return s.element('iframe', {
attrs: {
height: str.is('150'),
width: str.is('300')
}
});
});
Pipeline.async({}, [
sTestDataToHtml(editor,
{
'type': 'video',
'source1': 'a',
'source2': '',
'poster': '',
'data-ephox-embed': 'a'
},
videoStruct),
sTestDataToHtml(editor,
{
'type': 'iframe',
'source1': 'a',
'source2': '',
'poster': '',
'data-ephox-embed': 'a'
},
iframeStruct)
], onSuccess, onFailure);
}, {
plugins: ['media'],
toolbar: 'media',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,37 @@
import { Pipeline, UiFinder, Waiter } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyDom, TinyLoader, TinyUi } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/media/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import Utils from '../module/test/Utils';
import { document } from '@ephox/dom-globals';
UnitTest.asynctest('browser.tinymce.plugins.media.DimensionsControlTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
Plugin();
Theme();
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const ui = TinyUi(editor);
Pipeline.async({}, [
Utils.sOpenDialog(ui),
ui.sClickOnUi('Click on close button', 'button:contains("Ok")'),
Waiter.sTryUntil(
'Wait for dialog to close',
UiFinder.sNotExists(TinyDom.fromDom(document.body), 'div[aria-label="Insert/edit media"][role="dialog"]'),
50, 5000
)
], onSuccess, onFailure);
}, {
plugins: ['media'],
toolbar: 'media',
media_dimensions: false,
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,68 @@
import { ApproxStructure, Pipeline, Waiter } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyApis, TinyLoader, TinyUi } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/media/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import Utils from '../module/test/Utils';
UnitTest.asynctest('browser.tinymce.plugins.media.DimensionsFalseEmbedTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
Plugin();
Theme();
const struct = ApproxStructure.build(function (s, str) {
return s.element('body', {
children: [
s.element('p', {
children: [
s.element('span', {
attrs: {
'data-mce-object': str.is('iframe')
},
children: [
s.element('iframe', {
attrs: {
width: str.is('200'),
height: str.is('100')
}
}),
s.anything()
]
}),
s.anything()
]
})
]
});
});
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyUi = TinyUi(editor);
const tinyApis = TinyApis(editor);
Pipeline.async({}, [
Utils.sOpenDialog(tinyUi),
Utils.sPasteTextareaValue(
tinyUi,
'<iframe width="200" height="100" src="a" ' +
' frameborder="0" allowfullscreen></iframe>'
),
Utils.sSubmitDialog(tinyUi),
Waiter.sTryUntil(
'content was not expected structure',
tinyApis.sAssertContentStructure(struct),
100,
4000
)
], onSuccess, onFailure);
}, {
plugins: ['media'],
toolbar: 'media',
media_dimensions: false,
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,76 @@
import { ApproxStructure, Assertions, Pipeline, Step, Waiter } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyApis, TinyLoader, TinyUi } from '@ephox/mcagar';
import { Element } from '@ephox/sugar';
import Plugin from 'tinymce/plugins/media/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import Utils from '../module/test/Utils';
UnitTest.asynctest('browser.core.EphoxEmbedTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
Plugin();
Theme();
const ephoxEmbedStructure = ApproxStructure.build(function (s, str/*, arr*/) {
return s.element('p', {
children: [
s.element('div', {
children: [
s.element('iframe', {
attrs: {
src: str.is('about:blank')
}
})
],
attrs: {
'data-ephox-embed-iri': str.is('embed-iri'),
'contenteditable': str.is('false')
}
})
]
});
});
const sAssertDivStructure = function (editor, expected) {
return Step.sync(function () {
const div = editor.dom.select('div')[0];
const actual = div ? Element.fromHtml(div.outerHTML) : Element.fromHtml('');
return Assertions.sAssertStructure('Should be the same structure', expected, actual);
});
};
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const ui = TinyUi(editor);
const apis = TinyApis(editor);
Pipeline.async({}, [
apis.sFocus,
apis.sSetContent('<div contenteditable="false" data-ephox-embed-iri="embed-iri"><iframe src="about:blank"></iframe></div>'),
sAssertDivStructure(editor, ephoxEmbedStructure),
apis.sSelect('div', []),
Utils.sOpenDialog(ui),
Utils.sAssertSourceValue(ui, 'embed-iri'),
Utils.sAssertEmbedContent(ui,
'<div contenteditable="false" data-ephox-embed-iri="embed-iri">' +
'<iframe src="about:blank"></iframe>' +
'</div>'
),
Utils.sSubmitDialog(ui),
Waiter.sTryUntil('wait for div struture', sAssertDivStructure(editor, ephoxEmbedStructure), 100, 3000)
], onSuccess, onFailure);
}, {
plugins: 'media',
toolbar: 'media',
media_url_resolver (data, resolve) {
resolve({
html: '<video width="300" height="150" ' +
'controls="controls">\n<source src="' + data.url + '" />\n</video>'
});
},
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,101 @@
import { Pipeline, UiFinder, Chain, Assertions, ApproxStructure, Logger, GeneralSteps } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyApis, TinyLoader } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/media/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import { Element } from '@ephox/sugar';
UnitTest.asynctest('browser.core.IframeNodeTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
Plugin();
Theme();
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const apis = TinyApis(editor);
Pipeline.async({}, [
Logger.t('iframe with class and style, no width & height attribs', GeneralSteps.sequence([
apis.sSetContent(
'<iframe class="test-class" style="height: 250px; width: 500px;" src="about:blank"></iframe>'
),
Chain.asStep(Element.fromDom(editor.getBody()), [
UiFinder.cFindIn('iframe'),
Chain.op((input) =>
Assertions.assertStructure('should have all attributes', ApproxStructure.build((s, str, arr) => {
return s.element('iframe', {
classes: [ arr.has('test-class') ],
attrs: {
width: str.none('should not have width'),
height: str.none('should not have height')
},
styles: {
width: str.is('500px'),
height: str.is('250px')
},
});
}), input)
)
])
])),
Logger.t('iframe with class, style and width & height attribs', GeneralSteps.sequence([
apis.sSetContent(
'<iframe class="test-class" style="height: 250px; width: 500px;" width="300" height="150" src="about:blank"></iframe>'
),
Chain.asStep(Element.fromDom(editor.getBody()), [
UiFinder.cFindIn('iframe'),
Chain.op((input) =>
Assertions.assertStructure('should have all attributes', ApproxStructure.build((s, str, arr) => {
return s.element('iframe', {
classes: [ arr.has('test-class') ],
attrs: {
width: str.is('300'),
height: str.is('150')
},
styles: {
width: str.is('500px'),
height: str.is('250px')
},
});
}), input)
)
])
])),
Logger.t('iframe with width & height attribs', GeneralSteps.sequence([
apis.sSetContent(
'<iframe width="300" height="150" src="about:blank"></iframe>'
),
Chain.asStep(Element.fromDom(editor.getBody()), [
UiFinder.cFindIn('iframe'),
Chain.op((input) =>
Assertions.assertStructure('should have all attributes', ApproxStructure.build((s, str, arr) => {
return s.element('iframe', {
attrs: {
width: str.is('300'),
height: str.is('150')
},
styles: {
width: str.none('should not have width style'),
height: str.none('should not have height style')
},
});
}), input)
)
])
])),
], onSuccess, onFailure);
}, {
plugins: ['media'],
toolbar: 'media',
media_url_resolver (data, resolve) {
setTimeout(function () {
resolve({
html: '<span id="fake">' + data.url + '</span>'
});
}, 500);
},
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,87 @@
import {
Assertions, Chain, GeneralSteps, Guard, Logger, Mouse, Pipeline, UiControls, UiFinder
} from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyApis, TinyDom, TinyLoader, TinyUi } from '@ephox/mcagar';
import { Html } from '@ephox/sugar';
import MediaPlugin from 'tinymce/plugins/media/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import Utils from '../module/test/Utils';
import { document } from '@ephox/dom-globals';
UnitTest.asynctest('browser.tinymce.plugins.media.IsCachedResponseTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
ModernTheme();
MediaPlugin();
const cAssertEmbedValue = function (expected) {
return Chain.control(
Chain.fromChains([
UiFinder.cFindIn('label:contains("Paste your embed code below:")'),
Chain.mapper(function (elm) {
return TinyDom.fromDom(document.getElementById(elm.dom().htmlFor));
}),
UiControls.cGetValue,
Assertions.cAssertHtml('has expected html', expected)
]),
Guard.tryUntil('did not get correct html', 10, 3000)
);
};
const sWaitForAndAssertNotification = function (expected) {
return Chain.asStep(TinyDom.fromDom(document.body), [
UiFinder.cWaitFor('Could not find notification', 'div.mce-notification-inner'),
Chain.mapper(Html.get),
Assertions.cAssertHtml('Plugin list html does not match', expected)
]);
};
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyUi = TinyUi(editor);
const tinyApis = TinyApis(editor);
Pipeline.async({}, [
tinyApis.sFocus,
Logger.t('test cached response', GeneralSteps.sequence([
tinyUi.sClickOnToolbar('click media button', 'div[aria-label="Insert/edit media"] > button'),
Chain.asStep({}, [
Chain.fromParent(
tinyUi.cWaitForPopup('wait for media dialog', 'div[role="dialog"]'), [
Chain.fromChains([
Utils.cSetSourceInput(tinyUi, 'test'),
Utils.cFakeEvent('paste')
]),
Chain.fromChains([
cAssertEmbedValue('<div>x</div>')
]),
Chain.fromChains([
Utils.cSetSourceInput(tinyUi, 'XXX')
]),
Chain.fromChains([
UiFinder.cFindIn('button:contains("Ok")'),
Mouse.cClick
])
])
]),
sWaitForAndAssertNotification('Media embed handler threw unknown error.'),
tinyApis.sAssertContent('')
]))
], onSuccess, onFailure);
}, {
plugins: 'media',
toolbar: 'media',
skin_url: '/project/js/tinymce/skins/lightgray',
media_url_resolver (data, resolve, reject) {
if (data.url === 'test') {
resolve({
html: '<div>x</div>' });
} else {
reject('error');
}
}
}, success, failure);
});

View File

@@ -0,0 +1,48 @@
import { Pipeline } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyApis, TinyLoader, TinyUi } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/media/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import Utils from '../module/test/Utils';
UnitTest.asynctest('browser.core.MediaEmbedTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
Plugin();
Theme();
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const ui = TinyUi(editor);
const api = TinyApis(editor);
Pipeline.async({}, [
Utils.sTestEmbedContentFromUrl(ui,
'https://www.youtube.com/watch?v=b3XFjWInBog',
'<video width="300" height="150" controls="controls">\n' +
'<source src="https://www.youtube.com/watch?v=b3XFjWInBog" />\n</video>'
),
Utils.sTestEmbedContentFromUrl(ui,
'https://www.google.com',
'<video width="300" height="150" controls="controls">\n' +
'<source src="https://www.google.com" />\n</video>'
),
Utils.sAssertSizeRecalcConstrained(ui),
Utils.sAssertSizeRecalcUnconstrained(ui),
api.sSetContent(''),
Utils.sAssertSizeRecalcConstrainedReopen(ui)
], onSuccess, onFailure);
}, {
plugins: ['media'],
toolbar: 'media',
media_url_resolver (data, resolve) {
resolve({
html: '<video width="300" height="150" ' +
'controls="controls">\n<source src="' + data.url + '" />\n</video>'
});
},
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,72 @@
import { Pipeline, Chain, Logger, UiFinder, RawAssertions } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { UiChains, Editor } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/media/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import { Body, Element } from '@ephox/sugar';
const cNotExists = (selector) => {
return Chain.op((container: Element) => {
UiFinder.findIn(container, selector).fold(
() => RawAssertions.assertEq('should not find anything', true, true),
() => RawAssertions.assertEq('Expected ' + selector + ' not to exist.', true, false)
);
});
};
const cExists = (selector) => {
return Chain.op((container: Element) => {
UiFinder.findIn(container, selector).fold(
() => RawAssertions.assertEq('Expected ' + selector + ' to exist.', true, false),
() => RawAssertions.assertEq('found element', true, true)
);
});
};
UnitTest.asynctest('browser.tinymce.plugins.media.NoAdvancedTabTest', (success, failure) => {
Plugin();
Theme();
Pipeline.async({}, [
Logger.t('if alt source and poster set to false, do not show advance tab', Chain.asStep({}, [
Chain.fromParent(
Editor.cFromSettings({
plugins: ['media'],
toolbar: 'media',
media_alt_source: false,
media_poster: false,
skin_url: '/project/js/tinymce/skins/lightgray'
}),
[
Chain.fromChains([
UiChains.cClickOnToolbar('click button', 'div[aria-label="Insert/edit media"]'),
Chain.inject(Body.body()),
UiFinder.cWaitForVisible('wait for popup', 'div.mce-floatpanel[aria-label="Insert/edit media"]'),
cNotExists('div.mce-tab:contains("Advanced")')
]),
Editor.cRemove
]
)
])),
Logger.t('if alt source and poster not set to false, show advance tab', Chain.asStep({}, [
Chain.fromParent(
Editor.cFromSettings({
plugins: ['media'],
toolbar: 'media',
skin_url: '/project/js/tinymce/skins/lightgray'
}),
[
Chain.fromChains([
UiChains.cClickOnToolbar('click button', 'div[aria-label="Insert/edit media"]'),
Chain.inject(Body.body()),
UiFinder.cWaitForVisible('wait for popup', 'div.mce-floatpanel[aria-label="Insert/edit media"]'),
cExists('div.mce-tab:contains("Advanced")')
]),
Editor.cRemove
]
)
]))
], () => success(), failure);
});

View File

@@ -0,0 +1,141 @@
import { ApproxStructure, GeneralSteps, Pipeline, Waiter } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyApis, TinyLoader, TinyUi } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/media/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import Utils from '../module/test/Utils';
UnitTest.asynctest('browser.core.SubmitTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
Plugin();
Theme();
const sTestPlaceholder = function (ui, editor, apis, url, expected, struct) {
return GeneralSteps.sequence([
Utils.sOpenDialog(ui),
Utils.sSetFormItemNoEvent(ui, url),
ui.sClickOnUi('click checkbox', 'div.mce-primary > button'),
Utils.sAssertEditorContent(apis, editor, expected),
Waiter.sTryUntil('Wait for structure check',
apis.sAssertContentStructure(struct),
100, 3000),
apis.sSetContent('')
]);
};
const sTestScriptPlaceholder = function (ui, editor, apis, expected, struct) {
return GeneralSteps.sequence([
apis.sSetContent(
'<script src="http://media1.tinymce.com/123456"></script>' +
'<script src="http://media2.tinymce.com/123456"></script>'),
apis.sNodeChanged,
Waiter.sTryUntil('Wait for structure check',
apis.sAssertContentStructure(struct),
10, 500),
Utils.sAssertEditorContent(apis, editor, expected),
apis.sSetContent('')
]);
};
const placeholderStructure = ApproxStructure.build(function (s) {
return s.element('body', {
children: [
s.element('p', {
children: [
s.element('img', {})
]
}),
s.element('div', {}),
s.element('div', {}),
s.element('div', {}),
s.element('div', {})
]
});
});
const iframeStructure = ApproxStructure.build(function (s) {
return s.element('body', {
children: [
s.element('p', {
children: [
s.element('span', {
children: [
s.element('iframe', {}),
s.element('span', {})
]
}),
s.anything()
]
})
]
});
});
const scriptStruct = ApproxStructure.build(function (s, str, arr) {
return s.element('body', {
children: [
s.element('p', {
children: [
s.element('img', {
classes: [
arr.has('mce-object'),
arr.has('mce-object-script')
],
attrs: {
height: str.is('150'),
width: str.is('300')
}
}),
s.element('img', {
classes: [
arr.has('mce-object'),
arr.has('mce-object-script')
],
attrs: {
height: str.is('200'),
width: str.is('100')
}
})
]
})
]
});
});
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const ui = TinyUi(editor);
const apis = TinyApis(editor);
Pipeline.async({}, [
Utils.sSetSetting(editor.settings, 'media_live_embeds', false),
sTestScriptPlaceholder(ui, editor, apis,
'<p>\n' +
'<script src="http://media1.tinymce.com/123456" type="text/javascript"></sc' + 'ript>\n' +
'<script src="http://media2.tinymce.com/123456" type="text/javascript"></sc' + 'ript>\n' +
'</p>', scriptStruct),
sTestPlaceholder(ui, editor, apis,
'https://www.youtube.com/watch?v=P_205ZY52pY',
'<p><iframe src="//www.youtube.com/embed/P_205ZY52pY" width="560" ' +
'height="314" allowfullscreen="allowfullscreen"></iframe></p>',
placeholderStructure),
Utils.sSetSetting(editor.settings, 'media_live_embeds', true),
sTestPlaceholder(ui, editor, apis,
'https://www.youtube.com/watch?v=P_205ZY52pY',
'<p><iframe src="//www.youtube.com/embed/P_205ZY52pY" width="560" ' +
'height="314" allowfullscreen="allowfullscreen"></iframe></p>',
iframeStructure)
], onSuccess, onFailure);
}, {
plugins: ['media'],
toolbar: 'media',
extended_valid_elements: 'script[src|type]',
media_scripts: [
{ filter: 'http://media1.tinymce.com' },
{ filter: 'http://media2.tinymce.com', width: 100, height: 200 }
],
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,42 @@
import { Pipeline } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyLoader, TinyUi } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/media/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import Utils from '../module/test/Utils';
UnitTest.asynctest('browser.tinymce.plugins.media.PluginTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
Plugin();
Theme();
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const ui = TinyUi(editor);
Pipeline.async({}, [
Utils.sTestEmbedContentFromUrl(ui,
'https://www.youtube.com/watch?v=b3XFjWInBog',
'<iframe src="//www.youtube.com/embed/b3XFjWInBog" width="560" height="314" allowFullscreen="1"></iframe>'
),
Utils.sTestEmbedContentFromUrl(ui,
'https://www.youtube.com/watch?v=cOTbVN2qZBY&t=30s&index=2&list=PLfQW7NTMsSA1dTqk1dMEanFLovB4-C0FT',
'<iframe src="//www.youtube.com/embed/cOTbVN2qZBY?t=30s&amp;index=2&amp;list=PLfQW7NTMsSA1dTqk1dMEanFLovB4-C0FT" width="560" height="314" allowFullscreen="1"></iframe>'
),
Utils.sTestEmbedContentFromUrl(ui,
'https://www.google.com',
'<video width="300" height="150" controls="controls">\n<source src="https://www.google.com" />\n</video>'
),
Utils.sAssertSizeRecalcConstrained(ui),
Utils.sAssertSizeRecalcUnconstrained(ui),
Utils.sAssertSizeRecalcConstrainedReopen(ui)
], onSuccess, onFailure);
}, {
plugins: ['media'],
toolbar: 'media',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,60 @@
import { Pipeline, RawAssertions, Step, Waiter } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyLoader, TinyUi } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/media/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import Utils from '../module/test/Utils';
UnitTest.asynctest('browser.tinymce.plugins.media.ReopenResizeTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
Plugin();
Theme();
const sWaitForResizeHandles = function (editor) {
return Waiter.sTryUntil('Wait for new width value', Step.sync(function () {
RawAssertions.assertEq('Resize handle should exist', editor.dom.select('#mceResizeHandlenw').length, 1);
}), 1, 3000);
};
const sRawAssertImagePresence = function (editor) {
// Hacky way to assert that the placeholder image is in
// the correct place that works cross browser
// assertContentStructure did not work because some
// browsers insert BRs and some do not
return Step.sync(function () {
const actualCount = editor.dom.select('img.mce-object').length;
RawAssertions.assertEq('assert raw content', 1, actualCount);
});
};
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const ui = TinyUi(editor);
Pipeline.async({}, [
Utils.sOpenDialog(ui),
Utils.sPasteSourceValue(ui, 'a'),
Utils.sAssertWidthValue(ui, '300'),
ui.sClickOnUi('Click on close button', 'button:contains("Ok")'),
sWaitForResizeHandles(editor),
Utils.sOpenDialog(ui),
Utils.sChangeWidthValue(ui, '500'),
ui.sClickOnUi('Click on close button', 'button:contains("Ok")'),
sWaitForResizeHandles(editor),
Waiter.sTryUntil(
'Try assert content',
sRawAssertImagePresence(editor),
100, 3000
)
], onSuccess, onFailure);
}, {
plugins: ['media'],
toolbar: 'media',
indent: false,
forced_root_block: false,
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,52 @@
import { GeneralSteps, Pipeline } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyApis, TinyLoader, TinyUi } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/media/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import Utils from '../module/test/Utils';
UnitTest.asynctest('browser.core.SubmitTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
Plugin();
Theme();
const sTestEmbedContentSubmit = function (ui, editor, apis, url, expected) {
return GeneralSteps.sequence([
Utils.sOpenDialog(ui),
Utils.sSetFormItemNoEvent(ui, url),
ui.sClickOnUi('click ok button', 'div.mce-primary > button'),
Utils.sAssertEditorContent(apis, editor, expected)
]);
};
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const ui = TinyUi(editor);
const apis = TinyApis(editor);
Pipeline.async({}, [
sTestEmbedContentSubmit(ui, editor, apis, 'https://www.youtube.com/watch?v=IcgmSRJHu_8',
'<p><span id="fake">https://www.youtube.com/watch?v=IcgmSRJHu_8</span></p>'),
apis.sSetContent(''),
apis.sDeleteSetting('media_url_resolver'),
sTestEmbedContentSubmit(ui, editor, apis, 'https://www.youtube.com/watch?v=IcgmSRJHu_8',
'<p><iframe src="//www.youtube.com/embed/IcgmSRJHu_8" width="560" height="314" ' +
'allowfullscreen="allowfullscreen"></iframe></p>'),
apis.sSetContent('')
], onSuccess, onFailure);
}, {
plugins: ['media'],
toolbar: 'media',
media_url_resolver (data, resolve) {
setTimeout(function () {
resolve({
html: '<span id="fake">' + data.url + '</span>'
});
}, 500);
},
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,280 @@
import { Assertions, Chain, GeneralSteps, Step, UiControls, UiFinder, Waiter } from '@ephox/agar';
import { TinyDom } from '@ephox/mcagar';
import DOMUtils from 'tinymce/core/api/dom/DOMUtils';
import { document } from '@ephox/dom-globals';
import { Element } from '@ephox/sugar';
const sOpenDialog = function (ui) {
return GeneralSteps.sequence([
ui.sClickOnToolbar('Click on media button', 'div[aria-label="Insert/edit media"] > button'),
ui.sWaitForPopup('wait for popup', 'div[role="dialog"]')
]);
};
const cFindInDialog = function (mapper) {
return function (ui, text) {
return Chain.fromChains([
ui.cWaitForPopup('Wait for popup', 'div[role="dialog"]'),
UiFinder.cFindIn('label:contains(' + text + ')'),
Chain.mapper(function (val) {
return TinyDom.fromDom(mapper(val));
})
]);
};
};
const cFindWidthInput = cFindInDialog(function (value) {
return document.getElementById(value.dom().htmlFor).querySelector('input[aria-label="Width"]');
});
const cFindHeightInput = cFindInDialog(function (value) {
return document.getElementById(value.dom().htmlFor).querySelector('input[aria-label="Height"]');
});
const cGetWidthValue = function (ui) {
return Chain.fromChains([
cFindWidthInput(ui, 'Dimensions'),
UiControls.cGetValue
]);
};
const cSetWidthValue = function (ui, value) {
return Chain.fromChains([
cFindWidthInput(ui, 'Dimensions'),
UiControls.cSetValue(value)
]);
};
const cGetHeightValue = function (ui) {
return Chain.fromChains([
cFindHeightInput(ui, 'Dimensions'),
UiControls.cGetValue
]);
};
const cSetHeightValue = function (ui, value) {
return Chain.fromChains([
cFindHeightInput(ui, 'Dimensions'),
UiControls.cSetValue(value)
]);
};
const sAssertWidthValue = function (ui, value) {
return Waiter.sTryUntil('Wait for new width value',
Chain.asStep({}, [
cGetWidthValue(ui),
Assertions.cAssertEq('Assert size value', value)
]), 1, 3000
);
};
const sAssertHeightValue = function (ui, value) {
return Waiter.sTryUntil('Wait for new height value',
Chain.asStep({}, [
cGetHeightValue(ui),
Assertions.cAssertEq('Assert size value', value)
]), 1, 3000
);
};
const sAssertSourceValue = function (ui, value) {
return Waiter.sTryUntil('Wait for source value',
Chain.asStep({}, [
cFindFilepickerInput(ui, 'Source'),
UiControls.cGetValue,
Assertions.cAssertEq('Assert source value', value)
]), 1, 3000
);
};
const sPasteSourceValue = function (ui, value) {
return Chain.asStep({}, [
cFindFilepickerInput(ui, 'Source'),
UiControls.cSetValue(value),
cFakeEvent('paste')
]);
};
const sChangeWidthValue = function (ui, value) {
return Chain.asStep({}, [
cSetWidthValue(ui, value),
cFakeEvent('change')
]);
};
const sChangeHeightValue = function (ui, value) {
return Chain.asStep({}, [
cSetHeightValue(ui, value),
cFakeEvent('change')
]);
};
const sAssertSizeRecalcConstrained = function (ui) {
return GeneralSteps.sequence([
sOpenDialog(ui),
sPasteSourceValue(ui, 'http://test.se'),
sAssertWidthValue(ui, '300'),
sAssertHeightValue(ui, '150'),
sChangeWidthValue(ui, '350'),
sAssertWidthValue(ui, '350'),
sAssertHeightValue(ui, '175'),
sChangeHeightValue(ui, '100'),
sAssertHeightValue(ui, '100'),
sAssertWidthValue(ui, '200'),
sCloseDialog(ui)
]);
};
const sAssertSizeRecalcConstrainedReopen = function (ui) {
return GeneralSteps.sequence([
sOpenDialog(ui),
sPasteSourceValue(ui, 'http://test.se'),
sAssertWidthValue(ui, '300'),
sAssertHeightValue(ui, '150'),
sChangeWidthValue(ui, '350'),
sAssertWidthValue(ui, '350'),
sAssertHeightValue(ui, '175'),
sChangeHeightValue(ui, '100'),
sAssertHeightValue(ui, '100'),
sAssertWidthValue(ui, '200'),
sSubmitAndReopen(ui),
sAssertHeightValue(ui, '100'),
sAssertWidthValue(ui, '200'),
sChangeWidthValue(ui, '350'),
sAssertWidthValue(ui, '350'),
sAssertHeightValue(ui, '175')
]);
};
const sAssertSizeRecalcUnconstrained = function (ui) {
return GeneralSteps.sequence([
sOpenDialog(ui),
sPasteSourceValue(ui, 'http://test.se'),
ui.sClickOnUi('click checkbox', '.mce-checkbox'),
sAssertWidthValue(ui, '300'),
sAssertHeightValue(ui, '150'),
sChangeWidthValue(ui, '350'),
sAssertWidthValue(ui, '350'),
sAssertHeightValue(ui, '150'),
sChangeHeightValue(ui, '100'),
sAssertHeightValue(ui, '100'),
sAssertWidthValue(ui, '350'),
sCloseDialog(ui)
]);
};
const sCloseDialog = function (ui) {
return ui.sClickOnUi('Click cancel button', '.mce-i-remove');
};
const cFakeEvent = function (name) {
return Chain.op(function (elm: Element) {
DOMUtils.DOM.fire(elm.dom(), name);
});
};
const cFindFilepickerInput = cFindInDialog(function (value) {
return document.getElementById(value.dom().htmlFor).querySelector('input');
});
const cFindTextarea = cFindInDialog(function (value) {
return document.getElementById(value.dom().htmlFor);
});
const cSetSourceInput = function (ui, value) {
return Chain.fromChains([
cFindFilepickerInput(ui, 'Source'),
UiControls.cSetValue(value)
]);
};
const cGetTextareaContent = function (ui) {
return Chain.fromChains([
cFindTextarea(ui, 'Paste your embed code below:'),
UiControls.cGetValue
]);
};
const sPasteTextareaValue = function (ui, value) {
return Chain.asStep({}, [
cFindTextarea(ui, 'Paste your embed code below:'),
UiControls.cSetValue(value),
cFakeEvent('paste')
]);
};
const sAssertEmbedContent = function (ui, content) {
return Waiter.sTryUntil('Textarea should have a proper value',
Chain.asStep({}, [
cGetTextareaContent(ui),
Assertions.cAssertEq('Content same as embed', content)
]), 1, 3000
);
};
const sTestEmbedContentFromUrl = function (ui, url, content) {
return GeneralSteps.sequence([
sOpenDialog(ui),
sPasteSourceValue(ui, url),
sAssertEmbedContent(ui, content),
sCloseDialog(ui)
]);
};
const sSetFormItemNoEvent = function (ui, value) {
return Chain.asStep({}, [
cSetSourceInput(ui, value)
]);
};
const sAssertEditorContent = function (apis, editor, expected) {
return Waiter.sTryUntil('Wait for editor value',
Chain.asStep({}, [
apis.cGetContent,
Assertions.cAssertHtml('Assert body content', expected)
]), 10, 3000
);
};
const sSubmitDialog = function (ui) {
return ui.sClickOnUi('Click submit button', 'div.mce-primary > button');
};
const sSubmitAndReopen = function (ui) {
return GeneralSteps.sequence([
sSubmitDialog(ui),
sOpenDialog(ui)
]);
};
const sSetSetting = function (editorSetting, key, value) {
return Step.sync(function () {
editorSetting[key] = value;
});
};
export default {
cSetSourceInput,
cFindTextare: cFindTextarea,
cFakeEvent,
cFindInDialog,
sOpenDialog,
sCloseDialog,
sSubmitDialog,
sTestEmbedContentFromUrl,
sSetFormItemNoEvent,
sAssertEditorContent,
sSetSetting,
sSubmitAndReopen,
sAssertWidthValue,
sAssertHeightValue,
sPasteSourceValue,
sAssertSizeRecalcConstrained,
sAssertSizeRecalcConstrainedReopen,
sAssertSizeRecalcUnconstrained,
sAssertEmbedContent,
sAssertSourceValue,
sChangeWidthValue,
sPasteTextareaValue
};