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,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
};