From 803ad04ab06de9dce7036778ed9ec0a038628779 Mon Sep 17 00:00:00 2001
From: 0x29a ]*>( | |\s|\u00a0|)<\/p>[\r\n]*| | | | x x * text| text|text2 *texttext* | abcabc123 abc 123 text 1CHOPtext 2 text 1 text 2 text 1 text 2 a b | x| ] | | a b a b c x x a text text .
- *
- * @method start
- * @param {String} name Name of the element.
- * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
- * @param {Boolean} empty Optional empty state if the tag should end like bug on IE 8 #6178
- DOMUtils.DOM.setHTML(elm, html);
- }
- };
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/DragHelper.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/DragHelper.js
deleted file mode 100755
index c7c2850b26..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/DragHelper.js
+++ /dev/null
@@ -1,136 +0,0 @@
-/**
- * DragHelper.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * Drag/drop helper class.
- *
- * @example
- * var dragHelper = new tinymce.ui.DragHelper('mydiv', {
- * start: function(evt) {
- * },
- *
- * drag: function(evt) {
- * },
- *
- * end: function(evt) {
- * }
- * });
- *
- * @class tinymce.ui.DragHelper
- */
-define("tinymce/ui/DragHelper", [
- "tinymce/ui/DomUtils"
-], function(DomUtils) {
- "use strict";
-
- function getDocumentSize() {
- var doc = document, documentElement, body, scrollWidth, clientWidth;
- var offsetWidth, scrollHeight, clientHeight, offsetHeight, max = Math.max;
-
- documentElement = doc.documentElement;
- body = doc.body;
-
- scrollWidth = max(documentElement.scrollWidth, body.scrollWidth);
- clientWidth = max(documentElement.clientWidth, body.clientWidth);
- offsetWidth = max(documentElement.offsetWidth, body.offsetWidth);
-
- scrollHeight = max(documentElement.scrollHeight, body.scrollHeight);
- clientHeight = max(documentElement.clientHeight, body.clientHeight);
- offsetHeight = max(documentElement.offsetHeight, body.offsetHeight);
-
- return {
- width: scrollWidth < offsetWidth ? clientWidth : scrollWidth,
- height: scrollHeight < offsetHeight ? clientHeight : scrollHeight
- };
- }
-
- return function(id, settings) {
- var eventOverlayElm, doc = document, downButton, start, stop, drag, startX, startY;
-
- settings = settings || {};
-
- function getHandleElm() {
- return doc.getElementById(settings.handle || id);
- }
-
- start = function(e) {
- var docSize = getDocumentSize(), handleElm, cursor;
-
- e.preventDefault();
- downButton = e.button;
- handleElm = getHandleElm();
- startX = e.screenX;
- startY = e.screenY;
-
- // Grab cursor from handle
- if (window.getComputedStyle) {
- cursor = window.getComputedStyle(handleElm, null).getPropertyValue("cursor");
- } else {
- cursor = handleElm.runtimeStyle.cursor;
- }
-
- // Create event overlay and add it to document
- eventOverlayElm = doc.createElement('div');
- DomUtils.css(eventOverlayElm, {
- position: "absolute",
- top: 0, left: 0,
- width: docSize.width,
- height: docSize.height,
- zIndex: 0x7FFFFFFF,
- opacity: 0.0001,
- background: 'red',
- cursor: cursor
- });
-
- doc.body.appendChild(eventOverlayElm);
-
- // Bind mouse events
- DomUtils.on(doc, 'mousemove', drag);
- DomUtils.on(doc, 'mouseup', stop);
-
- // Begin drag
- settings.start(e);
- };
-
- drag = function(e) {
- if (e.button !== downButton) {
- return stop(e);
- }
-
- e.deltaX = e.screenX - startX;
- e.deltaY = e.screenY - startY;
-
- e.preventDefault();
- settings.drag(e);
- };
-
- stop = function(e) {
- DomUtils.off(doc, 'mousemove', drag);
- DomUtils.off(doc, 'mouseup', stop);
-
- eventOverlayElm.parentNode.removeChild(eventOverlayElm);
-
- if (settings.stop) {
- settings.stop(e);
- }
- };
-
- /**
- * Destroys the drag/drop helper instance.
- *
- * @method destroy
- */
- this.destroy = function() {
- DomUtils.off(getHandleElm());
- };
-
- DomUtils.on(getHandleElm(), 'mousedown', start);
- };
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/ElementPath.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/ElementPath.js
deleted file mode 100755
index 5b9d7fbcec..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/ElementPath.js
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * ElementPath.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This control creates an path for the current selections parent elements in TinyMCE.
- *
- * @class tinymce.ui.ElementPath
- * @extends tinymce.ui.Path
- */
-define("tinymce/ui/ElementPath", [
- "tinymce/ui/Path",
- "tinymce/EditorManager"
-], function(Path, EditorManager) {
- return Path.extend({
- /**
- * Post render method. Called after the control has been rendered to the target.
- *
- * @method postRender
- * @return {tinymce.ui.ElementPath} Current combobox instance.
- */
- postRender: function() {
- var self = this, editor = EditorManager.activeEditor;
-
- function isHidden(elm) {
- if (elm.nodeType === 1) {
- if (elm.nodeName == "BR" || !!elm.getAttribute('data-mce-bogus')) {
- return true;
- }
-
- if (elm.getAttribute('data-mce-type') === 'bookmark') {
- return true;
- }
- }
-
- return false;
- }
-
- self.on('select', function(e) {
- var parents = [], node, body = editor.getBody();
-
- editor.focus();
-
- node = editor.selection.getStart();
- while (node && node != body) {
- if (!isHidden(node)) {
- parents.push(node);
- }
-
- node = node.parentNode;
- }
-
- editor.selection.select(parents[parents.length - 1 - e.index]);
- editor.nodeChanged();
- });
-
- editor.on('nodeChange', function(e) {
- var parents = [], selectionParents = e.parents, i = selectionParents.length;
-
- while (i--) {
- if (selectionParents[i].nodeType == 1 && !isHidden(selectionParents[i])) {
- var args = editor.fire('ResolveName', {
- name: selectionParents[i].nodeName.toLowerCase(),
- target: selectionParents[i]
- });
-
- parents.push({name: args.name});
- }
- }
-
- self.data(parents);
- });
-
- return self._super();
- }
- });
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/Factory.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/Factory.js
deleted file mode 100755
index 6e4fc1c513..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/Factory.js
+++ /dev/null
@@ -1,105 +0,0 @@
-/**
- * Factory.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/*global tinymce:true */
-
-/**
- * This class is a factory for control instances. This enables you
- * to create instances of controls without having to require the UI controls directly.
- *
- * It also allow you to override or add new control types.
- *
- * @class tinymce.ui.Factory
- */
-define("tinymce/ui/Factory", [], function() {
- "use strict";
-
- var types = {}, namespaceInit;
-
- return {
- /**
- * Adds a new control instance type to the factory.
- *
- * @method add
- * @param {String} type Type name for example "button".
- * @param {function} typeClass Class type function.
- */
- add: function(type, typeClass) {
- types[type.toLowerCase()] = typeClass;
- },
-
- /**
- * Returns true/false if the specified type exists or not.
- *
- * @method has
- * @param {String} type Type to look for.
- * @return {Boolean} true/false if the control by name exists.
- */
- has: function(type) {
- return !!types[type.toLowerCase()];
- },
-
- /**
- * Creates a new control instance based on the settings provided. The instance created will be
- * based on the specified type property it can also create whole structures of components out of
- * the specified JSON object.
- *
- * @example
- * tinymce.ui.Factory.create({
- * type: 'button',
- * text: 'Hello world!'
- * });
- *
- * @method create
- * @param {Object/String} settings Name/Value object with items used to create the type.
- * @return {tinymce.ui.Control} Control instance based on the specified type.
- */
- create: function(type, settings) {
- var ControlType, name, namespace;
-
- // Build type lookup
- if (!namespaceInit) {
- namespace = tinymce.ui;
-
- for (name in namespace) {
- types[name.toLowerCase()] = namespace[name];
- }
-
- namespaceInit = true;
- }
-
- // If string is specified then use it as the type
- if (typeof(type) == 'string') {
- settings = settings || {};
- settings.type = type;
- } else {
- settings = type;
- type = settings.type;
- }
-
- // Find control type
- type = type.toLowerCase();
- ControlType = types[type];
-
- // #if debug
-
- if (!ControlType) {
- throw new Error("Could not find control by type: " + type);
- }
-
- // #endif
-
- ControlType = new ControlType(settings);
- ControlType.type = type; // Set the type on the instance, this will be used by the Selector engine
-
- return ControlType;
- }
- };
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FieldSet.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FieldSet.js
deleted file mode 100755
index 4142890cb0..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FieldSet.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * FieldSet.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class creates fieldset containers.
- *
- * @-x-less FieldSet.less
- * @class tinymce.ui.FieldSet
- * @extends tinymce.ui.Form
- */
-define("tinymce/ui/FieldSet", [
- "tinymce/ui/Form"
-], function(Form) {
- "use strict";
-
- return Form.extend({
- Defaults: {
- containerCls: 'fieldset',
- layout: 'flex',
- direction: 'column',
- align: 'stretch',
- flex: 1,
- padding: "25 15 5 15",
- labelGap: 30,
- spacing: 10,
- border: 1
- },
-
- /**
- * Renders the control as a HTML string.
- *
- * @method renderHtml
- * @return {String} HTML representing the control.
- */
- renderHtml: function() {
- var self = this, layout = self._layout, prefix = self.classPrefix;
-
- self.preRender();
- layout.preRender(self);
-
- return (
- ' |b | | a [a] bla[ck r]ed bla|ed bla|ed |x |x /gi, '');
+ rep(/<\/p>/gi, '\n');
+ rep(/ |\u00a0/gi, ' ');
+ rep(/"/gi, '"');
+ rep(/</gi, '<');
+ rep(/>/gi, '>');
+ rep(/&/gi, '&');
+ return s;
+ };
+ var bbcode2html = function (s) {
+ s = global$1.trim(s);
+ var rep = function (re, str) {
+ s = s.replace(re, str);
+ };
+ rep(/\n/gi, ' /gi,""),o(/<\/p>/gi,"\n"),o(/ |\u00a0/gi," "),o(/"/gi,'"'),o(/</gi,"<"),o(/>/gi,">"),o(/&/gi,"&"),t}(o.content))})})}();
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.js
index 203a38067a..9d4d8f06b1 100644
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.js
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.js
@@ -1,365 +1,1706 @@
/**
- * plugin.js
+ * 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/
*
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
+ * Version: 5.5.1 (2020-10-01)
*/
+(function () {
+ 'use strict';
-/*global tinymce:true */
+ var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
-tinymce.PluginManager.add('charmap', function(editor) {
- var charmap = [
- ['160', 'no-break space'],
- ['38', 'ampersand'],
- ['34', 'quotation mark'],
- // finance
- ['162', 'cent sign'],
- ['8364', 'euro sign'],
- ['163', 'pound sign'],
- ['165', 'yen sign'],
- // signs
- ['169', 'copyright sign'],
- ['174', 'registered sign'],
- ['8482', 'trade mark sign'],
- ['8240', 'per mille sign'],
- ['181', 'micro sign'],
- ['183', 'middle dot'],
- ['8226', 'bullet'],
- ['8230', 'three dot leader'],
- ['8242', 'minutes / feet'],
- ['8243', 'seconds / inches'],
- ['167', 'section sign'],
- ['182', 'paragraph sign'],
- ['223', 'sharp s / ess-zed'],
- // quotations
- ['8249', 'single left-pointing angle quotation mark'],
- ['8250', 'single right-pointing angle quotation mark'],
- ['171', 'left pointing guillemet'],
- ['187', 'right pointing guillemet'],
- ['8216', 'left single quotation mark'],
- ['8217', 'right single quotation mark'],
- ['8220', 'left double quotation mark'],
- ['8221', 'right double quotation mark'],
- ['8218', 'single low-9 quotation mark'],
- ['8222', 'double low-9 quotation mark'],
- ['60', 'less-than sign'],
- ['62', 'greater-than sign'],
- ['8804', 'less-than or equal to'],
- ['8805', 'greater-than or equal to'],
- ['8211', 'en dash'],
- ['8212', 'em dash'],
- ['175', 'macron'],
- ['8254', 'overline'],
- ['164', 'currency sign'],
- ['166', 'broken bar'],
- ['168', 'diaeresis'],
- ['161', 'inverted exclamation mark'],
- ['191', 'turned question mark'],
- ['710', 'circumflex accent'],
- ['732', 'small tilde'],
- ['176', 'degree sign'],
- ['8722', 'minus sign'],
- ['177', 'plus-minus sign'],
- ['247', 'division sign'],
- ['8260', 'fraction slash'],
- ['215', 'multiplication sign'],
- ['185', 'superscript one'],
- ['178', 'superscript two'],
- ['179', 'superscript three'],
- ['188', 'fraction one quarter'],
- ['189', 'fraction one half'],
- ['190', 'fraction three quarters'],
- // math / logical
- ['402', 'function / florin'],
- ['8747', 'integral'],
- ['8721', 'n-ary sumation'],
- ['8734', 'infinity'],
- ['8730', 'square root'],
- ['8764', 'similar to'],
- ['8773', 'approximately equal to'],
- ['8776', 'almost equal to'],
- ['8800', 'not equal to'],
- ['8801', 'identical to'],
- ['8712', 'element of'],
- ['8713', 'not an element of'],
- ['8715', 'contains as member'],
- ['8719', 'n-ary product'],
- ['8743', 'logical and'],
- ['8744', 'logical or'],
- ['172', 'not sign'],
- ['8745', 'intersection'],
- ['8746', 'union'],
- ['8706', 'partial differential'],
- ['8704', 'for all'],
- ['8707', 'there exists'],
- ['8709', 'diameter'],
- ['8711', 'backward difference'],
- ['8727', 'asterisk operator'],
- ['8733', 'proportional to'],
- ['8736', 'angle'],
- // undefined
- ['180', 'acute accent'],
- ['184', 'cedilla'],
- ['170', 'feminine ordinal indicator'],
- ['186', 'masculine ordinal indicator'],
- ['8224', 'dagger'],
- ['8225', 'double dagger'],
- // alphabetical special chars
- ['192', 'A - grave'],
- ['193', 'A - acute'],
- ['194', 'A - circumflex'],
- ['195', 'A - tilde'],
- ['196', 'A - diaeresis'],
- ['197', 'A - ring above'],
- ['198', 'ligature AE'],
- ['199', 'C - cedilla'],
- ['200', 'E - grave'],
- ['201', 'E - acute'],
- ['202', 'E - circumflex'],
- ['203', 'E - diaeresis'],
- ['204', 'I - grave'],
- ['205', 'I - acute'],
- ['206', 'I - circumflex'],
- ['207', 'I - diaeresis'],
- ['208', 'ETH'],
- ['209', 'N - tilde'],
- ['210', 'O - grave'],
- ['211', 'O - acute'],
- ['212', 'O - circumflex'],
- ['213', 'O - tilde'],
- ['214', 'O - diaeresis'],
- ['216', 'O - slash'],
- ['338', 'ligature OE'],
- ['352', 'S - caron'],
- ['217', 'U - grave'],
- ['218', 'U - acute'],
- ['219', 'U - circumflex'],
- ['220', 'U - diaeresis'],
- ['221', 'Y - acute'],
- ['376', 'Y - diaeresis'],
- ['222', 'THORN'],
- ['224', 'a - grave'],
- ['225', 'a - acute'],
- ['226', 'a - circumflex'],
- ['227', 'a - tilde'],
- ['228', 'a - diaeresis'],
- ['229', 'a - ring above'],
- ['230', 'ligature ae'],
- ['231', 'c - cedilla'],
- ['232', 'e - grave'],
- ['233', 'e - acute'],
- ['234', 'e - circumflex'],
- ['235', 'e - diaeresis'],
- ['236', 'i - grave'],
- ['237', 'i - acute'],
- ['238', 'i - circumflex'],
- ['239', 'i - diaeresis'],
- ['240', 'eth'],
- ['241', 'n - tilde'],
- ['242', 'o - grave'],
- ['243', 'o - acute'],
- ['244', 'o - circumflex'],
- ['245', 'o - tilde'],
- ['246', 'o - diaeresis'],
- ['248', 'o slash'],
- ['339', 'ligature oe'],
- ['353', 's - caron'],
- ['249', 'u - grave'],
- ['250', 'u - acute'],
- ['251', 'u - circumflex'],
- ['252', 'u - diaeresis'],
- ['253', 'y - acute'],
- ['254', 'thorn'],
- ['255', 'y - diaeresis'],
- ['913', 'Alpha'],
- ['914', 'Beta'],
- ['915', 'Gamma'],
- ['916', 'Delta'],
- ['917', 'Epsilon'],
- ['918', 'Zeta'],
- ['919', 'Eta'],
- ['920', 'Theta'],
- ['921', 'Iota'],
- ['922', 'Kappa'],
- ['923', 'Lambda'],
- ['924', 'Mu'],
- ['925', 'Nu'],
- ['926', 'Xi'],
- ['927', 'Omicron'],
- ['928', 'Pi'],
- ['929', 'Rho'],
- ['931', 'Sigma'],
- ['932', 'Tau'],
- ['933', 'Upsilon'],
- ['934', 'Phi'],
- ['935', 'Chi'],
- ['936', 'Psi'],
- ['937', 'Omega'],
- ['945', 'alpha'],
- ['946', 'beta'],
- ['947', 'gamma'],
- ['948', 'delta'],
- ['949', 'epsilon'],
- ['950', 'zeta'],
- ['951', 'eta'],
- ['952', 'theta'],
- ['953', 'iota'],
- ['954', 'kappa'],
- ['955', 'lambda'],
- ['956', 'mu'],
- ['957', 'nu'],
- ['958', 'xi'],
- ['959', 'omicron'],
- ['960', 'pi'],
- ['961', 'rho'],
- ['962', 'final sigma'],
- ['963', 'sigma'],
- ['964', 'tau'],
- ['965', 'upsilon'],
- ['966', 'phi'],
- ['967', 'chi'],
- ['968', 'psi'],
- ['969', 'omega'],
- // symbols
- ['8501', 'alef symbol'],
- ['982', 'pi symbol'],
- ['8476', 'real part symbol'],
- ['978', 'upsilon - hook symbol'],
- ['8472', 'Weierstrass p'],
- ['8465', 'imaginary part'],
- // arrows
- ['8592', 'leftwards arrow'],
- ['8593', 'upwards arrow'],
- ['8594', 'rightwards arrow'],
- ['8595', 'downwards arrow'],
- ['8596', 'left right arrow'],
- ['8629', 'carriage return'],
- ['8656', 'leftwards double arrow'],
- ['8657', 'upwards double arrow'],
- ['8658', 'rightwards double arrow'],
- ['8659', 'downwards double arrow'],
- ['8660', 'left right double arrow'],
- ['8756', 'therefore'],
- ['8834', 'subset of'],
- ['8835', 'superset of'],
- ['8836', 'not a subset of'],
- ['8838', 'subset of or equal to'],
- ['8839', 'superset of or equal to'],
- ['8853', 'circled plus'],
- ['8855', 'circled times'],
- ['8869', 'perpendicular'],
- ['8901', 'dot operator'],
- ['8968', 'left ceiling'],
- ['8969', 'right ceiling'],
- ['8970', 'left floor'],
- ['8971', 'right floor'],
- ['9001', 'left-pointing angle bracket'],
- ['9002', 'right-pointing angle bracket'],
- ['9674', 'lozenge'],
- ['9824', 'black spade suit'],
- ['9827', 'black club suit'],
- ['9829', 'black heart suit'],
- ['9830', 'black diamond suit'],
- ['8194', 'en space'],
- ['8195', 'em space'],
- ['8201', 'thin space'],
- ['8204', 'zero width non-joiner'],
- ['8205', 'zero width joiner'],
- ['8206', 'left-to-right mark'],
- ['8207', 'right-to-left mark'],
- ['173', 'soft hyphen']
- ];
+ var fireInsertCustomChar = function (editor, chr) {
+ return editor.fire('insertCustomChar', { chr: chr });
+ };
- function showDialog() {
- var gridHtml, x, y, win;
+ var insertChar = function (editor, chr) {
+ var evtChr = fireInsertCustomChar(editor, chr).chr;
+ editor.execCommand('mceInsertContent', false, evtChr);
+ };
- function getParentTd(elm) {
- while (elm) {
- if (elm.nodeName == 'TD') {
- return elm;
- }
+ var noop = function () {
+ };
+ var constant = function (value) {
+ return function () {
+ return value;
+ };
+ };
+ var never = constant(false);
+ var always = constant(true);
- elm = elm.parentNode;
- }
- }
+ var none = function () {
+ return NONE;
+ };
+ var NONE = function () {
+ var eq = function (o) {
+ return o.isNone();
+ };
+ var call = function (thunk) {
+ return thunk();
+ };
+ var id = function (n) {
+ return n;
+ };
+ var me = {
+ fold: function (n, _s) {
+ return n();
+ },
+ is: never,
+ isSome: never,
+ isNone: always,
+ getOr: id,
+ getOrThunk: call,
+ getOrDie: function (msg) {
+ throw new Error(msg || 'error: getOrDie called on none.');
+ },
+ getOrNull: constant(null),
+ getOrUndefined: constant(undefined),
+ or: id,
+ orThunk: call,
+ map: none,
+ each: noop,
+ bind: none,
+ exists: never,
+ forall: always,
+ filter: none,
+ equals: eq,
+ equals_: eq,
+ toArray: function () {
+ return [];
+ },
+ toString: constant('none()')
+ };
+ return me;
+ }();
+ var some = function (a) {
+ var constant_a = constant(a);
+ var self = function () {
+ return me;
+ };
+ var bind = function (f) {
+ return f(a);
+ };
+ var me = {
+ fold: function (n, s) {
+ return s(a);
+ },
+ is: function (v) {
+ return a === v;
+ },
+ isSome: always,
+ isNone: never,
+ getOr: constant_a,
+ getOrThunk: constant_a,
+ getOrDie: constant_a,
+ getOrNull: constant_a,
+ getOrUndefined: constant_a,
+ or: self,
+ orThunk: self,
+ map: function (f) {
+ return some(f(a));
+ },
+ each: function (f) {
+ f(a);
+ },
+ bind: bind,
+ exists: bind,
+ forall: bind,
+ filter: function (f) {
+ return f(a) ? me : NONE;
+ },
+ toArray: function () {
+ return [a];
+ },
+ toString: function () {
+ return 'some(' + a + ')';
+ },
+ equals: function (o) {
+ return o.is(a);
+ },
+ equals_: function (o, elementEq) {
+ return o.fold(never, function (b) {
+ return elementEq(a, b);
+ });
+ }
+ };
+ return me;
+ };
+ var from = function (value) {
+ return value === null || value === undefined ? NONE : some(value);
+ };
+ var Optional = {
+ some: some,
+ none: none,
+ from: from
+ };
- gridHtml = ' Could not load emoticons The sections of the outer UI of the editor - the menubar, toolbar, sidebar and footer - are all keyboard navigable. As such, there are multiple ways to activate keyboard navigation: Focusing the menubar or toolbar will start keyboard navigation at the first item in the menubar or toolbar, which will be highlighted with a gray background. Focusing the footer will start keyboard navigation at the first item in the element path, which will be highlighted with an underline. When keyboard navigation is active, pressing tab will move the focus to the next major section of the UI, where applicable. These sections are: Pressing shift + tab will move backwards through the same sections, except when moving from the footer to the toolbar. Focusing the element path then pressing shift + tab will move focus to the first toolbar group, not the last. Keyboard navigation within UI sections can usually be achieved using the left and right arrow keys. This includes: In all these UI sections, keyboard navigation will cycle within the section. For example, focusing the last button in a toolbar group then pressing right arrow will move focus to the first item in the same toolbar group. To execute a button, navigate the selection to the desired button and hit space or enter. When focusing a menubar button or a toolbar button with a menu, pressing space, enter or down arrow will open the menu. When the menu opens the first item will be selected. To move up or down the menu, press the up or down arrow key respectively. This is the same for submenus, which can also be opened and closed using the left and right arrow keys. To close any active menu, hit the escape key. When a menu is closed the selection will be restored to its previous selection. This also works for closing submenus. To focus an open context toolbar such as the table context toolbar, press Ctrl + F9 (Windows) or ⌃F9 (MacOS). Context toolbar navigation is the same as toolbar navigation, and context menu navigation is the same as standard menu navigation. There are two types of dialog UIs in TinyMCE: tabbed dialogs and non-tabbed dialogs. When a non-tabbed dialog is opened, the first interactive component in the dialog will be focused. Users can navigate between interactive components by pressing tab. This includes any footer buttons. Navigation will cycle back to the first dialog component if tab is pressed while focusing the last component in the dialog. Pressing shift + tab will navigate backwards. When a tabbed dialog is opened, the first button in the tab menu is focused. Pressing tab will navigate to the first interactive component in that tab, and will cycle through the tab\u2019s components, the footer buttons, then back to the tab button. To switch to another tab, focus the tab button for the current tab, then use the arrow keys to cycle through the tab buttons. ' + global$2.translate('Premium plugins:') + ' ' + global$2.translate([
+ 'Plugins installed ({0}):',
+ count
+ ]) + ' ' + global$2.translate([
+ 'You are using {0}',
+ changeLogLink
+ ]) + ' "+A.translate(["Plugins installed ({0}):",r])+" '+A.translate("Premium plugins:")+" The sections of the outer UI of the editor - the menubar, toolbar, sidebar and footer - are all keyboard navigable. As such, there are multiple ways to activate keyboard navigation: Focusing the menubar or toolbar will start keyboard navigation at the first item in the menubar or toolbar, which will be highlighted with a gray background. Focusing the footer will start keyboard navigation at the first item in the element path, which will be highlighted with an underline. When keyboard navigation is active, pressing tab will move the focus to the next major section of the UI, where applicable. These sections are: Pressing shift + tab will move backwards through the same sections, except when moving from the footer to the toolbar. Focusing the element path then pressing shift + tab will move focus to the first toolbar group, not the last. Keyboard navigation within UI sections can usually be achieved using the left and right arrow keys. This includes: In all these UI sections, keyboard navigation will cycle within the section. For example, focusing the last button in a toolbar group then pressing right arrow will move focus to the first item in the same toolbar group. To execute a button, navigate the selection to the desired button and hit space or enter. When focusing a menubar button or a toolbar button with a menu, pressing space, enter or down arrow will open the menu. When the menu opens the first item will be selected. To move up or down the menu, press the up or down arrow key respectively. This is the same for submenus, which can also be opened and closed using the left and right arrow keys. To close any active menu, hit the escape key. When a menu is closed the selection will be restored to its previous selection. This also works for closing submenus. To focus an open context toolbar such as the table context toolbar, press Ctrl + F9 (Windows) or ⌃F9 (MacOS). Context toolbar navigation is the same as toolbar navigation, and context menu navigation is the same as standard menu navigation. There are two types of dialog UIs in TinyMCE: tabbed dialogs and non-tabbed dialogs. When a non-tabbed dialog is opened, the first interactive component in the dialog will be focused. Users can navigate between interactive components by pressing tab. This includes any footer buttons. Navigation will cycle back to the first dialog component if tab is pressed while focusing the last component in the dialog. Pressing shift + tab will navigate backwards. When a tabbed dialog is opened, the first button in the tab menu is focused. Pressing tab will navigate to the first interactive component in that tab, and will cycle through the tab\u2019s components, the footer buttons, then back to the tab button. To switch to another tab, focus the tab button for the current tab, then use the arrow keys to cycle through the tab buttons. "+A.translate(["You are using {0}",i])+" ||
- var forcedRootBlockName = editor.settings.forced_root_block;
- var forcedRootBlockStartHtml;
- if (forcedRootBlockName) {
- forcedRootBlockStartHtml = editor.dom.createHTML(forcedRootBlockName, editor.settings.forced_root_block_attrs);
- forcedRootBlockStartHtml = forcedRootBlockStartHtml.substr(0, forcedRootBlockStartHtml.length - 3) + '>';
- }
-
- if ((startBlock && /^(PRE|DIV)$/.test(startBlock.nodeName)) || !forcedRootBlockName) {
- text = Utils.filter(text, [
- [/\n/g, " )$/, forcedRootBlockStartHtml + '$1'],
- [/\n/g, " ') != -1) {
- text = forcedRootBlockStartHtml + text;
- }
- }
-
- pasteHtml(text);
- }
-
- /**
- * Creates a paste bin element as close as possible to the current caret location and places the focus inside that element
- * so that when the real paste event occurs the contents gets inserted into this element
- * instead of the current editor selection element.
- */
- function createPasteBin() {
- var dom = editor.dom, body = editor.getBody();
- var viewport = editor.dom.getViewPort(editor.getWin()), scrollTop = viewport.y, top = 20;
- var scrollContainer;
-
- lastRng = editor.selection.getRng();
-
- if (editor.inline) {
- scrollContainer = editor.selection.getScrollContainer();
-
- if (scrollContainer) {
- scrollTop = scrollContainer.scrollTop;
- }
- }
-
- // Calculate top cordinate this is needed to avoid scrolling to top of document
- // We want the paste bin to be as close to the caret as possible to avoid scrolling
- if (lastRng.getClientRects) {
- var rects = lastRng.getClientRects();
-
- if (rects.length) {
- // Client rects gets us closes to the actual
- // caret location in for example a wrapped paragraph block
- top = scrollTop + (rects[0].top - dom.getPos(body).y);
- } else {
- top = scrollTop;
-
- // Check if we can find a closer location by checking the range element
- var container = lastRng.startContainer;
- if (container) {
- if (container.nodeType == 3 && container.parentNode != body) {
- container = container.parentNode;
- }
-
- if (container.nodeType == 1) {
- top = dom.getPos(container, scrollContainer || body).y;
- }
- }
- }
- }
-
- // Create a pastebin
- pasteBinElm = dom.add(editor.getBody(), 'div', {
- id: "mcepastebin",
- contentEditable: true,
- "data-mce-bogus": "1",
- style: 'position: absolute; top: ' + top + 'px;' +
- 'width: 10px; height: 10px; overflow: hidden; opacity: 0'
- }, pasteBinDefaultContent);
-
- // Move paste bin out of sight since the controlSelection rect gets displayed otherwise on IE and Gecko
- if (Env.ie || Env.gecko) {
- dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) == 'rtl' ? 0xFFFF : -0xFFFF);
- }
-
- // Prevent focus events from bubbeling fixed FocusManager issues
- dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function(e) {
- e.stopPropagation();
- });
-
- pasteBinElm.focus();
- editor.selection.select(pasteBinElm, true);
- }
-
- /**
- * Removes the paste bin if it exists.
- */
- function removePasteBin() {
- if (pasteBinElm) {
- var pasteBinClone;
-
- // WebKit/Blink might clone the div so
- // lets make sure we remove all clones
- // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
- while ((pasteBinClone = editor.dom.get('mcepastebin'))) {
- editor.dom.remove(pasteBinClone);
- editor.dom.unbind(pasteBinClone);
- }
-
- if (lastRng) {
- editor.selection.setRng(lastRng);
- }
- }
-
- keyboardPastePlainTextState = false;
- pasteBinElm = lastRng = null;
- }
-
- /**
- * Returns the contents of the paste bin as a HTML string.
- *
- * @return {String} Get the contents of the paste bin.
- */
- function getPasteBinHtml() {
- var html = pasteBinDefaultContent, pasteBinClones, i;
-
- // Since WebKit/Chrome might clone the paste bin when pasting
- // for example: a b a b )$/,o+"$1"],[/\n/g," ")&&(e=o+e)),r(e)}function o(){var t=i.dom,n=i.getBody(),r=i.dom.getViewPort(i.getWin()),a=r.y,o=20,s;if(h=i.selection.getRng(),i.inline&&(s=i.selection.getScrollContainer(),s&&(a=s.scrollTop)),h.getClientRects){var c=h.getClientRects();if(c.length)o=a+(c[0].top-t.getPos(n).y);else{o=a;var l=h.startContainer;l&&(3==l.nodeType&&l.parentNode!=n&&(l=l.parentNode),1==l.nodeType&&(o=t.getPos(l,s||n).y))}}v=t.add(i.getBody(),"div",{id:"mcepastebin",contentEditable:!0,"data-mce-bogus":"1",style:"position: absolute; top: "+o+"px;width: 10px; height: 10px; overflow: hidden; opacity: 0"},b),(e.ie||e.gecko)&&t.setStyle(v,"left","rtl"==t.getStyle(n,"direction",!0)?65535:-65535),t.bind(v,"beforedeactivate focusin focusout",function(e){e.stopPropagation()}),v.focus(),i.selection.select(v,!0)}function s(){if(v){for(var e;e=i.dom.get("mcepastebin");)i.dom.remove(e),i.dom.unbind(e);h&&i.selection.setRng(h)}x=!1,v=h=null}function c(){var e=b,t,n;for(t=i.dom.select("div[id=mcepastebin]"),n=t.length;n--;){var r=t[n].innerHTML;e==b&&(e=""),r.length>e.length&&(e=r)}return e}function l(e){var t={};if(e&&e.types){var n=e.getData("Text");n&&n.length>0&&(t["text/plain"]=n);for(var i=0;i texttexttexttexttext ' + htmlEscape(template.value.description) + ' ]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
';
-
- /*eslint no-script-url:0 */
- var domainRelaxUrl = 'javascript:(function(){' +
- 'document.open();document.domain="' + document.domain + '";' +
- 'var ed = window.parent.tinymce.get("' + self.id + '");document.write(ed.iframeHTML);' +
- 'document.close();ed.initContentBody(true);})()';
-
- // Domain relaxing is required since the user has messed around with document.domain
- if (document.domain != location.hostname) {
- url = domainRelaxUrl;
- }
-
- // Create iframe
- // TODO: ACC add the appropriate description on this.
- n = DOM.add(o.iframeContainer, 'iframe', {
- id: self.id + "_ifr",
- src: url || 'javascript:""', // Workaround for HTTPS warning in IE6/7
- frameBorder: '0',
- allowTransparency: "true",
- title: self.editorManager.translate(
- "Rich Text Area. Press ALT-F9 for menu. " +
- "Press ALT-F10 for toolbar. Press ALT-0 for help"
- ),
- style: {
- width: '100%',
- height: h,
- display: 'block' // Important for Gecko to render the iframe correctly
- }
- });
-
- // Try accessing the document this will fail on IE when document.domain is set to the same as location.hostname
- // Then we have to force domain relaxing using the domainRelaxUrl approach very ugly!!
- if (ie) {
- try {
- self.getDoc();
- } catch (e) {
- n.src = url = domainRelaxUrl;
- }
- }
-
- self.contentAreaContainer = o.iframeContainer;
-
- if (o.editorContainer) {
- DOM.get(o.editorContainer).style.display = self.orgDisplay;
- }
-
- DOM.get(self.id).style.display = 'none';
- DOM.setAttrib(self.id, 'aria-hidden', true);
-
- if (!url) {
- self.initContentBody();
- }
-
- elm = n = o = null; // Cleanup
- },
-
- /**
- * This method get called by the init method ones the iframe is loaded.
- * It will fill the iframe with contents, setups DOM and selection objects for the iframe.
- *
- * @method initContentBody
- * @private
- */
- initContentBody: function(skipWrite) {
- var self = this, settings = self.settings, targetElm = DOM.get(self.id), doc = self.getDoc(), body, contentCssText;
-
- // Restore visibility on target element
- if (!settings.inline) {
- self.getElement().style.visibility = self.orgVisibility;
- }
-
- // Setup iframe body
- if (!skipWrite && !settings.content_editable) {
- doc.open();
- doc.write(self.iframeHTML);
- doc.close();
- }
-
- if (settings.content_editable) {
- self.on('remove', function() {
- var bodyEl = this.getBody();
-
- DOM.removeClass(bodyEl, 'mce-content-body');
- DOM.removeClass(bodyEl, 'mce-edit-focus');
- DOM.setAttrib(bodyEl, 'tabIndex', null);
- DOM.setAttrib(bodyEl, 'contentEditable', null);
- });
-
- DOM.addClass(targetElm, 'mce-content-body');
- targetElm.tabIndex = -1;
- self.contentDocument = doc = settings.content_document || document;
- self.contentWindow = settings.content_window || window;
- self.bodyElement = targetElm;
-
- // Prevent leak in IE
- settings.content_document = settings.content_window = null;
-
- // TODO: Fix this
- settings.root_name = targetElm.nodeName.toLowerCase();
- }
-
- // It will not steal focus while setting contentEditable
- body = self.getBody();
- body.disabled = true;
-
- if (!settings.readonly) {
- if (self.inline && DOM.getStyle(body, 'position', true) == 'static') {
- body.style.position = 'relative';
- }
-
- body.contentEditable = self.getParam('content_editable_state', true);
- }
-
- body.disabled = false;
-
- /**
- * Schema instance, enables you to validate elements and it's children.
- *
- * @property schema
- * @type tinymce.html.Schema
- */
- self.schema = new Schema(settings);
-
- /**
- * DOM instance for the editor.
- *
- * @property dom
- * @type tinymce.dom.DOMUtils
- * @example
- * // Adds a class to all paragraphs within the editor
- * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass');
- */
- self.dom = new DOMUtils(doc, {
- keep_values: true,
- url_converter: self.convertURL,
- url_converter_scope: self,
- hex_colors: settings.force_hex_style_colors,
- class_filter: settings.class_filter,
- update_styles: true,
- root_element: settings.content_editable ? self.id : null,
- collect: settings.content_editable,
- schema: self.schema,
- onSetAttrib: function(e) {
- self.fire('SetAttrib', e);
- }
- });
-
- /**
- * HTML parser will be used when contents is inserted into the editor.
- *
- * @property parser
- * @type tinymce.html.DomParser
- */
- self.parser = new DomParser(settings, self.schema);
-
- // Convert src and href into data-mce-src, data-mce-href and data-mce-style
- self.parser.addAttributeFilter('src,href,style', function(nodes, name) {
- var i = nodes.length, node, dom = self.dom, value, internalName;
-
- while (i--) {
- node = nodes[i];
- value = node.attr(name);
- internalName = 'data-mce-' + name;
-
- // Add internal attribute if we need to we don't on a refresh of the document
- if (!node.attributes.map[internalName]) {
- if (name === "style") {
- node.attr(internalName, dom.serializeStyle(dom.parseStyle(value), node.name));
- } else {
- node.attr(internalName, self.convertURL(value, name, node.name));
- }
- }
- }
- });
-
- // Keep scripts from executing
- self.parser.addNodeFilter('script', function(nodes) {
- var i = nodes.length, node;
-
- while (i--) {
- node = nodes[i];
- node.attr('type', 'mce-' + (node.attr('type') || 'text/javascript'));
- }
- });
-
- self.parser.addNodeFilter('#cdata', function(nodes) {
- var i = nodes.length, node;
-
- while (i--) {
- node = nodes[i];
- node.type = 8;
- node.name = '#comment';
- node.value = '[CDATA[' + node.value + ']]';
- }
- });
-
- self.parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function(nodes) {
- var i = nodes.length, node, nonEmptyElements = self.schema.getNonEmptyElements();
-
- while (i--) {
- node = nodes[i];
-
- if (node.isEmpty(nonEmptyElements)) {
- node.empty().append(new Node('br', 1)).shortEnded = true;
- }
- }
- });
-
- /**
- * DOM serializer for the editor. Will be used when contents is extracted from the editor.
- *
- * @property serializer
- * @type tinymce.dom.Serializer
- * @example
- * // Serializes the first paragraph in the editor into a string
- * tinymce.activeEditor.serializer.serialize(tinymce.activeEditor.dom.select('p')[0]);
- */
- self.serializer = new DomSerializer(settings, self);
-
- /**
- * Selection instance for the editor.
- *
- * @property selection
- * @type tinymce.dom.Selection
- * @example
- * // Sets some contents to the current selection in the editor
- * tinymce.activeEditor.selection.setContent('Some contents');
- *
- * // Gets the current selection
- * alert(tinymce.activeEditor.selection.getContent());
- *
- * // Selects the first paragraph found
- * tinymce.activeEditor.selection.select(tinymce.activeEditor.dom.select('p')[0]);
- */
- self.selection = new Selection(self.dom, self.getWin(), self.serializer, self);
-
- /**
- * Formatter instance.
- *
- * @property formatter
- * @type tinymce.Formatter
- */
- self.formatter = new Formatter(self);
-
- /**
- * Undo manager instance, responsible for handling undo levels.
- *
- * @property undoManager
- * @type tinymce.UndoManager
- * @example
- * // Undoes the last modification to the editor
- * tinymce.activeEditor.undoManager.undo();
- */
- self.undoManager = new UndoManager(self);
-
- self.forceBlocks = new ForceBlocks(self);
- self.enterKey = new EnterKey(self);
- self.editorCommands = new EditorCommands(self);
-
- self.fire('PreInit');
-
- if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
- doc.body.spellcheck = false; // Gecko
- DOM.setAttrib(body, "spellcheck", "false");
- }
-
- self.fire('PostRender');
-
- self.quirks = Quirks(self);
-
- if (settings.directionality) {
- body.dir = settings.directionality;
- }
-
- if (settings.nowrap) {
- body.style.whiteSpace = "nowrap";
- }
-
- if (settings.protect) {
- self.on('BeforeSetContent', function(e) {
- each(settings.protect, function(pattern) {
- e.content = e.content.replace(pattern, function(str) {
- return '';
- });
- });
- });
- }
-
- self.on('SetContent', function() {
- self.addVisual(self.getBody());
- });
-
- // Remove empty contents
- if (settings.padd_empty_editor) {
- self.on('PostProcess', function(e) {
- e.content = e.content.replace(/^(
[\r\n]*)$/, '');
- });
- }
-
- self.load({initial: true, format: 'html'});
- self.startContent = self.getContent({format: 'raw'});
-
- /**
- * Is set to true after the editor instance has been initialized
- *
- * @property initialized
- * @type Boolean
- * @example
- * function isEditorInitialized(editor) {
- * return editor && editor.initialized;
- * }
- */
- self.initialized = true;
-
- each(self._pendingNativeEvents, function(name) {
- self.dom.bind(getEventTarget(self, name), name, function(e) {
- self.fire(e.type, e);
- });
- });
-
- self.fire('init');
- self.focus(true);
- self.nodeChanged({initial: true});
- self.execCallback('init_instance_callback', self);
-
- // Add editor specific CSS styles
- if (self.contentStyles.length > 0) {
- contentCssText = '';
-
- each(self.contentStyles, function(style) {
- contentCssText += style + "\r\n";
- });
-
- self.dom.addStyle(contentCssText);
- }
-
- // Load specified content CSS last
- each(self.contentCSS, function(cssUrl) {
- if (!self.loadedCSS[cssUrl]) {
- self.dom.loadCSS(cssUrl);
- self.loadedCSS[cssUrl] = true;
- }
- });
-
- // Handle auto focus
- if (settings.auto_focus) {
- setTimeout(function () {
- var ed = self.editorManager.get(settings.auto_focus);
-
- ed.selection.select(ed.getBody(), 1);
- ed.selection.collapse(1);
- ed.getBody().focus();
- ed.getWin().focus();
- }, 100);
- }
-
- // Clean up references for IE
- targetElm = doc = body = null;
- },
-
- /**
- * Focuses/activates the editor. This will set this editor as the activeEditor in the tinymce collection
- * it will also place DOM focus inside the editor.
- *
- * @method focus
- * @param {Boolean} skip_focus Skip DOM focus. Just set is as the active editor.
- */
- focus: function(skip_focus) {
- var oed, self = this, selection = self.selection, contentEditable = self.settings.content_editable, rng;
- var controlElm, doc = self.getDoc(), body;
-
- if (!skip_focus) {
- // Get selected control element
- rng = selection.getRng();
- if (rng.item) {
- controlElm = rng.item(0);
- }
-
- self._refreshContentEditable();
-
- // Focus the window iframe
- if (!contentEditable) {
- // WebKit needs this call to fire focusin event properly see #5948
- // But Opera pre Blink engine will produce an empty selection so skip Opera
- if (!Env.opera) {
- self.getBody().focus();
- }
-
- self.getWin().focus();
- }
-
- // Focus the body as well since it's contentEditable
- if (isGecko || contentEditable) {
- body = self.getBody();
-
- // Check for setActive since it doesn't scroll to the element
- if (body.setActive && Env.ie < 11) {
- body.setActive();
- } else {
- body.focus();
- }
-
- if (contentEditable) {
- selection.normalize();
- }
- }
-
- // Restore selected control element
- // This is needed when for example an image is selected within a
- // layer a call to focus will then remove the control selection
- if (controlElm && controlElm.ownerDocument == doc) {
- rng = doc.body.createControlRange();
- rng.addElement(controlElm);
- rng.select();
- }
- }
-
- if (self.editorManager.activeEditor != self) {
- if ((oed = self.editorManager.activeEditor)) {
- oed.fire('deactivate', {relatedTarget: self});
- }
-
- self.fire('activate', {relatedTarget: oed});
- }
-
- self.editorManager.activeEditor = self;
- },
-
- /**
- * Executes a legacy callback. This method is useful to call old 2.x option callbacks.
- * There new event model is a better way to add callback so this method might be removed in the future.
- *
- * @method execCallback
- * @param {String} name Name of the callback to execute.
- * @return {Object} Return value passed from callback function.
- */
- execCallback: function(name) {
- var self = this, callback = self.settings[name], scope;
-
- if (!callback) {
- return;
- }
-
- // Look through lookup
- if (self.callbackLookup && (scope = self.callbackLookup[name])) {
- callback = scope.func;
- scope = scope.scope;
- }
-
- if (typeof(callback) === 'string') {
- scope = callback.replace(/\.\w+$/, '');
- scope = scope ? resolve(scope) : 0;
- callback = resolve(callback);
- self.callbackLookup = self.callbackLookup || {};
- self.callbackLookup[name] = {func: callback, scope: scope};
- }
-
- return callback.apply(scope || self, Array.prototype.slice.call(arguments, 1));
- },
-
- /**
- * Translates the specified string by replacing variables with language pack items it will also check if there is
- * a key mathcin the input.
- *
- * @method translate
- * @param {String} text String to translate by the language pack data.
- * @return {String} Translated string.
- */
- translate: function(text) {
- var lang = this.settings.language || 'en', i18n = this.editorManager.i18n;
-
- if (!text) {
- return '';
- }
-
- return i18n.data[lang + '.' + text] || text.replace(/\{\#([^\}]+)\}/g, function(a, b) {
- return i18n.data[lang + '.' + b] || '{#' + b + '}';
- });
- },
-
- /**
- * Returns a language pack item by name/key.
- *
- * @method getLang
- * @param {String} name Name/key to get from the language pack.
- * @param {String} defaultVal Optional default value to retrive.
- */
- getLang: function(name, defaultVal) {
- return (
- this.editorManager.i18n.data[(this.settings.language || 'en') + '.' + name] ||
- (defaultVal !== undefined ? defaultVal : '{#' + name + '}')
- );
- },
-
- /**
- * Returns a configuration parameter by name.
- *
- * @method getParam
- * @param {String} name Configruation parameter to retrive.
- * @param {String} defaultVal Optional default value to return.
- * @param {String} type Optional type parameter.
- * @return {String} Configuration parameter value or default value.
- * @example
- * // Returns a specific config value from the currently active editor
- * var someval = tinymce.activeEditor.getParam('myvalue');
- *
- * // Returns a specific config value from a specific editor instance by id
- * var someval2 = tinymce.get('my_editor').getParam('myvalue');
- */
- getParam: function(name, defaultVal, type) {
- var value = name in this.settings ? this.settings[name] : defaultVal, output;
-
- if (type === 'hash') {
- output = {};
-
- if (typeof(value) === 'string') {
- each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function(value) {
- value = value.split('=');
-
- if (value.length > 1) {
- output[trim(value[0])] = trim(value[1]);
- } else {
- output[trim(value[0])] = trim(value);
- }
- });
- } else {
- output = value;
- }
-
- return output;
- }
-
- return value;
- },
-
- /**
- * Distpaches out a onNodeChange event to all observers. This method should be called when you
- * need to update the UI states or element path etc.
- *
- * @method nodeChanged
- */
- nodeChanged: function() {
- var self = this, selection = self.selection, node, parents, root;
-
- // Fix for bug #1896577 it seems that this can not be fired while the editor is loading
- if (self.initialized && !self.settings.disable_nodechange && !self.settings.readonly) {
- // Get start node
- root = self.getBody();
- node = selection.getStart() || root;
- node = ie && node.ownerDocument != self.getDoc() ? self.getBody() : node; // Fix for IE initial state
-
- // Edge case for
';
- content = self.dom.createHTML(forcedRootBlockName, self.settings.forced_root_block_attrs, content);
- } else if (!ie) {
- // We need to add a BR when forced_root_block is disabled on non IE browsers to place the caret
- content = '
';
- }
-
- body.innerHTML = content;
-
- self.fire('SetContent', args);
- } else {
- // Parse and serialize the html
- if (args.format !== 'raw') {
- content = new Serializer({}, self.schema).serialize(
- self.parser.parse(content, {isRootContent: true})
- );
- }
-
- // Set the new cleaned contents to the editor
- args.content = trim(content);
- self.dom.setHTML(body, args.content);
-
- // Do post processing
- if (!args.no_events) {
- self.fire('SetContent', args);
- }
-
- // Don't normalize selection if the focused element isn't the body in
- // content editable mode since it will steal focus otherwise
- /*if (!self.settings.content_editable || document.activeElement === self.getBody()) {
- self.selection.normalize();
- }*/
- }
-
- return args.content;
- },
-
- /**
- * Gets the content from the editor instance, this will cleanup the content before it gets returned using
- * the different cleanup rules options.
- *
- * @method getContent
- * @param {Object} args Optional content object, this gets passed around through the whole get process.
- * @return {String} Cleaned content string, normally HTML contents.
- * @example
- * // Get the HTML contents of the currently active editor
- * console.debug(tinymce.activeEditor.getContent());
- *
- * // Get the raw contents of the currently active editor
- * tinymce.activeEditor.getContent({format: 'raw'});
- *
- * // Get content of a specific editor:
- * tinymce.get('content id').getContent()
- */
- getContent: function(args) {
- var self = this, content, body = self.getBody();
-
- // Setup args object
- args = args || {};
- args.format = args.format || 'html';
- args.get = true;
- args.getInner = true;
-
- // Do preprocessing
- if (!args.no_events) {
- self.fire('BeforeGetContent', args);
- }
-
- // Get raw contents or by default the cleaned contents
- if (args.format == 'raw') {
- content = body.innerHTML;
- } else if (args.format == 'text') {
- content = body.innerText || body.textContent;
- } else {
- content = self.serializer.serialize(body, args);
- }
-
- // Trim whitespace in beginning/end of HTML
- if (args.format != 'text') {
- args.content = trim(content);
- } else {
- args.content = content;
- }
-
- // Do post processing
- if (!args.no_events) {
- self.fire('GetContent', args);
- }
-
- return args.content;
- },
-
- /**
- * Inserts content at caret position.
- *
- * @method insertContent
- * @param {String} content Content to insert.
- */
- insertContent: function(content) {
- this.execCommand('mceInsertContent', false, content);
- },
-
- /**
- * Returns true/false if the editor is dirty or not. It will get dirty if the user has made modifications to the contents.
- *
- * @method isDirty
- * @return {Boolean} True/false if the editor is dirty or not. It will get dirty if the user has made modifications to the contents.
- * @example
- * if (tinymce.activeEditor.isDirty())
- * alert("You must save your contents.");
- */
- isDirty: function() {
- return !this.isNotDirty;
- },
-
- /**
- * Returns the editors container element. The container element wrappes in
- * all the elements added to the page for the editor. Such as UI, iframe etc.
- *
- * @method getContainer
- * @return {Element} HTML DOM element for the editor container.
- */
- getContainer: function() {
- var self = this;
-
- if (!self.container) {
- self.container = DOM.get(self.editorContainer || self.id + '_parent');
- }
-
- return self.container;
- },
-
- /**
- * Returns the editors content area container element. The this element is the one who
- * holds the iframe or the editable element.
- *
- * @method getContentAreaContainer
- * @return {Element} HTML DOM element for the editor area container.
- */
- getContentAreaContainer: function() {
- return this.contentAreaContainer;
- },
-
- /**
- * Returns the target element/textarea that got replaced with a TinyMCE editor instance.
- *
- * @method getElement
- * @return {Element} HTML DOM element for the replaced element.
- */
- getElement: function() {
- return DOM.get(this.settings.content_element || this.id);
- },
-
- /**
- * Returns the iframes window object.
- *
- * @method getWin
- * @return {Window} Iframe DOM window object.
- */
- getWin: function() {
- var self = this, elm;
-
- if (!self.contentWindow) {
- elm = DOM.get(self.id + "_ifr");
-
- if (elm) {
- self.contentWindow = elm.contentWindow;
- }
- }
-
- return self.contentWindow;
- },
-
- /**
- * Returns the iframes document object.
- *
- * @method getDoc
- * @return {Document} Iframe DOM document object.
- */
- getDoc: function() {
- var self = this, win;
-
- if (!self.contentDocument) {
- win = self.getWin();
-
- if (win) {
- self.contentDocument = win.document;
- }
- }
-
- return self.contentDocument;
- },
-
- /**
- * Returns the iframes body element.
- *
- * @method getBody
- * @return {Element} Iframe body element.
- */
- getBody: function() {
- return this.bodyElement || this.getDoc().body;
- },
-
- /**
- * URL converter function this gets executed each time a user adds an img, a or
- * any other element that has a URL in it. This will be called both by the DOM and HTML
- * manipulation functions.
- *
- * @method convertURL
- * @param {string} url URL to convert.
- * @param {string} name Attribute name src, href etc.
- * @param {string/HTMLElement} elm Tag name or HTML DOM element depending on HTML or DOM insert.
- * @return {string} Converted URL string.
- */
- convertURL: function(url, name, elm) {
- var self = this, settings = self.settings;
-
- // Use callback instead
- if (settings.urlconverter_callback) {
- return self.execCallback('urlconverter_callback', url, elm, true, name);
- }
-
- // Don't convert link href since thats the CSS files that gets loaded into the editor also skip local file URLs
- if (!settings.convert_urls || (elm && elm.nodeName == 'LINK') || url.indexOf('file:') === 0 || url.length === 0) {
- return url;
- }
-
- // Convert to relative
- if (settings.relative_urls) {
- return self.documentBaseURI.toRelative(url);
- }
-
- // Convert to absolute
- url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
-
- return url;
- },
-
- /**
- * Adds visual aid for tables, anchors etc so they can be more easily edited inside the editor.
- *
- * @method addVisual
- * @param {Element} elm Optional root element to loop though to find tables etc that needs the visual aid.
- */
- addVisual: function(elm) {
- var self = this, settings = self.settings, dom = self.dom, cls;
-
- elm = elm || self.getBody();
-
- if (self.hasVisual === undefined) {
- self.hasVisual = settings.visual;
- }
-
- each(dom.select('table,a', elm), function(elm) {
- var value;
-
- switch (elm.nodeName) {
- case 'TABLE':
- cls = settings.visual_table_class || 'mce-item-table';
- value = dom.getAttrib(elm, 'border');
-
- if (!value || value == '0') {
- if (self.hasVisual) {
- dom.addClass(elm, cls);
- } else {
- dom.removeClass(elm, cls);
- }
- }
-
- return;
-
- case 'A':
- if (!dom.getAttrib(elm, 'href', false)) {
- value = dom.getAttrib(elm, 'name') || elm.id;
- cls = settings.visual_anchor_class || 'mce-item-anchor';
-
- if (value) {
- if (self.hasVisual) {
- dom.addClass(elm, cls);
- } else {
- dom.removeClass(elm, cls);
- }
- }
- }
-
- return;
- }
- });
-
- self.fire('VisualAid', {element: elm, hasVisual: self.hasVisual});
- },
-
- /**
- * Removes the editor from the dom and tinymce collection.
- *
- * @method remove
- */
- remove: function() {
- var self = this;
-
- if (!self.removed) {
- self.save();
- self.fire('remove');
- self.off();
- self.removed = 1; // Cancels post remove event execution
-
- // Remove any hidden input
- if (self.hasHiddenInput) {
- DOM.remove(self.getElement().nextSibling);
- }
-
- DOM.setStyle(self.id, 'display', self.orgDisplay);
-
- // Don't clear the window or document if content editable
- // is enabled since other instances might still be present
- if (!self.settings.content_editable) {
- Event.unbind(self.getWin());
- Event.unbind(self.getDoc());
- }
-
- var elm = self.getContainer();
- Event.unbind(self.getBody());
- Event.unbind(elm);
-
- self.editorManager.remove(self);
- DOM.remove(elm);
- self.destroy();
- }
- },
-
- bindNative: function(name) {
- var self = this;
-
- if (self.settings.readonly) {
- return;
- }
-
- if (self.initialized) {
- self.dom.bind(getEventTarget(self, name), name, function(e) {
- self.fire(name, e);
- });
- } else {
- if (!self._pendingNativeEvents) {
- self._pendingNativeEvents = [name];
- } else {
- self._pendingNativeEvents.push(name);
- }
- }
- },
-
- unbindNative: function(name) {
- var self = this;
-
- if (self.initialized) {
- self.dom.unbind(name);
- }
- },
-
- /**
- * Destroys the editor instance by removing all events, element references or other resources
- * that could leak memory. This method will be called automatically when the page is unloaded
- * but you can also call it directly if you know what you are doing.
- *
- * @method destroy
- * @param {Boolean} automatic Optional state if the destroy is an automatic destroy or user called one.
- */
- destroy: function(automatic) {
- var self = this, form;
-
- // One time is enough
- if (self.destroyed) {
- return;
- }
-
- // If user manually calls destroy and not remove
- // Users seems to have logic that calls destroy instead of remove
- if (!automatic && !self.removed) {
- self.remove();
- return;
- }
-
- // We must unbind on Gecko since it would otherwise produce the pesky "attempt
- // to run compile-and-go script on a cleared scope" message
- if (automatic && isGecko) {
- Event.unbind(self.getDoc());
- Event.unbind(self.getWin());
- Event.unbind(self.getBody());
- }
-
- if (!automatic) {
- self.editorManager.off('beforeunload', self._beforeUnload);
-
- // Manual destroy
- if (self.theme && self.theme.destroy) {
- self.theme.destroy();
- }
-
- // Destroy controls, selection and dom
- self.selection.destroy();
- self.dom.destroy();
- }
-
- form = self.formElement;
- if (form) {
- if (form._mceOldSubmit) {
- form.submit = form._mceOldSubmit;
- form._mceOldSubmit = null;
- }
-
- DOM.unbind(form, 'submit reset', self.formEventDelegate);
- }
-
- self.contentAreaContainer = self.formElement = self.container = self.editorContainer = null;
- self.settings.content_element = self.bodyElement = self.contentDocument = self.contentWindow = null;
-
- if (self.selection) {
- self.selection = self.selection.win = self.selection.dom = self.selection.dom.doc = null;
- }
-
- self.destroyed = 1;
- },
-
- // Internal functions
-
- _refreshContentEditable: function() {
- var self = this, body, parent;
-
- // Check if the editor was hidden and the re-initalize contentEditable mode by removing and adding the body again
- if (self._isHidden()) {
- body = self.getBody();
- parent = body.parentNode;
-
- parent.removeChild(body);
- parent.appendChild(body);
-
- body.focus();
- }
- },
-
- _isHidden: function() {
- var sel;
-
- if (!isGecko) {
- return 0;
- }
-
- // Weird, wheres that cursor selection?
- sel = this.selection.getSel();
- return (!sel || !sel.rangeCount || sel.rangeCount === 0);
- }
- };
-
- extend(Editor.prototype, Observable);
-
- return Editor;
-});
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/EditorCommands.js b/common/static/js/vendor/tinymce/js/tinymce/classes/EditorCommands.js
deleted file mode 100755
index 0192017d46..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/EditorCommands.js
+++ /dev/null
@@ -1,721 +0,0 @@
-/**
- * EditorCommands.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class enables you to add custom editor commands and it contains
- * overrides for native browser commands to address various bugs and issues.
- *
- * @class tinymce.EditorCommands
- */
-define("tinymce/EditorCommands", [
- "tinymce/html/Serializer",
- "tinymce/Env",
- "tinymce/util/Tools"
-], function(Serializer, Env, Tools) {
- // Added for compression purposes
- var each = Tools.each, extend = Tools.extend;
- var map = Tools.map, inArray = Tools.inArray, explode = Tools.explode;
- var isGecko = Env.gecko, isIE = Env.ie;
- var TRUE = true, FALSE = false;
-
- return function(editor) {
- var dom = editor.dom,
- selection = editor.selection,
- commands = {state: {}, exec: {}, value: {}},
- settings = editor.settings,
- formatter = editor.formatter,
- bookmark;
-
- /**
- * Executes the specified command.
- *
- * @method execCommand
- * @param {String} command Command to execute.
- * @param {Boolean} ui Optional user interface state.
- * @param {Object} value Optional value for command.
- * @return {Boolean} true/false if the command was found or not.
- */
- function execCommand(command, ui, value) {
- var func;
-
- command = command.toLowerCase();
- if ((func = commands.exec[command])) {
- func(command, ui, value);
- return TRUE;
- }
-
- return FALSE;
- }
-
- /**
- * Queries the current state for a command for example if the current selection is "bold".
- *
- * @method queryCommandState
- * @param {String} command Command to check the state of.
- * @return {Boolean/Number} true/false if the selected contents is bold or not, -1 if it's not found.
- */
- function queryCommandState(command) {
- var func;
-
- command = command.toLowerCase();
- if ((func = commands.state[command])) {
- return func(command);
- }
-
- return -1;
- }
-
- /**
- * Queries the command value for example the current fontsize.
- *
- * @method queryCommandValue
- * @param {String} command Command to check the value of.
- * @return {Object} Command value of false if it's not found.
- */
- function queryCommandValue(command) {
- var func;
-
- command = command.toLowerCase();
- if ((func = commands.value[command])) {
- return func(command);
- }
-
- return FALSE;
- }
-
- /**
- * Adds commands to the command collection.
- *
- * @method addCommands
- * @param {Object} command_list Name/value collection with commands to add, the names can also be comma separated.
- * @param {String} type Optional type to add, defaults to exec. Can be value or state as well.
- */
- function addCommands(command_list, type) {
- type = type || 'exec';
-
- each(command_list, function(callback, command) {
- each(command.toLowerCase().split(','), function(command) {
- commands[type][command] = callback;
- });
- });
- }
-
- // Expose public methods
- extend(this, {
- execCommand: execCommand,
- queryCommandState: queryCommandState,
- queryCommandValue: queryCommandValue,
- addCommands: addCommands
- });
-
- // Private methods
-
- function execNativeCommand(command, ui, value) {
- if (ui === undefined) {
- ui = FALSE;
- }
-
- if (value === undefined) {
- value = null;
- }
-
- return editor.getDoc().execCommand(command, ui, value);
- }
-
- function isFormatMatch(name) {
- return formatter.match(name);
- }
-
- function toggleFormat(name, value) {
- formatter.toggle(name, value ? {value: value} : undefined);
- editor.nodeChanged();
- }
-
- function storeSelection(type) {
- bookmark = selection.getBookmark(type);
- }
-
- function restoreSelection() {
- selection.moveToBookmark(bookmark);
- }
-
- // Add execCommand overrides
- addCommands({
- // Ignore these, added for compatibility
- 'mceResetDesignMode,mceBeginUndoLevel': function() {},
-
- // Add undo manager logic
- 'mceEndUndoLevel,mceAddUndoLevel': function() {
- editor.undoManager.add();
- },
-
- 'Cut,Copy,Paste': function(command) {
- var doc = editor.getDoc(), failed;
-
- // Try executing the native command
- try {
- execNativeCommand(command);
- } catch (ex) {
- // Command failed
- failed = TRUE;
- }
-
- // Present alert message about clipboard access not being available
- if (failed || !doc.queryCommandSupported(command)) {
- var msg = editor.translate(
- "Your browser doesn't support direct access to the clipboard. " +
- "Please use the Ctrl+X/C/V keyboard shortcuts instead."
- );
-
- if (Env.mac) {
- msg = msg.replace(/Ctrl\+/g, '\u2318+');
- }
-
- editor.windowManager.alert(msg);
- }
- },
-
- // Override unlink command
- unlink: function() {
- if (selection.isCollapsed()) {
- var elm = selection.getNode();
- if (elm.tagName == 'A') {
- editor.dom.remove(elm, true);
- }
-
- return;
- }
-
- formatter.remove("link");
- },
-
- // Override justify commands to use the text formatter engine
- 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) {
- var align = command.substring(7);
-
- if (align == 'full') {
- align = 'justify';
- }
-
- // Remove all other alignments first
- each('left,center,right,justify'.split(','), function(name) {
- if (align != name) {
- formatter.remove('align' + name);
- }
- });
-
- toggleFormat('align' + align);
- execCommand('mceRepaint');
- },
-
- // Override list commands to fix WebKit bug
- 'InsertUnorderedList,InsertOrderedList': function(command) {
- var listElm, listParent;
-
- execNativeCommand(command);
-
- // WebKit produces lists within block elements so we need to split them
- // we will replace the native list creation logic to custom logic later on
- // TODO: Remove this when the list creation logic is removed
- listElm = dom.getParent(selection.getNode(), 'ol,ul');
- if (listElm) {
- listParent = listElm.parentNode;
-
- // If list is within a text block then split that block
- if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
- storeSelection();
- dom.split(listParent, listElm);
- restoreSelection();
- }
- }
- },
-
- // Override commands to use the text formatter engine
- 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) {
- toggleFormat(command);
- },
-
- // Override commands to use the text formatter engine
- 'ForeColor,HiliteColor,FontName': function(command, ui, value) {
- toggleFormat(command, value);
- },
-
- FontSize: function(command, ui, value) {
- var fontClasses, fontSizes;
-
- // Convert font size 1-7 to styles
- if (value >= 1 && value <= 7) {
- fontSizes = explode(settings.font_size_style_values);
- fontClasses = explode(settings.font_size_classes);
-
- if (fontClasses) {
- value = fontClasses[value - 1] || value;
- } else {
- value = fontSizes[value - 1] || value;
- }
- }
-
- toggleFormat(command, value);
- },
-
- RemoveFormat: function(command) {
- formatter.remove(command);
- },
-
- mceBlockQuote: function() {
- toggleFormat('blockquote');
- },
-
- FormatBlock: function(command, ui, value) {
- return toggleFormat(value || 'p');
- },
-
- mceCleanup: function() {
- var bookmark = selection.getBookmark();
-
- editor.setContent(editor.getContent({cleanup: TRUE}), {cleanup: TRUE});
-
- selection.moveToBookmark(bookmark);
- },
-
- mceRemoveNode: function(command, ui, value) {
- var node = value || selection.getNode();
-
- // Make sure that the body node isn't removed
- if (node != editor.getBody()) {
- storeSelection();
- editor.dom.remove(node, TRUE);
- restoreSelection();
- }
- },
-
- mceSelectNodeDepth: function(command, ui, value) {
- var counter = 0;
-
- dom.getParent(selection.getNode(), function(node) {
- if (node.nodeType == 1 && counter++ == value) {
- selection.select(node);
- return FALSE;
- }
- }, editor.getBody());
- },
-
- mceSelectNode: function(command, ui, value) {
- selection.select(value);
- },
-
- mceInsertContent: function(command, ui, value) {
- var parser, serializer, parentNode, rootNode, fragment, args;
- var marker, rng, node, node2, bookmarkHtml;
-
- function trimOrPaddLeftRight(html) {
- var rng, container, offset;
-
- rng = selection.getRng(true);
- container = rng.startContainer;
- offset = rng.startOffset;
-
- function hasSiblingText(siblingName) {
- return container[siblingName] && container[siblingName].nodeType == 3;
- }
-
- if (container.nodeType == 3) {
- if (offset > 0) {
- html = html.replace(/^ /, ' ');
- } else if (!hasSiblingText('previousSibling')) {
- html = html.replace(/^ /, ' ');
- }
-
- if (offset < container.length) {
- html = html.replace(/ (
|)$/, ' ');
- } else if (!hasSiblingText('nextSibling')) {
- html = html.replace(/( | )(
|)$/, ' ');
- }
- }
-
- return html;
- }
-
- // Check for whitespace before/after value
- if (/^ | $/.test(value)) {
- value = trimOrPaddLeftRight(value);
- }
-
- // Setup parser and serializer
- parser = editor.parser;
- serializer = new Serializer({}, editor.schema);
- bookmarkHtml = 'ÈB;';
-
- // Run beforeSetContent handlers on the HTML to be inserted
- args = {content: value, format: 'html', selection: true};
- editor.fire('BeforeSetContent', args);
- value = args.content;
-
- // Add caret at end of contents if it's missing
- if (value.indexOf('{$caret}') == -1) {
- value += '{$caret}';
- }
-
- // Replace the caret marker with a span bookmark element
- value = value.replace(/\{\$caret\}/, bookmarkHtml);
-
- // If selection is at | then move it into
');
- },
-
- mceToggleVisualAid: function() {
- editor.hasVisual = !editor.hasVisual;
- editor.addVisual();
- },
-
- mceReplaceContent: function(command, ui, value) {
- editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format: 'text'})));
- },
-
- mceInsertLink: function(command, ui, value) {
- var anchor;
-
- if (typeof(value) == 'string') {
- value = {href: value};
- }
-
- anchor = dom.getParent(selection.getNode(), 'a');
-
- // Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here.
- value.href = value.href.replace(' ', '%20');
-
- // Remove existing links if there could be child links or that the href isn't specified
- if (!anchor || !value.href) {
- formatter.remove('link');
- }
-
- // Apply new link to selection
- if (value.href) {
- formatter.apply('link', value, anchor);
- }
- },
-
- selectAll: function() {
- var root = dom.getRoot(), rng;
-
- if (selection.getRng().setStart) {
- rng = dom.createRng();
- rng.setStart(root, 0);
- rng.setEnd(root, root.childNodes.length);
- selection.setRng(rng);
- } else {
- // IE will render it's own root level block elements and sometimes
- // even put font elements in them when the user starts typing. So we need to
- // move the selection to a more suitable element from this:
- // | to this:
';
- }
-
- return block;
- }
-
- // Returns true/false if the caret is at the start/end of the parent block element
- function isCaretAtStartOrEndOfBlock(start) {
- var walker, node, name;
-
- // Caret is in the middle of a text node like "a|b"
- if (container.nodeType == 3 && (start ? offset > 0 : offset < container.nodeValue.length)) {
- return false;
- }
-
- // If after the last element in block node edge case for #5091
- if (container.parentNode == parentBlock && isAfterLastNodeInContainer && !start) {
- return true;
- }
-
- // If the caret if before the first element in parentBlock
- if (start && container.nodeType == 1 && container == parentBlock.firstChild) {
- return true;
- }
-
- // Caret can be before/after a table
- if (container.nodeName === "TABLE" || (container.previousSibling && container.previousSibling.nodeName == "TABLE")) {
- return (isAfterLastNodeInContainer && !start) || (!isAfterLastNodeInContainer && start);
- }
-
- // Walk the DOM and look for text nodes or non empty elements
- walker = new TreeWalker(container, parentBlock);
-
- // If caret is in beginning or end of a text block then jump to the next/previous node
- if (container.nodeType == 3) {
- if (start && offset === 0) {
- walker.prev();
- } else if (!start && offset == container.nodeValue.length) {
- walker.next();
- }
- }
-
- while ((node = walker.current())) {
- if (node.nodeType === 1) {
- // Ignore bogus elements
- if (!node.getAttribute('data-mce-bogus')) {
- // Keep empty elements like but not trailing br:s like
text|text2 will become this
- // This won't happen if root blocks are disabled or the shiftKey is pressed
- if ((newBlockName && !shiftKey) || (!newBlockName && shiftKey)) {
- container = wrapSelfAndSiblingsInDefaultBlock(container, offset);
- }
-
- // Find parent block and setup empty block paddings
- parentBlock = dom.getParent(container, dom.isBlock);
- containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
-
- // Setup block names
- parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5
- containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5
-
- // Enter inside block contained within a LI then split or insert before/after LI
- if (containerBlockName == 'LI' && !evt.ctrlKey) {
- parentBlock = containerBlock;
- parentBlockName = containerBlockName;
- }
-
- // Handle enter in LI
- if (parentBlockName == 'LI') {
- if (!newBlockName && shiftKey) {
- insertBr();
- return;
- }
-
- // Handle enter inside an empty list item
- if (dom.isEmpty(parentBlock)) {
- handleEmptyListItem();
- return;
- }
- }
-
- // Don't split PRE tags but insert a BR instead easier when writing code samples etc
- if (parentBlockName == 'PRE' && settings.br_in_pre !== false) {
- if (!shiftKey) {
- insertBr();
- return;
- }
- } else {
- // If no root block is configured then insert a BR by default or if the shiftKey is pressed
- if ((!newBlockName && !shiftKey && parentBlockName != 'LI') || (newBlockName && shiftKey)) {
- insertBr();
- return;
- }
- }
-
- // If parent block is root then never insert new blocks
- if (newBlockName && parentBlock === editor.getBody()) {
- return;
- }
-
- // Default block name if it's not configured
- newBlockName = newBlockName || 'P';
-
- // Insert new block before/after the parent block depending on caret location
- if (isCaretAtStartOrEndOfBlock()) {
- // If the caret is at the end of a header we produce a P tag after it similar to Word unless we are in a hgroup
- if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName != 'HGROUP') {
- newBlock = createNewBlock(newBlockName);
- } else {
- newBlock = createNewBlock();
- }
-
- // Split the current container block element if enter is pressed inside an empty inner block element
- if (settings.end_container_on_empty_block && canSplitBlock(containerBlock) && dom.isEmpty(parentBlock)) {
- // Split container block for example a BLOCKQUOTE at the current blockParent location for example a P
- newBlock = dom.split(containerBlock, parentBlock);
- } else {
- dom.insertAfter(newBlock, parentBlock);
- }
-
- moveToCaretPosition(newBlock);
- } else if (isCaretAtStartOrEndOfBlock(true)) {
- // Insert new block before
- newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
- renderBlockOnIE(newBlock);
- moveToCaretPosition(parentBlock);
- } else {
- // Extract after fragment and insert it after the current block
- tmpRng = rng.cloneRange();
- tmpRng.setEndAfter(parentBlock);
- fragment = tmpRng.extractContents();
- trimLeadingLineBreaks(fragment);
- newBlock = fragment.firstChild;
- dom.insertAfter(fragment, parentBlock);
- trimInlineElementsOnLeftSideOfBlock(newBlock);
- addBrToBlockIfNeeded(parentBlock);
- moveToCaretPosition(newBlock);
- }
-
- dom.setAttrib(newBlock, 'id', ''); // Remove ID since it needs to be document unique
-
- // Allow custom handling of new blocks
- editor.fire('NewBlock', { newBlock: newBlock });
-
- undoManager.add();
- }
-
- editor.on('keydown', function(evt) {
- if (evt.keyCode == 13) {
- if (handleEnterKey(evt) !== false) {
- evt.preventDefault();
- }
- }
- });
- };
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/Env.js b/common/static/js/vendor/tinymce/js/tinymce/classes/Env.js
deleted file mode 100755
index 8bf2c6ef84..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/Env.js
+++ /dev/null
@@ -1,135 +0,0 @@
-/**
- * Env.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class contains various environment constants like browser versions etc.
- * Normally you don't want to sniff specific browser versions but sometimes you have
- * to when it's impossible to feature detect. So use this with care.
- *
- * @class tinymce.Env
- * @static
- */
-define("tinymce/Env", [], function() {
- var nav = navigator, userAgent = nav.userAgent;
- var opera, webkit, ie, ie11, gecko, mac, iDevice;
-
- opera = window.opera && window.opera.buildNumber;
- webkit = /WebKit/.test(userAgent);
- ie = !webkit && !opera && (/MSIE/gi).test(userAgent) && (/Explorer/gi).test(nav.appName);
- ie = ie && /MSIE (\w+)\./.exec(userAgent)[1];
- ie11 = userAgent.indexOf('Trident/') != -1 && (userAgent.indexOf('rv:') != -1 || nav.appName.indexOf('Netscape') != -1) ? 11 : false;
- ie = ie || ie11;
- gecko = !webkit && !ie11 && /Gecko/.test(userAgent);
- mac = userAgent.indexOf('Mac') != -1;
- iDevice = /(iPad|iPhone)/.test(userAgent);
-
- // Is a iPad/iPhone and not on iOS5 sniff the WebKit version since older iOS WebKit versions
- // says it has contentEditable support but there is no visible caret.
- var contentEditable = !iDevice || userAgent.match(/AppleWebKit\/(\d*)/)[1] >= 534;
-
- return {
- /**
- * Constant that is true if the browser is Opera.
- *
- * @property opera
- * @type Boolean
- * @final
- */
- opera: opera,
-
- /**
- * Constant that is true if the browser is WebKit (Safari/Chrome).
- *
- * @property webKit
- * @type Boolean
- * @final
- */
- webkit: webkit,
-
- /**
- * Constant that is more than zero if the browser is IE.
- *
- * @property ie
- * @type Boolean
- * @final
- */
- ie: ie,
-
- /**
- * Constant that is true if the browser is Gecko.
- *
- * @property gecko
- * @type Boolean
- * @final
- */
- gecko: gecko,
-
- /**
- * Constant that is true if the os is Mac OS.
- *
- * @property mac
- * @type Boolean
- * @final
- */
- mac: mac,
-
- /**
- * Constant that is true if the os is iOS.
- *
- * @property iOS
- * @type Boolean
- * @final
- */
- iOS: iDevice,
-
- /**
- * Constant that is true if the browser supports editing.
- *
- * @property contentEditable
- * @type Boolean
- * @final
- */
- contentEditable: contentEditable,
-
- /**
- * Transparent image data url.
- *
- * @property transparentSrc
- * @type Boolean
- * @final
- */
- transparentSrc: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
-
- /**
- * Returns true/false if the browser can or can't place the caret after a inline block like an image.
- *
- * @property noCaretAfter
- * @type Boolean
- * @final
- */
- caretAfter: ie != 8,
-
- /**
- * Constant that is true if the browser supports native DOM Ranges. IE 9+.
- *
- * @property range
- * @type Boolean
- */
- range: window.getSelection && "Range" in window,
-
- /**
- * Returns the IE document mode for non IE browsers this will fake IE 10.
- *
- * @property documentMode
- * @type Number
- */
- documentMode: ie ? (document.documentMode || 7) : 10
- };
-});
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/FocusManager.js b/common/static/js/vendor/tinymce/js/tinymce/classes/FocusManager.js
deleted file mode 100755
index dca96befc6..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/FocusManager.js
+++ /dev/null
@@ -1,230 +0,0 @@
-/**
- * FocusManager.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class manages the focus/blur state of the editor. This class is needed since some
- * browsers fire false focus/blur states when the selection is moved to a UI dialog or similar.
- *
- * This class will fire two events focus and blur on the editor instances that got affected.
- * It will also handle the restore of selection when the focus is lost and returned.
- *
- * @class tinymce.FocusManager
- */
-define("tinymce/FocusManager", [
- "tinymce/dom/DOMUtils",
- "tinymce/Env"
-], function(DOMUtils, Env) {
- var selectionChangeHandler, documentFocusInHandler, DOM = DOMUtils.DOM;
-
- /**
- * Constructs a new focus manager instance.
- *
- * @constructor FocusManager
- * @param {tinymce.EditorManager} editorManager Editor manager instance to handle focus for.
- */
- function FocusManager(editorManager) {
- function getActiveElement() {
- try {
- return document.activeElement;
- } catch (ex) {
- // IE sometimes fails to get the activeElement when resizing table
- // TODO: Investigate this
- return document.body;
- }
- }
-
- // We can't store a real range on IE 11 since it gets mutated so we need to use a bookmark object
- // TODO: Move this to a separate range utils class since it's it's logic is present in Selection as well.
- function createBookmark(rng) {
- if (rng && rng.startContainer) {
- return {
- startContainer: rng.startContainer,
- startOffset: rng.startOffset,
- endContainer: rng.endContainer,
- endOffset: rng.endOffset
- };
- }
-
- return rng;
- }
-
- function bookmarkToRng(editor, bookmark) {
- var rng;
-
- if (bookmark.startContainer) {
- rng = editor.getDoc().createRange();
- rng.setStart(bookmark.startContainer, bookmark.startOffset);
- rng.setEnd(bookmark.endContainer, bookmark.endOffset);
- } else {
- rng = bookmark;
- }
-
- return rng;
- }
-
- function isUIElement(elm) {
- return !!DOM.getParent(elm, FocusManager.isEditorUIElement);
- }
-
- function isNodeInBodyOfEditor(node, editor) {
- var body = editor.getBody();
-
- while (node) {
- if (node == body) {
- return true;
- }
-
- node = node.parentNode;
- }
- }
-
- function registerEvents(e) {
- var editor = e.editor;
-
- editor.on('init', function() {
- // Gecko/WebKit has ghost selections in iframes and IE only has one selection per browser tab
- if (editor.inline || Env.ie) {
- // On other browsers take snapshot on nodechange in inline mode since they have Ghost selections for iframes
- editor.on('nodechange keyup', function() {
- var node = document.activeElement;
-
- // IE 11 reports active element as iframe not body of iframe
- if (node && node.id == editor.id + '_ifr') {
- node = editor.getBody();
- }
-
- if (isNodeInBodyOfEditor(node, editor)) {
- editor.lastRng = editor.selection.getRng();
- }
- });
-
- // Handles the issue with WebKit not retaining selection within inline document
- // If the user releases the mouse out side the body since a mouse up event wont occur on the body
- if (Env.webkit && !selectionChangeHandler) {
- selectionChangeHandler = function() {
- var activeEditor = editorManager.activeEditor;
-
- if (activeEditor && activeEditor.selection) {
- var rng = activeEditor.selection.getRng();
-
- // Store when it's non collapsed
- if (rng && !rng.collapsed) {
- editor.lastRng = rng;
- }
- }
- };
-
- DOM.bind(document, 'selectionchange', selectionChangeHandler);
- }
- }
- });
-
- editor.on('setcontent', function() {
- editor.lastRng = null;
- });
-
- // Remove last selection bookmark on mousedown see #6305
- editor.on('mousedown', function() {
- editor.selection.lastFocusBookmark = null;
- });
-
- editor.on('focusin', function() {
- var focusedEditor = editorManager.focusedEditor;
-
- if (editor.selection.lastFocusBookmark) {
- editor.selection.setRng(bookmarkToRng(editor, editor.selection.lastFocusBookmark));
- editor.selection.lastFocusBookmark = null;
- }
-
- if (focusedEditor != editor) {
- if (focusedEditor) {
- focusedEditor.fire('blur', {focusedEditor: editor});
- }
-
- editorManager.activeEditor = editor;
- editorManager.focusedEditor = editor;
- editor.fire('focus', {blurredEditor: focusedEditor});
- editor.focus(true);
- }
-
- editor.lastRng = null;
- });
-
- editor.on('focusout', function() {
- window.setTimeout(function() {
- var focusedEditor = editorManager.focusedEditor;
-
- // Still the same editor the the blur was outside any editor UI
- if (!isUIElement(getActiveElement()) && focusedEditor == editor) {
- editor.fire('blur', {focusedEditor: null});
- editorManager.focusedEditor = null;
-
- // Make sure selection is valid could be invalid if the editor is blured and removed before the timeout occurs
- if (editor.selection) {
- editor.selection.lastFocusBookmark = null;
- }
- }
- }, 0);
- });
-
- if (!documentFocusInHandler) {
- documentFocusInHandler = function(e) {
- var activeEditor = editorManager.activeEditor;
-
- if (activeEditor && e.target.ownerDocument == document) {
- // Check to make sure we have a valid selection
- if (activeEditor.selection) {
- activeEditor.selection.lastFocusBookmark = createBookmark(activeEditor.lastRng);
- }
-
- // Fire a blur event if the element isn't a UI element
- if (!isUIElement(e.target) && editorManager.focusedEditor == activeEditor) {
- activeEditor.fire('blur', {focusedEditor: null});
- editorManager.focusedEditor = null;
- }
- }
- };
-
- // Check if focus is moved to an element outside the active editor by checking if the target node
- // isn't within the body of the activeEditor nor a UI element such as a dialog child control
- DOM.bind(document, 'focusin', documentFocusInHandler);
- }
- }
-
- function unregisterDocumentEvents(e) {
- if (editorManager.focusedEditor == e.editor) {
- editorManager.focusedEditor = null;
- }
-
- if (!editorManager.activeEditor) {
- DOM.unbind(document, 'selectionchange', selectionChangeHandler);
- DOM.unbind(document, 'focusin', documentFocusInHandler);
- selectionChangeHandler = documentFocusInHandler = null;
- }
- }
-
- editorManager.on('AddEditor', registerEvents);
- editorManager.on('RemoveEditor', unregisterDocumentEvents);
- }
-
- /**
- * Returns true if the specified element is part of the UI for example an button or text input.
- *
- * @method isEditorUIElement
- * @param {Element} elm Element to check if it's part of the UI or not.
- * @return {Boolean} True/false state if the element is part of the UI or not.
- */
- FocusManager.isEditorUIElement = function(elm) {
- // Needs to be converted to string since svg can have focus: #6776
- return elm.className.toString().indexOf('mce-') !== -1;
- };
-
- return FocusManager;
-});
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ForceBlocks.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ForceBlocks.js
deleted file mode 100755
index 3a56b44111..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/ForceBlocks.js
+++ /dev/null
@@ -1,132 +0,0 @@
-/**
- * ForceBlocks.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-define("tinymce/ForceBlocks", [], function() {
- return function(editor) {
- var settings = editor.settings, dom = editor.dom, selection = editor.selection;
- var schema = editor.schema, blockElements = schema.getBlockElements();
-
- function addRootBlocks() {
- var node = selection.getStart(), rootNode = editor.getBody(), rng;
- var startContainer, startOffset, endContainer, endOffset, rootBlockNode;
- var tempNode, offset = -0xFFFFFF, wrapped, restoreSelection;
- var tmpRng, rootNodeName, forcedRootBlock;
-
- forcedRootBlock = settings.forced_root_block;
-
- if (!node || node.nodeType !== 1 || !forcedRootBlock) {
- return;
- }
-
- // Check if node is wrapped in block
- while (node && node != rootNode) {
- if (blockElements[node.nodeName]) {
- return;
- }
-
- node = node.parentNode;
- }
-
- // Get current selection
- rng = selection.getRng();
- if (rng.setStart) {
- startContainer = rng.startContainer;
- startOffset = rng.startOffset;
- endContainer = rng.endContainer;
- endOffset = rng.endOffset;
-
- try {
- restoreSelection = editor.getDoc().activeElement === rootNode;
- } catch (ex) {
- // IE throws unspecified error here sometimes
- }
- } else {
- // Force control range into text range
- if (rng.item) {
- node = rng.item(0);
- rng = editor.getDoc().body.createTextRange();
- rng.moveToElementText(node);
- }
-
- restoreSelection = rng.parentElement().ownerDocument === editor.getDoc();
- tmpRng = rng.duplicate();
- tmpRng.collapse(true);
- startOffset = tmpRng.move('character', offset) * -1;
-
- if (!tmpRng.collapsed) {
- tmpRng = rng.duplicate();
- tmpRng.collapse(false);
- endOffset = (tmpRng.move('character', offset) * -1) - startOffset;
- }
- }
-
- // Wrap non block elements and text nodes
- node = rootNode.firstChild;
- rootNodeName = rootNode.nodeName.toLowerCase();
- while (node) {
- // TODO: Break this up, too complex
- if (((node.nodeType === 3 || (node.nodeType == 1 && !blockElements[node.nodeName]))) &&
- schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase())) {
- // Remove empty text nodes
- if (node.nodeType === 3 && node.nodeValue.length === 0) {
- tempNode = node;
- node = node.nextSibling;
- dom.remove(tempNode);
- continue;
- }
-
- if (!rootBlockNode) {
- rootBlockNode = dom.create(forcedRootBlock, editor.settings.forced_root_block_attrs);
- node.parentNode.insertBefore(rootBlockNode, node);
- wrapped = true;
- }
-
- tempNode = node;
- node = node.nextSibling;
- rootBlockNode.appendChild(tempNode);
- } else {
- rootBlockNode = null;
- node = node.nextSibling;
- }
- }
-
- if (wrapped && restoreSelection) {
- if (rng.setStart) {
- rng.setStart(startContainer, startOffset);
- rng.setEnd(endContainer, endOffset);
- selection.setRng(rng);
- } else {
- // Only select if the previous selection was inside the document to prevent auto focus in quirks mode
- try {
- rng = editor.getDoc().body.createTextRange();
- rng.moveToElementText(rootNode);
- rng.collapse(true);
- rng.moveStart('character', startOffset);
-
- if (endOffset > 0) {
- rng.moveEnd('character', endOffset);
- }
-
- rng.select();
- } catch (ex) {
- // Ignore
- }
- }
-
- editor.nodeChanged();
- }
- }
-
- // Force root blocks
- if (settings.forced_root_block) {
- editor.on('NodeChange', addRootBlocks);
- }
- };
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/Formatter.js b/common/static/js/vendor/tinymce/js/tinymce/classes/Formatter.js
deleted file mode 100755
index baa0b8a417..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/Formatter.js
+++ /dev/null
@@ -1,2426 +0,0 @@
-/**
- * Formatter.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * Text formatter engine class. This class is used to apply formats like bold, italic, font size
- * etc to the current selection or specific nodes. This engine was build to replace the browsers
- * default formatting logic for execCommand due to it's inconsistent and buggy behavior.
- *
- * @class tinymce.Formatter
- * @example
- * tinymce.activeEditor.formatter.register('mycustomformat', {
- * inline: 'span',
- * styles: {color: '#ff0000'}
- * });
- *
- * tinymce.activeEditor.formatter.apply('mycustomformat');
- */
-define("tinymce/Formatter", [
- "tinymce/dom/TreeWalker",
- "tinymce/dom/RangeUtils",
- "tinymce/util/Tools"
-], function(TreeWalker, RangeUtils, Tools) {
- /**
- * Constructs a new formatter instance.
- *
- * @constructor Formatter
- * @param {tinymce.Editor} ed Editor instance to construct the formatter engine to.
- */
- return function(ed) {
- var formats = {},
- dom = ed.dom,
- selection = ed.selection,
- rangeUtils = new RangeUtils(dom),
- isValid = ed.schema.isValidChild,
- isBlock = dom.isBlock,
- forcedRootBlock = ed.settings.forced_root_block,
- nodeIndex = dom.nodeIndex,
- INVISIBLE_CHAR = '\uFEFF',
- MCE_ATTR_RE = /^(src|href|style)$/,
- FALSE = false,
- TRUE = true,
- formatChangeData,
- undef,
- getContentEditable = dom.getContentEditable,
- disableCaretContainer,
- markCaretContainersBogus;
-
- var each = Tools.each,
- grep = Tools.grep,
- walk = Tools.walk,
- extend = Tools.extend;
-
- function isTextBlock(name) {
- if (name.nodeType) {
- name = name.nodeName;
- }
-
- return !!ed.schema.getTextBlockElements()[name.toLowerCase()];
- }
-
- function getParents(node, selector) {
- return dom.getParents(node, selector, dom.getRoot());
- }
-
- function isCaretNode(node) {
- return node.nodeType === 1 && node.id === '_mce_caret';
- }
-
- function defaultFormats() {
- register({
- alignleft: [
- {selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li', styles: {textAlign: 'left'}, defaultBlock: 'div'},
- {selector: 'img,table', collapsed: false, styles: {'float': 'left'}}
- ],
-
- aligncenter: [
- {selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li', styles: {textAlign: 'center'}, defaultBlock: 'div'},
- {selector: 'img', collapsed: false, styles: {display: 'block', marginLeft: 'auto', marginRight: 'auto'}},
- {selector: 'table', collapsed: false, styles: {marginLeft: 'auto', marginRight: 'auto'}}
- ],
-
- alignright: [
- {selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li', styles: {textAlign: 'right'}, defaultBlock: 'div'},
- {selector: 'img,table', collapsed: false, styles: {'float': 'right'}}
- ],
-
- alignjustify: [
- {selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li', styles: {textAlign: 'justify'}, defaultBlock: 'div'}
- ],
-
- bold: [
- {inline: 'strong', remove: 'all'},
- {inline: 'span', styles: {fontWeight: 'bold'}},
- {inline: 'b', remove: 'all'}
- ],
-
- italic: [
- {inline: 'em', remove: 'all'},
- {inline: 'span', styles: {fontStyle: 'italic'}},
- {inline: 'i', remove: 'all'}
- ],
-
- underline: [
- {inline: 'span', styles: {textDecoration: 'underline'}, exact: true},
- {inline: 'u', remove: 'all'}
- ],
-
- strikethrough: [
- {inline: 'span', styles: {textDecoration: 'line-through'}, exact: true},
- {inline: 'strike', remove: 'all'}
- ],
-
- forecolor: {inline: 'span', styles: {color: '%value'}, wrap_links: false},
- hilitecolor: {inline: 'span', styles: {backgroundColor: '%value'}, wrap_links: false},
- fontname: {inline: 'span', styles: {fontFamily: '%value'}},
- fontsize: {inline: 'span', styles: {fontSize: '%value'}},
- fontsize_class: {inline: 'span', attributes: {'class': '%value'}},
- blockquote: {block: 'blockquote', wrapper: 1, remove: 'all'},
- subscript: {inline: 'sub'},
- superscript: {inline: 'sup'},
- code: {inline: 'code'},
-
- link: {inline: 'a', selector: 'a', remove: 'all', split: true, deep: true,
- onmatch: function() {
- return true;
- },
-
- onformat: function(elm, fmt, vars) {
- each(vars, function(value, key) {
- dom.setAttrib(elm, key, value);
- });
- }
- },
-
- removeformat: [
- {
- selector: 'b,strong,em,i,font,u,strike,sub,sup,dfn,code,samp,kbd,var,cite,mark,q',
- remove: 'all',
- split: true,
- expand: false,
- block_expand: true,
- deep: true
- },
- {selector: 'span', attributes: ['style', 'class'], remove: 'empty', split: true, expand: false, deep: true},
- {selector: '*', attributes: ['style', 'class'], split: false, expand: false, deep: true}
- ]
- });
-
- // Register default block formats
- each('p h1 h2 h3 h4 h5 h6 div address pre div dt dd samp'.split(/\s/), function(name) {
- register(name, {block: name, remove: 'all'});
- });
-
- // Register user defined formats
- register(ed.settings.formats);
- }
-
- function addKeyboardShortcuts() {
- // Add some inline shortcuts
- ed.addShortcut('ctrl+b', 'bold_desc', 'Bold');
- ed.addShortcut('ctrl+i', 'italic_desc', 'Italic');
- ed.addShortcut('ctrl+u', 'underline_desc', 'Underline');
-
- // BlockFormat shortcuts keys
- for (var i = 1; i <= 6; i++) {
- ed.addShortcut('ctrl+' + i, '', ['FormatBlock', false, 'h' + i]);
- }
-
- ed.addShortcut('ctrl+7', '', ['FormatBlock', false, 'p']);
- ed.addShortcut('ctrl+8', '', ['FormatBlock', false, 'div']);
- ed.addShortcut('ctrl+9', '', ['FormatBlock', false, 'address']);
- }
-
- // Public functions
-
- /**
- * Returns the format by name or all formats if no name is specified.
- *
- * @method get
- * @param {String} name Optional name to retrive by.
- * @return {Array/Object} Array/Object with all registred formats or a specific format.
- */
- function get(name) {
- return name ? formats[name] : formats;
- }
-
- /**
- * Registers a specific format by name.
- *
- * @method register
- * @param {Object/String} name Name of the format for example "bold".
- * @param {Object/Array} format Optional format object or array of format variants
- * can only be omitted if the first arg is an object.
- */
- function register(name, format) {
- if (name) {
- if (typeof(name) !== 'string') {
- each(name, function(format, name) {
- register(name, format);
- });
- } else {
- // Force format into array and add it to internal collection
- format = format.length ? format : [format];
-
- each(format, function(format) {
- // Set deep to false by default on selector formats this to avoid removing
- // alignment on images inside paragraphs when alignment is changed on paragraphs
- if (format.deep === undef) {
- format.deep = !format.selector;
- }
-
- // Default to true
- if (format.split === undef) {
- format.split = !format.selector || format.inline;
- }
-
- // Default to true
- if (format.remove === undef && format.selector && !format.inline) {
- format.remove = 'none';
- }
-
- // Mark format as a mixed format inline + block level
- if (format.selector && format.inline) {
- format.mixed = true;
- format.block_expand = true;
- }
-
- // Split classes if needed
- if (typeof(format.classes) === 'string') {
- format.classes = format.classes.split(/\s+/);
- }
- });
-
- formats[name] = format;
- }
- }
- }
-
- function getTextDecoration(node) {
- var decoration;
-
- ed.dom.getParent(node, function(n) {
- decoration = ed.dom.getStyle(n, 'text-decoration');
- return decoration && decoration !== 'none';
- });
-
- return decoration;
- }
-
- function processUnderlineAndColor(node) {
- var textDecoration;
- if (node.nodeType === 1 && node.parentNode && node.parentNode.nodeType === 1) {
- textDecoration = getTextDecoration(node.parentNode);
- if (ed.dom.getStyle(node, 'color') && textDecoration) {
- ed.dom.setStyle(node, 'text-decoration', textDecoration);
- } else if (ed.dom.getStyle(node, 'textdecoration') === textDecoration) {
- ed.dom.setStyle(node, 'text-decoration', null);
- }
- }
- }
-
- /**
- * Applies the specified format to the current selection or specified node.
- *
- * @method apply
- * @param {String} name Name of format to apply.
- * @param {Object} vars Optional list of variables to replace within format before applying it.
- * @param {Node} node Optional node to apply the format to defaults to current selection.
- */
- function apply(name, vars, node) {
- var formatList = get(name), format = formatList[0], bookmark, rng, isCollapsed = !node && selection.isCollapsed();
-
- function setElementFormat(elm, fmt) {
- fmt = fmt || format;
-
- if (elm) {
- if (fmt.onformat) {
- fmt.onformat(elm, fmt, vars, node);
- }
-
- each(fmt.styles, function(value, name) {
- dom.setStyle(elm, name, replaceVars(value, vars));
- });
-
- each(fmt.attributes, function(value, name) {
- dom.setAttrib(elm, name, replaceVars(value, vars));
- });
-
- each(fmt.classes, function(value) {
- value = replaceVars(value, vars);
-
- if (!dom.hasClass(elm, value)) {
- dom.addClass(elm, value);
- }
- });
- }
- }
-
- function adjustSelectionToVisibleSelection() {
- function findSelectionEnd(start, end) {
- var walker = new TreeWalker(end);
- for (node = walker.current(); node; node = walker.prev()) {
- if (node.childNodes.length > 1 || node == start || node.tagName == 'BR') {
- return node;
- }
- }
- }
-
- // Adjust selection so that a end container with a end offset of zero is not included in the selection
- // as this isn't visible to the user.
- var rng = ed.selection.getRng();
- var start = rng.startContainer;
- var end = rng.endContainer;
-
- if (start != end && rng.endOffset === 0) {
- var newEnd = findSelectionEnd(start, end);
- var endOffset = newEnd.nodeType == 3 ? newEnd.length : newEnd.childNodes.length;
-
- rng.setEnd(newEnd, endOffset);
- }
-
- return rng;
- }
-
- function applyStyleToList(node, bookmark, wrapElm, newWrappers, process){
- var nodes = [], listIndex = -1, list, startIndex = -1, endIndex = -1, currentWrapElm;
-
- // find the index of the first child list.
- each(node.childNodes, function(n, index) {
- if (n.nodeName === "UL" || n.nodeName === "OL") {
- listIndex = index;
- list = n;
- return false;
- }
- });
-
- // get the index of the bookmarks
- each(node.childNodes, function(n, index) {
- if (n.nodeName === "SPAN" && dom.getAttrib(n, "data-mce-type") == "bookmark") {
- if (n.id == bookmark.id + "_start") {
- startIndex = index;
- } else if (n.id == bookmark.id + "_end") {
- endIndex = index;
- }
- }
- });
-
- // if the selection spans across an embedded list, or there isn't an embedded list - handle processing normally
- if (listIndex <= 0 || (startIndex < listIndex && endIndex > listIndex)) {
- each(grep(node.childNodes), process);
- return 0;
- } else {
- currentWrapElm = dom.clone(wrapElm, FALSE);
-
- // create a list of the nodes on the same side of the list as the selection
- each(grep(node.childNodes), function(n, index) {
- if ((startIndex < listIndex && index < listIndex) || (startIndex > listIndex && index > listIndex)) {
- nodes.push(n);
- n.parentNode.removeChild(n);
- }
- });
-
- // insert the wrapping element either before or after the list.
- if (startIndex < listIndex) {
- node.insertBefore(currentWrapElm, list);
- } else if (startIndex > listIndex) {
- node.insertBefore(currentWrapElm, list.nextSibling);
- }
-
- // add the new nodes to the list.
- newWrappers.push(currentWrapElm);
-
- each(nodes, function(node) {
- currentWrapElm.appendChild(node);
- });
-
- return currentWrapElm;
- }
- }
-
- function applyRngStyle(rng, bookmark, node_specific) {
- var newWrappers = [], wrapName, wrapElm, contentEditable = true;
-
- // Setup wrapper element
- wrapName = format.inline || format.block;
- wrapElm = dom.create(wrapName);
- setElementFormat(wrapElm);
-
- rangeUtils.walk(rng, function(nodes) {
- var currentWrapElm;
-
- /**
- * Process a list of nodes wrap them.
- */
- function process(node) {
- var nodeName, parentName, found, hasContentEditableState, lastContentEditable;
-
- lastContentEditable = contentEditable;
- nodeName = node.nodeName.toLowerCase();
- parentName = node.parentNode.nodeName.toLowerCase();
-
- // Node has a contentEditable value
- if (node.nodeType === 1 && getContentEditable(node)) {
- lastContentEditable = contentEditable;
- contentEditable = getContentEditable(node) === "true";
- hasContentEditableState = true; // We don't want to wrap the container only it's children
- }
-
- // Stop wrapping on br elements
- if (isEq(nodeName, 'br')) {
- currentWrapElm = 0;
-
- // Remove any br elements when we wrap things
- if (format.block) {
- dom.remove(node);
- }
-
- return;
- }
-
- // If node is wrapper type
- if (format.wrapper && matchNode(node, name, vars)) {
- currentWrapElm = 0;
- return;
- }
-
- // Can we rename the block
- // TODO: Break this if up, too complex
- if (contentEditable && !hasContentEditableState && format.block &&
- !format.wrapper && isTextBlock(nodeName) && isValid(parentName, wrapName)) {
- node = dom.rename(node, wrapName);
- setElementFormat(node);
- newWrappers.push(node);
- currentWrapElm = 0;
- return;
- }
-
- // Handle selector patterns
- if (format.selector) {
- // Look for matching formats
- each(formatList, function(format) {
- // Check collapsed state if it exists
- if ('collapsed' in format && format.collapsed !== isCollapsed) {
- return;
- }
-
- if (dom.is(node, format.selector) && !isCaretNode(node)) {
- setElementFormat(node, format);
- found = true;
- }
- });
-
- // Continue processing if a selector match wasn't found and a inline element is defined
- if (!format.inline || found) {
- currentWrapElm = 0;
- return;
- }
- }
-
- // Is it valid to wrap this item
- // TODO: Break this if up, too complex
- if (contentEditable && !hasContentEditableState && isValid(wrapName, nodeName) && isValid(parentName, wrapName) &&
- !(!node_specific && node.nodeType === 3 &&
- node.nodeValue.length === 1 &&
- node.nodeValue.charCodeAt(0) === 65279) &&
- !isCaretNode(node) &&
- (!format.inline || !isBlock(node))) {
- // Start wrapping
- if (!currentWrapElm) {
- // Wrap the node
- currentWrapElm = dom.clone(wrapElm, FALSE);
- node.parentNode.insertBefore(currentWrapElm, node);
- newWrappers.push(currentWrapElm);
- }
-
- currentWrapElm.appendChild(node);
- } else if (nodeName == 'li' && bookmark) {
- // Start wrapping - if we are in a list node and have a bookmark, then
- // we will always begin by wrapping in a new element.
- currentWrapElm = applyStyleToList(node, bookmark, wrapElm, newWrappers, process);
- } else {
- // Start a new wrapper for possible children
- currentWrapElm = 0;
-
- each(grep(node.childNodes), process);
-
- if (hasContentEditableState) {
- contentEditable = lastContentEditable; // Restore last contentEditable state from stack
- }
-
- // End the last wrapper
- currentWrapElm = 0;
- }
- }
-
- // Process siblings from range
- each(nodes, process);
- });
-
- // Wrap links inside as well, for example color inside a link when the wrapper is around the link
- if (format.wrap_links === false) {
- each(newWrappers, function(node) {
- function process(node) {
- var i, currentWrapElm, children;
-
- if (node.nodeName === 'A') {
- currentWrapElm = dom.clone(wrapElm, FALSE);
- newWrappers.push(currentWrapElm);
-
- children = grep(node.childNodes);
- for (i = 0; i < children.length; i++) {
- currentWrapElm.appendChild(children[i]);
- }
-
- node.appendChild(currentWrapElm);
- }
-
- each(grep(node.childNodes), process);
- }
-
- process(node);
- });
- }
-
- // Cleanup
- each(newWrappers, function(node) {
- var childCount;
-
- function getChildCount(node) {
- var count = 0;
-
- each(node.childNodes, function(node) {
- if (!isWhiteSpaceNode(node) && !isBookmarkNode(node)) {
- count++;
- }
- });
-
- return count;
- }
-
- function mergeStyles(node) {
- var child, clone;
-
- each(node.childNodes, function(node) {
- if (node.nodeType == 1 && !isBookmarkNode(node) && !isCaretNode(node)) {
- child = node;
- return FALSE; // break loop
- }
- });
-
- // If child was found and of the same type as the current node
- if (child && !isBookmarkNode(child) && matchName(child, format)) {
- clone = dom.clone(child, FALSE);
- setElementFormat(clone);
-
- dom.replace(clone, node, TRUE);
- dom.remove(child, 1);
- }
-
- return clone || node;
- }
-
- childCount = getChildCount(node);
-
- // Remove empty nodes but only if there is multiple wrappers and they are not block
- // elements so never remove single since that would remove the
- // currrent empty block element where the caret is at
- if ((newWrappers.length > 1 || !isBlock(node)) && childCount === 0) {
- dom.remove(node, 1);
- return;
- }
-
- if (format.inline || format.wrapper) {
- // Merges the current node with it's children of similar type to reduce the number of elements
- if (!format.exact && childCount === 1) {
- node = mergeStyles(node);
- }
-
- // Remove/merge children
- each(formatList, function(format) {
- // Merge all children of similar type will move styles from child to parent
- // this: text
- // will become: text
- each(dom.select(format.inline, node), function(child) {
- var parent;
-
- if (isBookmarkNode(child)) {
- return;
- }
-
- // When wrap_links is set to false we don't want
- // to remove the format on children within links
- if (format.wrap_links === false) {
- parent = child.parentNode;
-
- do {
- if (parent.nodeName === 'A') {
- return;
- }
- } while ((parent = parent.parentNode));
- }
-
- removeFormat(format, vars, child, format.exact ? child : null);
- });
- });
-
- // Remove child if direct parent is of same type
- if (matchNode(node.parentNode, name, vars)) {
- dom.remove(node, 1);
- node = 0;
- return TRUE;
- }
-
- // Look for parent with similar style format
- if (format.merge_with_parents) {
- dom.getParent(node.parentNode, function(parent) {
- if (matchNode(parent, name, vars)) {
- dom.remove(node, 1);
- node = 0;
- return TRUE;
- }
- });
- }
-
- // Merge next and previous siblings if they are similar texttext becomes texttext
- if (node && format.merge_siblings !== false) {
- node = mergeSiblings(getNonWhiteSpaceSibling(node), node);
- node = mergeSiblings(node, getNonWhiteSpaceSibling(node, TRUE));
- }
- }
- });
- }
-
- if (format) {
- if (node) {
- if (node.nodeType) {
- rng = dom.createRng();
- rng.setStartBefore(node);
- rng.setEndAfter(node);
- applyRngStyle(expandRng(rng, formatList), null, true);
- } else {
- applyRngStyle(node, null, true);
- }
- } else {
- if (!isCollapsed || !format.inline || dom.select('td.mce-item-selected,th.mce-item-selected').length) {
- // Obtain selection node before selection is unselected by applyRngStyle()
- var curSelNode = ed.selection.getNode();
-
- // If the formats have a default block and we can't find a parent block then
- // start wrapping it with a DIV this is for forced_root_blocks: false
- // It's kind of a hack but people should be using the default block type P since all desktop editors work that way
- if (!forcedRootBlock && formatList[0].defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) {
- apply(formatList[0].defaultBlock);
- }
-
- // Apply formatting to selection
- ed.selection.setRng(adjustSelectionToVisibleSelection());
- bookmark = selection.getBookmark();
- applyRngStyle(expandRng(selection.getRng(TRUE), formatList), bookmark);
-
- // Colored nodes should be underlined so that the color of the underline matches the text color.
- if (format.styles && (format.styles.color || format.styles.textDecoration)) {
- walk(curSelNode, processUnderlineAndColor, 'childNodes');
- processUnderlineAndColor(curSelNode);
- }
-
- selection.moveToBookmark(bookmark);
- moveStart(selection.getRng(TRUE));
- ed.nodeChanged();
- } else {
- performCaretAction('apply', name, vars);
- }
- }
- }
- }
-
- /**
- * Removes the specified format from the current selection or specified node.
- *
- * @method remove
- * @param {String} name Name of format to remove.
- * @param {Object} vars Optional list of variables to replace within format before removing it.
- * @param {Node/Range} node Optional node or DOM range to remove the format from defaults to current selection.
- */
- function remove(name, vars, node) {
- var formatList = get(name), format = formatList[0], bookmark, rng, contentEditable = true;
-
- // Merges the styles for each node
- function process(node) {
- var children, i, l, lastContentEditable, hasContentEditableState;
-
- // Node has a contentEditable value
- if (node.nodeType === 1 && getContentEditable(node)) {
- lastContentEditable = contentEditable;
- contentEditable = getContentEditable(node) === "true";
- hasContentEditableState = true; // We don't want to wrap the container only it's children
- }
-
- // Grab the children first since the nodelist might be changed
- children = grep(node.childNodes);
-
- // Process current node
- if (contentEditable && !hasContentEditableState) {
- for (i = 0, l = formatList.length; i < l; i++) {
- if (removeFormat(formatList[i], vars, node, node)) {
- break;
- }
- }
- }
-
- // Process the children
- if (format.deep) {
- if (children.length) {
- for (i = 0, l = children.length; i < l; i++) {
- process(children[i]);
- }
-
- if (hasContentEditableState) {
- contentEditable = lastContentEditable; // Restore last contentEditable state from stack
- }
- }
- }
- }
-
- function findFormatRoot(container) {
- var formatRoot;
-
- // Find format root
- each(getParents(container.parentNode).reverse(), function(parent) {
- var format;
-
- // Find format root element
- if (!formatRoot && parent.id != '_start' && parent.id != '_end') {
- // Is the node matching the format we are looking for
- format = matchNode(parent, name, vars);
- if (format && format.split !== false) {
- formatRoot = parent;
- }
- }
- });
-
- return formatRoot;
- }
-
- function wrapAndSplit(format_root, container, target, split) {
- var parent, clone, lastClone, firstClone, i, formatRootParent;
-
- // Format root found then clone formats and split it
- if (format_root) {
- formatRootParent = format_root.parentNode;
-
- for (parent = container.parentNode; parent && parent != formatRootParent; parent = parent.parentNode) {
- clone = dom.clone(parent, FALSE);
-
- for (i = 0; i < formatList.length; i++) {
- if (removeFormat(formatList[i], vars, clone, clone)) {
- clone = 0;
- break;
- }
- }
-
- // Build wrapper node
- if (clone) {
- if (lastClone) {
- clone.appendChild(lastClone);
- }
-
- if (!firstClone) {
- firstClone = clone;
- }
-
- lastClone = clone;
- }
- }
-
- // Never split block elements if the format is mixed
- if (split && (!format.mixed || !isBlock(format_root))) {
- container = dom.split(format_root, container);
- }
-
- // Wrap container in cloned formats
- if (lastClone) {
- target.parentNode.insertBefore(lastClone, target);
- firstClone.appendChild(target);
- }
- }
-
- return container;
- }
-
- function splitToFormatRoot(container) {
- return wrapAndSplit(findFormatRoot(container), container, container, true);
- }
-
- function unwrap(start) {
- var node = dom.get(start ? '_start' : '_end'),
- out = node[start ? 'firstChild' : 'lastChild'];
-
- // If the end is placed within the start the result will be removed
- // So this checks if the out node is a bookmark node if it is it
- // checks for another more suitable node
- if (isBookmarkNode(out)) {
- out = out[start ? 'firstChild' : 'lastChild'];
- }
-
- dom.remove(node, true);
-
- return out;
- }
-
- function removeRngStyle(rng) {
- var startContainer, endContainer;
- var commonAncestorContainer = rng.commonAncestorContainer;
-
- rng = expandRng(rng, formatList, TRUE);
-
- if (format.split) {
- startContainer = getContainer(rng, TRUE);
- endContainer = getContainer(rng);
-
- if (startContainer != endContainer) {
- // WebKit will render the table incorrectly if we wrap a TH or TD in a SPAN
- // so let's see if we can use the first child instead
- // This will happen if you triple click a table cell and use remove formatting
- if (/^(TR|TH|TD)$/.test(startContainer.nodeName) && startContainer.firstChild) {
- if (startContainer.nodeName == "TR") {
- startContainer = startContainer.firstChild.firstChild || startContainer;
- } else {
- startContainer = startContainer.firstChild || startContainer;
- }
- }
-
- // Try to adjust endContainer as well if cells on the same row were selected - bug #6410
- if (commonAncestorContainer &&
- /^T(HEAD|BODY|FOOT|R)$/.test(commonAncestorContainer.nodeName) &&
- /^(TH|TD)$/.test(endContainer.nodeName) && endContainer.firstChild) {
- endContainer = endContainer.firstChild || endContainer;
- }
-
- // Wrap start/end nodes in span element since these might be cloned/moved
- startContainer = wrap(startContainer, 'span', {id: '_start', 'data-mce-type': 'bookmark'});
- endContainer = wrap(endContainer, 'span', {id: '_end', 'data-mce-type': 'bookmark'});
-
- // Split start/end
- splitToFormatRoot(startContainer);
- splitToFormatRoot(endContainer);
-
- // Unwrap start/end to get real elements again
- startContainer = unwrap(TRUE);
- endContainer = unwrap();
- } else {
- startContainer = endContainer = splitToFormatRoot(startContainer);
- }
-
- // Update range positions since they might have changed after the split operations
- rng.startContainer = startContainer.parentNode;
- rng.startOffset = nodeIndex(startContainer);
- rng.endContainer = endContainer.parentNode;
- rng.endOffset = nodeIndex(endContainer) + 1;
- }
-
- // Remove items between start/end
- rangeUtils.walk(rng, function(nodes) {
- each(nodes, function(node) {
- process(node);
-
- // Remove parent span if it only contains text-decoration: underline, yet a parent node is also underlined.
- if (node.nodeType === 1 && ed.dom.getStyle(node, 'text-decoration') === 'underline' &&
- node.parentNode && getTextDecoration(node.parentNode) === 'underline') {
- removeFormat({
- 'deep': false,
- 'exact': true,
- 'inline': 'span',
- 'styles': {
- 'textDecoration': 'underline'
- }
- }, null, node);
- }
- });
- });
- }
-
- // Handle node
- if (node) {
- if (node.nodeType) {
- rng = dom.createRng();
- rng.setStartBefore(node);
- rng.setEndAfter(node);
- removeRngStyle(rng);
- } else {
- removeRngStyle(node);
- }
-
- return;
- }
-
- if (!selection.isCollapsed() || !format.inline || dom.select('td.mce-item-selected,th.mce-item-selected').length) {
- bookmark = selection.getBookmark();
- removeRngStyle(selection.getRng(TRUE));
- selection.moveToBookmark(bookmark);
-
- // Check if start element still has formatting then we are at: "text|text"
- // and need to move the start into the next text node
- if (format.inline && match(name, vars, selection.getStart())) {
- moveStart(selection.getRng(true));
- }
-
- ed.nodeChanged();
- } else {
- performCaretAction('remove', name, vars);
- }
- }
-
- /**
- * Toggles the specified format on/off.
- *
- * @method toggle
- * @param {String} name Name of format to apply/remove.
- * @param {Object} vars Optional list of variables to replace within format before applying/removing it.
- * @param {Node} node Optional node to apply the format to or remove from. Defaults to current selection.
- */
- function toggle(name, vars, node) {
- var fmt = get(name);
-
- if (match(name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
- remove(name, vars, node);
- } else {
- apply(name, vars, node);
- }
- }
-
- /**
- * Return true/false if the specified node has the specified format.
- *
- * @method matchNode
- * @param {Node} node Node to check the format on.
- * @param {String} name Format name to check.
- * @param {Object} vars Optional list of variables to replace before checking it.
- * @param {Boolean} similar Match format that has similar properties.
- * @return {Object} Returns the format object it matches or undefined if it doesn't match.
- */
- function matchNode(node, name, vars, similar) {
- var formatList = get(name), format, i, classes;
-
- function matchItems(node, format, item_name) {
- var key, value, items = format[item_name], i;
-
- // Custom match
- if (format.onmatch) {
- return format.onmatch(node, format, item_name);
- }
-
- // Check all items
- if (items) {
- // Non indexed object
- if (items.length === undef) {
- for (key in items) {
- if (items.hasOwnProperty(key)) {
- if (item_name === 'attributes') {
- value = dom.getAttrib(node, key);
- } else {
- value = getStyle(node, key);
- }
-
- if (similar && !value && !format.exact) {
- return;
- }
-
- if ((!similar || format.exact) && !isEq(value, normalizeStyleValue(replaceVars(items[key], vars), key))) {
- return;
- }
- }
- }
- } else {
- // Only one match needed for indexed arrays
- for (i = 0; i < items.length; i++) {
- if (item_name === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(node, items[i])) {
- return format;
- }
- }
- }
- }
-
- return format;
- }
-
- if (formatList && node) {
- // Check each format in list
- for (i = 0; i < formatList.length; i++) {
- format = formatList[i];
-
- // Name name, attributes, styles and classes
- if (matchName(node, format) && matchItems(node, format, 'attributes') && matchItems(node, format, 'styles')) {
- // Match classes
- if ((classes = format.classes)) {
- for (i = 0; i < classes.length; i++) {
- if (!dom.hasClass(node, classes[i])) {
- return;
- }
- }
- }
-
- return format;
- }
- }
- }
- }
-
- /**
- * Matches the current selection or specified node against the specified format name.
- *
- * @method match
- * @param {String} name Name of format to match.
- * @param {Object} vars Optional list of variables to replace before checking it.
- * @param {Node} node Optional node to check.
- * @return {boolean} true/false if the specified selection/node matches the format.
- */
- function match(name, vars, node) {
- var startNode;
-
- function matchParents(node) {
- var root = dom.getRoot();
-
- if (node === root) {
- return false;
- }
-
- // Find first node with similar format settings
- node = dom.getParent(node, function(node) {
- return node.parentNode === root || !!matchNode(node, name, vars, true);
- });
-
- // Do an exact check on the similar format element
- return matchNode(node, name, vars);
- }
-
- // Check specified node
- if (node) {
- return matchParents(node);
- }
-
- // Check selected node
- node = selection.getNode();
- if (matchParents(node)) {
- return TRUE;
- }
-
- // Check start node if it's different
- startNode = selection.getStart();
- if (startNode != node) {
- if (matchParents(startNode)) {
- return TRUE;
- }
- }
-
- return FALSE;
- }
-
- /**
- * Matches the current selection against the array of formats and returns a new array with matching formats.
- *
- * @method matchAll
- * @param {Array} names Name of format to match.
- * @param {Object} vars Optional list of variables to replace before checking it.
- * @return {Array} Array with matched formats.
- */
- function matchAll(names, vars) {
- var startElement, matchedFormatNames = [], checkedMap = {};
-
- // Check start of selection for formats
- startElement = selection.getStart();
- dom.getParent(startElement, function(node) {
- var i, name;
-
- for (i = 0; i < names.length; i++) {
- name = names[i];
-
- if (!checkedMap[name] && matchNode(node, name, vars)) {
- checkedMap[name] = true;
- matchedFormatNames.push(name);
- }
- }
- }, dom.getRoot());
-
- return matchedFormatNames;
- }
-
- /**
- * Returns true/false if the specified format can be applied to the current selection or not. It
- * will currently only check the state for selector formats, it returns true on all other format types.
- *
- * @method canApply
- * @param {String} name Name of format to check.
- * @return {boolean} true/false if the specified format can be applied to the current selection/node.
- */
- function canApply(name) {
- var formatList = get(name), startNode, parents, i, x, selector;
-
- if (formatList) {
- startNode = selection.getStart();
- parents = getParents(startNode);
-
- for (x = formatList.length - 1; x >= 0; x--) {
- selector = formatList[x].selector;
-
- // Format is not selector based then always return TRUE
- // Is it has a defaultBlock then it's likely it can be applied for example align on a non block element line
- if (!selector || formatList[x].defaultBlock) {
- return TRUE;
- }
-
- for (i = parents.length - 1; i >= 0; i--) {
- if (dom.is(parents[i], selector)) {
- return TRUE;
- }
- }
- }
- }
-
- return FALSE;
- }
-
- /**
- * Executes the specified callback when the current selection matches the formats or not.
- *
- * @method formatChanged
- * @param {String} formats Comma separated list of formats to check for.
- * @param {function} callback Callback with state and args when the format is changed/toggled on/off.
- * @param {Boolean} similar True/false state if the match should handle similar or exact formats.
- */
- function formatChanged(formats, callback, similar) {
- var currentFormats;
-
- // Setup format node change logic
- if (!formatChangeData) {
- formatChangeData = {};
- currentFormats = {};
-
- ed.on('NodeChange', function(e) {
- var parents = getParents(e.element), matchedFormats = {};
-
- // Check for new formats
- each(formatChangeData, function(callbacks, format) {
- each(parents, function(node) {
- if (matchNode(node, format, {}, callbacks.similar)) {
- if (!currentFormats[format]) {
- // Execute callbacks
- each(callbacks, function(callback) {
- callback(true, {node: node, format: format, parents: parents});
- });
-
- currentFormats[format] = callbacks;
- }
-
- matchedFormats[format] = callbacks;
- return false;
- }
- });
- });
-
- // Check if current formats still match
- each(currentFormats, function(callbacks, format) {
- if (!matchedFormats[format]) {
- delete currentFormats[format];
-
- each(callbacks, function(callback) {
- callback(false, {node: e.element, format: format, parents: parents});
- });
- }
- });
- });
- }
-
- // Add format listeners
- each(formats.split(','), function(format) {
- if (!formatChangeData[format]) {
- formatChangeData[format] = [];
- formatChangeData[format].similar = similar;
- }
-
- formatChangeData[format].push(callback);
- });
-
- return this;
- }
-
- // Expose to public
- extend(this, {
- get: get,
- register: register,
- apply: apply,
- remove: remove,
- toggle: toggle,
- match: match,
- matchAll: matchAll,
- matchNode: matchNode,
- canApply: canApply,
- formatChanged: formatChanged
- });
-
- // Initialize
- defaultFormats();
- addKeyboardShortcuts();
- ed.on('BeforeGetContent', function() {
- if (markCaretContainersBogus) {
- markCaretContainersBogus();
- }
- });
- ed.on('mouseup keydown', function(e) {
- if (disableCaretContainer) {
- disableCaretContainer(e);
- }
- });
-
- // Private functions
-
- /**
- * Checks if the specified nodes name matches the format inline/block or selector.
- *
- * @private
- * @param {Node} node Node to match against the specified format.
- * @param {Object} format Format object o match with.
- * @return {boolean} true/false if the format matches.
- */
- function matchName(node, format) {
- // Check for inline match
- if (isEq(node, format.inline)) {
- return TRUE;
- }
-
- // Check for block match
- if (isEq(node, format.block)) {
- return TRUE;
- }
-
- // Check for selector match
- if (format.selector) {
- return node.nodeType == 1 && dom.is(node, format.selector);
- }
- }
-
- /**
- * Compares two string/nodes regardless of their case.
- *
- * @private
- * @param {String/Node} Node or string to compare.
- * @param {String/Node} Node or string to compare.
- * @return {boolean} True/false if they match.
- */
- function isEq(str1, str2) {
- str1 = str1 || '';
- str2 = str2 || '';
-
- str1 = '' + (str1.nodeName || str1);
- str2 = '' + (str2.nodeName || str2);
-
- return str1.toLowerCase() == str2.toLowerCase();
- }
-
- /**
- * Returns the style by name on the specified node. This method modifies the style
- * contents to make it more easy to match. This will resolve a few browser issues.
- *
- * @private
- * @param {Node} node to get style from.
- * @param {String} name Style name to get.
- * @return {String} Style item value.
- */
- function getStyle(node, name) {
- return normalizeStyleValue(dom.getStyle(node, name), name);
- }
-
- /**
- * Normalize style value by name. This method modifies the style contents
- * to make it more easy to match. This will resolve a few browser issues.
- *
- * @private
- * @param {Node} node to get style from.
- * @param {String} name Style name to get.
- * @return {String} Style item value.
- */
- function normalizeStyleValue(value, name) {
- // Force the format to hex
- if (name == 'color' || name == 'backgroundColor') {
- value = dom.toHex(value);
- }
-
- // Opera will return bold as 700
- if (name == 'fontWeight' && value == 700) {
- value = 'bold';
- }
-
- // Normalize fontFamily so "'Font name', Font" becomes: "Font name,Font"
- if (name == 'fontFamily') {
- value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
- }
-
- return '' + value;
- }
-
- /**
- * Replaces variables in the value. The variable format is %var.
- *
- * @private
- * @param {String} value Value to replace variables in.
- * @param {Object} vars Name/value array with variables to replace.
- * @return {String} New value with replaced variables.
- */
- function replaceVars(value, vars) {
- if (typeof(value) != "string") {
- value = value(vars);
- } else if (vars) {
- value = value.replace(/%(\w+)/g, function(str, name) {
- return vars[name] || str;
- });
- }
-
- return value;
- }
-
- function isWhiteSpaceNode(node) {
- return node && node.nodeType === 3 && /^([\t \r\n]+|)$/.test(node.nodeValue);
- }
-
- function wrap(node, name, attrs) {
- var wrapper = dom.create(name, attrs);
-
- node.parentNode.insertBefore(wrapper, node);
- wrapper.appendChild(node);
-
- return wrapper;
- }
-
- /**
- * Expands the specified range like object to depending on format.
- *
- * For example on block formats it will move the start/end position
- * to the beginning of the current block.
- *
- * @private
- * @param {Object} rng Range like object.
- * @param {Array} formats Array with formats to expand by.
- * @return {Object} Expanded range like object.
- */
- function expandRng(rng, format, remove) {
- var lastIdx, leaf, endPoint,
- startContainer = rng.startContainer,
- startOffset = rng.startOffset,
- endContainer = rng.endContainer,
- endOffset = rng.endOffset;
-
- // This function walks up the tree if there is no siblings before/after the node
- function findParentContainer(start) {
- var container, parent, sibling, siblingName, root;
-
- container = parent = start ? startContainer : endContainer;
- siblingName = start ? 'previousSibling' : 'nextSibling';
- root = dom.getRoot();
-
- function isBogusBr(node) {
- return node.nodeName == "BR" && node.getAttribute('data-mce-bogus') && !node.nextSibling;
- }
-
- // If it's a text node and the offset is inside the text
- if (container.nodeType == 3 && !isWhiteSpaceNode(container)) {
- if (start ? startOffset > 0 : endOffset < container.nodeValue.length) {
- return container;
- }
- }
-
- /*eslint no-constant-condition:0 */
- while (true) {
- // Stop expanding on block elements
- if (!format[0].block_expand && isBlock(parent)) {
- return parent;
- }
-
- // Walk left/right
- for (sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
- if (!isBookmarkNode(sibling) && !isWhiteSpaceNode(sibling) && !isBogusBr(sibling)) {
- return parent;
- }
- }
-
- // Check if we can move up are we at root level or body level
- if (parent.parentNode == root) {
- container = parent;
- break;
- }
-
- parent = parent.parentNode;
- }
-
- return container;
- }
-
- // This function walks down the tree to find the leaf at the selection.
- // The offset is also returned as if node initially a leaf, the offset may be in the middle of the text node.
- function findLeaf(node, offset) {
- if (offset === undef) {
- offset = node.nodeType === 3 ? node.length : node.childNodes.length;
- }
-
- while (node && node.hasChildNodes()) {
- node = node.childNodes[offset];
- if (node) {
- offset = node.nodeType === 3 ? node.length : node.childNodes.length;
- }
- }
- return { node: node, offset: offset };
- }
-
- // If index based start position then resolve it
- if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) {
- lastIdx = startContainer.childNodes.length - 1;
- startContainer = startContainer.childNodes[startOffset > lastIdx ? lastIdx : startOffset];
-
- if (startContainer.nodeType == 3) {
- startOffset = 0;
- }
- }
-
- // If index based end position then resolve it
- if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) {
- lastIdx = endContainer.childNodes.length - 1;
- endContainer = endContainer.childNodes[endOffset > lastIdx ? lastIdx : endOffset - 1];
-
- if (endContainer.nodeType == 3) {
- endOffset = endContainer.nodeValue.length;
- }
- }
-
- // Expands the node to the closes contentEditable false element if it exists
- function findParentContentEditable(node) {
- var parent = node;
-
- while (parent) {
- if (parent.nodeType === 1 && getContentEditable(parent)) {
- return getContentEditable(parent) === "false" ? parent : node;
- }
-
- parent = parent.parentNode;
- }
-
- return node;
- }
-
- function findWordEndPoint(container, offset, start) {
- var walker, node, pos, lastTextNode;
-
- function findSpace(node, offset) {
- var pos, pos2, str = node.nodeValue;
-
- if (typeof(offset) == "undefined") {
- offset = start ? str.length : 0;
- }
-
- if (start) {
- pos = str.lastIndexOf(' ', offset);
- pos2 = str.lastIndexOf('\u00a0', offset);
- pos = pos > pos2 ? pos : pos2;
-
- // Include the space on remove to avoid tag soup
- if (pos !== -1 && !remove) {
- pos++;
- }
- } else {
- pos = str.indexOf(' ', offset);
- pos2 = str.indexOf('\u00a0', offset);
- pos = pos !== -1 && (pos2 === -1 || pos < pos2) ? pos : pos2;
- }
-
- return pos;
- }
-
- if (container.nodeType === 3) {
- pos = findSpace(container, offset);
-
- if (pos !== -1) {
- return {container: container, offset: pos};
- }
-
- lastTextNode = container;
- }
-
- // Walk the nodes inside the block
- walker = new TreeWalker(container, dom.getParent(container, isBlock) || ed.getBody());
- while ((node = walker[start ? 'prev' : 'next']())) {
- if (node.nodeType === 3) {
- lastTextNode = node;
- pos = findSpace(node);
-
- if (pos !== -1) {
- return {container: node, offset: pos};
- }
- } else if (isBlock(node)) {
- break;
- }
- }
-
- if (lastTextNode) {
- if (start) {
- offset = 0;
- } else {
- offset = lastTextNode.length;
- }
-
- return {container: lastTextNode, offset: offset};
- }
- }
-
- function findSelectorEndPoint(container, sibling_name) {
- var parents, i, y, curFormat;
-
- if (container.nodeType == 3 && container.nodeValue.length === 0 && container[sibling_name]) {
- container = container[sibling_name];
- }
-
- parents = getParents(container);
- for (i = 0; i < parents.length; i++) {
- for (y = 0; y < format.length; y++) {
- curFormat = format[y];
-
- // If collapsed state is set then skip formats that doesn't match that
- if ("collapsed" in curFormat && curFormat.collapsed !== rng.collapsed) {
- continue;
- }
-
- if (dom.is(parents[i], curFormat.selector)) {
- return parents[i];
- }
- }
- }
-
- return container;
- }
-
- function findBlockEndPoint(container, sibling_name) {
- var node, root = dom.getRoot();
-
- // Expand to block of similar type
- if (!format[0].wrapper) {
- node = dom.getParent(container, format[0].block, root);
- }
-
- // Expand to first wrappable block element or any block element
- if (!node) {
- node = dom.getParent(container.nodeType == 3 ? container.parentNode : container, function(node) {
- // Fixes #6183 where it would expand to editable parent element in inline mode
- return node != root && isTextBlock(node);
- });
- }
-
- // Exclude inner lists from wrapping
- if (node && format[0].wrapper) {
- node = getParents(node, 'ul,ol').reverse()[0] || node;
- }
-
- // Didn't find a block element look for first/last wrappable element
- if (!node) {
- node = container;
-
- while (node[sibling_name] && !isBlock(node[sibling_name])) {
- node = node[sibling_name];
-
- // Break on BR but include it will be removed later on
- // we can't remove it now since we need to check if it can be wrapped
- if (isEq(node, 'br')) {
- break;
- }
- }
- }
-
- return node || container;
- }
-
- // Expand to closest contentEditable element
- startContainer = findParentContentEditable(startContainer);
- endContainer = findParentContentEditable(endContainer);
-
- // Exclude bookmark nodes if possible
- if (isBookmarkNode(startContainer.parentNode) || isBookmarkNode(startContainer)) {
- startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
- startContainer = startContainer.nextSibling || startContainer;
-
- if (startContainer.nodeType == 3) {
- startOffset = 0;
- }
- }
-
- if (isBookmarkNode(endContainer.parentNode) || isBookmarkNode(endContainer)) {
- endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
- endContainer = endContainer.previousSibling || endContainer;
-
- if (endContainer.nodeType == 3) {
- endOffset = endContainer.length;
- }
- }
-
- if (format[0].inline) {
- if (rng.collapsed) {
- // Expand left to closest word boundary
- endPoint = findWordEndPoint(startContainer, startOffset, true);
- if (endPoint) {
- startContainer = endPoint.container;
- startOffset = endPoint.offset;
- }
-
- // Expand right to closest word boundary
- endPoint = findWordEndPoint(endContainer, endOffset);
- if (endPoint) {
- endContainer = endPoint.container;
- endOffset = endPoint.offset;
- }
- }
-
- // Avoid applying formatting to a trailing space.
- leaf = findLeaf(endContainer, endOffset);
- if (leaf.node) {
- while (leaf.node && leaf.offset === 0 && leaf.node.previousSibling) {
- leaf = findLeaf(leaf.node.previousSibling);
- }
-
- if (leaf.node && leaf.offset > 0 && leaf.node.nodeType === 3 &&
- leaf.node.nodeValue.charAt(leaf.offset - 1) === ' ') {
-
- if (leaf.offset > 1) {
- endContainer = leaf.node;
- endContainer.splitText(leaf.offset - 1);
- }
- }
- }
- }
-
- // Move start/end point up the tree if the leaves are sharp and if we are in different containers
- // Example * becomes !: !
text
text
text
- *
- * @private
- * @param {Node} node Node to remove + apply BR/P elements to.
- * @param {Object} format Format rule.
- * @return {Node} Input node.
- */
- function removeNode(node, format) {
- var parentNode = node.parentNode, rootBlockElm;
-
- function find(node, next, inc) {
- node = getNonWhiteSpaceSibling(node, next, inc);
-
- return !node || (node.nodeName == 'BR' || isBlock(node));
- }
-
- if (format.block) {
- if (!forcedRootBlock) {
- // Append BR elements if needed before we remove the block
- if (isBlock(node) && !isBlock(parentNode)) {
- if (!find(node, FALSE) && !find(node.firstChild, TRUE, 1)) {
- node.insertBefore(dom.create('br'), node.firstChild);
- }
-
- if (!find(node, TRUE) && !find(node.lastChild, FALSE, 1)) {
- node.appendChild(dom.create('br'));
- }
- }
- } else {
- // Wrap the block in a forcedRootBlock if we are at the root of document
- if (parentNode == dom.getRoot()) {
- if (!format.list_block || !isEq(node, format.list_block)) {
- each(grep(node.childNodes), function(node) {
- if (isValid(forcedRootBlock, node.nodeName.toLowerCase())) {
- if (!rootBlockElm) {
- rootBlockElm = wrap(node, forcedRootBlock);
- dom.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
- } else {
- rootBlockElm.appendChild(node);
- }
- } else {
- rootBlockElm = 0;
- }
- });
- }
- }
- }
- }
-
- // Never remove nodes that isn't the specified inline element if a selector is specified too
- if (format.selector && format.inline && !isEq(format.inline, node)) {
- return;
- }
-
- dom.remove(node, 1);
- }
-
- /**
- * Returns the next/previous non whitespace node.
- *
- * @private
- * @param {Node} node Node to start at.
- * @param {boolean} next (Optional) Include next or previous node defaults to previous.
- * @param {boolean} inc (Optional) Include the current node in checking. Defaults to false.
- * @return {Node} Next or previous node or undefined if it wasn't found.
- */
- function getNonWhiteSpaceSibling(node, next, inc) {
- if (node) {
- next = next ? 'nextSibling' : 'previousSibling';
-
- for (node = inc ? node : node[next]; node; node = node[next]) {
- if (node.nodeType == 1 || !isWhiteSpaceNode(node)) {
- return node;
- }
- }
- }
- }
-
- /**
- * Checks if the specified node is a bookmark node or not.
- *
- * @private
- * @param {Node} node Node to check if it's a bookmark node or not.
- * @return {Boolean} true/false if the node is a bookmark node.
- */
- function isBookmarkNode(node) {
- return node && node.nodeType == 1 && node.getAttribute('data-mce-type') == 'bookmark';
- }
-
- /**
- * Merges the next/previous sibling element if they match.
- *
- * @private
- * @param {Node} prev Previous node to compare/merge.
- * @param {Node} next Next node to compare/merge.
- * @return {Node} Next node if we didn't merge and prev node if we did.
- */
- function mergeSiblings(prev, next) {
- var sibling, tmpSibling;
-
- /**
- * Compares two nodes and checks if it's attributes and styles matches.
- * This doesn't compare classes as items since their order is significant.
- *
- * @private
- * @param {Node} node1 First node to compare with.
- * @param {Node} node2 Second node to compare with.
- * @return {boolean} True/false if the nodes are the same or not.
- */
- function compareElements(node1, node2) {
- // Not the same name
- if (node1.nodeName != node2.nodeName) {
- return FALSE;
- }
-
- /**
- * Returns all the nodes attributes excluding internal ones, styles and classes.
- *
- * @private
- * @param {Node} node Node to get attributes from.
- * @return {Object} Name/value object with attributes and attribute values.
- */
- function getAttribs(node) {
- var attribs = {};
-
- each(dom.getAttribs(node), function(attr) {
- var name = attr.nodeName.toLowerCase();
-
- // Don't compare internal attributes or style
- if (name.indexOf('_') !== 0 && name !== 'style' && name !== 'data-mce-style') {
- attribs[name] = dom.getAttrib(node, name);
- }
- });
-
- return attribs;
- }
-
- /**
- * Compares two objects checks if it's key + value exists in the other one.
- *
- * @private
- * @param {Object} obj1 First object to compare.
- * @param {Object} obj2 Second object to compare.
- * @return {boolean} True/false if the objects matches or not.
- */
- function compareObjects(obj1, obj2) {
- var value, name;
-
- for (name in obj1) {
- // Obj1 has item obj2 doesn't have
- if (obj1.hasOwnProperty(name)) {
- value = obj2[name];
-
- // Obj2 doesn't have obj1 item
- if (value === undef) {
- return FALSE;
- }
-
- // Obj2 item has a different value
- if (obj1[name] != value) {
- return FALSE;
- }
-
- // Delete similar value
- delete obj2[name];
- }
- }
-
- // Check if obj 2 has something obj 1 doesn't have
- for (name in obj2) {
- // Obj2 has item obj1 doesn't have
- if (obj2.hasOwnProperty(name)) {
- return FALSE;
- }
- }
-
- return TRUE;
- }
-
- // Attribs are not the same
- if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
- return FALSE;
- }
-
- // Styles are not the same
- if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
- return FALSE;
- }
-
- return !isBookmarkNode(node1) && !isBookmarkNode(node2);
- }
-
- function findElementSibling(node, sibling_name) {
- for (sibling = node; sibling; sibling = sibling[sibling_name]) {
- if (sibling.nodeType == 3 && sibling.nodeValue.length !== 0) {
- return node;
- }
-
- if (sibling.nodeType == 1 && !isBookmarkNode(sibling)) {
- return sibling;
- }
- }
-
- return node;
- }
-
- // Check if next/prev exists and that they are elements
- if (prev && next) {
- // If previous sibling is empty then jump over it
- prev = findElementSibling(prev, 'previousSibling');
- next = findElementSibling(next, 'nextSibling');
-
- // Compare next and previous nodes
- if (compareElements(prev, next)) {
- // Append nodes between
- for (sibling = prev.nextSibling; sibling && sibling != next;) {
- tmpSibling = sibling;
- sibling = sibling.nextSibling;
- prev.appendChild(tmpSibling);
- }
-
- // Remove next node
- dom.remove(next);
-
- // Move children into prev node
- each(grep(next.childNodes), function(node) {
- prev.appendChild(node);
- });
-
- return prev;
- }
- }
-
- return next;
- }
-
- function getContainer(rng, start) {
- var container, offset, lastIdx;
-
- container = rng[start ? 'startContainer' : 'endContainer'];
- offset = rng[start ? 'startOffset' : 'endOffset'];
-
- if (container.nodeType == 1) {
- lastIdx = container.childNodes.length - 1;
-
- if (!start && offset) {
- offset--;
- }
-
- container = container.childNodes[offset > lastIdx ? lastIdx : offset];
- }
-
- // If start text node is excluded then walk to the next node
- if (container.nodeType === 3 && start && offset >= container.nodeValue.length) {
- container = new TreeWalker(container, ed.getBody()).next() || container;
- }
-
- // If end text node is excluded then walk to the previous node
- if (container.nodeType === 3 && !start && offset === 0) {
- container = new TreeWalker(container, ed.getBody()).prev() || container;
- }
-
- return container;
- }
-
- function performCaretAction(type, name, vars) {
- var caretContainerId = '_mce_caret', debug = ed.settings.caret_debug;
-
- // Creates a caret container bogus element
- function createCaretContainer(fill) {
- var caretContainer = dom.create('span', {id: caretContainerId, 'data-mce-bogus': true, style: debug ? 'color:red' : ''});
-
- if (fill) {
- caretContainer.appendChild(ed.getDoc().createTextNode(INVISIBLE_CHAR));
- }
-
- return caretContainer;
- }
-
- function isCaretContainerEmpty(node, nodes) {
- while (node) {
- if ((node.nodeType === 3 && node.nodeValue !== INVISIBLE_CHAR) || node.childNodes.length > 1) {
- return false;
- }
-
- // Collect nodes
- if (nodes && node.nodeType === 1) {
- nodes.push(node);
- }
-
- node = node.firstChild;
- }
-
- return true;
- }
-
- // Returns any parent caret container element
- function getParentCaretContainer(node) {
- while (node) {
- if (node.id === caretContainerId) {
- return node;
- }
-
- node = node.parentNode;
- }
- }
-
- // Finds the first text node in the specified node
- function findFirstTextNode(node) {
- var walker;
-
- if (node) {
- walker = new TreeWalker(node, node);
-
- for (node = walker.current(); node; node = walker.next()) {
- if (node.nodeType === 3) {
- return node;
- }
- }
- }
- }
-
- // Removes the caret container for the specified node or all on the current document
- function removeCaretContainer(node, move_caret) {
- var child, rng;
-
- if (!node) {
- node = getParentCaretContainer(selection.getStart());
-
- if (!node) {
- while ((node = dom.get(caretContainerId))) {
- removeCaretContainer(node, false);
- }
- }
- } else {
- rng = selection.getRng(true);
-
- if (isCaretContainerEmpty(node)) {
- if (move_caret !== false) {
- rng.setStartBefore(node);
- rng.setEndBefore(node);
- }
-
- dom.remove(node);
- } else {
- child = findFirstTextNode(node);
-
- if (child.nodeValue.charAt(0) === INVISIBLE_CHAR) {
- child = child.deleteData(0, 1);
- }
-
- dom.remove(node, 1);
- }
-
- selection.setRng(rng);
- }
- }
-
- // Applies formatting to the caret postion
- function applyCaretFormat() {
- var rng, caretContainer, textNode, offset, bookmark, container, text;
-
- rng = selection.getRng(true);
- offset = rng.startOffset;
- container = rng.startContainer;
- text = container.nodeValue;
-
- caretContainer = getParentCaretContainer(selection.getStart());
- if (caretContainer) {
- textNode = findFirstTextNode(caretContainer);
- }
-
- // Expand to word is caret is in the middle of a text node and the char before/after is a alpha numeric character
- if (text && offset > 0 && offset < text.length && /\w/.test(text.charAt(offset)) && /\w/.test(text.charAt(offset - 1))) {
- // Get bookmark of caret position
- bookmark = selection.getBookmark();
-
- // Collapse bookmark range (WebKit)
- rng.collapse(true);
-
- // Expand the range to the closest word and split it at those points
- rng = expandRng(rng, get(name));
- rng = rangeUtils.split(rng);
-
- // Apply the format to the range
- apply(name, vars, rng);
-
- // Move selection back to caret position
- selection.moveToBookmark(bookmark);
- } else {
- if (!caretContainer || textNode.nodeValue !== INVISIBLE_CHAR) {
- caretContainer = createCaretContainer(true);
- textNode = caretContainer.firstChild;
-
- rng.insertNode(caretContainer);
- offset = 1;
-
- apply(name, vars, caretContainer);
- } else {
- apply(name, vars, caretContainer);
- }
-
- // Move selection to text node
- selection.setCursorLocation(textNode, offset);
- }
- }
-
- function removeCaretFormat() {
- var rng = selection.getRng(true), container, offset, bookmark,
- hasContentAfter, node, formatNode, parents = [], i, caretContainer;
-
- container = rng.startContainer;
- offset = rng.startOffset;
- node = container;
-
- if (container.nodeType == 3) {
- if (offset != container.nodeValue.length || container.nodeValue === INVISIBLE_CHAR) {
- hasContentAfter = true;
- }
-
- node = node.parentNode;
- }
-
- while (node) {
- if (matchNode(node, name, vars)) {
- formatNode = node;
- break;
- }
-
- if (node.nextSibling) {
- hasContentAfter = true;
- }
-
- parents.push(node);
- node = node.parentNode;
- }
-
- // Node doesn't have the specified format
- if (!formatNode) {
- return;
- }
-
- // Is there contents after the caret then remove the format on the element
- if (hasContentAfter) {
- // Get bookmark of caret position
- bookmark = selection.getBookmark();
-
- // Collapse bookmark range (WebKit)
- rng.collapse(true);
-
- // Expand the range to the closest word and split it at those points
- rng = expandRng(rng, get(name), true);
- rng = rangeUtils.split(rng);
-
- // Remove the format from the range
- remove(name, vars, rng);
-
- // Move selection back to caret position
- selection.moveToBookmark(bookmark);
- } else {
- caretContainer = createCaretContainer();
-
- node = caretContainer;
- for (i = parents.length - 1; i >= 0; i--) {
- node.appendChild(dom.clone(parents[i], false));
- node = node.firstChild;
- }
-
- // Insert invisible character into inner most format element
- node.appendChild(dom.doc.createTextNode(INVISIBLE_CHAR));
- node = node.firstChild;
-
- var block = dom.getParent(formatNode, isTextBlock);
-
- if (block && dom.isEmpty(block)) {
- // Replace formatNode with caretContainer when removing format from empty block like
' + html;
- element.removeChild(element.firstChild);
- } catch (ex) {
- // IE sometimes produces an unknown runtime error on innerHTML if it's a block element
- // within a block element for example a div inside a p
- // This seems to fix this problem
-
- // Create new div with HTML contents and a BR in front to keep comments
- var newElement = self.create('div');
- newElement.innerHTML = '
' + html;
-
- // Add all children from div to target
- each(grep(newElement.childNodes), function(node, i) {
- // Skip br element
- if (i && element.canHaveHTML) {
- element.appendChild(node);
- }
- });
- }
- } else {
- element.innerHTML = html;
- }
-
- return html;
- });
- },
-
- /**
- * Returns the outer HTML of an element.
- *
- * @method getOuterHTML
- * @param {String/Element} elm Element ID or element object to get outer HTML from.
- * @return {String} Outer HTML string.
- * @example
- * tinymce.DOM.getOuterHTML(editorElement);
- * tinymce.activeEditor.getOuterHTML(tinymce.activeEditor.getBody());
- */
- getOuterHTML: function(elm) {
- var doc, self = this;
-
- elm = self.get(elm);
-
- if (!elm) {
- return null;
- }
-
- if (elm.nodeType === 1 && self.hasOuterHTML) {
- return elm.outerHTML;
- }
-
- doc = (elm.ownerDocument || self.doc).createElement("body");
- doc.appendChild(elm.cloneNode(true));
-
- return doc.innerHTML;
- },
-
- /**
- * Sets the specified outer HTML on an element or elements.
- *
- * @method setOuterHTML
- * @param {Element/String/Array} elm DOM element, element id string or array of elements/ids to set outer HTML on.
- * @param {Object} html HTML code to set as outer value for the element.
- * @param {Document} doc Optional document scope to use in this process - defaults to the document of the DOM class.
- * @example
- * // Sets the outer HTML of all paragraphs in the active editor
- * tinymce.activeEditor.dom.setOuterHTML(tinymce.activeEditor.dom.select('p'), '
- name = node.nodeName.toLowerCase();
- if (elements && elements[name]) {
- // Ignore single BR elements in blocks like
|
- // Becomes: |
- // Seems that only gecko has issues with this.
- // Special edge case for
' + (rng.item ? rng.item(0).outerHTML : rng.htmlText);
- tmpElm.removeChild(tmpElm.firstChild);
- } else {
- tmpElm.innerHTML = rng.toString();
- }
-
- // Keep whitespace before and after
- if (/^\s/.test(tmpElm.innerHTML)) {
- whiteSpaceBefore = ' ';
- }
-
- if (/\s+$/.test(tmpElm.innerHTML)) {
- whiteSpaceAfter = ' ';
- }
-
- args.getInner = true;
-
- args.content = self.isCollapsed() ? '' : whiteSpaceBefore + self.serializer.serialize(tmpElm, args) + whiteSpaceAfter;
- self.editor.fire('GetContent', args);
-
- return args.content;
- },
-
- /**
- * Sets the current selection to the specified content. If any contents is selected it will be replaced
- * with the contents passed in to this function. If there is no selection the contents will be inserted
- * where the caret is placed in the editor/page.
- *
- * @method setContent
- * @param {String} content HTML contents to set could also be other formats depending on settings.
- * @param {Object} args Optional settings object with for example data format.
- * @example
- * // Inserts some HTML contents at the current selection
- * tinymce.activeEditor.selection.setContent('Some contents');
- */
- setContent: function(content, args) {
- var self = this, rng = self.getRng(), caretNode, doc = self.win.document, frag, temp;
-
- args = args || {format: 'html'};
- args.set = true;
- args.selection = true;
- content = args.content = content;
-
- // Dispatch before set content event
- if (!args.no_events) {
- self.editor.fire('BeforeSetContent', args);
- }
-
- content = args.content;
-
- if (rng.insertNode) {
- // Make caret marker since insertNode places the caret in the beginning of text after insert
- content += '_';
-
- // Delete and insert new node
- if (rng.startContainer == doc && rng.endContainer == doc) {
- // WebKit will fail if the body is empty since the range is then invalid and it can't insert contents
- doc.body.innerHTML = content;
- } else {
- rng.deleteContents();
-
- if (doc.body.childNodes.length === 0) {
- doc.body.innerHTML = content;
- } else {
- // createContextualFragment doesn't exists in IE 9 DOMRanges
- if (rng.createContextualFragment) {
- rng.insertNode(rng.createContextualFragment(content));
- } else {
- // Fake createContextualFragment call in IE 9
- frag = doc.createDocumentFragment();
- temp = doc.createElement('div');
-
- frag.appendChild(temp);
- temp.outerHTML = content;
-
- rng.insertNode(frag);
- }
- }
- }
-
- // Move to caret marker
- caretNode = self.dom.get('__caret');
-
- // Make sure we wrap it compleatly, Opera fails with a simple select call
- rng = doc.createRange();
- rng.setStartBefore(caretNode);
- rng.setEndBefore(caretNode);
- self.setRng(rng);
-
- // Remove the caret position
- self.dom.remove('__caret');
-
- try {
- self.setRng(rng);
- } catch (ex) {
- // Might fail on Opera for some odd reason
- }
- } else {
- if (rng.item) {
- // Delete content and get caret text selection
- doc.execCommand('Delete', false, null);
- rng = self.getRng();
- }
-
- // Explorer removes spaces from the beginning of pasted contents
- if (/^\s+/.test(content)) {
- rng.pasteHTML('_' + content);
- self.dom.remove('__mce_tmp');
- } else {
- rng.pasteHTML(content);
- }
- }
-
- // Dispatch set content event
- if (!args.no_events) {
- self.editor.fire('SetContent', args);
- }
- },
-
- /**
- * Returns the start element of a selection range. If the start is in a text
- * node the parent element will be returned.
- *
- * @method getStart
- * @return {Element} Start element of selection range.
- */
- getStart: function() {
- var self = this, rng = self.getRng(), startElement, parentElement, checkRng, node;
-
- if (rng.duplicate || rng.item) {
- // Control selection, return first item
- if (rng.item) {
- return rng.item(0);
- }
-
- // Get start element
- checkRng = rng.duplicate();
- checkRng.collapse(1);
- startElement = checkRng.parentElement();
- if (startElement.ownerDocument !== self.dom.doc) {
- startElement = self.dom.getRoot();
- }
-
- // Check if range parent is inside the start element, then return the inner parent element
- // This will fix issues when a single element is selected, IE would otherwise return the wrong start element
- parentElement = node = rng.parentElement();
- while ((node = node.parentNode)) {
- if (node == startElement) {
- startElement = parentElement;
- break;
- }
- }
-
- return startElement;
- } else {
- startElement = rng.startContainer;
-
- if (startElement.nodeType == 1 && startElement.hasChildNodes()) {
- startElement = startElement.childNodes[Math.min(startElement.childNodes.length - 1, rng.startOffset)];
- }
-
- if (startElement && startElement.nodeType == 3) {
- return startElement.parentNode;
- }
-
- return startElement;
- }
- },
-
- /**
- * Returns the end element of a selection range. If the end is in a text
- * node the parent element will be returned.
- *
- * @method getEnd
- * @return {Element} End element of selection range.
- */
- getEnd: function() {
- var self = this, rng = self.getRng(), endElement, endOffset;
-
- if (rng.duplicate || rng.item) {
- if (rng.item) {
- return rng.item(0);
- }
-
- rng = rng.duplicate();
- rng.collapse(0);
- endElement = rng.parentElement();
- if (endElement.ownerDocument !== self.dom.doc) {
- endElement = self.dom.getRoot();
- }
-
- if (endElement && endElement.nodeName == 'BODY') {
- return endElement.lastChild || endElement;
- }
-
- return endElement;
- } else {
- endElement = rng.endContainer;
- endOffset = rng.endOffset;
-
- if (endElement.nodeType == 1 && endElement.hasChildNodes()) {
- endElement = endElement.childNodes[endOffset > 0 ? endOffset - 1 : endOffset];
- }
-
- if (endElement && endElement.nodeType == 3) {
- return endElement.parentNode;
- }
-
- return endElement;
- }
- },
-
- /**
- * Returns a bookmark location for the current selection. This bookmark object
- * can then be used to restore the selection after some content modification to the document.
- *
- * @method getBookmark
- * @param {Number} type Optional state if the bookmark should be simple or not. Default is complex.
- * @param {Boolean} normalized Optional state that enables you to get a position that it would be after normalization.
- * @return {Object} Bookmark object, use moveToBookmark with this object to restore the selection.
- * @example
- * // Stores a bookmark of the current selection
- * var bm = tinymce.activeEditor.selection.getBookmark();
- *
- * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content');
- *
- * // Restore the selection bookmark
- * tinymce.activeEditor.selection.moveToBookmark(bm);
- */
- getBookmark: function(type, normalized) {
- var self = this, dom = self.dom, rng, rng2, id, collapsed, name, element, chr = '', styles;
-
- function findIndex(name, element) {
- var index = 0;
-
- each(dom.select(name), function(node, i) {
- if (node == element) {
- index = i;
- }
- });
-
- return index;
- }
-
- function normalizeTableCellSelection(rng) {
- function moveEndPoint(start) {
- var container, offset, childNodes, prefix = start ? 'start' : 'end';
-
- container = rng[prefix + 'Container'];
- offset = rng[prefix + 'Offset'];
-
- if (container.nodeType == 1 && container.nodeName == "TR") {
- childNodes = container.childNodes;
- container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
- if (container) {
- offset = start ? 0 : container.childNodes.length;
- rng['set' + (start ? 'Start' : 'End')](container, offset);
- }
- }
- }
-
- moveEndPoint(true);
- moveEndPoint();
-
- return rng;
- }
-
- function getLocation() {
- var rng = self.getRng(true), root = dom.getRoot(), bookmark = {};
-
- function getPoint(rng, start) {
- var container = rng[start ? 'startContainer' : 'endContainer'],
- offset = rng[start ? 'startOffset' : 'endOffset'], point = [], node, childNodes, after = 0;
-
- if (container.nodeType == 3) {
- if (normalized) {
- for (node = container.previousSibling; node && node.nodeType == 3; node = node.previousSibling) {
- offset += node.nodeValue.length;
- }
- }
-
- point.push(offset);
- } else {
- childNodes = container.childNodes;
-
- if (offset >= childNodes.length && childNodes.length) {
- after = 1;
- offset = Math.max(0, childNodes.length - 1);
- }
-
- point.push(self.dom.nodeIndex(childNodes[offset], normalized) + after);
- }
-
- for (; container && container != root; container = container.parentNode) {
- point.push(self.dom.nodeIndex(container, normalized));
- }
-
- return point;
- }
-
- bookmark.start = getPoint(rng, true);
-
- if (!self.isCollapsed()) {
- bookmark.end = getPoint(rng);
- }
-
- return bookmark;
- }
-
- if (type == 2) {
- element = self.getNode();
- name = element ? element.nodeName : null;
-
- if (name == 'IMG') {
- return {name: name, index: findIndex(name, element)};
- }
-
- if (self.tridentSel) {
- return self.tridentSel.getBookmark(type);
- }
-
- return getLocation();
- }
-
- // Handle simple range
- if (type) {
- return {rng: self.getRng()};
- }
-
- rng = self.getRng();
- id = dom.uniqueId();
- collapsed = self.isCollapsed();
- styles = 'overflow:hidden;line-height:0px';
-
- // Explorer method
- if (rng.duplicate || rng.item) {
- // Text selection
- if (!rng.item) {
- rng2 = rng.duplicate();
-
- try {
- // Insert start marker
- rng.collapse();
- rng.pasteHTML('' + chr + '');
-
- // Insert end marker
- if (!collapsed) {
- rng2.collapse(false);
-
- // Detect the empty space after block elements in IE and move the
- // end back one character ] becomes
';
- }
-
- return node;
- }
-
- if (bookmark) {
- if (bookmark.start) {
- rng = dom.createRng();
- root = dom.getRoot();
-
- if (self.tridentSel) {
- return self.tridentSel.moveToBookmark(bookmark);
- }
-
- if (setEndPoint(true) && setEndPoint()) {
- self.setRng(rng);
- }
- } else if (bookmark.id) {
- // Restore start/end points
- restoreEndPoint('start');
- restoreEndPoint('end');
-
- if (startContainer) {
- rng = dom.createRng();
- rng.setStart(addBogus(startContainer), startOffset);
- rng.setEnd(addBogus(endContainer), endOffset);
- self.setRng(rng);
- }
- } else if (bookmark.name) {
- self.select(dom.select(bookmark.name)[bookmark.index]);
- } else if (bookmark.rng) {
- self.setRng(bookmark.rng);
- }
- }
- },
-
- /**
- * Selects the specified element. This will place the start and end of the selection range around the element.
- *
- * @method select
- * @param {Element} node HMTL DOM element to select.
- * @param {Boolean} content Optional bool state if the contents should be selected or not on non IE browser.
- * @return {Element} Selected element the same element as the one that got passed in.
- * @example
- * // Select the first paragraph in the active editor
- * tinymce.activeEditor.selection.select(tinymce.activeEditor.dom.select('p')[0]);
- */
- select: function(node, content) {
- var self = this, dom = self.dom, rng = dom.createRng(), idx;
-
- // Clear stored range set by FocusManager
- self.lastFocusBookmark = null;
-
- if (node) {
- if (!content && self.controlSelection.controlSelect(node)) {
- return;
- }
-
- idx = dom.nodeIndex(node);
- rng.setStart(node.parentNode, idx);
- rng.setEnd(node.parentNode, idx + 1);
-
- // Find first/last text node or BR element
- if (content) {
- self._moveEndPoint(rng, node, true);
- self._moveEndPoint(rng, node);
- }
-
- self.setRng(rng);
- }
-
- return node;
- },
-
- /**
- * Returns true/false if the selection range is collapsed or not. Collapsed means if it's a caret or a larger selection.
- *
- * @method isCollapsed
- * @return {Boolean} true/false state if the selection range is collapsed or not.
- * Collapsed means if it's a caret or a larger selection.
- */
- isCollapsed: function() {
- var self = this, rng = self.getRng(), sel = self.getSel();
-
- if (!rng || rng.item) {
- return false;
- }
-
- if (rng.compareEndPoints) {
- return rng.compareEndPoints('StartToEnd', rng) === 0;
- }
-
- return !sel || rng.collapsed;
- },
-
- /**
- * Collapse the selection to start or end of range.
- *
- * @method collapse
- * @param {Boolean} to_start Optional boolean state if to collapse to end or not. Defaults to start.
- */
- collapse: function(to_start) {
- var self = this, rng = self.getRng(), node;
-
- // Control range on IE
- if (rng.item) {
- node = rng.item(0);
- rng = self.win.document.body.createTextRange();
- rng.moveToElementText(node);
- }
-
- rng.collapse(!!to_start);
- self.setRng(rng);
- },
-
- /**
- * Returns the browsers internal selection object.
- *
- * @method getSel
- * @return {Selection} Internal browser selection object.
- */
- getSel: function() {
- var win = this.win;
-
- return win.getSelection ? win.getSelection() : win.document.selection;
- },
-
- /**
- * Returns the browsers internal range object.
- *
- * @method getRng
- * @param {Boolean} w3c Forces a compatible W3C range on IE.
- * @return {Range} Internal browser range object.
- * @see http://www.quirksmode.org/dom/range_intro.html
- * @see http://www.dotvoid.com/2001/03/using-the-range-object-in-mozilla/
- */
- getRng: function(w3c) {
- var self = this, selection, rng, elm, doc = self.win.document, ieRng;
-
- function tryCompareBounderyPoints(how, sourceRange, destinationRange) {
- try {
- return sourceRange.compareBoundaryPoints(how, destinationRange);
- } catch (ex) {
- // Gecko throws wrong document exception if the range points
- // to nodes that where removed from the dom #6690
- // Browsers should mutate existing DOMRange instances so that they always point
- // to something in the document this is not the case in Gecko works fine in IE/WebKit/Blink
- // For performance reasons just return -1
- return -1;
- }
- }
-
- // Use last rng passed from FocusManager if it's available this enables
- // calls to editor.selection.getStart() to work when caret focus is lost on IE
- if (!w3c && self.lastFocusBookmark) {
- var bookmark = self.lastFocusBookmark;
-
- // Convert bookmark to range IE 11 fix
- if (bookmark.startContainer) {
- rng = doc.createRange();
- rng.setStart(bookmark.startContainer, bookmark.startOffset);
- rng.setEnd(bookmark.endContainer, bookmark.endOffset);
- } else {
- rng = bookmark;
- }
-
- return rng;
- }
-
- // Found tridentSel object then we need to use that one
- if (w3c && self.tridentSel) {
- return self.tridentSel.getRangeAt(0);
- }
-
- try {
- if ((selection = self.getSel())) {
- if (selection.rangeCount > 0) {
- rng = selection.getRangeAt(0);
- } else {
- rng = selection.createRange ? selection.createRange() : doc.createRange();
- }
- }
- } catch (ex) {
- // IE throws unspecified error here if TinyMCE is placed in a frame/iframe
- }
-
- // We have W3C ranges and it's IE then fake control selection since IE9 doesn't handle that correctly yet
- // IE 11 doesn't support the selection object so we check for that as well
- if (isIE && rng && rng.setStart && doc.selection) {
- try {
- // IE will sometimes throw an exception here
- ieRng = doc.selection.createRange();
- } catch (ex) {
-
- }
-
- if (ieRng && ieRng.item) {
- elm = ieRng.item(0);
- rng = doc.createRange();
- rng.setStartBefore(elm);
- rng.setEndAfter(elm);
- }
- }
-
- // No range found then create an empty one
- // This can occur when the editor is placed in a hidden container element on Gecko
- // Or on IE when there was an exception
- if (!rng) {
- rng = doc.createRange ? doc.createRange() : doc.body.createTextRange();
- }
-
- // If range is at start of document then move it to start of body
- if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
- elm = self.dom.getRoot();
- rng.setStart(elm, 0);
- rng.setEnd(elm, 0);
- }
-
- if (self.selectedRange && self.explicitRange) {
- if (tryCompareBounderyPoints(rng.START_TO_START, rng, self.selectedRange) === 0 &&
- tryCompareBounderyPoints(rng.END_TO_END, rng, self.selectedRange) === 0) {
- // Safari, Opera and Chrome only ever select text which causes the range to change.
- // This lets us use the originally set range if the selection hasn't been changed by the user.
- rng = self.explicitRange;
- } else {
- self.selectedRange = null;
- self.explicitRange = null;
- }
- }
-
- return rng;
- },
-
- /**
- * Changes the selection to the specified DOM range.
- *
- * @method setRng
- * @param {Range} rng Range to select.
- */
- setRng: function(rng, forward) {
- var self = this, sel;
-
- // Is IE specific range
- if (rng.select) {
- try {
- rng.select();
- } catch (ex) {
- // Needed for some odd IE bug #1843306
- }
-
- return;
- }
-
- if (!self.tridentSel) {
- sel = self.getSel();
-
- if (sel) {
- self.explicitRange = rng;
-
- try {
- sel.removeAllRanges();
- sel.addRange(rng);
- } catch (ex) {
- // IE might throw errors here if the editor is within a hidden container and selection is changed
- }
-
- // Forward is set to false and we have an extend function
- if (forward === false && sel.extend) {
- sel.collapse(rng.endContainer, rng.endOffset);
- sel.extend(rng.startContainer, rng.startOffset);
- }
-
- // adding range isn't always successful so we need to check range count otherwise an exception can occur
- self.selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
- }
- } else {
- // Is W3C Range fake range on IE
- if (rng.cloneRange) {
- try {
- self.tridentSel.addRange(rng);
- return;
- } catch (ex) {
- //IE9 throws an error here if called before selection is placed in the editor
- }
- }
- }
- },
-
- /**
- * Sets the current selection to the specified DOM element.
- *
- * @method setNode
- * @param {Element} elm Element to set as the contents of the selection.
- * @return {Element} Returns the element that got passed in.
- * @example
- * // Inserts a DOM node at current selection/caret location
- * tinymce.activeEditor.selection.setNode(tinymce.activeEditor.dom.create('img', {src: 'some.gif', title: 'some title'}));
- */
- setNode: function(elm) {
- var self = this;
-
- self.setContent(self.dom.getOuterHTML(elm));
-
- return elm;
- },
-
- /**
- * Returns the currently selected element or the common ancestor element for both start and end of the selection.
- *
- * @method getNode
- * @return {Element} Currently selected element or common ancestor element.
- * @example
- * // Alerts the currently selected elements node name
- * alert(tinymce.activeEditor.selection.getNode().nodeName);
- */
- getNode: function() {
- var self = this, rng = self.getRng(), elm;
- var startContainer = rng.startContainer, endContainer = rng.endContainer;
- var startOffset = rng.startOffset, endOffset = rng.endOffset, root = self.dom.getRoot();
-
- function skipEmptyTextNodes(node, forwards) {
- var orig = node;
-
- while (node && node.nodeType === 3 && node.length === 0) {
- node = forwards ? node.nextSibling : node.previousSibling;
- }
-
- return node || orig;
- }
-
- // Range maybe lost after the editor is made visible again
- if (!rng) {
- return root;
- }
-
- if (rng.setStart) {
- elm = rng.commonAncestorContainer;
-
- // Handle selection a image or other control like element such as anchors
- if (!rng.collapsed) {
- if (startContainer == endContainer) {
- if (endOffset - startOffset < 2) {
- if (startContainer.hasChildNodes()) {
- elm = startContainer.childNodes[startOffset];
- }
- }
- }
-
- // If the anchor node is a element instead of a text node then return this element
- //if (tinymce.isWebKit && sel.anchorNode && sel.anchorNode.nodeType == 1)
- // return sel.anchorNode.childNodes[sel.anchorOffset];
-
- // Handle cases where the selection is immediately wrapped around a node and return that node instead of it's parent.
- // This happens when you double click an underlined word in FireFox.
- if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
- if (startContainer.length === startOffset) {
- startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
- } else {
- startContainer = startContainer.parentNode;
- }
-
- if (endOffset === 0) {
- endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
- } else {
- endContainer = endContainer.parentNode;
- }
-
- if (startContainer && startContainer === endContainer) {
- return startContainer;
- }
- }
- }
-
- if (elm && elm.nodeType == 3) {
- return elm.parentNode;
- }
-
- return elm;
- }
-
- elm = rng.item ? rng.item(0) : rng.parentElement();
-
- // IE 7 might return elements outside the iframe
- if (elm.ownerDocument !== self.win.document) {
- elm = root;
- }
-
- return elm;
- },
-
- getSelectedBlocks: function(startElm, endElm) {
- var self = this, dom = self.dom, node, root, selectedBlocks = [];
-
- root = dom.getRoot();
- startElm = dom.getParent(startElm || self.getStart(), dom.isBlock);
- endElm = dom.getParent(endElm || self.getEnd(), dom.isBlock);
-
- if (startElm && startElm != root) {
- selectedBlocks.push(startElm);
- }
-
- if (startElm && endElm && startElm != endElm) {
- node = startElm;
-
- var walker = new TreeWalker(startElm, root);
- while ((node = walker.next()) && node != endElm) {
- if (dom.isBlock(node)) {
- selectedBlocks.push(node);
- }
- }
- }
-
- if (endElm && startElm != endElm && endElm != root) {
- selectedBlocks.push(endElm);
- }
-
- return selectedBlocks;
- },
-
- isForward: function() {
- var dom = this.dom, sel = this.getSel(), anchorRange, focusRange;
-
- // No support for selection direction then always return true
- if (!sel || !sel.anchorNode || !sel.focusNode) {
- return true;
- }
-
- anchorRange = dom.createRng();
- anchorRange.setStart(sel.anchorNode, sel.anchorOffset);
- anchorRange.collapse(true);
-
- focusRange = dom.createRng();
- focusRange.setStart(sel.focusNode, sel.focusOffset);
- focusRange.collapse(true);
-
- return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
- },
-
- normalize: function() {
- var self = this, rng = self.getRng();
-
- if (!isIE && new RangeUtils(self.dom).normalize(rng)) {
- self.setRng(rng, self.isForward());
- }
-
- return rng;
- },
-
- /**
- * Executes callback of the current selection matches the specified selector or not and passes the state and args to the callback.
- *
- * @method selectorChanged
- * @param {String} selector CSS selector to check for.
- * @param {function} callback Callback with state and args when the selector is matches or not.
- */
- selectorChanged: function(selector, callback) {
- var self = this, currentSelectors;
-
- if (!self.selectorChangedData) {
- self.selectorChangedData = {};
- currentSelectors = {};
-
- self.editor.on('NodeChange', function(e) {
- var node = e.element, dom = self.dom, parents = dom.getParents(node, null, dom.getRoot()), matchedSelectors = {};
-
- // Check for new matching selectors
- each(self.selectorChangedData, function(callbacks, selector) {
- each(parents, function(node) {
- if (dom.is(node, selector)) {
- if (!currentSelectors[selector]) {
- // Execute callbacks
- each(callbacks, function(callback) {
- callback(true, {node: node, selector: selector, parents: parents});
- });
-
- currentSelectors[selector] = callbacks;
- }
-
- matchedSelectors[selector] = callbacks;
- return false;
- }
- });
- });
-
- // Check if current selectors still match
- each(currentSelectors, function(callbacks, selector) {
- if (!matchedSelectors[selector]) {
- delete currentSelectors[selector];
-
- each(callbacks, function(callback) {
- callback(false, {node: node, selector: selector, parents: parents});
- });
- }
- });
- });
- }
-
- // Add selector listeners
- if (!self.selectorChangedData[selector]) {
- self.selectorChangedData[selector] = [];
- }
-
- self.selectorChangedData[selector].push(callback);
-
- return self;
- },
-
- getScrollContainer: function() {
- var scrollContainer, node = this.dom.getRoot();
-
- while (node && node.nodeName != 'BODY') {
- if (node.scrollHeight > node.clientHeight) {
- scrollContainer = node;
- break;
- }
-
- node = node.parentNode;
- }
-
- return scrollContainer;
- },
-
- scrollIntoView: function(elm) {
- var y, viewPort, self = this, dom = self.dom, root = dom.getRoot(), viewPortY, viewPortH;
-
- function getPos(elm) {
- var x = 0, y = 0;
-
- var offsetParent = elm;
- while (offsetParent && offsetParent.nodeType) {
- x += offsetParent.offsetLeft || 0;
- y += offsetParent.offsetTop || 0;
- offsetParent = offsetParent.offsetParent;
- }
-
- return {x: x, y: y};
- }
-
- if (root.nodeName != 'BODY') {
- var scrollContainer = self.getScrollContainer();
- if (scrollContainer) {
- y = getPos(elm).y - getPos(scrollContainer).y;
- viewPortH = scrollContainer.clientHeight;
- viewPortY = scrollContainer.scrollTop;
- if (y < viewPortY || y + 25 > viewPortY + viewPortH) {
- scrollContainer.scrollTop = y < viewPortY ? y : y - viewPortH + 25;
- }
-
- return;
- }
- }
-
- viewPort = dom.getViewPort(self.editor.getWin());
- y = dom.getPos(elm).y;
- viewPortY = viewPort.y;
- viewPortH = viewPort.h;
- if (y < viewPort.y || y + 25 > viewPortY + viewPortH) {
- self.editor.getWin().scrollTo(0, y < viewPortY ? y : y - viewPortH + 25);
- }
- },
-
- _moveEndPoint: function(rng, node, start) {
- var root = node, walker = new TreeWalker(node, root);
- var nonEmptyElementsMap = this.dom.schema.getNonEmptyElements();
-
- do {
- // Text node
- if (node.nodeType == 3 && trim(node.nodeValue).length !== 0) {
- if (start) {
- rng.setStart(node, 0);
- } else {
- rng.setEnd(node, node.nodeValue.length);
- }
-
- return;
- }
-
- // BR/IMG/INPUT elements
- if (nonEmptyElementsMap[node.nodeName]) {
- if (start) {
- rng.setStartBefore(node);
- } else {
- if (node.nodeName == 'BR') {
- rng.setEndBefore(node);
- } else {
- rng.setEndAfter(node);
- }
- }
-
- return;
- }
-
- // Found empty text block old IE can place the selection inside those
- if (Env.ie && Env.ie < 11 && this.dom.isBlock(node) && this.dom.isEmpty(node)) {
- if (start) {
- rng.setStart(node, 0);
- } else {
- rng.setEnd(node, 0);
- }
-
- return;
- }
- } while ((node = (start ? walker.next() : walker.prev())));
-
- // Failed to find any text node or other suitable location then move to the root of body
- if (root.nodeName == 'BODY') {
- if (start) {
- rng.setStart(root, 0);
- } else {
- rng.setEnd(root, root.childNodes.length);
- }
- }
- },
-
- destroy: function() {
- this.win = null;
- this.controlSelection.destroy();
- }
- };
-
- return Selection;
-});
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/Serializer.js b/common/static/js/vendor/tinymce/js/tinymce/classes/dom/Serializer.js
deleted file mode 100755
index 6607497bd3..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/Serializer.js
+++ /dev/null
@@ -1,387 +0,0 @@
-/**
- * Serializer.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class is used to serialize DOM trees into a string. Consult the TinyMCE Wiki API for
- * more details and examples on how to use this class.
- *
- * @class tinymce.dom.Serializer
- */
-define("tinymce/dom/Serializer", [
- "tinymce/dom/DOMUtils",
- "tinymce/html/DomParser",
- "tinymce/html/Entities",
- "tinymce/html/Serializer",
- "tinymce/html/Node",
- "tinymce/html/Schema",
- "tinymce/Env",
- "tinymce/util/Tools"
-], function(DOMUtils, DomParser, Entities, Serializer, Node, Schema, Env, Tools) {
- var each = Tools.each, trim = Tools.trim;
- var DOM = DOMUtils.DOM;
-
- /**
- * Constructs a new DOM serializer class.
- *
- * @constructor
- * @method Serializer
- * @param {Object} settings Serializer settings object.
- * @param {tinymce.Editor} editor Optional editor to bind events to and get schema/dom from.
- */
- return function(settings, editor) {
- var dom, schema, htmlParser;
-
- if (editor) {
- dom = editor.dom;
- schema = editor.schema;
- }
-
- // Default DOM and Schema if they are undefined
- dom = dom || DOM;
- schema = schema || new Schema(settings);
- settings.entity_encoding = settings.entity_encoding || 'named';
- settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true;
-
- htmlParser = new DomParser(settings, schema);
-
- // Convert move data-mce-src, data-mce-href and data-mce-style into nodes or process them if needed
- htmlParser.addAttributeFilter('src,href,style', function(nodes, name) {
- var i = nodes.length, node, value, internalName = 'data-mce-' + name;
- var urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope, undef;
-
- while (i--) {
- node = nodes[i];
-
- value = node.attributes.map[internalName];
- if (value !== undef) {
- // Set external name to internal value and remove internal
- node.attr(name, value.length > 0 ? value : null);
- node.attr(internalName, null);
- } else {
- // No internal attribute found then convert the value we have in the DOM
- value = node.attributes.map[name];
-
- if (name === "style") {
- value = dom.serializeStyle(dom.parseStyle(value), node.name);
- } else if (urlConverter) {
- value = urlConverter.call(urlConverterScope, value, name, node.name);
- }
-
- node.attr(name, value.length > 0 ? value : null);
- }
- }
- });
-
- // Remove internal classes mceItem<..> or mceSelected
- htmlParser.addAttributeFilter('class', function(nodes) {
- var i = nodes.length, node, value;
-
- while (i--) {
- node = nodes[i];
- value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
- node.attr('class', value.length > 0 ? value : null);
- }
- });
-
- // Remove bookmark elements
- htmlParser.addAttributeFilter('data-mce-type', function(nodes, name, args) {
- var i = nodes.length, node;
-
- while (i--) {
- node = nodes[i];
-
- if (node.attributes.map['data-mce-type'] === 'bookmark' && !args.cleanup) {
- node.remove();
- }
- }
- });
-
- // Remove expando attributes
- htmlParser.addAttributeFilter('data-mce-expando', function(nodes, name) {
- var i = nodes.length;
-
- while (i--) {
- nodes[i].attr(name, null);
- }
- });
-
- htmlParser.addNodeFilter('noscript', function(nodes) {
- var i = nodes.length, node;
-
- while (i--) {
- node = nodes[i].firstChild;
-
- if (node) {
- node.value = Entities.decode(node.value);
- }
- }
- });
-
- // Force script into CDATA sections and remove the mce- prefix also add comments around styles
- htmlParser.addNodeFilter('script,style', function(nodes, name) {
- var i = nodes.length, node, value;
-
- function trim(value) {
- /*jshint maxlen:255 */
- /*eslint max-len:0 */
- return value.replace(/()/g, '\n')
- .replace(/^[\r\n]*|[\r\n]*$/g, '')
- .replace(/^\s*(()?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, '');
- }
-
- while (i--) {
- node = nodes[i];
- value = node.firstChild ? node.firstChild.value : '';
-
- if (name === "script") {
- // Remove mce- prefix from script elements and remove default text/javascript mime type (HTML5)
- var type = (node.attr('type') || 'text/javascript').replace(/^mce\-/, '');
- node.attr('type', type === 'text/javascript' ? null : type);
-
- if (value.length > 0) {
- node.firstChild.value = '// ';
- }
- } else {
- if (value.length > 0) {
- node.firstChild.value = '';
- }
- }
- }
- });
-
- // Convert comments to cdata and handle protected comments
- htmlParser.addNodeFilter('#comment', function(nodes) {
- var i = nodes.length, node;
-
- while (i--) {
- node = nodes[i];
-
- if (node.value.indexOf('[CDATA[') === 0) {
- node.name = '#cdata';
- node.type = 4;
- node.value = node.value.replace(/^\[CDATA\[|\]\]$/g, '');
- } else if (node.value.indexOf('mce:protected ') === 0) {
- node.name = "#text";
- node.type = 3;
- node.raw = true;
- node.value = unescape(node.value).substr(14);
- }
- }
- });
-
- htmlParser.addNodeFilter('xml:namespace,input', function(nodes, name) {
- var i = nodes.length, node;
-
- while (i--) {
- node = nodes[i];
- if (node.type === 7) {
- node.remove();
- } else if (node.type === 1) {
- if (name === "input" && !("type" in node.attributes.map)) {
- node.attr('type', 'text');
- }
- }
- }
- });
-
- // Fix list elements, TODO: Replace this later
- if (settings.fix_list_elements) {
- htmlParser.addNodeFilter('ul,ol', function(nodes) {
- var i = nodes.length, node, parentNode;
-
- while (i--) {
- node = nodes[i];
- parentNode = node.parent;
-
- if (parentNode.name === 'ul' || parentNode.name === 'ol') {
- if (node.prev && node.prev.name === 'li') {
- node.prev.append(node);
- }
- }
- }
- });
- }
-
- // Remove internal data attributes
- htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style,data-mce-selected', function(nodes, name) {
- var i = nodes.length;
-
- while (i--) {
- nodes[i].attr(name, null);
- }
- });
-
- // Return public methods
- return {
- /**
- * Schema instance that was used to when the Serializer was constructed.
- *
- * @field {tinymce.html.Schema} schema
- */
- schema: schema,
-
- /**
- * Adds a node filter function to the parser used by the serializer, the parser will collect the specified nodes by name
- * and then execute the callback ones it has finished parsing the document.
- *
- * @example
- * parser.addNodeFilter('p,h1', function(nodes, name) {
- * for (var i = 0; i < nodes.length; i++) {
- * console.log(nodes[i].name);
- * }
- * });
- * @method addNodeFilter
- * @method {String} name Comma separated list of nodes to collect.
- * @param {function} callback Callback function to execute once it has collected nodes.
- */
- addNodeFilter: htmlParser.addNodeFilter,
-
- /**
- * Adds a attribute filter function to the parser used by the serializer, the parser will
- * collect nodes that has the specified attributes
- * and then execute the callback ones it has finished parsing the document.
- *
- * @example
- * parser.addAttributeFilter('src,href', function(nodes, name) {
- * for (var i = 0; i < nodes.length; i++) {
- * console.log(nodes[i].name);
- * }
- * });
- * @method addAttributeFilter
- * @method {String} name Comma separated list of nodes to collect.
- * @param {function} callback Callback function to execute once it has collected nodes.
- */
- addAttributeFilter: htmlParser.addAttributeFilter,
-
- /**
- * Serializes the specified browser DOM node into a HTML string.
- *
- * @method serialize
- * @param {DOMNode} node DOM node to serialize.
- * @param {Object} args Arguments option that gets passed to event handlers.
- */
- serialize: function(node, args) {
- var self = this, impl, doc, oldDoc, htmlSerializer, content;
-
- // Explorer won't clone contents of script and style and the
- // selected index of select elements are cleared on a clone operation.
- if (Env.ie && dom.select('script,style,select,map').length > 0) {
- content = node.innerHTML;
- node = node.cloneNode(false);
- dom.setHTML(node, content);
- } else {
- node = node.cloneNode(true);
- }
-
- // Nodes needs to be attached to something in WebKit/Opera
- // This fix will make DOM ranges and make Sizzle happy!
- impl = node.ownerDocument.implementation;
- if (impl.createHTMLDocument) {
- // Create an empty HTML document
- doc = impl.createHTMLDocument("");
-
- // Add the element or it's children if it's a body element to the new document
- each(node.nodeName == 'BODY' ? node.childNodes : [node], function(node) {
- doc.body.appendChild(doc.importNode(node, true));
- });
-
- // Grab first child or body element for serialization
- if (node.nodeName != 'BODY') {
- node = doc.body.firstChild;
- } else {
- node = doc.body;
- }
-
- // set the new document in DOMUtils so createElement etc works
- oldDoc = dom.doc;
- dom.doc = doc;
- }
-
- args = args || {};
- args.format = args.format || 'html';
-
- // Don't wrap content if we want selected html
- if (args.selection) {
- args.forced_root_block = '';
- }
-
- // Pre process
- if (!args.no_events) {
- args.node = node;
- self.onPreProcess(args);
- }
-
- // Setup serializer
- htmlSerializer = new Serializer(settings, schema);
-
- // Parse and serialize HTML
- args.content = htmlSerializer.serialize(
- htmlParser.parse(trim(args.getInner ? node.innerHTML : dom.getOuterHTML(node)), args)
- );
-
- // Replace all BOM characters for now until we can find a better solution
- if (!args.cleanup) {
- args.content = args.content.replace(/\uFEFF/g, '');
- }
-
- // Post process
- if (!args.no_events) {
- self.onPostProcess(args);
- }
-
- // Restore the old document if it was changed
- if (oldDoc) {
- dom.doc = oldDoc;
- }
-
- args.node = null;
-
- return args.content;
- },
-
- /**
- * Adds valid elements rules to the serializers schema instance this enables you to specify things
- * like what elements should be outputted and what attributes specific elements might have.
- * Consult the Wiki for more details on this format.
- *
- * @method addRules
- * @param {String} rules Valid elements rules string to add to schema.
- */
- addRules: function(rules) {
- schema.addValidElements(rules);
- },
-
- /**
- * Sets the valid elements rules to the serializers schema instance this enables you to specify things
- * like what elements should be outputted and what attributes specific elements might have.
- * Consult the Wiki for more details on this format.
- *
- * @method setRules
- * @param {String} rules Valid elements rules string.
- */
- setRules: function(rules) {
- schema.setValidElements(rules);
- },
-
- onPreProcess: function(args) {
- if (editor) {
- editor.fire('PreProcess', args);
- }
- },
-
- onPostProcess: function(args) {
- if (editor) {
- editor.fire('PostProcess', args);
- }
- }
- };
- };
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/Sizzle.jQuery.js b/common/static/js/vendor/tinymce/js/tinymce/classes/dom/Sizzle.jQuery.js
deleted file mode 100755
index 8b9e2a16a6..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/Sizzle.jQuery.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- * Sizzle.jQuery.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/*global jQuery:true */
-
-/*
- * Fake Sizzle using jQuery.
- */
-define("tinymce/dom/Sizzle", [], function() {
- // Detect if jQuery is loaded
- if (!window.jQuery) {
- throw new Error("Load jQuery first");
- }
-
- return jQuery.find;
-});
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/Sizzle.js b/common/static/js/vendor/tinymce/js/tinymce/classes/dom/Sizzle.js
deleted file mode 100755
index 4eaa7bae52..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/Sizzle.js
+++ /dev/null
@@ -1,1928 +0,0 @@
-/**
- * Sizzle.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- *
- * @ignore-file
- */
-
-/*jshint bitwise:false, expr:true, noempty:false, sub:true, eqnull:true, latedef:false, maxlen:255 */
-/*eslint dot-notation:0, no-empty:0, no-cond-assign:0, no-unused-expressions:0, new-cap:0, no-nested-ternary:0, func-style:0, no-bitwise: 0 */
-
-/*
- * Sizzle CSS Selector Engine
- * Copyright, The Dojo Foundation
- * Released under the MIT, BSD, and GPL Licenses.
- * More information: http://sizzlejs.com/
- */
-define("tinymce/dom/Sizzle", [], function() {
-var i,
- cachedruns,
- Expr,
- getText,
- isXML,
- compile,
- outermostContext,
- recompare,
- sortInput,
-
- // Local document vars
- setDocument,
- document,
- docElem,
- documentIsHTML,
- rbuggyQSA,
- rbuggyMatches,
- matches,
- contains,
-
- // Instance-specific data
- expando = "sizzle" + -(new Date()),
- preferredDoc = window.document,
- support = {},
- dirruns = 0,
- done = 0,
- classCache = createCache(),
- tokenCache = createCache(),
- compilerCache = createCache(),
- hasDuplicate = false,
- sortOrder = function() { return 0; },
-
- // General-purpose constants
- strundefined = typeof undefined,
- MAX_NEGATIVE = 1 << 31,
-
- // Array methods
- arr = [],
- pop = arr.pop,
- push_native = arr.push,
- push = arr.push,
- slice = arr.slice,
- // Use a stripped-down indexOf if we can't use a native one
- indexOf = arr.indexOf || function( elem ) {
- var i = 0,
- len = this.length;
- for ( ; i < len; i++ ) {
- if ( this[i] === elem ) {
- return i;
- }
- }
- return -1;
- },
-
-
- // Regular expressions
-
- // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
- whitespace = "[\\x20\\t\\r\\n\\f]",
- // http://www.w3.org/TR/css3-syntax/#characters
- characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
-
- // Loosely modeled on CSS identifier characters
- // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
- // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
- identifier = characterEncoding.replace( "w", "w#" ),
-
- // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
- operators = "([*^$|!~]?=)",
- attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
- "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
-
- // Prefer arguments quoted,
- // then not containing pseudos/brackets,
- // then attribute selectors/non-parenthetical expressions,
- // then anything else
- // These preferences are here to reduce the number of selectors
- // needing tokenize in the PSEUDO preFilter
- pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
-
- // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
- rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
-
- rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
- rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
- rpseudo = new RegExp( pseudos ),
- ridentifier = new RegExp( "^" + identifier + "$" ),
-
- matchExpr = {
- "ID": new RegExp( "^#(" + characterEncoding + ")" ),
- "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
- "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
- "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
- "ATTR": new RegExp( "^" + attributes ),
- "PSEUDO": new RegExp( "^" + pseudos ),
- "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
- "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
- "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
- // For use in libraries implementing .is()
- // We use this for POS matching in `select`
- "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
- whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
- },
-
- rsibling = /[\x20\t\r\n\f]*[+~]/,
-
- rnative = /^[^{]+\{\s*\[native code/,
-
- // Easily-parseable/retrievable ID or TAG or CLASS selectors
- rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
-
- rinputs = /^(?:input|select|textarea|button)$/i,
- rheader = /^h\d$/i,
-
- rescape = /'|\\/g,
- rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
-
- // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
- runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
- funescape = function( _, escaped ) {
- var high = "0x" + escaped - 0x10000;
- // NaN means non-codepoint
- return high !== high ?
- escaped :
- // BMP codepoint
- high < 0 ?
- String.fromCharCode( high + 0x10000 ) :
- // Supplemental Plane codepoint (surrogate pair)
- String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
- };
-
-// Optimize for push.apply( _, NodeList )
-try {
- push.apply(
- (arr = slice.call( preferredDoc.childNodes )),
- preferredDoc.childNodes
- );
- // Support: Android<4.0
- // Detect silently failing push.apply
- arr[ preferredDoc.childNodes.length ].nodeType;
-} catch ( e ) {
- push = { apply: arr.length ?
-
- // Leverage slice if possible
- function( target, els ) {
- push_native.apply( target, slice.call(els) );
- } :
-
- // Support: IE<9
- // Otherwise append directly
- function( target, els ) {
- var j = target.length,
- i = 0;
- // Can't trust NodeList.length
- while ( (target[j++] = els[i++]) ) {}
- target.length = j - 1;
- }
- };
-}
-
-/**
- * For feature detection
- * @param {Function} fn The function to test for native support
- */
-function isNative( fn ) {
- return rnative.test( fn + "" );
-}
-
-/**
- * Create key-value caches of limited size
- * @returns {Function(string, Object)} Returns the Object data after storing it on itself with
- * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
- * deleting the oldest entry
- */
-function createCache() {
- var cache,
- keys = [];
-
- cache = function( key, value ) {
- // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
- if ( keys.push( key += " " ) > Expr.cacheLength ) {
- // Only keep the most recent entries
- delete cache[ keys.shift() ];
- }
- cache[ key ] = value;
- return value;
- };
-
- return cache;
-}
-
-/**
- * Mark a function for special use by Sizzle
- * @param {Function} fn The function to mark
- */
-function markFunction( fn ) {
- fn[ expando ] = true;
- return fn;
-}
-
-/**
- * Support testing using an element
- * @param {Function} fn Passed the created div and expects a boolean result
- */
-function assert( fn ) {
- var div = document.createElement("div");
-
- try {
- return !!fn( div );
- } catch (e) {
- return false;
- } finally {
- // release memory in IE
- div = null;
- }
-}
-
-function Sizzle( selector, context, results, seed ) {
- var match, elem, m, nodeType,
- // QSA vars
- i, groups, old, nid, newContext, newSelector;
-
- if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
- setDocument( context );
- }
-
- context = context || document;
- results = results || [];
-
- if ( !selector || typeof selector !== "string" ) {
- return results;
- }
-
- if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
- return [];
- }
-
- if ( documentIsHTML && !seed ) {
-
- // Shortcuts
- if ( (match = rquickExpr.exec( selector )) ) {
- // Speed-up: Sizzle("#ID")
- if ( (m = match[1]) ) {
- if ( nodeType === 9 ) {
- elem = context.getElementById( m );
- // Check parentNode to catch when Blackberry 4.6 returns
- // nodes that are no longer in the document #6963
- if ( elem && elem.parentNode ) {
- // Handle the case where IE, Opera, and Webkit return items
- // by name instead of ID
- if ( elem.id === m ) {
- results.push( elem );
- return results;
- }
- } else {
- return results;
- }
- } else {
- // Context is not a document
- if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
- contains( context, elem ) && elem.id === m ) {
- results.push( elem );
- return results;
- }
- }
-
- // Speed-up: Sizzle("TAG")
- } else if ( match[2] ) {
- push.apply( results, context.getElementsByTagName( selector ) );
- return results;
-
- // Speed-up: Sizzle(".CLASS")
- } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
- push.apply( results, context.getElementsByClassName( m ) );
- return results;
- }
- }
-
- // QSA path
- if ( support.qsa && !rbuggyQSA.test(selector) ) {
- old = true;
- nid = expando;
- newContext = context;
- newSelector = nodeType === 9 && selector;
-
- // qSA works strangely on Element-rooted queries
- // We can work around this by specifying an extra ID on the root
- // and working up from there (Thanks to Andrew Dupont for the technique)
- // IE 8 doesn't work on object elements
- if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
- groups = tokenize( selector );
-
- if ( (old = context.getAttribute("id")) ) {
- nid = old.replace( rescape, "\\$&" );
- } else {
- context.setAttribute( "id", nid );
- }
- nid = "[id='" + nid + "'] ";
-
- i = groups.length;
- while ( i-- ) {
- groups[i] = nid + toSelector( groups[i] );
- }
- newContext = rsibling.test( selector ) && context.parentNode || context;
- newSelector = groups.join(",");
- }
-
- if ( newSelector ) {
- try {
- push.apply( results,
- newContext.querySelectorAll( newSelector )
- );
- return results;
- } catch(qsaError) {
- } finally {
- if ( !old ) {
- context.removeAttribute("id");
- }
- }
- }
- }
- }
-
- // All others
- return select( selector.replace( rtrim, "$1" ), context, results, seed );
-}
-
-/**
- * Detect xml
- * @param {Element|Object} elem An element or a document
- */
-isXML = Sizzle.isXML = function( elem ) {
- // documentElement is verified for cases where it doesn't yet exist
- // (such as loading iframes in IE - #4833)
- var documentElement = elem && (elem.ownerDocument || elem).documentElement;
- return documentElement ? documentElement.nodeName !== "HTML" : false;
-};
-
-/**
- * Sets document-related variables once based on the current document
- * @param {Element|Object} [doc] An element or document object to use to set the document
- * @returns {Object} Returns the current document
- */
-setDocument = Sizzle.setDocument = function( node ) {
- var doc = node ? node.ownerDocument || node : preferredDoc;
-
- // If no document and documentElement is available, return
- if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
- return document;
- }
-
- // Set our document
- document = doc;
- docElem = doc.documentElement;
-
- // Support tests
- documentIsHTML = !isXML( doc );
-
- // Check if getElementsByTagName("*") returns only elements
- support.getElementsByTagName = assert(function( div ) {
- div.appendChild( doc.createComment("") );
- return !div.getElementsByTagName("*").length;
- });
-
- // Check if attributes should be retrieved by attribute nodes
- support.attributes = assert(function( div ) {
- div.innerHTML = "";
- var type = typeof div.lastChild.getAttribute("multiple");
- // IE8 returns a string for some attributes even when not present
- return type !== "boolean" && type !== "string";
- });
-
- // Check if getElementsByClassName can be trusted
- support.getElementsByClassName = assert(function( div ) {
- // Opera can't find a second classname (in 9.6)
- div.innerHTML = "";
- if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
- return false;
- }
-
- // Safari 3.2 caches class attributes and doesn't catch changes
- div.lastChild.className = "e";
- return div.getElementsByClassName("e").length === 2;
- });
-
- // Check if getElementsByName privileges form controls or returns elements by ID
- // If so, assume (for broader support) that getElementById returns elements by name
- support.getByName = assert(function( div ) {
- // Inject content
- div.id = expando + 0;
- // Support: Windows 8 Native Apps
- // Assigning innerHTML with "name" attributes throws uncatchable exceptions
- // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx
- div.appendChild( document.createElement("a") ).setAttribute( "name", expando );
- div.appendChild( document.createElement("i") ).setAttribute( "name", expando );
- docElem.appendChild( div );
-
- // Test
- var pass = doc.getElementsByName &&
- // buggy browsers will return fewer than the correct 2
- doc.getElementsByName( expando ).length === 2 +
- // buggy browsers will return more than the correct 0
- doc.getElementsByName( expando + 0 ).length;
-
- // Cleanup
- docElem.removeChild( div );
-
- return pass;
- });
-
- // Support: Webkit<537.32
- // Detached nodes confoundingly follow *each other*
- support.sortDetached = assert(function( div1 ) {
- return div1.compareDocumentPosition &&
- // Should return 1, but Webkit returns 4 (following)
- (div1.compareDocumentPosition( document.createElement("div") ) & 1);
- });
-
- // IE6/7 return modified attributes
- Expr.attrHandle = assert(function( div ) {
- div.innerHTML = "";
- return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
- div.firstChild.getAttribute("href") === "#";
- }) ?
- {} :
- {
- "href": function( elem ) {
- return elem.getAttribute( "href", 2 );
- },
- "type": function( elem ) {
- return elem.getAttribute("type");
- }
- };
-
- // ID find and filter
- if ( support.getByName ) {
- Expr.find["ID"] = function( id, context ) {
- if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
- var m = context.getElementById( id );
- // Check parentNode to catch when Blackberry 4.6 returns
- // nodes that are no longer in the document #6963
- return m && m.parentNode ? [m] : [];
- }
- };
- Expr.filter["ID"] = function( id ) {
- var attrId = id.replace( runescape, funescape );
- return function( elem ) {
- return elem.getAttribute("id") === attrId;
- };
- };
- } else {
- Expr.find["ID"] = function( id, context ) {
- if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
- var m = context.getElementById( id );
-
- return m ?
- m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
- [m] :
- undefined :
- [];
- }
- };
- Expr.filter["ID"] = function( id ) {
- var attrId = id.replace( runescape, funescape );
- return function( elem ) {
- var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
- return node && node.value === attrId;
- };
- };
- }
-
- // Tag
- Expr.find["TAG"] = support.getElementsByTagName ?
- function( tag, context ) {
- if ( typeof context.getElementsByTagName !== strundefined ) {
- return context.getElementsByTagName( tag );
- }
- } :
- function( tag, context ) {
- var elem,
- tmp = [],
- i = 0,
- results = context.getElementsByTagName( tag );
-
- // Filter out possible comments
- if ( tag === "*" ) {
- while ( (elem = results[i++]) ) {
- if ( elem.nodeType === 1 ) {
- tmp.push( elem );
- }
- }
-
- return tmp;
- }
- return results;
- };
-
- // Name
- Expr.find["NAME"] = support.getByName && function( tag, context ) {
- if ( typeof context.getElementsByName !== strundefined ) {
- return context.getElementsByName( name );
- }
- };
-
- // Class
- Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
- if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
- return context.getElementsByClassName( className );
- }
- };
-
- // QSA and matchesSelector support
-
- // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
- rbuggyMatches = [];
-
- // qSa(:focus) reports false when true (Chrome 21),
- // no need to also add to buggyMatches since matches checks buggyQSA
- // A support test would require too much code (would include document ready)
- rbuggyQSA = [ ":focus" ];
-
- if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
- // Build QSA regex
- // Regex strategy adopted from Diego Perini
- assert(function( div ) {
- // Select is set to empty string on purpose
- // This is to test IE's treatment of not explicitly
- // setting a boolean content attribute,
- // since its presence should be enough
- // http://bugs.jquery.com/ticket/12359
- div.innerHTML = "";
-
- // IE8 - Some boolean attributes are not treated correctly
- if ( !div.querySelectorAll("[selected]").length ) {
- rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
- }
-
- // Webkit/Opera - :checked should return selected option elements
- // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
- // IE8 throws error here and will not see later tests
- if ( !div.querySelectorAll(":checked").length ) {
- rbuggyQSA.push(":checked");
- }
- });
-
- assert(function( div ) {
-
- // Opera 10-12/IE8 - ^= $= *= and empty values
- // Should not select anything
- div.innerHTML = "";
- if ( div.querySelectorAll("[i^='']").length ) {
- rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
- }
-
- // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
- // IE8 throws error here and will not see later tests
- if ( !div.querySelectorAll(":enabled").length ) {
- rbuggyQSA.push( ":enabled", ":disabled" );
- }
-
- // Opera 10-11 does not throw on post-comma invalid pseudos
- div.querySelectorAll("*,:x");
- rbuggyQSA.push(",.*:");
- });
- }
-
- if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector ||
- docElem.mozMatchesSelector ||
- docElem.webkitMatchesSelector ||
- docElem.oMatchesSelector ||
- docElem.msMatchesSelector) )) ) {
-
- assert(function( div ) {
- // Check to see if it's possible to do matchesSelector
- // on a disconnected node (IE 9)
- support.disconnectedMatch = matches.call( div, "div" );
-
- // This should fail with an exception
- // Gecko does not error, returns false instead
- matches.call( div, "[s!='']:x" );
- rbuggyMatches.push( "!=", pseudos );
- });
- }
-
- rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
- rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
-
- // Element contains another
- // Purposefully does not implement inclusive descendant
- // As in, an element does not contain itself
- contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
- function( a, b ) {
- var adown = a.nodeType === 9 ? a.documentElement : a,
- bup = b && b.parentNode;
- return a === bup || !!( bup && bup.nodeType === 1 && (
- adown.contains ?
- adown.contains( bup ) :
- a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
- ));
- } :
- function( a, b ) {
- if ( b ) {
- while ( (b = b.parentNode) ) {
- if ( b === a ) {
- return true;
- }
- }
- }
- return false;
- };
-
- // Document order sorting
- sortOrder = docElem.compareDocumentPosition ?
- function( a, b ) {
-
- // Flag for duplicate removal
- if ( a === b ) {
- hasDuplicate = true;
- return 0;
- }
-
- var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
-
- if ( compare ) {
- // Disconnected nodes
- if ( compare & 1 ||
- (recompare && b.compareDocumentPosition( a ) === compare) ) {
-
- // Choose the first element that is related to our preferred document
- if ( a === doc || contains(preferredDoc, a) ) {
- return -1;
- }
- if ( b === doc || contains(preferredDoc, b) ) {
- return 1;
- }
-
- // Maintain original order
- return sortInput ?
- ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
- 0;
- }
-
- return compare & 4 ? -1 : 1;
- }
-
- // Not directly comparable, sort on existence of method
- return a.compareDocumentPosition ? -1 : 1;
- } :
- function( a, b ) {
- var cur,
- i = 0,
- aup = a.parentNode,
- bup = b.parentNode,
- ap = [ a ],
- bp = [ b ];
-
- // Exit early if the nodes are identical
- if ( a === b ) {
- hasDuplicate = true;
- return 0;
-
- // Parentless nodes are either documents or disconnected
- } else if ( !aup || !bup ) {
- return a === doc ? -1 :
- b === doc ? 1 :
- aup ? -1 :
- bup ? 1 :
- 0;
-
- // If the nodes are siblings, we can do a quick check
- } else if ( aup === bup ) {
- return siblingCheck( a, b );
- }
-
- // Otherwise we need full lists of their ancestors for comparison
- cur = a;
- while ( (cur = cur.parentNode) ) {
- ap.unshift( cur );
- }
- cur = b;
- while ( (cur = cur.parentNode) ) {
- bp.unshift( cur );
- }
-
- // Walk down the tree looking for a discrepancy
- while ( ap[i] === bp[i] ) {
- i++;
- }
-
- return i ?
- // Do a sibling check if the nodes have a common ancestor
- siblingCheck( ap[i], bp[i] ) :
-
- // Otherwise nodes in our document sort first
- ap[i] === preferredDoc ? -1 :
- bp[i] === preferredDoc ? 1 :
- 0;
- };
-
- return document;
-};
-
-Sizzle.matches = function( expr, elements ) {
- return Sizzle( expr, null, null, elements );
-};
-
-Sizzle.matchesSelector = function( elem, expr ) {
- // Set document vars if needed
- if ( ( elem.ownerDocument || elem ) !== document ) {
- setDocument( elem );
- }
-
- // Make sure that attribute selectors are quoted
- expr = expr.replace( rattributeQuotes, "='$1']" );
-
- // rbuggyQSA always contains :focus, so no need for an existence check
- if ( support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) {
- try {
- var ret = matches.call( elem, expr );
-
- // IE 9's matchesSelector returns false on disconnected nodes
- if ( ret || support.disconnectedMatch ||
- // As well, disconnected nodes are said to be in a document
- // fragment in IE 9
- elem.document && elem.document.nodeType !== 11 ) {
- return ret;
- }
- } catch(e) {}
- }
-
- return Sizzle( expr, document, null, [elem] ).length > 0;
-};
-
-Sizzle.contains = function( context, elem ) {
- // Set document vars if needed
- if ( ( context.ownerDocument || context ) !== document ) {
- setDocument( context );
- }
- return contains( context, elem );
-};
-
-Sizzle.attr = function( elem, name ) {
- var val;
-
- // Set document vars if needed
- if ( ( elem.ownerDocument || elem ) !== document ) {
- setDocument( elem );
- }
-
- if ( documentIsHTML ) {
- name = name.toLowerCase();
- }
- if ( (val = Expr.attrHandle[ name ]) ) {
- return val( elem );
- }
- if ( !documentIsHTML || support.attributes ) {
- return elem.getAttribute( name );
- }
- return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
- name :
- val && val.specified ? val.value : null;
-};
-
-Sizzle.error = function( msg ) {
- throw new Error( "Syntax error, unrecognized expression: " + msg );
-};
-
-// Document sorting and removing duplicates
-Sizzle.uniqueSort = function( results ) {
- var elem,
- duplicates = [],
- j = 0,
- i = 0;
-
- // Unless we *know* we can detect duplicates, assume their presence
- hasDuplicate = !support.detectDuplicates;
- // Compensate for sort limitations
- recompare = !support.sortDetached;
- sortInput = !support.sortStable && results.slice( 0 );
- results.sort( sortOrder );
-
- if ( hasDuplicate ) {
- while ( (elem = results[i++]) ) {
- if ( elem === results[ i ] ) {
- j = duplicates.push( i );
- }
- }
- while ( j-- ) {
- results.splice( duplicates[ j ], 1 );
- }
- }
-
- return results;
-};
-
-/**
- * Checks document order of two siblings
- * @param {Element} a
- * @param {Element} b
- * @returns Returns -1 if a precedes b, 1 if a follows b
- */
-function siblingCheck( a, b ) {
- var cur = b && a,
- diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE );
-
- // Use IE sourceIndex if available on both nodes
- if ( diff ) {
- return diff;
- }
-
- // Check if b follows a
- if ( cur ) {
- while ( (cur = cur.nextSibling) ) {
- if ( cur === b ) {
- return -1;
- }
- }
- }
-
- return a ? 1 : -1;
-}
-
-// Returns a function to use in pseudos for input types
-function createInputPseudo( type ) {
- return function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return name === "input" && elem.type === type;
- };
-}
-
-// Returns a function to use in pseudos for buttons
-function createButtonPseudo( type ) {
- return function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return (name === "input" || name === "button") && elem.type === type;
- };
-}
-
-// Returns a function to use in pseudos for positionals
-function createPositionalPseudo( fn ) {
- return markFunction(function( argument ) {
- argument = +argument;
- return markFunction(function( seed, matches ) {
- var j,
- matchIndexes = fn( [], seed.length, argument ),
- i = matchIndexes.length;
-
- // Match elements found at the specified indexes
- while ( i-- ) {
- if ( seed[ (j = matchIndexes[i]) ] ) {
- seed[j] = !(matches[j] = seed[j]);
- }
- }
- });
- });
-}
-
-/**
- * Utility function for retrieving the text value of an array of DOM nodes
- * @param {Array|Element} elem
- */
-getText = Sizzle.getText = function( elem ) {
- var node,
- ret = "",
- i = 0,
- nodeType = elem.nodeType;
-
- if ( !nodeType ) {
- // If no nodeType, this is expected to be an array
- for ( ; (node = elem[i]); i++ ) {
- // Do not traverse comment nodes
- ret += getText( node );
- }
- } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
- // Use textContent for elements
- // innerText usage removed for consistency of new lines (see #11153)
- if ( typeof elem.textContent === "string" ) {
- return elem.textContent;
- } else {
- // Traverse its children
- for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
- ret += getText( elem );
- }
- }
- } else if ( nodeType === 3 || nodeType === 4 ) {
- return elem.nodeValue;
- }
- // Do not include comment or processing instruction nodes
-
- return ret;
-};
-
-Expr = Sizzle.selectors = {
-
- // Can be adjusted by the user
- cacheLength: 50,
-
- createPseudo: markFunction,
-
- match: matchExpr,
-
- find: {},
-
- relative: {
- ">": { dir: "parentNode", first: true },
- " ": { dir: "parentNode" },
- "+": { dir: "previousSibling", first: true },
- "~": { dir: "previousSibling" }
- },
-
- preFilter: {
- "ATTR": function( match ) {
- match[1] = match[1].replace( runescape, funescape );
-
- // Move the given value to match[3] whether quoted or unquoted
- match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
-
- if ( match[2] === "~=" ) {
- match[3] = " " + match[3] + " ";
- }
-
- return match.slice( 0, 4 );
- },
-
- "CHILD": function( match ) {
- /* matches from matchExpr["CHILD"]
- 1 type (only|nth|...)
- 2 what (child|of-type)
- 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
- 4 xn-component of xn+y argument ([+-]?\d*n|)
- 5 sign of xn-component
- 6 x of xn-component
- 7 sign of y-component
- 8 y of y-component
- */
- match[1] = match[1].toLowerCase();
-
- if ( match[1].slice( 0, 3 ) === "nth" ) {
- // nth-* requires argument
- if ( !match[3] ) {
- Sizzle.error( match[0] );
- }
-
- // numeric x and y parameters for Expr.filter.CHILD
- // remember that false/true cast respectively to 0/1
- match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
- match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
-
- // other types prohibit arguments
- } else if ( match[3] ) {
- Sizzle.error( match[0] );
- }
-
- return match;
- },
-
- "PSEUDO": function( match ) {
- var excess,
- unquoted = !match[5] && match[2];
-
- if ( matchExpr["CHILD"].test( match[0] ) ) {
- return null;
- }
-
- // Accept quoted arguments as-is
- if ( match[4] ) {
- match[2] = match[4];
-
- // Strip excess characters from unquoted arguments
- } else if ( unquoted && rpseudo.test( unquoted ) &&
- // Get excess from tokenize (recursively)
- (excess = tokenize( unquoted, true )) &&
- // advance to the next closing parenthesis
- (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
-
- // excess is a negative index
- match[0] = match[0].slice( 0, excess );
- match[2] = unquoted.slice( 0, excess );
- }
-
- // Return only captures needed by the pseudo filter method (type and argument)
- return match.slice( 0, 3 );
- }
- },
-
- filter: {
-
- "TAG": function( nodeName ) {
- if ( nodeName === "*" ) {
- return function() { return true; };
- }
-
- nodeName = nodeName.replace( runescape, funescape ).toLowerCase();
- return function( elem ) {
- return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
- };
- },
-
- "CLASS": function( className ) {
- var pattern = classCache[ className + " " ];
-
- return pattern ||
- (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
- classCache( className, function( elem ) {
- return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
- });
- },
-
- "ATTR": function( name, operator, check ) {
- return function( elem ) {
- var result = Sizzle.attr( elem, name );
-
- if ( result == null ) {
- return operator === "!=";
- }
- if ( !operator ) {
- return true;
- }
-
- result += "";
-
- return operator === "=" ? result === check :
- operator === "!=" ? result !== check :
- operator === "^=" ? check && result.indexOf( check ) === 0 :
- operator === "*=" ? check && result.indexOf( check ) > -1 :
- operator === "$=" ? check && result.slice( -check.length ) === check :
- operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
- operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
- false;
- };
- },
-
- "CHILD": function( type, what, argument, first, last ) {
- var simple = type.slice( 0, 3 ) !== "nth",
- forward = type.slice( -4 ) !== "last",
- ofType = what === "of-type";
-
- return first === 1 && last === 0 ?
-
- // Shortcut for :nth-*(n)
- function( elem ) {
- return !!elem.parentNode;
- } :
-
- function( elem, context, xml ) {
- var cache, outerCache, node, diff, nodeIndex, start,
- dir = simple !== forward ? "nextSibling" : "previousSibling",
- parent = elem.parentNode,
- name = ofType && elem.nodeName.toLowerCase(),
- useCache = !xml && !ofType;
-
- if ( parent ) {
-
- // :(first|last|only)-(child|of-type)
- if ( simple ) {
- while ( dir ) {
- node = elem;
- while ( (node = node[ dir ]) ) {
- if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
- return false;
- }
- }
- // Reverse direction for :only-* (if we haven't yet done so)
- start = dir = type === "only" && !start && "nextSibling";
- }
- return true;
- }
-
- start = [ forward ? parent.firstChild : parent.lastChild ];
-
- // non-xml :nth-child(...) stores cache data on `parent`
- if ( forward && useCache ) {
- // Seek `elem` from a previously-cached index
- outerCache = parent[ expando ] || (parent[ expando ] = {});
- cache = outerCache[ type ] || [];
- nodeIndex = cache[0] === dirruns && cache[1];
- diff = cache[0] === dirruns && cache[2];
- node = nodeIndex && parent.childNodes[ nodeIndex ];
-
- while ( (node = ++nodeIndex && node && node[ dir ] ||
-
- // Fallback to seeking `elem` from the start
- (diff = nodeIndex = 0) || start.pop()) ) {
-
- // When found, cache indexes on `parent` and break
- if ( node.nodeType === 1 && ++diff && node === elem ) {
- outerCache[ type ] = [ dirruns, nodeIndex, diff ];
- break;
- }
- }
-
- // Use previously-cached element index if available
- } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
- diff = cache[1];
-
- // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
- } else {
- // Use the same loop as above to seek `elem` from the start
- while ( (node = ++nodeIndex && node && node[ dir ] ||
- (diff = nodeIndex = 0) || start.pop()) ) {
-
- if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
- // Cache the index of each encountered element
- if ( useCache ) {
- (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
- }
-
- if ( node === elem ) {
- break;
- }
- }
- }
- }
-
- // Incorporate the offset, then check against cycle size
- diff -= last;
- return diff === first || ( diff % first === 0 && diff / first >= 0 );
- }
- };
- },
-
- "PSEUDO": function( pseudo, argument ) {
- // pseudo-class names are case-insensitive
- // http://www.w3.org/TR/selectors/#pseudo-classes
- // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
- // Remember that setFilters inherits from pseudos
- var args,
- fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
- Sizzle.error( "unsupported pseudo: " + pseudo );
-
- // The user may use createPseudo to indicate that
- // arguments are needed to create the filter function
- // just as Sizzle does
- if ( fn[ expando ] ) {
- return fn( argument );
- }
-
- // But maintain support for old signatures
- if ( fn.length > 1 ) {
- args = [ pseudo, pseudo, "", argument ];
- return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
- markFunction(function( seed, matches ) {
- var idx,
- matched = fn( seed, argument ),
- i = matched.length;
- while ( i-- ) {
- idx = indexOf.call( seed, matched[i] );
- seed[ idx ] = !( matches[ idx ] = matched[i] );
- }
- }) :
- function( elem ) {
- return fn( elem, 0, args );
- };
- }
-
- return fn;
- }
- },
-
- pseudos: {
- // Potentially complex pseudos
- "not": markFunction(function( selector ) {
- // Trim the selector passed to compile
- // to avoid treating leading and trailing
- // spaces as combinators
- var input = [],
- results = [],
- matcher = compile( selector.replace( rtrim, "$1" ) );
-
- return matcher[ expando ] ?
- markFunction(function( seed, matches, context, xml ) {
- var elem,
- unmatched = matcher( seed, null, xml, [] ),
- i = seed.length;
-
- // Match elements unmatched by `matcher`
- while ( i-- ) {
- if ( (elem = unmatched[i]) ) {
- seed[i] = !(matches[i] = elem);
- }
- }
- }) :
- function( elem, context, xml ) {
- input[0] = elem;
- matcher( input, null, xml, results );
- return !results.pop();
- };
- }),
-
- "has": markFunction(function( selector ) {
- return function( elem ) {
- return Sizzle( selector, elem ).length > 0;
- };
- }),
-
- "contains": markFunction(function( text ) {
- return function( elem ) {
- return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
- };
- }),
-
- // "Whether an element is represented by a :lang() selector
- // is based solely on the element's language value
- // being equal to the identifier C,
- // or beginning with the identifier C immediately followed by "-".
- // The matching of C against the element's language value is performed case-insensitively.
- // The identifier C does not have to be a valid language name."
- // http://www.w3.org/TR/selectors/#lang-pseudo
- "lang": markFunction( function( lang ) {
- // lang value must be a valid identifier
- if ( !ridentifier.test(lang || "") ) {
- Sizzle.error( "unsupported lang: " + lang );
- }
- lang = lang.replace( runescape, funescape ).toLowerCase();
- return function( elem ) {
- var elemLang;
- do {
- if ( (elemLang = documentIsHTML ?
- elem.lang :
- elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
-
- elemLang = elemLang.toLowerCase();
- return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
- }
- } while ( (elem = elem.parentNode) && elem.nodeType === 1 );
- return false;
- };
- }),
-
- // Miscellaneous
- "target": function( elem ) {
- var hash = window.location && window.location.hash;
- return hash && hash.slice( 1 ) === elem.id;
- },
-
- "root": function( elem ) {
- return elem === docElem;
- },
-
- "focus": function( elem ) {
- return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
- },
-
- // Boolean properties
- "enabled": function( elem ) {
- return elem.disabled === false;
- },
-
- "disabled": function( elem ) {
- return elem.disabled === true;
- },
-
- "checked": function( elem ) {
- // In CSS3, :checked should return both checked and selected elements
- // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
- var nodeName = elem.nodeName.toLowerCase();
- return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
- },
-
- "selected": function( elem ) {
- // Accessing this property makes selected-by-default
- // options in Safari work properly
- if ( elem.parentNode ) {
- elem.parentNode.selectedIndex;
- }
-
- return elem.selected === true;
- },
-
- // Contents
- "empty": function( elem ) {
- // http://www.w3.org/TR/selectors/#empty-pseudo
- // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
- // not comment, processing instructions, or others
- // Thanks to Diego Perini for the nodeName shortcut
- // Greater than "@" means alpha characters (specifically not starting with "#" or "?")
- for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
- if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
- return false;
- }
- }
- return true;
- },
-
- "parent": function( elem ) {
- return !Expr.pseudos["empty"]( elem );
- },
-
- // Element/input types
- "header": function( elem ) {
- return rheader.test( elem.nodeName );
- },
-
- "input": function( elem ) {
- return rinputs.test( elem.nodeName );
- },
-
- "button": function( elem ) {
- var name = elem.nodeName.toLowerCase();
- return name === "input" && elem.type === "button" || name === "button";
- },
-
- "text": function( elem ) {
- var attr;
- // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
- // use getAttribute instead to test this case
- return elem.nodeName.toLowerCase() === "input" &&
- elem.type === "text" &&
- ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
- },
-
- // Position-in-collection
- "first": createPositionalPseudo(function() {
- return [ 0 ];
- }),
-
- "last": createPositionalPseudo(function( matchIndexes, length ) {
- return [ length - 1 ];
- }),
-
- "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
- return [ argument < 0 ? argument + length : argument ];
- }),
-
- "even": createPositionalPseudo(function( matchIndexes, length ) {
- var i = 0;
- for ( ; i < length; i += 2 ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "odd": createPositionalPseudo(function( matchIndexes, length ) {
- var i = 1;
- for ( ; i < length; i += 2 ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
- var i = argument < 0 ? argument + length : argument;
- for ( ; --i >= 0; ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- }),
-
- "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
- var i = argument < 0 ? argument + length : argument;
- for ( ; ++i < length; ) {
- matchIndexes.push( i );
- }
- return matchIndexes;
- })
- }
-};
-
-// Add button/input type pseudos
-for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
- Expr.pseudos[ i ] = createInputPseudo( i );
-}
-for ( i in { submit: true, reset: true } ) {
- Expr.pseudos[ i ] = createButtonPseudo( i );
-}
-
-function tokenize( selector, parseOnly ) {
- var matched, match, tokens, type,
- soFar, groups, preFilters,
- cached = tokenCache[ selector + " " ];
-
- if ( cached ) {
- return parseOnly ? 0 : cached.slice( 0 );
- }
-
- soFar = selector;
- groups = [];
- preFilters = Expr.preFilter;
-
- while ( soFar ) {
-
- // Comma and first run
- if ( !matched || (match = rcomma.exec( soFar )) ) {
- if ( match ) {
- // Don't consume trailing commas as valid
- soFar = soFar.slice( match[0].length ) || soFar;
- }
- groups.push( tokens = [] );
- }
-
- matched = false;
-
- // Combinators
- if ( (match = rcombinators.exec( soFar )) ) {
- matched = match.shift();
- tokens.push( {
- value: matched,
- // Cast descendant combinators to space
- type: match[0].replace( rtrim, " " )
- } );
- soFar = soFar.slice( matched.length );
- }
-
- // Filters
- for ( type in Expr.filter ) {
- if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
- (match = preFilters[ type ]( match ))) ) {
- matched = match.shift();
- tokens.push( {
- value: matched,
- type: type,
- matches: match
- } );
- soFar = soFar.slice( matched.length );
- }
- }
-
- if ( !matched ) {
- break;
- }
- }
-
- // Return the length of the invalid excess
- // if we're just parsing
- // Otherwise, throw an error or return tokens
- return parseOnly ?
- soFar.length :
- soFar ?
- Sizzle.error( selector ) :
- // Cache the tokens
- tokenCache( selector, groups ).slice( 0 );
-}
-
-function toSelector( tokens ) {
- var i = 0,
- len = tokens.length,
- selector = "";
- for ( ; i < len; i++ ) {
- selector += tokens[i].value;
- }
- return selector;
-}
-
-function addCombinator( matcher, combinator, base ) {
- var dir = combinator.dir,
- checkNonElements = base && dir === "parentNode",
- doneName = done++;
-
- return combinator.first ?
- // Check against closest ancestor/preceding element
- function( elem, context, xml ) {
- while ( (elem = elem[ dir ]) ) {
- if ( elem.nodeType === 1 || checkNonElements ) {
- return matcher( elem, context, xml );
- }
- }
- } :
-
- // Check against all ancestor/preceding elements
- function( elem, context, xml ) {
- var data, cache, outerCache,
- dirkey = dirruns + " " + doneName;
-
- // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
- if ( xml ) {
- while ( (elem = elem[ dir ]) ) {
- if ( elem.nodeType === 1 || checkNonElements ) {
- if ( matcher( elem, context, xml ) ) {
- return true;
- }
- }
- }
- } else {
- while ( (elem = elem[ dir ]) ) {
- if ( elem.nodeType === 1 || checkNonElements ) {
- outerCache = elem[ expando ] || (elem[ expando ] = {});
- if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
- if ( (data = cache[1]) === true || data === cachedruns ) {
- return data === true;
- }
- } else {
- cache = outerCache[ dir ] = [ dirkey ];
- cache[1] = matcher( elem, context, xml ) || cachedruns;
- if ( cache[1] === true ) {
- return true;
- }
- }
- }
- }
- }
- };
-}
-
-function elementMatcher( matchers ) {
- return matchers.length > 1 ?
- function( elem, context, xml ) {
- var i = matchers.length;
- while ( i-- ) {
- if ( !matchers[i]( elem, context, xml ) ) {
- return false;
- }
- }
- return true;
- } :
- matchers[0];
-}
-
-function condense( unmatched, map, filter, context, xml ) {
- var elem,
- newUnmatched = [],
- i = 0,
- len = unmatched.length,
- mapped = map != null;
-
- for ( ; i < len; i++ ) {
- if ( (elem = unmatched[i]) ) {
- if ( !filter || filter( elem, context, xml ) ) {
- newUnmatched.push( elem );
- if ( mapped ) {
- map.push( i );
- }
- }
- }
- }
-
- return newUnmatched;
-}
-
-function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
- if ( postFilter && !postFilter[ expando ] ) {
- postFilter = setMatcher( postFilter );
- }
- if ( postFinder && !postFinder[ expando ] ) {
- postFinder = setMatcher( postFinder, postSelector );
- }
- return markFunction(function( seed, results, context, xml ) {
- var temp, i, elem,
- preMap = [],
- postMap = [],
- preexisting = results.length,
-
- // Get initial elements from seed or context
- elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
-
- // Prefilter to get matcher input, preserving a map for seed-results synchronization
- matcherIn = preFilter && ( seed || !selector ) ?
- condense( elems, preMap, preFilter, context, xml ) :
- elems,
-
- matcherOut = matcher ?
- // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
- postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
-
- // ...intermediate processing is necessary
- [] :
-
- // ...otherwise use results directly
- results :
- matcherIn;
-
- // Find primary matches
- if ( matcher ) {
- matcher( matcherIn, matcherOut, context, xml );
- }
-
- // Apply postFilter
- if ( postFilter ) {
- temp = condense( matcherOut, postMap );
- postFilter( temp, [], context, xml );
-
- // Un-match failing elements by moving them back to matcherIn
- i = temp.length;
- while ( i-- ) {
- if ( (elem = temp[i]) ) {
- matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
- }
- }
- }
-
- if ( seed ) {
- if ( postFinder || preFilter ) {
- if ( postFinder ) {
- // Get the final matcherOut by condensing this intermediate into postFinder contexts
- temp = [];
- i = matcherOut.length;
- while ( i-- ) {
- if ( (elem = matcherOut[i]) ) {
- // Restore matcherIn since elem is not yet a final match
- temp.push( (matcherIn[i] = elem) );
- }
- }
- postFinder( null, (matcherOut = []), temp, xml );
- }
-
- // Move matched elements from seed to results to keep them synchronized
- i = matcherOut.length;
- while ( i-- ) {
- if ( (elem = matcherOut[i]) &&
- (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
-
- seed[temp] = !(results[temp] = elem);
- }
- }
- }
-
- // Add elements to results, through postFinder if defined
- } else {
- matcherOut = condense(
- matcherOut === results ?
- matcherOut.splice( preexisting, matcherOut.length ) :
- matcherOut
- );
- if ( postFinder ) {
- postFinder( null, results, matcherOut, xml );
- } else {
- push.apply( results, matcherOut );
- }
- }
- });
-}
-
-function matcherFromTokens( tokens ) {
- var checkContext, matcher, j,
- len = tokens.length,
- leadingRelative = Expr.relative[ tokens[0].type ],
- implicitRelative = leadingRelative || Expr.relative[" "],
- i = leadingRelative ? 1 : 0,
-
- // The foundational matcher ensures that elements are reachable from top-level context(s)
- matchContext = addCombinator( function( elem ) {
- return elem === checkContext;
- }, implicitRelative, true ),
- matchAnyContext = addCombinator( function( elem ) {
- return indexOf.call( checkContext, elem ) > -1;
- }, implicitRelative, true ),
- matchers = [ function( elem, context, xml ) {
- return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
- (checkContext = context).nodeType ?
- matchContext( elem, context, xml ) :
- matchAnyContext( elem, context, xml ) );
- } ];
-
- for ( ; i < len; i++ ) {
- if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
- matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
- } else {
- matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
-
- // Return special upon seeing a positional matcher
- if ( matcher[ expando ] ) {
- // Find the next relative operator (if any) for proper handling
- j = ++i;
- for ( ; j < len; j++ ) {
- if ( Expr.relative[ tokens[j].type ] ) {
- break;
- }
- }
- return setMatcher(
- i > 1 && elementMatcher( matchers ),
- i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ),
- matcher,
- i < j && matcherFromTokens( tokens.slice( i, j ) ),
- j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
- j < len && toSelector( tokens )
- );
- }
- matchers.push( matcher );
- }
- }
-
- return elementMatcher( matchers );
-}
-
-function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
- // A counter to specify which element is currently being matched
- var matcherCachedRuns = 0,
- bySet = setMatchers.length > 0,
- byElement = elementMatchers.length > 0,
- superMatcher = function( seed, context, xml, results, expandContext ) {
- var elem, j, matcher,
- setMatched = [],
- matchedCount = 0,
- i = "0",
- unmatched = seed && [],
- outermost = expandContext != null,
- contextBackup = outermostContext,
- // We must always have either seed elements or context
- elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
- // Use integer dirruns iff this is the outermost matcher
- dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
-
- if ( outermost ) {
- outermostContext = context !== document && context;
- cachedruns = matcherCachedRuns;
- }
-
- // Add elements passing elementMatchers directly to results
- // Keep `i` a string if there are no elements so `matchedCount` will be "00" below
- for ( ; (elem = elems[i]) != null; i++ ) {
- if ( byElement && elem ) {
- j = 0;
- while ( (matcher = elementMatchers[j++]) ) {
- if ( matcher( elem, context, xml ) ) {
- results.push( elem );
- break;
- }
- }
- if ( outermost ) {
- dirruns = dirrunsUnique;
- cachedruns = ++matcherCachedRuns;
- }
- }
-
- // Track unmatched elements for set filters
- if ( bySet ) {
- // They will have gone through all possible matchers
- if ( (elem = !matcher && elem) ) {
- matchedCount--;
- }
-
- // Lengthen the array for every element, matched or not
- if ( seed ) {
- unmatched.push( elem );
- }
- }
- }
-
- // Apply set filters to unmatched elements
- matchedCount += i;
- if ( bySet && i !== matchedCount ) {
- j = 0;
- while ( (matcher = setMatchers[j++]) ) {
- matcher( unmatched, setMatched, context, xml );
- }
-
- if ( seed ) {
- // Reintegrate element matches to eliminate the need for sorting
- if ( matchedCount > 0 ) {
- while ( i-- ) {
- if ( !(unmatched[i] || setMatched[i]) ) {
- setMatched[i] = pop.call( results );
- }
- }
- }
-
- // Discard index placeholder values to get only actual matches
- setMatched = condense( setMatched );
- }
-
- // Add matches to results
- push.apply( results, setMatched );
-
- // Seedless set matches succeeding multiple successful matchers stipulate sorting
- if ( outermost && !seed && setMatched.length > 0 &&
- ( matchedCount + setMatchers.length ) > 1 ) {
-
- Sizzle.uniqueSort( results );
- }
- }
-
- // Override manipulation of globals by nested matchers
- if ( outermost ) {
- dirruns = dirrunsUnique;
- outermostContext = contextBackup;
- }
-
- return unmatched;
- };
-
- return bySet ?
- markFunction( superMatcher ) :
- superMatcher;
-}
-
-compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
- var i,
- setMatchers = [],
- elementMatchers = [],
- cached = compilerCache[ selector + " " ];
-
- if ( !cached ) {
- // Generate a function of recursive functions that can be used to check each element
- if ( !group ) {
- group = tokenize( selector );
- }
- i = group.length;
- while ( i-- ) {
- cached = matcherFromTokens( group[i] );
- if ( cached[ expando ] ) {
- setMatchers.push( cached );
- } else {
- elementMatchers.push( cached );
- }
- }
-
- // Cache the compiled function
- cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
- }
- return cached;
-};
-
-function multipleContexts( selector, contexts, results ) {
- var i = 0,
- len = contexts.length;
- for ( ; i < len; i++ ) {
- Sizzle( selector, contexts[i], results );
- }
- return results;
-}
-
-function select( selector, context, results, seed ) {
- var i, tokens, token, type, find,
- match = tokenize( selector );
-
- if ( !seed ) {
- // Try to minimize operations if there is only one group
- if ( match.length === 1 ) {
-
- // Take a shortcut and set the context if the root selector is an ID
- tokens = match[0] = match[0].slice( 0 );
- if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
- context.nodeType === 9 && documentIsHTML &&
- Expr.relative[ tokens[1].type ] ) {
-
- context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
- if ( !context ) {
- return results;
- }
-
- selector = selector.slice( tokens.shift().value.length );
- }
-
- // Fetch a seed set for right-to-left matching
- i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
- while ( i-- ) {
- token = tokens[i];
-
- // Abort if we hit a combinator
- if ( Expr.relative[ (type = token.type) ] ) {
- break;
- }
- if ( (find = Expr.find[ type ]) ) {
- // Search, expanding context for leading sibling combinators
- if ( (seed = find(
- token.matches[0].replace( runescape, funescape ),
- rsibling.test( tokens[0].type ) && context.parentNode || context
- )) ) {
-
- // If seed is empty or no tokens remain, we can return early
- tokens.splice( i, 1 );
- selector = seed.length && toSelector( tokens );
- if ( !selector ) {
- push.apply( results, seed );
- return results;
- }
-
- break;
- }
- }
- }
- }
- }
-
- // Compile and execute a filtering function
- // Provide `match` to avoid retokenization if we modified the selector above
- compile( selector, match )(
- seed,
- context,
- !documentIsHTML,
- results,
- rsibling.test( selector )
- );
- return results;
-}
-
-// Deprecated
-Expr.pseudos["nth"] = Expr.pseudos["eq"];
-
-// Easy API for creating new setFilters
-function setFilters() {}
-setFilters.prototype = Expr.filters = Expr.pseudos;
-Expr.setFilters = new setFilters();
-
-// Check sort stability
-support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
-
-// Initialize with the default document
-setDocument();
-
-// Always assume the presence of duplicates if sort doesn't
-// pass them to our comparison function (as in Google Chrome).
-[0, 0].sort( sortOrder );
-support.detectDuplicates = hasDuplicate;
-
-/*
-// EXPOSE
-if ( typeof define === "function" && define.amd ) {
- define(function() { return Sizzle; });
-} else {
- window.Sizzle = Sizzle;
-}
-*/
-
-// EXPOSE
-return Sizzle;
-});
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/StyleSheetLoader.js b/common/static/js/vendor/tinymce/js/tinymce/classes/dom/StyleSheetLoader.js
deleted file mode 100755
index cf385acb34..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/StyleSheetLoader.js
+++ /dev/null
@@ -1,185 +0,0 @@
-/**
- * StyleSheetLoader.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class handles loading of external stylesheets and fires events when these are loaded.
- *
- * @class tinymce.dom.StyleSheetLoader
- * @private
- */
-define("tinymce/dom/StyleSheetLoader", [], function() {
- "use strict";
-
- return function(document, settings) {
- var idCount = 0, loadedStates = {}, maxLoadTime;
-
- settings = settings || {};
- maxLoadTime = settings.maxLoadTime || 5000;
-
- function appendToHead(node) {
- document.getElementsByTagName('head')[0].appendChild(node);
- }
-
- /**
- * Loads the specified css style sheet file and call the loadedCallback once it's finished loading.
- *
- * @method load
- * @param {String} url Url to be loaded.
- * @param {Function} loadedCallback Callback to be executed when loaded.
- * @param {Function} errorCallback Callback to be executed when failed loading.
- */
- function load(url, loadedCallback, errorCallback) {
- var link, style, startTime, state;
-
- function passed() {
- var callbacks = state.passed, i = callbacks.length;
-
- while (i--) {
- callbacks[i]();
- }
-
- state.status = 2;
- state.passed = [];
- state.failed = [];
- }
-
- function failed() {
- var callbacks = state.failed, i = callbacks.length;
-
- while (i--) {
- callbacks[i]();
- }
-
- state.status = 3;
- state.passed = [];
- state.failed = [];
- }
-
- // Sniffs for older WebKit versions that have the link.onload but a broken one
- function isOldWebKit() {
- var webKitChunks = navigator.userAgent.match(/WebKit\/(\d*)/);
- return !!(webKitChunks && webKitChunks[1] < 536);
- }
-
- // Calls the waitCallback until the test returns true or the timeout occurs
- function wait(testCallback, waitCallback) {
- if (!testCallback()) {
- // Wait for timeout
- if ((new Date().getTime()) - startTime < maxLoadTime) {
- window.setTimeout(waitCallback, 0);
- } else {
- failed();
- }
- }
- }
-
- // Workaround for WebKit that doesn't properly support the onload event for link elements
- // Or WebKit that fires the onload event before the StyleSheet is added to the document
- function waitForWebKitLinkLoaded() {
- wait(function() {
- var styleSheets = document.styleSheets, styleSheet, i = styleSheets.length, owner;
-
- while (i--) {
- styleSheet = styleSheets[i];
- owner = styleSheet.ownerNode ? styleSheet.ownerNode : styleSheet.owningElement;
- if (owner && owner.id === link.id) {
- passed();
- return true;
- }
- }
- }, waitForWebKitLinkLoaded);
- }
-
- // Workaround for older Geckos that doesn't have any onload event for StyleSheets
- function waitForGeckoLinkLoaded() {
- wait(function() {
- try {
- // Accessing the cssRules will throw an exception until the CSS file is loaded
- var cssRules = style.sheet.cssRules;
- passed();
- return !!cssRules;
- } catch (ex) {
- // Ignore
- }
- }, waitForGeckoLinkLoaded);
- }
-
- if (!loadedStates[url]) {
- state = {
- passed: [],
- failed: []
- };
-
- loadedStates[url] = state;
- } else {
- state = loadedStates[url];
- }
-
- if (loadedCallback) {
- state.passed.push(loadedCallback);
- }
-
- if (errorCallback) {
- state.failed.push(errorCallback);
- }
-
- // Is loading wait for it to pass
- if (state.status == 1) {
- return;
- }
-
- // Has finished loading and was success
- if (state.status == 2) {
- passed();
- return;
- }
-
- // Has finished loading and was a failure
- if (state.status == 3) {
- failed();
- return;
- }
-
- // Start loading
- state.status = 1;
- link = document.createElement('link');
- link.rel = 'stylesheet';
- link.type = 'text/css';
- link.id = 'u' + (idCount++);
- link.async = false;
- link.defer = false;
- startTime = new Date().getTime();
-
- // Feature detect onload on link element and sniff older webkits since it has an broken onload event
- if ("onload" in link && !isOldWebKit()) {
- link.onload = waitForWebKitLinkLoaded;
- link.onerror = failed;
- } else {
- // Sniff for old Firefox that doesn't support the onload event on link elements
- // TODO: Remove this in the future when everyone uses modern browsers
- if (navigator.userAgent.indexOf("Firefox") > 0) {
- style = document.createElement('style');
- style.textContent = '@import "' + url + '"';
- waitForGeckoLinkLoaded();
- appendToHead(style);
- return;
- } else {
- // Use the id owner on older webkits
- waitForWebKitLinkLoaded();
- }
- }
-
- appendToHead(link);
- link.href = url;
- }
-
- this.load = load;
- };
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/TreeWalker.js b/common/static/js/vendor/tinymce/js/tinymce/classes/dom/TreeWalker.js
deleted file mode 100755
index ffe8f0439d..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/TreeWalker.js
+++ /dev/null
@@ -1,79 +0,0 @@
-/**
- * TreeWalker.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * TreeWalker class enables you to walk the DOM in a linear manner.
- *
- * @class tinymce.dom.TreeWalker
- */
-define("tinymce/dom/TreeWalker", [], function() {
- return function(start_node, root_node) {
- var node = start_node;
-
- function findSibling(node, start_name, sibling_name, shallow) {
- var sibling, parent;
-
- if (node) {
- // Walk into nodes if it has a start
- if (!shallow && node[start_name]) {
- return node[start_name];
- }
-
- // Return the sibling if it has one
- if (node != root_node) {
- sibling = node[sibling_name];
- if (sibling) {
- return sibling;
- }
-
- // Walk up the parents to look for siblings
- for (parent = node.parentNode; parent && parent != root_node; parent = parent.parentNode) {
- sibling = parent[sibling_name];
- if (sibling) {
- return sibling;
- }
- }
- }
- }
- }
-
- /**
- * Returns the current node.
- *
- * @method current
- * @return {Node} Current node where the walker is.
- */
- this.current = function() {
- return node;
- };
-
- /**
- * Walks to the next node in tree.
- *
- * @method next
- * @return {Node} Current node where the walker is after moving to the next node.
- */
- this.next = function(shallow) {
- node = findSibling(node, 'firstChild', 'nextSibling', shallow);
- return node;
- };
-
- /**
- * Walks to the previous node in tree.
- *
- * @method prev
- * @return {Node} Current node where the walker is after moving to the previous node.
- */
- this.prev = function(shallow) {
- node = findSibling(node, 'lastChild', 'previousSibling', shallow);
- return node;
- };
- };
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/TridentSelection.js b/common/static/js/vendor/tinymce/js/tinymce/classes/dom/TridentSelection.js
deleted file mode 100755
index 1edb9208c2..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/TridentSelection.js
+++ /dev/null
@@ -1,502 +0,0 @@
-/**
- * TridentSelection.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * Selection class for old explorer versions. This one fakes the
- * native selection object available on modern browsers.
- *
- * @class tinymce.dom.TridentSelection
- */
-define("tinymce/dom/TridentSelection", [], function() {
- function Selection(selection) {
- var self = this, dom = selection.dom, FALSE = false;
-
- function getPosition(rng, start) {
- var checkRng, startIndex = 0, endIndex, inside,
- children, child, offset, index, position = -1, parent;
-
- // Setup test range, collapse it and get the parent
- checkRng = rng.duplicate();
- checkRng.collapse(start);
- parent = checkRng.parentElement();
-
- // Check if the selection is within the right document
- if (parent.ownerDocument !== selection.dom.doc) {
- return;
- }
-
- // IE will report non editable elements as it's parent so look for an editable one
- while (parent.contentEditable === "false") {
- parent = parent.parentNode;
- }
-
- // If parent doesn't have any children then return that we are inside the element
- if (!parent.hasChildNodes()) {
- return {node: parent, inside: 1};
- }
-
- // Setup node list and endIndex
- children = parent.children;
- endIndex = children.length - 1;
-
- // Perform a binary search for the position
- while (startIndex <= endIndex) {
- index = Math.floor((startIndex + endIndex) / 2);
-
- // Move selection to node and compare the ranges
- child = children[index];
- checkRng.moveToElementText(child);
- position = checkRng.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', rng);
-
- // Before/after or an exact match
- if (position > 0) {
- endIndex = index - 1;
- } else if (position < 0) {
- startIndex = index + 1;
- } else {
- return {node: child};
- }
- }
-
- // Check if child position is before or we didn't find a position
- if (position < 0) {
- // No element child was found use the parent element and the offset inside that
- if (!child) {
- checkRng.moveToElementText(parent);
- checkRng.collapse(true);
- child = parent;
- inside = true;
- } else {
- checkRng.collapse(false);
- }
-
- // Walk character by character in text node until we hit the selected range endpoint,
- // hit the end of document or parent isn't the right one
- // We need to walk char by char since rng.text or rng.htmlText will trim line endings
- offset = 0;
- while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) {
- if (checkRng.move('character', 1) === 0 || parent != checkRng.parentElement()) {
- break;
- }
-
- offset++;
- }
- } else {
- // Child position is after the selection endpoint
- checkRng.collapse(true);
-
- // Walk character by character in text node until we hit the selected range endpoint, hit
- // the end of document or parent isn't the right one
- offset = 0;
- while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) {
- if (checkRng.move('character', -1) === 0 || parent != checkRng.parentElement()) {
- break;
- }
-
- offset++;
- }
- }
-
- return {node: child, position: position, offset: offset, inside: inside};
- }
-
- // Returns a W3C DOM compatible range object by using the IE Range API
- function getRange() {
- var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed, tmpRange, element2, bookmark;
-
- // If selection is outside the current document just return an empty range
- element = ieRange.item ? ieRange.item(0) : ieRange.parentElement();
- if (element.ownerDocument != dom.doc) {
- return domRange;
- }
-
- collapsed = selection.isCollapsed();
-
- // Handle control selection
- if (ieRange.item) {
- domRange.setStart(element.parentNode, dom.nodeIndex(element));
- domRange.setEnd(domRange.startContainer, domRange.startOffset + 1);
-
- return domRange;
- }
-
- function findEndPoint(start) {
- var endPoint = getPosition(ieRange, start), container, offset, textNodeOffset = 0, sibling, undef, nodeValue;
-
- container = endPoint.node;
- offset = endPoint.offset;
-
- if (endPoint.inside && !container.hasChildNodes()) {
- domRange[start ? 'setStart' : 'setEnd'](container, 0);
- return;
- }
-
- if (offset === undef) {
- domRange[start ? 'setStartBefore' : 'setEndAfter'](container);
- return;
- }
-
- if (endPoint.position < 0) {
- sibling = endPoint.inside ? container.firstChild : container.nextSibling;
-
- if (!sibling) {
- domRange[start ? 'setStartAfter' : 'setEndAfter'](container);
- return;
- }
-
- if (!offset) {
- if (sibling.nodeType == 3) {
- domRange[start ? 'setStart' : 'setEnd'](sibling, 0);
- } else {
- domRange[start ? 'setStartBefore' : 'setEndBefore'](sibling);
- }
-
- return;
- }
-
- // Find the text node and offset
- while (sibling) {
- nodeValue = sibling.nodeValue;
- textNodeOffset += nodeValue.length;
-
- // We are at or passed the position we where looking for
- if (textNodeOffset >= offset) {
- container = sibling;
- textNodeOffset -= offset;
- textNodeOffset = nodeValue.length - textNodeOffset;
- break;
- }
-
- sibling = sibling.nextSibling;
- }
- } else {
- // Find the text node and offset
- sibling = container.previousSibling;
-
- if (!sibling) {
- return domRange[start ? 'setStartBefore' : 'setEndBefore'](container);
- }
-
- // If there isn't any text to loop then use the first position
- if (!offset) {
- if (container.nodeType == 3) {
- domRange[start ? 'setStart' : 'setEnd'](sibling, container.nodeValue.length);
- } else {
- domRange[start ? 'setStartAfter' : 'setEndAfter'](sibling);
- }
-
- return;
- }
-
- while (sibling) {
- textNodeOffset += sibling.nodeValue.length;
-
- // We are at or passed the position we where looking for
- if (textNodeOffset >= offset) {
- container = sibling;
- textNodeOffset -= offset;
- break;
- }
-
- sibling = sibling.previousSibling;
- }
- }
-
- domRange[start ? 'setStart' : 'setEnd'](container, textNodeOffset);
- }
-
- try {
- // Find start point
- findEndPoint(true);
-
- // Find end point if needed
- if (!collapsed) {
- findEndPoint();
- }
- } catch (ex) {
- // IE has a nasty bug where text nodes might throw "invalid argument" when you
- // access the nodeValue or other properties of text nodes. This seems to happend when
- // text nodes are split into two nodes by a delete/backspace call. So lets detect it and try to fix it.
- if (ex.number == -2147024809) {
- // Get the current selection
- bookmark = self.getBookmark(2);
-
- // Get start element
- tmpRange = ieRange.duplicate();
- tmpRange.collapse(true);
- element = tmpRange.parentElement();
-
- // Get end element
- if (!collapsed) {
- tmpRange = ieRange.duplicate();
- tmpRange.collapse(false);
- element2 = tmpRange.parentElement();
- element2.innerHTML = element2.innerHTML;
- }
-
- // Remove the broken elements
- element.innerHTML = element.innerHTML;
-
- // Restore the selection
- self.moveToBookmark(bookmark);
-
- // Since the range has moved we need to re-get it
- ieRange = selection.getRng();
-
- // Find start point
- findEndPoint(true);
-
- // Find end point if needed
- if (!collapsed) {
- findEndPoint();
- }
- } else {
- throw ex; // Throw other errors
- }
- }
-
- return domRange;
- }
-
- this.getBookmark = function(type) {
- var rng = selection.getRng(), bookmark = {};
-
- function getIndexes(node) {
- var parent, root, children, i, indexes = [];
-
- parent = node.parentNode;
- root = dom.getRoot().parentNode;
-
- while (parent != root && parent.nodeType !== 9) {
- children = parent.children;
-
- i = children.length;
- while (i--) {
- if (node === children[i]) {
- indexes.push(i);
- break;
- }
- }
-
- node = parent;
- parent = parent.parentNode;
- }
-
- return indexes;
- }
-
- function getBookmarkEndPoint(start) {
- var position;
-
- position = getPosition(rng, start);
- if (position) {
- return {
- position: position.position,
- offset: position.offset,
- indexes: getIndexes(position.node),
- inside: position.inside
- };
- }
- }
-
- // Non ubstructive bookmark
- if (type === 2) {
- // Handle text selection
- if (!rng.item) {
- bookmark.start = getBookmarkEndPoint(true);
-
- if (!selection.isCollapsed()) {
- bookmark.end = getBookmarkEndPoint();
- }
- } else {
- bookmark.start = {ctrl: true, indexes: getIndexes(rng.item(0))};
- }
- }
-
- return bookmark;
- };
-
- this.moveToBookmark = function(bookmark) {
- var rng, body = dom.doc.body;
-
- function resolveIndexes(indexes) {
- var node, i, idx, children;
-
- node = dom.getRoot();
- for (i = indexes.length - 1; i >= 0; i--) {
- children = node.children;
- idx = indexes[i];
-
- if (idx <= children.length - 1) {
- node = children[idx];
- }
- }
-
- return node;
- }
-
- function setBookmarkEndPoint(start) {
- var endPoint = bookmark[start ? 'start' : 'end'], moveLeft, moveRng, undef, offset;
-
- if (endPoint) {
- moveLeft = endPoint.position > 0;
-
- moveRng = body.createTextRange();
- moveRng.moveToElementText(resolveIndexes(endPoint.indexes));
-
- offset = endPoint.offset;
- if (offset !== undef) {
- moveRng.collapse(endPoint.inside || moveLeft);
- moveRng.moveStart('character', moveLeft ? -offset : offset);
- } else {
- moveRng.collapse(start);
- }
-
- rng.setEndPoint(start ? 'StartToStart' : 'EndToStart', moveRng);
-
- if (start) {
- rng.collapse(true);
- }
- }
- }
-
- if (bookmark.start) {
- if (bookmark.start.ctrl) {
- rng = body.createControlRange();
- rng.addElement(resolveIndexes(bookmark.start.indexes));
- rng.select();
- } else {
- rng = body.createTextRange();
- setBookmarkEndPoint(true);
- setBookmarkEndPoint();
- rng.select();
- }
- }
- };
-
- this.addRange = function(rng) {
- var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, sibling,
- doc = selection.dom.doc, body = doc.body, nativeRng, ctrlElm;
-
- function setEndPoint(start) {
- var container, offset, marker, tmpRng, nodes;
-
- marker = dom.create('a');
- container = start ? startContainer : endContainer;
- offset = start ? startOffset : endOffset;
- tmpRng = ieRng.duplicate();
-
- if (container == doc || container == doc.documentElement) {
- container = body;
- offset = 0;
- }
-
- if (container.nodeType == 3) {
- container.parentNode.insertBefore(marker, container);
- tmpRng.moveToElementText(marker);
- tmpRng.moveStart('character', offset);
- dom.remove(marker);
- ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng);
- } else {
- nodes = container.childNodes;
-
- if (nodes.length) {
- if (offset >= nodes.length) {
- dom.insertAfter(marker, nodes[nodes.length - 1]);
- } else {
- container.insertBefore(marker, nodes[offset]);
- }
-
- tmpRng.moveToElementText(marker);
- } else if (container.canHaveHTML) {
- // Empty node selection for example content
');
- *
- * @class tinymce.html.DomParser
- * @version 3.4
- */
-define("tinymce/html/DomParser", [
- "tinymce/html/Node",
- "tinymce/html/Schema",
- "tinymce/html/SaxParser",
- "tinymce/util/Tools"
-], function(Node, Schema, SaxParser, Tools) {
- var makeMap = Tools.makeMap, each = Tools.each, explode = Tools.explode, extend = Tools.extend;
-
- /**
- * Constructs a new DomParser instance.
- *
- * @constructor
- * @method DomParser
- * @param {Object} settings Name/value collection of settings. comment, cdata, text, start and end are callbacks.
- * @param {tinymce.html.Schema} schema HTML Schema class to use when parsing.
- */
- return function(settings, schema) {
- var self = this, nodeFilters = {}, attributeFilters = [], matchedNodes = {}, matchedAttributes = {};
-
- settings = settings || {};
- settings.validate = "validate" in settings ? settings.validate : true;
- settings.root_name = settings.root_name || 'body';
- self.schema = schema = schema || new Schema();
-
- function fixInvalidChildren(nodes) {
- var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i;
- var nonEmptyElements, nonSplitableElements, textBlockElements, sibling, nextNode;
-
- nonSplitableElements = makeMap('tr,td,th,tbody,thead,tfoot,table');
- nonEmptyElements = schema.getNonEmptyElements();
- textBlockElements = schema.getTextBlockElements();
-
- for (ni = 0; ni < nodes.length; ni++) {
- node = nodes[ni];
-
- // Already removed or fixed
- if (!node.parent || node.fixed) {
- continue;
- }
-
- // If the invalid element is a text block and the text block is within a parent LI element
- // Then unwrap the first text block and convert other sibling text blocks to LI elements similar to Word/Open Office
- if (textBlockElements[node.name] && node.parent.name == 'li') {
- // Move sibling text blocks after LI element
- sibling = node.next;
- while (sibling) {
- if (textBlockElements[sibling.name]) {
- sibling.name = 'li';
- sibling.fixed = true;
- node.parent.insert(sibling, node.parent);
- } else {
- break;
- }
-
- sibling = sibling.next;
- }
-
- // Unwrap current text block
- node.unwrap(node);
- continue;
- }
-
- // Get list of all parent nodes until we find a valid parent to stick the child into
- parents = [node];
- for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) &&
- !nonSplitableElements[parent.name]; parent = parent.parent) {
- parents.push(parent);
- }
-
- // Found a suitable parent
- if (parent && parents.length > 1) {
- // Reverse the array since it makes looping easier
- parents.reverse();
-
- // Clone the related parent and insert that after the moved node
- newParent = currentNode = self.filterNode(parents[0].clone());
-
- // Start cloning and moving children on the left side of the target node
- for (i = 0; i < parents.length - 1; i++) {
- if (schema.isValidChild(currentNode.name, parents[i].name)) {
- tempNode = self.filterNode(parents[i].clone());
- currentNode.append(tempNode);
- } else {
- tempNode = currentNode;
- }
-
- for (childNode = parents[i].firstChild; childNode && childNode != parents[i + 1]; ) {
- nextNode = childNode.next;
- tempNode.append(childNode);
- childNode = nextNode;
- }
-
- currentNode = tempNode;
- }
-
- if (!newParent.isEmpty(nonEmptyElements)) {
- parent.insert(newParent, parents[0], true);
- parent.insert(node, newParent);
- } else {
- parent.insert(node, parents[0], true);
- }
-
- // Check if the element is empty by looking through it's contents and special treatment for
or
- if (!empty) {
- node = newNode;
- }
-
- // Check if we are inside a whitespace preserved element
- if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
- isInWhiteSpacePreservedElement = true;
- }
- }
- },
-
- end: function(name) {
- var textNode, elementRule, text, sibling, tempNode;
-
- elementRule = validate ? schema.getElementRule(name) : {};
- if (elementRule) {
- if (blockElements[name]) {
- if (!isInWhiteSpacePreservedElement) {
- // Trim whitespace of the first node in a block
- textNode = node.firstChild;
- if (textNode && textNode.type === 3) {
- text = textNode.value.replace(startWhiteSpaceRegExp, '');
-
- // Any characters left after trim or should we remove it
- if (text.length > 0) {
- textNode.value = text;
- textNode = textNode.next;
- } else {
- sibling = textNode.next;
- textNode.remove();
- textNode = sibling;
-
- // Remove any pure whitespace siblings
- while (textNode && textNode.type === 3) {
- text = textNode.value;
- sibling = textNode.next;
-
- if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
- textNode.remove();
- textNode = sibling;
- }
-
- textNode = sibling;
- }
- }
- }
-
- // Trim whitespace of the last node in a block
- textNode = node.lastChild;
- if (textNode && textNode.type === 3) {
- text = textNode.value.replace(endWhiteSpaceRegExp, '');
-
- // Any characters left after trim or should we remove it
- if (text.length > 0) {
- textNode.value = text;
- textNode = textNode.prev;
- } else {
- sibling = textNode.prev;
- textNode.remove();
- textNode = sibling;
-
- // Remove any pure whitespace siblings
- while (textNode && textNode.type === 3) {
- text = textNode.value;
- sibling = textNode.prev;
-
- if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
- textNode.remove();
- textNode = sibling;
- }
-
- textNode = sibling;
- }
- }
- }
- }
-
- // Trim start white space
- // Removed due to: #5424
- /*textNode = node.prev;
- if (textNode && textNode.type === 3) {
- text = textNode.value.replace(startWhiteSpaceRegExp, '');
-
- if (text.length > 0)
- textNode.value = text;
- else
- textNode.remove();
- }*/
- }
-
- // Check if we exited a whitespace preserved element
- if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
- isInWhiteSpacePreservedElement = false;
- }
-
- // Handle empty nodes
- if (elementRule.removeEmpty || elementRule.paddEmpty) {
- if (node.isEmpty(nonEmptyElements)) {
- if (elementRule.paddEmpty) {
- node.empty().append(new Node('#text', '3')).value = '\u00a0';
- } else {
- // Leave nodes that have a name like
- if (!node.attributes.map.name && !node.attributes.map.id) {
- tempNode = node.parent;
- node.empty().remove();
- node = tempNode;
- return;
- }
- }
- }
- }
-
- node = node.parent;
- }
- }
- }, schema);
-
- rootNode = node = new Node(args.context || settings.root_name, 11);
-
- parser.parse(html);
-
- // Fix invalid children or report invalid children in a contextual parsing
- if (validate && invalidChildren.length) {
- if (!args.context) {
- fixInvalidChildren(invalidChildren);
- } else {
- args.invalid = true;
- }
- }
-
- // Wrap nodes in the root into block elements if the root is body
- if (rootBlockName && (rootNode.name == 'body' || args.isRootContent)) {
- addRootBlocks();
- }
-
- // Run filters only when the contents is valid
- if (!args.invalid) {
- // Run node filters
- for (name in matchedNodes) {
- list = nodeFilters[name];
- nodes = matchedNodes[name];
-
- // Remove already removed children
- fi = nodes.length;
- while (fi--) {
- if (!nodes[fi].parent) {
- nodes.splice(fi, 1);
- }
- }
-
- for (i = 0, l = list.length; i < l; i++) {
- list[i](nodes, name, args);
- }
- }
-
- // Run attribute filters
- for (i = 0, l = attributeFilters.length; i < l; i++) {
- list = attributeFilters[i];
-
- if (list.name in matchedAttributes) {
- nodes = matchedAttributes[list.name];
-
- // Remove already removed children
- fi = nodes.length;
- while (fi--) {
- if (!nodes[fi].parent) {
- nodes.splice(fi, 1);
- }
- }
-
- for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
- list.callbacks[fi](nodes, list.name, args);
- }
- }
- }
- }
-
- return rootNode;
- };
-
- // Remove
at end of block elements Gecko and WebKit injects BR elements to
- // make it possible to place the caret inside empty blocks. This logic tries to remove
- // these elements and keep br elements that where intended to be there intact
- if (settings.remove_trailing_brs) {
- self.addNodeFilter('br', function(nodes) {
- var i, l = nodes.length, node, blockElements = extend({}, schema.getBlockElements());
- var nonEmptyElements = schema.getNonEmptyElements(), parent, lastParent, prev, prevName;
- var elementRule, textNode;
-
- // Remove brs from body element as well
- blockElements.body = 1;
-
- // Must loop forwards since it will otherwise remove all brs in
structure then don't remove anything
- if (prevName === 'br') {
- node = null;
- break;
- }
- }
-
- prev = prev.prev;
- }
-
- if (node) {
- node.remove();
-
- // Is the parent to be considered empty after we removed the BR
- if (parent.isEmpty(nonEmptyElements)) {
- elementRule = schema.getElementRule(parent.name);
-
- // Remove or padd the element depending on schema rule
- if (elementRule) {
- if (elementRule.removeEmpty) {
- parent.remove();
- } else if (elementRule.paddEmpty) {
- parent.empty().append(new Node('#text', 3)).value = '\u00a0';
- }
- }
- }
- }
- } else {
- // Replaces BR elements inside inline elements like
- if (elements[node.name]) {
- return false;
- }
-
- // Keep elements with data attributes or name attribute like
- i = node.attributes.length;
- while (i--) {
- name = node.attributes[i].name;
- if (name === "name" || name.indexOf('data-mce-') === 0) {
- return false;
- }
- }
- }
-
- // Keep comments
- if (node.type === 8) {
- return false;
- }
-
- // Keep non whitespace text nodes
- if ((node.type === 3 && !whiteSpaceRegExp.test(node.value))) {
- return false;
- }
- } while ((node = walk(node, self)));
- }
-
- return true;
- },
-
- /**
- * Walks to the next or previous node and returns that node or null if it wasn't found.
- *
- * @method walk
- * @param {Boolean} prev Optional previous node state defaults to false.
- * @return {tinymce.html.Node} Node that is next to or previous of the current node.
- */
- walk: function(prev) {
- return walk(this, null, prev);
- }
- };
-
- /**
- * Creates a node of a specific type.
- *
- * @static
- * @method create
- * @param {String} name Name of the node type to create for example "b" or "#text".
- * @param {Object} attrs Name/value collection of attributes that will be applied to elements.
- */
- Node.create = function(name, attrs) {
- var node, attrName;
-
- // Create node
- node = new Node(name, typeLookup[name] || 1);
-
- // Add attributes if needed
- if (attrs) {
- for (attrName in attrs) {
- node.attr(attrName, attrs[attrName]);
- }
- }
-
- return node;
- };
-
- return Node;
-});
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/html/SaxParser.js b/common/static/js/vendor/tinymce/js/tinymce/classes/html/SaxParser.js
deleted file mode 100755
index 80258fde18..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/html/SaxParser.js
+++ /dev/null
@@ -1,423 +0,0 @@
-/**
- * SaxParser.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/*eslint max-depth:[2, 9] */
-
-/**
- * This class parses HTML code using pure JavaScript and executes various events for each item it finds. It will
- * always execute the events in the right order for tag soup code like . It will also remove elements
- * and attributes that doesn't fit the schema if the validate setting is enabled.
- *
- * @example
- * var parser = new tinymce.html.SaxParser({
- * validate: true,
- *
- * comment: function(text) {
- * console.log('Comment:', text);
- * },
- *
- * cdata: function(text) {
- * console.log('CDATA:', text);
- * },
- *
- * text: function(text, raw) {
- * console.log('Text:', text, 'Raw:', raw);
- * },
- *
- * start: function(name, attrs, empty) {
- * console.log('Start:', name, attrs, empty);
- * },
- *
- * end: function(name) {
- * console.log('End:', name);
- * },
- *
- * pi: function(name, text) {
- * console.log('PI:', name, text);
- * },
- *
- * doctype: function(text) {
- * console.log('DocType:', text);
- * }
- * }, schema);
- * @class tinymce.html.SaxParser
- * @version 3.4
- */
-define("tinymce/html/SaxParser", [
- "tinymce/html/Schema",
- "tinymce/html/Entities",
- "tinymce/util/Tools"
-], function(Schema, Entities, Tools) {
- var each = Tools.each;
-
- /**
- * Constructs a new SaxParser instance.
- *
- * @constructor
- * @method SaxParser
- * @param {Object} settings Name/value collection of settings. comment, cdata, text, start and end are callbacks.
- * @param {tinymce.html.Schema} schema HTML Schema class to use when parsing.
- */
- return function(settings, schema) {
- var self = this;
-
- function noop() {}
-
- settings = settings || {};
- self.schema = schema = schema || new Schema();
-
- if (settings.fix_self_closing !== false) {
- settings.fix_self_closing = true;
- }
-
- // Add handler functions from settings and setup default handlers
- each('comment cdata text start end pi doctype'.split(' '), function(name) {
- if (name) {
- self[name] = settings[name] || noop;
- }
- });
-
- /**
- * Parses the specified HTML string and executes the callbacks for each item it finds.
- *
- * @example
- * new SaxParser({...}).parse('text');
- * @method parse
- * @param {String} html Html string to sax parse.
- */
- self.parse = function(html) {
- var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name;
- var isInternalElement, removeInternalElements, shortEndedElements, fillAttrsMap, isShortEnded;
- var validate, elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
- var attributesRequired, attributesDefault, attributesForced;
- var anyAttributesRequired, selfClosing, tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0;
- var decode = Entities.decode, fixSelfClosing, filteredUrlAttrs = Tools.makeMap('src,href');
- var scriptUriRegExp = /(java|vb)script:/i;
-
- function processEndTag(name) {
- var pos, i;
-
- // Find position of parent of the same type
- pos = stack.length;
- while (pos--) {
- if (stack[pos].name === name) {
- break;
- }
- }
-
- // Found parent
- if (pos >= 0) {
- // Close all the open elements
- for (i = stack.length - 1; i >= pos; i--) {
- name = stack[i];
-
- if (name.valid) {
- self.end(name.name);
- }
- }
-
- // Remove the open elements from the stack
- stack.length = pos;
- }
- }
-
- function parseAttribute(match, name, value, val2, val3) {
- var attrRule, i, trimRegExp = /[\s\u0000-\u001F]+/g;
-
- name = name.toLowerCase();
- value = name in fillAttrsMap ? name : decode(value || val2 || val3 || ''); // Handle boolean attribute than value attribute
-
- // Validate name and value pass through all data- attributes
- if (validate && !isInternalElement && name.indexOf('data-') !== 0) {
- attrRule = validAttributesMap[name];
-
- // Find rule by pattern matching
- if (!attrRule && validAttributePatterns) {
- i = validAttributePatterns.length;
- while (i--) {
- attrRule = validAttributePatterns[i];
- if (attrRule.pattern.test(name)) {
- break;
- }
- }
-
- // No rule matched
- if (i === -1) {
- attrRule = null;
- }
- }
-
- // No attribute rule found
- if (!attrRule) {
- return;
- }
-
- // Validate value
- if (attrRule.validValues && !(value in attrRule.validValues)) {
- return;
- }
- }
-
- // Block any javascript: urls
- if (filteredUrlAttrs[name] && !settings.allow_script_urls) {
- var uri = value.replace(trimRegExp, '');
-
- try {
- // Might throw malformed URI sequence
- uri = decodeURIComponent(uri);
- if (scriptUriRegExp.test(uri)) {
- return;
- }
- } catch (ex) {
- // Fallback to non UTF-8 decoder
- uri = unescape(uri);
- if (scriptUriRegExp.test(uri)) {
- return;
- }
- }
- }
-
- // Add attribute to list and map
- attrList.map[name] = value;
- attrList.push({
- name: name,
- value: value
- });
- }
-
- // Precompile RegExps and map objects
- tokenRegExp = new RegExp('<(?:' +
- '(?:!--([\\w\\W]*?)-->)|' + // Comment
- '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|' + // CDATA
- '(?:!DOCTYPE([\\w\\W]*?)>)|' + // DOCTYPE
- '(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + // PI
- '(?:\\/([^>]+)>)|' + // End element
- '(?:([A-Za-z0-9\\-\\:\\.]+)((?:\\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\\/|\\s+)>)' + // Start element
- ')', 'g');
-
- attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;
-
- // Setup lookup tables for empty elements and boolean attributes
- shortEndedElements = schema.getShortEndedElements();
- selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
- fillAttrsMap = schema.getBoolAttrs();
- validate = settings.validate;
- removeInternalElements = settings.remove_internals;
- fixSelfClosing = settings.fix_self_closing;
- specialElements = schema.getSpecialElements();
-
- while ((matches = tokenRegExp.exec(html))) {
- // Text
- if (index < matches.index) {
- self.text(decode(html.substr(index, matches.index - index)));
- }
-
- if ((value = matches[6])) { // End element
- value = value.toLowerCase();
-
- // IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements
- if (value.charAt(0) === ':') {
- value = value.substr(1);
- }
-
- processEndTag(value);
- } else if ((value = matches[7])) { // Start element
- value = value.toLowerCase();
-
- // IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements
- if (value.charAt(0) === ':') {
- value = value.substr(1);
- }
-
- isShortEnded = value in shortEndedElements;
-
- // Is self closing tag for example an
.
- */
- start: function(name, attrs, empty) {
- var i, l, attr, value;
-
- if (indent && indentBefore[name] && html.length > 0) {
- value = html[html.length - 1];
-
- if (value.length > 0 && value !== '\n') {
- html.push('\n');
- }
- }
-
- html.push('<', name);
-
- if (attrs) {
- for (i = 0, l = attrs.length; i < l; i++) {
- attr = attrs[i];
- html.push(' ', attr.name, '="', encode(attr.value, true), '"');
- }
- }
-
- if (!empty || htmlOutput) {
- html[html.length] = '>';
- } else {
- html[html.length] = ' />';
- }
-
- if (empty && indent && indentAfter[name] && html.length > 0) {
- value = html[html.length - 1];
-
- if (value.length > 0 && value !== '\n') {
- html.push('\n');
- }
- }
- },
-
- /**
- * Writes the a end element such as a
ab
- *
- * This fixes the backspace to produce:
- *
a|b
- *
- * See bug: https://bugs.webkit.org/show_bug.cgi?id=45784
- *
- * This fixes the following delete scenarios:
- * 1. Delete by pressing backspace key.
- * 2. Delete by pressing delete key.
- * 3. Delete by pressing backspace key with ctrl/cmd (Word delete).
- * 4. Delete by pressing delete key with ctrl/cmd (Word delete).
- * 5. Delete by drag/dropping contents inside the editor.
- * 6. Delete by using Cut Ctrl+X/Cmd+X.
- * 7. Delete by selecting contents and writing a character.'
- *
- * This code is a ugly hack since writing full custom delete logic for just this bug
- * fix seemed like a huge task. I hope we can remove this before the year 2030.
- */
- function cleanupStylesWhenDeleting() {
- var doc = editor.getDoc(), urlPrefix = 'data:text/mce-internal,';
- var MutationObserver = window.MutationObserver, olderWebKit;
-
- // Add mini polyfill for older WebKits
- // TODO: Remove this when old Safari versions gets updated
- if (!MutationObserver) {
- olderWebKit = true;
-
- MutationObserver = function() {
- var records = [], target;
-
- function nodeInsert(e) {
- var target = e.relatedNode || e.target;
- records.push({target: target, addedNodes: [target]});
- }
-
- function attrModified(e) {
- var target = e.relatedNode || e.target;
- records.push({target: target, attributeName: e.attrName});
- }
-
- this.observe = function(node) {
- target = node;
- target.addEventListener('DOMSubtreeModified', nodeInsert, false);
- target.addEventListener('DOMNodeInsertedIntoDocument', nodeInsert, false);
- target.addEventListener('DOMNodeInserted', nodeInsert, false);
- target.addEventListener('DOMAttrModified', attrModified, false);
- };
-
- this.disconnect = function() {
- target.removeEventListener('DOMNodeInserted', nodeInsert);
- target.removeEventListener('DOMAttrModified', attrModified);
- target.removeEventListener('DOMSubtreeModified', nodeInsert, false);
- };
-
- this.takeRecords = function() {
- return records;
- };
- };
- }
-
- function customDelete(isForward) {
- var mutationObserver = new MutationObserver(function() {});
-
- Tools.each(editor.getBody().getElementsByTagName('*'), function(elm) {
- // Mark existing spans
- if (elm.tagName == 'SPAN') {
- elm.setAttribute('mce-data-marked', 1);
- }
-
- // Make sure all elements has a data-mce-style attribute
- if (!elm.hasAttribute('data-mce-style') && elm.hasAttribute('style')) {
- editor.dom.setAttrib(elm, 'style', elm.getAttribute('style'));
- }
- });
-
- // Observe added nodes and style attribute changes
- mutationObserver.observe(editor.getDoc(), {
- childList: true,
- attributes: true,
- subtree: true,
- attributeFilter: ['style']
- });
-
- editor.getDoc().execCommand(isForward ? 'ForwardDelete' : 'Delete', false, null);
-
- var rng = editor.selection.getRng();
- var caretElement = rng.startContainer.parentNode;
-
- Tools.each(mutationObserver.takeRecords(), function(record) {
- // Restore style attribute to previous value
- if (record.attributeName == "style") {
- var oldValue = record.target.getAttribute('data-mce-style');
-
- if (oldValue) {
- record.target.setAttribute("style", oldValue);
- } else {
- record.target.removeAttribute("style");
- }
- }
-
- // Remove all spans that isn't maked and retain selection
- Tools.each(record.addedNodes, function(node) {
- if (node.nodeName == "SPAN" && !node.getAttribute('mce-data-marked')) {
- var offset, container;
-
- if (node == caretElement) {
- offset = rng.startOffset;
- container = node.firstChild;
- }
-
- dom.remove(node, true);
-
- if (container) {
- rng.setStart(container, offset);
- rng.setEnd(container, offset);
- editor.selection.setRng(rng);
- }
- }
- });
- });
-
- mutationObserver.disconnect();
-
- // Remove any left over marks
- Tools.each(editor.dom.select('span[mce-data-marked]'), function(span) {
- span.removeAttribute('mce-data-marked');
- });
- }
-
- editor.on('keydown', function(e) {
- var isForward = e.keyCode == DELETE, isMeta = VK.metaKeyPressed(e);
-
- if (!isDefaultPrevented(e) && (isForward || e.keyCode == BACKSPACE)) {
- var rng = editor.selection.getRng(), container = rng.startContainer, offset = rng.startOffset;
-
- // Ignore non meta delete in the where there is text before/after the caret
- if (!isMeta && rng.collapsed && container.nodeType == 3) {
- if (isForward ? offset < container.data.length : offset > 0) {
- return;
- }
- }
-
- e.preventDefault();
-
- if (isMeta) {
- editor.selection.getSel().modify("extend", isForward ? "forward" : "backward", "word");
- }
-
- customDelete(isForward);
- }
- });
-
- editor.on('keypress', function(e) {
- if (!isDefaultPrevented(e) && !selection.isCollapsed() && e.charCode && !VK.metaKeyPressed(e)) {
- e.preventDefault();
- customDelete(true);
- editor.selection.setContent(String.fromCharCode(e.charCode));
- }
- });
-
- editor.addCommand('Delete', function() {
- customDelete();
- });
-
- editor.addCommand('ForwardDelete', function() {
- customDelete(true);
- });
-
- // Older WebKits doesn't properly handle the clipboard so we can't add the rest
- if (olderWebKit) {
- return;
- }
-
- editor.on('dragstart', function(e) {
- // Safari doesn't support custom dataTransfer items so we can only use URL and Text
- e.dataTransfer.setData('URL', 'data:text/mce-internal,' + escape(editor.selection.getContent()));
- });
-
- editor.on('drop', function(e) {
- if (!isDefaultPrevented(e)) {
- var internalContent = e.dataTransfer.getData('URL');
-
- if (!internalContent || internalContent.indexOf(urlPrefix) == -1 || !doc.caretRangeFromPoint) {
- return;
- }
-
- internalContent = unescape(internalContent.substr(urlPrefix.length));
- if (doc.caretRangeFromPoint) {
- e.preventDefault();
- customDelete();
- editor.selection.setRng(doc.caretRangeFromPoint(e.x, e.y));
- editor.insertContent(internalContent);
- }
- }
- });
-
- editor.on('cut', function(e) {
- if (!isDefaultPrevented(e) && e.clipboardData) {
- e.preventDefault();
- e.clipboardData.clearData();
- e.clipboardData.setData('text/html', editor.selection.getContent());
- e.clipboardData.setData('text/plain', editor.selection.getContent({format: 'text'}));
- customDelete(true);
- }
- });
- }
-
- /**
- * Makes sure that the editor body becomes empty when backspace or delete is pressed in empty editors.
- *
- * For example:
- *
|
- *
- * Or:
- * []
- */
- function emptyEditorWhenDeleting() {
- function serializeRng(rng) {
- var body = dom.create("body");
- var contents = rng.cloneContents();
- body.appendChild(contents);
- return selection.serializer.serialize(body, {format: 'html'});
- }
-
- function allContentsSelected(rng) {
- if (!rng.setStart) {
- if (rng.item) {
- return false;
- }
-
- var bodyRng = rng.duplicate();
- bodyRng.moveToElementText(editor.getBody());
- return RangeUtils.compareRanges(rng, bodyRng);
- }
-
- var selection = serializeRng(rng);
-
- var allRng = dom.createRng();
- allRng.selectNode(editor.getBody());
-
- var allSelection = serializeRng(allRng);
- return selection === allSelection;
- }
-
- editor.on('keydown', function(e) {
- var keyCode = e.keyCode, isCollapsed, body;
-
- // Empty the editor if it's needed for example backspace at
- *
- * Becomes:
- *
- */
- function doubleTrailingBrElements() {
- if (!editor.inline) {
- editor.on('focus blur', function() {
- var br = editor.dom.create('br');
- editor.getBody().appendChild(br);
- br.parentNode.removeChild(br);
- }, true);
- }
- }
-
- /**
- * iOS 7.1 introduced two new bugs:
- * 1) It's possible to open links within a contentEditable area by clicking on them.
- * 2) If you hold down the finger it will display the link/image touch callout menu.
- */
- function tapLinksAndImages() {
- editor.on('click', function(e) {
- if (e.target.tagName === 'A') {
- e.preventDefault();
- }
- });
-
- editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
- }
-
- // All browsers
- disableBackspaceIntoATable();
- removeBlockQuoteOnBackSpace();
- emptyEditorWhenDeleting();
- normalizeSelection();
-
- // WebKit
- if (isWebKit) {
- cleanupStylesWhenDeleting();
- inputMethodFocus();
- selectControlElements();
- setDefaultBlockType();
-
- // iOS
- if (Env.iOS) {
- selectionChangeNodeChanged();
- restoreFocusOnKeyDown();
- bodyHeight();
- tapLinksAndImages();
- } else {
- selectAll();
- }
- }
-
- // IE
- if (isIE && Env.ie < 11) {
- removeHrOnBackspace();
- ensureBodyHasRoleApplication();
- addNewLinesBeforeBrInPre();
- removePreSerializedStylesWhenSelectingControls();
- deleteControlItemOnBackSpace();
- renderEmptyBlocksFix();
- keepNoScriptContents();
- fixCaretSelectionOfDocumentElementOnIe();
- }
-
- if (Env.ie >= 11) {
- bodyHeight();
- doubleTrailingBrElements();
- }
-
- if (Env.ie) {
- selectAll();
- disableAutoUrlDetect();
- }
-
- // Gecko
- if (isGecko) {
- removeHrOnBackspace();
- focusBody();
- removeStylesWhenDeletingAcrossBlockElements();
- setGeckoEditingOptions();
- addBrAfterLastLinks();
- removeGhostSelection();
- showBrokenImageIcon();
- blockCmdArrowNavigation();
- }
- };
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/util/Tools.js b/common/static/js/vendor/tinymce/js/tinymce/classes/util/Tools.js
deleted file mode 100755
index c30101b5e3..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/classes/util/Tools.js
+++ /dev/null
@@ -1,503 +0,0 @@
-/**
- * Tools.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class contains various utlity functions. These are also exposed
- * directly on the tinymce namespace.
- *
- * @class tinymce.util.Tools
- */
-define("tinymce/util/Tools", [], function() {
- /**
- * Removes whitespace from the beginning and end of a string.
- *
- * @method trim
- * @param {String} s String to remove whitespace from.
- * @return {String} New string with removed whitespace.
- */
- var whiteSpaceRegExp = /^\s*|\s*$/g;
-
- function trim(str) {
- return (str === null || str === undefined) ? '' : ("" + str).replace(whiteSpaceRegExp, '');
- }
-
- /**
- * Returns true/false if the object is an array or not.
- *
- * @method isArray
- * @param {Object} obj Object to check.
- * @return {boolean} true/false state if the object is an array or not.
- */
- var isArray = Array.isArray || function(obj) {
- return Object.prototype.toString.call(obj) === "[object Array]";
- };
-
- /**
- * Checks if a object is of a specific type for example an array.
- *
- * @method is
- * @param {Object} o Object to check type of.
- * @param {string} t Optional type to check for.
- * @return {Boolean} true/false if the object is of the specified type.
- */
- function is(o, t) {
- if (!t) {
- return o !== undefined;
- }
-
- if (t == 'array' && isArray(o)) {
- return true;
- }
-
- return typeof(o) == t;
- }
-
- /**
- * Converts the specified object into a real JavaScript array.
- *
- * @method toArray
- * @param {Object} obj Object to convert into array.
- * @return {Array} Array object based in input.
- */
- function toArray(obj) {
- var array = [], i, l;
-
- for (i = 0, l = obj.length; i < l; i++) {
- array[i] = obj[i];
- }
-
- return array;
- }
-
- /**
- * Makes a name/object map out of an array with names.
- *
- * @method makeMap
- * @param {Array/String} items Items to make map out of.
- * @param {String} delim Optional delimiter to split string by.
- * @param {Object} map Optional map to add items to.
- * @return {Object} Name/value map of items.
- */
- function makeMap(items, delim, map) {
- var i;
-
- items = items || [];
- delim = delim || ',';
-
- if (typeof(items) == "string") {
- items = items.split(delim);
- }
-
- map = map || {};
-
- i = items.length;
- while (i--) {
- map[items[i]] = {};
- }
-
- return map;
- }
-
- /**
- * Performs an iteration of all items in a collection such as an object or array. This method will execure the
- * callback function for each item in the collection, if the callback returns false the iteration will terminate.
- * The callback has the following format: cb(value, key_or_index).
- *
- * @method each
- * @param {Object} o Collection to iterate.
- * @param {function} cb Callback function to execute for each item.
- * @param {Object} s Optional scope to execute the callback in.
- * @example
- * // Iterate an array
- * tinymce.each([1,2,3], function(v, i) {
- * console.debug("Value: " + v + ", Index: " + i);
- * });
- *
- * // Iterate an object
- * tinymce.each({a: 1, b: 2, c: 3], function(v, k) {
- * console.debug("Value: " + v + ", Key: " + k);
- * });
- */
- function each(o, cb, s) {
- var n, l;
-
- if (!o) {
- return 0;
- }
-
- s = s || o;
-
- if (o.length !== undefined) {
- // Indexed arrays, needed for Safari
- for (n = 0, l = o.length; n < l; n++) {
- if (cb.call(s, o[n], n, o) === false) {
- return 0;
- }
- }
- } else {
- // Hashtables
- for (n in o) {
- if (o.hasOwnProperty(n)) {
- if (cb.call(s, o[n], n, o) === false) {
- return 0;
- }
- }
- }
- }
-
- return 1;
- }
-
- /**
- * Creates a new array by the return value of each iteration function call. This enables you to convert
- * one array list into another.
- *
- * @method map
- * @param {Array} a Array of items to iterate.
- * @param {function} f Function to call for each item. It's return value will be the new value.
- * @return {Array} Array with new values based on function return values.
- */
- function map(a, f) {
- var o = [];
-
- each(a, function(v) {
- o.push(f(v));
- });
-
- return o;
- }
-
- /**
- * Filters out items from the input array by calling the specified function for each item.
- * If the function returns false the item will be excluded if it returns true it will be included.
- *
- * @method grep
- * @param {Array} a Array of items to loop though.
- * @param {function} f Function to call for each item. Include/exclude depends on it's return value.
- * @return {Array} New array with values imported and filtered based in input.
- * @example
- * // Filter out some items, this will return an array with 4 and 5
- * var items = tinymce.grep([1,2,3,4,5], function(v) {return v > 3;});
- */
- function grep(a, f) {
- var o = [];
-
- each(a, function(v) {
- if (!f || f(v)) {
- o.push(v);
- }
- });
-
- return o;
- }
-
- /**
- * Creates a class, subclass or static singleton.
- * More details on this method can be found in the Wiki.
- *
- * @method create
- * @param {String} s Class name, inheritage and prefix.
- * @param {Object} p Collection of methods to add to the class.
- * @param {Object} root Optional root object defaults to the global window object.
- * @example
- * // Creates a basic class
- * tinymce.create('tinymce.somepackage.SomeClass', {
- * SomeClass: function() {
- * // Class constructor
- * },
- *
- * method: function() {
- * // Some method
- * }
- * });
- *
- * // Creates a basic subclass class
- * tinymce.create('tinymce.somepackage.SomeSubClass:tinymce.somepackage.SomeClass', {
- * SomeSubClass: function() {
- * // Class constructor
- * this.parent(); // Call parent constructor
- * },
- *
- * method: function() {
- * // Some method
- * this.parent(); // Call parent method
- * },
- *
- * 'static': {
- * staticMethod: function() {
- * // Static method
- * }
- * }
- * });
- *
- * // Creates a singleton/static class
- * tinymce.create('static tinymce.somepackage.SomeSingletonClass', {
- * method: function() {
- * // Some method
- * }
- * });
- */
- function create(s, p, root) {
- var self = this, sp, ns, cn, scn, c, de = 0;
-
- // Parse : ]*>/gi, '[quote]');
+ rep(/<\/blockquote>/gi, '[/quote]');
+ rep(/
- *
- * @param {DOMRange} rng DOM Range to get bookmark on.
- * @return {Object} Bookmark object.
- */
- function createBookmark(rng) {
- var bookmark = {};
-
- function setupEndPoint(start) {
- var offsetNode, container, offset;
-
- container = rng[start ? 'startContainer' : 'endContainer'];
- offset = rng[start ? 'startOffset' : 'endOffset'];
-
- if (container.nodeType == 1) {
- offsetNode = dom.create('span', {'data-mce-type': 'bookmark'});
-
- if (container.hasChildNodes()) {
- offset = Math.min(offset, container.childNodes.length - 1);
-
- if (start) {
- container.insertBefore(offsetNode, container.childNodes[offset]);
- } else {
- dom.insertAfter(offsetNode, container.childNodes[offset]);
- }
- } else {
- container.appendChild(offsetNode);
- }
-
- container = offsetNode;
- offset = 0;
- }
-
- bookmark[start ? 'startContainer' : 'endContainer'] = container;
- bookmark[start ? 'startOffset' : 'endOffset'] = offset;
- }
-
- setupEndPoint(true);
-
- if (!rng.collapsed) {
- setupEndPoint();
- }
-
- return bookmark;
- }
-
- /**
- * Moves the selection to the current bookmark and removes any selection container wrappers.
- *
- * @param {Object} bookmark Bookmark object to move selection to.
- */
- function moveToBookmark(bookmark) {
- function restoreEndPoint(start) {
- var container, offset, node;
-
- function nodeIndex(container) {
- var node = container.parentNode.firstChild, idx = 0;
-
- while (node) {
- if (node == container) {
- return idx;
- }
-
- // Skip data-mce-type=bookmark nodes
- if (node.nodeType != 1 || node.getAttribute('data-mce-type') != 'bookmark') {
- idx++;
- }
-
- node = node.nextSibling;
- }
-
- return -1;
- }
-
- container = node = bookmark[start ? 'startContainer' : 'endContainer'];
- offset = bookmark[start ? 'startOffset' : 'endOffset'];
-
- if (!container) {
- return;
- }
-
- if (container.nodeType == 1) {
- offset = nodeIndex(container);
- container = container.parentNode;
- dom.remove(node);
- }
-
- bookmark[start ? 'startContainer' : 'endContainer'] = container;
- bookmark[start ? 'startOffset' : 'endOffset'] = offset;
- }
-
- restoreEndPoint(true);
- restoreEndPoint();
-
- var rng = dom.createRng();
-
- rng.setStart(bookmark.startContainer, bookmark.startOffset);
-
- if (bookmark.endContainer) {
- rng.setEnd(bookmark.endContainer, bookmark.endOffset);
- }
-
- selection.setRng(rng);
- }
-
- function createNewTextBlock(contentNode, blockName) {
- var node, textBlock, fragment = dom.createFragment(), hasContentNode;
- var blockElements = editor.schema.getBlockElements();
-
- if (editor.settings.forced_root_block) {
- blockName = blockName || editor.settings.forced_root_block;
- }
-
- if (blockName) {
- textBlock = dom.create(blockName);
-
- if (textBlock.tagName === editor.settings.forced_root_block) {
- dom.setAttribs(textBlock, editor.settings.forced_root_block_attrs);
- }
-
- fragment.appendChild(textBlock);
- }
-
- if (contentNode) {
- while ((node = contentNode.firstChild)) {
- var nodeName = node.nodeName;
-
- if (!hasContentNode && (nodeName != 'SPAN' || node.getAttribute('data-mce-type') != 'bookmark')) {
- hasContentNode = true;
- }
-
- if (blockElements[nodeName]) {
- fragment.appendChild(node);
- textBlock = null;
- } else {
- if (blockName) {
- if (!textBlock) {
- textBlock = dom.create(blockName);
- fragment.appendChild(textBlock);
- }
-
- textBlock.appendChild(node);
- } else {
- fragment.appendChild(node);
- }
- }
- }
- }
-
- if (!editor.settings.forced_root_block) {
- fragment.appendChild(dom.create('br'));
- } else {
- // BR is needed in empty blocks on non IE browsers
- if (!hasContentNode && (!tinymce.Env.ie || tinymce.Env.ie > 10)) {
- textBlock.appendChild(dom.create('br', {'data-mce-bogus': '1'}));
- }
- }
-
- return fragment;
- }
-
- function getSelectedListItems() {
- return tinymce.grep(selection.getSelectedBlocks(), function(block) {
- return block.nodeName == 'LI';
- });
- }
-
- function splitList(ul, li, newBlock) {
- var tmpRng, fragment;
-
- var bookmarks = dom.select('span[data-mce-type="bookmark"]', ul);
-
- newBlock = newBlock || createNewTextBlock(li);
- tmpRng = dom.createRng();
- tmpRng.setStartAfter(li);
- tmpRng.setEndAfter(ul);
- fragment = tmpRng.extractContents();
-
- if (!dom.isEmpty(fragment)) {
- dom.insertAfter(fragment, ul);
- }
-
- dom.insertAfter(newBlock, ul);
-
- if (dom.isEmpty(li.parentNode)) {
- tinymce.each(bookmarks, function(node) {
- li.parentNode.parentNode.insertBefore(node, li.parentNode);
- });
-
- dom.remove(li.parentNode);
- }
-
- dom.remove(li);
- }
-
- function mergeWithAdjacentLists(listBlock) {
- var sibling, node;
-
- sibling = listBlock.nextSibling;
- if (sibling && isListNode(sibling) && sibling.nodeName == listBlock.nodeName) {
- while ((node = sibling.firstChild)) {
- listBlock.appendChild(node);
- }
-
- dom.remove(sibling);
- }
-
- sibling = listBlock.previousSibling;
- if (sibling && isListNode(sibling) && sibling.nodeName == listBlock.nodeName) {
- while ((node = sibling.firstChild)) {
- listBlock.insertBefore(node, listBlock.firstChild);
- }
-
- dom.remove(sibling);
- }
- }
-
- /**
- * Normalizes the all lists in the specified element.
- */
- function normalizeList(element) {
- tinymce.each(tinymce.grep(dom.select('ol,ul', element)), function(ul) {
- var sibling, parentNode = ul.parentNode;
-
- // Move UL/OL to previous LI if it's the only child of a LI
- if (parentNode.nodeName == 'LI' && parentNode.firstChild == ul) {
- sibling = parentNode.previousSibling;
- if (sibling && sibling.nodeName == 'LI') {
- sibling.appendChild(ul);
-
- if (dom.isEmpty(parentNode)) {
- dom.remove(parentNode);
- }
- }
- }
-
- // Append OL/UL to previous LI if it's in a parent OL/UL i.e. old HTML4
- if (isListNode(parentNode)) {
- sibling = parentNode.previousSibling;
- if (sibling && sibling.nodeName == 'LI') {
- sibling.appendChild(ul);
- }
- }
- });
- }
-
- function outdent(li) {
- var ul = li.parentNode, ulParent = ul.parentNode, newBlock;
-
- function removeEmptyLi(li) {
- if (dom.isEmpty(li)) {
- dom.remove(li);
- }
- }
-
- if (isFirstChild(li) && isLastChild(li)) {
- if (ulParent.nodeName == "LI") {
- dom.insertAfter(li, ulParent);
- removeEmptyLi(ulParent);
- dom.remove(ul);
- } else if (isListNode(ulParent)) {
- dom.remove(ul, true);
- } else {
- ulParent.insertBefore(createNewTextBlock(li), ul);
- dom.remove(ul);
- }
-
- return true;
- } else if (isFirstChild(li)) {
- if (ulParent.nodeName == "LI") {
- dom.insertAfter(li, ulParent);
- li.appendChild(ul);
- removeEmptyLi(ulParent);
- } else if (isListNode(ulParent)) {
- ulParent.insertBefore(li, ul);
- } else {
- ulParent.insertBefore(createNewTextBlock(li), ul);
- dom.remove(li);
- }
-
- return true;
- } else if (isLastChild(li)) {
- if (ulParent.nodeName == "LI") {
- dom.insertAfter(li, ulParent);
- } else if (isListNode(ulParent)) {
- dom.insertAfter(li, ul);
- } else {
- dom.insertAfter(createNewTextBlock(li), ul);
- dom.remove(li);
- }
-
- return true;
- } else {
- if (ulParent.nodeName == 'LI') {
- ul = ulParent;
- newBlock = createNewTextBlock(li, 'LI');
- } else if (isListNode(ulParent)) {
- newBlock = createNewTextBlock(li, 'LI');
- } else {
- newBlock = createNewTextBlock(li);
- }
-
- splitList(ul, li, newBlock);
- normalizeList(ul.parentNode);
-
- return true;
- }
-
- return false;
- }
-
- function indent(li) {
- var sibling, newList;
-
- function mergeLists(from, to) {
- var node;
-
- if (isListNode(from)) {
- while ((node = li.lastChild.firstChild)) {
- to.appendChild(node);
- }
-
- dom.remove(from);
- }
- }
-
- sibling = li.previousSibling;
-
- if (sibling && isListNode(sibling)) {
- sibling.appendChild(li);
- return true;
- }
-
- if (sibling && sibling.nodeName == 'LI' && isListNode(sibling.lastChild)) {
- sibling.lastChild.appendChild(li);
- mergeLists(li.lastChild, sibling.lastChild);
- return true;
- }
-
- sibling = li.nextSibling;
-
- if (sibling && isListNode(sibling)) {
- sibling.insertBefore(li, sibling.firstChild);
- return true;
- }
-
- if (sibling && sibling.nodeName == 'LI' && isListNode(li.lastChild)) {
- return false;
- }
-
- sibling = li.previousSibling;
- if (sibling && sibling.nodeName == 'LI') {
- newList = dom.create(li.parentNode.nodeName);
- sibling.appendChild(newList);
- newList.appendChild(li);
- mergeLists(li.lastChild, newList);
- return true;
- }
-
- return false;
- }
-
- function indentSelection() {
- var listElements = getSelectedListItems();
-
- if (listElements.length) {
- var bookmark = createBookmark(selection.getRng(true));
-
- for (var i = 0; i < listElements.length; i++) {
- if (!indent(listElements[i]) && i === 0) {
- break;
- }
- }
-
- moveToBookmark(bookmark);
- editor.nodeChanged();
-
- return true;
- }
- }
-
- function outdentSelection() {
- var listElements = getSelectedListItems();
-
- if (listElements.length) {
- var bookmark = createBookmark(selection.getRng(true));
- var i, y, root = editor.getBody();
-
- i = listElements.length;
- while (i--) {
- var node = listElements[i].parentNode;
-
- while (node && node != root) {
- y = listElements.length;
- while (y--) {
- if (listElements[y] === node) {
- listElements.splice(i, 1);
- break;
- }
- }
-
- node = node.parentNode;
- }
- }
-
- for (i = 0; i < listElements.length; i++) {
- if (!outdent(listElements[i]) && i === 0) {
- break;
- }
- }
-
- moveToBookmark(bookmark);
- editor.nodeChanged();
-
- return true;
- }
- }
-
- function applyList(listName) {
- var rng = selection.getRng(true), bookmark = createBookmark(rng);
-
- function getSelectedTextBlocks() {
- var textBlocks = [], root = editor.getBody();
-
- function getEndPointNode(start) {
- var container, offset;
-
- container = rng[start ? 'startContainer' : 'endContainer'];
- offset = rng[start ? 'startOffset' : 'endOffset'];
-
- // Resolve node index
- if (container.nodeType == 1) {
- container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
- }
-
- while (container.parentNode != root) {
- if (isTextBlock(container)) {
- return container;
- }
-
- if (/^(TD|TH)$/.test(container.parentNode.nodeName)) {
- return container;
- }
-
- container = container.parentNode;
- }
-
- return container;
- }
-
- var startNode = getEndPointNode(true);
- var endNode = getEndPointNode();
- var block, siblings = [];
-
- for (var node = startNode; node; node = node.nextSibling) {
- siblings.push(node);
-
- if (node == endNode) {
- break;
- }
- }
-
- tinymce.each(siblings, function(node) {
- if (isTextBlock(node)) {
- textBlocks.push(node);
- block = null;
- return;
- }
-
- if (dom.isBlock(node) || node.nodeName == 'BR') {
- if (node.nodeName == 'BR') {
- dom.remove(node);
- }
-
- block = null;
- return;
- }
-
- var nextSibling = node.nextSibling;
- if (isBookmarkNode(node)) {
- if (isTextBlock(nextSibling) || (!nextSibling && node.parentNode == root)) {
- block = null;
- return;
- }
- }
-
- if (!block) {
- block = dom.create('p');
- node.parentNode.insertBefore(block, node);
- textBlocks.push(block);
- }
-
- block.appendChild(node);
- });
-
- return textBlocks;
- }
-
- var textBlocks = getSelectedTextBlocks();
-
- tinymce.each(textBlocks, function(block) {
- var listBlock, sibling;
-
- sibling = block.previousSibling;
- if (sibling && isListNode(sibling) && sibling.nodeName == listName) {
- listBlock = sibling;
- block = dom.rename(block, 'LI');
- sibling.appendChild(block);
- } else {
- listBlock = dom.create(listName);
- block.parentNode.insertBefore(listBlock, block);
- listBlock.appendChild(block);
- block = dom.rename(block, 'LI');
- }
-
- mergeWithAdjacentLists(listBlock);
- });
-
- moveToBookmark(bookmark);
- }
-
- function removeList() {
- var bookmark = createBookmark(selection.getRng(true)), root = editor.getBody();
-
- tinymce.each(getSelectedListItems(), function(li) {
- var node, rootList;
-
- if (dom.isEmpty(li)) {
- outdent(li);
- return;
- }
-
- for (node = li; node && node != root; node = node.parentNode) {
- if (isListNode(node)) {
- rootList = node;
- }
- }
-
- splitList(rootList, li);
- });
-
- moveToBookmark(bookmark);
- }
-
- function toggleList(listName) {
- var parentList = dom.getParent(selection.getStart(), 'OL,UL');
-
- if (parentList) {
- if (parentList.nodeName == listName) {
- removeList(listName);
- } else {
- var bookmark = createBookmark(selection.getRng(true));
- mergeWithAdjacentLists(dom.rename(parentList, listName));
- moveToBookmark(bookmark);
- }
- } else {
- applyList(listName);
- }
- }
-
- self.backspaceDelete = function(isForward) {
- function findNextCaretContainer(rng, isForward) {
- var node = rng.startContainer, offset = rng.startOffset;
-
- if (node.nodeType == 3 && (isForward ? offset < node.data.length : offset > 0)) {
- return node;
- }
-
- var walker = new tinymce.dom.TreeWalker(rng.startContainer);
- while ((node = walker[isForward ? 'next' : 'prev']())) {
- if (node.nodeType == 3 && node.data.length > 0) {
- return node;
- }
- }
- }
-
- function mergeLiElements(fromElm, toElm) {
- var node, listNode, ul = fromElm.parentNode;
-
- if (isListNode(toElm.lastChild)) {
- listNode = toElm.lastChild;
- }
-
- node = toElm.lastChild;
- if (node && node.nodeName == 'BR' && fromElm.hasChildNodes()) {
- dom.remove(node);
- }
-
- while ((node = fromElm.firstChild)) {
- toElm.appendChild(node);
- }
-
- if (listNode) {
- toElm.appendChild(listNode);
- }
-
- dom.remove(fromElm);
-
- if (dom.isEmpty(ul)) {
- dom.remove(ul);
- }
- }
-
- if (selection.isCollapsed()) {
- var li = dom.getParent(selection.getStart(), 'LI');
-
- if (li) {
- var rng = selection.getRng(true);
- var otherLi = dom.getParent(findNextCaretContainer(rng, isForward), 'LI');
-
- if (otherLi && otherLi != li) {
- var bookmark = createBookmark(rng);
-
- if (isForward) {
- mergeLiElements(otherLi, li);
- } else {
- mergeLiElements(li, otherLi);
- }
-
- moveToBookmark(bookmark);
-
- return true;
- } else if (!otherLi) {
- if (!isForward && removeList(li.parentNode.nodeName)) {
- return true;
- }
- }
- }
- }
- };
-
- editor.addCommand('Indent', function() {
- if (!indentSelection()) {
- return true;
- }
- });
-
- editor.addCommand('Outdent', function() {
- if (!outdentSelection()) {
- return true;
- }
- });
-
- editor.addCommand('InsertUnorderedList', function() {
- toggleList('UL');
- });
-
- editor.addCommand('InsertOrderedList', function() {
- toggleList('OL');
- });
-
- editor.on('keydown', function(e) {
- if (e.keyCode == 9 && editor.dom.getParent(editor.selection.getStart(), 'LI')) {
- e.preventDefault();
-
- if (e.shiftKey) {
- outdentSelection();
- } else {
- indentSelection();
- }
- }
- });
- });
-
- editor.addButton('indent', {
- icon: 'indent',
- title: 'Increase indent',
- cmd: 'Indent',
- onPostRender: function() {
- var ctrl = this;
-
- editor.on('nodechange', function() {
- var li = editor.dom.getParent(editor.selection.getNode(), 'LI,UL,OL');
- ctrl.disabled(li && (li.nodeName != 'LI' || isFirstChild(li)));
- });
- }
- });
-
- editor.on('keydown', function(e) {
- if (e.keyCode == tinymce.util.VK.BACKSPACE) {
- if (self.backspaceDelete()) {
- e.preventDefault();
- }
- } else if (e.keyCode == tinymce.util.VK.DELETE) {
- if (self.backspaceDelete(true)) {
- e.preventDefault();
- }
- }
- });
-});
+(function () {
+ 'use strict';
+
+ var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
+
+ var noop = function () {
+ };
+ var constant = function (value) {
+ return function () {
+ return value;
+ };
+ };
+ var not = function (f) {
+ return function (t) {
+ return !f(t);
+ };
+ };
+ var never = constant(false);
+ var always = constant(true);
+
+ var none = function () {
+ return NONE;
+ };
+ var NONE = function () {
+ var eq = function (o) {
+ return o.isNone();
+ };
+ var call = function (thunk) {
+ return thunk();
+ };
+ var id = function (n) {
+ return n;
+ };
+ var me = {
+ fold: function (n, _s) {
+ return n();
+ },
+ is: never,
+ isSome: never,
+ isNone: always,
+ getOr: id,
+ getOrThunk: call,
+ getOrDie: function (msg) {
+ throw new Error(msg || 'error: getOrDie called on none.');
+ },
+ getOrNull: constant(null),
+ getOrUndefined: constant(undefined),
+ or: id,
+ orThunk: call,
+ map: none,
+ each: noop,
+ bind: none,
+ exists: never,
+ forall: always,
+ filter: none,
+ equals: eq,
+ equals_: eq,
+ toArray: function () {
+ return [];
+ },
+ toString: constant('none()')
+ };
+ return me;
+ }();
+ var some = function (a) {
+ var constant_a = constant(a);
+ var self = function () {
+ return me;
+ };
+ var bind = function (f) {
+ return f(a);
+ };
+ var me = {
+ fold: function (n, s) {
+ return s(a);
+ },
+ is: function (v) {
+ return a === v;
+ },
+ isSome: always,
+ isNone: never,
+ getOr: constant_a,
+ getOrThunk: constant_a,
+ getOrDie: constant_a,
+ getOrNull: constant_a,
+ getOrUndefined: constant_a,
+ or: self,
+ orThunk: self,
+ map: function (f) {
+ return some(f(a));
+ },
+ each: function (f) {
+ f(a);
+ },
+ bind: bind,
+ exists: bind,
+ forall: bind,
+ filter: function (f) {
+ return f(a) ? me : NONE;
+ },
+ toArray: function () {
+ return [a];
+ },
+ toString: function () {
+ return 'some(' + a + ')';
+ },
+ equals: function (o) {
+ return o.is(a);
+ },
+ equals_: function (o, elementEq) {
+ return o.fold(never, function (b) {
+ return elementEq(a, b);
+ });
+ }
+ };
+ return me;
+ };
+ var from = function (value) {
+ return value === null || value === undefined ? NONE : some(value);
+ };
+ var Optional = {
+ some: some,
+ none: none,
+ from: from
+ };
+
+ var typeOf = function (x) {
+ var t = typeof x;
+ if (x === null) {
+ return 'null';
+ } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
+ return 'array';
+ } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
+ return 'string';
+ } else {
+ return t;
+ }
+ };
+ var isType = function (type) {
+ return function (value) {
+ return typeOf(value) === type;
+ };
+ };
+ var isSimpleType = function (type) {
+ return function (value) {
+ return typeof value === type;
+ };
+ };
+ var isString = isType('string');
+ var isArray = isType('array');
+ var isBoolean = isSimpleType('boolean');
+ var isFunction = isSimpleType('function');
+ var isNumber = isSimpleType('number');
+
+ var nativeSlice = Array.prototype.slice;
+ var nativePush = Array.prototype.push;
+ var map = function (xs, f) {
+ var len = xs.length;
+ var r = new Array(len);
+ for (var i = 0; i < len; i++) {
+ var x = xs[i];
+ r[i] = f(x, i);
+ }
+ return r;
+ };
+ var each = function (xs, f) {
+ for (var i = 0, len = xs.length; i < len; i++) {
+ var x = xs[i];
+ f(x, i);
+ }
+ };
+ var filter = function (xs, pred) {
+ var r = [];
+ for (var i = 0, len = xs.length; i < len; i++) {
+ var x = xs[i];
+ if (pred(x, i)) {
+ r.push(x);
+ }
+ }
+ return r;
+ };
+ var groupBy = function (xs, f) {
+ if (xs.length === 0) {
+ return [];
+ } else {
+ var wasType = f(xs[0]);
+ var r = [];
+ var group = [];
+ for (var i = 0, len = xs.length; i < len; i++) {
+ var x = xs[i];
+ var type = f(x);
+ if (type !== wasType) {
+ r.push(group);
+ group = [];
+ }
+ wasType = type;
+ group.push(x);
+ }
+ if (group.length !== 0) {
+ r.push(group);
+ }
+ return r;
+ }
+ };
+ var foldl = function (xs, f, acc) {
+ each(xs, function (x) {
+ acc = f(acc, x);
+ });
+ return acc;
+ };
+ var findUntil = function (xs, pred, until) {
+ for (var i = 0, len = xs.length; i < len; i++) {
+ var x = xs[i];
+ if (pred(x, i)) {
+ return Optional.some(x);
+ } else if (until(x, i)) {
+ break;
+ }
+ }
+ return Optional.none();
+ };
+ var find = function (xs, pred) {
+ return findUntil(xs, pred, never);
+ };
+ var flatten = function (xs) {
+ var r = [];
+ for (var i = 0, len = xs.length; i < len; ++i) {
+ if (!isArray(xs[i])) {
+ throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
+ }
+ nativePush.apply(r, xs[i]);
+ }
+ return r;
+ };
+ var bind = function (xs, f) {
+ return flatten(map(xs, f));
+ };
+ var reverse = function (xs) {
+ var r = nativeSlice.call(xs, 0);
+ r.reverse();
+ return r;
+ };
+ var head = function (xs) {
+ return xs.length === 0 ? Optional.none() : Optional.some(xs[0]);
+ };
+ var last = function (xs) {
+ return xs.length === 0 ? Optional.none() : Optional.some(xs[xs.length - 1]);
+ };
+
+ var __assign = function () {
+ __assign = Object.assign || function __assign(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s)
+ if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+ };
+
+ var cached = function (f) {
+ var called = false;
+ var r;
+ return function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ if (!called) {
+ called = true;
+ r = f.apply(null, args);
+ }
+ return r;
+ };
+ };
+
+ var DeviceType = function (os, browser, userAgent, mediaMatch) {
+ var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
+ var isiPhone = os.isiOS() && !isiPad;
+ var isMobile = os.isiOS() || os.isAndroid();
+ var isTouch = isMobile || mediaMatch('(pointer:coarse)');
+ var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
+ var isPhone = isiPhone || isMobile && !isTablet;
+ var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
+ var isDesktop = !isPhone && !isTablet && !iOSwebview;
+ return {
+ isiPad: constant(isiPad),
+ isiPhone: constant(isiPhone),
+ isTablet: constant(isTablet),
+ isPhone: constant(isPhone),
+ isTouch: constant(isTouch),
+ isAndroid: os.isAndroid,
+ isiOS: os.isiOS,
+ isWebView: constant(iOSwebview),
+ isDesktop: constant(isDesktop)
+ };
+ };
+
+ var firstMatch = function (regexes, s) {
+ for (var i = 0; i < regexes.length; i++) {
+ var x = regexes[i];
+ if (x.test(s)) {
+ return x;
+ }
+ }
+ return undefined;
+ };
+ var find$1 = function (regexes, agent) {
+ var r = firstMatch(regexes, agent);
+ if (!r) {
+ return {
+ major: 0,
+ minor: 0
+ };
+ }
+ var group = function (i) {
+ return Number(agent.replace(r, '$' + i));
+ };
+ return nu(group(1), group(2));
+ };
+ var detect = function (versionRegexes, agent) {
+ var cleanedAgent = String(agent).toLowerCase();
+ if (versionRegexes.length === 0) {
+ return unknown();
+ }
+ return find$1(versionRegexes, cleanedAgent);
+ };
+ var unknown = function () {
+ return nu(0, 0);
+ };
+ var nu = function (major, minor) {
+ return {
+ major: major,
+ minor: minor
+ };
+ };
+ var Version = {
+ nu: nu,
+ detect: detect,
+ unknown: unknown
+ };
+
+ var detect$1 = function (candidates, userAgent) {
+ var agent = String(userAgent).toLowerCase();
+ return find(candidates, function (candidate) {
+ return candidate.search(agent);
+ });
+ };
+ var detectBrowser = function (browsers, userAgent) {
+ return detect$1(browsers, userAgent).map(function (browser) {
+ var version = Version.detect(browser.versionRegexes, userAgent);
+ return {
+ current: browser.name,
+ version: version
+ };
+ });
+ };
+ var detectOs = function (oses, userAgent) {
+ return detect$1(oses, userAgent).map(function (os) {
+ var version = Version.detect(os.versionRegexes, userAgent);
+ return {
+ current: os.name,
+ version: version
+ };
+ });
+ };
+ var UaString = {
+ detectBrowser: detectBrowser,
+ detectOs: detectOs
+ };
+
+ var contains = function (str, substr) {
+ return str.indexOf(substr) !== -1;
+ };
+
+ var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
+ var checkContains = function (target) {
+ return function (uastring) {
+ return contains(uastring, target);
+ };
+ };
+ var browsers = [
+ {
+ name: 'Edge',
+ versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
+ search: function (uastring) {
+ return contains(uastring, 'edge/') && contains(uastring, 'chrome') && contains(uastring, 'safari') && contains(uastring, 'applewebkit');
+ }
+ },
+ {
+ name: 'Chrome',
+ versionRegexes: [
+ /.*?chrome\/([0-9]+)\.([0-9]+).*/,
+ normalVersionRegex
+ ],
+ search: function (uastring) {
+ return contains(uastring, 'chrome') && !contains(uastring, 'chromeframe');
+ }
+ },
+ {
+ name: 'IE',
+ versionRegexes: [
+ /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
+ /.*?rv:([0-9]+)\.([0-9]+).*/
+ ],
+ search: function (uastring) {
+ return contains(uastring, 'msie') || contains(uastring, 'trident');
+ }
+ },
+ {
+ name: 'Opera',
+ versionRegexes: [
+ normalVersionRegex,
+ /.*?opera\/([0-9]+)\.([0-9]+).*/
+ ],
+ search: checkContains('opera')
+ },
+ {
+ name: 'Firefox',
+ versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
+ search: checkContains('firefox')
+ },
+ {
+ name: 'Safari',
+ versionRegexes: [
+ normalVersionRegex,
+ /.*?cpu os ([0-9]+)_([0-9]+).*/
+ ],
+ search: function (uastring) {
+ return (contains(uastring, 'safari') || contains(uastring, 'mobile/')) && contains(uastring, 'applewebkit');
+ }
+ }
+ ];
+ var oses = [
+ {
+ name: 'Windows',
+ search: checkContains('win'),
+ versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
+ },
+ {
+ name: 'iOS',
+ search: function (uastring) {
+ return contains(uastring, 'iphone') || contains(uastring, 'ipad');
+ },
+ versionRegexes: [
+ /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
+ /.*cpu os ([0-9]+)_([0-9]+).*/,
+ /.*cpu iphone os ([0-9]+)_([0-9]+).*/
+ ]
+ },
+ {
+ name: 'Android',
+ search: checkContains('android'),
+ versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
+ },
+ {
+ name: 'OSX',
+ search: checkContains('mac os x'),
+ versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
+ },
+ {
+ name: 'Linux',
+ search: checkContains('linux'),
+ versionRegexes: []
+ },
+ {
+ name: 'Solaris',
+ search: checkContains('sunos'),
+ versionRegexes: []
+ },
+ {
+ name: 'FreeBSD',
+ search: checkContains('freebsd'),
+ versionRegexes: []
+ },
+ {
+ name: 'ChromeOS',
+ search: checkContains('cros'),
+ versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
+ }
+ ];
+ var PlatformInfo = {
+ browsers: constant(browsers),
+ oses: constant(oses)
+ };
+
+ var edge = 'Edge';
+ var chrome = 'Chrome';
+ var ie = 'IE';
+ var opera = 'Opera';
+ var firefox = 'Firefox';
+ var safari = 'Safari';
+ var unknown$1 = function () {
+ return nu$1({
+ current: undefined,
+ version: Version.unknown()
+ });
+ };
+ var nu$1 = function (info) {
+ var current = info.current;
+ var version = info.version;
+ var isBrowser = function (name) {
+ return function () {
+ return current === name;
+ };
+ };
+ return {
+ current: current,
+ version: version,
+ isEdge: isBrowser(edge),
+ isChrome: isBrowser(chrome),
+ isIE: isBrowser(ie),
+ isOpera: isBrowser(opera),
+ isFirefox: isBrowser(firefox),
+ isSafari: isBrowser(safari)
+ };
+ };
+ var Browser = {
+ unknown: unknown$1,
+ nu: nu$1,
+ edge: constant(edge),
+ chrome: constant(chrome),
+ ie: constant(ie),
+ opera: constant(opera),
+ firefox: constant(firefox),
+ safari: constant(safari)
+ };
+
+ var windows = 'Windows';
+ var ios = 'iOS';
+ var android = 'Android';
+ var linux = 'Linux';
+ var osx = 'OSX';
+ var solaris = 'Solaris';
+ var freebsd = 'FreeBSD';
+ var chromeos = 'ChromeOS';
+ var unknown$2 = function () {
+ return nu$2({
+ current: undefined,
+ version: Version.unknown()
+ });
+ };
+ var nu$2 = function (info) {
+ var current = info.current;
+ var version = info.version;
+ var isOS = function (name) {
+ return function () {
+ return current === name;
+ };
+ };
+ return {
+ current: current,
+ version: version,
+ isWindows: isOS(windows),
+ isiOS: isOS(ios),
+ isAndroid: isOS(android),
+ isOSX: isOS(osx),
+ isLinux: isOS(linux),
+ isSolaris: isOS(solaris),
+ isFreeBSD: isOS(freebsd),
+ isChromeOS: isOS(chromeos)
+ };
+ };
+ var OperatingSystem = {
+ unknown: unknown$2,
+ nu: nu$2,
+ windows: constant(windows),
+ ios: constant(ios),
+ android: constant(android),
+ linux: constant(linux),
+ osx: constant(osx),
+ solaris: constant(solaris),
+ freebsd: constant(freebsd),
+ chromeos: constant(chromeos)
+ };
+
+ var detect$2 = function (userAgent, mediaMatch) {
+ var browsers = PlatformInfo.browsers();
+ var oses = PlatformInfo.oses();
+ var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
+ var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
+ var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
+ return {
+ browser: browser,
+ os: os,
+ deviceType: deviceType
+ };
+ };
+ var PlatformDetection = { detect: detect$2 };
+
+ var mediaMatch = function (query) {
+ return window.matchMedia(query).matches;
+ };
+ var platform = cached(function () {
+ return PlatformDetection.detect(navigator.userAgent, mediaMatch);
+ });
+ var detect$3 = function () {
+ return platform();
+ };
+
+ var compareDocumentPosition = function (a, b, match) {
+ return (a.compareDocumentPosition(b) & match) !== 0;
+ };
+ var documentPositionContainedBy = function (a, b) {
+ return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
+ };
+
+ var ELEMENT = 1;
+
+ var fromHtml = function (html, scope) {
+ var doc = scope || document;
+ var div = doc.createElement('div');
+ div.innerHTML = html;
+ if (!div.hasChildNodes() || div.childNodes.length > 1) {
+ console.error('HTML does not have a single root node', html);
+ throw new Error('HTML must have a single root node');
+ }
+ return fromDom(div.childNodes[0]);
+ };
+ var fromTag = function (tag, scope) {
+ var doc = scope || document;
+ var node = doc.createElement(tag);
+ return fromDom(node);
+ };
+ var fromText = function (text, scope) {
+ var doc = scope || document;
+ var node = doc.createTextNode(text);
+ return fromDom(node);
+ };
+ var fromDom = function (node) {
+ if (node === null || node === undefined) {
+ throw new Error('Node cannot be null or undefined');
+ }
+ return { dom: node };
+ };
+ var fromPoint = function (docElm, x, y) {
+ return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
+ };
+ var SugarElement = {
+ fromHtml: fromHtml,
+ fromTag: fromTag,
+ fromText: fromText,
+ fromDom: fromDom,
+ fromPoint: fromPoint
+ };
+
+ var is = function (element, selector) {
+ var dom = element.dom;
+ if (dom.nodeType !== ELEMENT) {
+ return false;
+ } else {
+ var elem = dom;
+ if (elem.matches !== undefined) {
+ return elem.matches(selector);
+ } else if (elem.msMatchesSelector !== undefined) {
+ return elem.msMatchesSelector(selector);
+ } else if (elem.webkitMatchesSelector !== undefined) {
+ return elem.webkitMatchesSelector(selector);
+ } else if (elem.mozMatchesSelector !== undefined) {
+ return elem.mozMatchesSelector(selector);
+ } else {
+ throw new Error('Browser lacks native selectors');
+ }
+ }
+ };
+
+ var eq = function (e1, e2) {
+ return e1.dom === e2.dom;
+ };
+ var regularContains = function (e1, e2) {
+ var d1 = e1.dom;
+ var d2 = e2.dom;
+ return d1 === d2 ? false : d1.contains(d2);
+ };
+ var ieContains = function (e1, e2) {
+ return documentPositionContainedBy(e1.dom, e2.dom);
+ };
+ var contains$1 = function (e1, e2) {
+ return detect$3().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
+ };
+ var is$1 = is;
+
+ var global$1 = tinymce.util.Tools.resolve('tinymce.dom.RangeUtils');
+
+ var global$2 = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker');
+
+ var global$3 = tinymce.util.Tools.resolve('tinymce.util.VK');
+
+ var keys = Object.keys;
+ var each$1 = function (obj, f) {
+ var props = keys(obj);
+ for (var k = 0, len = props.length; k < len; k++) {
+ var i = props[k];
+ var x = obj[i];
+ f(x, i);
+ }
+ };
+ var objAcc = function (r) {
+ return function (x, i) {
+ r[i] = x;
+ };
+ };
+ var internalFilter = function (obj, pred, onTrue, onFalse) {
+ var r = {};
+ each$1(obj, function (x, i) {
+ (pred(x, i) ? onTrue : onFalse)(x, i);
+ });
+ return r;
+ };
+ var filter$1 = function (obj, pred) {
+ var t = {};
+ internalFilter(obj, pred, objAcc(t), noop);
+ return t;
+ };
+
+ var Global = typeof window !== 'undefined' ? window : Function('return this;')();
+
+ var name = function (element) {
+ var r = element.dom.nodeName;
+ return r.toLowerCase();
+ };
+ var type = function (element) {
+ return element.dom.nodeType;
+ };
+ var isType$1 = function (t) {
+ return function (element) {
+ return type(element) === t;
+ };
+ };
+ var isElement = isType$1(ELEMENT);
+
+ var rawSet = function (dom, key, value) {
+ if (isString(value) || isBoolean(value) || isNumber(value)) {
+ dom.setAttribute(key, value + '');
+ } else {
+ console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
+ throw new Error('Attribute value was not simple');
+ }
+ };
+ var setAll = function (element, attrs) {
+ var dom = element.dom;
+ each$1(attrs, function (v, k) {
+ rawSet(dom, k, v);
+ });
+ };
+ var clone = function (element) {
+ return foldl(element.dom.attributes, function (acc, attr) {
+ acc[attr.name] = attr.value;
+ return acc;
+ }, {});
+ };
+
+ var parent = function (element) {
+ return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
+ };
+ var children = function (element) {
+ return map(element.dom.childNodes, SugarElement.fromDom);
+ };
+ var child = function (element, index) {
+ var cs = element.dom.childNodes;
+ return Optional.from(cs[index]).map(SugarElement.fromDom);
+ };
+ var firstChild = function (element) {
+ return child(element, 0);
+ };
+ var lastChild = function (element) {
+ return child(element, element.dom.childNodes.length - 1);
+ };
+
+ var before = function (marker, element) {
+ var parent$1 = parent(marker);
+ parent$1.each(function (v) {
+ v.dom.insertBefore(element.dom, marker.dom);
+ });
+ };
+ var append = function (parent, element) {
+ parent.dom.appendChild(element.dom);
+ };
+
+ var before$1 = function (marker, elements) {
+ each(elements, function (x) {
+ before(marker, x);
+ });
+ };
+ var append$1 = function (parent, elements) {
+ each(elements, function (x) {
+ append(parent, x);
+ });
+ };
+
+ var remove = function (element) {
+ var dom = element.dom;
+ if (dom.parentNode !== null) {
+ dom.parentNode.removeChild(dom);
+ }
+ };
+
+ var clone$1 = function (original, isDeep) {
+ return SugarElement.fromDom(original.dom.cloneNode(isDeep));
+ };
+ var deep = function (original) {
+ return clone$1(original, true);
+ };
+ var shallowAs = function (original, tag) {
+ var nu = SugarElement.fromTag(tag);
+ var attributes = clone(original);
+ setAll(nu, attributes);
+ return nu;
+ };
+ var mutate = function (original, tag) {
+ var nu = shallowAs(original, tag);
+ before(original, nu);
+ var children$1 = children(original);
+ append$1(nu, children$1);
+ remove(original);
+ return nu;
+ };
+
+ var global$4 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
+
+ var global$5 = tinymce.util.Tools.resolve('tinymce.util.Tools');
+
+ var matchNodeName = function (name) {
+ return function (node) {
+ return node && node.nodeName.toLowerCase() === name;
+ };
+ };
+ var matchNodeNames = function (regex) {
+ return function (node) {
+ return node && regex.test(node.nodeName);
+ };
+ };
+ var isTextNode = function (node) {
+ return node && node.nodeType === 3;
+ };
+ var isListNode = matchNodeNames(/^(OL|UL|DL)$/);
+ var isOlUlNode = matchNodeNames(/^(OL|UL)$/);
+ var isOlNode = matchNodeName('ol');
+ var isListItemNode = matchNodeNames(/^(LI|DT|DD)$/);
+ var isDlItemNode = matchNodeNames(/^(DT|DD)$/);
+ var isTableCellNode = matchNodeNames(/^(TH|TD)$/);
+ var isBr = matchNodeName('br');
+ var isFirstChild = function (node) {
+ return node.parentNode.firstChild === node;
+ };
+ var isTextBlock = function (editor, node) {
+ return node && !!editor.schema.getTextBlockElements()[node.nodeName];
+ };
+ var isBlock = function (node, blockElements) {
+ return node && node.nodeName in blockElements;
+ };
+ var isBogusBr = function (dom, node) {
+ if (!isBr(node)) {
+ return false;
+ }
+ return dom.isBlock(node.nextSibling) && !isBr(node.previousSibling);
+ };
+ var isEmpty = function (dom, elm, keepBookmarks) {
+ var empty = dom.isEmpty(elm);
+ if (keepBookmarks && dom.select('span[data-mce-type=bookmark]', elm).length > 0) {
+ return false;
+ }
+ return empty;
+ };
+ var isChildOfBody = function (dom, elm) {
+ return dom.isChildOf(elm, dom.getRoot());
+ };
+
+ var shouldIndentOnTab = function (editor) {
+ return editor.getParam('lists_indent_on_tab', true);
+ };
+ var getForcedRootBlock = function (editor) {
+ var block = editor.getParam('forced_root_block', 'p');
+ if (block === false) {
+ return '';
+ } else if (block === true) {
+ return 'p';
+ } else {
+ return block;
+ }
+ };
+ var getForcedRootBlockAttrs = function (editor) {
+ return editor.getParam('forced_root_block_attrs', {});
+ };
+
+ var createTextBlock = function (editor, contentNode) {
+ var dom = editor.dom;
+ var blockElements = editor.schema.getBlockElements();
+ var fragment = dom.createFragment();
+ var blockName = getForcedRootBlock(editor);
+ var node, textBlock, hasContentNode;
+ if (blockName) {
+ textBlock = dom.create(blockName);
+ if (textBlock.tagName === blockName.toUpperCase()) {
+ dom.setAttribs(textBlock, getForcedRootBlockAttrs(editor));
+ }
+ if (!isBlock(contentNode.firstChild, blockElements)) {
+ fragment.appendChild(textBlock);
+ }
+ }
+ if (contentNode) {
+ while (node = contentNode.firstChild) {
+ var nodeName = node.nodeName;
+ if (!hasContentNode && (nodeName !== 'SPAN' || node.getAttribute('data-mce-type') !== 'bookmark')) {
+ hasContentNode = true;
+ }
+ if (isBlock(node, blockElements)) {
+ fragment.appendChild(node);
+ textBlock = null;
+ } else {
+ if (blockName) {
+ if (!textBlock) {
+ textBlock = dom.create(blockName);
+ fragment.appendChild(textBlock);
+ }
+ textBlock.appendChild(node);
+ } else {
+ fragment.appendChild(node);
+ }
+ }
+ }
+ }
+ if (!blockName) {
+ fragment.appendChild(dom.create('br'));
+ } else {
+ if (!hasContentNode) {
+ textBlock.appendChild(dom.create('br', { 'data-mce-bogus': '1' }));
+ }
+ }
+ return fragment;
+ };
+
+ var DOM = global$4.DOM;
+ var splitList = function (editor, ul, li) {
+ var removeAndKeepBookmarks = function (targetNode) {
+ global$5.each(bookmarks, function (node) {
+ targetNode.parentNode.insertBefore(node, li.parentNode);
+ });
+ DOM.remove(targetNode);
+ };
+ var bookmarks = DOM.select('span[data-mce-type="bookmark"]', ul);
+ var newBlock = createTextBlock(editor, li);
+ var tmpRng = DOM.createRng();
+ tmpRng.setStartAfter(li);
+ tmpRng.setEndAfter(ul);
+ var fragment = tmpRng.extractContents();
+ for (var node = fragment.firstChild; node; node = node.firstChild) {
+ if (node.nodeName === 'LI' && editor.dom.isEmpty(node)) {
+ DOM.remove(node);
+ break;
+ }
+ }
+ if (!editor.dom.isEmpty(fragment)) {
+ DOM.insertAfter(fragment, ul);
+ }
+ DOM.insertAfter(newBlock, ul);
+ if (isEmpty(editor.dom, li.parentNode)) {
+ removeAndKeepBookmarks(li.parentNode);
+ }
+ DOM.remove(li);
+ if (isEmpty(editor.dom, ul)) {
+ DOM.remove(ul);
+ }
+ };
+
+ var outdentDlItem = function (editor, item) {
+ if (is$1(item, 'dd')) {
+ mutate(item, 'dt');
+ } else if (is$1(item, 'dt')) {
+ parent(item).each(function (dl) {
+ return splitList(editor, dl.dom, item.dom);
+ });
+ }
+ };
+ var indentDlItem = function (item) {
+ if (is$1(item, 'dt')) {
+ mutate(item, 'dd');
+ }
+ };
+ var dlIndentation = function (editor, indentation, dlItems) {
+ if (indentation === 'Indent') {
+ each(dlItems, indentDlItem);
+ } else {
+ each(dlItems, function (item) {
+ return outdentDlItem(editor, item);
+ });
+ }
+ };
+
+ var getNormalizedPoint = function (container, offset) {
+ if (isTextNode(container)) {
+ return {
+ container: container,
+ offset: offset
+ };
+ }
+ var node = global$1.getNode(container, offset);
+ if (isTextNode(node)) {
+ return {
+ container: node,
+ offset: offset >= container.childNodes.length ? node.data.length : 0
+ };
+ } else if (node.previousSibling && isTextNode(node.previousSibling)) {
+ return {
+ container: node.previousSibling,
+ offset: node.previousSibling.data.length
+ };
+ } else if (node.nextSibling && isTextNode(node.nextSibling)) {
+ return {
+ container: node.nextSibling,
+ offset: 0
+ };
+ }
+ return {
+ container: container,
+ offset: offset
+ };
+ };
+ var normalizeRange = function (rng) {
+ var outRng = rng.cloneRange();
+ var rangeStart = getNormalizedPoint(rng.startContainer, rng.startOffset);
+ outRng.setStart(rangeStart.container, rangeStart.offset);
+ var rangeEnd = getNormalizedPoint(rng.endContainer, rng.endOffset);
+ outRng.setEnd(rangeEnd.container, rangeEnd.offset);
+ return outRng;
+ };
+
+ var global$6 = tinymce.util.Tools.resolve('tinymce.dom.DomQuery');
+
+ var getParentList = function (editor, node) {
+ var selectionStart = node || editor.selection.getStart(true);
+ return editor.dom.getParent(selectionStart, 'OL,UL,DL', getClosestListRootElm(editor, selectionStart));
+ };
+ var isParentListSelected = function (parentList, selectedBlocks) {
+ return parentList && selectedBlocks.length === 1 && selectedBlocks[0] === parentList;
+ };
+ var findSubLists = function (parentList) {
+ return global$5.grep(parentList.querySelectorAll('ol,ul,dl'), function (elm) {
+ return isListNode(elm);
+ });
+ };
+ var getSelectedSubLists = function (editor) {
+ var parentList = getParentList(editor);
+ var selectedBlocks = editor.selection.getSelectedBlocks();
+ if (isParentListSelected(parentList, selectedBlocks)) {
+ return findSubLists(parentList);
+ } else {
+ return global$5.grep(selectedBlocks, function (elm) {
+ return isListNode(elm) && parentList !== elm;
+ });
+ }
+ };
+ var findParentListItemsNodes = function (editor, elms) {
+ var listItemsElms = global$5.map(elms, function (elm) {
+ var parentLi = editor.dom.getParent(elm, 'li,dd,dt', getClosestListRootElm(editor, elm));
+ return parentLi ? parentLi : elm;
+ });
+ return global$6.unique(listItemsElms);
+ };
+ var getSelectedListItems = function (editor) {
+ var selectedBlocks = editor.selection.getSelectedBlocks();
+ return global$5.grep(findParentListItemsNodes(editor, selectedBlocks), function (block) {
+ return isListItemNode(block);
+ });
+ };
+ var getSelectedDlItems = function (editor) {
+ return filter(getSelectedListItems(editor), isDlItemNode);
+ };
+ var getClosestListRootElm = function (editor, elm) {
+ var parentTableCell = editor.dom.getParents(elm, 'TD,TH');
+ var root = parentTableCell.length > 0 ? parentTableCell[0] : editor.getBody();
+ return root;
+ };
+ var findLastParentListNode = function (editor, elm) {
+ var parentLists = editor.dom.getParents(elm, 'ol,ul', getClosestListRootElm(editor, elm));
+ return last(parentLists);
+ };
+ var getSelectedLists = function (editor) {
+ var firstList = findLastParentListNode(editor, editor.selection.getStart());
+ var subsequentLists = filter(editor.selection.getSelectedBlocks(), isOlUlNode);
+ return firstList.toArray().concat(subsequentLists);
+ };
+ var getSelectedListRoots = function (editor) {
+ var selectedLists = getSelectedLists(editor);
+ return getUniqueListRoots(editor, selectedLists);
+ };
+ var getUniqueListRoots = function (editor, lists) {
+ var listRoots = map(lists, function (list) {
+ return findLastParentListNode(editor, list).getOr(list);
+ });
+ return global$6.unique(listRoots);
+ };
+
+ var lift2 = function (oa, ob, f) {
+ return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
+ };
+
+ var fromElements = function (elements, scope) {
+ var doc = scope || document;
+ var fragment = doc.createDocumentFragment();
+ each(elements, function (element) {
+ fragment.appendChild(element.dom);
+ });
+ return SugarElement.fromDom(fragment);
+ };
+
+ var fireListEvent = function (editor, action, element) {
+ return editor.fire('ListMutation', {
+ action: action,
+ element: element
+ });
+ };
+
+ var isSupported = function (dom) {
+ return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
+ };
+
+ var internalSet = function (dom, property, value) {
+ if (!isString(value)) {
+ console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
+ throw new Error('CSS value must be a string: ' + value);
+ }
+ if (isSupported(dom)) {
+ dom.style.setProperty(property, value);
+ }
+ };
+ var set = function (element, property, value) {
+ var dom = element.dom;
+ internalSet(dom, property, value);
+ };
+
+ var joinSegment = function (parent, child) {
+ append(parent.item, child.list);
+ };
+ var joinSegments = function (segments) {
+ for (var i = 1; i < segments.length; i++) {
+ joinSegment(segments[i - 1], segments[i]);
+ }
+ };
+ var appendSegments = function (head$1, tail) {
+ lift2(last(head$1), head(tail), joinSegment);
+ };
+ var createSegment = function (scope, listType) {
+ var segment = {
+ list: SugarElement.fromTag(listType, scope),
+ item: SugarElement.fromTag('li', scope)
+ };
+ append(segment.list, segment.item);
+ return segment;
+ };
+ var createSegments = function (scope, entry, size) {
+ var segments = [];
+ for (var i = 0; i < size; i++) {
+ segments.push(createSegment(scope, entry.listType));
+ }
+ return segments;
+ };
+ var populateSegments = function (segments, entry) {
+ for (var i = 0; i < segments.length - 1; i++) {
+ set(segments[i].item, 'list-style-type', 'none');
+ }
+ last(segments).each(function (segment) {
+ setAll(segment.list, entry.listAttributes);
+ setAll(segment.item, entry.itemAttributes);
+ append$1(segment.item, entry.content);
+ });
+ };
+ var normalizeSegment = function (segment, entry) {
+ if (name(segment.list) !== entry.listType) {
+ segment.list = mutate(segment.list, entry.listType);
+ }
+ setAll(segment.list, entry.listAttributes);
+ };
+ var createItem = function (scope, attr, content) {
+ var item = SugarElement.fromTag('li', scope);
+ setAll(item, attr);
+ append$1(item, content);
+ return item;
+ };
+ var appendItem = function (segment, item) {
+ append(segment.list, item);
+ segment.item = item;
+ };
+ var writeShallow = function (scope, cast, entry) {
+ var newCast = cast.slice(0, entry.depth);
+ last(newCast).each(function (segment) {
+ var item = createItem(scope, entry.itemAttributes, entry.content);
+ appendItem(segment, item);
+ normalizeSegment(segment, entry);
+ });
+ return newCast;
+ };
+ var writeDeep = function (scope, cast, entry) {
+ var segments = createSegments(scope, entry, entry.depth - cast.length);
+ joinSegments(segments);
+ populateSegments(segments, entry);
+ appendSegments(cast, segments);
+ return cast.concat(segments);
+ };
+ var composeList = function (scope, entries) {
+ var cast = foldl(entries, function (cast, entry) {
+ return entry.depth > cast.length ? writeDeep(scope, cast, entry) : writeShallow(scope, cast, entry);
+ }, []);
+ return head(cast).map(function (segment) {
+ return segment.list;
+ });
+ };
+
+ var isList = function (el) {
+ return is$1(el, 'OL,UL');
+ };
+ var hasFirstChildList = function (el) {
+ return firstChild(el).map(isList).getOr(false);
+ };
+ var hasLastChildList = function (el) {
+ return lastChild(el).map(isList).getOr(false);
+ };
+
+ var isIndented = function (entry) {
+ return entry.depth > 0;
+ };
+ var isSelected = function (entry) {
+ return entry.isSelected;
+ };
+ var cloneItemContent = function (li) {
+ var children$1 = children(li);
+ var content = hasLastChildList(li) ? children$1.slice(0, -1) : children$1;
+ return map(content, deep);
+ };
+ var createEntry = function (li, depth, isSelected) {
+ return parent(li).filter(isElement).map(function (list) {
+ return {
+ depth: depth,
+ dirty: false,
+ isSelected: isSelected,
+ content: cloneItemContent(li),
+ itemAttributes: clone(li),
+ listAttributes: clone(list),
+ listType: name(list)
+ };
+ });
+ };
+
+ var indentEntry = function (indentation, entry) {
+ switch (indentation) {
+ case 'Indent':
+ entry.depth++;
+ break;
+ case 'Outdent':
+ entry.depth--;
+ break;
+ case 'Flatten':
+ entry.depth = 0;
+ }
+ entry.dirty = true;
+ };
+
+ var cloneListProperties = function (target, source) {
+ target.listType = source.listType;
+ target.listAttributes = __assign({}, source.listAttributes);
+ };
+ var cleanListProperties = function (entry) {
+ entry.listAttributes = filter$1(entry.listAttributes, function (_value, key) {
+ return key !== 'start';
+ });
+ };
+ var closestSiblingEntry = function (entries, start) {
+ var depth = entries[start].depth;
+ var matches = function (entry) {
+ return entry.depth === depth && !entry.dirty;
+ };
+ var until = function (entry) {
+ return entry.depth < depth;
+ };
+ return findUntil(reverse(entries.slice(0, start)), matches, until).orThunk(function () {
+ return findUntil(entries.slice(start + 1), matches, until);
+ });
+ };
+ var normalizeEntries = function (entries) {
+ each(entries, function (entry, i) {
+ closestSiblingEntry(entries, i).fold(function () {
+ if (entry.dirty) {
+ cleanListProperties(entry);
+ }
+ }, function (matchingEntry) {
+ return cloneListProperties(entry, matchingEntry);
+ });
+ });
+ return entries;
+ };
+
+ var Cell = function (initial) {
+ var value = initial;
+ var get = function () {
+ return value;
+ };
+ var set = function (v) {
+ value = v;
+ };
+ return {
+ get: get,
+ set: set
+ };
+ };
+
+ var parseItem = function (depth, itemSelection, selectionState, item) {
+ return firstChild(item).filter(isList).fold(function () {
+ itemSelection.each(function (selection) {
+ if (eq(selection.start, item)) {
+ selectionState.set(true);
+ }
+ });
+ var currentItemEntry = createEntry(item, depth, selectionState.get());
+ itemSelection.each(function (selection) {
+ if (eq(selection.end, item)) {
+ selectionState.set(false);
+ }
+ });
+ var childListEntries = lastChild(item).filter(isList).map(function (list) {
+ return parseList(depth, itemSelection, selectionState, list);
+ }).getOr([]);
+ return currentItemEntry.toArray().concat(childListEntries);
+ }, function (list) {
+ return parseList(depth, itemSelection, selectionState, list);
+ });
+ };
+ var parseList = function (depth, itemSelection, selectionState, list) {
+ return bind(children(list), function (element) {
+ var parser = isList(element) ? parseList : parseItem;
+ var newDepth = depth + 1;
+ return parser(newDepth, itemSelection, selectionState, element);
+ });
+ };
+ var parseLists = function (lists, itemSelection) {
+ var selectionState = Cell(false);
+ var initialDepth = 0;
+ return map(lists, function (list) {
+ return {
+ sourceList: list,
+ entries: parseList(initialDepth, itemSelection, selectionState, list)
+ };
+ });
+ };
+
+ var outdentedComposer = function (editor, entries) {
+ var normalizedEntries = normalizeEntries(entries);
+ return map(normalizedEntries, function (entry) {
+ var content = fromElements(entry.content);
+ return SugarElement.fromDom(createTextBlock(editor, content.dom));
+ });
+ };
+ var indentedComposer = function (editor, entries) {
+ var normalizedEntries = normalizeEntries(entries);
+ return composeList(editor.contentDocument, normalizedEntries).toArray();
+ };
+ var composeEntries = function (editor, entries) {
+ return bind(groupBy(entries, isIndented), function (entries) {
+ var groupIsIndented = head(entries).map(isIndented).getOr(false);
+ return groupIsIndented ? indentedComposer(editor, entries) : outdentedComposer(editor, entries);
+ });
+ };
+ var indentSelectedEntries = function (entries, indentation) {
+ each(filter(entries, isSelected), function (entry) {
+ return indentEntry(indentation, entry);
+ });
+ };
+ var getItemSelection = function (editor) {
+ var selectedListItems = map(getSelectedListItems(editor), SugarElement.fromDom);
+ return lift2(find(selectedListItems, not(hasFirstChildList)), find(reverse(selectedListItems), not(hasFirstChildList)), function (start, end) {
+ return {
+ start: start,
+ end: end
+ };
+ });
+ };
+ var listIndentation = function (editor, lists, indentation) {
+ var entrySets = parseLists(lists, getItemSelection(editor));
+ each(entrySets, function (entrySet) {
+ indentSelectedEntries(entrySet.entries, indentation);
+ var composedLists = composeEntries(editor, entrySet.entries);
+ each(composedLists, function (composedList) {
+ fireListEvent(editor, indentation === 'Indent' ? 'IndentList' : 'OutdentList', composedList.dom);
+ });
+ before$1(entrySet.sourceList, composedLists);
+ remove(entrySet.sourceList);
+ });
+ };
+
+ var selectionIndentation = function (editor, indentation) {
+ var lists = map(getSelectedListRoots(editor), SugarElement.fromDom);
+ var dlItems = map(getSelectedDlItems(editor), SugarElement.fromDom);
+ var isHandled = false;
+ if (lists.length || dlItems.length) {
+ var bookmark = editor.selection.getBookmark();
+ listIndentation(editor, lists, indentation);
+ dlIndentation(editor, indentation, dlItems);
+ editor.selection.moveToBookmark(bookmark);
+ editor.selection.setRng(normalizeRange(editor.selection.getRng()));
+ editor.nodeChanged();
+ isHandled = true;
+ }
+ return isHandled;
+ };
+ var indentListSelection = function (editor) {
+ return selectionIndentation(editor, 'Indent');
+ };
+ var outdentListSelection = function (editor) {
+ return selectionIndentation(editor, 'Outdent');
+ };
+ var flattenListSelection = function (editor) {
+ return selectionIndentation(editor, 'Flatten');
+ };
+
+ var global$7 = tinymce.util.Tools.resolve('tinymce.dom.BookmarkManager');
+
+ var DOM$1 = global$4.DOM;
+ var createBookmark = function (rng) {
+ var bookmark = {};
+ var setupEndPoint = function (start) {
+ var offsetNode, container, offset;
+ container = rng[start ? 'startContainer' : 'endContainer'];
+ offset = rng[start ? 'startOffset' : 'endOffset'];
+ if (container.nodeType === 1) {
+ offsetNode = DOM$1.create('span', { 'data-mce-type': 'bookmark' });
+ if (container.hasChildNodes()) {
+ offset = Math.min(offset, container.childNodes.length - 1);
+ if (start) {
+ container.insertBefore(offsetNode, container.childNodes[offset]);
+ } else {
+ DOM$1.insertAfter(offsetNode, container.childNodes[offset]);
+ }
+ } else {
+ container.appendChild(offsetNode);
+ }
+ container = offsetNode;
+ offset = 0;
+ }
+ bookmark[start ? 'startContainer' : 'endContainer'] = container;
+ bookmark[start ? 'startOffset' : 'endOffset'] = offset;
+ };
+ setupEndPoint(true);
+ if (!rng.collapsed) {
+ setupEndPoint();
+ }
+ return bookmark;
+ };
+ var resolveBookmark = function (bookmark) {
+ function restoreEndPoint(start) {
+ var container, offset, node;
+ var nodeIndex = function (container) {
+ var node = container.parentNode.firstChild, idx = 0;
+ while (node) {
+ if (node === container) {
+ return idx;
+ }
+ if (node.nodeType !== 1 || node.getAttribute('data-mce-type') !== 'bookmark') {
+ idx++;
+ }
+ node = node.nextSibling;
+ }
+ return -1;
+ };
+ container = node = bookmark[start ? 'startContainer' : 'endContainer'];
+ offset = bookmark[start ? 'startOffset' : 'endOffset'];
+ if (!container) {
+ return;
+ }
+ if (container.nodeType === 1) {
+ offset = nodeIndex(container);
+ container = container.parentNode;
+ DOM$1.remove(node);
+ if (!container.hasChildNodes() && DOM$1.isBlock(container)) {
+ container.appendChild(DOM$1.create('br'));
+ }
+ }
+ bookmark[start ? 'startContainer' : 'endContainer'] = container;
+ bookmark[start ? 'startOffset' : 'endOffset'] = offset;
+ }
+ restoreEndPoint(true);
+ restoreEndPoint();
+ var rng = DOM$1.createRng();
+ rng.setStart(bookmark.startContainer, bookmark.startOffset);
+ if (bookmark.endContainer) {
+ rng.setEnd(bookmark.endContainer, bookmark.endOffset);
+ }
+ return normalizeRange(rng);
+ };
+
+ var listToggleActionFromListName = function (listName) {
+ switch (listName) {
+ case 'UL':
+ return 'ToggleUlList';
+ case 'OL':
+ return 'ToggleOlList';
+ case 'DL':
+ return 'ToggleDLList';
+ }
+ };
+
+ var isCustomList = function (list) {
+ return /\btox\-/.test(list.className);
+ };
+ var listState = function (editor, listName, activate) {
+ var nodeChangeHandler = function (e) {
+ var inList = findUntil(e.parents, isListNode, isTableCellNode).filter(function (list) {
+ return list.nodeName === listName && !isCustomList(list);
+ }).isSome();
+ activate(inList);
+ };
+ var parents = editor.dom.getParents(editor.selection.getNode());
+ nodeChangeHandler({ parents: parents });
+ editor.on('NodeChange', nodeChangeHandler);
+ return function () {
+ return editor.off('NodeChange', nodeChangeHandler);
+ };
+ };
+
+ var updateListStyle = function (dom, el, detail) {
+ var type = detail['list-style-type'] ? detail['list-style-type'] : null;
+ dom.setStyle(el, 'list-style-type', type);
+ };
+ var setAttribs = function (elm, attrs) {
+ global$5.each(attrs, function (value, key) {
+ elm.setAttribute(key, value);
+ });
+ };
+ var updateListAttrs = function (dom, el, detail) {
+ setAttribs(el, detail['list-attributes']);
+ global$5.each(dom.select('li', el), function (li) {
+ setAttribs(li, detail['list-item-attributes']);
+ });
+ };
+ var updateListWithDetails = function (dom, el, detail) {
+ updateListStyle(dom, el, detail);
+ updateListAttrs(dom, el, detail);
+ };
+ var removeStyles = function (dom, element, styles) {
+ global$5.each(styles, function (style) {
+ var _a;
+ return dom.setStyle(element, (_a = {}, _a[style] = '', _a));
+ });
+ };
+ var getEndPointNode = function (editor, rng, start, root) {
+ var container = rng[start ? 'startContainer' : 'endContainer'];
+ var offset = rng[start ? 'startOffset' : 'endOffset'];
+ if (container.nodeType === 1) {
+ container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
+ }
+ if (!start && isBr(container.nextSibling)) {
+ container = container.nextSibling;
+ }
+ while (container.parentNode !== root) {
+ if (isTextBlock(editor, container)) {
+ return container;
+ }
+ if (/^(TD|TH)$/.test(container.parentNode.nodeName)) {
+ return container;
+ }
+ container = container.parentNode;
+ }
+ return container;
+ };
+ var getSelectedTextBlocks = function (editor, rng, root) {
+ var textBlocks = [], dom = editor.dom;
+ var startNode = getEndPointNode(editor, rng, true, root);
+ var endNode = getEndPointNode(editor, rng, false, root);
+ var block;
+ var siblings = [];
+ for (var node = startNode; node; node = node.nextSibling) {
+ siblings.push(node);
+ if (node === endNode) {
+ break;
+ }
+ }
+ global$5.each(siblings, function (node) {
+ if (isTextBlock(editor, node)) {
+ textBlocks.push(node);
+ block = null;
+ return;
+ }
+ if (dom.isBlock(node) || isBr(node)) {
+ if (isBr(node)) {
+ dom.remove(node);
+ }
+ block = null;
+ return;
+ }
+ var nextSibling = node.nextSibling;
+ if (global$7.isBookmarkNode(node)) {
+ if (isTextBlock(editor, nextSibling) || !nextSibling && node.parentNode === root) {
+ block = null;
+ return;
+ }
+ }
+ if (!block) {
+ block = dom.create('p');
+ node.parentNode.insertBefore(block, node);
+ textBlocks.push(block);
+ }
+ block.appendChild(node);
+ });
+ return textBlocks;
+ };
+ var hasCompatibleStyle = function (dom, sib, detail) {
+ var sibStyle = dom.getStyle(sib, 'list-style-type');
+ var detailStyle = detail ? detail['list-style-type'] : '';
+ detailStyle = detailStyle === null ? '' : detailStyle;
+ return sibStyle === detailStyle;
+ };
+ var applyList = function (editor, listName, detail) {
+ if (detail === void 0) {
+ detail = {};
+ }
+ var rng = editor.selection.getRng();
+ var listItemName = 'LI';
+ var root = getClosestListRootElm(editor, editor.selection.getStart(true));
+ var dom = editor.dom;
+ if (dom.getContentEditable(editor.selection.getNode()) === 'false') {
+ return;
+ }
+ listName = listName.toUpperCase();
+ if (listName === 'DL') {
+ listItemName = 'DT';
+ }
+ var bookmark = createBookmark(rng);
+ global$5.each(getSelectedTextBlocks(editor, rng, root), function (block) {
+ var listBlock;
+ var sibling = block.previousSibling;
+ if (sibling && isListNode(sibling) && sibling.nodeName === listName && hasCompatibleStyle(dom, sibling, detail)) {
+ listBlock = sibling;
+ block = dom.rename(block, listItemName);
+ sibling.appendChild(block);
+ } else {
+ listBlock = dom.create(listName);
+ block.parentNode.insertBefore(listBlock, block);
+ listBlock.appendChild(block);
+ block = dom.rename(block, listItemName);
+ }
+ removeStyles(dom, block, [
+ 'margin',
+ 'margin-right',
+ 'margin-bottom',
+ 'margin-left',
+ 'margin-top',
+ 'padding',
+ 'padding-right',
+ 'padding-bottom',
+ 'padding-left',
+ 'padding-top'
+ ]);
+ updateListWithDetails(dom, listBlock, detail);
+ mergeWithAdjacentLists(editor.dom, listBlock);
+ });
+ editor.selection.setRng(resolveBookmark(bookmark));
+ };
+ var isValidLists = function (list1, list2) {
+ return list1 && list2 && isListNode(list1) && list1.nodeName === list2.nodeName;
+ };
+ var hasSameListStyle = function (dom, list1, list2) {
+ var targetStyle = dom.getStyle(list1, 'list-style-type', true);
+ var style = dom.getStyle(list2, 'list-style-type', true);
+ return targetStyle === style;
+ };
+ var hasSameClasses = function (elm1, elm2) {
+ return elm1.className === elm2.className;
+ };
+ var shouldMerge = function (dom, list1, list2) {
+ return isValidLists(list1, list2) && hasSameListStyle(dom, list1, list2) && hasSameClasses(list1, list2);
+ };
+ var mergeWithAdjacentLists = function (dom, listBlock) {
+ var sibling, node;
+ sibling = listBlock.nextSibling;
+ if (shouldMerge(dom, listBlock, sibling)) {
+ while (node = sibling.firstChild) {
+ listBlock.appendChild(node);
+ }
+ dom.remove(sibling);
+ }
+ sibling = listBlock.previousSibling;
+ if (shouldMerge(dom, listBlock, sibling)) {
+ while (node = sibling.lastChild) {
+ listBlock.insertBefore(node, listBlock.firstChild);
+ }
+ dom.remove(sibling);
+ }
+ };
+ var updateList = function (editor, list, listName, detail) {
+ if (list.nodeName !== listName) {
+ var newList = editor.dom.rename(list, listName);
+ updateListWithDetails(editor.dom, newList, detail);
+ fireListEvent(editor, listToggleActionFromListName(listName), newList);
+ } else {
+ updateListWithDetails(editor.dom, list, detail);
+ fireListEvent(editor, listToggleActionFromListName(listName), list);
+ }
+ };
+ var toggleMultipleLists = function (editor, parentList, lists, listName, detail) {
+ if (parentList.nodeName === listName && !hasListStyleDetail(detail)) {
+ flattenListSelection(editor);
+ } else {
+ var bookmark = createBookmark(editor.selection.getRng(true));
+ global$5.each([parentList].concat(lists), function (elm) {
+ updateList(editor, elm, listName, detail);
+ });
+ editor.selection.setRng(resolveBookmark(bookmark));
+ }
+ };
+ var hasListStyleDetail = function (detail) {
+ return 'list-style-type' in detail;
+ };
+ var toggleSingleList = function (editor, parentList, listName, detail) {
+ if (parentList === editor.getBody()) {
+ return;
+ }
+ if (parentList) {
+ if (parentList.nodeName === listName && !hasListStyleDetail(detail) && !isCustomList(parentList)) {
+ flattenListSelection(editor);
+ } else {
+ var bookmark = createBookmark(editor.selection.getRng(true));
+ updateListWithDetails(editor.dom, parentList, detail);
+ var newList = editor.dom.rename(parentList, listName);
+ mergeWithAdjacentLists(editor.dom, newList);
+ editor.selection.setRng(resolveBookmark(bookmark));
+ fireListEvent(editor, listToggleActionFromListName(listName), newList);
+ }
+ } else {
+ applyList(editor, listName, detail);
+ fireListEvent(editor, listToggleActionFromListName(listName), parentList);
+ }
+ };
+ var toggleList = function (editor, listName, detail) {
+ var parentList = getParentList(editor);
+ var selectedSubLists = getSelectedSubLists(editor);
+ detail = detail ? detail : {};
+ if (parentList && selectedSubLists.length > 0) {
+ toggleMultipleLists(editor, parentList, selectedSubLists, listName, detail);
+ } else {
+ toggleSingleList(editor, parentList, listName, detail);
+ }
+ };
+
+ var DOM$2 = global$4.DOM;
+ var normalizeList = function (dom, ul) {
+ var sibling;
+ var parentNode = ul.parentNode;
+ if (parentNode.nodeName === 'LI' && parentNode.firstChild === ul) {
+ sibling = parentNode.previousSibling;
+ if (sibling && sibling.nodeName === 'LI') {
+ sibling.appendChild(ul);
+ if (isEmpty(dom, parentNode)) {
+ DOM$2.remove(parentNode);
+ }
+ } else {
+ DOM$2.setStyle(parentNode, 'listStyleType', 'none');
+ }
+ }
+ if (isListNode(parentNode)) {
+ sibling = parentNode.previousSibling;
+ if (sibling && sibling.nodeName === 'LI') {
+ sibling.appendChild(ul);
+ }
+ }
+ };
+ var normalizeLists = function (dom, element) {
+ global$5.each(global$5.grep(dom.select('ol,ul', element)), function (ul) {
+ normalizeList(dom, ul);
+ });
+ };
+
+ var findNextCaretContainer = function (editor, rng, isForward, root) {
+ var node = rng.startContainer;
+ var offset = rng.startOffset;
+ if (isTextNode(node) && (isForward ? offset < node.data.length : offset > 0)) {
+ return node;
+ }
+ var nonEmptyBlocks = editor.schema.getNonEmptyElements();
+ if (node.nodeType === 1) {
+ node = global$1.getNode(node, offset);
+ }
+ var walker = new global$2(node, root);
+ if (isForward) {
+ if (isBogusBr(editor.dom, node)) {
+ walker.next();
+ }
+ }
+ while (node = walker[isForward ? 'next' : 'prev2']()) {
+ if (node.nodeName === 'LI' && !node.hasChildNodes()) {
+ return node;
+ }
+ if (nonEmptyBlocks[node.nodeName]) {
+ return node;
+ }
+ if (isTextNode(node) && node.data.length > 0) {
+ return node;
+ }
+ }
+ };
+ var hasOnlyOneBlockChild = function (dom, elm) {
+ var childNodes = elm.childNodes;
+ return childNodes.length === 1 && !isListNode(childNodes[0]) && dom.isBlock(childNodes[0]);
+ };
+ var unwrapSingleBlockChild = function (dom, elm) {
+ if (hasOnlyOneBlockChild(dom, elm)) {
+ dom.remove(elm.firstChild, true);
+ }
+ };
+ var moveChildren = function (dom, fromElm, toElm) {
+ var node;
+ var targetElm = hasOnlyOneBlockChild(dom, toElm) ? toElm.firstChild : toElm;
+ unwrapSingleBlockChild(dom, fromElm);
+ if (!isEmpty(dom, fromElm, true)) {
+ while (node = fromElm.firstChild) {
+ targetElm.appendChild(node);
+ }
+ }
+ };
+ var mergeLiElements = function (dom, fromElm, toElm) {
+ var listNode;
+ var ul = fromElm.parentNode;
+ if (!isChildOfBody(dom, fromElm) || !isChildOfBody(dom, toElm)) {
+ return;
+ }
+ if (isListNode(toElm.lastChild)) {
+ listNode = toElm.lastChild;
+ }
+ if (ul === toElm.lastChild) {
+ if (isBr(ul.previousSibling)) {
+ dom.remove(ul.previousSibling);
+ }
+ }
+ var node = toElm.lastChild;
+ if (node && isBr(node) && fromElm.hasChildNodes()) {
+ dom.remove(node);
+ }
+ if (isEmpty(dom, toElm, true)) {
+ dom.$(toElm).empty();
+ }
+ moveChildren(dom, fromElm, toElm);
+ if (listNode) {
+ toElm.appendChild(listNode);
+ }
+ var contains = contains$1(SugarElement.fromDom(toElm), SugarElement.fromDom(fromElm));
+ var nestedLists = contains ? dom.getParents(fromElm, isListNode, toElm) : [];
+ dom.remove(fromElm);
+ each(nestedLists, function (list) {
+ if (isEmpty(dom, list) && list !== dom.getRoot()) {
+ dom.remove(list);
+ }
+ });
+ };
+ var mergeIntoEmptyLi = function (editor, fromLi, toLi) {
+ editor.dom.$(toLi).empty();
+ mergeLiElements(editor.dom, fromLi, toLi);
+ editor.selection.setCursorLocation(toLi);
+ };
+ var mergeForward = function (editor, rng, fromLi, toLi) {
+ var dom = editor.dom;
+ if (dom.isEmpty(toLi)) {
+ mergeIntoEmptyLi(editor, fromLi, toLi);
+ } else {
+ var bookmark = createBookmark(rng);
+ mergeLiElements(dom, fromLi, toLi);
+ editor.selection.setRng(resolveBookmark(bookmark));
+ }
+ };
+ var mergeBackward = function (editor, rng, fromLi, toLi) {
+ var bookmark = createBookmark(rng);
+ mergeLiElements(editor.dom, fromLi, toLi);
+ var resolvedBookmark = resolveBookmark(bookmark);
+ editor.selection.setRng(resolvedBookmark);
+ };
+ var backspaceDeleteFromListToListCaret = function (editor, isForward) {
+ var dom = editor.dom, selection = editor.selection;
+ var selectionStartElm = selection.getStart();
+ var root = getClosestListRootElm(editor, selectionStartElm);
+ var li = dom.getParent(selection.getStart(), 'LI', root);
+ if (li) {
+ var ul = li.parentNode;
+ if (ul === editor.getBody() && isEmpty(dom, ul)) {
+ return true;
+ }
+ var rng_1 = normalizeRange(selection.getRng());
+ var otherLi_1 = dom.getParent(findNextCaretContainer(editor, rng_1, isForward, root), 'LI', root);
+ if (otherLi_1 && otherLi_1 !== li) {
+ editor.undoManager.transact(function () {
+ if (isForward) {
+ mergeForward(editor, rng_1, otherLi_1, li);
+ } else {
+ if (isFirstChild(li)) {
+ outdentListSelection(editor);
+ } else {
+ mergeBackward(editor, rng_1, li, otherLi_1);
+ }
+ }
+ });
+ return true;
+ } else if (!otherLi_1) {
+ if (!isForward && rng_1.startOffset === 0 && rng_1.endOffset === 0) {
+ editor.undoManager.transact(function () {
+ flattenListSelection(editor);
+ });
+ return true;
+ }
+ }
+ }
+ return false;
+ };
+ var removeBlock = function (dom, block, root) {
+ var parentBlock = dom.getParent(block.parentNode, dom.isBlock, root);
+ dom.remove(block);
+ if (parentBlock && dom.isEmpty(parentBlock)) {
+ dom.remove(parentBlock);
+ }
+ };
+ var backspaceDeleteIntoListCaret = function (editor, isForward) {
+ var dom = editor.dom;
+ var selectionStartElm = editor.selection.getStart();
+ var root = getClosestListRootElm(editor, selectionStartElm);
+ var block = dom.getParent(selectionStartElm, dom.isBlock, root);
+ if (block && dom.isEmpty(block)) {
+ var rng = normalizeRange(editor.selection.getRng());
+ var otherLi_2 = dom.getParent(findNextCaretContainer(editor, rng, isForward, root), 'LI', root);
+ if (otherLi_2) {
+ editor.undoManager.transact(function () {
+ removeBlock(dom, block, root);
+ mergeWithAdjacentLists(dom, otherLi_2.parentNode);
+ editor.selection.select(otherLi_2, true);
+ editor.selection.collapse(isForward);
+ });
+ return true;
+ }
+ }
+ return false;
+ };
+ var backspaceDeleteCaret = function (editor, isForward) {
+ return backspaceDeleteFromListToListCaret(editor, isForward) || backspaceDeleteIntoListCaret(editor, isForward);
+ };
+ var backspaceDeleteRange = function (editor) {
+ var selectionStartElm = editor.selection.getStart();
+ var root = getClosestListRootElm(editor, selectionStartElm);
+ var startListParent = editor.dom.getParent(selectionStartElm, 'LI,DT,DD', root);
+ if (startListParent || getSelectedListItems(editor).length > 0) {
+ editor.undoManager.transact(function () {
+ editor.execCommand('Delete');
+ normalizeLists(editor.dom, editor.getBody());
+ });
+ return true;
+ }
+ return false;
+ };
+ var backspaceDelete = function (editor, isForward) {
+ return editor.selection.isCollapsed() ? backspaceDeleteCaret(editor, isForward) : backspaceDeleteRange(editor);
+ };
+ var setup = function (editor) {
+ editor.on('keydown', function (e) {
+ if (e.keyCode === global$3.BACKSPACE) {
+ if (backspaceDelete(editor, false)) {
+ e.preventDefault();
+ }
+ } else if (e.keyCode === global$3.DELETE) {
+ if (backspaceDelete(editor, true)) {
+ e.preventDefault();
+ }
+ }
+ });
+ };
+
+ var get = function (editor) {
+ return {
+ backspaceDelete: function (isForward) {
+ backspaceDelete(editor, isForward);
+ }
+ };
+ };
+
+ var open = function (editor) {
+ var dom = editor.dom;
+ var currentList = getParentList(editor);
+ if (!isOlNode(currentList)) {
+ return;
+ }
+ editor.windowManager.open({
+ title: 'List Properties',
+ body: {
+ type: 'panel',
+ items: [{
+ type: 'input',
+ name: 'start',
+ label: 'Start list at number',
+ inputMode: 'numeric'
+ }]
+ },
+ initialData: { start: dom.getAttrib(currentList, 'start') || '1' },
+ buttons: [
+ {
+ type: 'cancel',
+ name: 'cancel',
+ text: 'Cancel'
+ },
+ {
+ type: 'submit',
+ name: 'save',
+ text: 'Save',
+ primary: true
+ }
+ ],
+ onSubmit: function (api) {
+ var data = api.getData();
+ editor.undoManager.transact(function () {
+ dom.setAttrib(getParentList(editor), 'start', data.start === '1' ? '' : data.start);
+ });
+ api.close();
+ }
+ });
+ };
+
+ var queryListCommandState = function (editor, listName) {
+ return function () {
+ var parentList = editor.dom.getParent(editor.selection.getStart(), 'UL,OL,DL');
+ return parentList && parentList.nodeName === listName;
+ };
+ };
+ var register = function (editor) {
+ editor.on('BeforeExecCommand', function (e) {
+ var cmd = e.command.toLowerCase();
+ if (cmd === 'indent') {
+ indentListSelection(editor);
+ } else if (cmd === 'outdent') {
+ outdentListSelection(editor);
+ }
+ });
+ editor.addCommand('InsertUnorderedList', function (ui, detail) {
+ toggleList(editor, 'UL', detail);
+ });
+ editor.addCommand('InsertOrderedList', function (ui, detail) {
+ toggleList(editor, 'OL', detail);
+ });
+ editor.addCommand('InsertDefinitionList', function (ui, detail) {
+ toggleList(editor, 'DL', detail);
+ });
+ editor.addCommand('RemoveList', function () {
+ flattenListSelection(editor);
+ });
+ editor.addCommand('mceListProps', function () {
+ open(editor);
+ });
+ editor.addQueryStateHandler('InsertUnorderedList', queryListCommandState(editor, 'UL'));
+ editor.addQueryStateHandler('InsertOrderedList', queryListCommandState(editor, 'OL'));
+ editor.addQueryStateHandler('InsertDefinitionList', queryListCommandState(editor, 'DL'));
+ };
+
+ var setupTabKey = function (editor) {
+ editor.on('keydown', function (e) {
+ if (e.keyCode !== global$3.TAB || global$3.metaKeyPressed(e)) {
+ return;
+ }
+ editor.undoManager.transact(function () {
+ if (e.shiftKey ? outdentListSelection(editor) : indentListSelection(editor)) {
+ e.preventDefault();
+ }
+ });
+ });
+ };
+ var setup$1 = function (editor) {
+ if (shouldIndentOnTab(editor)) {
+ setupTabKey(editor);
+ }
+ setup(editor);
+ };
+
+ var register$1 = function (editor) {
+ var exec = function (command) {
+ return function () {
+ return editor.execCommand(command);
+ };
+ };
+ if (!editor.hasPlugin('advlist')) {
+ editor.ui.registry.addToggleButton('numlist', {
+ icon: 'ordered-list',
+ active: false,
+ tooltip: 'Numbered list',
+ onAction: exec('InsertOrderedList'),
+ onSetup: function (api) {
+ return listState(editor, 'OL', api.setActive);
+ }
+ });
+ editor.ui.registry.addToggleButton('bullist', {
+ icon: 'unordered-list',
+ active: false,
+ tooltip: 'Bullet list',
+ onAction: exec('InsertUnorderedList'),
+ onSetup: function (api) {
+ return listState(editor, 'UL', api.setActive);
+ }
+ });
+ }
+ };
+
+ var register$2 = function (editor) {
+ var listProperties = {
+ text: 'List properties...',
+ icon: 'ordered-list',
+ onAction: function () {
+ return open(editor);
+ },
+ onSetup: function (api) {
+ return listState(editor, 'OL', function (active) {
+ return api.setDisabled(!active);
+ });
+ }
+ };
+ editor.ui.registry.addMenuItem('listprops', listProperties);
+ editor.ui.registry.addContextMenu('lists', {
+ update: function (node) {
+ var parentList = getParentList(editor, node);
+ return isOlNode(parentList) ? ['listprops'] : [];
+ }
+ });
+ };
+
+ function Plugin () {
+ global.add('lists', function (editor) {
+ if (editor.hasPlugin('rtc', true) === false) {
+ setup$1(editor);
+ register(editor);
+ }
+ register$1(editor);
+ register$2(editor);
+ return get(editor);
+ });
+ }
+
+ Plugin();
+
+}());
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/lists/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/lists/plugin.min.js
index 4391553061..01a36ea7ea 100644
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/lists/plugin.min.js
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/lists/plugin.min.js
@@ -1 +1,9 @@
-tinymce.PluginManager.add("lists",function(e){function t(e){return e&&/^(OL|UL)$/.test(e.nodeName)}function n(e){return e.parentNode.firstChild==e}function r(e){return e.parentNode.lastChild==e}function o(t){return t&&!!e.schema.getTextBlockElements()[t.nodeName]}function i(e){return e&&"SPAN"===e.nodeName&&"bookmark"===e.getAttribute("data-mce-type")}var a=this;e.on("init",function(){function d(e){function t(t){var r,o,i;o=e[t?"startContainer":"endContainer"],i=e[t?"startOffset":"endOffset"],1==o.nodeType&&(r=b.create("span",{"data-mce-type":"bookmark"}),o.hasChildNodes()?(i=Math.min(i,o.childNodes.length-1),t?o.insertBefore(r,o.childNodes[i]):b.insertAfter(r,o.childNodes[i])):o.appendChild(r),o=r,i=0),n[t?"startContainer":"endContainer"]=o,n[t?"startOffset":"endOffset"]=i}var n={};return t(!0),e.collapsed||t(),n}function s(e){function t(t){function n(e){for(var t=e.parentNode.firstChild,n=0;t;){if(t==e)return n;(1!=t.nodeType||"bookmark"!=t.getAttribute("data-mce-type"))&&n++,t=t.nextSibling}return-1}var r,o,i;r=i=e[t?"startContainer":"endContainer"],o=e[t?"startOffset":"endOffset"],r&&(1==r.nodeType&&(o=n(r),r=r.parentNode,b.remove(i)),e[t?"startContainer":"endContainer"]=r,e[t?"startOffset":"endOffset"]=o)}t(!0),t();var n=b.createRng();n.setStart(e.startContainer,e.startOffset),e.endContainer&&n.setEnd(e.endContainer,e.endOffset),L.setRng(n)}function f(t,n){var r,o,i,a=b.createFragment(),d=e.schema.getBlockElements();if(e.settings.forced_root_block&&(n=n||e.settings.forced_root_block),n&&(o=b.create(n),o.tagName===e.settings.forced_root_block&&b.setAttribs(o,e.settings.forced_root_block_attrs),a.appendChild(o)),t)for(;r=t.firstChild;){var s=r.nodeName;i||"SPAN"==s&&"bookmark"==r.getAttribute("data-mce-type")||(i=!0),d[s]?(a.appendChild(r),o=null):n?(o||(o=b.create(n),a.appendChild(o)),o.appendChild(r)):a.appendChild(r)}return e.settings.forced_root_block?i||tinymce.Env.ie&&!(tinymce.Env.ie>10)||o.appendChild(b.create("br",{"data-mce-bogus":"1"})):a.appendChild(b.create("br")),a}function l(){return tinymce.grep(L.getSelectedBlocks(),function(e){return"LI"==e.nodeName})}function c(e,t,n){var r,o,i=b.select('span[data-mce-type="bookmark"]',e);n=n||f(t),r=b.createRng(),r.setStartAfter(t),r.setEndAfter(e),o=r.extractContents(),b.isEmpty(o)||b.insertAfter(o,e),b.insertAfter(n,e),b.isEmpty(t.parentNode)&&(tinymce.each(i,function(e){t.parentNode.parentNode.insertBefore(e,t.parentNode)}),b.remove(t.parentNode)),b.remove(t)}function p(e){var n,r;if(n=e.nextSibling,n&&t(n)&&n.nodeName==e.nodeName){for(;r=n.firstChild;)e.appendChild(r);b.remove(n)}if(n=e.previousSibling,n&&t(n)&&n.nodeName==e.nodeName){for(;r=n.firstChild;)e.insertBefore(r,e.firstChild);b.remove(n)}}function u(e){tinymce.each(tinymce.grep(b.select("ol,ul",e)),function(e){var n,r=e.parentNode;"LI"==r.nodeName&&r.firstChild==e&&(n=r.previousSibling,n&&"LI"==n.nodeName&&(n.appendChild(e),b.isEmpty(r)&&b.remove(r))),t(r)&&(n=r.previousSibling,n&&"LI"==n.nodeName&&n.appendChild(e))})}function m(e){function o(e){b.isEmpty(e)&&b.remove(e)}var i,a=e.parentNode,d=a.parentNode;return n(e)&&r(e)?("LI"==d.nodeName?(b.insertAfter(e,d),o(d),b.remove(a)):t(d)?b.remove(a,!0):(d.insertBefore(f(e),a),b.remove(a)),!0):n(e)?("LI"==d.nodeName?(b.insertAfter(e,d),e.appendChild(a),o(d)):t(d)?d.insertBefore(e,a):(d.insertBefore(f(e),a),b.remove(e)),!0):r(e)?("LI"==d.nodeName?b.insertAfter(e,d):t(d)?b.insertAfter(e,a):(b.insertAfter(f(e),a),b.remove(e)),!0):("LI"==d.nodeName?(a=d,i=f(e,"LI")):i=t(d)?f(e,"LI"):f(e),c(a,e,i),u(a.parentNode),!0)}function h(e){function n(n,r){var o;if(t(n)){for(;o=e.lastChild.firstChild;)r.appendChild(o);b.remove(n)}}var r,o;return r=e.previousSibling,r&&t(r)?(r.appendChild(e),!0):r&&"LI"==r.nodeName&&t(r.lastChild)?(r.lastChild.appendChild(e),n(e.lastChild,r.lastChild),!0):(r=e.nextSibling,r&&t(r)?(r.insertBefore(e,r.firstChild),!0):r&&"LI"==r.nodeName&&t(e.lastChild)?!1:(r=e.previousSibling,r&&"LI"==r.nodeName?(o=b.create(e.parentNode.nodeName),r.appendChild(o),o.appendChild(e),n(e.lastChild,o),!0):!1))}function v(){var t=l();if(t.length){for(var n=d(L.getRng(!0)),r=0;r
/gi, '\n');
+ rep(/
/gi, '\n');
+ rep(/
/gi, '\n');
+ rep(/
');
+ rep(/\[b\]/gi, '');
+ rep(/\[\/b\]/gi, '');
+ rep(/\[i\]/gi, '');
+ rep(/\[\/i\]/gi, '');
+ rep(/\[u\]/gi, '');
+ rep(/\[\/u\]/gi, '');
+ rep(/\[url=([^\]]+)\](.*?)\[\/url\]/gi, '$2');
+ rep(/\[url\](.*?)\[\/url\]/gi, '$1');
+ rep(/\[img\](.*?)\[\/img\]/gi, '');
+ rep(/\[color=(.*?)\](.*?)\[\/color\]/gi, '$2');
+ rep(/\[code\](.*?)\[\/code\]/gi, '$1 ');
+ rep(/\[quote.*?\](.*?)\[\/quote\]/gi, '$1 ');
+ return s;
+ };
+
+ function Plugin () {
+ global.add('bbcode', function (editor) {
+ editor.on('BeforeSetContent', function (e) {
+ e.content = bbcode2html(e.content);
+ });
+ editor.on('PostProcess', function (e) {
+ if (e.set) {
+ e.content = bbcode2html(e.content);
+ }
+ if (e.get) {
+ e.content = html2bbcode(e.content);
+ }
+ });
+ });
+ }
+
+ Plugin();
+
+}());
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/bbcode/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/bbcode/plugin.min.js
new file mode 100644
index 0000000000..4c26eab1f8
--- /dev/null
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/bbcode/plugin.min.js
@@ -0,0 +1,9 @@
+/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var o=tinymce.util.Tools.resolve("tinymce.PluginManager"),e=tinymce.util.Tools.resolve("tinymce.util.Tools"),t=function(t){t=e.trim(t);var o=function(o,e){t=t.replace(o,e)};return o(/\n/gi,"
"),o(/\[b\]/gi,""),o(/\[\/b\]/gi,""),o(/\[i\]/gi,""),o(/\[\/i\]/gi,""),o(/\[u\]/gi,""),o(/\[\/u\]/gi,""),o(/\[url=([^\]]+)\](.*?)\[\/url\]/gi,'$2'),o(/\[url\](.*?)\[\/url\]/gi,'$1'),o(/\[img\](.*?)\[\/img\]/gi,''),o(/\[color=(.*?)\](.*?)\[\/color\]/gi,'$2'),o(/\[code\](.*?)\[\/code\]/gi,'$1 '),o(/\[quote.*?\](.*?)\[\/quote\]/gi,'$1 '),t};o.add("bbcode",function(o){o.on("BeforeSetContent",function(o){o.content=t(o.content)}),o.on("PostProcess",function(o){o.set&&(o.content=t(o.content)),o.get&&(o.content=function(t){t=e.trim(t);var o=function(o,e){t=t.replace(o,e)};return o(/
]*>/gi,"[quote]"),o(/<\/blockquote>/gi,"[/quote]"),o(/
/gi,"\n"),o(/
/gi,"\n"),o(/
/gi,"\n"),o(/';
+ var typeOf = function (x) {
+ var t = typeof x;
+ if (x === null) {
+ return 'null';
+ } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
+ return 'array';
+ } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
+ return 'string';
+ } else {
+ return t;
+ }
+ };
+ var isType = function (type) {
+ return function (value) {
+ return typeOf(value) === type;
+ };
+ };
+ var isArray = isType('array');
- var width = 25;
- for (y = 0; y < 10; y++) {
- gridHtml += '
';
+ var get = function (editor) {
+ var getCharMap = function () {
+ return getCharMap$1(editor);
+ };
+ var insertChar$1 = function (chr) {
+ insertChar(editor, chr);
+ };
+ return {
+ getCharMap: getCharMap,
+ insertChar: insertChar$1
+ };
+ };
- var charMapPanel = {
- type: 'container',
- html: gridHtml,
- onclick: function(e) {
- var target = e.target;
- if (/^(TD|DIV)$/.test(target.nodeName)) {
- editor.execCommand('mceInsertContent', false, tinymce.trim(target.innerText || target.textContent));
+ var Cell = function (initial) {
+ var value = initial;
+ var get = function () {
+ return value;
+ };
+ var set = function (v) {
+ value = v;
+ };
+ return {
+ get: get,
+ set: set
+ };
+ };
- if (!e.ctrlKey) {
- win.close();
- }
- }
- },
- onmouseover: function(e) {
- var td = getParentTd(e.target);
+ var last = function (fn, rate) {
+ var timer = null;
+ var cancel = function () {
+ if (timer !== null) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ };
+ var throttle = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ if (timer !== null) {
+ clearTimeout(timer);
+ }
+ timer = setTimeout(function () {
+ fn.apply(null, args);
+ timer = null;
+ }, rate);
+ };
+ return {
+ cancel: cancel,
+ throttle: throttle
+ };
+ };
- if (td) {
- win.find('#preview').text(td.firstChild.firstChild.data);
- }
- }
- };
+ var nativeFromCodePoint = String.fromCodePoint;
+ var contains = function (str, substr) {
+ return str.indexOf(substr) !== -1;
+ };
+ var fromCodePoint = function () {
+ var codePoints = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ codePoints[_i] = arguments[_i];
+ }
+ if (nativeFromCodePoint) {
+ return nativeFromCodePoint.apply(void 0, codePoints);
+ } else {
+ var codeUnits = [];
+ var codeLen = 0;
+ var result = '';
+ for (var index = 0, len = codePoints.length; index !== len; ++index) {
+ var codePoint = +codePoints[index];
+ if (!(codePoint < 1114111 && codePoint >>> 0 === codePoint)) {
+ throw RangeError('Invalid code point: ' + codePoint);
+ }
+ if (codePoint <= 65535) {
+ codeLen = codeUnits.push(codePoint);
+ } else {
+ codePoint -= 65536;
+ codeLen = codeUnits.push((codePoint >> 10) + 55296, codePoint % 1024 + 56320);
+ }
+ if (codeLen >= 16383) {
+ result += String.fromCharCode.apply(null, codeUnits);
+ codeUnits.length = 0;
+ }
+ }
+ return result + String.fromCharCode.apply(null, codeUnits);
+ }
+ };
- win = editor.windowManager.open({
- title: "Special character",
- spacing: 10,
- padding: 10,
- items: [
- charMapPanel,
- {
- type: 'label',
- name: 'preview',
- text: ' ',
- style: 'font-size: 40px; text-align: center',
- border: 1,
- minWidth: 100,
- minHeight: 80
- }
- ],
- buttons: [
- {text: "Close", onclick: function() {
- win.close();
- }}
- ]
- });
- }
+ var charMatches = function (charCode, name, lowerCasePattern) {
+ if (contains(fromCodePoint(charCode).toLowerCase(), lowerCasePattern)) {
+ return true;
+ } else {
+ return contains(name.toLowerCase(), lowerCasePattern) || contains(name.toLowerCase().replace(/\s+/g, ''), lowerCasePattern);
+ }
+ };
+ var scan = function (group, pattern) {
+ var matches = [];
+ var lowerCasePattern = pattern.toLowerCase();
+ each(group.characters, function (g) {
+ if (charMatches(g[0], g[1], lowerCasePattern)) {
+ matches.push(g);
+ }
+ });
+ return map(matches, function (m) {
+ return {
+ text: m[1],
+ value: fromCodePoint(m[0]),
+ icon: fromCodePoint(m[0])
+ };
+ });
+ };
- editor.addButton('charmap', {
- icon: 'charmap',
- tooltip: 'Special character',
- onclick: showDialog
- });
+ var patternName = 'pattern';
+ var open = function (editor, charMap) {
+ var makeGroupItems = function () {
+ return [
+ {
+ label: 'Search',
+ type: 'input',
+ name: patternName
+ },
+ {
+ type: 'collection',
+ name: 'results'
+ }
+ ];
+ };
+ var makeTabs = function () {
+ return map(charMap, function (charGroup) {
+ return {
+ title: charGroup.name,
+ name: charGroup.name,
+ items: makeGroupItems()
+ };
+ });
+ };
+ var makePanel = function () {
+ return {
+ type: 'panel',
+ items: makeGroupItems()
+ };
+ };
+ var makeTabPanel = function () {
+ return {
+ type: 'tabpanel',
+ tabs: makeTabs()
+ };
+ };
+ var currentTab = charMap.length === 1 ? Cell(UserDefined) : Cell('All');
+ var scanAndSet = function (dialogApi, pattern) {
+ find(charMap, function (group) {
+ return group.name === currentTab.get();
+ }).each(function (f) {
+ var items = scan(f, pattern);
+ dialogApi.setData({ results: items });
+ });
+ };
+ var SEARCH_DELAY = 40;
+ var updateFilter = last(function (dialogApi) {
+ var pattern = dialogApi.getData().pattern;
+ scanAndSet(dialogApi, pattern);
+ }, SEARCH_DELAY);
+ var body = charMap.length === 1 ? makePanel() : makeTabPanel();
+ var initialData = {
+ pattern: '',
+ results: scan(charMap[0], '')
+ };
+ var bridgeSpec = {
+ title: 'Special Character',
+ size: 'normal',
+ body: body,
+ buttons: [{
+ type: 'cancel',
+ name: 'close',
+ text: 'Close',
+ primary: true
+ }],
+ initialData: initialData,
+ onAction: function (api, details) {
+ if (details.name === 'results') {
+ insertChar(editor, details.value);
+ api.close();
+ }
+ },
+ onTabChange: function (dialogApi, details) {
+ currentTab.set(details.newTabName);
+ updateFilter.throttle(dialogApi);
+ },
+ onChange: function (dialogApi, changeData) {
+ if (changeData.name === patternName) {
+ updateFilter.throttle(dialogApi);
+ }
+ }
+ };
+ var dialogApi = editor.windowManager.open(bridgeSpec);
+ dialogApi.focus(patternName);
+ };
- editor.addMenuItem('charmap', {
- icon: 'charmap',
- text: 'Special character',
- onclick: showDialog,
- context: 'insert'
- });
-});
\ No newline at end of file
+ var register = function (editor, charMap) {
+ editor.addCommand('mceShowCharmap', function () {
+ open(editor, charMap);
+ });
+ };
+
+ var global$2 = tinymce.util.Tools.resolve('tinymce.util.Promise');
+
+ var init = function (editor, all) {
+ editor.ui.registry.addAutocompleter('charmap', {
+ ch: ':',
+ columns: 'auto',
+ minChars: 2,
+ fetch: function (pattern, _maxResults) {
+ return new global$2(function (resolve, _reject) {
+ resolve(scan(all, pattern));
+ });
+ },
+ onAction: function (autocompleteApi, rng, value) {
+ editor.selection.setRng(rng);
+ editor.insertContent(value);
+ autocompleteApi.hide();
+ }
+ });
+ };
+
+ var register$1 = function (editor) {
+ editor.ui.registry.addButton('charmap', {
+ icon: 'insert-character',
+ tooltip: 'Special character',
+ onAction: function () {
+ return editor.execCommand('mceShowCharmap');
+ }
+ });
+ editor.ui.registry.addMenuItem('charmap', {
+ icon: 'insert-character',
+ text: 'Special character...',
+ onAction: function () {
+ return editor.execCommand('mceShowCharmap');
+ }
+ });
+ };
+
+ function Plugin () {
+ global.add('charmap', function (editor) {
+ var charMap = getCharMap$1(editor);
+ register(editor, charMap);
+ register$1(editor);
+ init(editor, charMap[0]);
+ return get(editor);
+ });
+ }
+
+ Plugin();
+
+}());
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.min.js
index 69d189143a..05c0f3d79f 100644
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.min.js
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.min.js
@@ -1 +1,9 @@
-tinymce.PluginManager.add("charmap",function(e){function a(){function a(e){for(;e;){if("TD"==e.nodeName)return e;e=e.parentNode}}var i,r,o,n;i='';
+ var nativePush = Array.prototype.push;
+ var map = function (xs, f) {
+ var len = xs.length;
+ var r = new Array(len);
+ for (var i = 0; i < len; i++) {
+ var x = xs[i];
+ r[i] = f(x, i);
+ }
+ return r;
+ };
+ var each = function (xs, f) {
+ for (var i = 0, len = xs.length; i < len; i++) {
+ var x = xs[i];
+ f(x, i);
+ }
+ };
+ var findUntil = function (xs, pred, until) {
+ for (var i = 0, len = xs.length; i < len; i++) {
+ var x = xs[i];
+ if (pred(x, i)) {
+ return Optional.some(x);
+ } else if (until(x, i)) {
+ break;
+ }
+ }
+ return Optional.none();
+ };
+ var find = function (xs, pred) {
+ return findUntil(xs, pred, never);
+ };
+ var flatten = function (xs) {
+ var r = [];
+ for (var i = 0, len = xs.length; i < len; ++i) {
+ if (!isArray(xs[i])) {
+ throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
+ }
+ nativePush.apply(r, xs[i]);
+ }
+ return r;
+ };
+ var bind = function (xs, f) {
+ return flatten(map(xs, f));
+ };
- for (x = 0; x < width; x++) {
- var chr = charmap[y * width + x];
+ var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');
- gridHtml += ' ';
- }
+ var isArray$1 = global$1.isArray;
+ var UserDefined = 'User Defined';
+ var getDefaultCharMap = function () {
+ return [
+ {
+ name: 'Currency',
+ characters: [
+ [
+ 36,
+ 'dollar sign'
+ ],
+ [
+ 162,
+ 'cent sign'
+ ],
+ [
+ 8364,
+ 'euro sign'
+ ],
+ [
+ 163,
+ 'pound sign'
+ ],
+ [
+ 165,
+ 'yen sign'
+ ],
+ [
+ 164,
+ 'currency sign'
+ ],
+ [
+ 8352,
+ 'euro-currency sign'
+ ],
+ [
+ 8353,
+ 'colon sign'
+ ],
+ [
+ 8354,
+ 'cruzeiro sign'
+ ],
+ [
+ 8355,
+ 'french franc sign'
+ ],
+ [
+ 8356,
+ 'lira sign'
+ ],
+ [
+ 8357,
+ 'mill sign'
+ ],
+ [
+ 8358,
+ 'naira sign'
+ ],
+ [
+ 8359,
+ 'peseta sign'
+ ],
+ [
+ 8360,
+ 'rupee sign'
+ ],
+ [
+ 8361,
+ 'won sign'
+ ],
+ [
+ 8362,
+ 'new sheqel sign'
+ ],
+ [
+ 8363,
+ 'dong sign'
+ ],
+ [
+ 8365,
+ 'kip sign'
+ ],
+ [
+ 8366,
+ 'tugrik sign'
+ ],
+ [
+ 8367,
+ 'drachma sign'
+ ],
+ [
+ 8368,
+ 'german penny symbol'
+ ],
+ [
+ 8369,
+ 'peso sign'
+ ],
+ [
+ 8370,
+ 'guarani sign'
+ ],
+ [
+ 8371,
+ 'austral sign'
+ ],
+ [
+ 8372,
+ 'hryvnia sign'
+ ],
+ [
+ 8373,
+ 'cedi sign'
+ ],
+ [
+ 8374,
+ 'livre tournois sign'
+ ],
+ [
+ 8375,
+ 'spesmilo sign'
+ ],
+ [
+ 8376,
+ 'tenge sign'
+ ],
+ [
+ 8377,
+ 'indian rupee sign'
+ ],
+ [
+ 8378,
+ 'turkish lira sign'
+ ],
+ [
+ 8379,
+ 'nordic mark sign'
+ ],
+ [
+ 8380,
+ 'manat sign'
+ ],
+ [
+ 8381,
+ 'ruble sign'
+ ],
+ [
+ 20870,
+ 'yen character'
+ ],
+ [
+ 20803,
+ 'yuan character'
+ ],
+ [
+ 22291,
+ 'yuan character, in hong kong and taiwan'
+ ],
+ [
+ 22278,
+ 'yen/yuan character variant one'
+ ]
+ ]
+ },
+ {
+ name: 'Text',
+ characters: [
+ [
+ 169,
+ 'copyright sign'
+ ],
+ [
+ 174,
+ 'registered sign'
+ ],
+ [
+ 8482,
+ 'trade mark sign'
+ ],
+ [
+ 8240,
+ 'per mille sign'
+ ],
+ [
+ 181,
+ 'micro sign'
+ ],
+ [
+ 183,
+ 'middle dot'
+ ],
+ [
+ 8226,
+ 'bullet'
+ ],
+ [
+ 8230,
+ 'three dot leader'
+ ],
+ [
+ 8242,
+ 'minutes / feet'
+ ],
+ [
+ 8243,
+ 'seconds / inches'
+ ],
+ [
+ 167,
+ 'section sign'
+ ],
+ [
+ 182,
+ 'paragraph sign'
+ ],
+ [
+ 223,
+ 'sharp s / ess-zed'
+ ]
+ ]
+ },
+ {
+ name: 'Quotations',
+ characters: [
+ [
+ 8249,
+ 'single left-pointing angle quotation mark'
+ ],
+ [
+ 8250,
+ 'single right-pointing angle quotation mark'
+ ],
+ [
+ 171,
+ 'left pointing guillemet'
+ ],
+ [
+ 187,
+ 'right pointing guillemet'
+ ],
+ [
+ 8216,
+ 'left single quotation mark'
+ ],
+ [
+ 8217,
+ 'right single quotation mark'
+ ],
+ [
+ 8220,
+ 'left double quotation mark'
+ ],
+ [
+ 8221,
+ 'right double quotation mark'
+ ],
+ [
+ 8218,
+ 'single low-9 quotation mark'
+ ],
+ [
+ 8222,
+ 'double low-9 quotation mark'
+ ],
+ [
+ 60,
+ 'less-than sign'
+ ],
+ [
+ 62,
+ 'greater-than sign'
+ ],
+ [
+ 8804,
+ 'less-than or equal to'
+ ],
+ [
+ 8805,
+ 'greater-than or equal to'
+ ],
+ [
+ 8211,
+ 'en dash'
+ ],
+ [
+ 8212,
+ 'em dash'
+ ],
+ [
+ 175,
+ 'macron'
+ ],
+ [
+ 8254,
+ 'overline'
+ ],
+ [
+ 164,
+ 'currency sign'
+ ],
+ [
+ 166,
+ 'broken bar'
+ ],
+ [
+ 168,
+ 'diaeresis'
+ ],
+ [
+ 161,
+ 'inverted exclamation mark'
+ ],
+ [
+ 191,
+ 'turned question mark'
+ ],
+ [
+ 710,
+ 'circumflex accent'
+ ],
+ [
+ 732,
+ 'small tilde'
+ ],
+ [
+ 176,
+ 'degree sign'
+ ],
+ [
+ 8722,
+ 'minus sign'
+ ],
+ [
+ 177,
+ 'plus-minus sign'
+ ],
+ [
+ 247,
+ 'division sign'
+ ],
+ [
+ 8260,
+ 'fraction slash'
+ ],
+ [
+ 215,
+ 'multiplication sign'
+ ],
+ [
+ 185,
+ 'superscript one'
+ ],
+ [
+ 178,
+ 'superscript two'
+ ],
+ [
+ 179,
+ 'superscript three'
+ ],
+ [
+ 188,
+ 'fraction one quarter'
+ ],
+ [
+ 189,
+ 'fraction one half'
+ ],
+ [
+ 190,
+ 'fraction three quarters'
+ ]
+ ]
+ },
+ {
+ name: 'Mathematical',
+ characters: [
+ [
+ 402,
+ 'function / florin'
+ ],
+ [
+ 8747,
+ 'integral'
+ ],
+ [
+ 8721,
+ 'n-ary sumation'
+ ],
+ [
+ 8734,
+ 'infinity'
+ ],
+ [
+ 8730,
+ 'square root'
+ ],
+ [
+ 8764,
+ 'similar to'
+ ],
+ [
+ 8773,
+ 'approximately equal to'
+ ],
+ [
+ 8776,
+ 'almost equal to'
+ ],
+ [
+ 8800,
+ 'not equal to'
+ ],
+ [
+ 8801,
+ 'identical to'
+ ],
+ [
+ 8712,
+ 'element of'
+ ],
+ [
+ 8713,
+ 'not an element of'
+ ],
+ [
+ 8715,
+ 'contains as member'
+ ],
+ [
+ 8719,
+ 'n-ary product'
+ ],
+ [
+ 8743,
+ 'logical and'
+ ],
+ [
+ 8744,
+ 'logical or'
+ ],
+ [
+ 172,
+ 'not sign'
+ ],
+ [
+ 8745,
+ 'intersection'
+ ],
+ [
+ 8746,
+ 'union'
+ ],
+ [
+ 8706,
+ 'partial differential'
+ ],
+ [
+ 8704,
+ 'for all'
+ ],
+ [
+ 8707,
+ 'there exists'
+ ],
+ [
+ 8709,
+ 'diameter'
+ ],
+ [
+ 8711,
+ 'backward difference'
+ ],
+ [
+ 8727,
+ 'asterisk operator'
+ ],
+ [
+ 8733,
+ 'proportional to'
+ ],
+ [
+ 8736,
+ 'angle'
+ ]
+ ]
+ },
+ {
+ name: 'Extended Latin',
+ characters: [
+ [
+ 192,
+ 'A - grave'
+ ],
+ [
+ 193,
+ 'A - acute'
+ ],
+ [
+ 194,
+ 'A - circumflex'
+ ],
+ [
+ 195,
+ 'A - tilde'
+ ],
+ [
+ 196,
+ 'A - diaeresis'
+ ],
+ [
+ 197,
+ 'A - ring above'
+ ],
+ [
+ 256,
+ 'A - macron'
+ ],
+ [
+ 198,
+ 'ligature AE'
+ ],
+ [
+ 199,
+ 'C - cedilla'
+ ],
+ [
+ 200,
+ 'E - grave'
+ ],
+ [
+ 201,
+ 'E - acute'
+ ],
+ [
+ 202,
+ 'E - circumflex'
+ ],
+ [
+ 203,
+ 'E - diaeresis'
+ ],
+ [
+ 274,
+ 'E - macron'
+ ],
+ [
+ 204,
+ 'I - grave'
+ ],
+ [
+ 205,
+ 'I - acute'
+ ],
+ [
+ 206,
+ 'I - circumflex'
+ ],
+ [
+ 207,
+ 'I - diaeresis'
+ ],
+ [
+ 298,
+ 'I - macron'
+ ],
+ [
+ 208,
+ 'ETH'
+ ],
+ [
+ 209,
+ 'N - tilde'
+ ],
+ [
+ 210,
+ 'O - grave'
+ ],
+ [
+ 211,
+ 'O - acute'
+ ],
+ [
+ 212,
+ 'O - circumflex'
+ ],
+ [
+ 213,
+ 'O - tilde'
+ ],
+ [
+ 214,
+ 'O - diaeresis'
+ ],
+ [
+ 216,
+ 'O - slash'
+ ],
+ [
+ 332,
+ 'O - macron'
+ ],
+ [
+ 338,
+ 'ligature OE'
+ ],
+ [
+ 352,
+ 'S - caron'
+ ],
+ [
+ 217,
+ 'U - grave'
+ ],
+ [
+ 218,
+ 'U - acute'
+ ],
+ [
+ 219,
+ 'U - circumflex'
+ ],
+ [
+ 220,
+ 'U - diaeresis'
+ ],
+ [
+ 362,
+ 'U - macron'
+ ],
+ [
+ 221,
+ 'Y - acute'
+ ],
+ [
+ 376,
+ 'Y - diaeresis'
+ ],
+ [
+ 562,
+ 'Y - macron'
+ ],
+ [
+ 222,
+ 'THORN'
+ ],
+ [
+ 224,
+ 'a - grave'
+ ],
+ [
+ 225,
+ 'a - acute'
+ ],
+ [
+ 226,
+ 'a - circumflex'
+ ],
+ [
+ 227,
+ 'a - tilde'
+ ],
+ [
+ 228,
+ 'a - diaeresis'
+ ],
+ [
+ 229,
+ 'a - ring above'
+ ],
+ [
+ 257,
+ 'a - macron'
+ ],
+ [
+ 230,
+ 'ligature ae'
+ ],
+ [
+ 231,
+ 'c - cedilla'
+ ],
+ [
+ 232,
+ 'e - grave'
+ ],
+ [
+ 233,
+ 'e - acute'
+ ],
+ [
+ 234,
+ 'e - circumflex'
+ ],
+ [
+ 235,
+ 'e - diaeresis'
+ ],
+ [
+ 275,
+ 'e - macron'
+ ],
+ [
+ 236,
+ 'i - grave'
+ ],
+ [
+ 237,
+ 'i - acute'
+ ],
+ [
+ 238,
+ 'i - circumflex'
+ ],
+ [
+ 239,
+ 'i - diaeresis'
+ ],
+ [
+ 299,
+ 'i - macron'
+ ],
+ [
+ 240,
+ 'eth'
+ ],
+ [
+ 241,
+ 'n - tilde'
+ ],
+ [
+ 242,
+ 'o - grave'
+ ],
+ [
+ 243,
+ 'o - acute'
+ ],
+ [
+ 244,
+ 'o - circumflex'
+ ],
+ [
+ 245,
+ 'o - tilde'
+ ],
+ [
+ 246,
+ 'o - diaeresis'
+ ],
+ [
+ 248,
+ 'o slash'
+ ],
+ [
+ 333,
+ 'o macron'
+ ],
+ [
+ 339,
+ 'ligature oe'
+ ],
+ [
+ 353,
+ 's - caron'
+ ],
+ [
+ 249,
+ 'u - grave'
+ ],
+ [
+ 250,
+ 'u - acute'
+ ],
+ [
+ 251,
+ 'u - circumflex'
+ ],
+ [
+ 252,
+ 'u - diaeresis'
+ ],
+ [
+ 363,
+ 'u - macron'
+ ],
+ [
+ 253,
+ 'y - acute'
+ ],
+ [
+ 254,
+ 'thorn'
+ ],
+ [
+ 255,
+ 'y - diaeresis'
+ ],
+ [
+ 563,
+ 'y - macron'
+ ],
+ [
+ 913,
+ 'Alpha'
+ ],
+ [
+ 914,
+ 'Beta'
+ ],
+ [
+ 915,
+ 'Gamma'
+ ],
+ [
+ 916,
+ 'Delta'
+ ],
+ [
+ 917,
+ 'Epsilon'
+ ],
+ [
+ 918,
+ 'Zeta'
+ ],
+ [
+ 919,
+ 'Eta'
+ ],
+ [
+ 920,
+ 'Theta'
+ ],
+ [
+ 921,
+ 'Iota'
+ ],
+ [
+ 922,
+ 'Kappa'
+ ],
+ [
+ 923,
+ 'Lambda'
+ ],
+ [
+ 924,
+ 'Mu'
+ ],
+ [
+ 925,
+ 'Nu'
+ ],
+ [
+ 926,
+ 'Xi'
+ ],
+ [
+ 927,
+ 'Omicron'
+ ],
+ [
+ 928,
+ 'Pi'
+ ],
+ [
+ 929,
+ 'Rho'
+ ],
+ [
+ 931,
+ 'Sigma'
+ ],
+ [
+ 932,
+ 'Tau'
+ ],
+ [
+ 933,
+ 'Upsilon'
+ ],
+ [
+ 934,
+ 'Phi'
+ ],
+ [
+ 935,
+ 'Chi'
+ ],
+ [
+ 936,
+ 'Psi'
+ ],
+ [
+ 937,
+ 'Omega'
+ ],
+ [
+ 945,
+ 'alpha'
+ ],
+ [
+ 946,
+ 'beta'
+ ],
+ [
+ 947,
+ 'gamma'
+ ],
+ [
+ 948,
+ 'delta'
+ ],
+ [
+ 949,
+ 'epsilon'
+ ],
+ [
+ 950,
+ 'zeta'
+ ],
+ [
+ 951,
+ 'eta'
+ ],
+ [
+ 952,
+ 'theta'
+ ],
+ [
+ 953,
+ 'iota'
+ ],
+ [
+ 954,
+ 'kappa'
+ ],
+ [
+ 955,
+ 'lambda'
+ ],
+ [
+ 956,
+ 'mu'
+ ],
+ [
+ 957,
+ 'nu'
+ ],
+ [
+ 958,
+ 'xi'
+ ],
+ [
+ 959,
+ 'omicron'
+ ],
+ [
+ 960,
+ 'pi'
+ ],
+ [
+ 961,
+ 'rho'
+ ],
+ [
+ 962,
+ 'final sigma'
+ ],
+ [
+ 963,
+ 'sigma'
+ ],
+ [
+ 964,
+ 'tau'
+ ],
+ [
+ 965,
+ 'upsilon'
+ ],
+ [
+ 966,
+ 'phi'
+ ],
+ [
+ 967,
+ 'chi'
+ ],
+ [
+ 968,
+ 'psi'
+ ],
+ [
+ 969,
+ 'omega'
+ ]
+ ]
+ },
+ {
+ name: 'Symbols',
+ characters: [
+ [
+ 8501,
+ 'alef symbol'
+ ],
+ [
+ 982,
+ 'pi symbol'
+ ],
+ [
+ 8476,
+ 'real part symbol'
+ ],
+ [
+ 978,
+ 'upsilon - hook symbol'
+ ],
+ [
+ 8472,
+ 'Weierstrass p'
+ ],
+ [
+ 8465,
+ 'imaginary part'
+ ]
+ ]
+ },
+ {
+ name: 'Arrows',
+ characters: [
+ [
+ 8592,
+ 'leftwards arrow'
+ ],
+ [
+ 8593,
+ 'upwards arrow'
+ ],
+ [
+ 8594,
+ 'rightwards arrow'
+ ],
+ [
+ 8595,
+ 'downwards arrow'
+ ],
+ [
+ 8596,
+ 'left right arrow'
+ ],
+ [
+ 8629,
+ 'carriage return'
+ ],
+ [
+ 8656,
+ 'leftwards double arrow'
+ ],
+ [
+ 8657,
+ 'upwards double arrow'
+ ],
+ [
+ 8658,
+ 'rightwards double arrow'
+ ],
+ [
+ 8659,
+ 'downwards double arrow'
+ ],
+ [
+ 8660,
+ 'left right double arrow'
+ ],
+ [
+ 8756,
+ 'therefore'
+ ],
+ [
+ 8834,
+ 'subset of'
+ ],
+ [
+ 8835,
+ 'superset of'
+ ],
+ [
+ 8836,
+ 'not a subset of'
+ ],
+ [
+ 8838,
+ 'subset of or equal to'
+ ],
+ [
+ 8839,
+ 'superset of or equal to'
+ ],
+ [
+ 8853,
+ 'circled plus'
+ ],
+ [
+ 8855,
+ 'circled times'
+ ],
+ [
+ 8869,
+ 'perpendicular'
+ ],
+ [
+ 8901,
+ 'dot operator'
+ ],
+ [
+ 8968,
+ 'left ceiling'
+ ],
+ [
+ 8969,
+ 'right ceiling'
+ ],
+ [
+ 8970,
+ 'left floor'
+ ],
+ [
+ 8971,
+ 'right floor'
+ ],
+ [
+ 9001,
+ 'left-pointing angle bracket'
+ ],
+ [
+ 9002,
+ 'right-pointing angle bracket'
+ ],
+ [
+ 9674,
+ 'lozenge'
+ ],
+ [
+ 9824,
+ 'black spade suit'
+ ],
+ [
+ 9827,
+ 'black club suit'
+ ],
+ [
+ 9829,
+ 'black heart suit'
+ ],
+ [
+ 9830,
+ 'black diamond suit'
+ ],
+ [
+ 8194,
+ 'en space'
+ ],
+ [
+ 8195,
+ 'em space'
+ ],
+ [
+ 8201,
+ 'thin space'
+ ],
+ [
+ 8204,
+ 'zero width non-joiner'
+ ],
+ [
+ 8205,
+ 'zero width joiner'
+ ],
+ [
+ 8206,
+ 'left-to-right mark'
+ ],
+ [
+ 8207,
+ 'right-to-left mark'
+ ]
+ ]
+ }
+ ];
+ };
+ var charmapFilter = function (charmap) {
+ return global$1.grep(charmap, function (item) {
+ return isArray$1(item) && item.length === 2;
+ });
+ };
+ var getCharsFromSetting = function (settingValue) {
+ if (isArray$1(settingValue)) {
+ return [].concat(charmapFilter(settingValue));
+ }
+ if (typeof settingValue === 'function') {
+ return settingValue();
+ }
+ return [];
+ };
+ var extendCharMap = function (editor, charmap) {
+ var userCharMap = getCharMap(editor);
+ if (userCharMap) {
+ charmap = [{
+ name: UserDefined,
+ characters: getCharsFromSetting(userCharMap)
+ }];
+ }
+ var userCharMapAppend = getCharMapAppend(editor);
+ if (userCharMapAppend) {
+ var userDefinedGroup = global$1.grep(charmap, function (cg) {
+ return cg.name === UserDefined;
+ });
+ if (userDefinedGroup.length) {
+ userDefinedGroup[0].characters = [].concat(userDefinedGroup[0].characters).concat(getCharsFromSetting(userCharMapAppend));
+ return charmap;
+ }
+ return [].concat(charmap).concat({
+ name: UserDefined,
+ characters: getCharsFromSetting(userCharMapAppend)
+ });
+ }
+ return charmap;
+ };
+ var getCharMap$1 = function (editor) {
+ var groups = extendCharMap(editor, getDefaultCharMap());
+ return groups.length > 1 ? [{
+ name: 'All',
+ characters: bind(groups, function (g) {
+ return g.characters;
+ })
+ }].concat(groups) : groups;
+ };
- gridHtml += ' ';
- }
+ var getCharMap = function (editor) {
+ return editor.getParam('charmap');
+ };
+ var getCharMapAppend = function (editor) {
+ return editor.getParam('charmap_append');
+ };
- gridHtml += '';var l=25;for(o=0;o<10;o++){for(i+="
";var c={type:"container",html:i,onclick:function(a){var t=a.target;/^(TD|DIV)$/.test(t.nodeName)&&(e.execCommand("mceInsertContent",!1,tinymce.trim(t.innerText||t.textContent)),a.ctrlKey||n.close())},onmouseover:function(e){var t=a(e.target);t&&n.find("#preview").text(t.firstChild.firstChild.data)}};n=e.windowManager.open({title:"Special character",spacing:10,padding:10,items:[c,{type:"label",name:"preview",text:" ",style:"font-size: 40px; text-align: center",border:1,minWidth:100,minHeight:80}],buttons:[{text:"Close",onclick:function(){n.close()}}]})}var t=[["160","no-break space"],["38","ampersand"],["34","quotation mark"],["162","cent sign"],["8364","euro sign"],["163","pound sign"],["165","yen sign"],["169","copyright sign"],["174","registered sign"],["8482","trade mark sign"],["8240","per mille sign"],["181","micro sign"],["183","middle dot"],["8226","bullet"],["8230","three dot leader"],["8242","minutes / feet"],["8243","seconds / inches"],["167","section sign"],["182","paragraph sign"],["223","sharp s / ess-zed"],["8249","single left-pointing angle quotation mark"],["8250","single right-pointing angle quotation mark"],["171","left pointing guillemet"],["187","right pointing guillemet"],["8216","left single quotation mark"],["8217","right single quotation mark"],["8220","left double quotation mark"],["8221","right double quotation mark"],["8218","single low-9 quotation mark"],["8222","double low-9 quotation mark"],["60","less-than sign"],["62","greater-than sign"],["8804","less-than or equal to"],["8805","greater-than or equal to"],["8211","en dash"],["8212","em dash"],["175","macron"],["8254","overline"],["164","currency sign"],["166","broken bar"],["168","diaeresis"],["161","inverted exclamation mark"],["191","turned question mark"],["710","circumflex accent"],["732","small tilde"],["176","degree sign"],["8722","minus sign"],["177","plus-minus sign"],["247","division sign"],["8260","fraction slash"],["215","multiplication sign"],["185","superscript one"],["178","superscript two"],["179","superscript three"],["188","fraction one quarter"],["189","fraction one half"],["190","fraction three quarters"],["402","function / florin"],["8747","integral"],["8721","n-ary sumation"],["8734","infinity"],["8730","square root"],["8764","similar to"],["8773","approximately equal to"],["8776","almost equal to"],["8800","not equal to"],["8801","identical to"],["8712","element of"],["8713","not an element of"],["8715","contains as member"],["8719","n-ary product"],["8743","logical and"],["8744","logical or"],["172","not sign"],["8745","intersection"],["8746","union"],["8706","partial differential"],["8704","for all"],["8707","there exists"],["8709","diameter"],["8711","backward difference"],["8727","asterisk operator"],["8733","proportional to"],["8736","angle"],["180","acute accent"],["184","cedilla"],["170","feminine ordinal indicator"],["186","masculine ordinal indicator"],["8224","dagger"],["8225","double dagger"],["192","A - grave"],["193","A - acute"],["194","A - circumflex"],["195","A - tilde"],["196","A - diaeresis"],["197","A - ring above"],["198","ligature AE"],["199","C - cedilla"],["200","E - grave"],["201","E - acute"],["202","E - circumflex"],["203","E - diaeresis"],["204","I - grave"],["205","I - acute"],["206","I - circumflex"],["207","I - diaeresis"],["208","ETH"],["209","N - tilde"],["210","O - grave"],["211","O - acute"],["212","O - circumflex"],["213","O - tilde"],["214","O - diaeresis"],["216","O - slash"],["338","ligature OE"],["352","S - caron"],["217","U - grave"],["218","U - acute"],["219","U - circumflex"],["220","U - diaeresis"],["221","Y - acute"],["376","Y - diaeresis"],["222","THORN"],["224","a - grave"],["225","a - acute"],["226","a - circumflex"],["227","a - tilde"],["228","a - diaeresis"],["229","a - ring above"],["230","ligature ae"],["231","c - cedilla"],["232","e - grave"],["233","e - acute"],["234","e - circumflex"],["235","e - diaeresis"],["236","i - grave"],["237","i - acute"],["238","i - circumflex"],["239","i - diaeresis"],["240","eth"],["241","n - tilde"],["242","o - grave"],["243","o - acute"],["244","o - circumflex"],["245","o - tilde"],["246","o - diaeresis"],["248","o slash"],["339","ligature oe"],["353","s - caron"],["249","u - grave"],["250","u - acute"],["251","u - circumflex"],["252","u - diaeresis"],["253","y - acute"],["254","thorn"],["255","y - diaeresis"],["913","Alpha"],["914","Beta"],["915","Gamma"],["916","Delta"],["917","Epsilon"],["918","Zeta"],["919","Eta"],["920","Theta"],["921","Iota"],["922","Kappa"],["923","Lambda"],["924","Mu"],["925","Nu"],["926","Xi"],["927","Omicron"],["928","Pi"],["929","Rho"],["931","Sigma"],["932","Tau"],["933","Upsilon"],["934","Phi"],["935","Chi"],["936","Psi"],["937","Omega"],["945","alpha"],["946","beta"],["947","gamma"],["948","delta"],["949","epsilon"],["950","zeta"],["951","eta"],["952","theta"],["953","iota"],["954","kappa"],["955","lambda"],["956","mu"],["957","nu"],["958","xi"],["959","omicron"],["960","pi"],["961","rho"],["962","final sigma"],["963","sigma"],["964","tau"],["965","upsilon"],["966","phi"],["967","chi"],["968","psi"],["969","omega"],["8501","alef symbol"],["982","pi symbol"],["8476","real part symbol"],["978","upsilon - hook symbol"],["8472","Weierstrass p"],["8465","imaginary part"],["8592","leftwards arrow"],["8593","upwards arrow"],["8594","rightwards arrow"],["8595","downwards arrow"],["8596","left right arrow"],["8629","carriage return"],["8656","leftwards double arrow"],["8657","upwards double arrow"],["8658","rightwards double arrow"],["8659","downwards double arrow"],["8660","left right double arrow"],["8756","therefore"],["8834","subset of"],["8835","superset of"],["8836","not a subset of"],["8838","subset of or equal to"],["8839","superset of or equal to"],["8853","circled plus"],["8855","circled times"],["8869","perpendicular"],["8901","dot operator"],["8968","left ceiling"],["8969","right ceiling"],["8970","left floor"],["8971","right floor"],["9001","left-pointing angle bracket"],["9002","right-pointing angle bracket"],["9674","lozenge"],["9824","black spade suit"],["9827","black club suit"],["9829","black heart suit"],["9830","black diamond suit"],["8194","en space"],["8195","em space"],["8201","thin space"],["8204","zero width non-joiner"],["8205","zero width joiner"],["8206","left-to-right mark"],["8207","right-to-left mark"],["173","soft hyphen"]];e.addButton("charmap",{icon:"charmap",tooltip:"Special character",onclick:a}),e.addMenuItem("charmap",{icon:"charmap",text:"Special character",onclick:a,context:"insert"})});
\ No newline at end of file
+/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var e,n,r,t,a=tinymce.util.Tools.resolve("tinymce.PluginManager"),s=function(e,n){var r,t=(r=n,e.fire("insertCustomChar",{chr:r}).chr);e.execCommand("mceInsertContent",!1,t)},i=function(e){return function(){return e}},o=i(!1),c=i(!0),u=function(){return l},l=(e=function(e){return e.isNone()},{fold:function(e,n){return e()},is:o,isSome:o,isNone:c,getOr:r=function(e){return e},getOrThunk:n=function(e){return e()},getOrDie:function(e){throw new Error(e||"error: getOrDie called on none.")},getOrNull:i(null),getOrUndefined:i(undefined),or:r,orThunk:n,map:u,each:function(){},bind:u,exists:o,forall:c,filter:u,equals:e,equals_:e,toArray:function(){return[]},toString:i("none()")}),g=function(r){var e=i(r),n=function(){return a},t=function(e){return e(r)},a={fold:function(e,n){return n(r)},is:function(e){return r===e},isSome:c,isNone:o,getOr:e,getOrThunk:e,getOrDie:e,getOrNull:e,getOrUndefined:e,or:n,orThunk:n,map:function(e){return g(e(r))},each:function(e){e(r)},bind:t,exists:t,forall:t,filter:function(e){return e(r)?a:l},toArray:function(){return[r]},toString:function(){return"some("+r+")"},equals:function(e){return e.is(r)},equals_:function(e,n){return e.fold(o,function(e){return n(r,e)})}};return a},m={some:g,none:u,from:function(e){return null===e||e===undefined?l:g(e)}},f=(t="array",function(e){return r=typeof(n=e),(null===n?"null":"object"==r&&(Array.prototype.isPrototypeOf(n)||n.constructor&&"Array"===n.constructor.name)?"array":"object"==r&&(String.prototype.isPrototypeOf(n)||n.constructor&&"String"===n.constructor.name)?"string":r)===t;var n,r}),h=Array.prototype.push,p=function(e,n){for(var r=e.length,t=new Array(r),a=0;a",r=0;r "}i+="' + code + '
');
+ editor.selection.select(editor.$('#__new').removeAttr('id')[0]);
+ }, function (n) {
+ editor.dom.setAttrib(n, 'class', 'language-' + language);
+ n.innerHTML = code;
+ get(editor).highlightElement(n);
+ editor.selection.select(n);
+ });
+ });
+ };
+ var getCurrentCode = function (editor) {
+ var node = getSelectedCodeSample(editor);
+ return node.fold(function () {
+ return '';
+ }, function (n) {
+ return n.textContent;
+ });
+ };
+
+ var getLanguages$1 = function (editor) {
+ var defaultLanguages = [
+ {
+ text: 'HTML/XML',
+ value: 'markup'
+ },
+ {
+ text: 'JavaScript',
+ value: 'javascript'
+ },
+ {
+ text: 'CSS',
+ value: 'css'
+ },
+ {
+ text: 'PHP',
+ value: 'php'
+ },
+ {
+ text: 'Ruby',
+ value: 'ruby'
+ },
+ {
+ text: 'Python',
+ value: 'python'
+ },
+ {
+ text: 'Java',
+ value: 'java'
+ },
+ {
+ text: 'C',
+ value: 'c'
+ },
+ {
+ text: 'C#',
+ value: 'csharp'
+ },
+ {
+ text: 'C++',
+ value: 'cpp'
+ }
+ ];
+ var customLanguages = getLanguages(editor);
+ return customLanguages ? customLanguages : defaultLanguages;
+ };
+ var getCurrentLanguage = function (editor, fallback) {
+ var node = getSelectedCodeSample(editor);
+ return node.fold(function () {
+ return fallback;
+ }, function (n) {
+ var matches = n.className.match(/language-(\w+)/);
+ return matches ? matches[1] : fallback;
+ });
+ };
+
+ var open = function (editor) {
+ var languages = getLanguages$1(editor);
+ var defaultLanguage = head(languages).fold(function () {
+ return '';
+ }, function (l) {
+ return l.value;
+ });
+ var currentLanguage = getCurrentLanguage(editor, defaultLanguage);
+ var currentCode = getCurrentCode(editor);
+ editor.windowManager.open({
+ title: 'Insert/Edit Code Sample',
+ size: 'large',
+ body: {
+ type: 'panel',
+ items: [
+ {
+ type: 'selectbox',
+ name: 'language',
+ label: 'Language',
+ items: languages
+ },
+ {
+ type: 'textarea',
+ name: 'code',
+ label: 'Code view'
+ }
+ ]
+ },
+ buttons: [
+ {
+ type: 'cancel',
+ name: 'cancel',
+ text: 'Cancel'
+ },
+ {
+ type: 'submit',
+ name: 'save',
+ text: 'Save',
+ primary: true
+ }
+ ],
+ initialData: {
+ language: currentLanguage,
+ code: currentCode
+ },
+ onSubmit: function (api) {
+ var data = api.getData();
+ insertCodeSample(editor, data.language, data.code);
+ api.close();
+ }
+ });
+ };
+
+ var register = function (editor) {
+ editor.addCommand('codesample', function () {
+ var node = editor.selection.getNode();
+ if (editor.selection.isCollapsed() || isCodeSample(node)) {
+ open(editor);
+ } else {
+ editor.formatter.toggle('code');
+ }
+ });
+ };
+
+ var setup = function (editor) {
+ var $ = editor.$;
+ editor.on('PreProcess', function (e) {
+ $('pre[contenteditable=false]', e.node).filter(trimArg(isCodeSample)).each(function (idx, elm) {
+ var $elm = $(elm), code = elm.textContent;
+ $elm.attr('class', $.trim($elm.attr('class')));
+ $elm.removeAttr('contentEditable');
+ $elm.empty().append($('').each(function () {
+ this.textContent = code;
+ }));
+ });
+ });
+ editor.on('SetContent', function () {
+ var unprocessedCodeSamples = $('pre').filter(trimArg(isCodeSample)).filter(function (idx, elm) {
+ return elm.contentEditable !== 'false';
+ });
+ if (unprocessedCodeSamples.length) {
+ editor.undoManager.transact(function () {
+ unprocessedCodeSamples.each(function (idx, elm) {
+ $(elm).find('br').each(function (idx, elm) {
+ elm.parentNode.replaceChild(editor.getDoc().createTextNode('\n'), elm);
+ });
+ elm.contentEditable = 'false';
+ elm.innerHTML = editor.dom.encode(elm.textContent);
+ get(editor).highlightElement(elm);
+ elm.className = $.trim(elm.className);
+ });
+ });
+ }
+ });
+ };
+
+ var isCodeSampleSelection = function (editor) {
+ var node = editor.selection.getStart();
+ return editor.dom.is(node, 'pre[class*="language-"]');
+ };
+ var register$1 = function (editor) {
+ editor.ui.registry.addToggleButton('codesample', {
+ icon: 'code-sample',
+ tooltip: 'Insert/edit code sample',
+ onAction: function () {
+ return open(editor);
+ },
+ onSetup: function (api) {
+ var nodeChangeHandler = function () {
+ api.setActive(isCodeSampleSelection(editor));
+ };
+ editor.on('NodeChange', nodeChangeHandler);
+ return function () {
+ return editor.off('NodeChange', nodeChangeHandler);
+ };
+ }
+ });
+ editor.ui.registry.addMenuItem('codesample', {
+ text: 'Code sample...',
+ icon: 'code-sample',
+ onAction: function () {
+ return open(editor);
+ }
+ });
+ };
+
+ function Plugin () {
+ global.add('codesample', function (editor) {
+ setup(editor);
+ register$1(editor);
+ register(editor);
+ editor.on('dblclick', function (ev) {
+ if (isCodeSample(ev.target)) {
+ open(editor);
+ }
+ });
+ });
+ }
+
+ Plugin();
+
+}());
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codesample/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codesample/plugin.min.js
new file mode 100644
index 0000000000..e094d08e6b
--- /dev/null
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codesample/plugin.min.js
@@ -0,0 +1,9 @@
+/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var e,n,t,a=tinymce.util.Tools.resolve("tinymce.PluginManager"),i=function(e){return function(){return e}},s=i(!1),o=i(!0),r=function(){return l},l=(e=function(e){return e.isNone()},{fold:function(e,n){return e()},is:s,isSome:s,isNone:o,getOr:t=function(e){return e},getOrThunk:n=function(e){return e()},getOrDie:function(e){throw new Error(e||"error: getOrDie called on none.")},getOrNull:i(null),getOrUndefined:i(undefined),or:t,orThunk:n,map:r,each:function(){},bind:r,exists:s,forall:o,filter:r,equals:e,equals_:e,toArray:function(){return[]},toString:i("none()")}),u=function(t){var e=i(t),n=function(){return r},a=function(e){return e(t)},r={fold:function(e,n){return n(t)},is:function(e){return t===e},isSome:o,isNone:s,getOr:e,getOrThunk:e,getOrDie:e,getOrNull:e,getOrUndefined:e,or:n,orThunk:n,map:function(e){return u(e(t))},each:function(e){e(t)},bind:a,exists:a,forall:a,filter:function(e){return e(t)?r:l},toArray:function(){return[t]},toString:function(){return"some("+t+")"},equals:function(e){return e.is(t)},equals_:function(e,n){return e.fold(s,function(e){return n(t,e)})}};return r},c={some:u,none:r,from:function(e){return null===e||e===undefined?l:u(e)}},d=tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");function p(e){return e&&"PRE"===e.nodeName&&-1!==e.className.indexOf("language-")}function g(t){return function(e,n){return t(n)}}var m="undefined"!=typeof window?window:Function("return this;")(),f={},h={exports:f},b={};!function(n,t,a,d){var e=window.Prism;window.Prism={manual:!0},function(e){"object"==typeof t&&void 0!==a?a.exports=e():"function"==typeof n&&n.amd?n([],e):("undefined"!=typeof window?window:void 0!==b?b:"undefined"!=typeof self?self:this).EphoxContactWrapper=e()}(function(){return function c(i,s,o){function l(n,e){if(!s[n]){if(!i[n]){var t="function"==typeof d&&d;if(!e&&t)return t(n,!0);if(u)return u(n,!0);var a=new Error("Cannot find module '"+n+"'");throw a.code="MODULE_NOT_FOUND",a}var r=s[n]={exports:{}};i[n][0].call(r.exports,function(e){return l(i[n][1][e]||e)},r,r.exports,c,i,s,o)}return s[n].exports}for(var u="function"==typeof d&&d,e=0;e'+a+"
"),n.selection.select(n.$("#__new").removeAttr("id")[0])},function(e){n.dom.setAttrib(e,"class","language-"+t),e.innerHTML=a,w(n).highlightElement(e),n.selection.select(e)})}),e.close()}})},x=function(a){a.ui.registry.addToggleButton("codesample",{icon:"code-sample",tooltip:"Insert/edit code sample",onAction:function(){return k(a)},onSetup:function(t){var e=function(){var e,n;t.setActive((n=(e=a).selection.getStart(),e.dom.is(n,'pre[class*="language-"]')))};return a.on("NodeChange",e),function(){return a.off("NodeChange",e)}}}),a.ui.registry.addMenuItem("codesample",{text:"Code sample...",icon:"code-sample",onAction:function(){return k(a)}})};a.add("codesample",function(n){var t,r,a;r=(t=n).$,t.on("PreProcess",function(e){r("pre[contenteditable=false]",e.node).filter(g(p)).each(function(e,n){var t=r(n),a=n.textContent;t.attr("class",r.trim(t.attr("class"))),t.removeAttr("contentEditable"),t.empty().append(r("").each(function(){this.textContent=a}))})}),t.on("SetContent",function(){var e=r("pre").filter(g(p)).filter(function(e,n){return"false"!==n.contentEditable});e.length&&t.undoManager.transact(function(){e.each(function(e,n){r(n).find("br").each(function(e,n){n.parentNode.replaceChild(t.getDoc().createTextNode("\n"),n)}),n.contentEditable="false",n.innerHTML=t.dom.encode(n.textContent),w(t).highlightElement(n),n.className=r.trim(n.className)})})}),x(n),(a=n).addCommand("codesample",function(){var e=a.selection.getNode();a.selection.isCollapsed()||p(e)?k(a):a.formatter.toggle("code")}),n.on("dblclick",function(e){p(e.target)&&k(n)})})}();
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/colorpicker/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/colorpicker/plugin.js
new file mode 100644
index 0000000000..2d0623aacb
--- /dev/null
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/colorpicker/plugin.js
@@ -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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+(function () {
+ 'use strict';
+
+ var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
+
+ function Plugin () {
+ global.add('colorpicker', function () {
+ console.warn('Color picker plugin is now built in to the core editor, please remove it from your editor configuration');
+ });
+ }
+
+ Plugin();
+
+}());
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/colorpicker/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/colorpicker/plugin.min.js
new file mode 100644
index 0000000000..ccdf6629cb
--- /dev/null
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/colorpicker/plugin.min.js
@@ -0,0 +1,9 @@
+/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";tinymce.util.Tools.resolve("tinymce.PluginManager").add("colorpicker",function(){console.warn("Color picker plugin is now built in to the core editor, please remove it from your editor configuration")})}();
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.js
index ada25f77b7..0a7ef19bce 100644
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.js
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.js
@@ -1,77 +1,22 @@
/**
- * plugin.js
+ * 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/
*
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
+ * Version: 5.5.1 (2020-10-01)
*/
+(function () {
+ 'use strict';
-/*global tinymce:true */
+ var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
-tinymce.PluginManager.add('contextmenu', function(editor) {
- var menu, contextmenuNeverUseNative = editor.settings.contextmenu_never_use_native;
+ function Plugin () {
+ global.add('contextmenu', function () {
+ console.warn('Context menu plugin is now built in to the core editor, please remove it from your editor configuration');
+ });
+ }
- editor.on('contextmenu', function(e) {
- var contextmenu;
+ Plugin();
- // Block TinyMCE menu on ctrlKey
- if (e.ctrlKey && !contextmenuNeverUseNative) {
- return;
- }
-
- e.preventDefault();
-
- contextmenu = editor.settings.contextmenu || 'link image inserttable | cell row column deletetable';
-
- // Render menu
- if (!menu) {
- var items = [];
-
- tinymce.each(contextmenu.split(/[ ,]/), function(name) {
- var item = editor.menuItems[name];
-
- if (name == '|') {
- item = {text: name};
- }
-
- if (item) {
- item.shortcut = ''; // Hide shortcuts
- items.push(item);
- }
- });
-
- for (var i = 0; i < items.length; i++) {
- if (items[i].text == '|') {
- if (i === 0 || i == items.length - 1) {
- items.splice(i, 1);
- }
- }
- }
-
- menu = new tinymce.ui.Menu({
- items: items,
- context: 'contextmenu'
- }).addClass('contextmenu').renderTo();
-
- editor.on('remove', function() {
- menu.remove();
- menu = null;
- });
- } else {
- menu.show();
- }
-
- // Position menu
- var pos = {x: e.pageX, y: e.pageY};
-
- if (!editor.inline) {
- pos = tinymce.DOM.getPos(editor.getContentAreaContainer());
- pos.x += e.clientX;
- pos.y += e.clientY;
- }
-
- menu.moveTo(pos.x, pos.y);
- });
-});
\ No newline at end of file
+}());
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.min.js
index 06f0d4bd5d..9ecd56617a 100644
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.min.js
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.min.js
@@ -1 +1,9 @@
-tinymce.PluginManager.add("contextmenu",function(e){var n,t=e.settings.contextmenu_never_use_native;e.on("contextmenu",function(i){var o;if(!i.ctrlKey||t){if(i.preventDefault(),o=e.settings.contextmenu||"link image inserttable | cell row column deletetable",n)n.show();else{var c=[];tinymce.each(o.split(/[ ,]/),function(n){var t=e.menuItems[n];"|"==n&&(t={text:n}),t&&(t.shortcut="",c.push(t))});for(var a=0;aEditor UI keyboard navigation
\n\nActivating keyboard navigation
\n\n\n
\n\nMoving between UI sections
\n\n\n
\n\nMoving within UI sections
\n\n\n
\n\nExecuting buttons
\n\nOpening, navigating and closing menus
\n\nContext toolbars and menus
\n\nDialog navigation
\n\n' + premiumPluginList + '
' + '' + pluginsString + '
';
+ return html;
+ };
+ var installedPlugins = function (editor) {
+ if (editor == null) {
+ return '';
+ }
+ return '"+s+"
"}(n)+"Editor UI keyboard navigation
\n\nActivating keyboard navigation
\n\n\n
\n\nMoving between UI sections
\n\n\n
\n\nMoving within UI sections
\n\n\n
\n\nExecuting buttons
\n\nOpening, navigating and closing menus
\n\nContext toolbars and menus
\n\nDialog navigation
\n\n
")}),(t=n).ui.registry.addButton("hr",{icon:"horizontal-rule",tooltip:"Horizontal line",onAction:function(){return t.execCommand("InsertHorizontalRule")}}),t.ui.registry.addMenuItem("hr",{icon:"horizontal-rule",text:"Horizontal line",onAction:function(){return t.execCommand("InsertHorizontalRule")}})})}();
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.js
new file mode 100644
index 0000000000..83c519ae07
--- /dev/null
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.js
@@ -0,0 +1,1651 @@
+/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+(function () {
+ 'use strict';
+
+ var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
+
+ var __assign = function () {
+ __assign = Object.assign || function __assign(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s)
+ if (Object.prototype.hasOwnProperty.call(s, p))
+ t[p] = s[p];
+ }
+ return t;
+ };
+ return __assign.apply(this, arguments);
+ };
+
+ var typeOf = function (x) {
+ var t = typeof x;
+ if (x === null) {
+ return 'null';
+ } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
+ return 'array';
+ } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
+ return 'string';
+ } else {
+ return t;
+ }
+ };
+ var isType = function (type) {
+ return function (value) {
+ return typeOf(value) === type;
+ };
+ };
+ var isSimpleType = function (type) {
+ return function (value) {
+ return typeof value === type;
+ };
+ };
+ var eq = function (t) {
+ return function (a) {
+ return t === a;
+ };
+ };
+ var isString = isType('string');
+ var isObject = isType('object');
+ var isArray = isType('array');
+ var isNull = eq(null);
+ var isBoolean = isSimpleType('boolean');
+ var isNumber = isSimpleType('number');
+
+ var noop = function () {
+ };
+ var constant = function (value) {
+ return function () {
+ return value;
+ };
+ };
+ var never = constant(false);
+ var always = constant(true);
+
+ var none = function () {
+ return NONE;
+ };
+ var NONE = function () {
+ var eq = function (o) {
+ return o.isNone();
+ };
+ var call = function (thunk) {
+ return thunk();
+ };
+ var id = function (n) {
+ return n;
+ };
+ var me = {
+ fold: function (n, _s) {
+ return n();
+ },
+ is: never,
+ isSome: never,
+ isNone: always,
+ getOr: id,
+ getOrThunk: call,
+ getOrDie: function (msg) {
+ throw new Error(msg || 'error: getOrDie called on none.');
+ },
+ getOrNull: constant(null),
+ getOrUndefined: constant(undefined),
+ or: id,
+ orThunk: call,
+ map: none,
+ each: noop,
+ bind: none,
+ exists: never,
+ forall: always,
+ filter: none,
+ equals: eq,
+ equals_: eq,
+ toArray: function () {
+ return [];
+ },
+ toString: constant('none()')
+ };
+ return me;
+ }();
+ var some = function (a) {
+ var constant_a = constant(a);
+ var self = function () {
+ return me;
+ };
+ var bind = function (f) {
+ return f(a);
+ };
+ var me = {
+ fold: function (n, s) {
+ return s(a);
+ },
+ is: function (v) {
+ return a === v;
+ },
+ isSome: always,
+ isNone: never,
+ getOr: constant_a,
+ getOrThunk: constant_a,
+ getOrDie: constant_a,
+ getOrNull: constant_a,
+ getOrUndefined: constant_a,
+ or: self,
+ orThunk: self,
+ map: function (f) {
+ return some(f(a));
+ },
+ each: function (f) {
+ f(a);
+ },
+ bind: bind,
+ exists: bind,
+ forall: bind,
+ filter: function (f) {
+ return f(a) ? me : NONE;
+ },
+ toArray: function () {
+ return [a];
+ },
+ toString: function () {
+ return 'some(' + a + ')';
+ },
+ equals: function (o) {
+ return o.is(a);
+ },
+ equals_: function (o, elementEq) {
+ return o.fold(never, function (b) {
+ return elementEq(a, b);
+ });
+ }
+ };
+ return me;
+ };
+ var from = function (value) {
+ return value === null || value === undefined ? NONE : some(value);
+ };
+ var Optional = {
+ some: some,
+ none: none,
+ from: from
+ };
+
+ var nativePush = Array.prototype.push;
+ var flatten = function (xs) {
+ var r = [];
+ for (var i = 0, len = xs.length; i < len; ++i) {
+ if (!isArray(xs[i])) {
+ throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
+ }
+ nativePush.apply(r, xs[i]);
+ }
+ return r;
+ };
+ var head = function (xs) {
+ return xs.length === 0 ? Optional.none() : Optional.some(xs[0]);
+ };
+ var findMap = function (arr, f) {
+ for (var i = 0; i < arr.length; i++) {
+ var r = f(arr[i], i);
+ if (r.isSome()) {
+ return r;
+ }
+ }
+ return Optional.none();
+ };
+
+ var Global = typeof window !== 'undefined' ? window : Function('return this;')();
+
+ var rawSet = function (dom, key, value) {
+ if (isString(value) || isBoolean(value) || isNumber(value)) {
+ dom.setAttribute(key, value + '');
+ } else {
+ console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
+ throw new Error('Attribute value was not simple');
+ }
+ };
+ var set = function (element, key, value) {
+ rawSet(element.dom, key, value);
+ };
+ var remove = function (element, key) {
+ element.dom.removeAttribute(key);
+ };
+
+ var fromHtml = function (html, scope) {
+ var doc = scope || document;
+ var div = doc.createElement('div');
+ div.innerHTML = html;
+ if (!div.hasChildNodes() || div.childNodes.length > 1) {
+ console.error('HTML does not have a single root node', html);
+ throw new Error('HTML must have a single root node');
+ }
+ return fromDom(div.childNodes[0]);
+ };
+ var fromTag = function (tag, scope) {
+ var doc = scope || document;
+ var node = doc.createElement(tag);
+ return fromDom(node);
+ };
+ var fromText = function (text, scope) {
+ var doc = scope || document;
+ var node = doc.createTextNode(text);
+ return fromDom(node);
+ };
+ var fromDom = function (node) {
+ if (node === null || node === undefined) {
+ throw new Error('Node cannot be null or undefined');
+ }
+ return { dom: node };
+ };
+ var fromPoint = function (docElm, x, y) {
+ return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
+ };
+ var SugarElement = {
+ fromHtml: fromHtml,
+ fromTag: fromTag,
+ fromText: fromText,
+ fromDom: fromDom,
+ fromPoint: fromPoint
+ };
+
+ var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
+
+ var global$2 = tinymce.util.Tools.resolve('tinymce.util.Promise');
+
+ var global$3 = tinymce.util.Tools.resolve('tinymce.util.XHR');
+
+ var hasDimensions = function (editor) {
+ return editor.getParam('image_dimensions', true, 'boolean');
+ };
+ var hasAdvTab = function (editor) {
+ return editor.getParam('image_advtab', false, 'boolean');
+ };
+ var hasUploadTab = function (editor) {
+ return editor.getParam('image_uploadtab', true, 'boolean');
+ };
+ var getPrependUrl = function (editor) {
+ return editor.getParam('image_prepend_url', '', 'string');
+ };
+ var getClassList = function (editor) {
+ return editor.getParam('image_class_list');
+ };
+ var hasDescription = function (editor) {
+ return editor.getParam('image_description', true, 'boolean');
+ };
+ var hasImageTitle = function (editor) {
+ return editor.getParam('image_title', false, 'boolean');
+ };
+ var hasImageCaption = function (editor) {
+ return editor.getParam('image_caption', false, 'boolean');
+ };
+ var getImageList = function (editor) {
+ return editor.getParam('image_list', false);
+ };
+ var hasUploadUrl = function (editor) {
+ return !!getUploadUrl(editor);
+ };
+ var hasUploadHandler = function (editor) {
+ return !!getUploadHandler(editor);
+ };
+ var getUploadUrl = function (editor) {
+ return editor.getParam('images_upload_url', '', 'string');
+ };
+ var getUploadHandler = function (editor) {
+ return editor.getParam('images_upload_handler', undefined, 'function');
+ };
+ var getUploadBasePath = function (editor) {
+ return editor.getParam('images_upload_base_path', undefined, 'string');
+ };
+ var getUploadCredentials = function (editor) {
+ return editor.getParam('images_upload_credentials', false, 'boolean');
+ };
+ var showAccessibilityOptions = function (editor) {
+ return editor.getParam('a11y_advanced_options', false, 'boolean');
+ };
+ var isAutomaticUploadsEnabled = function (editor) {
+ return editor.getParam('automatic_uploads', true, 'boolean');
+ };
+
+ var parseIntAndGetMax = function (val1, val2) {
+ return Math.max(parseInt(val1, 10), parseInt(val2, 10));
+ };
+ var getImageSize = function (url) {
+ return new global$2(function (callback) {
+ var img = document.createElement('img');
+ var done = function (dimensions) {
+ if (img.parentNode) {
+ img.parentNode.removeChild(img);
+ }
+ callback(dimensions);
+ };
+ img.onload = function () {
+ var width = parseIntAndGetMax(img.width, img.clientWidth);
+ var height = parseIntAndGetMax(img.height, img.clientHeight);
+ var dimensions = {
+ width: width,
+ height: height
+ };
+ done(global$2.resolve(dimensions));
+ };
+ img.onerror = function () {
+ done(global$2.reject('Failed to get image dimensions for: ' + url));
+ };
+ var style = img.style;
+ style.visibility = 'hidden';
+ style.position = 'fixed';
+ style.bottom = style.left = '0px';
+ style.width = style.height = 'auto';
+ document.body.appendChild(img);
+ img.src = url;
+ });
+ };
+ var removePixelSuffix = function (value) {
+ if (value) {
+ value = value.replace(/px$/, '');
+ }
+ return value;
+ };
+ var addPixelSuffix = function (value) {
+ if (value.length > 0 && /^[0-9]+$/.test(value)) {
+ value += 'px';
+ }
+ return value;
+ };
+ var mergeMargins = function (css) {
+ if (css.margin) {
+ var splitMargin = String(css.margin).split(' ');
+ switch (splitMargin.length) {
+ case 1:
+ css['margin-top'] = css['margin-top'] || splitMargin[0];
+ css['margin-right'] = css['margin-right'] || splitMargin[0];
+ css['margin-bottom'] = css['margin-bottom'] || splitMargin[0];
+ css['margin-left'] = css['margin-left'] || splitMargin[0];
+ break;
+ case 2:
+ css['margin-top'] = css['margin-top'] || splitMargin[0];
+ css['margin-right'] = css['margin-right'] || splitMargin[1];
+ css['margin-bottom'] = css['margin-bottom'] || splitMargin[0];
+ css['margin-left'] = css['margin-left'] || splitMargin[1];
+ break;
+ case 3:
+ css['margin-top'] = css['margin-top'] || splitMargin[0];
+ css['margin-right'] = css['margin-right'] || splitMargin[1];
+ css['margin-bottom'] = css['margin-bottom'] || splitMargin[2];
+ css['margin-left'] = css['margin-left'] || splitMargin[1];
+ break;
+ case 4:
+ css['margin-top'] = css['margin-top'] || splitMargin[0];
+ css['margin-right'] = css['margin-right'] || splitMargin[1];
+ css['margin-bottom'] = css['margin-bottom'] || splitMargin[2];
+ css['margin-left'] = css['margin-left'] || splitMargin[3];
+ }
+ delete css.margin;
+ }
+ return css;
+ };
+ var createImageList = function (editor, callback) {
+ var imageList = getImageList(editor);
+ if (typeof imageList === 'string') {
+ global$3.send({
+ url: imageList,
+ success: function (text) {
+ callback(JSON.parse(text));
+ }
+ });
+ } else if (typeof imageList === 'function') {
+ imageList(callback);
+ } else {
+ callback(imageList);
+ }
+ };
+ var waitLoadImage = function (editor, data, imgElm) {
+ var selectImage = function () {
+ imgElm.onload = imgElm.onerror = null;
+ if (editor.selection) {
+ editor.selection.select(imgElm);
+ editor.nodeChanged();
+ }
+ };
+ imgElm.onload = function () {
+ if (!data.width && !data.height && hasDimensions(editor)) {
+ editor.dom.setAttribs(imgElm, {
+ width: String(imgElm.clientWidth),
+ height: String(imgElm.clientHeight)
+ });
+ }
+ selectImage();
+ };
+ imgElm.onerror = selectImage;
+ };
+ var blobToDataUri = function (blob) {
+ return new global$2(function (resolve, reject) {
+ var reader = new FileReader();
+ reader.onload = function () {
+ resolve(reader.result);
+ };
+ reader.onerror = function () {
+ reject(reader.error.message);
+ };
+ reader.readAsDataURL(blob);
+ });
+ };
+ var isPlaceholderImage = function (imgElm) {
+ return imgElm.nodeName === 'IMG' && (imgElm.hasAttribute('data-mce-object') || imgElm.hasAttribute('data-mce-placeholder'));
+ };
+
+ var DOM = global$1.DOM;
+ var getHspace = function (image) {
+ if (image.style.marginLeft && image.style.marginRight && image.style.marginLeft === image.style.marginRight) {
+ return removePixelSuffix(image.style.marginLeft);
+ } else {
+ return '';
+ }
+ };
+ var getVspace = function (image) {
+ if (image.style.marginTop && image.style.marginBottom && image.style.marginTop === image.style.marginBottom) {
+ return removePixelSuffix(image.style.marginTop);
+ } else {
+ return '';
+ }
+ };
+ var getBorder = function (image) {
+ if (image.style.borderWidth) {
+ return removePixelSuffix(image.style.borderWidth);
+ } else {
+ return '';
+ }
+ };
+ var getAttrib = function (image, name) {
+ if (image.hasAttribute(name)) {
+ return image.getAttribute(name);
+ } else {
+ return '';
+ }
+ };
+ var getStyle = function (image, name) {
+ return image.style[name] ? image.style[name] : '';
+ };
+ var hasCaption = function (image) {
+ return image.parentNode !== null && image.parentNode.nodeName === 'FIGURE';
+ };
+ var updateAttrib = function (image, name, value) {
+ if (value === '') {
+ image.removeAttribute(name);
+ } else {
+ image.setAttribute(name, value);
+ }
+ };
+ var wrapInFigure = function (image) {
+ var figureElm = DOM.create('figure', { class: 'image' });
+ DOM.insertAfter(figureElm, image);
+ figureElm.appendChild(image);
+ figureElm.appendChild(DOM.create('figcaption', { contentEditable: 'true' }, 'Caption'));
+ figureElm.contentEditable = 'false';
+ };
+ var removeFigure = function (image) {
+ var figureElm = image.parentNode;
+ DOM.insertAfter(image, figureElm);
+ DOM.remove(figureElm);
+ };
+ var toggleCaption = function (image) {
+ if (hasCaption(image)) {
+ removeFigure(image);
+ } else {
+ wrapInFigure(image);
+ }
+ };
+ var normalizeStyle = function (image, normalizeCss) {
+ var attrValue = image.getAttribute('style');
+ var value = normalizeCss(attrValue !== null ? attrValue : '');
+ if (value.length > 0) {
+ image.setAttribute('style', value);
+ image.setAttribute('data-mce-style', value);
+ } else {
+ image.removeAttribute('style');
+ }
+ };
+ var setSize = function (name, normalizeCss) {
+ return function (image, name, value) {
+ if (image.style[name]) {
+ image.style[name] = addPixelSuffix(value);
+ normalizeStyle(image, normalizeCss);
+ } else {
+ updateAttrib(image, name, value);
+ }
+ };
+ };
+ var getSize = function (image, name) {
+ if (image.style[name]) {
+ return removePixelSuffix(image.style[name]);
+ } else {
+ return getAttrib(image, name);
+ }
+ };
+ var setHspace = function (image, value) {
+ var pxValue = addPixelSuffix(value);
+ image.style.marginLeft = pxValue;
+ image.style.marginRight = pxValue;
+ };
+ var setVspace = function (image, value) {
+ var pxValue = addPixelSuffix(value);
+ image.style.marginTop = pxValue;
+ image.style.marginBottom = pxValue;
+ };
+ var setBorder = function (image, value) {
+ var pxValue = addPixelSuffix(value);
+ image.style.borderWidth = pxValue;
+ };
+ var setBorderStyle = function (image, value) {
+ image.style.borderStyle = value;
+ };
+ var getBorderStyle = function (image) {
+ return getStyle(image, 'borderStyle');
+ };
+ var isFigure = function (elm) {
+ return elm.nodeName === 'FIGURE';
+ };
+ var isImage = function (elm) {
+ return elm.nodeName === 'IMG';
+ };
+ var getIsDecorative = function (image) {
+ return DOM.getAttrib(image, 'alt').length === 0 && DOM.getAttrib(image, 'role') === 'presentation';
+ };
+ var getAlt = function (image) {
+ if (getIsDecorative(image)) {
+ return '';
+ } else {
+ return getAttrib(image, 'alt');
+ }
+ };
+ var defaultData = function () {
+ return {
+ src: '',
+ alt: '',
+ title: '',
+ width: '',
+ height: '',
+ class: '',
+ style: '',
+ caption: false,
+ hspace: '',
+ vspace: '',
+ border: '',
+ borderStyle: '',
+ isDecorative: false
+ };
+ };
+ var getStyleValue = function (normalizeCss, data) {
+ var image = document.createElement('img');
+ updateAttrib(image, 'style', data.style);
+ if (getHspace(image) || data.hspace !== '') {
+ setHspace(image, data.hspace);
+ }
+ if (getVspace(image) || data.vspace !== '') {
+ setVspace(image, data.vspace);
+ }
+ if (getBorder(image) || data.border !== '') {
+ setBorder(image, data.border);
+ }
+ if (getBorderStyle(image) || data.borderStyle !== '') {
+ setBorderStyle(image, data.borderStyle);
+ }
+ return normalizeCss(image.getAttribute('style'));
+ };
+ var create = function (normalizeCss, data) {
+ var image = document.createElement('img');
+ write(normalizeCss, __assign(__assign({}, data), { caption: false }), image);
+ setAlt(image, data.alt, data.isDecorative);
+ if (data.caption) {
+ var figure = DOM.create('figure', { class: 'image' });
+ figure.appendChild(image);
+ figure.appendChild(DOM.create('figcaption', { contentEditable: 'true' }, 'Caption'));
+ figure.contentEditable = 'false';
+ return figure;
+ } else {
+ return image;
+ }
+ };
+ var read = function (normalizeCss, image) {
+ return {
+ src: getAttrib(image, 'src'),
+ alt: getAlt(image),
+ title: getAttrib(image, 'title'),
+ width: getSize(image, 'width'),
+ height: getSize(image, 'height'),
+ class: getAttrib(image, 'class'),
+ style: normalizeCss(getAttrib(image, 'style')),
+ caption: hasCaption(image),
+ hspace: getHspace(image),
+ vspace: getVspace(image),
+ border: getBorder(image),
+ borderStyle: getStyle(image, 'borderStyle'),
+ isDecorative: getIsDecorative(image)
+ };
+ };
+ var updateProp = function (image, oldData, newData, name, set) {
+ if (newData[name] !== oldData[name]) {
+ set(image, name, newData[name]);
+ }
+ };
+ var setAlt = function (image, alt, isDecorative) {
+ if (isDecorative) {
+ DOM.setAttrib(image, 'role', 'presentation');
+ var sugarImage = SugarElement.fromDom(image);
+ set(sugarImage, 'alt', '');
+ } else {
+ if (isNull(alt)) {
+ var sugarImage = SugarElement.fromDom(image);
+ remove(sugarImage, 'alt');
+ } else {
+ var sugarImage = SugarElement.fromDom(image);
+ set(sugarImage, 'alt', alt);
+ }
+ if (DOM.getAttrib(image, 'role') === 'presentation') {
+ DOM.setAttrib(image, 'role', '');
+ }
+ }
+ };
+ var updateAlt = function (image, oldData, newData) {
+ if (newData.alt !== oldData.alt || newData.isDecorative !== oldData.isDecorative) {
+ setAlt(image, newData.alt, newData.isDecorative);
+ }
+ };
+ var normalized = function (set, normalizeCss) {
+ return function (image, name, value) {
+ set(image, value);
+ normalizeStyle(image, normalizeCss);
+ };
+ };
+ var write = function (normalizeCss, newData, image) {
+ var oldData = read(normalizeCss, image);
+ updateProp(image, oldData, newData, 'caption', function (image, _name, _value) {
+ return toggleCaption(image);
+ });
+ updateProp(image, oldData, newData, 'src', updateAttrib);
+ updateProp(image, oldData, newData, 'title', updateAttrib);
+ updateProp(image, oldData, newData, 'width', setSize('width', normalizeCss));
+ updateProp(image, oldData, newData, 'height', setSize('height', normalizeCss));
+ updateProp(image, oldData, newData, 'class', updateAttrib);
+ updateProp(image, oldData, newData, 'style', normalized(function (image, value) {
+ return updateAttrib(image, 'style', value);
+ }, normalizeCss));
+ updateProp(image, oldData, newData, 'hspace', normalized(setHspace, normalizeCss));
+ updateProp(image, oldData, newData, 'vspace', normalized(setVspace, normalizeCss));
+ updateProp(image, oldData, newData, 'border', normalized(setBorder, normalizeCss));
+ updateProp(image, oldData, newData, 'borderStyle', normalized(setBorderStyle, normalizeCss));
+ updateAlt(image, oldData, newData);
+ };
+
+ var normalizeCss = function (editor, cssText) {
+ var css = editor.dom.styles.parse(cssText);
+ var mergedCss = mergeMargins(css);
+ var compressed = editor.dom.styles.parse(editor.dom.styles.serialize(mergedCss));
+ return editor.dom.styles.serialize(compressed);
+ };
+ var getSelectedImage = function (editor) {
+ var imgElm = editor.selection.getNode();
+ var figureElm = editor.dom.getParent(imgElm, 'figure.image');
+ if (figureElm) {
+ return editor.dom.select('img', figureElm)[0];
+ }
+ if (imgElm && (imgElm.nodeName !== 'IMG' || isPlaceholderImage(imgElm))) {
+ return null;
+ }
+ return imgElm;
+ };
+ var splitTextBlock = function (editor, figure) {
+ var dom = editor.dom;
+ var textBlock = dom.getParent(figure.parentNode, function (node) {
+ return !!editor.schema.getTextBlockElements()[node.nodeName];
+ }, editor.getBody());
+ if (textBlock) {
+ return dom.split(textBlock, figure);
+ } else {
+ return figure;
+ }
+ };
+ var readImageDataFromSelection = function (editor) {
+ var image = getSelectedImage(editor);
+ return image ? read(function (css) {
+ return normalizeCss(editor, css);
+ }, image) : defaultData();
+ };
+ var insertImageAtCaret = function (editor, data) {
+ var elm = create(function (css) {
+ return normalizeCss(editor, css);
+ }, data);
+ editor.dom.setAttrib(elm, 'data-mce-id', '__mcenew');
+ editor.focus();
+ editor.selection.setContent(elm.outerHTML);
+ var insertedElm = editor.dom.select('*[data-mce-id="__mcenew"]')[0];
+ editor.dom.setAttrib(insertedElm, 'data-mce-id', null);
+ if (isFigure(insertedElm)) {
+ var figure = splitTextBlock(editor, insertedElm);
+ editor.selection.select(figure);
+ } else {
+ editor.selection.select(insertedElm);
+ }
+ };
+ var syncSrcAttr = function (editor, image) {
+ editor.dom.setAttrib(image, 'src', image.getAttribute('src'));
+ };
+ var deleteImage = function (editor, image) {
+ if (image) {
+ var elm = editor.dom.is(image.parentNode, 'figure.image') ? image.parentNode : image;
+ editor.dom.remove(elm);
+ editor.focus();
+ editor.nodeChanged();
+ if (editor.dom.isEmpty(editor.getBody())) {
+ editor.setContent('');
+ editor.selection.setCursorLocation();
+ }
+ }
+ };
+ var writeImageDataToSelection = function (editor, data) {
+ var image = getSelectedImage(editor);
+ write(function (css) {
+ return normalizeCss(editor, css);
+ }, data, image);
+ syncSrcAttr(editor, image);
+ if (isFigure(image.parentNode)) {
+ var figure = image.parentNode;
+ splitTextBlock(editor, figure);
+ editor.selection.select(image.parentNode);
+ } else {
+ editor.selection.select(image);
+ waitLoadImage(editor, data, image);
+ }
+ };
+ var insertOrUpdateImage = function (editor, partialData) {
+ var image = getSelectedImage(editor);
+ if (image) {
+ var selectedImageData = read(function (css) {
+ return normalizeCss(editor, css);
+ }, image);
+ var data = __assign(__assign({}, selectedImageData), partialData);
+ if (data.src) {
+ writeImageDataToSelection(editor, data);
+ } else {
+ deleteImage(editor, image);
+ }
+ } else if (partialData.src) {
+ insertImageAtCaret(editor, __assign(__assign({}, defaultData()), partialData));
+ }
+ };
+
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
+ var deep = function (old, nu) {
+ var bothObjects = isObject(old) && isObject(nu);
+ return bothObjects ? deepMerge(old, nu) : nu;
+ };
+ var baseMerge = function (merger) {
+ return function () {
+ var objects = new Array(arguments.length);
+ for (var i = 0; i < objects.length; i++) {
+ objects[i] = arguments[i];
+ }
+ if (objects.length === 0) {
+ throw new Error('Can\'t merge zero objects');
+ }
+ var ret = {};
+ for (var j = 0; j < objects.length; j++) {
+ var curObject = objects[j];
+ for (var key in curObject) {
+ if (hasOwnProperty.call(curObject, key)) {
+ ret[key] = merger(ret[key], curObject[key]);
+ }
+ }
+ }
+ return ret;
+ };
+ };
+ var deepMerge = baseMerge(deep);
+
+ var global$4 = tinymce.util.Tools.resolve('tinymce.util.Tools');
+
+ var getValue = function (item) {
+ return isString(item.value) ? item.value : '';
+ };
+ var sanitizeList = function (list, extractValue) {
+ var out = [];
+ global$4.each(list, function (item) {
+ var text = isString(item.text) ? item.text : isString(item.title) ? item.title : '';
+ if (item.menu !== undefined) {
+ var items = sanitizeList(item.menu, extractValue);
+ out.push({
+ text: text,
+ items: items
+ });
+ } else {
+ var value = extractValue(item);
+ out.push({
+ text: text,
+ value: value
+ });
+ }
+ });
+ return out;
+ };
+ var sanitizer = function (extracter) {
+ if (extracter === void 0) {
+ extracter = getValue;
+ }
+ return function (list) {
+ if (list) {
+ return Optional.from(list).map(function (list) {
+ return sanitizeList(list, extracter);
+ });
+ } else {
+ return Optional.none();
+ }
+ };
+ };
+ var sanitize = function (list) {
+ return sanitizer(getValue)(list);
+ };
+ var isGroup = function (item) {
+ return Object.prototype.hasOwnProperty.call(item, 'items');
+ };
+ var findEntryDelegate = function (list, value) {
+ return findMap(list, function (item) {
+ if (isGroup(item)) {
+ return findEntryDelegate(item.items, value);
+ } else if (item.value === value) {
+ return Optional.some(item);
+ } else {
+ return Optional.none();
+ }
+ });
+ };
+ var findEntry = function (optList, value) {
+ return optList.bind(function (list) {
+ return findEntryDelegate(list, value);
+ });
+ };
+ var ListUtils = {
+ sanitizer: sanitizer,
+ sanitize: sanitize,
+ findEntry: findEntry
+ };
+
+ var pathJoin = function (path1, path2) {
+ if (path1) {
+ return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, '');
+ }
+ return path2;
+ };
+ function Uploader (settings) {
+ var defaultHandler = function (blobInfo, success, failure, progress) {
+ var xhr = new XMLHttpRequest();
+ xhr.open('POST', settings.url);
+ xhr.withCredentials = settings.credentials;
+ xhr.upload.onprogress = function (e) {
+ progress(e.loaded / e.total * 100);
+ };
+ xhr.onerror = function () {
+ failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
+ };
+ xhr.onload = function () {
+ if (xhr.status < 200 || xhr.status >= 300) {
+ failure('HTTP Error: ' + xhr.status);
+ return;
+ }
+ var json = JSON.parse(xhr.responseText);
+ if (!json || typeof json.location !== 'string') {
+ failure('Invalid JSON: ' + xhr.responseText);
+ return;
+ }
+ success(pathJoin(settings.basePath, json.location));
+ };
+ var formData = new FormData();
+ formData.append('file', blobInfo.blob(), blobInfo.filename());
+ xhr.send(formData);
+ };
+ var uploadBlob = function (blobInfo, handler) {
+ return new global$2(function (resolve, reject) {
+ try {
+ handler(blobInfo, resolve, reject, noop);
+ } catch (ex) {
+ reject(ex.message);
+ }
+ });
+ };
+ var isDefaultHandler = function (handler) {
+ return handler === defaultHandler;
+ };
+ var upload = function (blobInfo) {
+ return !settings.url && isDefaultHandler(settings.handler) ? global$2.reject('Upload url missing from the settings.') : uploadBlob(blobInfo, settings.handler);
+ };
+ settings = global$4.extend({
+ credentials: false,
+ handler: defaultHandler
+ }, settings);
+ return { upload: upload };
+ }
+
+ var makeTab = function (_info) {
+ return {
+ title: 'Advanced',
+ name: 'advanced',
+ items: [
+ {
+ type: 'input',
+ label: 'Style',
+ name: 'style'
+ },
+ {
+ type: 'grid',
+ columns: 2,
+ items: [
+ {
+ type: 'input',
+ label: 'Vertical space',
+ name: 'vspace',
+ inputMode: 'numeric'
+ },
+ {
+ type: 'input',
+ label: 'Horizontal space',
+ name: 'hspace',
+ inputMode: 'numeric'
+ },
+ {
+ type: 'input',
+ label: 'Border width',
+ name: 'border',
+ inputMode: 'numeric'
+ },
+ {
+ type: 'listbox',
+ name: 'borderstyle',
+ label: 'Border style',
+ items: [
+ {
+ text: 'Select...',
+ value: ''
+ },
+ {
+ text: 'Solid',
+ value: 'solid'
+ },
+ {
+ text: 'Dotted',
+ value: 'dotted'
+ },
+ {
+ text: 'Dashed',
+ value: 'dashed'
+ },
+ {
+ text: 'Double',
+ value: 'double'
+ },
+ {
+ text: 'Groove',
+ value: 'groove'
+ },
+ {
+ text: 'Ridge',
+ value: 'ridge'
+ },
+ {
+ text: 'Inset',
+ value: 'inset'
+ },
+ {
+ text: 'Outset',
+ value: 'outset'
+ },
+ {
+ text: 'None',
+ value: 'none'
+ },
+ {
+ text: 'Hidden',
+ value: 'hidden'
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ };
+ };
+ var AdvTab = { makeTab: makeTab };
+
+ var collect = function (editor) {
+ var urlListSanitizer = ListUtils.sanitizer(function (item) {
+ return editor.convertURL(item.value || item.url, 'src');
+ });
+ var futureImageList = new global$2(function (completer) {
+ createImageList(editor, function (imageList) {
+ completer(urlListSanitizer(imageList).map(function (items) {
+ return flatten([
+ [{
+ text: 'None',
+ value: ''
+ }],
+ items
+ ]);
+ }));
+ });
+ });
+ var classList = ListUtils.sanitize(getClassList(editor));
+ var hasAdvTab$1 = hasAdvTab(editor);
+ var hasUploadTab$1 = hasUploadTab(editor);
+ var hasUploadUrl$1 = hasUploadUrl(editor);
+ var hasUploadHandler$1 = hasUploadHandler(editor);
+ var image = readImageDataFromSelection(editor);
+ var hasDescription$1 = hasDescription(editor);
+ var hasImageTitle$1 = hasImageTitle(editor);
+ var hasDimensions$1 = hasDimensions(editor);
+ var hasImageCaption$1 = hasImageCaption(editor);
+ var hasAccessibilityOptions = showAccessibilityOptions(editor);
+ var url = getUploadUrl(editor);
+ var basePath = getUploadBasePath(editor);
+ var credentials = getUploadCredentials(editor);
+ var handler = getUploadHandler(editor);
+ var automaticUploads = isAutomaticUploadsEnabled(editor);
+ var prependURL = Optional.some(getPrependUrl(editor)).filter(function (preUrl) {
+ return isString(preUrl) && preUrl.length > 0;
+ });
+ return futureImageList.then(function (imageList) {
+ return {
+ image: image,
+ imageList: imageList,
+ classList: classList,
+ hasAdvTab: hasAdvTab$1,
+ hasUploadTab: hasUploadTab$1,
+ hasUploadUrl: hasUploadUrl$1,
+ hasUploadHandler: hasUploadHandler$1,
+ hasDescription: hasDescription$1,
+ hasImageTitle: hasImageTitle$1,
+ hasDimensions: hasDimensions$1,
+ hasImageCaption: hasImageCaption$1,
+ url: url,
+ basePath: basePath,
+ credentials: credentials,
+ handler: handler,
+ prependURL: prependURL,
+ hasAccessibilityOptions: hasAccessibilityOptions,
+ automaticUploads: automaticUploads
+ };
+ });
+ };
+
+ var makeItems = function (info) {
+ var imageUrl = {
+ name: 'src',
+ type: 'urlinput',
+ filetype: 'image',
+ label: 'Source'
+ };
+ var imageList = info.imageList.map(function (items) {
+ return {
+ name: 'images',
+ type: 'listbox',
+ label: 'Image list',
+ items: items
+ };
+ });
+ var imageDescription = {
+ name: 'alt',
+ type: 'input',
+ label: 'Alternative description',
+ disabled: info.hasAccessibilityOptions && info.image.isDecorative
+ };
+ var imageTitle = {
+ name: 'title',
+ type: 'input',
+ label: 'Image title'
+ };
+ var imageDimensions = {
+ name: 'dimensions',
+ type: 'sizeinput'
+ };
+ var isDecorative = {
+ type: 'label',
+ label: 'Accessibility',
+ items: [{
+ name: 'isDecorative',
+ type: 'checkbox',
+ label: 'Image is decorative'
+ }]
+ };
+ var classList = info.classList.map(function (items) {
+ return {
+ name: 'classes',
+ type: 'listbox',
+ label: 'Class',
+ items: items
+ };
+ });
+ var caption = {
+ type: 'label',
+ label: 'Caption',
+ items: [{
+ type: 'checkbox',
+ name: 'caption',
+ label: 'Show caption'
+ }]
+ };
+ return flatten([
+ [imageUrl],
+ imageList.toArray(),
+ info.hasAccessibilityOptions && info.hasDescription ? [isDecorative] : [],
+ info.hasDescription ? [imageDescription] : [],
+ info.hasImageTitle ? [imageTitle] : [],
+ info.hasDimensions ? [imageDimensions] : [],
+ [{
+ type: 'grid',
+ columns: 2,
+ items: flatten([
+ classList.toArray(),
+ info.hasImageCaption ? [caption] : []
+ ])
+ }]
+ ]);
+ };
+ var makeTab$1 = function (info) {
+ return {
+ title: 'General',
+ name: 'general',
+ items: makeItems(info)
+ };
+ };
+ var MainTab = {
+ makeTab: makeTab$1,
+ makeItems: makeItems
+ };
+
+ var makeTab$2 = function (_info) {
+ var items = [{
+ type: 'dropzone',
+ name: 'fileinput'
+ }];
+ return {
+ title: 'Upload',
+ name: 'upload',
+ items: items
+ };
+ };
+ var UploadTab = { makeTab: makeTab$2 };
+
+ var createState = function (info) {
+ return {
+ prevImage: ListUtils.findEntry(info.imageList, info.image.src),
+ prevAlt: info.image.alt,
+ open: true
+ };
+ };
+ var fromImageData = function (image) {
+ return {
+ src: {
+ value: image.src,
+ meta: {}
+ },
+ images: image.src,
+ alt: image.alt,
+ title: image.title,
+ dimensions: {
+ width: image.width,
+ height: image.height
+ },
+ classes: image.class,
+ caption: image.caption,
+ style: image.style,
+ vspace: image.vspace,
+ border: image.border,
+ hspace: image.hspace,
+ borderstyle: image.borderStyle,
+ fileinput: [],
+ isDecorative: image.isDecorative
+ };
+ };
+ var toImageData = function (data, removeEmptyAlt) {
+ return {
+ src: data.src.value,
+ alt: data.alt.length === 0 && removeEmptyAlt ? null : data.alt,
+ title: data.title,
+ width: data.dimensions.width,
+ height: data.dimensions.height,
+ class: data.classes,
+ style: data.style,
+ caption: data.caption,
+ hspace: data.hspace,
+ vspace: data.vspace,
+ border: data.border,
+ borderStyle: data.borderstyle,
+ isDecorative: data.isDecorative
+ };
+ };
+ var addPrependUrl2 = function (info, srcURL) {
+ if (!/^(?:[a-zA-Z]+:)?\/\//.test(srcURL)) {
+ return info.prependURL.bind(function (prependUrl) {
+ if (srcURL.substring(0, prependUrl.length) !== prependUrl) {
+ return Optional.some(prependUrl + srcURL);
+ }
+ return Optional.none();
+ });
+ }
+ return Optional.none();
+ };
+ var addPrependUrl = function (info, api) {
+ var data = api.getData();
+ addPrependUrl2(info, data.src.value).each(function (srcURL) {
+ api.setData({
+ src: {
+ value: srcURL,
+ meta: data.src.meta
+ }
+ });
+ });
+ };
+ var formFillFromMeta2 = function (info, data, meta) {
+ if (info.hasDescription && isString(meta.alt)) {
+ data.alt = meta.alt;
+ }
+ if (info.hasAccessibilityOptions) {
+ data.isDecorative = meta.isDecorative || data.isDecorative || false;
+ }
+ if (info.hasImageTitle && isString(meta.title)) {
+ data.title = meta.title;
+ }
+ if (info.hasDimensions) {
+ if (isString(meta.width)) {
+ data.dimensions.width = meta.width;
+ }
+ if (isString(meta.height)) {
+ data.dimensions.height = meta.height;
+ }
+ }
+ if (isString(meta.class)) {
+ ListUtils.findEntry(info.classList, meta.class).each(function (entry) {
+ data.classes = entry.value;
+ });
+ }
+ if (info.hasImageCaption) {
+ if (isBoolean(meta.caption)) {
+ data.caption = meta.caption;
+ }
+ }
+ if (info.hasAdvTab) {
+ if (isString(meta.style)) {
+ data.style = meta.style;
+ }
+ if (isString(meta.vspace)) {
+ data.vspace = meta.vspace;
+ }
+ if (isString(meta.border)) {
+ data.border = meta.border;
+ }
+ if (isString(meta.hspace)) {
+ data.hspace = meta.hspace;
+ }
+ if (isString(meta.borderstyle)) {
+ data.borderstyle = meta.borderstyle;
+ }
+ }
+ };
+ var formFillFromMeta = function (info, api) {
+ var data = api.getData();
+ var meta = data.src.meta;
+ if (meta !== undefined) {
+ var newData = deepMerge({}, data);
+ formFillFromMeta2(info, newData, meta);
+ api.setData(newData);
+ }
+ };
+ var calculateImageSize = function (helpers, info, state, api) {
+ var data = api.getData();
+ var url = data.src.value;
+ var meta = data.src.meta || {};
+ if (!meta.width && !meta.height && info.hasDimensions) {
+ helpers.imageSize(url).then(function (size) {
+ if (state.open) {
+ api.setData({ dimensions: size });
+ }
+ });
+ }
+ };
+ var updateImagesDropdown = function (info, state, api) {
+ var data = api.getData();
+ var image = ListUtils.findEntry(info.imageList, data.src.value);
+ state.prevImage = image;
+ api.setData({
+ images: image.map(function (entry) {
+ return entry.value;
+ }).getOr('')
+ });
+ };
+ var changeSrc = function (helpers, info, state, api) {
+ addPrependUrl(info, api);
+ formFillFromMeta(info, api);
+ calculateImageSize(helpers, info, state, api);
+ updateImagesDropdown(info, state, api);
+ };
+ var changeImages = function (helpers, info, state, api) {
+ var data = api.getData();
+ var image = ListUtils.findEntry(info.imageList, data.images);
+ image.each(function (img) {
+ var updateAlt = data.alt === '' || state.prevImage.map(function (image) {
+ return image.text === data.alt;
+ }).getOr(false);
+ if (updateAlt) {
+ if (img.value === '') {
+ api.setData({
+ src: img,
+ alt: state.prevAlt
+ });
+ } else {
+ api.setData({
+ src: img,
+ alt: img.text
+ });
+ }
+ } else {
+ api.setData({ src: img });
+ }
+ });
+ state.prevImage = image;
+ changeSrc(helpers, info, state, api);
+ };
+ var calcVSpace = function (css) {
+ var matchingTopBottom = css['margin-top'] && css['margin-bottom'] && css['margin-top'] === css['margin-bottom'];
+ return matchingTopBottom ? removePixelSuffix(String(css['margin-top'])) : '';
+ };
+ var calcHSpace = function (css) {
+ var matchingLeftRight = css['margin-right'] && css['margin-left'] && css['margin-right'] === css['margin-left'];
+ return matchingLeftRight ? removePixelSuffix(String(css['margin-right'])) : '';
+ };
+ var calcBorderWidth = function (css) {
+ return css['border-width'] ? removePixelSuffix(String(css['border-width'])) : '';
+ };
+ var calcBorderStyle = function (css) {
+ return css['border-style'] ? String(css['border-style']) : '';
+ };
+ var calcStyle = function (parseStyle, serializeStyle, css) {
+ return serializeStyle(parseStyle(serializeStyle(css)));
+ };
+ var changeStyle2 = function (parseStyle, serializeStyle, data) {
+ var css = mergeMargins(parseStyle(data.style));
+ var dataCopy = deepMerge({}, data);
+ dataCopy.vspace = calcVSpace(css);
+ dataCopy.hspace = calcHSpace(css);
+ dataCopy.border = calcBorderWidth(css);
+ dataCopy.borderstyle = calcBorderStyle(css);
+ dataCopy.style = calcStyle(parseStyle, serializeStyle, css);
+ return dataCopy;
+ };
+ var changeStyle = function (helpers, api) {
+ var data = api.getData();
+ var newData = changeStyle2(helpers.parseStyle, helpers.serializeStyle, data);
+ api.setData(newData);
+ };
+ var changeAStyle = function (helpers, info, api) {
+ var data = deepMerge(fromImageData(info.image), api.getData());
+ var style = getStyleValue(helpers.normalizeCss, toImageData(data, false));
+ api.setData({ style: style });
+ };
+ var changeFileInput = function (helpers, info, state, api) {
+ var data = api.getData();
+ api.block('Uploading image');
+ head(data.fileinput).fold(function () {
+ api.unblock();
+ }, function (file) {
+ var blobUri = URL.createObjectURL(file);
+ var uploader = Uploader({
+ url: info.url,
+ basePath: info.basePath,
+ credentials: info.credentials,
+ handler: info.handler
+ });
+ var finalize = function () {
+ api.unblock();
+ URL.revokeObjectURL(blobUri);
+ };
+ var updateSrcAndSwitchTab = function (url) {
+ api.setData({
+ src: {
+ value: url,
+ meta: {}
+ }
+ });
+ api.showTab('general');
+ changeSrc(helpers, info, state, api);
+ };
+ blobToDataUri(file).then(function (dataUrl) {
+ var blobInfo = helpers.createBlobCache(file, blobUri, dataUrl);
+ if (info.automaticUploads) {
+ uploader.upload(blobInfo).then(function (url) {
+ updateSrcAndSwitchTab(url);
+ finalize();
+ }).catch(function (err) {
+ finalize();
+ helpers.alertErr(err);
+ });
+ } else {
+ helpers.addToBlobCache(blobInfo);
+ updateSrcAndSwitchTab(blobInfo.blobUri());
+ api.unblock();
+ }
+ });
+ });
+ };
+ var changeHandler = function (helpers, info, state) {
+ return function (api, evt) {
+ if (evt.name === 'src') {
+ changeSrc(helpers, info, state, api);
+ } else if (evt.name === 'images') {
+ changeImages(helpers, info, state, api);
+ } else if (evt.name === 'alt') {
+ state.prevAlt = api.getData().alt;
+ } else if (evt.name === 'style') {
+ changeStyle(helpers, api);
+ } else if (evt.name === 'vspace' || evt.name === 'hspace' || evt.name === 'border' || evt.name === 'borderstyle') {
+ changeAStyle(helpers, info, api);
+ } else if (evt.name === 'fileinput') {
+ changeFileInput(helpers, info, state, api);
+ } else if (evt.name === 'isDecorative') {
+ if (api.getData().isDecorative) {
+ api.disable('alt');
+ } else {
+ api.enable('alt');
+ }
+ }
+ };
+ };
+ var closeHandler = function (state) {
+ return function () {
+ state.open = false;
+ };
+ };
+ var makeDialogBody = function (info) {
+ if (info.hasAdvTab || info.hasUploadUrl || info.hasUploadHandler) {
+ var tabPanel = {
+ type: 'tabpanel',
+ tabs: flatten([
+ [MainTab.makeTab(info)],
+ info.hasAdvTab ? [AdvTab.makeTab(info)] : [],
+ info.hasUploadTab && (info.hasUploadUrl || info.hasUploadHandler) ? [UploadTab.makeTab(info)] : []
+ ])
+ };
+ return tabPanel;
+ } else {
+ var panel = {
+ type: 'panel',
+ items: MainTab.makeItems(info)
+ };
+ return panel;
+ }
+ };
+ var makeDialog = function (helpers) {
+ return function (info) {
+ var state = createState(info);
+ return {
+ title: 'Insert/Edit Image',
+ size: 'normal',
+ body: makeDialogBody(info),
+ buttons: [
+ {
+ type: 'cancel',
+ name: 'cancel',
+ text: 'Cancel'
+ },
+ {
+ type: 'submit',
+ name: 'save',
+ text: 'Save',
+ primary: true
+ }
+ ],
+ initialData: fromImageData(info.image),
+ onSubmit: helpers.onSubmit(info),
+ onChange: changeHandler(helpers, info, state),
+ onClose: closeHandler(state)
+ };
+ };
+ };
+ var submitHandler = function (editor) {
+ return function (info) {
+ return function (api) {
+ var data = deepMerge(fromImageData(info.image), api.getData());
+ editor.execCommand('mceUpdateImage', false, toImageData(data, info.hasAccessibilityOptions));
+ editor.editorUpload.uploadImagesAuto();
+ api.close();
+ };
+ };
+ };
+ var imageSize = function (editor) {
+ return function (url) {
+ return getImageSize(editor.documentBaseURI.toAbsolute(url)).then(function (dimensions) {
+ return {
+ width: String(dimensions.width),
+ height: String(dimensions.height)
+ };
+ });
+ };
+ };
+ var createBlobCache = function (editor) {
+ return function (file, blobUri, dataUrl) {
+ return editor.editorUpload.blobCache.create({
+ blob: file,
+ blobUri: blobUri,
+ name: file.name ? file.name.replace(/\.[^\.]+$/, '') : null,
+ base64: dataUrl.split(',')[1]
+ });
+ };
+ };
+ var addToBlobCache = function (editor) {
+ return function (blobInfo) {
+ editor.editorUpload.blobCache.add(blobInfo);
+ };
+ };
+ var alertErr = function (editor) {
+ return function (message) {
+ editor.windowManager.alert(message);
+ };
+ };
+ var normalizeCss$1 = function (editor) {
+ return function (cssText) {
+ return normalizeCss(editor, cssText);
+ };
+ };
+ var parseStyle = function (editor) {
+ return function (cssText) {
+ return editor.dom.parseStyle(cssText);
+ };
+ };
+ var serializeStyle = function (editor) {
+ return function (stylesArg, name) {
+ return editor.dom.serializeStyle(stylesArg, name);
+ };
+ };
+ var Dialog = function (editor) {
+ var helpers = {
+ onSubmit: submitHandler(editor),
+ imageSize: imageSize(editor),
+ addToBlobCache: addToBlobCache(editor),
+ createBlobCache: createBlobCache(editor),
+ alertErr: alertErr(editor),
+ normalizeCss: normalizeCss$1(editor),
+ parseStyle: parseStyle(editor),
+ serializeStyle: serializeStyle(editor)
+ };
+ var open = function () {
+ collect(editor).then(makeDialog(helpers)).then(editor.windowManager.open);
+ };
+ return { open: open };
+ };
+
+ var register = function (editor) {
+ editor.addCommand('mceImage', Dialog(editor).open);
+ editor.addCommand('mceUpdateImage', function (_ui, data) {
+ editor.undoManager.transact(function () {
+ return insertOrUpdateImage(editor, data);
+ });
+ });
+ };
+
+ var hasImageClass = function (node) {
+ var className = node.attr('class');
+ return className && /\bimage\b/.test(className);
+ };
+ var toggleContentEditableState = function (state) {
+ return function (nodes) {
+ var i = nodes.length;
+ var toggleContentEditable = function (node) {
+ node.attr('contenteditable', state ? 'true' : null);
+ };
+ while (i--) {
+ var node = nodes[i];
+ if (hasImageClass(node)) {
+ node.attr('contenteditable', state ? 'false' : null);
+ global$4.each(node.getAll('figcaption'), toggleContentEditable);
+ }
+ }
+ };
+ };
+ var setup = function (editor) {
+ editor.on('PreInit', function () {
+ editor.parser.addNodeFilter('figure', toggleContentEditableState(true));
+ editor.serializer.addNodeFilter('figure', toggleContentEditableState(false));
+ });
+ };
+
+ var register$1 = function (editor) {
+ editor.ui.registry.addToggleButton('image', {
+ icon: 'image',
+ tooltip: 'Insert/edit image',
+ onAction: Dialog(editor).open,
+ onSetup: function (buttonApi) {
+ return editor.selection.selectorChangedWithUnbind('img:not([data-mce-object],[data-mce-placeholder]),figure.image', buttonApi.setActive).unbind;
+ }
+ });
+ editor.ui.registry.addMenuItem('image', {
+ icon: 'image',
+ text: 'Image...',
+ onAction: Dialog(editor).open
+ });
+ editor.ui.registry.addContextMenu('image', {
+ update: function (element) {
+ return isFigure(element) || isImage(element) && !isPlaceholderImage(element) ? ['image'] : [];
+ }
+ });
+ };
+
+ function Plugin () {
+ global.add('image', function (editor) {
+ setup(editor);
+ register$1(editor);
+ register(editor);
+ });
+ }
+
+ Plugin();
+
+}());
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.min.js
index fb8ee8fd7f..9e01ef9a50 100644
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.min.js
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.min.js
@@ -1 +1,9 @@
-tinymce.PluginManager.add("image",function(e){function t(e,t){function n(e,n){i.parentNode&&i.parentNode.removeChild(i),t({width:e,height:n})}var i=document.createElement("img");i.onload=function(){n(i.clientWidth,i.clientHeight)},i.onerror=function(){n()};var a=i.style;a.visibility="hidden",a.position="fixed",a.bottom=a.left=0,a.width=a.height="auto",document.body.appendChild(i),i.src=e}function n(t){return function(){var n=e.settings.image_list;"string"==typeof n?tinymce.util.XHR.send({url:n,success:function(e){t(tinymce.util.JSON.parse(e))}}):t(n)}}function i(n){function i(){var t=[{text:"None",value:""}];return tinymce.each(n,function(n){t.push({text:n.text||n.title,value:e.convertURL(n.value||n.url,"src"),menu:n.menu})}),t}function a(){var e,t,n,i;e=s.find("#width")[0],t=s.find("#height")[0],n=e.value(),i=t.value(),s.find("#constrain")[0].checked()&&d&&u&&n&&i&&(d!=n?(i=Math.round(n/d*i),t.value(i)):(n=Math.round(i/u*n),e.value(n))),d=n,u=i}function o(){function t(t){function i(){t.onload=t.onerror=null,e.selection.select(t),e.nodeChanged()}t.onload=function(){n.width||n.height||m.setAttribs(t,{width:t.clientWidth,height:t.clientHeight}),i()},t.onerror=i}c(),a();var n=s.toJSON();""===n.width&&(n.width=null),""===n.height&&(n.height=null),""===n.style&&(n.style=null),n={src:n.src,alt:n.alt,width:n.width,height:n.height,style:n.style},e.fire('SaveImage', n),e.undoManager.transact(function(){return n.src?(p?m.setAttribs(p,n):(n.id="__mcenew",e.focus(),e.selection.setContent(m.createHTML("img",n)),p=m.get("__mcenew"),m.setAttrib(p,"id",null)),void t(p)):void(p&&(m.remove(p),e.nodeChanged()))})}function l(e){return e&&(e=e.replace(/px$/,"")),e}function r(){h&&h.value(e.convertURL(this.value(),"src")),t(this.value(),function(e){e.width&&e.height&&(d=e.width,u=e.height,s.find("#width").value(d),s.find("#height").value(u))})}function c(){function t(e){return e.length>0&&/^[0-9]+$/.test(e)&&(e+="px"),e}if(e.settings.image_advtab){var n=s.toJSON(),i=m.parseStyle(n.style);delete i.margin,i["margin-top"]=i["margin-bottom"]=t(n.vspace),i["margin-left"]=i["margin-right"]=t(n.hspace),i["border-width"]=t(n.border),s.find("#style").value(m.serializeStyle(m.parseStyle(m.serializeStyle(i))))}}var s,d,u,h,g={},m=e.dom,p=e.selection.getNode();d=m.getAttrib(p,"width"),u=m.getAttrib(p,"height"),"IMG"!=p.nodeName||p.getAttribute("data-mce-object")||p.getAttribute("data-mce-placeholder")?p=null:g={src:m.getAttrib(p,"src"),alt:m.getAttrib(p,"alt"),width:d,height:u},n&&(h={type:"listbox",label:"Image list",values:i(),value:g.src&&e.convertURL(g.src,"src"),onselect:function(e){var t=s.find("#alt");(!t.value()||e.lastControl&&t.value()==e.lastControl.text())&&t.value(e.control.text()),s.find("#src").value(e.control.value())},onPostRender:function(){h=this}});var y=[{name:"src",type:"filepicker",filetype:"image",label:"Source",autofocus:!0,onchange:r},h,{name:"alt",type:"textbox",label:"Image description"},{type:"container",label:"Dimensions",layout:"flex",direction:"row",align:"center",spacing:5,items:[{name:"width",type:"textbox",maxLength:5,size:3,onchange:a},{type:"label",text:"x"},{name:"height",type:"textbox",maxLength:5,size:3,onchange:a},{name:"constrain",type:"checkbox",checked:!0,text:"Constrain proportions"}]}];e.fire('EditImage', g),e.settings.image_advtab?(p&&(g.hspace=l(p.style.marginLeft||p.style.marginRight),g.vspace=l(p.style.marginTop||p.style.marginBottom),g.border=l(p.style.borderWidth),g.style=e.dom.serializeStyle(e.dom.parseStyle(e.dom.getAttrib(p,"style")))),s=e.windowManager.open({title:"Insert/edit image",data:g,bodyType:"tabpanel",body:[{title:"General",type:"form",items:y},{title:"Advanced",type:"form",pack:"start",items:[{label:"Style",name:"style",type:"textbox"},{type:"form",layout:"grid",packV:"start",columns:2,padding:0,alignH:["left","right"],defaults:{type:"textbox",maxWidth:50,onchange:c},items:[{label:"Vertical space",name:"vspace"},{label:"Horizontal space",name:"hspace"},{label:"Border",name:"border"}]}]}],onSubmit:o})):s=e.windowManager.open({title:"Insert/edit image",data:g,body:y,onSubmit:o})}e.addButton("image",{icon:"image",tooltip:"Insert/edit image",onclick:n(i),stateSelector:"img:not([data-mce-object],[data-mce-placeholder])"}),e.addMenuItem("image",{icon:"image",text:"Insert image",onclick:n(i),context:"insert",prependToContext:!0})});
\ No newline at end of file
+/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var t,e,n,r,o,a=tinymce.util.Tools.resolve("tinymce.PluginManager"),c=function(){return(c=Object.assign||function(e){for(var t,n=1,r=arguments.length;n
"]
- ]);
- } else {
- text = Utils.filter(text, [
- [/\n\n/g, "
"]
- ]);
-
- if (text.indexOf(' we need to check if any of them contains some useful html.
- // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
- pasteBinClones = editor.dom.select('div[id=mcepastebin]');
- i = pasteBinClones.length;
- while (i--) {
- var cloneHtml = pasteBinClones[i].innerHTML;
-
- if (html == pasteBinDefaultContent) {
- html = '';
- }
-
- if (cloneHtml.length > html.length) {
- html = cloneHtml;
- }
- }
-
- return html;
- }
-
- /**
- * Gets various content types out of a datatransfer object.
- *
- * @param {DataTransfer} dataTransfer Event fired on paste.
- * @return {Object} Object with mime types and data for those mime types.
- */
- function getDataTransferItems(dataTransfer) {
- var data = {};
-
- if (dataTransfer && dataTransfer.types) {
- // Use old WebKit API
- var legacyText = dataTransfer.getData('Text');
- if (legacyText && legacyText.length > 0) {
- data['text/plain'] = legacyText;
- }
-
- for (var i = 0; i < dataTransfer.types.length; i++) {
- var contentType = dataTransfer.types[i];
- data[contentType] = dataTransfer.getData(contentType);
- }
- }
-
- return data;
- }
-
- /**
- * Gets various content types out of the Clipboard API. It will also get the
- * plain text using older IE and WebKit API:s.
- *
- * @param {ClipboardEvent} clipboardEvent Event fired on paste.
- * @return {Object} Object with mime types and data for those mime types.
- */
- function getClipboardContent(clipboardEvent) {
- return getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer);
- }
-
- /**
- * Checks if the clipboard contains image data if it does it will take that data
- * and convert it into a data url image and paste that image at the caret location.
- *
- * @param {ClipboardEvent} e Paste event object.
- * @param {Object} clipboardContent Collection of clipboard contents.
- * @return {Boolean} true/false if the image data was found or not.
- */
- function pasteImageData(e, clipboardContent) {
- function pasteImage(item) {
- if (items[i].type == 'image/png') {
- var reader = new FileReader();
-
- reader.onload = function() {
- pasteHtml('
');
- };
-
- reader.readAsDataURL(item.getAsFile());
-
- return true;
- }
- }
-
- // If paste data images are disabled or there is HTML or plain text
- // contents then proceed with the normal paste process
- if (!editor.settings.paste_data_images || "text/html" in clipboardContent || "text/plain" in clipboardContent) {
- return;
- }
-
- if (e.clipboardData) {
- var items = e.clipboardData.items;
-
- if (items) {
- for (var i = 0; i < items.length; i++) {
- if (pasteImage(items[i])) {
- return true;
- }
- }
- }
- }
- }
-
- function getCaretRangeFromEvent(e) {
- var doc = editor.getDoc(), rng;
-
- if (doc.caretPositionFromPoint) {
- var point = doc.caretPositionFromPoint(e.clientX, e.clientY);
- rng = doc.createRange();
- rng.setStart(point.offsetNode, point.offset);
- rng.collapse(true);
- } else if (doc.caretRangeFromPoint) {
- rng = doc.caretRangeFromPoint(e.clientX, e.clientY);
- }
-
- return rng;
- }
-
- function hasContentType(clipboardContent, mimeType) {
- return mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
- }
-
- function registerEventHandlers() {
- editor.on('keydown', function(e) {
- if (e.isDefaultPrevented()) {
- return;
- }
-
- // Ctrl+V or Shift+Insert
- if ((VK.metaKeyPressed(e) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45)) {
- keyboardPastePlainTextState = e.shiftKey && e.keyCode == 86;
-
- // Prevent undoManager keydown handler from making an undo level with the pastebin in it
- e.stopImmediatePropagation();
-
- keyboardPasteTimeStamp = new Date().getTime();
-
- // IE doesn't support Ctrl+Shift+V and it doesn't even produce a paste event
- // so lets fake a paste event and let IE use the execCommand/dataTransfer methods
- if (Env.ie && keyboardPastePlainTextState) {
- e.preventDefault();
- editor.fire('paste', {ieFake: true});
- return;
- }
-
- removePasteBin();
- createPasteBin();
- }
- });
-
- editor.on('paste', function(e) {
- var clipboardContent = getClipboardContent(e);
- var isKeyBoardPaste = new Date().getTime() - keyboardPasteTimeStamp < 1000;
- var plainTextMode = self.pasteFormat == "text" || keyboardPastePlainTextState;
-
- if (e.isDefaultPrevented()) {
- removePasteBin();
- return;
- }
-
- if (pasteImageData(e, clipboardContent)) {
- removePasteBin();
- return;
- }
-
- // Not a keyboard paste prevent default paste and try to grab the clipboard contents using different APIs
- if (!isKeyBoardPaste) {
- e.preventDefault();
- }
-
- // Try IE only method if paste isn't a keyboard paste
- if (Env.ie && (!isKeyBoardPaste || e.ieFake)) {
- createPasteBin();
-
- editor.dom.bind(pasteBinElm, 'paste', function(e) {
- e.stopPropagation();
- });
-
- editor.getDoc().execCommand('Paste', false, null);
- clipboardContent["text/html"] = getPasteBinHtml();
- }
-
- setTimeout(function() {
- var html = getPasteBinHtml();
-
- // WebKit has a nice bug where it clones the paste bin if you paste from for example notepad
- if (pasteBinElm && pasteBinElm.firstChild && pasteBinElm.firstChild.id === 'mcepastebin') {
- plainTextMode = true;
- }
-
- removePasteBin();
-
- if (html == pasteBinDefaultContent || !isKeyBoardPaste) {
- html = clipboardContent['text/html'] || clipboardContent['text/plain'] || pasteBinDefaultContent;
-
- if (html == pasteBinDefaultContent) {
- if (!isKeyBoardPaste) {
- editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.');
- }
-
- return;
- }
- }
-
- // Force plain text mode if we only got a text/plain content type
- if (!hasContentType(clipboardContent, 'text/html') && hasContentType(clipboardContent, 'text/plain')) {
- plainTextMode = true;
- }
-
- if (plainTextMode) {
- pasteText(clipboardContent['text/plain'] || Utils.innerText(html));
- } else {
- pasteHtml(html);
- }
- }, 0);
- });
-
- editor.on('dragstart', function(e) {
- if (e.dataTransfer.types) {
- try {
- e.dataTransfer.setData('mce-internal', editor.selection.getContent());
- } catch (ex) {
- // IE 10 throws an error since it doesn't support custom data items
- }
- }
- });
-
- editor.on('drop', function(e) {
- var rng = getCaretRangeFromEvent(e);
-
- if (rng && !e.isDefaultPrevented()) {
- var dropContent = getDataTransferItems(e.dataTransfer);
- var content = dropContent['mce-internal'] || dropContent['text/html'] || dropContent['text/plain'];
-
- if (content) {
- e.preventDefault();
-
- editor.undoManager.transact(function() {
- if (dropContent['mce-internal']) {
- editor.execCommand('Delete');
- }
-
- editor.selection.setRng(rng);
-
- if (!dropContent['text/html']) {
- pasteText(content);
- } else {
- pasteHtml(content);
- }
- });
- }
- }
- });
- }
-
- self.pasteHtml = pasteHtml;
- self.pasteText = pasteText;
-
- editor.on('preInit', function() {
- registerEventHandlers();
-
- // Remove all data images from paste for example from Gecko
- // except internal images like video elements
- editor.parser.addNodeFilter('img', function(nodes) {
- if (!editor.settings.paste_data_images) {
- var i = nodes.length;
-
- while (i--) {
- var src = nodes[i].attributes.map.src;
- if (src && src.indexOf('data:image') === 0) {
- if (!nodes[i].attr('data-mce-object') && src !== Env.transparentSrc) {
- nodes[i].remove();
- }
- }
- }
- }
- });
- });
-
- // Fix for #6504 we need to remove the paste bin on IE if the user paste in a file
- editor.on('PreProcess', function() {
- editor.dom.remove(editor.dom.get('mcepastebin'));
- });
- };
-});
-
-// Included from: js/tinymce/plugins/paste/classes/WordFilter.js
-
-/**
- * WordFilter.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class parses word HTML into proper TinyMCE markup.
- *
- * @class tinymce.pasteplugin.Quirks
- * @private
- */
-define("tinymce/pasteplugin/WordFilter", [
- "tinymce/util/Tools",
- "tinymce/html/DomParser",
- "tinymce/html/Schema",
- "tinymce/html/Serializer",
- "tinymce/html/Node",
- "tinymce/pasteplugin/Utils"
-], function(Tools, DomParser, Schema, Serializer, Node, Utils) {
- function isWordContent(content) {
- return (/ 1) {
- currentListNode.attr('start', '' + start);
- }
-
- paragraphNode.wrap(currentListNode);
- } else {
- currentListNode.append(paragraphNode);
- }
-
- paragraphNode.name = 'li';
- listStartTextNode.value = '';
-
- var nextNode = listStartTextNode.next;
- if (nextNode && nextNode.type == 3) {
- nextNode.value = nextNode.value.replace(/^\u00a0+/, '');
- }
-
- // Append list to previous list if it exists
- if (level > lastLevel && prevListNode) {
- prevListNode.lastChild.append(currentListNode);
- }
-
- lastLevel = level;
- }
-
- var paragraphs = node.getAll('p');
-
- for (var i = 0; i < paragraphs.length; i++) {
- node = paragraphs[i];
-
- if (node.name == 'p' && node.firstChild) {
- // Find first text node in paragraph
- var nodeText = '';
- var listStartTextNode = node.firstChild;
-
- while (listStartTextNode) {
- nodeText = listStartTextNode.value;
- if (nodeText) {
- break;
- }
-
- listStartTextNode = listStartTextNode.firstChild;
- }
-
- // Detect unordered lists look for bullets
- if (/^\s*[\u2022\u00b7\u00a7\u00d8\u25CF]\s*$/.test(nodeText)) {
- convertParagraphToLi(node, listStartTextNode, 'ul');
- continue;
- }
-
- // Detect ordered lists 1., a. or ixv.
- if (/^\s*\w+\.$/.test(nodeText)) {
- // Parse OL start number
- var matches = /([0-9])\./.exec(nodeText);
- var start = 1;
- if (matches) {
- start = parseInt(matches[1], 10);
- }
-
- convertParagraphToLi(node, listStartTextNode, 'ol', start);
- continue;
- }
-
- currentListNode = null;
- }
- }
- }
-
- function filterStyles(node, styleValue) {
- // Parse out list indent level for lists
- if (node.name === 'p') {
- var matches = /mso-list:\w+ \w+([0-9]+)/.exec(styleValue);
-
- if (matches) {
- node._listLevel = parseInt(matches[1], 10);
- }
- }
-
- if (editor.getParam("paste_retain_style_properties", "none")) {
- var outputStyle = "";
-
- Tools.each(editor.dom.parseStyle(styleValue), function(value, name) {
- // Convert various MS styles to W3C styles
- switch (name) {
- case "horiz-align":
- name = "text-align";
- return;
-
- case "vert-align":
- name = "vertical-align";
- return;
-
- case "font-color":
- case "mso-foreground":
- name = "color";
- return;
-
- case "mso-background":
- case "mso-highlight":
- name = "background";
- break;
- }
-
- // Output only valid styles
- if (retainStyleProperties == "all" || (validStyles && validStyles[name])) {
- outputStyle += name + ':' + value + ';';
- }
- });
-
- if (outputStyle) {
- return outputStyle;
- }
- }
-
- return null;
- }
-
- if (settings.paste_enable_default_filters === false) {
- return;
- }
-
- // Detect is the contents is Word junk HTML
- if (isWordContent(e.content)) {
- e.wordContent = true; // Mark it for other processors
-
- // Remove basic Word junk
- content = Utils.filter(content, [
- // Word comments like conditional comments etc
- //gi,
-
- // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
- // MS Office namespaced tags, and a few other tags
- /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
-
- // Convert
into for line-though
- [/<(\/?)s>/gi, "<$1strike>"],
-
- // Replace nsbp entites to char since it's easier to handle
- [/ /gi, "\u00a0"],
-
- // Convert ___ to string of alternating
- // breaking/non-breaking spaces of same length
- [/([\s\u00a0]*)<\/span>/gi,
- function(str, spaces) {
- return (spaces.length > 0) ?
- spaces.replace(/./, " ").slice(Math.floor(spaces.length / 2)).split("").join("\u00a0") : "";
- }
- ]
- ]);
-
- var validElements = settings.paste_word_valid_elements;
- if (!validElements) {
- validElements = '@[style],-strong/b,-em/i,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,' +
- '-table[width],-tr,-td[colspan|rowspan|width],-th,-thead,-tfoot,-tbody,-a[href|name],sub,sup,strike,br';
- }
-
- // Setup strict schema
- var schema = new Schema({
- valid_elements: validElements
- });
-
- // Parse HTML into DOM structure
- var domParser = new DomParser({}, schema);
-
- domParser.addAttributeFilter('style', function(nodes) {
- var i = nodes.length, node;
-
- while (i--) {
- node = nodes[i];
- node.attr('style', filterStyles(node, node.attr('style')));
-
- // Remove pointess spans
- if (node.name == 'span' && !node.attributes.length) {
- node.unwrap();
- }
- }
- });
-
- domParser.addNodeFilter('a', function(nodes) {
- var i = nodes.length, node, href, name;
-
- while (i--) {
- node = nodes[i];
- href = node.attr('href');
- name = node.attr('name');
-
- if (href && href.indexOf('file://') === 0) {
- href = href.split('#')[1];
- if (href) {
- href = '#' + href;
- }
- }
-
- if (!href && !name) {
- node.unwrap();
- } else {
- node.attr({
- href: href,
- name: name
- });
- }
- }
- });
- // Parse into DOM structure
- var rootNode = domParser.parse(content);
-
- // Process DOM
- convertFakeListsToProperLists(rootNode);
-
- // Serialize DOM back to HTML
- e.content = new Serializer({}, schema).serialize(rootNode);
- }
- });
- }
-
- WordFilter.isWordContent = isWordContent;
-
- return WordFilter;
-});
-
-// Included from: js/tinymce/plugins/paste/classes/Quirks.js
-
-/**
- * Quirks.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class contains various fixes for browsers. These issues can not be feature
- * detected since we have no direct control over the clipboard. However we might be able
- * to remove some of these fixes once the browsers gets updated/fixed.
- *
- * @class tinymce.pasteplugin.Quirks
- * @private
- */
-define("tinymce/pasteplugin/Quirks", [
- "tinymce/Env",
- "tinymce/util/Tools",
- "tinymce/pasteplugin/WordFilter",
- "tinymce/pasteplugin/Utils"
-], function(Env, Tools, WordFilter, Utils) {
- "use strict";
-
- return function(editor) {
- function addPreProcessFilter(filterFunc) {
- editor.on('BeforePastePreProcess', function(e) {
- e.content = filterFunc(e.content);
- });
- }
-
- /**
- * Removes WebKit fragment comments and converted-space spans.
- *
- * This:
- * a b
- *
- * Becomes:
- * a b
- */
- function removeWebKitFragments(html) {
- html = Utils.filter(html, [
- /^[\s\S]*|[\s\S]*$/g, // WebKit fragment
- [/\u00a0<\/span>/g, '\u00a0'], // WebKit
- /
$/i // Traling BR elements
- ]);
-
- return html;
- }
-
- /**
- * Removes BR elements after block elements. IE9 has a nasty bug where it puts a BR element after each
- * block element when pasting from word. This removes those elements.
- *
- * This:
- *
[\\s\\r\\n]+|
)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:
[\\s\\r\\n]+|
)*',
- 'g'
- );
-
- // Remove BR:s from:
- html = Utils.filter(html, [
- [explorerBlocksRegExp, '$1']
- ]);
-
- // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break
- html = Utils.filter(html, [
- [/
/g, '
'], // Replace multiple BR elements with uppercase BR to keep them intact
- [/
/g, ' '], // Replace single br elements with space since they are word wrap BR:s
- [/
/g, '
'] // Replace back the double brs but into a single BR
- ]);
-
- return html;
- }
-
- /**
- * WebKit has a nasty bug where the all runtime styles gets added to style attributes when copy/pasting contents.
- * This fix solves that by simply removing the whole style attribute.
- *
- * Todo: This can be made smarter. Keeping styles that override existing ones etc.
- *
- * @param {String} content Content that needs to be processed.
- * @return {String} Processed contents.
- */
- function removeWebKitStyles(content) {
- if (editor.settings.paste_remove_styles || editor.settings.paste_remove_styles_if_webkit !== false) {
- content = content.replace(/ style=\"[^\"]+\"/g, '');
- }
-
- return content;
- }
-
- // Sniff browsers and apply fixes since we can't feature detect
- if (Env.webkit) {
- addPreProcessFilter(removeWebKitStyles);
- addPreProcessFilter(removeWebKitFragments);
- }
-
- if (Env.ie) {
- addPreProcessFilter(removeExplorerBrElementsAfterBlocks);
- }
- };
-});
-
-// Included from: js/tinymce/plugins/paste/classes/Plugin.js
-
-/**
- * Plugin.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class contains the tinymce plugin logic for the paste plugin.
- *
- * @class tinymce.pasteplugin.Plugin
- * @private
- */
-define("tinymce/pasteplugin/Plugin", [
- "tinymce/PluginManager",
- "tinymce/pasteplugin/Clipboard",
- "tinymce/pasteplugin/WordFilter",
- "tinymce/pasteplugin/Quirks"
-], function(PluginManager, Clipboard, WordFilter, Quirks) {
- var userIsInformed;
-
- PluginManager.add('paste', function(editor) {
- var self = this, clipboard, settings = editor.settings;
-
- function togglePlainTextPaste() {
- if (clipboard.pasteFormat == "text") {
- this.active(false);
- clipboard.pasteFormat = "html";
- } else {
- clipboard.pasteFormat = "text";
- this.active(true);
-
- if (!userIsInformed) {
- editor.windowManager.alert(
- 'Paste is now in plain text mode. Contents will now ' +
- 'be pasted as plain text until you toggle this option off.'
- );
-
- userIsInformed = true;
- }
- }
- }
-
- self.clipboard = clipboard = new Clipboard(editor);
- self.quirks = new Quirks(editor);
- self.wordFilter = new WordFilter(editor);
-
- if (editor.settings.paste_as_text) {
- self.clipboard.pasteFormat = "text";
- }
-
- if (settings.paste_preprocess) {
- editor.on('PastePreProcess', function(e) {
- settings.paste_preprocess.call(self, self, e);
- });
- }
-
- if (settings.paste_postprocess) {
- editor.on('PastePostProcess', function(e) {
- settings.paste_postprocess.call(self, self, e);
- });
- }
-
- editor.addCommand('mceInsertClipboardContent', function(ui, value) {
- if (value.content) {
- self.clipboard.pasteHtml(value.content);
- }
-
- if (value.text) {
- self.clipboard.pasteText(value.text);
- }
- });
-
- // Block all drag/drop events
- if (editor.paste_block_drop) {
- editor.on('dragend dragover draggesture dragdrop drop drag', function(e) {
- e.preventDefault();
- e.stopPropagation();
- });
- }
-
- // Prevent users from dropping data images on Gecko
- if (!editor.settings.paste_data_images) {
- editor.on('drop', function(e) {
- var dataTransfer = e.dataTransfer;
-
- if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
- e.preventDefault();
- }
- });
- }
-
- editor.addButton('pastetext', {
- icon: 'pastetext',
- tooltip: 'Paste as text',
- onclick: togglePlainTextPaste,
- active: self.clipboard.pasteFormat == "text"
- });
-
- editor.addMenuItem('pastetext', {
- text: 'Paste as text',
- selectable: true,
- active: clipboard.pasteFormat,
- onclick: togglePlainTextPaste
- });
- });
-});
-
-expose(["tinymce/pasteplugin/Utils","tinymce/pasteplugin/Clipboard","tinymce/pasteplugin/WordFilter","tinymce/pasteplugin/Quirks","tinymce/pasteplugin/Plugin"]);
-})(this);
\ No newline at end of file
+(function () {
+ 'use strict';
+
+ var Cell = function (initial) {
+ var value = initial;
+ var get = function () {
+ return value;
+ };
+ var set = function (v) {
+ value = v;
+ };
+ return {
+ get: get,
+ set: set
+ };
+ };
+
+ var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
+
+ var hasProPlugin = function (editor) {
+ if (editor.hasPlugin('powerpaste', true)) {
+ if (typeof window.console !== 'undefined' && window.console.log) {
+ window.console.log('PowerPaste is incompatible with Paste plugin! Remove \'paste\' from the \'plugins\' option.');
+ }
+ return true;
+ } else {
+ return false;
+ }
+ };
+
+ var get = function (clipboard, quirks) {
+ return {
+ clipboard: clipboard,
+ quirks: quirks
+ };
+ };
+
+ var noop = function () {
+ };
+ var constant = function (value) {
+ return function () {
+ return value;
+ };
+ };
+ var never = constant(false);
+ var always = constant(true);
+
+ var none = function () {
+ return NONE;
+ };
+ var NONE = function () {
+ var eq = function (o) {
+ return o.isNone();
+ };
+ var call = function (thunk) {
+ return thunk();
+ };
+ var id = function (n) {
+ return n;
+ };
+ var me = {
+ fold: function (n, _s) {
+ return n();
+ },
+ is: never,
+ isSome: never,
+ isNone: always,
+ getOr: id,
+ getOrThunk: call,
+ getOrDie: function (msg) {
+ throw new Error(msg || 'error: getOrDie called on none.');
+ },
+ getOrNull: constant(null),
+ getOrUndefined: constant(undefined),
+ or: id,
+ orThunk: call,
+ map: none,
+ each: noop,
+ bind: none,
+ exists: never,
+ forall: always,
+ filter: none,
+ equals: eq,
+ equals_: eq,
+ toArray: function () {
+ return [];
+ },
+ toString: constant('none()')
+ };
+ return me;
+ }();
+ var some = function (a) {
+ var constant_a = constant(a);
+ var self = function () {
+ return me;
+ };
+ var bind = function (f) {
+ return f(a);
+ };
+ var me = {
+ fold: function (n, s) {
+ return s(a);
+ },
+ is: function (v) {
+ return a === v;
+ },
+ isSome: always,
+ isNone: never,
+ getOr: constant_a,
+ getOrThunk: constant_a,
+ getOrDie: constant_a,
+ getOrNull: constant_a,
+ getOrUndefined: constant_a,
+ or: self,
+ orThunk: self,
+ map: function (f) {
+ return some(f(a));
+ },
+ each: function (f) {
+ f(a);
+ },
+ bind: bind,
+ exists: bind,
+ forall: bind,
+ filter: function (f) {
+ return f(a) ? me : NONE;
+ },
+ toArray: function () {
+ return [a];
+ },
+ toString: function () {
+ return 'some(' + a + ')';
+ },
+ equals: function (o) {
+ return o.is(a);
+ },
+ equals_: function (o, elementEq) {
+ return o.fold(never, function (b) {
+ return elementEq(a, b);
+ });
+ }
+ };
+ return me;
+ };
+ var from = function (value) {
+ return value === null || value === undefined ? NONE : some(value);
+ };
+ var Optional = {
+ some: some,
+ none: none,
+ from: from
+ };
+
+ var isSimpleType = function (type) {
+ return function (value) {
+ return typeof value === type;
+ };
+ };
+ var isFunction = isSimpleType('function');
+
+ var nativeSlice = Array.prototype.slice;
+ var map = function (xs, f) {
+ var len = xs.length;
+ var r = new Array(len);
+ for (var i = 0; i < len; i++) {
+ var x = xs[i];
+ r[i] = f(x, i);
+ }
+ return r;
+ };
+ var each = function (xs, f) {
+ for (var i = 0, len = xs.length; i < len; i++) {
+ var x = xs[i];
+ f(x, i);
+ }
+ };
+ var filter = function (xs, pred) {
+ var r = [];
+ for (var i = 0, len = xs.length; i < len; i++) {
+ var x = xs[i];
+ if (pred(x, i)) {
+ r.push(x);
+ }
+ }
+ return r;
+ };
+ var foldl = function (xs, f, acc) {
+ each(xs, function (x) {
+ acc = f(acc, x);
+ });
+ return acc;
+ };
+ var from$1 = isFunction(Array.from) ? Array.from : function (x) {
+ return nativeSlice.call(x);
+ };
+
+ var value = function () {
+ var subject = Cell(Optional.none());
+ var clear = function () {
+ return subject.set(Optional.none());
+ };
+ var set = function (s) {
+ return subject.set(Optional.some(s));
+ };
+ var isSet = function () {
+ return subject.get().isSome();
+ };
+ var on = function (f) {
+ return subject.get().each(f);
+ };
+ return {
+ clear: clear,
+ set: set,
+ isSet: isSet,
+ on: on
+ };
+ };
+
+ var global$1 = tinymce.util.Tools.resolve('tinymce.Env');
+
+ var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
+
+ var global$3 = tinymce.util.Tools.resolve('tinymce.util.Promise');
+
+ var global$4 = tinymce.util.Tools.resolve('tinymce.util.VK');
+
+ var firePastePreProcess = function (editor, html, internal, isWordHtml) {
+ return editor.fire('PastePreProcess', {
+ content: html,
+ internal: internal,
+ wordContent: isWordHtml
+ });
+ };
+ var firePastePostProcess = function (editor, node, internal, isWordHtml) {
+ return editor.fire('PastePostProcess', {
+ node: node,
+ internal: internal,
+ wordContent: isWordHtml
+ });
+ };
+ var firePastePlainTextToggle = function (editor, state) {
+ return editor.fire('PastePlainTextToggle', { state: state });
+ };
+ var firePaste = function (editor, ieFake) {
+ return editor.fire('paste', { ieFake: ieFake });
+ };
+
+ var shouldBlockDrop = function (editor) {
+ return editor.getParam('paste_block_drop', false);
+ };
+ var shouldPasteDataImages = function (editor) {
+ return editor.getParam('paste_data_images', false);
+ };
+ var shouldFilterDrop = function (editor) {
+ return editor.getParam('paste_filter_drop', true);
+ };
+ var getPreProcess = function (editor) {
+ return editor.getParam('paste_preprocess');
+ };
+ var getPostProcess = function (editor) {
+ return editor.getParam('paste_postprocess');
+ };
+ var getWebkitStyles = function (editor) {
+ return editor.getParam('paste_webkit_styles');
+ };
+ var shouldRemoveWebKitStyles = function (editor) {
+ return editor.getParam('paste_remove_styles_if_webkit', true);
+ };
+ var shouldMergeFormats = function (editor) {
+ return editor.getParam('paste_merge_formats', true);
+ };
+ var isSmartPasteEnabled = function (editor) {
+ return editor.getParam('smart_paste', true);
+ };
+ var isPasteAsTextEnabled = function (editor) {
+ return editor.getParam('paste_as_text', false);
+ };
+ var getRetainStyleProps = function (editor) {
+ return editor.getParam('paste_retain_style_properties');
+ };
+ var getWordValidElements = function (editor) {
+ var defaultValidElements = '-strong/b,-em/i,-u,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,' + '-p/div,-a[href|name],sub,sup,strike,br,del,table[width],tr,' + 'td[colspan|rowspan|width],th[colspan|rowspan|width],thead,tfoot,tbody';
+ return editor.getParam('paste_word_valid_elements', defaultValidElements);
+ };
+ var shouldConvertWordFakeLists = function (editor) {
+ return editor.getParam('paste_convert_word_fake_lists', true);
+ };
+ var shouldUseDefaultFilters = function (editor) {
+ return editor.getParam('paste_enable_default_filters', true);
+ };
+ var getValidate = function (editor) {
+ return editor.getParam('validate');
+ };
+ var getAllowHtmlDataUrls = function (editor) {
+ return editor.getParam('allow_html_data_urls', false, 'boolean');
+ };
+ var getPasteDataImages = function (editor) {
+ return editor.getParam('paste_data_images', false, 'boolean');
+ };
+ var getImagesDataImgFilter = function (editor) {
+ return editor.getParam('images_dataimg_filter');
+ };
+ var getImagesReuseFilename = function (editor) {
+ return editor.getParam('images_reuse_filename');
+ };
+ var getForcedRootBlock = function (editor) {
+ return editor.getParam('forced_root_block');
+ };
+ var getForcedRootBlockAttrs = function (editor) {
+ return editor.getParam('forced_root_block_attrs');
+ };
+ var getTabSpaces = function (editor) {
+ return editor.getParam('paste_tab_spaces', 4, 'number');
+ };
+
+ var internalMimeType = 'x-tinymce/html';
+ var internalMark = '';
+ var mark = function (html) {
+ return internalMark + html;
+ };
+ var unmark = function (html) {
+ return html.replace(internalMark, '');
+ };
+ var isMarked = function (html) {
+ return html.indexOf(internalMark) !== -1;
+ };
+ var internalHtmlMime = function () {
+ return internalMimeType;
+ };
+
+ var global$5 = tinymce.util.Tools.resolve('tinymce.html.Entities');
+
+ var global$6 = tinymce.util.Tools.resolve('tinymce.util.Tools');
+
+ var isPlainText = function (text) {
+ return !/<(?:\/?(?!(?:div|p|br|span)>)\w+|(?:(?!(?:span style="white-space:\s?pre;?">)|br\s?\/>))\w+\s[^>]+)>/i.test(text);
+ };
+ var toBRs = function (text) {
+ return text.replace(/\r?\n/g, '
');
+ };
+ var openContainer = function (rootTag, rootAttrs) {
+ var key;
+ var attrs = [];
+ var tag = '<' + rootTag;
+ if (typeof rootAttrs === 'object') {
+ for (key in rootAttrs) {
+ if (rootAttrs.hasOwnProperty(key)) {
+ attrs.push(key + '="' + global$5.encodeAllRaw(rootAttrs[key]) + '"');
+ }
+ }
+ if (attrs.length) {
+ tag += ' ' + attrs.join(' ');
+ }
+ }
+ return tag + '>';
+ };
+ var toBlockElements = function (text, rootTag, rootAttrs) {
+ var blocks = text.split(/\n\n/);
+ var tagOpen = openContainer(rootTag, rootAttrs);
+ var tagClose = '' + rootTag + '>';
+ var paragraphs = global$6.map(blocks, function (p) {
+ return p.split(/\n/).join('
');
+ });
+ var stitch = function (p) {
+ return tagOpen + p + tagClose;
+ };
+ return paragraphs.length === 1 ? paragraphs[0] : global$6.map(paragraphs, stitch).join('');
+ };
+ var convert = function (text, rootTag, rootAttrs) {
+ return rootTag ? toBlockElements(text, rootTag === true ? 'p' : rootTag, rootAttrs) : toBRs(text);
+ };
+
+ var global$7 = tinymce.util.Tools.resolve('tinymce.html.DomParser');
+
+ var global$8 = tinymce.util.Tools.resolve('tinymce.html.Serializer');
+
+ var nbsp = '\xA0';
+
+ var global$9 = tinymce.util.Tools.resolve('tinymce.html.Node');
+
+ var global$a = tinymce.util.Tools.resolve('tinymce.html.Schema');
+
+ function filter$1(content, items) {
+ global$6.each(items, function (v) {
+ if (v.constructor === RegExp) {
+ content = content.replace(v, '');
+ } else {
+ content = content.replace(v[0], v[1]);
+ }
+ });
+ return content;
+ }
+ function innerText(html) {
+ var schema = global$a();
+ var domParser = global$7({}, schema);
+ var text = '';
+ var shortEndedElements = schema.getShortEndedElements();
+ var ignoreElements = global$6.makeMap('script noscript style textarea video audio iframe object', ' ');
+ var blockElements = schema.getBlockElements();
+ function walk(node) {
+ var name = node.name, currentNode = node;
+ if (name === 'br') {
+ text += '\n';
+ return;
+ }
+ if (name === 'wbr') {
+ return;
+ }
+ if (shortEndedElements[name]) {
+ text += ' ';
+ }
+ if (ignoreElements[name]) {
+ text += ' ';
+ return;
+ }
+ if (node.type === 3) {
+ text += node.value;
+ }
+ if (!node.shortEnded) {
+ if (node = node.firstChild) {
+ do {
+ walk(node);
+ } while (node = node.next);
+ }
+ }
+ if (blockElements[name] && currentNode.next) {
+ text += '\n';
+ if (name === 'p') {
+ text += '\n';
+ }
+ }
+ }
+ html = filter$1(html, [//g]);
+ walk(domParser.parse(html));
+ return text;
+ }
+ function trimHtml(html) {
+ function trimSpaces(all, s1, s2) {
+ if (!s1 && !s2) {
+ return ' ';
+ }
+ return nbsp;
+ }
+ html = filter$1(html, [
+ /^[\s\S]*]*>\s*|\s*<\/body[^>]*>[\s\S]*$/ig,
+ /|/g,
+ [
+ /( ?)\u00a0<\/span>( ?)/g,
+ trimSpaces
+ ],
+ /
/g,
+ /
$/i
+ ]);
+ return html;
+ }
+ function createIdGenerator(prefix) {
+ var count = 0;
+ return function () {
+ return prefix + count++;
+ };
+ }
+
+ function isWordContent(content) {
+ return / 1) {
+ currentListNode.attr('start', '' + start);
+ }
+ paragraphNode.wrap(currentListNode);
+ } else {
+ currentListNode.append(paragraphNode);
+ }
+ paragraphNode.name = 'li';
+ if (level > lastLevel && prevListNode) {
+ prevListNode.lastChild.append(currentListNode);
+ }
+ lastLevel = level;
+ removeIgnoredNodes(paragraphNode);
+ trimListStart(paragraphNode, /^\u00a0+/);
+ trimListStart(paragraphNode, /^\s*([\u2022\u00b7\u00a7\u25CF]|\w+\.)/);
+ trimListStart(paragraphNode, /^\u00a0+/);
+ }
+ var elements = [];
+ var child = node.firstChild;
+ while (typeof child !== 'undefined' && child !== null) {
+ elements.push(child);
+ child = child.walk();
+ if (child !== null) {
+ while (typeof child !== 'undefined' && child.parent !== node) {
+ child = child.walk();
+ }
+ }
+ }
+ for (var i = 0; i < elements.length; i++) {
+ node = elements[i];
+ if (node.name === 'p' && node.firstChild) {
+ var nodeText = getText(node);
+ if (isBulletList(nodeText)) {
+ convertParagraphToLi(node, 'ul');
+ continue;
+ }
+ if (isNumericList(nodeText)) {
+ var matches = /([0-9]+)\./.exec(nodeText);
+ var start = 1;
+ if (matches) {
+ start = parseInt(matches[1], 10);
+ }
+ convertParagraphToLi(node, 'ol', start);
+ continue;
+ }
+ if (node._listLevel) {
+ convertParagraphToLi(node, 'ul', 1);
+ continue;
+ }
+ currentListNode = null;
+ } else {
+ prevListNode = currentListNode;
+ currentListNode = null;
+ }
+ }
+ }
+ function filterStyles(editor, validStyles, node, styleValue) {
+ var outputStyles = {}, matches;
+ var styles = editor.dom.parseStyle(styleValue);
+ global$6.each(styles, function (value, name) {
+ switch (name) {
+ case 'mso-list':
+ matches = /\w+ \w+([0-9]+)/i.exec(styleValue);
+ if (matches) {
+ node._listLevel = parseInt(matches[1], 10);
+ }
+ if (/Ignore/i.test(value) && node.firstChild) {
+ node._listIgnore = true;
+ node.firstChild._listIgnore = true;
+ }
+ break;
+ case 'horiz-align':
+ name = 'text-align';
+ break;
+ case 'vert-align':
+ name = 'vertical-align';
+ break;
+ case 'font-color':
+ case 'mso-foreground':
+ name = 'color';
+ break;
+ case 'mso-background':
+ case 'mso-highlight':
+ name = 'background';
+ break;
+ case 'font-weight':
+ case 'font-style':
+ if (value !== 'normal') {
+ outputStyles[name] = value;
+ }
+ return;
+ case 'mso-element':
+ if (/^(comment|comment-list)$/i.test(value)) {
+ node.remove();
+ return;
+ }
+ break;
+ }
+ if (name.indexOf('mso-comment') === 0) {
+ node.remove();
+ return;
+ }
+ if (name.indexOf('mso-') === 0) {
+ return;
+ }
+ if (getRetainStyleProps(editor) === 'all' || validStyles && validStyles[name]) {
+ outputStyles[name] = value;
+ }
+ });
+ if (/(bold)/i.test(outputStyles['font-weight'])) {
+ delete outputStyles['font-weight'];
+ node.wrap(new global$9('b', 1));
+ }
+ if (/(italic)/i.test(outputStyles['font-style'])) {
+ delete outputStyles['font-style'];
+ node.wrap(new global$9('i', 1));
+ }
+ outputStyles = editor.dom.serializeStyle(outputStyles, node.name);
+ if (outputStyles) {
+ return outputStyles;
+ }
+ return null;
+ }
+ var filterWordContent = function (editor, content) {
+ var validStyles;
+ var retainStyleProperties = getRetainStyleProps(editor);
+ if (retainStyleProperties) {
+ validStyles = global$6.makeMap(retainStyleProperties.split(/[, ]/));
+ }
+ content = filter$1(content, [
+ /
/gi,
+ /]+id="?docs-internal-[^>]*>/gi,
+ //gi,
+ /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
+ [
+ /<(\/?)s>/gi,
+ '<$1strike>'
+ ],
+ [
+ / /gi,
+ nbsp
+ ],
+ [
+ /([\s\u00a0]*)<\/span>/gi,
+ function (str, spaces) {
+ return spaces.length > 0 ? spaces.replace(/./, ' ').slice(Math.floor(spaces.length / 2)).split('').join(nbsp) : '';
+ }
+ ]
+ ]);
+ var validElements = getWordValidElements(editor);
+ var schema = global$a({
+ valid_elements: validElements,
+ valid_children: '-li[p]'
+ });
+ global$6.each(schema.elements, function (rule) {
+ if (!rule.attributes.class) {
+ rule.attributes.class = {};
+ rule.attributesOrder.push('class');
+ }
+ if (!rule.attributes.style) {
+ rule.attributes.style = {};
+ rule.attributesOrder.push('style');
+ }
+ });
+ var domParser = global$7({}, schema);
+ domParser.addAttributeFilter('style', function (nodes) {
+ var i = nodes.length, node;
+ while (i--) {
+ node = nodes[i];
+ node.attr('style', filterStyles(editor, validStyles, node, node.attr('style')));
+ if (node.name === 'span' && node.parent && !node.attributes.length) {
+ node.unwrap();
+ }
+ }
+ });
+ domParser.addAttributeFilter('class', function (nodes) {
+ var i = nodes.length, node, className;
+ while (i--) {
+ node = nodes[i];
+ className = node.attr('class');
+ if (/^(MsoCommentReference|MsoCommentText|msoDel)$/i.test(className)) {
+ node.remove();
+ }
+ node.attr('class', null);
+ }
+ });
+ domParser.addNodeFilter('del', function (nodes) {
+ var i = nodes.length;
+ while (i--) {
+ nodes[i].remove();
+ }
+ });
+ domParser.addNodeFilter('a', function (nodes) {
+ var i = nodes.length, node, href, name;
+ while (i--) {
+ node = nodes[i];
+ href = node.attr('href');
+ name = node.attr('name');
+ if (href && href.indexOf('#_msocom_') !== -1) {
+ node.remove();
+ continue;
+ }
+ if (href && href.indexOf('file://') === 0) {
+ href = href.split('#')[1];
+ if (href) {
+ href = '#' + href;
+ }
+ }
+ if (!href && !name) {
+ node.unwrap();
+ } else {
+ if (name && !/^_?(?:toc|edn|ftn)/i.test(name)) {
+ node.unwrap();
+ continue;
+ }
+ node.attr({
+ href: href,
+ name: name
+ });
+ }
+ }
+ });
+ var rootNode = domParser.parse(content);
+ if (shouldConvertWordFakeLists(editor)) {
+ convertFakeListsToProperLists(rootNode);
+ }
+ content = global$8({ validate: getValidate(editor) }, schema).serialize(rootNode);
+ return content;
+ };
+ var preProcess = function (editor, content) {
+ return shouldUseDefaultFilters(editor) ? filterWordContent(editor, content) : content;
+ };
+
+ var preProcess$1 = function (editor, html) {
+ var parser = global$7({}, editor.schema);
+ parser.addNodeFilter('meta', function (nodes) {
+ global$6.each(nodes, function (node) {
+ node.remove();
+ });
+ });
+ var fragment = parser.parse(html, {
+ forced_root_block: false,
+ isRootContent: true
+ });
+ return global$8({ validate: getValidate(editor) }, editor.schema).serialize(fragment);
+ };
+ var processResult = function (content, cancelled) {
+ return {
+ content: content,
+ cancelled: cancelled
+ };
+ };
+ var postProcessFilter = function (editor, html, internal, isWordHtml) {
+ var tempBody = editor.dom.create('div', { style: 'display:none' }, html);
+ var postProcessArgs = firePastePostProcess(editor, tempBody, internal, isWordHtml);
+ return processResult(postProcessArgs.node.innerHTML, postProcessArgs.isDefaultPrevented());
+ };
+ var filterContent = function (editor, content, internal, isWordHtml) {
+ var preProcessArgs = firePastePreProcess(editor, content, internal, isWordHtml);
+ var filteredContent = preProcess$1(editor, preProcessArgs.content);
+ if (editor.hasEventListeners('PastePostProcess') && !preProcessArgs.isDefaultPrevented()) {
+ return postProcessFilter(editor, filteredContent, internal, isWordHtml);
+ } else {
+ return processResult(filteredContent, preProcessArgs.isDefaultPrevented());
+ }
+ };
+ var process = function (editor, html, internal) {
+ var isWordHtml = isWordContent(html);
+ var content = isWordHtml ? preProcess(editor, html) : html;
+ return filterContent(editor, content, internal, isWordHtml);
+ };
+
+ var pasteHtml = function (editor, html) {
+ editor.insertContent(html, {
+ merge: shouldMergeFormats(editor),
+ paste: true
+ });
+ return true;
+ };
+ var isAbsoluteUrl = function (url) {
+ return /^https?:\/\/[\w\?\-\/+=.&%@~#]+$/i.test(url);
+ };
+ var isImageUrl = function (url) {
+ return isAbsoluteUrl(url) && /.(gif|jpe?g|png)$/.test(url);
+ };
+ var createImage = function (editor, url, pasteHtmlFn) {
+ editor.undoManager.extra(function () {
+ pasteHtmlFn(editor, url);
+ }, function () {
+ editor.insertContent('');
+ });
+ return true;
+ };
+ var createLink = function (editor, url, pasteHtmlFn) {
+ editor.undoManager.extra(function () {
+ pasteHtmlFn(editor, url);
+ }, function () {
+ editor.execCommand('mceInsertLink', false, url);
+ });
+ return true;
+ };
+ var linkSelection = function (editor, html, pasteHtmlFn) {
+ return editor.selection.isCollapsed() === false && isAbsoluteUrl(html) ? createLink(editor, html, pasteHtmlFn) : false;
+ };
+ var insertImage = function (editor, html, pasteHtmlFn) {
+ return isImageUrl(html) ? createImage(editor, html, pasteHtmlFn) : false;
+ };
+ var smartInsertContent = function (editor, html) {
+ global$6.each([
+ linkSelection,
+ insertImage,
+ pasteHtml
+ ], function (action) {
+ return action(editor, html, pasteHtml) !== true;
+ });
+ };
+ var insertContent = function (editor, html, pasteAsText) {
+ if (pasteAsText || isSmartPasteEnabled(editor) === false) {
+ pasteHtml(editor, html);
+ } else {
+ smartInsertContent(editor, html);
+ }
+ };
+
+ var repeat = function (s, count) {
+ return count <= 0 ? '' : new Array(count + 1).join(s);
+ };
+
+ var isCollapsibleWhitespace = function (c) {
+ return ' \f\t\x0B'.indexOf(c) !== -1;
+ };
+ var isNewLineChar = function (c) {
+ return c === '\n' || c === '\r';
+ };
+ var isNewline = function (text, idx) {
+ return idx < text.length && idx >= 0 ? isNewLineChar(text[idx]) : false;
+ };
+ var normalizeWhitespace = function (editor, text) {
+ var tabSpace = repeat(' ', getTabSpaces(editor));
+ var normalizedText = text.replace(/\t/g, tabSpace);
+ var result = foldl(normalizedText, function (acc, c) {
+ if (isCollapsibleWhitespace(c) || c === nbsp) {
+ if (acc.pcIsSpace || acc.str === '' || acc.str.length === normalizedText.length - 1 || isNewline(normalizedText, acc.str.length + 1)) {
+ return {
+ pcIsSpace: false,
+ str: acc.str + nbsp
+ };
+ } else {
+ return {
+ pcIsSpace: true,
+ str: acc.str + ' '
+ };
+ }
+ } else {
+ return {
+ pcIsSpace: isNewLineChar(c),
+ str: acc.str + c
+ };
+ }
+ }, {
+ pcIsSpace: false,
+ str: ''
+ });
+ return result.str;
+ };
+
+ var doPaste = function (editor, content, internal, pasteAsText) {
+ var args = process(editor, content, internal);
+ if (args.cancelled === false) {
+ insertContent(editor, args.content, pasteAsText);
+ }
+ };
+ var pasteHtml$1 = function (editor, html, internalFlag) {
+ var internal = internalFlag ? internalFlag : isMarked(html);
+ doPaste(editor, unmark(html), internal, false);
+ };
+ var pasteText = function (editor, text) {
+ var encodedText = editor.dom.encode(text).replace(/\r\n/g, '\n');
+ var normalizedText = normalizeWhitespace(editor, encodedText);
+ var html = convert(normalizedText, getForcedRootBlock(editor), getForcedRootBlockAttrs(editor));
+ doPaste(editor, html, false, true);
+ };
+ var getDataTransferItems = function (dataTransfer) {
+ var items = {};
+ var mceInternalUrlPrefix = 'data:text/mce-internal,';
+ if (dataTransfer) {
+ if (dataTransfer.getData) {
+ var legacyText = dataTransfer.getData('Text');
+ if (legacyText && legacyText.length > 0) {
+ if (legacyText.indexOf(mceInternalUrlPrefix) === -1) {
+ items['text/plain'] = legacyText;
+ }
+ }
+ }
+ if (dataTransfer.types) {
+ for (var i = 0; i < dataTransfer.types.length; i++) {
+ var contentType = dataTransfer.types[i];
+ try {
+ items[contentType] = dataTransfer.getData(contentType);
+ } catch (ex) {
+ items[contentType] = '';
+ }
+ }
+ }
+ }
+ return items;
+ };
+ var getClipboardContent = function (editor, clipboardEvent) {
+ return getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer);
+ };
+ var hasContentType = function (clipboardContent, mimeType) {
+ return mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
+ };
+ var hasHtmlOrText = function (content) {
+ return hasContentType(content, 'text/html') || hasContentType(content, 'text/plain');
+ };
+ var parseDataUri = function (uri) {
+ var matches = /data:([^;]+);base64,([a-z0-9\+\/=]+)/i.exec(uri);
+ if (matches) {
+ return {
+ type: matches[1],
+ data: decodeURIComponent(matches[2])
+ };
+ } else {
+ return {
+ type: null,
+ data: null
+ };
+ }
+ };
+ var isValidDataUriImage = function (editor, imgElm) {
+ var filter = getImagesDataImgFilter(editor);
+ return filter ? filter(imgElm) : true;
+ };
+ var extractFilename = function (editor, str) {
+ var m = str.match(/([\s\S]+?)\.(?:jpeg|jpg|png|gif)$/i);
+ return m ? editor.dom.encode(m[1]) : null;
+ };
+ var uniqueId = createIdGenerator('mceclip');
+ var pasteImage = function (editor, imageItem) {
+ var _a = parseDataUri(imageItem.uri), base64 = _a.data, type = _a.type;
+ var id = uniqueId();
+ var name = getImagesReuseFilename(editor) && imageItem.blob.name ? extractFilename(editor, imageItem.blob.name) : id;
+ var img = new Image();
+ img.src = imageItem.uri;
+ if (isValidDataUriImage(editor, img)) {
+ var blobCache = editor.editorUpload.blobCache;
+ var blobInfo = void 0;
+ var existingBlobInfo = blobCache.getByData(base64, type);
+ if (!existingBlobInfo) {
+ blobInfo = blobCache.create(id, imageItem.blob, base64, name);
+ blobCache.add(blobInfo);
+ } else {
+ blobInfo = existingBlobInfo;
+ }
+ pasteHtml$1(editor, '
', false);
+ } else {
+ pasteHtml$1(editor, '
', false);
+ }
+ };
+ var isClipboardEvent = function (event) {
+ return event.type === 'paste';
+ };
+ var readBlobsAsDataUris = function (items) {
+ return global$3.all(map(items, function (item) {
+ return new global$3(function (resolve) {
+ var blob = item.getAsFile ? item.getAsFile() : item;
+ var reader = new window.FileReader();
+ reader.onload = function () {
+ resolve({
+ blob: blob,
+ uri: reader.result
+ });
+ };
+ reader.readAsDataURL(blob);
+ });
+ }));
+ };
+ var getImagesFromDataTransfer = function (dataTransfer) {
+ var items = dataTransfer.items ? map(from$1(dataTransfer.items), function (item) {
+ return item.getAsFile();
+ }) : [];
+ var files = dataTransfer.files ? from$1(dataTransfer.files) : [];
+ var images = filter(items.length > 0 ? items : files, function (file) {
+ return /^image\/(jpeg|png|gif|bmp)$/.test(file.type);
+ });
+ return images;
+ };
+ var pasteImageData = function (editor, e, rng) {
+ var dataTransfer = isClipboardEvent(e) ? e.clipboardData : e.dataTransfer;
+ if (getPasteDataImages(editor) && dataTransfer) {
+ var images = getImagesFromDataTransfer(dataTransfer);
+ if (images.length > 0) {
+ e.preventDefault();
+ readBlobsAsDataUris(images).then(function (blobResults) {
+ if (rng) {
+ editor.selection.setRng(rng);
+ }
+ each(blobResults, function (result) {
+ pasteImage(editor, result);
+ });
+ });
+ return true;
+ }
+ }
+ return false;
+ };
+ var isBrokenAndroidClipboardEvent = function (e) {
+ var clipboardData = e.clipboardData;
+ return navigator.userAgent.indexOf('Android') !== -1 && clipboardData && clipboardData.items && clipboardData.items.length === 0;
+ };
+ var isKeyboardPasteEvent = function (e) {
+ return global$4.metaKeyPressed(e) && e.keyCode === 86 || e.shiftKey && e.keyCode === 45;
+ };
+ var registerEventHandlers = function (editor, pasteBin, pasteFormat) {
+ var keyboardPasteEvent = value();
+ var keyboardPastePlainTextState;
+ editor.on('keydown', function (e) {
+ function removePasteBinOnKeyUp(e) {
+ if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
+ pasteBin.remove();
+ }
+ }
+ if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
+ keyboardPastePlainTextState = e.shiftKey && e.keyCode === 86;
+ if (keyboardPastePlainTextState && global$1.webkit && navigator.userAgent.indexOf('Version/') !== -1) {
+ return;
+ }
+ e.stopImmediatePropagation();
+ keyboardPasteEvent.set(e);
+ window.setTimeout(function () {
+ keyboardPasteEvent.clear();
+ }, 100);
+ if (global$1.ie && keyboardPastePlainTextState) {
+ e.preventDefault();
+ firePaste(editor, true);
+ return;
+ }
+ pasteBin.remove();
+ pasteBin.create();
+ editor.once('keyup', removePasteBinOnKeyUp);
+ editor.once('paste', function () {
+ editor.off('keyup', removePasteBinOnKeyUp);
+ });
+ }
+ });
+ function insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal) {
+ var content;
+ if (hasContentType(clipboardContent, 'text/html')) {
+ content = clipboardContent['text/html'];
+ } else {
+ content = pasteBin.getHtml();
+ internal = internal ? internal : isMarked(content);
+ if (pasteBin.isDefaultContent(content)) {
+ plainTextMode = true;
+ }
+ }
+ content = trimHtml(content);
+ pasteBin.remove();
+ var isPlainTextHtml = internal === false && isPlainText(content);
+ var isImage = isImageUrl(content);
+ if (!content.length || isPlainTextHtml && !isImage) {
+ plainTextMode = true;
+ }
+ if (plainTextMode || isImage) {
+ if (hasContentType(clipboardContent, 'text/plain') && isPlainTextHtml) {
+ content = clipboardContent['text/plain'];
+ } else {
+ content = innerText(content);
+ }
+ }
+ if (pasteBin.isDefaultContent(content)) {
+ if (!isKeyBoardPaste) {
+ editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.');
+ }
+ return;
+ }
+ if (plainTextMode) {
+ pasteText(editor, content);
+ } else {
+ pasteHtml$1(editor, content, internal);
+ }
+ }
+ var getLastRng = function () {
+ return pasteBin.getLastRng() || editor.selection.getRng();
+ };
+ editor.on('paste', function (e) {
+ var isKeyBoardPaste = keyboardPasteEvent.isSet();
+ var clipboardContent = getClipboardContent(editor, e);
+ var plainTextMode = pasteFormat.get() === 'text' || keyboardPastePlainTextState;
+ var internal = hasContentType(clipboardContent, internalHtmlMime());
+ keyboardPastePlainTextState = false;
+ if (e.isDefaultPrevented() || isBrokenAndroidClipboardEvent(e)) {
+ pasteBin.remove();
+ return;
+ }
+ if (!hasHtmlOrText(clipboardContent) && pasteImageData(editor, e, getLastRng())) {
+ pasteBin.remove();
+ return;
+ }
+ if (!isKeyBoardPaste) {
+ e.preventDefault();
+ }
+ if (global$1.ie && (!isKeyBoardPaste || e.ieFake) && !hasContentType(clipboardContent, 'text/html')) {
+ pasteBin.create();
+ editor.dom.bind(pasteBin.getEl(), 'paste', function (e) {
+ e.stopPropagation();
+ });
+ editor.getDoc().execCommand('Paste', false, null);
+ clipboardContent['text/html'] = pasteBin.getHtml();
+ }
+ if (hasContentType(clipboardContent, 'text/html')) {
+ e.preventDefault();
+ if (!internal) {
+ internal = isMarked(clipboardContent['text/html']);
+ }
+ insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal);
+ } else {
+ global$2.setEditorTimeout(editor, function () {
+ insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal);
+ }, 0);
+ }
+ });
+ };
+ var registerEventsAndFilters = function (editor, pasteBin, pasteFormat) {
+ registerEventHandlers(editor, pasteBin, pasteFormat);
+ var src;
+ editor.parser.addNodeFilter('img', function (nodes, name, args) {
+ var isPasteInsert = function (args) {
+ return args.data && args.data.paste === true;
+ };
+ var remove = function (node) {
+ if (!node.attr('data-mce-object') && src !== global$1.transparentSrc) {
+ node.remove();
+ }
+ };
+ var isWebKitFakeUrl = function (src) {
+ return src.indexOf('webkit-fake-url') === 0;
+ };
+ var isDataUri = function (src) {
+ return src.indexOf('data:') === 0;
+ };
+ if (!getPasteDataImages(editor) && isPasteInsert(args)) {
+ var i = nodes.length;
+ while (i--) {
+ src = nodes[i].attr('src');
+ if (!src) {
+ continue;
+ }
+ if (isWebKitFakeUrl(src)) {
+ remove(nodes[i]);
+ } else if (!getAllowHtmlDataUrls(editor) && isDataUri(src)) {
+ remove(nodes[i]);
+ }
+ }
+ }
+ });
+ };
+
+ var getPasteBinParent = function (editor) {
+ return global$1.ie && editor.inline ? document.body : editor.getBody();
+ };
+ var isExternalPasteBin = function (editor) {
+ return getPasteBinParent(editor) !== editor.getBody();
+ };
+ var delegatePasteEvents = function (editor, pasteBinElm, pasteBinDefaultContent) {
+ if (isExternalPasteBin(editor)) {
+ editor.dom.bind(pasteBinElm, 'paste keyup', function (_e) {
+ if (!isDefault(editor, pasteBinDefaultContent)) {
+ editor.fire('paste');
+ }
+ });
+ }
+ };
+ var create = function (editor, lastRngCell, pasteBinDefaultContent) {
+ var dom = editor.dom, body = editor.getBody();
+ lastRngCell.set(editor.selection.getRng());
+ var pasteBinElm = editor.dom.add(getPasteBinParent(editor), 'div', {
+ 'id': 'mcepastebin',
+ 'class': 'mce-pastebin',
+ 'contentEditable': true,
+ 'data-mce-bogus': 'all',
+ 'style': 'position: fixed; top: 50%; width: 10px; height: 10px; overflow: hidden; opacity: 0'
+ }, pasteBinDefaultContent);
+ if (global$1.ie || global$1.gecko) {
+ dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) === 'rtl' ? 65535 : -65535);
+ }
+ dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function (e) {
+ e.stopPropagation();
+ });
+ delegatePasteEvents(editor, pasteBinElm, pasteBinDefaultContent);
+ pasteBinElm.focus();
+ editor.selection.select(pasteBinElm, true);
+ };
+ var remove = function (editor, lastRngCell) {
+ if (getEl(editor)) {
+ var pasteBinClone = void 0;
+ var lastRng = lastRngCell.get();
+ while (pasteBinClone = editor.dom.get('mcepastebin')) {
+ editor.dom.remove(pasteBinClone);
+ editor.dom.unbind(pasteBinClone);
+ }
+ if (lastRng) {
+ editor.selection.setRng(lastRng);
+ }
+ }
+ lastRngCell.set(null);
+ };
+ var getEl = function (editor) {
+ return editor.dom.get('mcepastebin');
+ };
+ var getHtml = function (editor) {
+ var copyAndRemove = function (toElm, fromElm) {
+ toElm.appendChild(fromElm);
+ editor.dom.remove(fromElm, true);
+ };
+ var pasteBinClones = global$6.grep(getPasteBinParent(editor).childNodes, function (elm) {
+ return elm.id === 'mcepastebin';
+ });
+ var pasteBinElm = pasteBinClones.shift();
+ global$6.each(pasteBinClones, function (pasteBinClone) {
+ copyAndRemove(pasteBinElm, pasteBinClone);
+ });
+ var dirtyWrappers = editor.dom.select('div[id=mcepastebin]', pasteBinElm);
+ for (var i = dirtyWrappers.length - 1; i >= 0; i--) {
+ var cleanWrapper = editor.dom.create('div');
+ pasteBinElm.insertBefore(cleanWrapper, dirtyWrappers[i]);
+ copyAndRemove(cleanWrapper, dirtyWrappers[i]);
+ }
+ return pasteBinElm ? pasteBinElm.innerHTML : '';
+ };
+ var getLastRng = function (lastRng) {
+ return lastRng.get();
+ };
+ var isDefaultContent = function (pasteBinDefaultContent, content) {
+ return content === pasteBinDefaultContent;
+ };
+ var isPasteBin = function (elm) {
+ return elm && elm.id === 'mcepastebin';
+ };
+ var isDefault = function (editor, pasteBinDefaultContent) {
+ var pasteBinElm = getEl(editor);
+ return isPasteBin(pasteBinElm) && isDefaultContent(pasteBinDefaultContent, pasteBinElm.innerHTML);
+ };
+ var PasteBin = function (editor) {
+ var lastRng = Cell(null);
+ var pasteBinDefaultContent = '%MCEPASTEBIN%';
+ return {
+ create: function () {
+ return create(editor, lastRng, pasteBinDefaultContent);
+ },
+ remove: function () {
+ return remove(editor, lastRng);
+ },
+ getEl: function () {
+ return getEl(editor);
+ },
+ getHtml: function () {
+ return getHtml(editor);
+ },
+ getLastRng: function () {
+ return getLastRng(lastRng);
+ },
+ isDefault: function () {
+ return isDefault(editor, pasteBinDefaultContent);
+ },
+ isDefaultContent: function (content) {
+ return isDefaultContent(pasteBinDefaultContent, content);
+ }
+ };
+ };
+
+ var Clipboard = function (editor, pasteFormat) {
+ var pasteBin = PasteBin(editor);
+ editor.on('PreInit', function () {
+ return registerEventsAndFilters(editor, pasteBin, pasteFormat);
+ });
+ return {
+ pasteFormat: pasteFormat,
+ pasteHtml: function (html, internalFlag) {
+ return pasteHtml$1(editor, html, internalFlag);
+ },
+ pasteText: function (text) {
+ return pasteText(editor, text);
+ },
+ pasteImageData: function (e, rng) {
+ return pasteImageData(editor, e, rng);
+ },
+ getDataTransferItems: getDataTransferItems,
+ hasHtmlOrText: hasHtmlOrText,
+ hasContentType: hasContentType
+ };
+ };
+
+ var togglePlainTextPaste = function (editor, clipboard) {
+ if (clipboard.pasteFormat.get() === 'text') {
+ clipboard.pasteFormat.set('html');
+ firePastePlainTextToggle(editor, false);
+ } else {
+ clipboard.pasteFormat.set('text');
+ firePastePlainTextToggle(editor, true);
+ }
+ editor.focus();
+ };
+
+ var register = function (editor, clipboard) {
+ editor.addCommand('mceTogglePlainTextPaste', function () {
+ togglePlainTextPaste(editor, clipboard);
+ });
+ editor.addCommand('mceInsertClipboardContent', function (ui, value) {
+ if (value.content) {
+ clipboard.pasteHtml(value.content, value.internal);
+ }
+ if (value.text) {
+ clipboard.pasteText(value.text);
+ }
+ });
+ };
+
+ var hasWorkingClipboardApi = function (clipboardData) {
+ return global$1.iOS === false && typeof (clipboardData === null || clipboardData === void 0 ? void 0 : clipboardData.setData) === 'function';
+ };
+ var setHtml5Clipboard = function (clipboardData, html, text) {
+ if (hasWorkingClipboardApi(clipboardData)) {
+ try {
+ clipboardData.clearData();
+ clipboardData.setData('text/html', html);
+ clipboardData.setData('text/plain', text);
+ clipboardData.setData(internalHtmlMime(), html);
+ return true;
+ } catch (e) {
+ return false;
+ }
+ } else {
+ return false;
+ }
+ };
+ var setClipboardData = function (evt, data, fallback, done) {
+ if (setHtml5Clipboard(evt.clipboardData, data.html, data.text)) {
+ evt.preventDefault();
+ done();
+ } else {
+ fallback(data.html, done);
+ }
+ };
+ var fallback = function (editor) {
+ return function (html, done) {
+ var markedHtml = mark(html);
+ var outer = editor.dom.create('div', {
+ 'contenteditable': 'false',
+ 'data-mce-bogus': 'all'
+ });
+ var inner = editor.dom.create('div', { contenteditable: 'true' }, markedHtml);
+ editor.dom.setStyles(outer, {
+ position: 'fixed',
+ top: '0',
+ left: '-3000px',
+ width: '1000px',
+ overflow: 'hidden'
+ });
+ outer.appendChild(inner);
+ editor.dom.add(editor.getBody(), outer);
+ var range = editor.selection.getRng();
+ inner.focus();
+ var offscreenRange = editor.dom.createRng();
+ offscreenRange.selectNodeContents(inner);
+ editor.selection.setRng(offscreenRange);
+ global$2.setTimeout(function () {
+ editor.selection.setRng(range);
+ outer.parentNode.removeChild(outer);
+ done();
+ }, 0);
+ };
+ };
+ var getData = function (editor) {
+ return {
+ html: editor.selection.getContent({ contextual: true }),
+ text: editor.selection.getContent({ format: 'text' })
+ };
+ };
+ var isTableSelection = function (editor) {
+ return !!editor.dom.getParent(editor.selection.getStart(), 'td[data-mce-selected],th[data-mce-selected]', editor.getBody());
+ };
+ var hasSelectedContent = function (editor) {
+ return !editor.selection.isCollapsed() || isTableSelection(editor);
+ };
+ var cut = function (editor) {
+ return function (evt) {
+ if (hasSelectedContent(editor)) {
+ setClipboardData(evt, getData(editor), fallback(editor), function () {
+ if (global$1.browser.isChrome()) {
+ var rng_1 = editor.selection.getRng();
+ global$2.setEditorTimeout(editor, function () {
+ editor.selection.setRng(rng_1);
+ editor.execCommand('Delete');
+ }, 0);
+ } else {
+ editor.execCommand('Delete');
+ }
+ });
+ }
+ };
+ };
+ var copy = function (editor) {
+ return function (evt) {
+ if (hasSelectedContent(editor)) {
+ setClipboardData(evt, getData(editor), fallback(editor), function () {
+ });
+ }
+ };
+ };
+ var register$1 = function (editor) {
+ editor.on('cut', cut(editor));
+ editor.on('copy', copy(editor));
+ };
+
+ var global$b = tinymce.util.Tools.resolve('tinymce.dom.RangeUtils');
+
+ var getCaretRangeFromEvent = function (editor, e) {
+ return global$b.getCaretRangeFromPoint(e.clientX, e.clientY, editor.getDoc());
+ };
+ var isPlainTextFileUrl = function (content) {
+ var plainTextContent = content['text/plain'];
+ return plainTextContent ? plainTextContent.indexOf('file://') === 0 : false;
+ };
+ var setFocusedRange = function (editor, rng) {
+ editor.focus();
+ editor.selection.setRng(rng);
+ };
+ var setup = function (editor, clipboard, draggingInternallyState) {
+ if (shouldBlockDrop(editor)) {
+ editor.on('dragend dragover draggesture dragdrop drop drag', function (e) {
+ e.preventDefault();
+ e.stopPropagation();
+ });
+ }
+ if (!shouldPasteDataImages(editor)) {
+ editor.on('drop', function (e) {
+ var dataTransfer = e.dataTransfer;
+ if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
+ e.preventDefault();
+ }
+ });
+ }
+ editor.on('drop', function (e) {
+ var rng = getCaretRangeFromEvent(editor, e);
+ if (e.isDefaultPrevented() || draggingInternallyState.get()) {
+ return;
+ }
+ var dropContent = clipboard.getDataTransferItems(e.dataTransfer);
+ var internal = clipboard.hasContentType(dropContent, internalHtmlMime());
+ if ((!clipboard.hasHtmlOrText(dropContent) || isPlainTextFileUrl(dropContent)) && clipboard.pasteImageData(e, rng)) {
+ return;
+ }
+ if (rng && shouldFilterDrop(editor)) {
+ var content_1 = dropContent['mce-internal'] || dropContent['text/html'] || dropContent['text/plain'];
+ if (content_1) {
+ e.preventDefault();
+ global$2.setEditorTimeout(editor, function () {
+ editor.undoManager.transact(function () {
+ if (dropContent['mce-internal']) {
+ editor.execCommand('Delete');
+ }
+ setFocusedRange(editor, rng);
+ content_1 = trimHtml(content_1);
+ if (!dropContent['text/html']) {
+ clipboard.pasteText(content_1);
+ } else {
+ clipboard.pasteHtml(content_1, internal);
+ }
+ });
+ });
+ }
+ }
+ });
+ editor.on('dragstart', function (_e) {
+ draggingInternallyState.set(true);
+ });
+ editor.on('dragover dragend', function (e) {
+ if (shouldPasteDataImages(editor) && draggingInternallyState.get() === false) {
+ e.preventDefault();
+ setFocusedRange(editor, getCaretRangeFromEvent(editor, e));
+ }
+ if (e.type === 'dragend') {
+ draggingInternallyState.set(false);
+ }
+ });
+ };
+
+ var setup$1 = function (editor) {
+ var plugin = editor.plugins.paste;
+ var preProcess = getPreProcess(editor);
+ if (preProcess) {
+ editor.on('PastePreProcess', function (e) {
+ preProcess.call(plugin, plugin, e);
+ });
+ }
+ var postProcess = getPostProcess(editor);
+ if (postProcess) {
+ editor.on('PastePostProcess', function (e) {
+ postProcess.call(plugin, plugin, e);
+ });
+ }
+ };
+
+ function addPreProcessFilter(editor, filterFunc) {
+ editor.on('PastePreProcess', function (e) {
+ e.content = filterFunc(editor, e.content, e.internal, e.wordContent);
+ });
+ }
+ function addPostProcessFilter(editor, filterFunc) {
+ editor.on('PastePostProcess', function (e) {
+ filterFunc(editor, e.node);
+ });
+ }
+ function removeExplorerBrElementsAfterBlocks(editor, html) {
+ if (!isWordContent(html)) {
+ return html;
+ }
+ var blockElements = [];
+ global$6.each(editor.schema.getBlockElements(), function (block, blockName) {
+ blockElements.push(blockName);
+ });
+ var explorerBlocksRegExp = new RegExp('(?:
[\\s\\r\\n]+|
)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:
[\\s\\r\\n]+|
)*', 'g');
+ html = filter$1(html, [[
+ explorerBlocksRegExp,
+ '$1'
+ ]]);
+ html = filter$1(html, [
+ [
+ /
/g,
+ '
'
+ ],
+ [
+ /
/g,
+ ' '
+ ],
+ [
+ /
/g,
+ '
'
+ ]
+ ]);
+ return html;
+ }
+ function removeWebKitStyles(editor, content, internal, isWordHtml) {
+ if (isWordHtml || internal) {
+ return content;
+ }
+ var webKitStylesSetting = getWebkitStyles(editor);
+ var webKitStyles;
+ if (shouldRemoveWebKitStyles(editor) === false || webKitStylesSetting === 'all') {
+ return content;
+ }
+ if (webKitStylesSetting) {
+ webKitStyles = webKitStylesSetting.split(/[, ]/);
+ }
+ if (webKitStyles) {
+ var dom_1 = editor.dom, node_1 = editor.selection.getNode();
+ content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, function (all, before, value, after) {
+ var inputStyles = dom_1.parseStyle(dom_1.decode(value));
+ var outputStyles = {};
+ if (webKitStyles === 'none') {
+ return before + after;
+ }
+ for (var i = 0; i < webKitStyles.length; i++) {
+ var inputValue = inputStyles[webKitStyles[i]], currentValue = dom_1.getStyle(node_1, webKitStyles[i], true);
+ if (/color/.test(webKitStyles[i])) {
+ inputValue = dom_1.toHex(inputValue);
+ currentValue = dom_1.toHex(currentValue);
+ }
+ if (currentValue !== inputValue) {
+ outputStyles[webKitStyles[i]] = inputValue;
+ }
+ }
+ outputStyles = dom_1.serializeStyle(outputStyles, 'span');
+ if (outputStyles) {
+ return before + ' style="' + outputStyles + '"' + after;
+ }
+ return before + after;
+ });
+ } else {
+ content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, '$1$3');
+ }
+ content = content.replace(/(<[^>]+) data-mce-style="([^"]+)"([^>]*>)/gi, function (all, before, value, after) {
+ return before + ' style="' + value + '"' + after;
+ });
+ return content;
+ }
+ function removeUnderlineAndFontInAnchor(editor, root) {
+ editor.$('a', root).find('font,u').each(function (i, node) {
+ editor.dom.remove(node, true);
+ });
+ }
+ var setup$2 = function (editor) {
+ if (global$1.webkit) {
+ addPreProcessFilter(editor, removeWebKitStyles);
+ }
+ if (global$1.ie) {
+ addPreProcessFilter(editor, removeExplorerBrElementsAfterBlocks);
+ addPostProcessFilter(editor, removeUnderlineAndFontInAnchor);
+ }
+ };
+
+ var makeSetupHandler = function (editor, clipboard) {
+ return function (api) {
+ api.setActive(clipboard.pasteFormat.get() === 'text');
+ var pastePlainTextToggleHandler = function (e) {
+ return api.setActive(e.state);
+ };
+ editor.on('PastePlainTextToggle', pastePlainTextToggleHandler);
+ return function () {
+ return editor.off('PastePlainTextToggle', pastePlainTextToggleHandler);
+ };
+ };
+ };
+ var register$2 = function (editor, clipboard) {
+ editor.ui.registry.addToggleButton('pastetext', {
+ active: false,
+ icon: 'paste-text',
+ tooltip: 'Paste as text',
+ onAction: function () {
+ return editor.execCommand('mceTogglePlainTextPaste');
+ },
+ onSetup: makeSetupHandler(editor, clipboard)
+ });
+ editor.ui.registry.addToggleMenuItem('pastetext', {
+ text: 'Paste as text',
+ icon: 'paste-text',
+ onAction: function () {
+ return editor.execCommand('mceTogglePlainTextPaste');
+ },
+ onSetup: makeSetupHandler(editor, clipboard)
+ });
+ };
+
+ function Plugin () {
+ global.add('paste', function (editor) {
+ if (hasProPlugin(editor) === false) {
+ var draggingInternallyState = Cell(false);
+ var pasteFormat = Cell(isPasteAsTextEnabled(editor) ? 'text' : 'html');
+ var clipboard = Clipboard(editor, pasteFormat);
+ var quirks = setup$2(editor);
+ register$2(editor, clipboard);
+ register(editor, clipboard);
+ setup$1(editor);
+ register$1(editor);
+ setup(editor, clipboard, draggingInternallyState);
+ return get(clipboard, quirks);
+ }
+ });
+ }
+
+ Plugin();
+
+}());
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/paste/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/paste/plugin.min.js
old mode 100755
new mode 100644
index 3cce5f864f..15160d421b
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/paste/plugin.min.js
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/paste/plugin.min.js
@@ -1 +1,9 @@
-!function(e,t){"use strict";function n(e,t){for(var n,i=[],r=0;r
"]]):(e=n.filter(e,[[/\n\n/g,"
"]]),-1!=e.indexOf("
$/i])}function s(e){if(!n.isWordContent(e))return e;var a=[];t.each(r.schema.getBlockElements(),function(e,t){a.push(t)});var o=new RegExp("(?:
[\\s\\r\\n]+|
)*(<\\/?("+a.join("|")+")[^>]*>)(?:
[\\s\\r\\n]+|
)*","g");return e=i.filter(e,[[o,"$1"]]),e=i.filter(e,[[/
/g,"
"],[/
/g," "],[/
/g,"
"]])}function c(e){return(r.settings.paste_remove_styles||r.settings.paste_remove_styles_if_webkit!==!1)&&(e=e.replace(/ style=\"[^\"]+\"/g,"")),e}e.webkit&&(a(c),a(o)),e.ie&&a(s)}}),i(b,[x,d,g,y],function(e,t,n,i){var r;e.add("paste",function(e){function a(){"text"==s.pasteFormat?(this.active(!1),s.pasteFormat="html"):(s.pasteFormat="text",this.active(!0),r||(e.windowManager.alert("Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off."),r=!0))}var o=this,s,c=e.settings;o.clipboard=s=new t(e),o.quirks=new i(e),o.wordFilter=new n(e),e.settings.paste_as_text&&(o.clipboard.pasteFormat="text"),c.paste_preprocess&&e.on("PastePreProcess",function(e){c.paste_preprocess.call(o,o,e)}),c.paste_postprocess&&e.on("PastePostProcess",function(e){c.paste_postprocess.call(o,o,e)}),e.addCommand("mceInsertClipboardContent",function(e,t){t.content&&o.clipboard.pasteHtml(t.content),t.text&&o.clipboard.pasteText(t.text)}),e.paste_block_drop&&e.on("dragend dragover draggesture dragdrop drop drag",function(e){e.preventDefault(),e.stopPropagation()}),e.settings.paste_data_images||e.on("drop",function(e){var t=e.dataTransfer;t&&t.files&&t.files.length>0&&e.preventDefault()}),e.addButton("pastetext",{icon:"pastetext",tooltip:"Paste as text",onclick:a,active:"text"==o.clipboard.pasteFormat}),e.addMenuItem("pastetext",{text:"Paste as text",selectable:!0,active:s.pasteFormat,onclick:a})})}),o([c,d,g,y,b])}(this);
\ No newline at end of file
+/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var e,t,n,r,m=function(e){var t=e;return{get:function(){return t},set:function(e){t=e}}},o=tinymce.util.Tools.resolve("tinymce.PluginManager"),a=function(e){return function(){return e}},i=a(!1),s=a(!0),u=function(){return l},l=(e=function(e){return e.isNone()},{fold:function(e,t){return e()},is:i,isSome:i,isNone:s,getOr:n=function(e){return e},getOrThunk:t=function(e){return e()},getOrDie:function(e){throw new Error(e||"error: getOrDie called on none.")},getOrNull:a(null),getOrUndefined:a(undefined),or:n,orThunk:t,map:u,each:function(){},bind:u,exists:i,forall:s,filter:u,equals:e,equals_:e,toArray:function(){return[]},toString:a("none()")}),c=function(n){var e=a(n),t=function(){return o},r=function(e){return e(n)},o={fold:function(e,t){return t(n)},is:function(e){return n===e},isSome:s,isNone:i,getOr:e,getOrThunk:e,getOrDie:e,getOrNull:e,getOrUndefined:e,or:t,orThunk:t,map:function(e){return c(e(n))},each:function(e){e(n)},bind:r,exists:r,forall:r,filter:function(e){return e(n)?o:l},toArray:function(){return[n]},toString:function(){return"some("+n+")"},equals:function(e){return e.is(n)},equals_:function(e,t){return e.fold(i,function(e){return t(n,e)})}};return o},p={some:c,none:u,from:function(e){return null===e||e===undefined?l:c(e)}},f=(r="function",function(e){return typeof e===r}),d=Array.prototype.slice,g=function(e,t){for(var n=e.length,r=new Array(n),o=0;o
")});return 1===i.length?i[0]:A.map(i,function(e){return o+e+a}).join("")},F=tinymce.util.Tools.resolve("tinymce.html.DomParser"),E=tinymce.util.Tools.resolve("tinymce.html.Serializer"),M="\xa0",N=tinymce.util.Tools.resolve("tinymce.html.Node"),B=tinymce.util.Tools.resolve("tinymce.html.Schema");function j(t,e){return A.each(e,function(e){t=e.constructor===RegExp?t.replace(e,""):t.replace(e[0],e[1])}),t}function H(e){var t=B(),n=F({},t),r="",o=t.getShortEndedElements(),a=A.makeMap("script noscript style textarea video audio iframe object"," "),i=t.getBlockElements();return e=j(e,[//g]),function s(e){var t=e.name,n=e;if("br"!==t){if("wbr"!==t)if(o[t]&&(r+=" "),a[t])r+=" ";else{if(3===e.type&&(r+=e.value),!e.shortEnded&&(e=e.firstChild))for(;s(e),e=e.next;);i[t]&&n.next&&(r+="\n","p"===t&&(r+="\n"))}}else r+="\n"}(n.parse(e)),r}function $(e){return e=j(e,[/^[\s\S]*]*>\s*|\s*<\/body[^>]*>[\s\S]*$/gi,/|/g,[/( ?)\u00a0<\/span>( ?)/g,function(e,t,n){return t||n?M:" "}],/
/g,/
$/i])}function L(e){return//gi,/]+id="?docs-internal-[^>]*>/gi,//gi,/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,[/<(\/?)s>/gi,"<$1strike>"],[/ /gi,M],[/([\s\u00a0]*)<\/span>/gi,function(e,t){return 0',!1)},fe=function(t,e,n){var r,o,a,i,s="paste"===e.type?e.clipboardData:e.dataTransfer;if(D(t)&&s){var u=(a=(o=s).items?g(h(o.items),function(e){return e.getAsFile()}):[],i=o.files?h(o.files):[],function(e,t){for(var n=[],r=0,o=e.length;r
)*(<\\/?("+n.join("|")+")[^>]*>)(?:
[\\s\\r\\n]+|
)*","g"),"$1"]]),t=j(t,[[/
/g,"
"],[/
/g," "],[/
/g,"
"]])}function Ee(e,t,n,r){if(r||n)return t;var l,c,f,o=e.getParam("paste_webkit_styles");return!1===e.getParam("paste_remove_styles_if_webkit",!0)||"all"===o?t:(o&&(l=o.split(/[, ]/)),t=(t=l?(c=e.dom,f=e.selection.getNode(),t.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi,function(e,t,n,r){var o=c.parseStyle(c.decode(n)),a={};if("none"===l)return t+r;for(var i=0;i
' : '\u00a0';
- tableElm.insertBefore(captionElm, tableElm.firstChild);
- }
-
- unApplyAlign(tableElm);
- if (data.align) {
- editor.formatter.apply('align' + data.align, {}, tableElm);
- }
-
- editor.focus();
- editor.addVisual();
- });
- }
- });
- }
-
- function mergeDialog(grid, cell) {
- editor.windowManager.open({
- title: "Merge cells",
- body: [
- {label: 'Cols', name: 'cols', type: 'textbox', size: 10},
- {label: 'Rows', name: 'rows', type: 'textbox', size: 10}
- ],
- onsubmit: function() {
- var data = this.toJSON();
-
- editor.undoManager.transact(function() {
- grid.merge(cell, data.cols, data.rows);
- });
- }
- });
- }
-
- function cellDialog() {
- var dom = editor.dom, cellElm, data, cells = [];
-
- // Get selected cells or the current cell
- cells = editor.dom.select('td.mce-item-selected,th.mce-item-selected');
- cellElm = editor.dom.getParent(editor.selection.getStart(), 'td,th');
- if (!cells.length && cellElm) {
- cells.push(cellElm);
- }
-
- cellElm = cellElm || cells[0];
-
- if (!cellElm) {
- // If this element is null, return now to avoid crashing.
- return;
- }
-
- data = {
- width: removePxSuffix(dom.getStyle(cellElm, 'width') || dom.getAttrib(cellElm, 'width')),
- height: removePxSuffix(dom.getStyle(cellElm, 'height') || dom.getAttrib(cellElm, 'height')),
- scope: dom.getAttrib(cellElm, 'scope')
- };
-
- data.type = cellElm.nodeName.toLowerCase();
-
- each('left center right'.split(' '), function(name) {
- if (editor.formatter.matchNode(cellElm, 'align' + name)) {
- data.align = name;
- }
- });
-
- editor.windowManager.open({
- title: "Cell properties",
- items: {
- type: 'form',
- data: data,
- layout: 'grid',
- columns: 2,
- defaults: {
- type: 'textbox',
- maxWidth: 50
- },
- items: [
- {label: 'Width', name: 'width'},
- {label: 'Height', name: 'height'},
- {
- label: 'Cell type',
- name: 'type',
- type: 'listbox',
- text: 'None',
- minWidth: 90,
- maxWidth: null,
- values: [
- {text: 'Cell', value: 'td'},
- {text: 'Header cell', value: 'th'}
- ]
- },
- {
- label: 'Scope',
- name: 'scope',
- type: 'listbox',
- text: 'None',
- minWidth: 90,
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Row', value: 'row'},
- {text: 'Column', value: 'col'},
- {text: 'Row group', value: 'rowgroup'},
- {text: 'Column group', value: 'colgroup'}
- ]
- },
- {
- label: 'Alignment',
- name: 'align',
- type: 'listbox',
- text: 'None',
- minWidth: 90,
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Left', value: 'left'},
- {text: 'Center', value: 'center'},
- {text: 'Right', value: 'right'}
- ]
- }
- ]
- },
-
- onsubmit: function() {
- var data = this.toJSON();
-
- editor.undoManager.transact(function() {
- each(cells, function(cellElm) {
- editor.dom.setAttrib(cellElm, 'scope', data.scope);
-
- editor.dom.setStyles(cellElm, {
- width: addSizeSuffix(data.width),
- height: addSizeSuffix(data.height)
- });
-
- // Switch cell type
- if (data.type && cellElm.nodeName.toLowerCase() != data.type) {
- cellElm = dom.rename(cellElm, data.type);
- }
-
- // Apply/remove alignment
- unApplyAlign(cellElm);
- if (data.align) {
- editor.formatter.apply('align' + data.align, {}, cellElm);
- }
- });
-
- editor.focus();
- });
- }
- });
- }
-
- function rowDialog() {
- var dom = editor.dom, tableElm, cellElm, rowElm, data, rows = [];
-
- tableElm = editor.dom.getParent(editor.selection.getStart(), 'table');
- cellElm = editor.dom.getParent(editor.selection.getStart(), 'td,th');
-
- each(tableElm.rows, function(row) {
- each(row.cells, function(cell) {
- if (dom.hasClass(cell, 'mce-item-selected') || cell == cellElm) {
- rows.push(row);
- return false;
- }
- });
- });
-
- rowElm = rows[0];
- if (!rowElm) {
- // If this element is null, return now to avoid crashing.
- return;
- }
-
- data = {
- height: removePxSuffix(dom.getStyle(rowElm, 'height') || dom.getAttrib(rowElm, 'height')),
- scope: dom.getAttrib(rowElm, 'scope')
- };
-
- data.type = rowElm.parentNode.nodeName.toLowerCase();
-
- each('left center right'.split(' '), function(name) {
- if (editor.formatter.matchNode(rowElm, 'align' + name)) {
- data.align = name;
- }
- });
-
- editor.windowManager.open({
- title: "Row properties",
- items: {
- type: 'form',
- data: data,
- columns: 2,
- defaults: {
- type: 'textbox'
- },
- items: [
- {
- type: 'listbox',
- name: 'type',
- label: 'Row type',
- text: 'None',
- maxWidth: null,
- values: [
- {text: 'Header', value: 'thead'},
- {text: 'Body', value: 'tbody'},
- {text: 'Footer', value: 'tfoot'}
- ]
- },
- {
- type: 'listbox',
- name: 'align',
- label: 'Alignment',
- text: 'None',
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Left', value: 'left'},
- {text: 'Center', value: 'center'},
- {text: 'Right', value: 'right'}
- ]
- },
- {label: 'Height', name: 'height'}
- ]
- },
-
- onsubmit: function() {
- var data = this.toJSON(), tableElm, oldParentElm, parentElm;
-
- editor.undoManager.transact(function() {
- var toType = data.type;
-
- each(rows, function(rowElm) {
- editor.dom.setAttrib(rowElm, 'scope', data.scope);
-
- editor.dom.setStyles(rowElm, {
- height: addSizeSuffix(data.height)
- });
-
- if (toType != rowElm.parentNode.nodeName.toLowerCase()) {
- tableElm = dom.getParent(rowElm, 'table');
-
- oldParentElm = rowElm.parentNode;
- parentElm = dom.select(toType, tableElm)[0];
- if (!parentElm) {
- parentElm = dom.create(toType);
- if (tableElm.firstChild) {
- tableElm.insertBefore(parentElm, tableElm.firstChild);
- } else {
- tableElm.appendChild(parentElm);
- }
- }
-
- parentElm.appendChild(rowElm);
-
- if (!oldParentElm.hasChildNodes()) {
- dom.remove(oldParentElm);
- }
- }
-
- // Apply/remove alignment
- unApplyAlign(rowElm);
- if (data.align) {
- editor.formatter.apply('align' + data.align, {}, rowElm);
- }
- });
-
- editor.focus();
- });
- }
- });
- }
-
- function cmd(command) {
- return function() {
- editor.execCommand(command);
- };
- }
-
- function insertTable(cols, rows) {
- var y, x, html;
-
- html = '';
-
- for (y = 0; y < rows; y++) {
- html += '
';
-
- editor.insertContent(html);
- }
-
- function handleDisabledState(ctrl, selector) {
- function bindStateListener() {
- ctrl.disabled(!editor.dom.getParent(editor.selection.getStart(), selector));
-
- editor.selection.selectorChanged(selector, function(state) {
- ctrl.disabled(!state);
- });
- }
-
- if (editor.initialized) {
- bindStateListener();
- } else {
- editor.on('init', bindStateListener);
- }
- }
-
- function postRender() {
- /*jshint validthis:true*/
- handleDisabledState(this, 'table');
- }
-
- function postRenderCell() {
- /*jshint validthis:true*/
- handleDisabledState(this, 'td,th');
- }
-
- function generateTableGrid() {
- var html = '';
-
- html = '';
-
- for (x = 0; x < cols; x++) {
- html += ' ';
- }
-
- html += '' + (Env.ie ? " " : ' ';
- }
-
- html += '
') + '';
-
- for (var y = 0; y < 10; y++) {
- html += '
';
-
- html += '';
-
- for (var x = 0; x < 10; x++) {
- html += ' ';
- }
-
- html += '';
- }
-
- html += '
'
- );
- } else {
- editor.dom.add(editor.getBody(), 'br', {'data-mce-bogus': '1'});
- }
- }
- });
-
- editor.on('PreProcess', function(o) {
- var last = o.node.lastChild;
-
- if (last && (last.nodeName == "BR" || (last.childNodes.length == 1 &&
- (last.firstChild.nodeName == 'BR' || last.firstChild.nodeValue == '\u00a0'))) &&
- last.previousSibling && last.previousSibling.nodeName == "TABLE") {
- editor.dom.remove(last);
- }
- });
- }
-
- // this nasty hack is here to work around some WebKit selection bugs.
- function fixTableCellSelection() {
- function tableCellSelected(ed, rng, n, currentCell) {
- // The decision of when a table cell is selected is somewhat involved. The fact that this code is
- // required is actually a pointer to the root cause of this bug. A cell is selected when the start
- // and end offsets are 0, the start container is a text, and the selection node is either a TR (most cases)
- // or the parent of the table (in the case of the selection containing the last cell of a table).
- var TEXT_NODE = 3, table = ed.dom.getParent(rng.startContainer, 'TABLE');
- var tableParent, allOfCellSelected, tableCellSelection;
-
- if (table) {
- tableParent = table.parentNode;
- }
-
- allOfCellSelected = rng.startContainer.nodeType == TEXT_NODE &&
- rng.startOffset === 0 &&
- rng.endOffset === 0 &&
- currentCell &&
- (n.nodeName == "TR" || n == tableParent);
-
- tableCellSelection = (n.nodeName == "TD" || n.nodeName == "TH") && !currentCell;
-
- return allOfCellSelected || tableCellSelection;
- }
-
- function fixSelection() {
- var rng = editor.selection.getRng();
- var n = editor.selection.getNode();
- var currentCell = editor.dom.getParent(rng.startContainer, 'TD,TH');
-
- if (!tableCellSelected(editor, rng, n, currentCell)) {
- return;
- }
-
- if (!currentCell) {
- currentCell = n;
- }
-
- // Get the very last node inside the table cell
- var end = currentCell.lastChild;
- while (end.lastChild) {
- end = end.lastChild;
- }
-
- // Select the entire table cell. Nothing outside of the table cell should be selected.
- rng.setEnd(end, end.nodeValue.length);
- editor.selection.setRng(rng);
- }
-
- editor.on('KeyDown', function() {
- fixSelection();
- });
-
- editor.on('MouseDown', function(e) {
- if (e.button != 2) {
- fixSelection();
- }
- });
- }
-
- /**
- * Delete table if all cells are selected.
- */
- function deleteTable() {
- editor.on('keydown', function(e) {
- if ((e.keyCode == VK.DELETE || e.keyCode == VK.BACKSPACE) && !e.isDefaultPrevented()) {
- var table = editor.dom.getParent(editor.selection.getStart(), 'table');
-
- if (table) {
- var cells = editor.dom.select('td,th', table), i = cells.length;
- while (i--) {
- if (!editor.dom.hasClass(cells[i], 'mce-item-selected')) {
- return;
- }
- }
-
- e.preventDefault();
- editor.execCommand('mceTableDelete');
- }
- }
- });
- }
-
- deleteTable();
-
- if (Env.webkit) {
- moveWebKitSelection();
- fixTableCellSelection();
- }
-
- if (Env.gecko) {
- fixBeforeTableCaretBug();
- fixTableCaretPos();
- }
-
- if (Env.ie > 10) {
- fixBeforeTableCaretBug();
- fixTableCaretPos();
- }
- };
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/classes/TableGrid.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/table/classes/TableGrid.js
deleted file mode 100755
index eea3cd23d9..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/classes/TableGrid.js
+++ /dev/null
@@ -1,833 +0,0 @@
-/**
- * TableGrid.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class creates a grid out of a table element. This
- * makes it a whole lot easier to handle complex tables with
- * col/row spans.
- *
- * @class tinymce.tableplugin.TableGrid
- * @private
- */
-define("tinymce/tableplugin/TableGrid", [
- "tinymce/util/Tools",
- "tinymce/Env"
-], function(Tools, Env) {
- var each = Tools.each;
-
- function getSpanVal(td, name) {
- return parseInt(td.getAttribute(name) || 1, 10);
- }
-
- return function(editor, table) {
- var grid, startPos, endPos, selectedCell, selection = editor.selection, dom = selection.dom;
-
- function buildGrid() {
- var startY = 0;
-
- grid = [];
-
- each(['thead', 'tbody', 'tfoot'], function(part) {
- var rows = dom.select('> ' + part + ' tr', table);
-
- each(rows, function(tr, y) {
- y += startY;
-
- each(dom.select('> td, > th', tr), function(td, x) {
- var x2, y2, rowspan, colspan;
-
- // Skip over existing cells produced by rowspan
- if (grid[y]) {
- while (grid[y][x]) {
- x++;
- }
- }
-
- // Get col/rowspan from cell
- rowspan = getSpanVal(td, 'rowspan');
- colspan = getSpanVal(td, 'colspan');
-
- // Fill out rowspan/colspan right and down
- for (y2 = y; y2 < y + rowspan; y2++) {
- if (!grid[y2]) {
- grid[y2] = [];
- }
-
- for (x2 = x; x2 < x + colspan; x2++) {
- grid[y2][x2] = {
- part: part,
- real: y2 == y && x2 == x,
- elm: td,
- rowspan: rowspan,
- colspan: colspan
- };
- }
- }
- });
- });
-
- startY += rows.length;
- });
- }
-
- function cloneNode(node, children) {
- node = node.cloneNode(children);
- node.removeAttribute('id');
-
- return node;
- }
-
- function getCell(x, y) {
- var row;
-
- row = grid[y];
- if (row) {
- return row[x];
- }
- }
-
- function setSpanVal(td, name, val) {
- if (td) {
- val = parseInt(val, 10);
-
- if (val === 1) {
- td.removeAttribute(name, 1);
- } else {
- td.setAttribute(name, val, 1);
- }
- }
- }
-
- function isCellSelected(cell) {
- return cell && (dom.hasClass(cell.elm, 'mce-item-selected') || cell == selectedCell);
- }
-
- function getSelectedRows() {
- var rows = [];
-
- each(table.rows, function(row) {
- each(row.cells, function(cell) {
- if (dom.hasClass(cell, 'mce-item-selected') || (selectedCell && cell == selectedCell.elm)) {
- rows.push(row);
- return false;
- }
- });
- });
-
- return rows;
- }
-
- function deleteTable() {
- var rng = dom.createRng();
-
- rng.setStartAfter(table);
- rng.setEndAfter(table);
-
- selection.setRng(rng);
-
- dom.remove(table);
- }
-
- function cloneCell(cell) {
- var formatNode, cloneFormats = {};
-
- if (editor.settings.table_clone_elements !== false) {
- cloneFormats = Tools.makeMap(
- (editor.settings.table_clone_elements || 'strong em b i span font h1 h2 h3 h4 h5 h6 p div').toUpperCase(),
- /[ ,]/
- );
- }
-
- // Clone formats
- Tools.walk(cell, function(node) {
- var curNode;
-
- if (node.nodeType == 3) {
- each(dom.getParents(node.parentNode, null, cell).reverse(), function(node) {
- if (!cloneFormats[node.nodeName]) {
- return;
- }
-
- node = cloneNode(node, false);
-
- if (!formatNode) {
- formatNode = curNode = node;
- } else if (curNode) {
- curNode.appendChild(node);
- }
-
- curNode = node;
- });
-
- // Add something to the inner node
- if (curNode) {
- curNode.innerHTML = Env.ie ? ' ' : '
';
- }
-
- return false;
- }
- }, 'childNodes');
-
- cell = cloneNode(cell, false);
- setSpanVal(cell, 'rowSpan', 1);
- setSpanVal(cell, 'colSpan', 1);
-
- if (formatNode) {
- cell.appendChild(formatNode);
- } else {
- if (!Env.ie) {
- cell.innerHTML = '
';
- }
- }
-
- return cell;
- }
-
- function cleanup() {
- var rng = dom.createRng(), row;
-
- // Empty rows
- each(dom.select('tr', table), function(tr) {
- if (tr.cells.length === 0) {
- dom.remove(tr);
- }
- });
-
- // Empty table
- if (dom.select('tr', table).length === 0) {
- rng.setStartBefore(table);
- rng.setEndBefore(table);
- selection.setRng(rng);
- dom.remove(table);
- return;
- }
-
- // Empty header/body/footer
- each(dom.select('thead,tbody,tfoot', table), function(part) {
- if (part.rows.length === 0) {
- dom.remove(part);
- }
- });
-
- // Restore selection to start position if it still exists
- buildGrid();
-
- // If we have a valid startPos object
- if (startPos) {
- // Restore the selection to the closest table position
- row = grid[Math.min(grid.length - 1, startPos.y)];
- if (row) {
- selection.select(row[Math.min(row.length - 1, startPos.x)].elm, true);
- selection.collapse(true);
- }
- }
- }
-
- function fillLeftDown(x, y, rows, cols) {
- var tr, x2, r, c, cell;
-
- tr = grid[y][x].elm.parentNode;
- for (r = 1; r <= rows; r++) {
- tr = dom.getNext(tr, 'tr');
-
- if (tr) {
- // Loop left to find real cell
- for (x2 = x; x2 >= 0; x2--) {
- cell = grid[y + r][x2].elm;
-
- if (cell.parentNode == tr) {
- // Append clones after
- for (c = 1; c <= cols; c++) {
- dom.insertAfter(cloneCell(cell), cell);
- }
-
- break;
- }
- }
-
- if (x2 == -1) {
- // Insert nodes before first cell
- for (c = 1; c <= cols; c++) {
- tr.insertBefore(cloneCell(tr.cells[0]), tr.cells[0]);
- }
- }
- }
- }
- }
-
- function split() {
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- var colSpan, rowSpan, i;
-
- if (isCellSelected(cell)) {
- cell = cell.elm;
- colSpan = getSpanVal(cell, 'colspan');
- rowSpan = getSpanVal(cell, 'rowspan');
-
- if (colSpan > 1 || rowSpan > 1) {
- setSpanVal(cell, 'rowSpan', 1);
- setSpanVal(cell, 'colSpan', 1);
-
- // Insert cells right
- for (i = 0; i < colSpan - 1; i++) {
- dom.insertAfter(cloneCell(cell), cell);
- }
-
- fillLeftDown(x, y, rowSpan - 1, colSpan);
- }
- }
- });
- });
- }
-
- function merge(cell, cols, rows) {
- var pos, startX, startY, endX, endY, x, y, startCell, endCell, children, count;
-
- // Use specified cell and cols/rows
- if (cell) {
- pos = getPos(cell);
- startX = pos.x;
- startY = pos.y;
- endX = startX + (cols - 1);
- endY = startY + (rows - 1);
- } else {
- startPos = endPos = null;
-
- // Calculate start/end pos by checking for selected cells in grid works better with context menu
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- if (isCellSelected(cell)) {
- if (!startPos) {
- startPos = {x: x, y: y};
- }
-
- endPos = {x: x, y: y};
- }
- });
- });
-
- // Use selection, but make sure startPos is valid before accessing
- if (startPos) {
- startX = startPos.x;
- startY = startPos.y;
- endX = endPos.x;
- endY = endPos.y;
- }
- }
-
- // Find start/end cells
- startCell = getCell(startX, startY);
- endCell = getCell(endX, endY);
-
- // Check if the cells exists and if they are of the same part for example tbody = tbody
- if (startCell && endCell && startCell.part == endCell.part) {
- // Split and rebuild grid
- split();
- buildGrid();
-
- // Set row/col span to start cell
- startCell = getCell(startX, startY).elm;
- setSpanVal(startCell, 'colSpan', (endX - startX) + 1);
- setSpanVal(startCell, 'rowSpan', (endY - startY) + 1);
-
- // Remove other cells and add it's contents to the start cell
- for (y = startY; y <= endY; y++) {
- for (x = startX; x <= endX; x++) {
- if (!grid[y] || !grid[y][x]) {
- continue;
- }
-
- cell = grid[y][x].elm;
-
- /*jshint loopfunc:true */
- /*eslint loop-func:0 */
- if (cell != startCell) {
- // Move children to startCell
- children = Tools.grep(cell.childNodes);
- each(children, function(node) {
- startCell.appendChild(node);
- });
-
- // Remove bogus nodes if there is children in the target cell
- if (children.length) {
- children = Tools.grep(startCell.childNodes);
- count = 0;
- each(children, function(node) {
- if (node.nodeName == 'BR' && dom.getAttrib(node, 'data-mce-bogus') && count++ < children.length - 1) {
- startCell.removeChild(node);
- }
- });
- }
-
- dom.remove(cell);
- }
- }
- }
-
- // Remove empty rows etc and restore caret location
- cleanup();
- }
- }
-
- function insertRow(before) {
- var posY, cell, lastCell, x, rowElm, newRow, newCell, otherCell, rowSpan;
-
- // Find first/last row
- each(grid, function(row, y) {
- each(row, function(cell) {
- if (isCellSelected(cell)) {
- cell = cell.elm;
- rowElm = cell.parentNode;
- newRow = cloneNode(rowElm, false);
- posY = y;
-
- if (before) {
- return false;
- }
- }
- });
-
- if (before) {
- return !posY;
- }
- });
-
- // If posY is undefined there is nothing for us to do here...just return to avoid crashing below
- if (posY === undefined) {
- return;
- }
-
- for (x = 0; x < grid[0].length; x++) {
- // Cell not found could be because of an invalid table structure
- if (!grid[posY][x]) {
- continue;
- }
-
- cell = grid[posY][x].elm;
-
- if (cell != lastCell) {
- if (!before) {
- rowSpan = getSpanVal(cell, 'rowspan');
- if (rowSpan > 1) {
- setSpanVal(cell, 'rowSpan', rowSpan + 1);
- continue;
- }
- } else {
- // Check if cell above can be expanded
- if (posY > 0 && grid[posY - 1][x]) {
- otherCell = grid[posY - 1][x].elm;
- rowSpan = getSpanVal(otherCell, 'rowSpan');
- if (rowSpan > 1) {
- setSpanVal(otherCell, 'rowSpan', rowSpan + 1);
- continue;
- }
- }
- }
-
- // Insert new cell into new row
- newCell = cloneCell(cell);
- setSpanVal(newCell, 'colSpan', cell.colSpan);
-
- newRow.appendChild(newCell);
-
- lastCell = cell;
- }
- }
-
- if (newRow.hasChildNodes()) {
- if (!before) {
- dom.insertAfter(newRow, rowElm);
- } else {
- rowElm.parentNode.insertBefore(newRow, rowElm);
- }
- }
- }
-
- function insertCol(before) {
- var posX, lastCell;
-
- // Find first/last column
- each(grid, function(row) {
- each(row, function(cell, x) {
- if (isCellSelected(cell)) {
- posX = x;
-
- if (before) {
- return false;
- }
- }
- });
-
- if (before) {
- return !posX;
- }
- });
-
- each(grid, function(row, y) {
- var cell, rowSpan, colSpan;
-
- if (!row[posX]) {
- return;
- }
-
- cell = row[posX].elm;
- if (cell != lastCell) {
- colSpan = getSpanVal(cell, 'colspan');
- rowSpan = getSpanVal(cell, 'rowspan');
-
- if (colSpan == 1) {
- if (!before) {
- dom.insertAfter(cloneCell(cell), cell);
- fillLeftDown(posX, y, rowSpan - 1, colSpan);
- } else {
- cell.parentNode.insertBefore(cloneCell(cell), cell);
- fillLeftDown(posX, y, rowSpan - 1, colSpan);
- }
- } else {
- setSpanVal(cell, 'colSpan', cell.colSpan + 1);
- }
-
- lastCell = cell;
- }
- });
- }
-
- function deleteCols() {
- var cols = [];
-
- // Get selected column indexes
- each(grid, function(row) {
- each(row, function(cell, x) {
- if (isCellSelected(cell) && Tools.inArray(cols, x) === -1) {
- each(grid, function(row) {
- var cell = row[x].elm, colSpan;
-
- colSpan = getSpanVal(cell, 'colSpan');
-
- if (colSpan > 1) {
- setSpanVal(cell, 'colSpan', colSpan - 1);
- } else {
- dom.remove(cell);
- }
- });
-
- cols.push(x);
- }
- });
- });
-
- cleanup();
- }
-
- function deleteRows() {
- var rows;
-
- function deleteRow(tr) {
- var nextTr, pos, lastCell;
-
- nextTr = dom.getNext(tr, 'tr');
-
- // Move down row spanned cells
- each(tr.cells, function(cell) {
- var rowSpan = getSpanVal(cell, 'rowSpan');
-
- if (rowSpan > 1) {
- setSpanVal(cell, 'rowSpan', rowSpan - 1);
- pos = getPos(cell);
- fillLeftDown(pos.x, pos.y, 1, 1);
- }
- });
-
- // Delete cells
- pos = getPos(tr.cells[0]);
- each(grid[pos.y], function(cell) {
- var rowSpan;
-
- cell = cell.elm;
-
- if (cell != lastCell) {
- rowSpan = getSpanVal(cell, 'rowSpan');
-
- if (rowSpan <= 1) {
- dom.remove(cell);
- } else {
- setSpanVal(cell, 'rowSpan', rowSpan - 1);
- }
-
- lastCell = cell;
- }
- });
- }
-
- // Get selected rows and move selection out of scope
- rows = getSelectedRows();
-
- // Delete all selected rows
- each(rows.reverse(), function(tr) {
- deleteRow(tr);
- });
-
- cleanup();
- }
-
- function cutRows() {
- var rows = getSelectedRows();
-
- dom.remove(rows);
- cleanup();
-
- return rows;
- }
-
- function copyRows() {
- var rows = getSelectedRows();
-
- each(rows, function(row, i) {
- rows[i] = cloneNode(row, true);
- });
-
- return rows;
- }
-
- function pasteRows(rows, before) {
- var selectedRows = getSelectedRows(),
- targetRow = selectedRows[before ? 0 : selectedRows.length - 1],
- targetCellCount = targetRow.cells.length;
-
- // Nothing to paste
- if (!rows) {
- return;
- }
-
- // Calc target cell count
- each(grid, function(row) {
- var match;
-
- targetCellCount = 0;
- each(row, function(cell) {
- if (cell.real) {
- targetCellCount += cell.colspan;
- }
-
- if (cell.elm.parentNode == targetRow) {
- match = 1;
- }
- });
-
- if (match) {
- return false;
- }
- });
-
- if (!before) {
- rows.reverse();
- }
-
- each(rows, function(row) {
- var i, cellCount = row.cells.length, cell;
-
- // Remove col/rowspans
- for (i = 0; i < cellCount; i++) {
- cell = row.cells[i];
- setSpanVal(cell, 'colSpan', 1);
- setSpanVal(cell, 'rowSpan', 1);
- }
-
- // Needs more cells
- for (i = cellCount; i < targetCellCount; i++) {
- row.appendChild(cloneCell(row.cells[cellCount - 1]));
- }
-
- // Needs less cells
- for (i = targetCellCount; i < cellCount; i++) {
- dom.remove(row.cells[i]);
- }
-
- // Add before/after
- if (before) {
- targetRow.parentNode.insertBefore(row, targetRow);
- } else {
- dom.insertAfter(row, targetRow);
- }
- });
-
- // Remove current selection
- dom.removeClass(dom.select('td.mce-item-selected,th.mce-item-selected'), 'mce-item-selected');
- }
-
- function getPos(target) {
- var pos;
-
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- if (cell.elm == target) {
- pos = {x : x, y : y};
- return false;
- }
- });
-
- return !pos;
- });
-
- return pos;
- }
-
- function setStartCell(cell) {
- startPos = getPos(cell);
- }
-
- function findEndPos() {
- var maxX, maxY;
-
- maxX = maxY = 0;
-
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- var colSpan, rowSpan;
-
- if (isCellSelected(cell)) {
- cell = grid[y][x];
-
- if (x > maxX) {
- maxX = x;
- }
-
- if (y > maxY) {
- maxY = y;
- }
-
- if (cell.real) {
- colSpan = cell.colspan - 1;
- rowSpan = cell.rowspan - 1;
-
- if (colSpan) {
- if (x + colSpan > maxX) {
- maxX = x + colSpan;
- }
- }
-
- if (rowSpan) {
- if (y + rowSpan > maxY) {
- maxY = y + rowSpan;
- }
- }
- }
- }
- });
- });
-
- return {x : maxX, y : maxY};
- }
-
- function setEndCell(cell) {
- var startX, startY, endX, endY, maxX, maxY, colSpan, rowSpan, x, y;
-
- endPos = getPos(cell);
-
- if (startPos && endPos) {
- // Get start/end positions
- startX = Math.min(startPos.x, endPos.x);
- startY = Math.min(startPos.y, endPos.y);
- endX = Math.max(startPos.x, endPos.x);
- endY = Math.max(startPos.y, endPos.y);
-
- // Expand end positon to include spans
- maxX = endX;
- maxY = endY;
-
- // Expand startX
- for (y = startY; y <= maxY; y++) {
- cell = grid[y][startX];
-
- if (!cell.real) {
- if (startX - (cell.colspan - 1) < startX) {
- startX -= cell.colspan - 1;
- }
- }
- }
-
- // Expand startY
- for (x = startX; x <= maxX; x++) {
- cell = grid[startY][x];
-
- if (!cell.real) {
- if (startY - (cell.rowspan - 1) < startY) {
- startY -= cell.rowspan - 1;
- }
- }
- }
-
- // Find max X, Y
- for (y = startY; y <= endY; y++) {
- for (x = startX; x <= endX; x++) {
- cell = grid[y][x];
-
- if (cell.real) {
- colSpan = cell.colspan - 1;
- rowSpan = cell.rowspan - 1;
-
- if (colSpan) {
- if (x + colSpan > maxX) {
- maxX = x + colSpan;
- }
- }
-
- if (rowSpan) {
- if (y + rowSpan > maxY) {
- maxY = y + rowSpan;
- }
- }
- }
- }
- }
-
- // Remove current selection
- dom.removeClass(dom.select('td.mce-item-selected,th.mce-item-selected'), 'mce-item-selected');
-
- // Add new selection
- for (y = startY; y <= maxY; y++) {
- for (x = startX; x <= maxX; x++) {
- if (grid[y][x]) {
- dom.addClass(grid[y][x].elm, 'mce-item-selected');
- }
- }
- }
- }
- }
-
- table = table || dom.getParent(selection.getStart(), 'table');
-
- buildGrid();
-
- selectedCell = dom.getParent(selection.getStart(), 'th,td');
- if (selectedCell) {
- startPos = getPos(selectedCell);
- endPos = findEndPos();
- selectedCell = getCell(startPos.x, startPos.y);
- }
-
- Tools.extend(this, {
- deleteTable: deleteTable,
- split: split,
- merge: merge,
- insertRow: insertRow,
- insertCol: insertCol,
- deleteCols: deleteCols,
- deleteRows: deleteRows,
- cutRows: cutRows,
- copyRows: copyRows,
- pasteRows: pasteRows,
- getPos: getPos,
- setStartCell: setStartCell,
- setEndCell: setEndCell
- });
- };
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.dev.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.dev.js
deleted file mode 100755
index 253bd3ecf6..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.dev.js
+++ /dev/null
@@ -1,119 +0,0 @@
-/**
- * Inline development version. Only to be used while developing since it uses document.write to load scripts.
- */
-
-/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
-/*globals $code */
-
-(function(exports) {
- "use strict";
-
- var html = "", baseDir;
- var modules = {}, exposedModules = [], moduleCount = 0;
-
- var scripts = document.getElementsByTagName('script');
- for (var i = 0; i < scripts.length; i++) {
- var src = scripts[i].src;
-
- if (src.indexOf('/plugin.dev.js') != -1) {
- baseDir = src.substring(0, src.lastIndexOf('/'));
- }
- }
-
- function require(ids, callback) {
- var module, defs = [];
-
- for (var i = 0; i < ids.length; ++i) {
- module = modules[ids[i]] || resolve(ids[i]);
- if (!module) {
- throw 'module definition dependecy not found: ' + ids[i];
- }
-
- defs.push(module);
- }
-
- callback.apply(null, defs);
- }
-
- function resolve(id) {
- var target = exports;
- var fragments = id.split(/[.\/]/);
-
- for (var fi = 0; fi < fragments.length; ++fi) {
- if (!target[fragments[fi]]) {
- return;
- }
-
- target = target[fragments[fi]];
- }
-
- return target;
- }
-
- function register(id) {
- var target = exports;
- var fragments = id.split(/[.\/]/);
-
- for (var fi = 0; fi < fragments.length - 1; ++fi) {
- if (target[fragments[fi]] === undefined) {
- target[fragments[fi]] = {};
- }
-
- target = target[fragments[fi]];
- }
-
- target[fragments[fragments.length - 1]] = modules[id];
- }
-
- function define(id, dependencies, definition) {
- if (typeof id !== 'string') {
- throw 'invalid module definition, module id must be defined and be a string';
- }
-
- if (dependencies === undefined) {
- throw 'invalid module definition, dependencies must be specified';
- }
-
- if (definition === undefined) {
- throw 'invalid module definition, definition function must be specified';
- }
-
- require(dependencies, function() {
- modules[id] = definition.apply(null, arguments);
- });
-
- if (--moduleCount === 0) {
- for (var i = 0; i < exposedModules.length; i++) {
- register(exposedModules[i]);
- }
- }
- }
-
- function expose(ids) {
- exposedModules = ids;
- }
-
- function writeScripts() {
- document.write(html);
- }
-
- function load(path) {
- html += '\n';
- moduleCount++;
- }
-
- // Expose globally
- exports.define = define;
- exports.require = require;
-
- expose(["tinymce/tableplugin/TableGrid","tinymce/tableplugin/Quirks","tinymce/tableplugin/CellSelection","tinymce/tableplugin/Plugin"]);
-
- load('classes/TableGrid.js');
- load('classes/Quirks.js');
- load('classes/CellSelection.js');
- load('classes/Plugin.js');
-
- writeScripts();
-})(this);
-
-// $hash: 8a0327b8917332b89e69b02d5ba10c30
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.js
old mode 100755
new mode 100644
index ff9bfe82f1..5273df8e3c
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.js
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.js
@@ -1,2260 +1,10260 @@
/**
- * Compiled inline version. (Library mode)
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
*/
-
-/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
-/*globals $code */
-
-(function(exports, undefined) {
- "use strict";
-
- var modules = {};
-
- function require(ids, callback) {
- var module, defs = [];
-
- for (var i = 0; i < ids.length; ++i) {
- module = modules[ids[i]] || resolve(ids[i]);
- if (!module) {
- throw 'module definition dependecy not found: ' + ids[i];
- }
-
- defs.push(module);
- }
-
- callback.apply(null, defs);
- }
-
- function define(id, dependencies, definition) {
- if (typeof id !== 'string') {
- throw 'invalid module definition, module id must be defined and be a string';
- }
-
- if (dependencies === undefined) {
- throw 'invalid module definition, dependencies must be specified';
- }
-
- if (definition === undefined) {
- throw 'invalid module definition, definition function must be specified';
- }
-
- require(dependencies, function() {
- modules[id] = definition.apply(null, arguments);
- });
- }
-
- function defined(id) {
- return !!modules[id];
- }
-
- function resolve(id) {
- var target = exports;
- var fragments = id.split(/[.\/]/);
-
- for (var fi = 0; fi < fragments.length; ++fi) {
- if (!target[fragments[fi]]) {
- return;
- }
-
- target = target[fragments[fi]];
- }
-
- return target;
- }
-
- function expose(ids) {
- for (var i = 0; i < ids.length; i++) {
- var target = exports;
- var id = ids[i];
- var fragments = id.split(/[.\/]/);
-
- for (var fi = 0; fi < fragments.length - 1; ++fi) {
- if (target[fragments[fi]] === undefined) {
- target[fragments[fi]] = {};
- }
-
- target = target[fragments[fi]];
- }
-
- target[fragments[fragments.length - 1]] = modules[id];
- }
- }
-
-// Included from: js/tinymce/plugins/table/classes/TableGrid.js
-
-/**
- * TableGrid.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class creates a grid out of a table element. This
- * makes it a whole lot easier to handle complex tables with
- * col/row spans.
- *
- * @class tinymce.tableplugin.TableGrid
- * @private
- */
-define("tinymce/tableplugin/TableGrid", [
- "tinymce/util/Tools",
- "tinymce/Env"
-], function(Tools, Env) {
- var each = Tools.each;
-
- function getSpanVal(td, name) {
- return parseInt(td.getAttribute(name) || 1, 10);
- }
-
- return function(editor, table) {
- var grid, startPos, endPos, selectedCell, selection = editor.selection, dom = selection.dom;
-
- function buildGrid() {
- var startY = 0;
-
- grid = [];
-
- each(['thead', 'tbody', 'tfoot'], function(part) {
- var rows = dom.select('> ' + part + ' tr', table);
-
- each(rows, function(tr, y) {
- y += startY;
-
- each(dom.select('> td, > th', tr), function(td, x) {
- var x2, y2, rowspan, colspan;
-
- // Skip over existing cells produced by rowspan
- if (grid[y]) {
- while (grid[y][x]) {
- x++;
- }
- }
-
- // Get col/rowspan from cell
- rowspan = getSpanVal(td, 'rowspan');
- colspan = getSpanVal(td, 'colspan');
-
- // Fill out rowspan/colspan right and down
- for (y2 = y; y2 < y + rowspan; y2++) {
- if (!grid[y2]) {
- grid[y2] = [];
- }
-
- for (x2 = x; x2 < x + colspan; x2++) {
- grid[y2][x2] = {
- part: part,
- real: y2 == y && x2 == x,
- elm: td,
- rowspan: rowspan,
- colspan: colspan
- };
- }
- }
- });
- });
-
- startY += rows.length;
- });
- }
-
- function cloneNode(node, children) {
- node = node.cloneNode(children);
- node.removeAttribute('id');
-
- return node;
- }
-
- function getCell(x, y) {
- var row;
-
- row = grid[y];
- if (row) {
- return row[x];
- }
- }
-
- function setSpanVal(td, name, val) {
- if (td) {
- val = parseInt(val, 10);
-
- if (val === 1) {
- td.removeAttribute(name, 1);
- } else {
- td.setAttribute(name, val, 1);
- }
- }
- }
-
- function isCellSelected(cell) {
- return cell && (dom.hasClass(cell.elm, 'mce-item-selected') || cell == selectedCell);
- }
-
- function getSelectedRows() {
- var rows = [];
-
- each(table.rows, function(row) {
- each(row.cells, function(cell) {
- if (dom.hasClass(cell, 'mce-item-selected') || (selectedCell && cell == selectedCell.elm)) {
- rows.push(row);
- return false;
- }
- });
- });
-
- return rows;
- }
-
- function deleteTable() {
- var rng = dom.createRng();
-
- rng.setStartAfter(table);
- rng.setEndAfter(table);
-
- selection.setRng(rng);
-
- dom.remove(table);
- }
-
- function cloneCell(cell) {
- var formatNode, cloneFormats = {};
-
- if (editor.settings.table_clone_elements !== false) {
- cloneFormats = Tools.makeMap(
- (editor.settings.table_clone_elements || 'strong em b i span font h1 h2 h3 h4 h5 h6 p div').toUpperCase(),
- /[ ,]/
- );
- }
-
- // Clone formats
- Tools.walk(cell, function(node) {
- var curNode;
-
- if (node.nodeType == 3) {
- each(dom.getParents(node.parentNode, null, cell).reverse(), function(node) {
- if (!cloneFormats[node.nodeName]) {
- return;
- }
-
- node = cloneNode(node, false);
-
- if (!formatNode) {
- formatNode = curNode = node;
- } else if (curNode) {
- curNode.appendChild(node);
- }
-
- curNode = node;
- });
-
- // Add something to the inner node
- if (curNode) {
- curNode.innerHTML = Env.ie ? ' ' : '
';
- }
-
- return false;
- }
- }, 'childNodes');
-
- cell = cloneNode(cell, false);
- setSpanVal(cell, 'rowSpan', 1);
- setSpanVal(cell, 'colSpan', 1);
-
- if (formatNode) {
- cell.appendChild(formatNode);
- } else {
- if (!Env.ie) {
- cell.innerHTML = '
';
- }
- }
-
- return cell;
- }
-
- function cleanup() {
- var rng = dom.createRng(), row;
-
- // Empty rows
- each(dom.select('tr', table), function(tr) {
- if (tr.cells.length === 0) {
- dom.remove(tr);
- }
- });
-
- // Empty table
- if (dom.select('tr', table).length === 0) {
- rng.setStartBefore(table);
- rng.setEndBefore(table);
- selection.setRng(rng);
- dom.remove(table);
- return;
- }
-
- // Empty header/body/footer
- each(dom.select('thead,tbody,tfoot', table), function(part) {
- if (part.rows.length === 0) {
- dom.remove(part);
- }
- });
-
- // Restore selection to start position if it still exists
- buildGrid();
-
- // If we have a valid startPos object
- if (startPos) {
- // Restore the selection to the closest table position
- row = grid[Math.min(grid.length - 1, startPos.y)];
- if (row) {
- selection.select(row[Math.min(row.length - 1, startPos.x)].elm, true);
- selection.collapse(true);
- }
- }
- }
-
- function fillLeftDown(x, y, rows, cols) {
- var tr, x2, r, c, cell;
-
- tr = grid[y][x].elm.parentNode;
- for (r = 1; r <= rows; r++) {
- tr = dom.getNext(tr, 'tr');
-
- if (tr) {
- // Loop left to find real cell
- for (x2 = x; x2 >= 0; x2--) {
- cell = grid[y + r][x2].elm;
-
- if (cell.parentNode == tr) {
- // Append clones after
- for (c = 1; c <= cols; c++) {
- dom.insertAfter(cloneCell(cell), cell);
- }
-
- break;
- }
- }
-
- if (x2 == -1) {
- // Insert nodes before first cell
- for (c = 1; c <= cols; c++) {
- tr.insertBefore(cloneCell(tr.cells[0]), tr.cells[0]);
- }
- }
- }
- }
- }
-
- function split() {
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- var colSpan, rowSpan, i;
-
- if (isCellSelected(cell)) {
- cell = cell.elm;
- colSpan = getSpanVal(cell, 'colspan');
- rowSpan = getSpanVal(cell, 'rowspan');
-
- if (colSpan > 1 || rowSpan > 1) {
- setSpanVal(cell, 'rowSpan', 1);
- setSpanVal(cell, 'colSpan', 1);
-
- // Insert cells right
- for (i = 0; i < colSpan - 1; i++) {
- dom.insertAfter(cloneCell(cell), cell);
- }
-
- fillLeftDown(x, y, rowSpan - 1, colSpan);
- }
- }
- });
- });
- }
-
- function merge(cell, cols, rows) {
- var pos, startX, startY, endX, endY, x, y, startCell, endCell, children, count;
-
- // Use specified cell and cols/rows
- if (cell) {
- pos = getPos(cell);
- startX = pos.x;
- startY = pos.y;
- endX = startX + (cols - 1);
- endY = startY + (rows - 1);
- } else {
- startPos = endPos = null;
-
- // Calculate start/end pos by checking for selected cells in grid works better with context menu
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- if (isCellSelected(cell)) {
- if (!startPos) {
- startPos = {x: x, y: y};
- }
-
- endPos = {x: x, y: y};
- }
- });
- });
-
- // Use selection, but make sure startPos is valid before accessing
- if (startPos) {
- startX = startPos.x;
- startY = startPos.y;
- endX = endPos.x;
- endY = endPos.y;
- }
- }
-
- // Find start/end cells
- startCell = getCell(startX, startY);
- endCell = getCell(endX, endY);
-
- // Check if the cells exists and if they are of the same part for example tbody = tbody
- if (startCell && endCell && startCell.part == endCell.part) {
- // Split and rebuild grid
- split();
- buildGrid();
-
- // Set row/col span to start cell
- startCell = getCell(startX, startY).elm;
- setSpanVal(startCell, 'colSpan', (endX - startX) + 1);
- setSpanVal(startCell, 'rowSpan', (endY - startY) + 1);
-
- // Remove other cells and add it's contents to the start cell
- for (y = startY; y <= endY; y++) {
- for (x = startX; x <= endX; x++) {
- if (!grid[y] || !grid[y][x]) {
- continue;
- }
-
- cell = grid[y][x].elm;
-
- /*jshint loopfunc:true */
- /*eslint loop-func:0 */
- if (cell != startCell) {
- // Move children to startCell
- children = Tools.grep(cell.childNodes);
- each(children, function(node) {
- startCell.appendChild(node);
- });
-
- // Remove bogus nodes if there is children in the target cell
- if (children.length) {
- children = Tools.grep(startCell.childNodes);
- count = 0;
- each(children, function(node) {
- if (node.nodeName == 'BR' && dom.getAttrib(node, 'data-mce-bogus') && count++ < children.length - 1) {
- startCell.removeChild(node);
- }
- });
- }
-
- dom.remove(cell);
- }
- }
- }
-
- // Remove empty rows etc and restore caret location
- cleanup();
- }
- }
-
- function insertRow(before) {
- var posY, cell, lastCell, x, rowElm, newRow, newCell, otherCell, rowSpan;
-
- // Find first/last row
- each(grid, function(row, y) {
- each(row, function(cell) {
- if (isCellSelected(cell)) {
- cell = cell.elm;
- rowElm = cell.parentNode;
- newRow = cloneNode(rowElm, false);
- posY = y;
-
- if (before) {
- return false;
- }
- }
- });
-
- if (before) {
- return !posY;
- }
- });
-
- // If posY is undefined there is nothing for us to do here...just return to avoid crashing below
- if (posY === undefined) {
- return;
- }
-
- for (x = 0; x < grid[0].length; x++) {
- // Cell not found could be because of an invalid table structure
- if (!grid[posY][x]) {
- continue;
- }
-
- cell = grid[posY][x].elm;
-
- if (cell != lastCell) {
- if (!before) {
- rowSpan = getSpanVal(cell, 'rowspan');
- if (rowSpan > 1) {
- setSpanVal(cell, 'rowSpan', rowSpan + 1);
- continue;
- }
- } else {
- // Check if cell above can be expanded
- if (posY > 0 && grid[posY - 1][x]) {
- otherCell = grid[posY - 1][x].elm;
- rowSpan = getSpanVal(otherCell, 'rowSpan');
- if (rowSpan > 1) {
- setSpanVal(otherCell, 'rowSpan', rowSpan + 1);
- continue;
- }
- }
- }
-
- // Insert new cell into new row
- newCell = cloneCell(cell);
- setSpanVal(newCell, 'colSpan', cell.colSpan);
-
- newRow.appendChild(newCell);
-
- lastCell = cell;
- }
- }
-
- if (newRow.hasChildNodes()) {
- if (!before) {
- dom.insertAfter(newRow, rowElm);
- } else {
- rowElm.parentNode.insertBefore(newRow, rowElm);
- }
- }
- }
-
- function insertCol(before) {
- var posX, lastCell;
-
- // Find first/last column
- each(grid, function(row) {
- each(row, function(cell, x) {
- if (isCellSelected(cell)) {
- posX = x;
-
- if (before) {
- return false;
- }
- }
- });
-
- if (before) {
- return !posX;
- }
- });
-
- each(grid, function(row, y) {
- var cell, rowSpan, colSpan;
-
- if (!row[posX]) {
- return;
- }
-
- cell = row[posX].elm;
- if (cell != lastCell) {
- colSpan = getSpanVal(cell, 'colspan');
- rowSpan = getSpanVal(cell, 'rowspan');
-
- if (colSpan == 1) {
- if (!before) {
- dom.insertAfter(cloneCell(cell), cell);
- fillLeftDown(posX, y, rowSpan - 1, colSpan);
- } else {
- cell.parentNode.insertBefore(cloneCell(cell), cell);
- fillLeftDown(posX, y, rowSpan - 1, colSpan);
- }
- } else {
- setSpanVal(cell, 'colSpan', cell.colSpan + 1);
- }
-
- lastCell = cell;
- }
- });
- }
-
- function deleteCols() {
- var cols = [];
-
- // Get selected column indexes
- each(grid, function(row) {
- each(row, function(cell, x) {
- if (isCellSelected(cell) && Tools.inArray(cols, x) === -1) {
- each(grid, function(row) {
- var cell = row[x].elm, colSpan;
-
- colSpan = getSpanVal(cell, 'colSpan');
-
- if (colSpan > 1) {
- setSpanVal(cell, 'colSpan', colSpan - 1);
- } else {
- dom.remove(cell);
- }
- });
-
- cols.push(x);
- }
- });
- });
-
- cleanup();
- }
-
- function deleteRows() {
- var rows;
-
- function deleteRow(tr) {
- var nextTr, pos, lastCell;
-
- nextTr = dom.getNext(tr, 'tr');
-
- // Move down row spanned cells
- each(tr.cells, function(cell) {
- var rowSpan = getSpanVal(cell, 'rowSpan');
-
- if (rowSpan > 1) {
- setSpanVal(cell, 'rowSpan', rowSpan - 1);
- pos = getPos(cell);
- fillLeftDown(pos.x, pos.y, 1, 1);
- }
- });
-
- // Delete cells
- pos = getPos(tr.cells[0]);
- each(grid[pos.y], function(cell) {
- var rowSpan;
-
- cell = cell.elm;
-
- if (cell != lastCell) {
- rowSpan = getSpanVal(cell, 'rowSpan');
-
- if (rowSpan <= 1) {
- dom.remove(cell);
- } else {
- setSpanVal(cell, 'rowSpan', rowSpan - 1);
- }
-
- lastCell = cell;
- }
- });
- }
-
- // Get selected rows and move selection out of scope
- rows = getSelectedRows();
-
- // Delete all selected rows
- each(rows.reverse(), function(tr) {
- deleteRow(tr);
- });
-
- cleanup();
- }
-
- function cutRows() {
- var rows = getSelectedRows();
-
- dom.remove(rows);
- cleanup();
-
- return rows;
- }
-
- function copyRows() {
- var rows = getSelectedRows();
-
- each(rows, function(row, i) {
- rows[i] = cloneNode(row, true);
- });
-
- return rows;
- }
-
- function pasteRows(rows, before) {
- var selectedRows = getSelectedRows(),
- targetRow = selectedRows[before ? 0 : selectedRows.length - 1],
- targetCellCount = targetRow.cells.length;
-
- // Nothing to paste
- if (!rows) {
- return;
- }
-
- // Calc target cell count
- each(grid, function(row) {
- var match;
-
- targetCellCount = 0;
- each(row, function(cell) {
- if (cell.real) {
- targetCellCount += cell.colspan;
- }
-
- if (cell.elm.parentNode == targetRow) {
- match = 1;
- }
- });
-
- if (match) {
- return false;
- }
- });
-
- if (!before) {
- rows.reverse();
- }
-
- each(rows, function(row) {
- var i, cellCount = row.cells.length, cell;
-
- // Remove col/rowspans
- for (i = 0; i < cellCount; i++) {
- cell = row.cells[i];
- setSpanVal(cell, 'colSpan', 1);
- setSpanVal(cell, 'rowSpan', 1);
- }
-
- // Needs more cells
- for (i = cellCount; i < targetCellCount; i++) {
- row.appendChild(cloneCell(row.cells[cellCount - 1]));
- }
-
- // Needs less cells
- for (i = targetCellCount; i < cellCount; i++) {
- dom.remove(row.cells[i]);
- }
-
- // Add before/after
- if (before) {
- targetRow.parentNode.insertBefore(row, targetRow);
- } else {
- dom.insertAfter(row, targetRow);
- }
- });
-
- // Remove current selection
- dom.removeClass(dom.select('td.mce-item-selected,th.mce-item-selected'), 'mce-item-selected');
- }
-
- function getPos(target) {
- var pos;
-
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- if (cell.elm == target) {
- pos = {x : x, y : y};
- return false;
- }
- });
-
- return !pos;
- });
-
- return pos;
- }
-
- function setStartCell(cell) {
- startPos = getPos(cell);
- }
-
- function findEndPos() {
- var maxX, maxY;
-
- maxX = maxY = 0;
-
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- var colSpan, rowSpan;
-
- if (isCellSelected(cell)) {
- cell = grid[y][x];
-
- if (x > maxX) {
- maxX = x;
- }
-
- if (y > maxY) {
- maxY = y;
- }
-
- if (cell.real) {
- colSpan = cell.colspan - 1;
- rowSpan = cell.rowspan - 1;
-
- if (colSpan) {
- if (x + colSpan > maxX) {
- maxX = x + colSpan;
- }
- }
-
- if (rowSpan) {
- if (y + rowSpan > maxY) {
- maxY = y + rowSpan;
- }
- }
- }
- }
- });
- });
-
- return {x : maxX, y : maxY};
- }
-
- function setEndCell(cell) {
- var startX, startY, endX, endY, maxX, maxY, colSpan, rowSpan, x, y;
-
- endPos = getPos(cell);
-
- if (startPos && endPos) {
- // Get start/end positions
- startX = Math.min(startPos.x, endPos.x);
- startY = Math.min(startPos.y, endPos.y);
- endX = Math.max(startPos.x, endPos.x);
- endY = Math.max(startPos.y, endPos.y);
-
- // Expand end positon to include spans
- maxX = endX;
- maxY = endY;
-
- // Expand startX
- for (y = startY; y <= maxY; y++) {
- cell = grid[y][startX];
-
- if (!cell.real) {
- if (startX - (cell.colspan - 1) < startX) {
- startX -= cell.colspan - 1;
- }
- }
- }
-
- // Expand startY
- for (x = startX; x <= maxX; x++) {
- cell = grid[startY][x];
-
- if (!cell.real) {
- if (startY - (cell.rowspan - 1) < startY) {
- startY -= cell.rowspan - 1;
- }
- }
- }
-
- // Find max X, Y
- for (y = startY; y <= endY; y++) {
- for (x = startX; x <= endX; x++) {
- cell = grid[y][x];
-
- if (cell.real) {
- colSpan = cell.colspan - 1;
- rowSpan = cell.rowspan - 1;
-
- if (colSpan) {
- if (x + colSpan > maxX) {
- maxX = x + colSpan;
- }
- }
-
- if (rowSpan) {
- if (y + rowSpan > maxY) {
- maxY = y + rowSpan;
- }
- }
- }
- }
- }
-
- // Remove current selection
- dom.removeClass(dom.select('td.mce-item-selected,th.mce-item-selected'), 'mce-item-selected');
-
- // Add new selection
- for (y = startY; y <= maxY; y++) {
- for (x = startX; x <= maxX; x++) {
- if (grid[y][x]) {
- dom.addClass(grid[y][x].elm, 'mce-item-selected');
- }
- }
- }
- }
- }
-
- table = table || dom.getParent(selection.getStart(), 'table');
-
- buildGrid();
-
- selectedCell = dom.getParent(selection.getStart(), 'th,td');
- if (selectedCell) {
- startPos = getPos(selectedCell);
- endPos = findEndPos();
- selectedCell = getCell(startPos.x, startPos.y);
- }
-
- Tools.extend(this, {
- deleteTable: deleteTable,
- split: split,
- merge: merge,
- insertRow: insertRow,
- insertCol: insertCol,
- deleteCols: deleteCols,
- deleteRows: deleteRows,
- cutRows: cutRows,
- copyRows: copyRows,
- pasteRows: pasteRows,
- getPos: getPos,
- setStartCell: setStartCell,
- setEndCell: setEndCell
- });
- };
-});
-
-// Included from: js/tinymce/plugins/table/classes/Quirks.js
-
-/**
- * Quirks.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class includes fixes for various browser quirks.
- *
- * @class tinymce.tableplugin.Quirks
- * @private
- */
-define("tinymce/tableplugin/Quirks", [
- "tinymce/util/VK",
- "tinymce/Env",
- "tinymce/util/Tools"
-], function(VK, Env, Tools) {
- var each = Tools.each;
-
- function getSpanVal(td, name) {
- return parseInt(td.getAttribute(name) || 1, 10);
- }
-
- return function(editor) {
- /**
- * Fixed caret movement around tables on WebKit.
- */
- function moveWebKitSelection() {
- function eventHandler(e) {
- var key = e.keyCode;
-
- function handle(upBool, sourceNode) {
- var siblingDirection = upBool ? 'previousSibling' : 'nextSibling';
- var currentRow = editor.dom.getParent(sourceNode, 'tr');
- var siblingRow = currentRow[siblingDirection];
-
- if (siblingRow) {
- moveCursorToRow(editor, sourceNode, siblingRow, upBool);
- e.preventDefault();
- return true;
- } else {
- var tableNode = editor.dom.getParent(currentRow, 'table');
- var middleNode = currentRow.parentNode;
- var parentNodeName = middleNode.nodeName.toLowerCase();
- if (parentNodeName === 'tbody' || parentNodeName === (upBool ? 'tfoot' : 'thead')) {
- var targetParent = getTargetParent(upBool, tableNode, middleNode, 'tbody');
- if (targetParent !== null) {
- return moveToRowInTarget(upBool, targetParent, sourceNode);
- }
- }
- return escapeTable(upBool, currentRow, siblingDirection, tableNode);
- }
- }
-
- function getTargetParent(upBool, topNode, secondNode, nodeName) {
- var tbodies = editor.dom.select('>' + nodeName, topNode);
- var position = tbodies.indexOf(secondNode);
- if (upBool && position === 0 || !upBool && position === tbodies.length - 1) {
- return getFirstHeadOrFoot(upBool, topNode);
- } else if (position === -1) {
- var topOrBottom = secondNode.tagName.toLowerCase() === 'thead' ? 0 : tbodies.length - 1;
- return tbodies[topOrBottom];
- } else {
- return tbodies[position + (upBool ? -1 : 1)];
- }
- }
-
- function getFirstHeadOrFoot(upBool, parent) {
- var tagName = upBool ? 'thead' : 'tfoot';
- var headOrFoot = editor.dom.select('>' + tagName, parent);
- return headOrFoot.length !== 0 ? headOrFoot[0] : null;
- }
-
- function moveToRowInTarget(upBool, targetParent, sourceNode) {
- var targetRow = getChildForDirection(targetParent, upBool);
-
- if (targetRow) {
- moveCursorToRow(editor, sourceNode, targetRow, upBool);
- }
-
- e.preventDefault();
- return true;
- }
-
- function escapeTable(upBool, currentRow, siblingDirection, table) {
- var tableSibling = table[siblingDirection];
-
- if (tableSibling) {
- moveCursorToStartOfElement(tableSibling);
- return true;
- } else {
- var parentCell = editor.dom.getParent(table, 'td,th');
- if (parentCell) {
- return handle(upBool, parentCell, e);
- } else {
- var backUpSibling = getChildForDirection(currentRow, !upBool);
- moveCursorToStartOfElement(backUpSibling);
- e.preventDefault();
- return false;
- }
- }
- }
-
- function getChildForDirection(parent, up) {
- var child = parent && parent[up ? 'lastChild' : 'firstChild'];
- // BR is not a valid table child to return in this case we return the table cell
- return child && child.nodeName === 'BR' ? editor.dom.getParent(child, 'td,th') : child;
- }
-
- function moveCursorToStartOfElement(n) {
- editor.selection.setCursorLocation(n, 0);
- }
-
- function isVerticalMovement() {
- return key == VK.UP || key == VK.DOWN;
- }
-
- function isInTable(editor) {
- var node = editor.selection.getNode();
- var currentRow = editor.dom.getParent(node, 'tr');
- return currentRow !== null;
- }
-
- function columnIndex(column) {
- var colIndex = 0;
- var c = column;
- while (c.previousSibling) {
- c = c.previousSibling;
- colIndex = colIndex + getSpanVal(c, "colspan");
- }
- return colIndex;
- }
-
- function findColumn(rowElement, columnIndex) {
- var c = 0, r = 0;
-
- each(rowElement.children, function(cell, i) {
- c = c + getSpanVal(cell, "colspan");
- r = i;
- if (c > columnIndex) {
- return false;
- }
- });
- return r;
- }
-
- function moveCursorToRow(ed, node, row, upBool) {
- var srcColumnIndex = columnIndex(editor.dom.getParent(node, 'td,th'));
- var tgtColumnIndex = findColumn(row, srcColumnIndex);
- var tgtNode = row.childNodes[tgtColumnIndex];
- var rowCellTarget = getChildForDirection(tgtNode, upBool);
- moveCursorToStartOfElement(rowCellTarget || tgtNode);
- }
-
- function shouldFixCaret(preBrowserNode) {
- var newNode = editor.selection.getNode();
- var newParent = editor.dom.getParent(newNode, 'td,th');
- var oldParent = editor.dom.getParent(preBrowserNode, 'td,th');
-
- return newParent && newParent !== oldParent && checkSameParentTable(newParent, oldParent);
- }
-
- function checkSameParentTable(nodeOne, NodeTwo) {
- return editor.dom.getParent(nodeOne, 'TABLE') === editor.dom.getParent(NodeTwo, 'TABLE');
- }
-
- if (isVerticalMovement() && isInTable(editor)) {
- var preBrowserNode = editor.selection.getNode();
- setTimeout(function() {
- if (shouldFixCaret(preBrowserNode)) {
- handle(!e.shiftKey && key === VK.UP, preBrowserNode, e);
- }
- }, 0);
- }
- }
-
- editor.on('KeyDown', function(e) {
- eventHandler(e);
- });
- }
-
- function fixBeforeTableCaretBug() {
- // Checks if the selection/caret is at the start of the specified block element
- function isAtStart(rng, par) {
- var doc = par.ownerDocument, rng2 = doc.createRange(), elm;
-
- rng2.setStartBefore(par);
- rng2.setEnd(rng.endContainer, rng.endOffset);
-
- elm = doc.createElement('body');
- elm.appendChild(rng2.cloneContents());
-
- // Check for text characters of other elements that should be treated as content
- return elm.innerHTML.replace(/<(br|img|object|embed|input|textarea)[^>]*>/gi, '-').replace(/<[^>]+>/g, '').length === 0;
- }
-
- // Fixes an bug where it's impossible to place the caret before a table in Gecko
- // this fix solves it by detecting when the caret is at the beginning of such a table
- // and then manually moves the caret infront of the table
- editor.on('KeyDown', function(e) {
- var rng, table, dom = editor.dom;
-
- // On gecko it's not possible to place the caret before a table
- if (e.keyCode == 37 || e.keyCode == 38) {
- rng = editor.selection.getRng();
- table = dom.getParent(rng.startContainer, 'table');
-
- if (table && editor.getBody().firstChild == table) {
- if (isAtStart(rng, table)) {
- rng = dom.createRng();
-
- rng.setStartBefore(table);
- rng.setEndBefore(table);
-
- editor.selection.setRng(rng);
-
- e.preventDefault();
- }
- }
- }
- });
- }
-
- // Fixes an issue on Gecko where it's impossible to place the caret behind a table
- // This fix will force a paragraph element after the table but only when the forced_root_block setting is enabled
- function fixTableCaretPos() {
- editor.on('KeyDown SetContent VisualAid', function() {
- var last;
-
- // Skip empty text nodes from the end
- for (last = editor.getBody().lastChild; last; last = last.previousSibling) {
- if (last.nodeType == 3) {
- if (last.nodeValue.length > 0) {
- break;
- }
- } else if (last.nodeType == 1 && !last.getAttribute('data-mce-bogus')) {
- break;
- }
- }
-
- if (last && last.nodeName == 'TABLE') {
- if (editor.settings.forced_root_block) {
- editor.dom.add(
- editor.getBody(),
- editor.settings.forced_root_block,
- editor.settings.forced_root_block_attrs,
- Env.ie && Env.ie < 11 ? ' ' : '
'
- );
- } else {
- editor.dom.add(editor.getBody(), 'br', {'data-mce-bogus': '1'});
- }
- }
- });
-
- editor.on('PreProcess', function(o) {
- var last = o.node.lastChild;
-
- if (last && (last.nodeName == "BR" || (last.childNodes.length == 1 &&
- (last.firstChild.nodeName == 'BR' || last.firstChild.nodeValue == '\u00a0'))) &&
- last.previousSibling && last.previousSibling.nodeName == "TABLE") {
- editor.dom.remove(last);
- }
- });
- }
-
- // this nasty hack is here to work around some WebKit selection bugs.
- function fixTableCellSelection() {
- function tableCellSelected(ed, rng, n, currentCell) {
- // The decision of when a table cell is selected is somewhat involved. The fact that this code is
- // required is actually a pointer to the root cause of this bug. A cell is selected when the start
- // and end offsets are 0, the start container is a text, and the selection node is either a TR (most cases)
- // or the parent of the table (in the case of the selection containing the last cell of a table).
- var TEXT_NODE = 3, table = ed.dom.getParent(rng.startContainer, 'TABLE');
- var tableParent, allOfCellSelected, tableCellSelection;
-
- if (table) {
- tableParent = table.parentNode;
- }
-
- allOfCellSelected = rng.startContainer.nodeType == TEXT_NODE &&
- rng.startOffset === 0 &&
- rng.endOffset === 0 &&
- currentCell &&
- (n.nodeName == "TR" || n == tableParent);
-
- tableCellSelection = (n.nodeName == "TD" || n.nodeName == "TH") && !currentCell;
-
- return allOfCellSelected || tableCellSelection;
- }
-
- function fixSelection() {
- var rng = editor.selection.getRng();
- var n = editor.selection.getNode();
- var currentCell = editor.dom.getParent(rng.startContainer, 'TD,TH');
-
- if (!tableCellSelected(editor, rng, n, currentCell)) {
- return;
- }
-
- if (!currentCell) {
- currentCell = n;
- }
-
- // Get the very last node inside the table cell
- var end = currentCell.lastChild;
- while (end.lastChild) {
- end = end.lastChild;
- }
-
- // Select the entire table cell. Nothing outside of the table cell should be selected.
- rng.setEnd(end, end.nodeValue.length);
- editor.selection.setRng(rng);
- }
-
- editor.on('KeyDown', function() {
- fixSelection();
- });
-
- editor.on('MouseDown', function(e) {
- if (e.button != 2) {
- fixSelection();
- }
- });
- }
-
- /**
- * Delete table if all cells are selected.
- */
- function deleteTable() {
- editor.on('keydown', function(e) {
- if ((e.keyCode == VK.DELETE || e.keyCode == VK.BACKSPACE) && !e.isDefaultPrevented()) {
- var table = editor.dom.getParent(editor.selection.getStart(), 'table');
-
- if (table) {
- var cells = editor.dom.select('td,th', table), i = cells.length;
- while (i--) {
- if (!editor.dom.hasClass(cells[i], 'mce-item-selected')) {
- return;
- }
- }
-
- e.preventDefault();
- editor.execCommand('mceTableDelete');
- }
- }
- });
- }
-
- deleteTable();
-
- if (Env.webkit) {
- moveWebKitSelection();
- fixTableCellSelection();
- }
-
- if (Env.gecko) {
- fixBeforeTableCaretBug();
- fixTableCaretPos();
- }
-
- if (Env.ie > 10) {
- fixBeforeTableCaretBug();
- fixTableCaretPos();
- }
- };
-});
-
-// Included from: js/tinymce/plugins/table/classes/CellSelection.js
-
-/**
- * CellSelection.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class handles table cell selection by faking it using a css class that gets applied
- * to cells when dragging the mouse from one cell to another.
- *
- * @class tinymce.tableplugin.CellSelection
- * @private
- */
-define("tinymce/tableplugin/CellSelection", [
- "tinymce/tableplugin/TableGrid",
- "tinymce/dom/TreeWalker",
- "tinymce/util/Tools"
-], function(TableGrid, TreeWalker, Tools) {
- return function(editor) {
- var dom = editor.dom, tableGrid, startCell, startTable, hasCellSelection = true;
-
- function clear() {
- // Restore selection possibilities
- editor.getBody().style.webkitUserSelect = '';
-
- if (hasCellSelection) {
- editor.dom.removeClass(
- editor.dom.select('td.mce-item-selected,th.mce-item-selected'),
- 'mce-item-selected'
- );
-
- hasCellSelection = false;
- }
- }
-
- function cellSelectionHandler(e) {
- var sel, table, target = e.target;
-
- if (startCell && (tableGrid || target != startCell) && (target.nodeName == 'TD' || target.nodeName == 'TH')) {
- table = dom.getParent(target, 'table');
- if (table == startTable) {
- if (!tableGrid) {
- tableGrid = new TableGrid(editor, table);
- tableGrid.setStartCell(startCell);
-
- editor.getBody().style.webkitUserSelect = 'none';
- }
-
- tableGrid.setEndCell(target);
- hasCellSelection = true;
- }
-
- // Remove current selection
- sel = editor.selection.getSel();
-
- try {
- if (sel.removeAllRanges) {
- sel.removeAllRanges();
- } else {
- sel.empty();
- }
- } catch (ex) {
- // IE9 might throw errors here
- }
-
- e.preventDefault();
- }
- }
-
- // Add cell selection logic
- editor.on('MouseDown', function(e) {
- if (e.button != 2) {
- clear();
-
- startCell = dom.getParent(e.target, 'td,th');
- startTable = dom.getParent(startCell, 'table');
- }
- });
-
- editor.on('mouseover', cellSelectionHandler);
-
- editor.on('remove', function() {
- dom.unbind(editor.getDoc(), 'mouseover', cellSelectionHandler);
- });
-
- editor.on('MouseUp', function() {
- var rng, sel = editor.selection, selectedCells, walker, node, lastNode, endNode;
-
- function setPoint(node, start) {
- var walker = new TreeWalker(node, node);
-
- do {
- // Text node
- if (node.nodeType == 3 && Tools.trim(node.nodeValue).length !== 0) {
- if (start) {
- rng.setStart(node, 0);
- } else {
- rng.setEnd(node, node.nodeValue.length);
- }
-
- return;
- }
-
- // BR element
- if (node.nodeName == 'BR') {
- if (start) {
- rng.setStartBefore(node);
- } else {
- rng.setEndBefore(node);
- }
-
- return;
- }
- } while ((node = (start ? walker.next() : walker.prev())));
- }
-
- // Move selection to startCell
- if (startCell) {
- if (tableGrid) {
- editor.getBody().style.webkitUserSelect = '';
- }
-
- // Try to expand text selection as much as we can only Gecko supports cell selection
- selectedCells = dom.select('td.mce-item-selected,th.mce-item-selected');
- if (selectedCells.length > 0) {
- rng = dom.createRng();
- node = selectedCells[0];
- endNode = selectedCells[selectedCells.length - 1];
- rng.setStartBefore(node);
- rng.setEndAfter(node);
-
- setPoint(node, 1);
- walker = new TreeWalker(node, dom.getParent(selectedCells[0], 'table'));
-
- do {
- if (node.nodeName == 'TD' || node.nodeName == 'TH') {
- if (!dom.hasClass(node, 'mce-item-selected')) {
- break;
- }
-
- lastNode = node;
- }
- } while ((node = walker.next()));
-
- setPoint(lastNode);
-
- sel.setRng(rng);
- }
-
- editor.nodeChanged();
- startCell = tableGrid = startTable = null;
- }
- });
-
- editor.on('KeyUp', function() {
- clear();
- });
-
- return {
- clear: clear
- };
- };
-});
-
-// Included from: js/tinymce/plugins/table/classes/Plugin.js
-
-/**
- * Plugin.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class contains all core logic for the table plugin.
- *
- * @class tinymce.tableplugin.Plugin
- * @private
- */
-define("tinymce/tableplugin/Plugin", [
- "tinymce/tableplugin/TableGrid",
- "tinymce/tableplugin/Quirks",
- "tinymce/tableplugin/CellSelection",
- "tinymce/util/Tools",
- "tinymce/dom/TreeWalker",
- "tinymce/Env",
- "tinymce/PluginManager"
-], function(TableGrid, Quirks, CellSelection, Tools, TreeWalker, Env, PluginManager) {
- var each = Tools.each;
-
- function Plugin(editor) {
- var winMan, clipboardRows, self = this; // Might be selected cells on reload
-
- function removePxSuffix(size) {
- return size ? size.replace(/px$/, '') : "";
- }
-
- function addSizeSuffix(size) {
- if (/^[0-9]+$/.test(size)) {
- size += "px";
- }
-
- return size;
- }
-
- function unApplyAlign(elm) {
- each('left center right'.split(' '), function(name) {
- editor.formatter.remove('align' + name, {}, elm);
- });
- }
-
- function tableDialog() {
- var dom = editor.dom, tableElm, data;
-
- tableElm = dom.getParent(editor.selection.getStart(), 'table');
-
- data = {
- width: removePxSuffix(dom.getStyle(tableElm, 'width') || dom.getAttrib(tableElm, 'width')),
- height: removePxSuffix(dom.getStyle(tableElm, 'height') || dom.getAttrib(tableElm, 'height')),
- cellspacing: dom.getAttrib(tableElm, 'cellspacing'),
- cellpadding: dom.getAttrib(tableElm, 'cellpadding'),
- border: dom.getAttrib(tableElm, 'border'),
- caption: !!dom.select('caption', tableElm)[0]
- };
-
- each('left center right'.split(' '), function(name) {
- if (editor.formatter.matchNode(tableElm, 'align' + name)) {
- data.align = name;
- }
- });
-
- editor.windowManager.open({
- title: "Table properties",
- items: {
- type: 'form',
- layout: 'grid',
- columns: 2,
- data: data,
- defaults: {
- type: 'textbox',
- maxWidth: 50
- },
- items: [
- {label: 'Width', name: 'width'},
- {label: 'Height', name: 'height'},
- {label: 'Cell spacing', name: 'cellspacing'},
- {label: 'Cell padding', name: 'cellpadding'},
- {label: 'Border', name: 'border'},
- {label: 'Caption', name: 'caption', type: 'checkbox'},
- {
- label: 'Alignment',
- minWidth: 90,
- name: 'align',
- type: 'listbox',
- text: 'None',
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Left', value: 'left'},
- {text: 'Center', value: 'center'},
- {text: 'Right', value: 'right'}
- ]
- }
- ]
- },
-
- onsubmit: function() {
- var data = this.toJSON(), captionElm;
-
- editor.undoManager.transact(function() {
- editor.dom.setAttribs(tableElm, {
- cellspacing: data.cellspacing,
- cellpadding: data.cellpadding,
- border: data.border
- });
-
- editor.dom.setStyles(tableElm, {
- width: addSizeSuffix(data.width),
- height: addSizeSuffix(data.height)
- });
-
- // Toggle caption on/off
- captionElm = dom.select('caption', tableElm)[0];
-
- if (captionElm && !data.caption) {
- dom.remove(captionElm);
- }
-
- if (!captionElm && data.caption) {
- captionElm = dom.create('caption');
- captionElm.innerHTML = !Env.ie ? '
' : '\u00a0';
- tableElm.insertBefore(captionElm, tableElm.firstChild);
- }
-
- unApplyAlign(tableElm);
- if (data.align) {
- editor.formatter.apply('align' + data.align, {}, tableElm);
- }
-
- editor.focus();
- editor.addVisual();
- });
- }
- });
- }
-
- function mergeDialog(grid, cell) {
- editor.windowManager.open({
- title: "Merge cells",
- body: [
- {label: 'Cols', name: 'cols', type: 'textbox', size: 10},
- {label: 'Rows', name: 'rows', type: 'textbox', size: 10}
- ],
- onsubmit: function() {
- var data = this.toJSON();
-
- editor.undoManager.transact(function() {
- grid.merge(cell, data.cols, data.rows);
- });
- }
- });
- }
-
- function cellDialog() {
- var dom = editor.dom, cellElm, data, cells = [];
-
- // Get selected cells or the current cell
- cells = editor.dom.select('td.mce-item-selected,th.mce-item-selected');
- cellElm = editor.dom.getParent(editor.selection.getStart(), 'td,th');
- if (!cells.length && cellElm) {
- cells.push(cellElm);
- }
-
- cellElm = cellElm || cells[0];
-
- if (!cellElm) {
- // If this element is null, return now to avoid crashing.
- return;
- }
-
- data = {
- width: removePxSuffix(dom.getStyle(cellElm, 'width') || dom.getAttrib(cellElm, 'width')),
- height: removePxSuffix(dom.getStyle(cellElm, 'height') || dom.getAttrib(cellElm, 'height')),
- scope: dom.getAttrib(cellElm, 'scope')
- };
-
- data.type = cellElm.nodeName.toLowerCase();
-
- each('left center right'.split(' '), function(name) {
- if (editor.formatter.matchNode(cellElm, 'align' + name)) {
- data.align = name;
- }
- });
-
- editor.windowManager.open({
- title: "Cell properties",
- items: {
- type: 'form',
- data: data,
- layout: 'grid',
- columns: 2,
- defaults: {
- type: 'textbox',
- maxWidth: 50
- },
- items: [
- {label: 'Width', name: 'width'},
- {label: 'Height', name: 'height'},
- {
- label: 'Cell type',
- name: 'type',
- type: 'listbox',
- text: 'None',
- minWidth: 90,
- maxWidth: null,
- values: [
- {text: 'Cell', value: 'td'},
- {text: 'Header cell', value: 'th'}
- ]
- },
- {
- label: 'Scope',
- name: 'scope',
- type: 'listbox',
- text: 'None',
- minWidth: 90,
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Row', value: 'row'},
- {text: 'Column', value: 'col'},
- {text: 'Row group', value: 'rowgroup'},
- {text: 'Column group', value: 'colgroup'}
- ]
- },
- {
- label: 'Alignment',
- name: 'align',
- type: 'listbox',
- text: 'None',
- minWidth: 90,
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Left', value: 'left'},
- {text: 'Center', value: 'center'},
- {text: 'Right', value: 'right'}
- ]
- }
- ]
- },
-
- onsubmit: function() {
- var data = this.toJSON();
-
- editor.undoManager.transact(function() {
- each(cells, function(cellElm) {
- editor.dom.setAttrib(cellElm, 'scope', data.scope);
-
- editor.dom.setStyles(cellElm, {
- width: addSizeSuffix(data.width),
- height: addSizeSuffix(data.height)
- });
-
- // Switch cell type
- if (data.type && cellElm.nodeName.toLowerCase() != data.type) {
- cellElm = dom.rename(cellElm, data.type);
- }
-
- // Apply/remove alignment
- unApplyAlign(cellElm);
- if (data.align) {
- editor.formatter.apply('align' + data.align, {}, cellElm);
- }
- });
-
- editor.focus();
- });
- }
- });
- }
-
- function rowDialog() {
- var dom = editor.dom, tableElm, cellElm, rowElm, data, rows = [];
-
- tableElm = editor.dom.getParent(editor.selection.getStart(), 'table');
- cellElm = editor.dom.getParent(editor.selection.getStart(), 'td,th');
-
- each(tableElm.rows, function(row) {
- each(row.cells, function(cell) {
- if (dom.hasClass(cell, 'mce-item-selected') || cell == cellElm) {
- rows.push(row);
- return false;
- }
- });
- });
-
- rowElm = rows[0];
- if (!rowElm) {
- // If this element is null, return now to avoid crashing.
- return;
- }
-
- data = {
- height: removePxSuffix(dom.getStyle(rowElm, 'height') || dom.getAttrib(rowElm, 'height')),
- scope: dom.getAttrib(rowElm, 'scope')
- };
-
- data.type = rowElm.parentNode.nodeName.toLowerCase();
-
- each('left center right'.split(' '), function(name) {
- if (editor.formatter.matchNode(rowElm, 'align' + name)) {
- data.align = name;
- }
- });
-
- editor.windowManager.open({
- title: "Row properties",
- items: {
- type: 'form',
- data: data,
- columns: 2,
- defaults: {
- type: 'textbox'
- },
- items: [
- {
- type: 'listbox',
- name: 'type',
- label: 'Row type',
- text: 'None',
- maxWidth: null,
- values: [
- {text: 'Header', value: 'thead'},
- {text: 'Body', value: 'tbody'},
- {text: 'Footer', value: 'tfoot'}
- ]
- },
- {
- type: 'listbox',
- name: 'align',
- label: 'Alignment',
- text: 'None',
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Left', value: 'left'},
- {text: 'Center', value: 'center'},
- {text: 'Right', value: 'right'}
- ]
- },
- {label: 'Height', name: 'height'}
- ]
- },
-
- onsubmit: function() {
- var data = this.toJSON(), tableElm, oldParentElm, parentElm;
-
- editor.undoManager.transact(function() {
- var toType = data.type;
-
- each(rows, function(rowElm) {
- editor.dom.setAttrib(rowElm, 'scope', data.scope);
-
- editor.dom.setStyles(rowElm, {
- height: addSizeSuffix(data.height)
- });
-
- if (toType != rowElm.parentNode.nodeName.toLowerCase()) {
- tableElm = dom.getParent(rowElm, 'table');
-
- oldParentElm = rowElm.parentNode;
- parentElm = dom.select(toType, tableElm)[0];
- if (!parentElm) {
- parentElm = dom.create(toType);
- if (tableElm.firstChild) {
- tableElm.insertBefore(parentElm, tableElm.firstChild);
- } else {
- tableElm.appendChild(parentElm);
- }
- }
-
- parentElm.appendChild(rowElm);
-
- if (!oldParentElm.hasChildNodes()) {
- dom.remove(oldParentElm);
- }
- }
-
- // Apply/remove alignment
- unApplyAlign(rowElm);
- if (data.align) {
- editor.formatter.apply('align' + data.align, {}, rowElm);
- }
- });
-
- editor.focus();
- });
- }
- });
- }
-
- function cmd(command) {
- return function() {
- editor.execCommand(command);
- };
- }
-
- function insertTable(cols, rows) {
- var y, x, html;
-
- html = '';
-
- for (y = 0; y < rows; y++) {
- html += '
';
-
- editor.insertContent(html);
- }
-
- function handleDisabledState(ctrl, selector) {
- function bindStateListener() {
- ctrl.disabled(!editor.dom.getParent(editor.selection.getStart(), selector));
-
- editor.selection.selectorChanged(selector, function(state) {
- ctrl.disabled(!state);
- });
- }
-
- if (editor.initialized) {
- bindStateListener();
- } else {
- editor.on('init', bindStateListener);
- }
- }
-
- function postRender() {
- /*jshint validthis:true*/
- handleDisabledState(this, 'table');
- }
-
- function postRenderCell() {
- /*jshint validthis:true*/
- handleDisabledState(this, 'td,th');
- }
-
- function generateTableGrid() {
- var html = '';
-
- html = '';
-
- for (x = 0; x < cols; x++) {
- html += ' ';
- }
-
- html += '' + (Env.ie ? " " : ' ';
- }
-
- html += '
') + '';
-
- for (var y = 0; y < 10; y++) {
- html += '
';
-
- html += '';
-
- for (var x = 0; x < 10; x++) {
- html += ' ';
- }
-
- html += '';
- }
-
- html += '
' : nbsp;
+ tableElm.insertBefore(captionElm, tableElm.firstChild);
+ }
+ if (data.align === '') {
+ unApplyAlign(editor, tableElm);
+ } else {
+ applyAlign(editor, tableElm, data.align);
+ }
+ editor.focus();
+ editor.addVisual();
+ });
+ };
+ var open$2 = function (editor, insertNewTable) {
+ var dom = editor.dom;
+ var tableElm;
+ var data = extractDataFromSettings(editor, hasAdvancedTableTab(editor));
+ if (insertNewTable === false) {
+ tableElm = dom.getParent(editor.selection.getStart(), 'table');
+ if (tableElm) {
+ data = extractDataFromTableElement(editor, tableElm, hasAdvancedTableTab(editor));
+ } else {
+ if (hasAdvancedTableTab(editor)) {
+ data.borderstyle = '';
+ data.bordercolor = '';
+ data.backgroundcolor = '';
+ }
+ }
+ } else {
+ data.cols = '1';
+ data.rows = '1';
+ if (hasAdvancedTableTab(editor)) {
+ data.borderstyle = '';
+ data.bordercolor = '';
+ data.backgroundcolor = '';
+ }
+ }
+ var classes = buildListItems(getTableClassList(editor));
+ if (classes.length > 0) {
+ if (data.class) {
+ data.class = data.class.replace(/\s*mce\-item\-table\s*/g, '');
+ }
+ }
+ var generalPanel = {
+ type: 'grid',
+ columns: 2,
+ items: getItems$2(editor, classes, insertNewTable)
+ };
+ var nonAdvancedForm = function () {
+ return {
+ type: 'panel',
+ items: [generalPanel]
+ };
+ };
+ var advancedForm = function () {
+ return {
+ type: 'tabpanel',
+ tabs: [
+ {
+ title: 'General',
+ name: 'general',
+ items: [generalPanel]
+ },
+ getAdvancedTab('table')
+ ]
+ };
+ };
+ var dialogBody = hasAdvancedTableTab(editor) ? advancedForm() : nonAdvancedForm();
+ editor.windowManager.open({
+ title: 'Table Properties',
+ size: 'normal',
+ body: dialogBody,
+ onSubmit: curry(onSubmitTableForm, editor, tableElm),
+ buttons: [
+ {
+ type: 'cancel',
+ name: 'cancel',
+ text: 'Cancel'
+ },
+ {
+ type: 'submit',
+ name: 'save',
+ text: 'Save',
+ primary: true
+ }
+ ],
+ initialData: data
+ });
+ };
+
+ var getSelectionStartCellOrCaption$1 = function (editor) {
+ return getSelectionStartCellOrCaption(getSelectionStart(editor));
+ };
+ var getSelectionStartCell$1 = function (editor) {
+ return getSelectionStartCell(getSelectionStart(editor));
+ };
+ var registerCommands = function (editor, actions, cellSelection, selections, clipboard) {
+ var isRoot = getIsRoot(editor);
+ var eraseTable = function () {
+ return getSelectionStartCellOrCaption$1(editor).each(function (cellOrCaption) {
+ table(cellOrCaption, isRoot).filter(not(isRoot)).each(function (table) {
+ var cursor = SugarElement.fromText('');
+ after(table, cursor);
+ remove$2(table);
+ if (editor.dom.isEmpty(editor.getBody())) {
+ editor.setContent('');
+ editor.selection.setCursorLocation();
+ } else {
+ var rng = editor.dom.createRng();
+ rng.setStart(cursor.dom, 0);
+ rng.setEnd(cursor.dom, 0);
+ editor.selection.setRng(rng);
+ editor.nodeChanged();
+ }
+ });
+ });
+ };
+ var setSizingMode = function (sizing) {
+ return getSelectionStartCellOrCaption$1(editor).each(function (cellOrCaption) {
+ var isForcedSizing = isResponsiveForced(editor) || isPixelsForced(editor) || isPercentagesForced(editor);
+ if (!isForcedSizing) {
+ table(cellOrCaption, isRoot).each(function (table) {
+ if (sizing === 'relative' && !isPercentSizing$1(table)) {
+ enforcePercentage(editor, table);
+ } else if (sizing === 'fixed' && !isPixelSizing$1(table)) {
+ enforcePixels(editor, table);
+ } else if (sizing === 'responsive' && !isNoneSizing$1(table)) {
+ enforceNone(table);
+ }
+ removeDataStyle(table);
+ });
+ }
+ });
+ };
+ var getTableFromCell = function (cell) {
+ return table(cell, isRoot);
+ };
+ var actOnSelection = function (execute) {
+ return getSelectionStartCell$1(editor).each(function (cell) {
+ getTableFromCell(cell).each(function (table) {
+ var targets = forMenu(selections, table, cell);
+ execute(table, targets).each(function (rng) {
+ editor.selection.setRng(rng);
+ editor.focus();
+ cellSelection.clear(table);
+ removeDataStyle(table);
+ });
+ });
+ });
+ };
+ var copyRowSelection = function () {
+ return getSelectionStartCell$1(editor).map(function (cell) {
+ return getTableFromCell(cell).bind(function (table) {
+ var targets = forMenu(selections, table, cell);
+ var generators = cellOperations(noop, SugarElement.fromDom(editor.getDoc()), Optional.none());
+ return copyRows(table, targets, generators);
+ });
+ });
+ };
+ var copyColSelection = function () {
+ return getSelectionStartCell$1(editor).map(function (cell) {
+ return getTableFromCell(cell).bind(function (table) {
+ var targets = forMenu(selections, table, cell);
+ return copyCols(table, targets);
+ });
+ });
+ };
+ var pasteOnSelection = function (execute, getRows) {
+ return getRows().each(function (rows) {
+ var clonedRows = map(rows, function (row) {
+ return deep(row);
+ });
+ getSelectionStartCell$1(editor).each(function (cell) {
+ return getTableFromCell(cell).each(function (table) {
+ var generators = paste(SugarElement.fromDom(editor.getDoc()));
+ var targets = pasteRows(selections, cell, clonedRows, generators);
+ execute(table, targets).each(function (rng) {
+ editor.selection.setRng(rng);
+ editor.focus();
+ cellSelection.clear(table);
+ });
+ });
+ });
+ });
+ };
+ each$1({
+ mceTableSplitCells: function () {
+ return actOnSelection(actions.unmergeCells);
+ },
+ mceTableMergeCells: function () {
+ return actOnSelection(actions.mergeCells);
+ },
+ mceTableInsertRowBefore: function () {
+ return actOnSelection(actions.insertRowsBefore);
+ },
+ mceTableInsertRowAfter: function () {
+ return actOnSelection(actions.insertRowsAfter);
+ },
+ mceTableInsertColBefore: function () {
+ return actOnSelection(actions.insertColumnsBefore);
+ },
+ mceTableInsertColAfter: function () {
+ return actOnSelection(actions.insertColumnsAfter);
+ },
+ mceTableDeleteCol: function () {
+ return actOnSelection(actions.deleteColumn);
+ },
+ mceTableDeleteRow: function () {
+ return actOnSelection(actions.deleteRow);
+ },
+ mceTableCutCol: function (_grid) {
+ return copyColSelection().each(function (selection) {
+ clipboard.setColumns(selection);
+ actOnSelection(actions.deleteColumn);
+ });
+ },
+ mceTableCutRow: function (_grid) {
+ return copyRowSelection().each(function (selection) {
+ clipboard.setRows(selection);
+ actOnSelection(actions.deleteRow);
+ });
+ },
+ mceTableCopyCol: function (_grid) {
+ return copyColSelection().each(function (selection) {
+ return clipboard.setColumns(selection);
+ });
+ },
+ mceTableCopyRow: function (_grid) {
+ return copyRowSelection().each(function (selection) {
+ return clipboard.setRows(selection);
+ });
+ },
+ mceTablePasteColBefore: function (_grid) {
+ return pasteOnSelection(actions.pasteColsBefore, clipboard.getColumns);
+ },
+ mceTablePasteColAfter: function (_grid) {
+ return pasteOnSelection(actions.pasteColsAfter, clipboard.getColumns);
+ },
+ mceTablePasteRowBefore: function (_grid) {
+ return pasteOnSelection(actions.pasteRowsBefore, clipboard.getRows);
+ },
+ mceTablePasteRowAfter: function (_grid) {
+ return pasteOnSelection(actions.pasteRowsAfter, clipboard.getRows);
+ },
+ mceTableDelete: eraseTable,
+ mceTableSizingMode: function (ui, sizing) {
+ return setSizingMode(sizing);
+ }
+ }, function (func, name) {
+ return editor.addCommand(name, func);
+ });
+ each$1({
+ mceTableCellType: function (_ui, args) {
+ return actions.setTableCellType(editor, args);
+ },
+ mceTableRowType: function (_ui, args) {
+ return actions.setTableRowType(editor, args);
+ }
+ }, function (func, name) {
+ return editor.addCommand(name, func);
+ });
+ editor.addCommand('mceTableColType', function (_ui, args) {
+ return get(args, 'type').each(function (type) {
+ return actOnSelection(type === 'th' ? actions.makeColumnHeader : actions.unmakeColumnHeader);
+ });
+ });
+ each$1({
+ mceTableProps: curry(open$2, editor, false),
+ mceTableRowProps: curry(open$1, editor),
+ mceTableCellProps: curry(open, editor, selections)
+ }, function (func, name) {
+ return editor.addCommand(name, function () {
+ return func();
+ });
+ });
+ editor.addCommand('mceInsertTable', function (_ui, args) {
+ if (isObject(args) && keys(args).length > 0) {
+ insertTableWithDataValidation(editor, args.rows, args.columns, args.options, 'Invalid values for mceInsertTable - rows and columns values are required to insert a table.');
+ } else {
+ open$2(editor, true);
+ }
+ });
+ editor.addCommand('mceTableApplyCellStyle', function (_ui, args) {
+ if (!isObject(args)) {
+ return;
+ }
+ var cells = getCellsFromSelection(getSelectionStart(editor), selections);
+ if (cells.length === 0) {
+ return;
+ }
+ each$1(args, function (value, style) {
+ var formatName = 'tablecell' + style.toLowerCase().replace('-', '');
+ if (editor.formatter.has(formatName) && isString(value)) {
+ each(cells, function (cell) {
+ DomModifier.normal(editor, cell.dom).setFormat(formatName, value);
+ });
+ }
+ });
+ });
+ };
+
+ var registerQueryCommands = function (editor, actions, selections) {
+ var isRoot = getIsRoot(editor);
+ var getTableFromCell = function (cell) {
+ return table(cell, isRoot);
+ };
+ each$1({
+ mceTableRowType: function () {
+ return actions.getTableRowType(editor);
+ },
+ mceTableCellType: function () {
+ return actions.getTableCellType(editor);
+ },
+ mceTableColType: function () {
+ return getSelectionStartCell(getSelectionStart(editor)).bind(function (cell) {
+ return getTableFromCell(cell).map(function (table) {
+ var targets = forMenu(selections, table, cell);
+ return actions.getTableColType(table, targets);
+ });
+ }).getOr('');
+ }
+ }, function (func, name) {
+ return editor.addQueryValueHandler(name, func);
+ });
+ };
+
+ var Clipboard = function () {
+ var rows = Cell(Optional.none());
+ var cols = Cell(Optional.none());
+ var clearClipboard = function (clipboard) {
+ clipboard.set(Optional.none());
+ };
+ return {
+ getRows: rows.get,
+ setRows: function (r) {
+ rows.set(r);
+ clearClipboard(cols);
+ },
+ clearRows: function () {
+ return clearClipboard(rows);
+ },
+ getColumns: cols.get,
+ setColumns: function (c) {
+ cols.set(c);
+ clearClipboard(rows);
+ },
+ clearColumns: function () {
+ return clearClipboard(cols);
+ }
+ };
+ };
+
+ var cellFormats = {
+ tablecellbackgroundcolor: {
+ selector: 'td,th',
+ styles: { backgroundColor: '%value' },
+ remove_similar: true
+ },
+ tablecellbordercolor: {
+ selector: 'td,th',
+ styles: { borderColor: '%value' },
+ remove_similar: true
+ },
+ tablecellborderstyle: {
+ selector: 'td,th',
+ styles: { borderStyle: '%value' },
+ remove_similar: true
+ },
+ tablecellborderwidth: {
+ selector: 'td,th',
+ styles: { borderWidth: '%value' },
+ remove_similar: true
+ }
+ };
+ var registerFormats = function (editor) {
+ editor.formatter.register(cellFormats);
+ };
+
+ var adt$2 = Adt.generate([
+ { none: ['current'] },
+ { first: ['current'] },
+ {
+ middle: [
+ 'current',
+ 'target'
+ ]
+ },
+ { last: ['current'] }
+ ]);
+ var none$2 = function (current) {
+ if (current === void 0) {
+ current = undefined;
+ }
+ return adt$2.none(current);
+ };
+ var CellLocation = __assign(__assign({}, adt$2), { none: none$2 });
+
+ var detect$5 = function (current, isRoot) {
+ return table(current, isRoot).bind(function (table) {
+ var all = cells(table);
+ var index = findIndex(all, function (x) {
+ return eq(current, x);
+ });
+ return index.map(function (index) {
+ return {
+ index: index,
+ all: all
+ };
+ });
+ });
+ };
+ var next = function (current, isRoot) {
+ var detection = detect$5(current, isRoot);
+ return detection.fold(function () {
+ return CellLocation.none(current);
+ }, function (info) {
+ return info.index + 1 < info.all.length ? CellLocation.middle(current, info.all[info.index + 1]) : CellLocation.last(current);
+ });
+ };
+ var prev = function (current, isRoot) {
+ var detection = detect$5(current, isRoot);
+ return detection.fold(function () {
+ return CellLocation.none();
+ }, function (info) {
+ return info.index - 1 >= 0 ? CellLocation.middle(current, info.all[info.index - 1]) : CellLocation.first(current);
+ });
+ };
+
+ var create$2 = function (start, soffset, finish, foffset) {
+ return {
+ start: start,
+ soffset: soffset,
+ finish: finish,
+ foffset: foffset
+ };
+ };
+ var SimRange = { create: create$2 };
+
+ var adt$3 = Adt.generate([
+ { before: ['element'] },
+ {
+ on: [
+ 'element',
+ 'offset'
+ ]
+ },
+ { after: ['element'] }
+ ]);
+ var cata$1 = function (subject, onBefore, onOn, onAfter) {
+ return subject.fold(onBefore, onOn, onAfter);
+ };
+ var getStart = function (situ) {
+ return situ.fold(identity, identity, identity);
+ };
+ var before$2 = adt$3.before;
+ var on = adt$3.on;
+ var after$2 = adt$3.after;
+ var Situ = {
+ before: before$2,
+ on: on,
+ after: after$2,
+ cata: cata$1,
+ getStart: getStart
+ };
+
+ var adt$4 = Adt.generate([
+ { domRange: ['rng'] },
+ {
+ relative: [
+ 'startSitu',
+ 'finishSitu'
+ ]
+ },
+ {
+ exact: [
+ 'start',
+ 'soffset',
+ 'finish',
+ 'foffset'
+ ]
+ }
+ ]);
+ var exactFromRange = function (simRange) {
+ return adt$4.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
+ };
+ var getStart$1 = function (selection) {
+ return selection.match({
+ domRange: function (rng) {
+ return SugarElement.fromDom(rng.startContainer);
+ },
+ relative: function (startSitu, _finishSitu) {
+ return Situ.getStart(startSitu);
+ },
+ exact: function (start, _soffset, _finish, _foffset) {
+ return start;
+ }
+ });
+ };
+ var domRange = adt$4.domRange;
+ var relative = adt$4.relative;
+ var exact = adt$4.exact;
+ var getWin = function (selection) {
+ var start = getStart$1(selection);
+ return defaultView(start);
+ };
+ var range$1 = SimRange.create;
+ var SimSelection = {
+ domRange: domRange,
+ relative: relative,
+ exact: exact,
+ exactFromRange: exactFromRange,
+ getWin: getWin,
+ range: range$1
+ };
+
+ var selectNodeContents = function (win, element) {
+ var rng = win.document.createRange();
+ selectNodeContentsUsing(rng, element);
+ return rng;
+ };
+ var selectNodeContentsUsing = function (rng, element) {
+ return rng.selectNodeContents(element.dom);
+ };
+ var setStart = function (rng, situ) {
+ situ.fold(function (e) {
+ rng.setStartBefore(e.dom);
+ }, function (e, o) {
+ rng.setStart(e.dom, o);
+ }, function (e) {
+ rng.setStartAfter(e.dom);
+ });
+ };
+ var setFinish = function (rng, situ) {
+ situ.fold(function (e) {
+ rng.setEndBefore(e.dom);
+ }, function (e, o) {
+ rng.setEnd(e.dom, o);
+ }, function (e) {
+ rng.setEndAfter(e.dom);
+ });
+ };
+ var relativeToNative = function (win, startSitu, finishSitu) {
+ var range = win.document.createRange();
+ setStart(range, startSitu);
+ setFinish(range, finishSitu);
+ return range;
+ };
+ var exactToNative = function (win, start, soffset, finish, foffset) {
+ var rng = win.document.createRange();
+ rng.setStart(start.dom, soffset);
+ rng.setEnd(finish.dom, foffset);
+ return rng;
+ };
+ var toRect = function (rect) {
+ return {
+ left: rect.left,
+ top: rect.top,
+ right: rect.right,
+ bottom: rect.bottom,
+ width: rect.width,
+ height: rect.height
+ };
+ };
+ var getFirstRect = function (rng) {
+ var rects = rng.getClientRects();
+ var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
+ return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
+ };
+
+ var adt$5 = Adt.generate([
+ {
+ ltr: [
+ 'start',
+ 'soffset',
+ 'finish',
+ 'foffset'
+ ]
+ },
+ {
+ rtl: [
+ 'start',
+ 'soffset',
+ 'finish',
+ 'foffset'
+ ]
+ }
+ ]);
+ var fromRange = function (win, type, range) {
+ return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
+ };
+ var getRanges = function (win, selection) {
+ return selection.match({
+ domRange: function (rng) {
+ return {
+ ltr: constant(rng),
+ rtl: Optional.none
+ };
+ },
+ relative: function (startSitu, finishSitu) {
+ return {
+ ltr: cached(function () {
+ return relativeToNative(win, startSitu, finishSitu);
+ }),
+ rtl: cached(function () {
+ return Optional.some(relativeToNative(win, finishSitu, startSitu));
+ })
+ };
+ },
+ exact: function (start, soffset, finish, foffset) {
+ return {
+ ltr: cached(function () {
+ return exactToNative(win, start, soffset, finish, foffset);
+ }),
+ rtl: cached(function () {
+ return Optional.some(exactToNative(win, finish, foffset, start, soffset));
+ })
+ };
+ }
+ });
+ };
+ var doDiagnose = function (win, ranges) {
+ var rng = ranges.ltr();
+ if (rng.collapsed) {
+ var reversed = ranges.rtl().filter(function (rev) {
+ return rev.collapsed === false;
+ });
+ return reversed.map(function (rev) {
+ return adt$5.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
+ }).getOrThunk(function () {
+ return fromRange(win, adt$5.ltr, rng);
+ });
+ } else {
+ return fromRange(win, adt$5.ltr, rng);
+ }
+ };
+ var diagnose = function (win, selection) {
+ var ranges = getRanges(win, selection);
+ return doDiagnose(win, ranges);
+ };
+ var asLtrRange = function (win, selection) {
+ var diagnosis = diagnose(win, selection);
+ return diagnosis.match({
+ ltr: function (start, soffset, finish, foffset) {
+ var rng = win.document.createRange();
+ rng.setStart(start.dom, soffset);
+ rng.setEnd(finish.dom, foffset);
+ return rng;
+ },
+ rtl: function (start, soffset, finish, foffset) {
+ var rng = win.document.createRange();
+ rng.setStart(finish.dom, foffset);
+ rng.setEnd(start.dom, soffset);
+ return rng;
+ }
+ });
+ };
+ var ltr$1 = adt$5.ltr;
+ var rtl$1 = adt$5.rtl;
+
+ var searchForPoint = function (rectForOffset, x, y, maxX, length) {
+ if (length === 0) {
+ return 0;
+ } else if (x === maxX) {
+ return length - 1;
+ }
+ var xDelta = maxX;
+ for (var i = 1; i < length; i++) {
+ var rect = rectForOffset(i);
+ var curDeltaX = Math.abs(x - rect.left);
+ if (y <= rect.bottom) {
+ if (y < rect.top || curDeltaX > xDelta) {
+ return i - 1;
+ } else {
+ xDelta = curDeltaX;
+ }
+ }
+ }
+ return 0;
+ };
+ var inRect = function (rect, x, y) {
+ return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
+ };
+
+ var locateOffset = function (doc, textnode, x, y, rect) {
+ var rangeForOffset = function (o) {
+ var r = doc.dom.createRange();
+ r.setStart(textnode.dom, o);
+ r.collapse(true);
+ return r;
+ };
+ var rectForOffset = function (o) {
+ var r = rangeForOffset(o);
+ return r.getBoundingClientRect();
+ };
+ var length = get$3(textnode).length;
+ var offset = searchForPoint(rectForOffset, x, y, rect.right, length);
+ return rangeForOffset(offset);
+ };
+ var locate = function (doc, node, x, y) {
+ var r = doc.dom.createRange();
+ r.selectNode(node.dom);
+ var rects = r.getClientRects();
+ var foundRect = findMap(rects, function (rect) {
+ return inRect(rect, x, y) ? Optional.some(rect) : Optional.none();
+ });
+ return foundRect.map(function (rect) {
+ return locateOffset(doc, node, x, y, rect);
+ });
+ };
+
+ var searchInChildren = function (doc, node, x, y) {
+ var r = doc.dom.createRange();
+ var nodes = children(node);
+ return findMap(nodes, function (n) {
+ r.selectNode(n.dom);
+ return inRect(r.getBoundingClientRect(), x, y) ? locateNode(doc, n, x, y) : Optional.none();
+ });
+ };
+ var locateNode = function (doc, node, x, y) {
+ return isText(node) ? locate(doc, node, x, y) : searchInChildren(doc, node, x, y);
+ };
+ var locate$1 = function (doc, node, x, y) {
+ var r = doc.dom.createRange();
+ r.selectNode(node.dom);
+ var rect = r.getBoundingClientRect();
+ var boundedX = Math.max(rect.left, Math.min(rect.right, x));
+ var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
+ return locateNode(doc, node, boundedX, boundedY);
+ };
+
+ var COLLAPSE_TO_LEFT = true;
+ var COLLAPSE_TO_RIGHT = false;
+ var getCollapseDirection = function (rect, x) {
+ return x - rect.left < rect.right - x ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
+ };
+ var createCollapsedNode = function (doc, target, collapseDirection) {
+ var r = doc.dom.createRange();
+ r.selectNode(target.dom);
+ r.collapse(collapseDirection);
+ return r;
+ };
+ var locateInElement = function (doc, node, x) {
+ var cursorRange = doc.dom.createRange();
+ cursorRange.selectNode(node.dom);
+ var rect = cursorRange.getBoundingClientRect();
+ var collapseDirection = getCollapseDirection(rect, x);
+ var f = collapseDirection === COLLAPSE_TO_LEFT ? first : last$1;
+ return f(node).map(function (target) {
+ return createCollapsedNode(doc, target, collapseDirection);
+ });
+ };
+ var locateInEmpty = function (doc, node, x) {
+ var rect = node.dom.getBoundingClientRect();
+ var collapseDirection = getCollapseDirection(rect, x);
+ return Optional.some(createCollapsedNode(doc, node, collapseDirection));
+ };
+ var search = function (doc, node, x) {
+ var f = children(node).length === 0 ? locateInEmpty : locateInElement;
+ return f(doc, node, x);
+ };
+
+ var caretPositionFromPoint = function (doc, x, y) {
+ return Optional.from(doc.dom.caretPositionFromPoint(x, y)).bind(function (pos) {
+ if (pos.offsetNode === null) {
+ return Optional.none();
+ }
+ var r = doc.dom.createRange();
+ r.setStart(pos.offsetNode, pos.offset);
+ r.collapse();
+ return Optional.some(r);
+ });
+ };
+ var caretRangeFromPoint = function (doc, x, y) {
+ return Optional.from(doc.dom.caretRangeFromPoint(x, y));
+ };
+ var searchTextNodes = function (doc, node, x, y) {
+ var r = doc.dom.createRange();
+ r.selectNode(node.dom);
+ var rect = r.getBoundingClientRect();
+ var boundedX = Math.max(rect.left, Math.min(rect.right, x));
+ var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
+ return locate$1(doc, node, boundedX, boundedY);
+ };
+ var searchFromPoint = function (doc, x, y) {
+ return SugarElement.fromPoint(doc, x, y).bind(function (elem) {
+ var fallback = function () {
+ return search(doc, elem, x);
+ };
+ return children(elem).length === 0 ? fallback() : searchTextNodes(doc, elem, x, y).orThunk(fallback);
+ });
+ };
+ var availableSearch = document.caretPositionFromPoint ? caretPositionFromPoint : document.caretRangeFromPoint ? caretRangeFromPoint : searchFromPoint;
+ var fromPoint$1 = function (win, x, y) {
+ var doc = SugarElement.fromDom(win.document);
+ return availableSearch(doc, x, y).map(function (rng) {
+ return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
+ });
+ };
+
+ var beforeSpecial = function (element, offset) {
+ var name$1 = name(element);
+ if ('input' === name$1) {
+ return Situ.after(element);
+ } else if (!contains([
+ 'br',
+ 'img'
+ ], name$1)) {
+ return Situ.on(element, offset);
+ } else {
+ return offset === 0 ? Situ.before(element) : Situ.after(element);
+ }
+ };
+ var preprocessRelative = function (startSitu, finishSitu) {
+ var start = startSitu.fold(Situ.before, beforeSpecial, Situ.after);
+ var finish = finishSitu.fold(Situ.before, beforeSpecial, Situ.after);
+ return SimSelection.relative(start, finish);
+ };
+ var preprocessExact = function (start, soffset, finish, foffset) {
+ var startSitu = beforeSpecial(start, soffset);
+ var finishSitu = beforeSpecial(finish, foffset);
+ return SimSelection.relative(startSitu, finishSitu);
+ };
+ var preprocess = function (selection) {
+ return selection.match({
+ domRange: function (rng) {
+ var start = SugarElement.fromDom(rng.startContainer);
+ var finish = SugarElement.fromDom(rng.endContainer);
+ return preprocessExact(start, rng.startOffset, finish, rng.endOffset);
+ },
+ relative: preprocessRelative,
+ exact: preprocessExact
+ });
+ };
+
+ var makeRange = function (start, soffset, finish, foffset) {
+ var doc = owner(start);
+ var rng = doc.dom.createRange();
+ rng.setStart(start.dom, soffset);
+ rng.setEnd(finish.dom, foffset);
+ return rng;
+ };
+ var after$3 = function (start, soffset, finish, foffset) {
+ var r = makeRange(start, soffset, finish, foffset);
+ var same = eq(start, finish) && soffset === foffset;
+ return r.collapsed && !same;
+ };
+
+ var getNativeSelection = function (win) {
+ return Optional.from(win.getSelection());
+ };
+ var doSetNativeRange = function (win, rng) {
+ getNativeSelection(win).each(function (selection) {
+ selection.removeAllRanges();
+ selection.addRange(rng);
+ });
+ };
+ var doSetRange = function (win, start, soffset, finish, foffset) {
+ var rng = exactToNative(win, start, soffset, finish, foffset);
+ doSetNativeRange(win, rng);
+ };
+ var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
+ selection.collapse(start.dom, soffset);
+ selection.extend(finish.dom, foffset);
+ };
+ var setRangeFromRelative = function (win, relative) {
+ return diagnose(win, relative).match({
+ ltr: function (start, soffset, finish, foffset) {
+ doSetRange(win, start, soffset, finish, foffset);
+ },
+ rtl: function (start, soffset, finish, foffset) {
+ getNativeSelection(win).each(function (selection) {
+ if (selection.setBaseAndExtent) {
+ selection.setBaseAndExtent(start.dom, soffset, finish.dom, foffset);
+ } else if (selection.extend) {
+ try {
+ setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
+ } catch (e) {
+ doSetRange(win, finish, foffset, start, soffset);
+ }
+ } else {
+ doSetRange(win, finish, foffset, start, soffset);
+ }
+ });
+ }
+ });
+ };
+ var setExact = function (win, start, soffset, finish, foffset) {
+ var relative = preprocessExact(start, soffset, finish, foffset);
+ setRangeFromRelative(win, relative);
+ };
+ var setRelative = function (win, startSitu, finishSitu) {
+ var relative = preprocessRelative(startSitu, finishSitu);
+ setRangeFromRelative(win, relative);
+ };
+ var toNative = function (selection) {
+ var win = SimSelection.getWin(selection).dom;
+ var getDomRange = function (start, soffset, finish, foffset) {
+ return exactToNative(win, start, soffset, finish, foffset);
+ };
+ var filtered = preprocess(selection);
+ return diagnose(win, filtered).match({
+ ltr: getDomRange,
+ rtl: getDomRange
+ });
+ };
+ var readRange = function (selection) {
+ if (selection.rangeCount > 0) {
+ var firstRng = selection.getRangeAt(0);
+ var lastRng = selection.getRangeAt(selection.rangeCount - 1);
+ return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
+ } else {
+ return Optional.none();
+ }
+ };
+ var doGetExact = function (selection) {
+ if (selection.anchorNode === null || selection.focusNode === null) {
+ return readRange(selection);
+ } else {
+ var anchor = SugarElement.fromDom(selection.anchorNode);
+ var focus_1 = SugarElement.fromDom(selection.focusNode);
+ return after$3(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
+ }
+ };
+ var setToElement = function (win, element) {
+ var rng = selectNodeContents(win, element);
+ doSetNativeRange(win, rng);
+ };
+ var getExact = function (win) {
+ return getNativeSelection(win).filter(function (sel) {
+ return sel.rangeCount > 0;
+ }).bind(doGetExact);
+ };
+ var get$b = function (win) {
+ return getExact(win).map(function (range) {
+ return SimSelection.exact(range.start, range.soffset, range.finish, range.foffset);
+ });
+ };
+ var getFirstRect$1 = function (win, selection) {
+ var rng = asLtrRange(win, selection);
+ return getFirstRect(rng);
+ };
+ var getAtPoint = function (win, x, y) {
+ return fromPoint$1(win, x, y);
+ };
+ var clear = function (win) {
+ getNativeSelection(win).each(function (selection) {
+ return selection.removeAllRanges();
+ });
+ };
+
+ var global$3 = tinymce.util.Tools.resolve('tinymce.util.VK');
+
+ var forward = function (editor, isRoot, cell, actions) {
+ return go(editor, isRoot, next(cell), actions);
+ };
+ var backward = function (editor, isRoot, cell, actions) {
+ return go(editor, isRoot, prev(cell), actions);
+ };
+ var getCellFirstCursorPosition = function (editor, cell) {
+ var selection = SimSelection.exact(cell, 0, cell, 0);
+ return toNative(selection);
+ };
+ var getNewRowCursorPosition = function (editor, table) {
+ var rows = descendants$1(table, 'tr');
+ return last(rows).bind(function (last) {
+ return descendant$1(last, 'td,th').map(function (first) {
+ return getCellFirstCursorPosition(editor, first);
+ });
+ });
+ };
+ var go = function (editor, isRoot, cell, actions) {
+ return cell.fold(Optional.none, Optional.none, function (current, next) {
+ return first(next).map(function (cell) {
+ return getCellFirstCursorPosition(editor, cell);
+ });
+ }, function (current) {
+ return table(current, isRoot).bind(function (table) {
+ var targets = noMenu(current);
+ editor.undoManager.transact(function () {
+ actions.insertRowsAfter(table, targets);
+ });
+ return getNewRowCursorPosition(editor, table);
+ });
+ });
+ };
+ var rootElements = [
+ 'table',
+ 'li',
+ 'dl'
+ ];
+ var handle$1 = function (event, editor, actions) {
+ if (event.keyCode === global$3.TAB) {
+ var body_1 = getBody$1(editor);
+ var isRoot_1 = function (element) {
+ var name$1 = name(element);
+ return eq(element, body_1) || contains(rootElements, name$1);
+ };
+ var rng = editor.selection.getRng();
+ if (rng.collapsed) {
+ var start = SugarElement.fromDom(rng.startContainer);
+ cell(start, isRoot_1).each(function (cell) {
+ event.preventDefault();
+ var navigation = event.shiftKey ? backward : forward;
+ var rng = navigation(editor, isRoot_1, cell, actions);
+ rng.each(function (range) {
+ editor.selection.setRng(range);
+ });
+ });
+ }
+ }
+ };
+
+ var create$3 = function (selection, kill) {
+ return {
+ selection: selection,
+ kill: kill
+ };
+ };
+ var Response = { create: create$3 };
+
+ var create$4 = function (start, soffset, finish, foffset) {
+ return {
+ start: Situ.on(start, soffset),
+ finish: Situ.on(finish, foffset)
+ };
+ };
+ var Situs = { create: create$4 };
+
+ var convertToRange = function (win, selection) {
+ var rng = asLtrRange(win, selection);
+ return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
+ };
+ var makeSitus = Situs.create;
+
+ var sync = function (container, isRoot, start, soffset, finish, foffset, selectRange) {
+ if (!(eq(start, finish) && soffset === foffset)) {
+ return closest$1(start, 'td,th', isRoot).bind(function (s) {
+ return closest$1(finish, 'td,th', isRoot).bind(function (f) {
+ return detect$6(container, isRoot, s, f, selectRange);
+ });
+ });
+ } else {
+ return Optional.none();
+ }
+ };
+ var detect$6 = function (container, isRoot, start, finish, selectRange) {
+ if (!eq(start, finish)) {
+ return identify(start, finish, isRoot).bind(function (cellSel) {
+ var boxes = cellSel.boxes.getOr([]);
+ if (boxes.length > 0) {
+ selectRange(container, boxes, cellSel.start, cellSel.finish);
+ return Optional.some(Response.create(Optional.some(makeSitus(start, 0, start, getEnd(start))), true));
+ } else {
+ return Optional.none();
+ }
+ });
+ } else {
+ return Optional.none();
+ }
+ };
+ var update = function (rows, columns, container, selected, annotations) {
+ var updateSelection = function (newSels) {
+ annotations.clearBeforeUpdate(container);
+ annotations.selectRange(container, newSels.boxes, newSels.start, newSels.finish);
+ return newSels.boxes;
+ };
+ return shiftSelection(selected, rows, columns, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(updateSelection);
+ };
+
+ var traverse = function (item, mode) {
+ return {
+ item: item,
+ mode: mode
+ };
+ };
+ var backtrack = function (universe, item, _direction, transition) {
+ if (transition === void 0) {
+ transition = sidestep;
+ }
+ return universe.property().parent(item).map(function (p) {
+ return traverse(p, transition);
+ });
+ };
+ var sidestep = function (universe, item, direction, transition) {
+ if (transition === void 0) {
+ transition = advance;
+ }
+ return direction.sibling(universe, item).map(function (p) {
+ return traverse(p, transition);
+ });
+ };
+ var advance = function (universe, item, direction, transition) {
+ if (transition === void 0) {
+ transition = advance;
+ }
+ var children = universe.property().children(item);
+ var result = direction.first(children);
+ return result.map(function (r) {
+ return traverse(r, transition);
+ });
+ };
+ var successors = [
+ {
+ current: backtrack,
+ next: sidestep,
+ fallback: Optional.none()
+ },
+ {
+ current: sidestep,
+ next: advance,
+ fallback: Optional.some(backtrack)
+ },
+ {
+ current: advance,
+ next: advance,
+ fallback: Optional.some(sidestep)
+ }
+ ];
+ var go$1 = function (universe, item, mode, direction, rules) {
+ if (rules === void 0) {
+ rules = successors;
+ }
+ var ruleOpt = find(rules, function (succ) {
+ return succ.current === mode;
+ });
+ return ruleOpt.bind(function (rule) {
+ return rule.current(universe, item, direction, rule.next).orThunk(function () {
+ return rule.fallback.bind(function (fb) {
+ return go$1(universe, item, fb, direction);
+ });
+ });
+ });
+ };
+
+ var left = function () {
+ var sibling = function (universe, item) {
+ return universe.query().prevSibling(item);
+ };
+ var first = function (children) {
+ return children.length > 0 ? Optional.some(children[children.length - 1]) : Optional.none();
+ };
+ return {
+ sibling: sibling,
+ first: first
+ };
+ };
+ var right = function () {
+ var sibling = function (universe, item) {
+ return universe.query().nextSibling(item);
+ };
+ var first = function (children) {
+ return children.length > 0 ? Optional.some(children[0]) : Optional.none();
+ };
+ return {
+ sibling: sibling,
+ first: first
+ };
+ };
+ var Walkers = {
+ left: left,
+ right: right
+ };
+
+ var hone = function (universe, item, predicate, mode, direction, isRoot) {
+ var next = go$1(universe, item, mode, direction);
+ return next.bind(function (n) {
+ if (isRoot(n.item)) {
+ return Optional.none();
+ } else {
+ return predicate(n.item) ? Optional.some(n.item) : hone(universe, n.item, predicate, n.mode, direction, isRoot);
+ }
+ });
+ };
+ var left$1 = function (universe, item, predicate, isRoot) {
+ return hone(universe, item, predicate, sidestep, Walkers.left(), isRoot);
+ };
+ var right$1 = function (universe, item, predicate, isRoot) {
+ return hone(universe, item, predicate, sidestep, Walkers.right(), isRoot);
+ };
+
+ var isLeaf = function (universe) {
+ return function (element) {
+ return universe.property().children(element).length === 0;
+ };
+ };
+ var before$3 = function (universe, item, isRoot) {
+ return seekLeft(universe, item, isLeaf(universe), isRoot);
+ };
+ var after$4 = function (universe, item, isRoot) {
+ return seekRight(universe, item, isLeaf(universe), isRoot);
+ };
+ var seekLeft = left$1;
+ var seekRight = right$1;
+
+ var universe$3 = DomUniverse();
+ var before$4 = function (element, isRoot) {
+ return before$3(universe$3, element, isRoot);
+ };
+ var after$5 = function (element, isRoot) {
+ return after$4(universe$3, element, isRoot);
+ };
+ var seekLeft$1 = function (element, predicate, isRoot) {
+ return seekLeft(universe$3, element, predicate, isRoot);
+ };
+ var seekRight$1 = function (element, predicate, isRoot) {
+ return seekRight(universe$3, element, predicate, isRoot);
+ };
+
+ var ancestor$2 = function (scope, predicate, isRoot) {
+ return ancestor(scope, predicate, isRoot).isSome();
+ };
+
+ var adt$6 = Adt.generate([
+ { none: ['message'] },
+ { success: [] },
+ { failedUp: ['cell'] },
+ { failedDown: ['cell'] }
+ ]);
+ var isOverlapping = function (bridge, before, after) {
+ var beforeBounds = bridge.getRect(before);
+ var afterBounds = bridge.getRect(after);
+ return afterBounds.right > beforeBounds.left && afterBounds.left < beforeBounds.right;
+ };
+ var isRow = function (elem) {
+ return closest$1(elem, 'tr');
+ };
+ var verify = function (bridge, before, beforeOffset, after, afterOffset, failure, isRoot) {
+ return closest$1(after, 'td,th', isRoot).bind(function (afterCell) {
+ return closest$1(before, 'td,th', isRoot).map(function (beforeCell) {
+ if (!eq(afterCell, beforeCell)) {
+ return sharedOne$1(isRow, [
+ afterCell,
+ beforeCell
+ ]).fold(function () {
+ return isOverlapping(bridge, beforeCell, afterCell) ? adt$6.success() : failure(beforeCell);
+ }, function (_sharedRow) {
+ return failure(beforeCell);
+ });
+ } else {
+ return eq(after, afterCell) && getEnd(afterCell) === afterOffset ? failure(beforeCell) : adt$6.none('in same cell');
+ }
+ });
+ }).getOr(adt$6.none('default'));
+ };
+ var cata$2 = function (subject, onNone, onSuccess, onFailedUp, onFailedDown) {
+ return subject.fold(onNone, onSuccess, onFailedUp, onFailedDown);
+ };
+ var BeforeAfter = __assign(__assign({}, adt$6), {
+ verify: verify,
+ cata: cata$2
+ });
+
+ var inParent = function (parent, children, element, index) {
+ return {
+ parent: parent,
+ children: children,
+ element: element,
+ index: index
+ };
+ };
+ var indexInParent = function (element) {
+ return parent(element).bind(function (parent) {
+ var children$1 = children(parent);
+ return indexOf(children$1, element).map(function (index) {
+ return inParent(parent, children$1, element, index);
+ });
+ });
+ };
+ var indexOf = function (elements, element) {
+ return findIndex(elements, curry(eq, element));
+ };
+
+ var isBr = function (elem) {
+ return name(elem) === 'br';
+ };
+ var gatherer = function (cand, gather, isRoot) {
+ return gather(cand, isRoot).bind(function (target) {
+ return isText(target) && get$3(target).trim().length === 0 ? gatherer(target, gather, isRoot) : Optional.some(target);
+ });
+ };
+ var handleBr = function (isRoot, element, direction) {
+ return direction.traverse(element).orThunk(function () {
+ return gatherer(element, direction.gather, isRoot);
+ }).map(direction.relative);
+ };
+ var findBr = function (element, offset) {
+ return child(element, offset).filter(isBr).orThunk(function () {
+ return child(element, offset - 1).filter(isBr);
+ });
+ };
+ var handleParent = function (isRoot, element, offset, direction) {
+ return findBr(element, offset).bind(function (br) {
+ return direction.traverse(br).fold(function () {
+ return gatherer(br, direction.gather, isRoot).map(direction.relative);
+ }, function (adjacent) {
+ return indexInParent(adjacent).map(function (info) {
+ return Situ.on(info.parent, info.index);
+ });
+ });
+ });
+ };
+ var tryBr = function (isRoot, element, offset, direction) {
+ var target = isBr(element) ? handleBr(isRoot, element, direction) : handleParent(isRoot, element, offset, direction);
+ return target.map(function (tgt) {
+ return {
+ start: tgt,
+ finish: tgt
+ };
+ });
+ };
+ var process = function (analysis) {
+ return BeforeAfter.cata(analysis, function (_message) {
+ return Optional.none();
+ }, function () {
+ return Optional.none();
+ }, function (cell) {
+ return Optional.some(point(cell, 0));
+ }, function (cell) {
+ return Optional.some(point(cell, getEnd(cell)));
+ });
+ };
+
+ var moveDown = function (caret, amount) {
+ return {
+ left: caret.left,
+ top: caret.top + amount,
+ right: caret.right,
+ bottom: caret.bottom + amount
+ };
+ };
+ var moveUp = function (caret, amount) {
+ return {
+ left: caret.left,
+ top: caret.top - amount,
+ right: caret.right,
+ bottom: caret.bottom - amount
+ };
+ };
+ var translate = function (caret, xDelta, yDelta) {
+ return {
+ left: caret.left + xDelta,
+ top: caret.top + yDelta,
+ right: caret.right + xDelta,
+ bottom: caret.bottom + yDelta
+ };
+ };
+ var getTop$1 = function (caret) {
+ return caret.top;
+ };
+ var getBottom = function (caret) {
+ return caret.bottom;
+ };
+
+ var getPartialBox = function (bridge, element, offset) {
+ if (offset >= 0 && offset < getEnd(element)) {
+ return bridge.getRangedRect(element, offset, element, offset + 1);
+ } else if (offset > 0) {
+ return bridge.getRangedRect(element, offset - 1, element, offset);
+ }
+ return Optional.none();
+ };
+ var toCaret = function (rect) {
+ return {
+ left: rect.left,
+ top: rect.top,
+ right: rect.right,
+ bottom: rect.bottom
+ };
+ };
+ var getElemBox = function (bridge, element) {
+ return Optional.some(bridge.getRect(element));
+ };
+ var getBoxAt = function (bridge, element, offset) {
+ if (isElement(element)) {
+ return getElemBox(bridge, element).map(toCaret);
+ } else if (isText(element)) {
+ return getPartialBox(bridge, element, offset).map(toCaret);
+ } else {
+ return Optional.none();
+ }
+ };
+ var getEntireBox = function (bridge, element) {
+ if (isElement(element)) {
+ return getElemBox(bridge, element).map(toCaret);
+ } else if (isText(element)) {
+ return bridge.getRangedRect(element, 0, element, getEnd(element)).map(toCaret);
+ } else {
+ return Optional.none();
+ }
+ };
+
+ var JUMP_SIZE = 5;
+ var NUM_RETRIES = 100;
+ var adt$7 = Adt.generate([
+ { none: [] },
+ { retry: ['caret'] }
+ ]);
+ var isOutside = function (caret, box) {
+ return caret.left < box.left || Math.abs(box.right - caret.left) < 1 || caret.left > box.right;
+ };
+ var inOutsideBlock = function (bridge, element, caret) {
+ return closest(element, isBlock$1).fold(never, function (cell) {
+ return getEntireBox(bridge, cell).exists(function (box) {
+ return isOutside(caret, box);
+ });
+ });
+ };
+ var adjustDown = function (bridge, element, guessBox, original, caret) {
+ var lowerCaret = moveDown(caret, JUMP_SIZE);
+ if (Math.abs(guessBox.bottom - original.bottom) < 1) {
+ return adt$7.retry(lowerCaret);
+ } else if (guessBox.top > caret.bottom) {
+ return adt$7.retry(lowerCaret);
+ } else if (guessBox.top === caret.bottom) {
+ return adt$7.retry(moveDown(caret, 1));
+ } else {
+ return inOutsideBlock(bridge, element, caret) ? adt$7.retry(translate(lowerCaret, JUMP_SIZE, 0)) : adt$7.none();
+ }
+ };
+ var adjustUp = function (bridge, element, guessBox, original, caret) {
+ var higherCaret = moveUp(caret, JUMP_SIZE);
+ if (Math.abs(guessBox.top - original.top) < 1) {
+ return adt$7.retry(higherCaret);
+ } else if (guessBox.bottom < caret.top) {
+ return adt$7.retry(higherCaret);
+ } else if (guessBox.bottom === caret.top) {
+ return adt$7.retry(moveUp(caret, 1));
+ } else {
+ return inOutsideBlock(bridge, element, caret) ? adt$7.retry(translate(higherCaret, JUMP_SIZE, 0)) : adt$7.none();
+ }
+ };
+ var upMovement = {
+ point: getTop$1,
+ adjuster: adjustUp,
+ move: moveUp,
+ gather: before$4
+ };
+ var downMovement = {
+ point: getBottom,
+ adjuster: adjustDown,
+ move: moveDown,
+ gather: after$5
+ };
+ var isAtTable = function (bridge, x, y) {
+ return bridge.elementFromPoint(x, y).filter(function (elm) {
+ return name(elm) === 'table';
+ }).isSome();
+ };
+ var adjustForTable = function (bridge, movement, original, caret, numRetries) {
+ return adjustTil(bridge, movement, original, movement.move(caret, JUMP_SIZE), numRetries);
+ };
+ var adjustTil = function (bridge, movement, original, caret, numRetries) {
+ if (numRetries === 0) {
+ return Optional.some(caret);
+ }
+ if (isAtTable(bridge, caret.left, movement.point(caret))) {
+ return adjustForTable(bridge, movement, original, caret, numRetries - 1);
+ }
+ return bridge.situsFromPoint(caret.left, movement.point(caret)).bind(function (guess) {
+ return guess.start.fold(Optional.none, function (element) {
+ return getEntireBox(bridge, element).bind(function (guessBox) {
+ return movement.adjuster(bridge, element, guessBox, original, caret).fold(Optional.none, function (newCaret) {
+ return adjustTil(bridge, movement, original, newCaret, numRetries - 1);
+ });
+ }).orThunk(function () {
+ return Optional.some(caret);
+ });
+ }, Optional.none);
+ });
+ };
+ var ieTryDown = function (bridge, caret) {
+ return bridge.situsFromPoint(caret.left, caret.bottom + JUMP_SIZE);
+ };
+ var ieTryUp = function (bridge, caret) {
+ return bridge.situsFromPoint(caret.left, caret.top - JUMP_SIZE);
+ };
+ var checkScroll = function (movement, adjusted, bridge) {
+ if (movement.point(adjusted) > bridge.getInnerHeight()) {
+ return Optional.some(movement.point(adjusted) - bridge.getInnerHeight());
+ } else if (movement.point(adjusted) < 0) {
+ return Optional.some(-movement.point(adjusted));
+ } else {
+ return Optional.none();
+ }
+ };
+ var retry = function (movement, bridge, caret) {
+ var moved = movement.move(caret, JUMP_SIZE);
+ var adjusted = adjustTil(bridge, movement, caret, moved, NUM_RETRIES).getOr(moved);
+ return checkScroll(movement, adjusted, bridge).fold(function () {
+ return bridge.situsFromPoint(adjusted.left, movement.point(adjusted));
+ }, function (delta) {
+ bridge.scrollBy(0, delta);
+ return bridge.situsFromPoint(adjusted.left, movement.point(adjusted) - delta);
+ });
+ };
+ var Retries = {
+ tryUp: curry(retry, upMovement),
+ tryDown: curry(retry, downMovement),
+ ieTryUp: ieTryUp,
+ ieTryDown: ieTryDown,
+ getJumpSize: constant(JUMP_SIZE)
+ };
+
+ var MAX_RETRIES = 20;
+ var findSpot = function (bridge, isRoot, direction) {
+ return bridge.getSelection().bind(function (sel) {
+ return tryBr(isRoot, sel.finish, sel.foffset, direction).fold(function () {
+ return Optional.some(point(sel.finish, sel.foffset));
+ }, function (brNeighbour) {
+ var range = bridge.fromSitus(brNeighbour);
+ var analysis = BeforeAfter.verify(bridge, sel.finish, sel.foffset, range.finish, range.foffset, direction.failure, isRoot);
+ return process(analysis);
+ });
+ });
+ };
+ var scan$1 = function (bridge, isRoot, element, offset, direction, numRetries) {
+ if (numRetries === 0) {
+ return Optional.none();
+ }
+ return tryCursor(bridge, isRoot, element, offset, direction).bind(function (situs) {
+ var range = bridge.fromSitus(situs);
+ var analysis = BeforeAfter.verify(bridge, element, offset, range.finish, range.foffset, direction.failure, isRoot);
+ return BeforeAfter.cata(analysis, function () {
+ return Optional.none();
+ }, function () {
+ return Optional.some(situs);
+ }, function (cell) {
+ if (eq(element, cell) && offset === 0) {
+ return tryAgain(bridge, element, offset, moveUp, direction);
+ } else {
+ return scan$1(bridge, isRoot, cell, 0, direction, numRetries - 1);
+ }
+ }, function (cell) {
+ if (eq(element, cell) && offset === getEnd(cell)) {
+ return tryAgain(bridge, element, offset, moveDown, direction);
+ } else {
+ return scan$1(bridge, isRoot, cell, getEnd(cell), direction, numRetries - 1);
+ }
+ });
+ });
+ };
+ var tryAgain = function (bridge, element, offset, move, direction) {
+ return getBoxAt(bridge, element, offset).bind(function (box) {
+ return tryAt(bridge, direction, move(box, Retries.getJumpSize()));
+ });
+ };
+ var tryAt = function (bridge, direction, box) {
+ var browser = detect$3().browser;
+ if (browser.isChrome() || browser.isSafari() || browser.isFirefox() || browser.isEdge()) {
+ return direction.otherRetry(bridge, box);
+ } else if (browser.isIE()) {
+ return direction.ieRetry(bridge, box);
+ } else {
+ return Optional.none();
+ }
+ };
+ var tryCursor = function (bridge, isRoot, element, offset, direction) {
+ return getBoxAt(bridge, element, offset).bind(function (box) {
+ return tryAt(bridge, direction, box);
+ });
+ };
+ var handle$2 = function (bridge, isRoot, direction) {
+ return findSpot(bridge, isRoot, direction).bind(function (spot) {
+ return scan$1(bridge, isRoot, spot.element, spot.offset, direction, MAX_RETRIES).map(bridge.fromSitus);
+ });
+ };
+
+ var inSameTable = function (elem, table) {
+ return ancestor$2(elem, function (e) {
+ return parent(e).exists(function (p) {
+ return eq(p, table);
+ });
+ });
+ };
+ var simulate = function (bridge, isRoot, direction, initial, anchor) {
+ return closest$1(initial, 'td,th', isRoot).bind(function (start) {
+ return closest$1(start, 'table', isRoot).bind(function (table) {
+ if (!inSameTable(anchor, table)) {
+ return Optional.none();
+ }
+ return handle$2(bridge, isRoot, direction).bind(function (range) {
+ return closest$1(range.finish, 'td,th', isRoot).map(function (finish) {
+ return {
+ start: start,
+ finish: finish,
+ range: range
+ };
+ });
+ });
+ });
+ });
+ };
+ var navigate = function (bridge, isRoot, direction, initial, anchor, precheck) {
+ if (detect$3().browser.isIE()) {
+ return Optional.none();
+ } else {
+ return precheck(initial, isRoot).orThunk(function () {
+ return simulate(bridge, isRoot, direction, initial, anchor).map(function (info) {
+ var range = info.range;
+ return Response.create(Optional.some(makeSitus(range.start, range.soffset, range.finish, range.foffset)), true);
+ });
+ });
+ }
+ };
+ var firstUpCheck = function (initial, isRoot) {
+ return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
+ return closest$1(startRow, 'table', isRoot).bind(function (table) {
+ var rows = descendants$1(table, 'tr');
+ if (eq(startRow, rows[0])) {
+ return seekLeft$1(table, function (element) {
+ return last$1(element).isSome();
+ }, isRoot).map(function (last) {
+ var lastOffset = getEnd(last);
+ return Response.create(Optional.some(makeSitus(last, lastOffset, last, lastOffset)), true);
+ });
+ } else {
+ return Optional.none();
+ }
+ });
+ });
+ };
+ var lastDownCheck = function (initial, isRoot) {
+ return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
+ return closest$1(startRow, 'table', isRoot).bind(function (table) {
+ var rows = descendants$1(table, 'tr');
+ if (eq(startRow, rows[rows.length - 1])) {
+ return seekRight$1(table, function (element) {
+ return first(element).isSome();
+ }, isRoot).map(function (first) {
+ return Response.create(Optional.some(makeSitus(first, 0, first, 0)), true);
+ });
+ } else {
+ return Optional.none();
+ }
+ });
+ });
+ };
+ var select = function (bridge, container, isRoot, direction, initial, anchor, selectRange) {
+ return simulate(bridge, isRoot, direction, initial, anchor).bind(function (info) {
+ return detect$6(container, isRoot, info.start, info.finish, selectRange);
+ });
+ };
+
+ var value$1 = function () {
+ var subject = Cell(Optional.none());
+ var clear = function () {
+ return subject.set(Optional.none());
+ };
+ var set = function (s) {
+ return subject.set(Optional.some(s));
+ };
+ var isSet = function () {
+ return subject.get().isSome();
+ };
+ var on = function (f) {
+ return subject.get().each(f);
+ };
+ return {
+ clear: clear,
+ set: set,
+ isSet: isSet,
+ on: on
+ };
+ };
+
+ var findCell = function (target, isRoot) {
+ return closest$1(target, 'td,th', isRoot);
+ };
+ function MouseSelection (bridge, container, isRoot, annotations) {
+ var cursor = value$1();
+ var clearstate = cursor.clear;
+ var mousedown = function (event) {
+ annotations.clear(container);
+ findCell(event.target, isRoot).each(cursor.set);
+ };
+ var mouseover = function (event) {
+ cursor.on(function (start) {
+ annotations.clearBeforeUpdate(container);
+ findCell(event.target, isRoot).each(function (finish) {
+ identify(start, finish, isRoot).each(function (cellSel) {
+ var boxes = cellSel.boxes.getOr([]);
+ if (boxes.length > 1 || boxes.length === 1 && !eq(start, finish)) {
+ annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
+ bridge.selectContents(finish);
+ }
+ });
+ });
+ });
+ };
+ var mouseup = function (_event) {
+ clearstate();
+ };
+ return {
+ clearstate: clearstate,
+ mousedown: mousedown,
+ mouseover: mouseover,
+ mouseup: mouseup
+ };
+ }
+
+ var down = {
+ traverse: nextSibling,
+ gather: after$5,
+ relative: Situ.before,
+ otherRetry: Retries.tryDown,
+ ieRetry: Retries.ieTryDown,
+ failure: BeforeAfter.failedDown
+ };
+ var up = {
+ traverse: prevSibling,
+ gather: before$4,
+ relative: Situ.before,
+ otherRetry: Retries.tryUp,
+ ieRetry: Retries.ieTryUp,
+ failure: BeforeAfter.failedUp
+ };
+
+ var isKey = function (key) {
+ return function (keycode) {
+ return keycode === key;
+ };
+ };
+ var isUp = isKey(38);
+ var isDown = isKey(40);
+ var isNavigation = function (keycode) {
+ return keycode >= 37 && keycode <= 40;
+ };
+ var ltr$2 = {
+ isBackward: isKey(37),
+ isForward: isKey(39)
+ };
+ var rtl$2 = {
+ isBackward: isKey(39),
+ isForward: isKey(37)
+ };
+
+ var get$c = function (_DOC) {
+ var doc = _DOC !== undefined ? _DOC.dom : document;
+ var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
+ var y = doc.body.scrollTop || doc.documentElement.scrollTop;
+ return SugarPosition(x, y);
+ };
+ var by = function (x, y, _DOC) {
+ var doc = _DOC !== undefined ? _DOC.dom : document;
+ var win = doc.defaultView;
+ if (win) {
+ win.scrollBy(x, y);
+ }
+ };
+
+ var WindowBridge = function (win) {
+ var elementFromPoint = function (x, y) {
+ return SugarElement.fromPoint(SugarElement.fromDom(win.document), x, y);
+ };
+ var getRect = function (element) {
+ return element.dom.getBoundingClientRect();
+ };
+ var getRangedRect = function (start, soffset, finish, foffset) {
+ var sel = SimSelection.exact(start, soffset, finish, foffset);
+ return getFirstRect$1(win, sel);
+ };
+ var getSelection = function () {
+ return get$b(win).map(function (exactAdt) {
+ return convertToRange(win, exactAdt);
+ });
+ };
+ var fromSitus = function (situs) {
+ var relative = SimSelection.relative(situs.start, situs.finish);
+ return convertToRange(win, relative);
+ };
+ var situsFromPoint = function (x, y) {
+ return getAtPoint(win, x, y).map(function (exact) {
+ return Situs.create(exact.start, exact.soffset, exact.finish, exact.foffset);
+ });
+ };
+ var clearSelection = function () {
+ clear(win);
+ };
+ var collapseSelection = function (toStart) {
+ if (toStart === void 0) {
+ toStart = false;
+ }
+ get$b(win).each(function (sel) {
+ return sel.fold(function (rng) {
+ return rng.collapse(toStart);
+ }, function (startSitu, finishSitu) {
+ var situ = toStart ? startSitu : finishSitu;
+ setRelative(win, situ, situ);
+ }, function (start, soffset, finish, foffset) {
+ var node = toStart ? start : finish;
+ var offset = toStart ? soffset : foffset;
+ setExact(win, node, offset, node, offset);
+ });
+ });
+ };
+ var selectContents = function (element) {
+ setToElement(win, element);
+ };
+ var setSelection = function (sel) {
+ setExact(win, sel.start, sel.soffset, sel.finish, sel.foffset);
+ };
+ var setRelativeSelection = function (start, finish) {
+ setRelative(win, start, finish);
+ };
+ var getInnerHeight = function () {
+ return win.innerHeight;
+ };
+ var getScrollY = function () {
+ var pos = get$c(SugarElement.fromDom(win.document));
+ return pos.top;
+ };
+ var scrollBy = function (x, y) {
+ by(x, y, SugarElement.fromDom(win.document));
+ };
+ return {
+ elementFromPoint: elementFromPoint,
+ getRect: getRect,
+ getRangedRect: getRangedRect,
+ getSelection: getSelection,
+ fromSitus: fromSitus,
+ situsFromPoint: situsFromPoint,
+ clearSelection: clearSelection,
+ collapseSelection: collapseSelection,
+ setSelection: setSelection,
+ setRelativeSelection: setRelativeSelection,
+ selectContents: selectContents,
+ getInnerHeight: getInnerHeight,
+ getScrollY: getScrollY,
+ scrollBy: scrollBy
+ };
+ };
+
+ var rc = function (rows, cols) {
+ return {
+ rows: rows,
+ cols: cols
+ };
+ };
+ var mouse = function (win, container, isRoot, annotations) {
+ var bridge = WindowBridge(win);
+ var handlers = MouseSelection(bridge, container, isRoot, annotations);
+ return {
+ clearstate: handlers.clearstate,
+ mousedown: handlers.mousedown,
+ mouseover: handlers.mouseover,
+ mouseup: handlers.mouseup
+ };
+ };
+ var keyboard = function (win, container, isRoot, annotations) {
+ var bridge = WindowBridge(win);
+ var clearToNavigate = function () {
+ annotations.clear(container);
+ return Optional.none();
+ };
+ var keydown = function (event, start, soffset, finish, foffset, direction) {
+ var realEvent = event.raw;
+ var keycode = realEvent.which;
+ var shiftKey = realEvent.shiftKey === true;
+ var handler = retrieve(container, annotations.selectedSelector).fold(function () {
+ if (isDown(keycode) && shiftKey) {
+ return curry(select, bridge, container, isRoot, down, finish, start, annotations.selectRange);
+ } else if (isUp(keycode) && shiftKey) {
+ return curry(select, bridge, container, isRoot, up, finish, start, annotations.selectRange);
+ } else if (isDown(keycode)) {
+ return curry(navigate, bridge, isRoot, down, finish, start, lastDownCheck);
+ } else if (isUp(keycode)) {
+ return curry(navigate, bridge, isRoot, up, finish, start, firstUpCheck);
+ } else {
+ return Optional.none;
+ }
+ }, function (selected) {
+ var update$1 = function (attempts) {
+ return function () {
+ var navigation = findMap(attempts, function (delta) {
+ return update(delta.rows, delta.cols, container, selected, annotations);
+ });
+ return navigation.fold(function () {
+ return getEdges(container, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(function (edges) {
+ var relative = isDown(keycode) || direction.isForward(keycode) ? Situ.after : Situ.before;
+ bridge.setRelativeSelection(Situ.on(edges.first, 0), relative(edges.table));
+ annotations.clear(container);
+ return Response.create(Optional.none(), true);
+ });
+ }, function (_) {
+ return Optional.some(Response.create(Optional.none(), true));
+ });
+ };
+ };
+ if (isDown(keycode) && shiftKey) {
+ return update$1([rc(+1, 0)]);
+ } else if (isUp(keycode) && shiftKey) {
+ return update$1([rc(-1, 0)]);
+ } else if (direction.isBackward(keycode) && shiftKey) {
+ return update$1([
+ rc(0, -1),
+ rc(-1, 0)
+ ]);
+ } else if (direction.isForward(keycode) && shiftKey) {
+ return update$1([
+ rc(0, +1),
+ rc(+1, 0)
+ ]);
+ } else if (isNavigation(keycode) && shiftKey === false) {
+ return clearToNavigate;
+ } else {
+ return Optional.none;
+ }
+ });
+ return handler();
+ };
+ var keyup = function (event, start, soffset, finish, foffset) {
+ return retrieve(container, annotations.selectedSelector).fold(function () {
+ var realEvent = event.raw;
+ var keycode = realEvent.which;
+ var shiftKey = realEvent.shiftKey === true;
+ if (shiftKey === false) {
+ return Optional.none();
+ }
+ if (isNavigation(keycode)) {
+ return sync(container, isRoot, start, soffset, finish, foffset, annotations.selectRange);
+ } else {
+ return Optional.none();
+ }
+ }, Optional.none);
+ };
+ return {
+ keydown: keydown,
+ keyup: keyup
+ };
+ };
+ var external = function (win, container, isRoot, annotations) {
+ var bridge = WindowBridge(win);
+ return function (start, finish) {
+ annotations.clearBeforeUpdate(container);
+ identify(start, finish, isRoot).each(function (cellSel) {
+ var boxes = cellSel.boxes.getOr([]);
+ annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
+ bridge.selectContents(finish);
+ bridge.collapseSelection();
+ });
+ };
+ };
+
+ var remove$7 = function (element, classes) {
+ each(classes, function (x) {
+ remove$5(element, x);
+ });
+ };
+
+ var addClass = function (clazz) {
+ return function (element) {
+ add$3(element, clazz);
+ };
+ };
+ var removeClasses = function (classes) {
+ return function (element) {
+ remove$7(element, classes);
+ };
+ };
+
+ var byClass = function (ephemera) {
+ var addSelectionClass = addClass(ephemera.selected);
+ var removeSelectionClasses = removeClasses([
+ ephemera.selected,
+ ephemera.lastSelected,
+ ephemera.firstSelected
+ ]);
+ var clear = function (container) {
+ var sels = descendants$1(container, ephemera.selectedSelector);
+ each(sels, removeSelectionClasses);
+ };
+ var selectRange = function (container, cells, start, finish) {
+ clear(container);
+ each(cells, addSelectionClass);
+ add$3(start, ephemera.firstSelected);
+ add$3(finish, ephemera.lastSelected);
+ };
+ return {
+ clearBeforeUpdate: clear,
+ clear: clear,
+ selectRange: selectRange,
+ selectedSelector: ephemera.selectedSelector,
+ firstSelectedSelector: ephemera.firstSelectedSelector,
+ lastSelectedSelector: ephemera.lastSelectedSelector
+ };
+ };
+ var byAttr = function (ephemera, onSelection, onClear) {
+ var removeSelectionAttributes = function (element) {
+ remove(element, ephemera.selected);
+ remove(element, ephemera.firstSelected);
+ remove(element, ephemera.lastSelected);
+ };
+ var addSelectionAttribute = function (element) {
+ set(element, ephemera.selected, '1');
+ };
+ var clear = function (container) {
+ clearBeforeUpdate(container);
+ onClear();
+ };
+ var clearBeforeUpdate = function (container) {
+ var sels = descendants$1(container, ephemera.selectedSelector);
+ each(sels, removeSelectionAttributes);
+ };
+ var selectRange = function (container, cells, start, finish) {
+ clear(container);
+ each(cells, addSelectionAttribute);
+ set(start, ephemera.firstSelected, '1');
+ set(finish, ephemera.lastSelected, '1');
+ onSelection(cells, start, finish);
+ };
+ return {
+ clearBeforeUpdate: clearBeforeUpdate,
+ clear: clear,
+ selectRange: selectRange,
+ selectedSelector: ephemera.selectedSelector,
+ firstSelectedSelector: ephemera.firstSelectedSelector,
+ lastSelectedSelector: ephemera.lastSelectedSelector
+ };
+ };
+ var SelectionAnnotation = {
+ byClass: byClass,
+ byAttr: byAttr
+ };
+
+ var getUpOrLeftCells = function (grid, selectedCells, generators) {
+ var upGrid = grid.slice(0, selectedCells[selectedCells.length - 1].row + 1);
+ var upDetails = toDetailList(upGrid, generators);
+ return bind(upDetails, function (detail) {
+ var slicedCells = detail.cells.slice(0, selectedCells[selectedCells.length - 1].column + 1);
+ return map(slicedCells, function (cell) {
+ return cell.element;
+ });
+ });
+ };
+ var getDownOrRightCells = function (grid, selectedCells, generators) {
+ var downGrid = grid.slice(selectedCells[0].row + selectedCells[0].rowspan - 1, grid.length);
+ var downDetails = toDetailList(downGrid, generators);
+ return bind(downDetails, function (detail) {
+ var slicedCells = detail.cells.slice(selectedCells[0].column + selectedCells[0].colspan - 1, detail.cells.length);
+ return map(slicedCells, function (cell) {
+ return cell.element;
+ });
+ });
+ };
+ var getOtherCells = function (table, target, generators) {
+ var warehouse = Warehouse.fromTable(table);
+ var details = onCells(warehouse, target);
+ return details.map(function (selectedCells) {
+ var grid = toGrid(warehouse, generators, false);
+ var upOrLeftCells = getUpOrLeftCells(grid, selectedCells, generators);
+ var downOrRightCells = getDownOrRightCells(grid, selectedCells, generators);
+ return {
+ upOrLeftCells: upOrLeftCells,
+ downOrRightCells: downOrRightCells
+ };
+ });
+ };
+
+ var hasInternalTarget = function (e) {
+ return has$1(SugarElement.fromDom(e.target), 'ephox-snooker-resizer-bar') === false;
+ };
+ function CellSelection (editor, lazyResize, selectionTargets) {
+ var onSelection = function (cells, start, finish) {
+ selectionTargets.targets().each(function (targets) {
+ var tableOpt = table(start);
+ tableOpt.each(function (table) {
+ var cloneFormats = getCloneElements(editor);
+ var generators = cellOperations(noop, SugarElement.fromDom(editor.getDoc()), cloneFormats);
+ var otherCells = getOtherCells(table, targets, generators);
+ fireTableSelectionChange(editor, cells, start, finish, otherCells);
+ });
+ });
+ };
+ var onClear = function () {
+ return fireTableSelectionClear(editor);
+ };
+ var annotations = SelectionAnnotation.byAttr(ephemera, onSelection, onClear);
+ editor.on('init', function (_e) {
+ var win = editor.getWin();
+ var body = getBody$1(editor);
+ var isRoot = getIsRoot(editor);
+ var syncSelection = function () {
+ var sel = editor.selection;
+ var start = SugarElement.fromDom(sel.getStart());
+ var end = SugarElement.fromDom(sel.getEnd());
+ var shared = sharedOne$1(table, [
+ start,
+ end
+ ]);
+ shared.fold(function () {
+ return annotations.clear(body);
+ }, noop);
+ };
+ var mouseHandlers = mouse(win, body, isRoot, annotations);
+ var keyHandlers = keyboard(win, body, isRoot, annotations);
+ var external$1 = external(win, body, isRoot, annotations);
+ var hasShiftKey = function (event) {
+ return event.raw.shiftKey === true;
+ };
+ editor.on('TableSelectorChange', function (e) {
+ return external$1(e.start, e.finish);
+ });
+ var handleResponse = function (event, response) {
+ if (!hasShiftKey(event)) {
+ return;
+ }
+ if (response.kill) {
+ event.kill();
+ }
+ response.selection.each(function (ns) {
+ var relative = SimSelection.relative(ns.start, ns.finish);
+ var rng = asLtrRange(win, relative);
+ editor.selection.setRng(rng);
+ });
+ };
+ var keyup = function (event) {
+ var wrappedEvent = fromRawEvent$1(event);
+ if (wrappedEvent.raw.shiftKey && isNavigation(wrappedEvent.raw.which)) {
+ var rng = editor.selection.getRng();
+ var start = SugarElement.fromDom(rng.startContainer);
+ var end = SugarElement.fromDom(rng.endContainer);
+ keyHandlers.keyup(wrappedEvent, start, rng.startOffset, end, rng.endOffset).each(function (response) {
+ handleResponse(wrappedEvent, response);
+ });
+ }
+ };
+ var keydown = function (event) {
+ var wrappedEvent = fromRawEvent$1(event);
+ lazyResize().each(function (resize) {
+ return resize.hideBars();
+ });
+ var rng = editor.selection.getRng();
+ var start = SugarElement.fromDom(rng.startContainer);
+ var end = SugarElement.fromDom(rng.endContainer);
+ var direction = onDirection(ltr$2, rtl$2)(SugarElement.fromDom(editor.selection.getStart()));
+ keyHandlers.keydown(wrappedEvent, start, rng.startOffset, end, rng.endOffset, direction).each(function (response) {
+ handleResponse(wrappedEvent, response);
+ });
+ lazyResize().each(function (resize) {
+ return resize.showBars();
+ });
+ };
+ var isLeftMouse = function (raw) {
+ return raw.button === 0;
+ };
+ var isLeftButtonPressed = function (raw) {
+ if (raw.buttons === undefined) {
+ return true;
+ }
+ if (global$2.browser.isEdge() && raw.buttons === 0) {
+ return true;
+ }
+ return (raw.buttons & 1) !== 0;
+ };
+ var dragStart = function (_e) {
+ mouseHandlers.clearstate();
+ };
+ var mouseDown = function (e) {
+ if (isLeftMouse(e) && hasInternalTarget(e)) {
+ mouseHandlers.mousedown(fromRawEvent$1(e));
+ }
+ };
+ var mouseOver = function (e) {
+ if (isLeftButtonPressed(e) && hasInternalTarget(e)) {
+ mouseHandlers.mouseover(fromRawEvent$1(e));
+ }
+ };
+ var mouseUp = function (e) {
+ if (isLeftMouse(e) && hasInternalTarget(e)) {
+ mouseHandlers.mouseup(fromRawEvent$1(e));
+ }
+ };
+ var getDoubleTap = function () {
+ var lastTarget = Cell(SugarElement.fromDom(body));
+ var lastTimeStamp = Cell(0);
+ var touchEnd = function (t) {
+ var target = SugarElement.fromDom(t.target);
+ if (name(target) === 'td' || name(target) === 'th') {
+ var lT = lastTarget.get();
+ var lTS = lastTimeStamp.get();
+ if (eq(lT, target) && t.timeStamp - lTS < 300) {
+ t.preventDefault();
+ external$1(target, target);
+ }
+ }
+ lastTarget.set(target);
+ lastTimeStamp.set(t.timeStamp);
+ };
+ return { touchEnd: touchEnd };
+ };
+ var doubleTap = getDoubleTap();
+ editor.on('dragstart', dragStart);
+ editor.on('mousedown', mouseDown);
+ editor.on('mouseover', mouseOver);
+ editor.on('mouseup', mouseUp);
+ editor.on('touchend', doubleTap.touchEnd);
+ editor.on('keyup', keyup);
+ editor.on('keydown', keydown);
+ editor.on('NodeChange', syncSelection);
+ });
+ return { clear: annotations.clear };
+ }
+
+ var getSelectionTargets = function (editor, selections) {
+ var targets = Cell(Optional.none());
+ var changeHandlers = Cell([]);
+ var findTargets = function () {
+ return getSelectionStartCellOrCaption(getSelectionStart(editor)).bind(function (cellOrCaption) {
+ var table$1 = table(cellOrCaption);
+ var isCaption = function (elem) {
+ return name(elem) === 'caption';
+ };
+ return table$1.map(function (table) {
+ if (isCaption(cellOrCaption)) {
+ return noMenu(cellOrCaption);
+ } else {
+ return forMenu(selections, table, cellOrCaption);
+ }
+ });
+ });
+ };
+ var resetTargets = function () {
+ targets.set(cached(findTargets)());
+ each(changeHandlers.get(), function (handler) {
+ return handler();
+ });
+ };
+ var onSetup = function (api, isDisabled) {
+ var handler = function () {
+ return targets.get().fold(function () {
+ api.setDisabled(true);
+ }, function (targets) {
+ api.setDisabled(isDisabled(targets));
+ });
+ };
+ handler();
+ changeHandlers.set(changeHandlers.get().concat([handler]));
+ return function () {
+ changeHandlers.set(filter(changeHandlers.get(), function (h) {
+ return h !== handler;
+ }));
+ };
+ };
+ var onSetupTable = function (api) {
+ return onSetup(api, function (_) {
+ return false;
+ });
+ };
+ var onSetupCellOrRow = function (api) {
+ return onSetup(api, function (targets) {
+ return name(targets.element) === 'caption';
+ });
+ };
+ var onSetupPasteable = function (getClipboardData) {
+ return function (api) {
+ return onSetup(api, function (targets) {
+ return name(targets.element) === 'caption' || getClipboardData().isNone();
+ });
+ };
+ };
+ var onSetupMergeable = function (api) {
+ return onSetup(api, function (targets) {
+ return targets.mergable.isNone();
+ });
+ };
+ var onSetupUnmergeable = function (api) {
+ return onSetup(api, function (targets) {
+ return targets.unmergable.isNone();
+ });
+ };
+ editor.on('NodeChange ExecCommand TableSelectorChange', resetTargets);
+ return {
+ onSetupTable: onSetupTable,
+ onSetupCellOrRow: onSetupCellOrRow,
+ onSetupPasteable: onSetupPasteable,
+ onSetupMergeable: onSetupMergeable,
+ onSetupUnmergeable: onSetupUnmergeable,
+ resetTargets: resetTargets,
+ targets: function () {
+ return targets.get();
+ }
+ };
+ };
+
+ var addButtons = function (editor, selectionTargets, clipboard) {
+ editor.ui.registry.addMenuButton('table', {
+ tooltip: 'Table',
+ icon: 'table',
+ fetch: function (callback) {
+ return callback('inserttable | cell row column | advtablesort | tableprops deletetable');
+ }
+ });
+ var cmd = function (command) {
+ return function () {
+ return editor.execCommand(command);
+ };
+ };
+ editor.ui.registry.addButton('tableprops', {
+ tooltip: 'Table properties',
+ onAction: cmd('mceTableProps'),
+ icon: 'table',
+ onSetup: selectionTargets.onSetupTable
+ });
+ editor.ui.registry.addButton('tabledelete', {
+ tooltip: 'Delete table',
+ onAction: cmd('mceTableDelete'),
+ icon: 'table-delete-table',
+ onSetup: selectionTargets.onSetupTable
+ });
+ editor.ui.registry.addButton('tablecellprops', {
+ tooltip: 'Cell properties',
+ onAction: cmd('mceTableCellProps'),
+ icon: 'table-cell-properties',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablemergecells', {
+ tooltip: 'Merge cells',
+ onAction: cmd('mceTableMergeCells'),
+ icon: 'table-merge-cells',
+ onSetup: selectionTargets.onSetupMergeable
+ });
+ editor.ui.registry.addButton('tablesplitcells', {
+ tooltip: 'Split cell',
+ onAction: cmd('mceTableSplitCells'),
+ icon: 'table-split-cells',
+ onSetup: selectionTargets.onSetupUnmergeable
+ });
+ editor.ui.registry.addButton('tableinsertrowbefore', {
+ tooltip: 'Insert row before',
+ onAction: cmd('mceTableInsertRowBefore'),
+ icon: 'table-insert-row-above',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tableinsertrowafter', {
+ tooltip: 'Insert row after',
+ onAction: cmd('mceTableInsertRowAfter'),
+ icon: 'table-insert-row-after',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tabledeleterow', {
+ tooltip: 'Delete row',
+ onAction: cmd('mceTableDeleteRow'),
+ icon: 'table-delete-row',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablerowprops', {
+ tooltip: 'Row properties',
+ onAction: cmd('mceTableRowProps'),
+ icon: 'table-row-properties',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tableinsertcolbefore', {
+ tooltip: 'Insert column before',
+ onAction: cmd('mceTableInsertColBefore'),
+ icon: 'table-insert-column-before',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tableinsertcolafter', {
+ tooltip: 'Insert column after',
+ onAction: cmd('mceTableInsertColAfter'),
+ icon: 'table-insert-column-after',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tabledeletecol', {
+ tooltip: 'Delete column',
+ onAction: cmd('mceTableDeleteCol'),
+ icon: 'table-delete-column',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablecutrow', {
+ tooltip: 'Cut row',
+ icon: 'cut-row',
+ onAction: cmd('mceTableCutRow'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablecopyrow', {
+ tooltip: 'Copy row',
+ icon: 'duplicate-row',
+ onAction: cmd('mceTableCopyRow'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablepasterowbefore', {
+ tooltip: 'Paste row before',
+ icon: 'paste-row-before',
+ onAction: cmd('mceTablePasteRowBefore'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
+ });
+ editor.ui.registry.addButton('tablepasterowafter', {
+ tooltip: 'Paste row after',
+ icon: 'paste-row-after',
+ onAction: cmd('mceTablePasteRowAfter'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
+ });
+ editor.ui.registry.addButton('tablecutcol', {
+ tooltip: 'Cut column',
+ icon: 'cut-column',
+ onAction: cmd('mceTableCutCol'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablecopycol', {
+ tooltip: 'Copy column',
+ icon: 'duplicate-column',
+ onAction: cmd('mceTableCopyCol'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablepastecolbefore', {
+ tooltip: 'Paste column before',
+ icon: 'paste-column-before',
+ onAction: cmd('mceTablePasteColBefore'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getColumns)
+ });
+ editor.ui.registry.addButton('tablepastecolafter', {
+ tooltip: 'Paste column after',
+ icon: 'paste-column-after',
+ onAction: cmd('mceTablePasteColAfter'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getColumns)
+ });
+ editor.ui.registry.addButton('tableinsertdialog', {
+ tooltip: 'Insert table',
+ onAction: cmd('mceInsertTable'),
+ icon: 'table'
+ });
+ };
+ var addToolbars = function (editor) {
+ var isTable = function (table) {
+ return editor.dom.is(table, 'table') && editor.getBody().contains(table);
+ };
+ var toolbar = getToolbar(editor);
+ if (toolbar.length > 0) {
+ editor.ui.registry.addContextToolbar('table', {
+ predicate: isTable,
+ items: toolbar,
+ scope: 'node',
+ position: 'node'
+ });
+ }
+ };
+
+ var addMenuItems = function (editor, selectionTargets, clipboard) {
+ var cmd = function (command) {
+ return function () {
+ return editor.execCommand(command);
+ };
+ };
+ var insertTableAction = function (_a) {
+ var numRows = _a.numRows, numColumns = _a.numColumns;
+ editor.undoManager.transact(function () {
+ insert$1(editor, numColumns, numRows, 0, 0);
+ });
+ editor.addVisual();
+ };
+ var tableProperties = {
+ text: 'Table properties',
+ onSetup: selectionTargets.onSetupTable,
+ onAction: cmd('mceTableProps')
+ };
+ var deleteTable = {
+ text: 'Delete table',
+ icon: 'table-delete-table',
+ onSetup: selectionTargets.onSetupTable,
+ onAction: cmd('mceTableDelete')
+ };
+ editor.ui.registry.addMenuItem('tableinsertrowbefore', {
+ text: 'Insert row before',
+ icon: 'table-insert-row-above',
+ onAction: cmd('mceTableInsertRowBefore'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tableinsertrowafter', {
+ text: 'Insert row after',
+ icon: 'table-insert-row-after',
+ onAction: cmd('mceTableInsertRowAfter'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tabledeleterow', {
+ text: 'Delete row',
+ icon: 'table-delete-row',
+ onAction: cmd('mceTableDeleteRow'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablerowprops', {
+ text: 'Row properties',
+ icon: 'table-row-properties',
+ onAction: cmd('mceTableRowProps'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablecutrow', {
+ text: 'Cut row',
+ icon: 'cut-row',
+ onAction: cmd('mceTableCutRow'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablecopyrow', {
+ text: 'Copy row',
+ icon: 'duplicate-row',
+ onAction: cmd('mceTableCopyRow'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablepasterowbefore', {
+ text: 'Paste row before',
+ icon: 'paste-row-before',
+ onAction: cmd('mceTablePasteRowBefore'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
+ });
+ editor.ui.registry.addMenuItem('tablepasterowafter', {
+ text: 'Paste row after',
+ icon: 'paste-row-after',
+ onAction: cmd('mceTablePasteRowAfter'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
+ });
+ var row = {
+ type: 'nestedmenuitem',
+ text: 'Row',
+ getSubmenuItems: function () {
+ return 'tableinsertrowbefore tableinsertrowafter tabledeleterow tablerowprops | tablecutrow tablecopyrow tablepasterowbefore tablepasterowafter';
+ }
+ };
+ editor.ui.registry.addMenuItem('tableinsertcolumnbefore', {
+ text: 'Insert column before',
+ icon: 'table-insert-column-before',
+ onAction: cmd('mceTableInsertColBefore'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tableinsertcolumnafter', {
+ text: 'Insert column after',
+ icon: 'table-insert-column-after',
+ onAction: cmd('mceTableInsertColAfter'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tabledeletecolumn', {
+ text: 'Delete column',
+ icon: 'table-delete-column',
+ onAction: cmd('mceTableDeleteCol'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablecutcolumn', {
+ text: 'Cut column',
+ icon: 'cut-column',
+ onAction: cmd('mceTableCutCol'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablecopycolumn', {
+ text: 'Copy column',
+ icon: 'duplicate-column',
+ onAction: cmd('mceTableCopyCol'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablepastecolumnbefore', {
+ text: 'Paste column before',
+ icon: 'paste-column-before',
+ onAction: cmd('mceTablePasteColBefore'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getColumns)
+ });
+ editor.ui.registry.addMenuItem('tablepastecolumnafter', {
+ text: 'Paste column after',
+ icon: 'paste-column-after',
+ onAction: cmd('mceTablePasteColAfter'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getColumns)
+ });
+ var column = {
+ type: 'nestedmenuitem',
+ text: 'Column',
+ getSubmenuItems: function () {
+ return 'tableinsertcolumnbefore tableinsertcolumnafter tabledeletecolumn | tablecutcolumn tablecopycolumn tablepastecolumnbefore tablepastecolumnafter';
+ }
+ };
+ editor.ui.registry.addMenuItem('tablecellprops', {
+ text: 'Cell properties',
+ icon: 'table-cell-properties',
+ onAction: cmd('mceTableCellProps'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablemergecells', {
+ text: 'Merge cells',
+ icon: 'table-merge-cells',
+ onAction: cmd('mceTableMergeCells'),
+ onSetup: selectionTargets.onSetupMergeable
+ });
+ editor.ui.registry.addMenuItem('tablesplitcells', {
+ text: 'Split cell',
+ icon: 'table-split-cells',
+ onAction: cmd('mceTableSplitCells'),
+ onSetup: selectionTargets.onSetupUnmergeable
+ });
+ var cell = {
+ type: 'nestedmenuitem',
+ text: 'Cell',
+ getSubmenuItems: function () {
+ return 'tablecellprops tablemergecells tablesplitcells';
+ }
+ };
+ if (hasTableGrid(editor) === false) {
+ editor.ui.registry.addMenuItem('inserttable', {
+ text: 'Table',
+ icon: 'table',
+ onAction: cmd('mceInsertTable')
+ });
+ } else {
+ editor.ui.registry.addNestedMenuItem('inserttable', {
+ text: 'Table',
+ icon: 'table',
+ getSubmenuItems: function () {
+ return [{
+ type: 'fancymenuitem',
+ fancytype: 'inserttable',
+ onAction: insertTableAction
+ }];
+ }
+ });
+ }
+ editor.ui.registry.addMenuItem('inserttabledialog', {
+ text: 'Insert table',
+ icon: 'table',
+ onAction: cmd('mceInsertTable')
+ });
+ editor.ui.registry.addMenuItem('tableprops', tableProperties);
+ editor.ui.registry.addMenuItem('deletetable', deleteTable);
+ editor.ui.registry.addNestedMenuItem('row', row);
+ editor.ui.registry.addNestedMenuItem('column', column);
+ editor.ui.registry.addNestedMenuItem('cell', cell);
+ editor.ui.registry.addContextMenu('table', {
+ update: function () {
+ selectionTargets.resetTargets();
+ return selectionTargets.targets().fold(function () {
+ return '';
+ }, function (targets) {
+ if (name(targets.element) === 'caption') {
+ return 'tableprops deletetable';
+ } else {
+ return 'cell row column | advtablesort | tableprops deletetable';
+ }
+ });
+ }
+ });
+ };
+
+ function Plugin(editor) {
+ var selections = Selections(function () {
+ return getBody$1(editor);
+ }, function () {
+ return getSelectionStartCellOrCaption(getSelectionStart(editor));
+ }, ephemera.selectedSelector);
+ var selectionTargets = getSelectionTargets(editor, selections);
+ var resizeHandler = getResizeHandler(editor);
+ var cellSelection = CellSelection(editor, resizeHandler.lazyResize, selectionTargets);
+ var actions = TableActions(editor, resizeHandler.lazyWire, selections);
+ var clipboard = Clipboard();
+ registerCommands(editor, actions, cellSelection, selections, clipboard);
+ registerQueryCommands(editor, actions, selections);
+ registerEvents(editor, selections, actions, cellSelection);
+ addMenuItems(editor, selectionTargets, clipboard);
+ addButtons(editor, selectionTargets, clipboard);
+ addToolbars(editor);
+ editor.on('PreInit', function () {
+ editor.serializer.addTempAttr(ephemera.firstSelected);
+ editor.serializer.addTempAttr(ephemera.lastSelected);
+ registerFormats(editor);
+ });
+ if (hasTabNavigation(editor)) {
+ editor.on('keydown', function (e) {
+ handle$1(e, editor, actions);
+ });
+ }
+ editor.on('remove', function () {
+ resizeHandler.destroy();
+ });
+ return getApi(editor, clipboard, resizeHandler, selectionTargets);
+ }
+ function Plugin$1 () {
+ global.add('table', Plugin);
+ }
+
+ Plugin$1();
+
+}());
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.min.js
old mode 100755
new mode 100644
index a2aac1e06f..17330b459a
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.min.js
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.min.js
@@ -1 +1,9 @@
-!function(e,t){"use strict";function n(e,t){for(var n,o=[],i=0;i
'),!1):void 0},"childNodes"),t=s(t,!1),d(t,"rowSpan",1),d(t,"colSpan",1),o?t.appendChild(o):n.ie||(t.innerHTML='
'),t}function g(){var e=I.createRng(),t;return i(I.select("tr",a),function(e){0===e.cells.length&&I.remove(e)}),0===I.select("tr",a).length?(e.setStartBefore(a),e.setEndBefore(a),E.setRng(e),void I.remove(a)):(i(I.select("thead,tbody,tfoot",a),function(e){0===e.rows.length&&I.remove(e)}),l(),void(B&&(t=A[Math.min(A.length-1,B.y)],t&&(E.select(t[Math.min(t.length-1,B.x)].elm,!0),E.collapse(!0)))))}function h(e,t,n,o){var i,r,a,l,s;for(i=A[t][e].elm.parentNode,a=1;n>=a;a++)if(i=I.getNext(i,"tr")){for(r=e;r>=0;r--)if(s=A[t+a][r].elm,s.parentNode==i){for(l=1;o>=l;l++)I.insertAfter(p(s),s);break}if(-1==r)for(l=1;o>=l;l++)i.insertBefore(p(i.cells[0]),i.cells[0])}}function v(){i(A,function(e,t){i(e,function(e,n){var i,r,a;if(u(e)&&(e=e.elm,i=o(e,"colspan"),r=o(e,"rowspan"),i>1||r>1)){for(d(e,"rowSpan",1),d(e,"colSpan",1),a=0;i-1>a;a++)I.insertAfter(p(e),e);h(n,t,r-1,i)}})})}function b(t,n,o){var r,a,s,f,m,p,h,b,y,w,x;if(t?(r=S(t),a=r.x,s=r.y,f=a+(n-1),m=s+(o-1)):(B=_=null,i(A,function(e,t){i(e,function(e,n){u(e)&&(B||(B={x:n,y:t}),_={x:n,y:t})})}),B&&(a=B.x,s=B.y,f=_.x,m=_.y)),b=c(a,s),y=c(f,m),b&&y&&b.part==y.part){for(v(),l(),b=c(a,s).elm,d(b,"colSpan",f-a+1),d(b,"rowSpan",m-s+1),h=s;m>=h;h++)for(p=a;f>=p;p++)A[h]&&A[h][p]&&(t=A[h][p].elm,t!=b&&(w=e.grep(t.childNodes),i(w,function(e){b.appendChild(e)}),w.length&&(w=e.grep(b.childNodes),x=0,i(w,function(e){"BR"==e.nodeName&&I.getAttrib(e,"data-mce-bogus")&&x++
'):n.dom.add(n.getBody(),"br",{"data-mce-bogus":"1"}))}),n.on("PreProcess",function(e){var t=e.node.lastChild;t&&("BR"==t.nodeName||1==t.childNodes.length&&("BR"==t.firstChild.nodeName||"\xa0"==t.firstChild.nodeValue))&&t.previousSibling&&"TABLE"==t.previousSibling.nodeName&&n.dom.remove(t)})}function s(){function e(e,t,n,o){var i=3,r=e.dom.getParent(t.startContainer,"TABLE"),a,l,s;return r&&(a=r.parentNode),l=t.startContainer.nodeType==i&&0===t.startOffset&&0===t.endOffset&&o&&("TR"==n.nodeName||n==a),s=("TD"==n.nodeName||"TH"==n.nodeName)&&!o,l||s}function t(){var t=n.selection.getRng(),o=n.selection.getNode(),i=n.dom.getParent(t.startContainer,"TD,TH");if(e(n,t,o,i)){i||(i=o);for(var r=i.lastChild;r.lastChild;)r=r.lastChild;t.setEnd(r,r.nodeValue.length),n.selection.setRng(t)}}n.on("KeyDown",function(){t()}),n.on("MouseDown",function(e){2!=e.button&&t()})}function c(){n.on("keydown",function(t){if((t.keyCode==e.DELETE||t.keyCode==e.BACKSPACE)&&!t.isDefaultPrevented()){var o=n.dom.getParent(n.selection.getStart(),"table");if(o){for(var i=n.dom.select("td,th",o),r=i.length;r--;)if(!n.dom.hasClass(i[r],"mce-item-selected"))return;t.preventDefault(),n.execCommand("mceTableDelete")}}})}c(),t.webkit&&(r(),s()),t.gecko&&(a(),l()),t.ie>10&&(a(),l())}}),o(m,[s,p,c],function(e,t,n){return function(o){function i(){o.getBody().style.webkitUserSelect="",d&&(o.dom.removeClass(o.dom.select("td.mce-item-selected,th.mce-item-selected"),"mce-item-selected"),d=!1)}function r(t){var n,i,r=t.target;if(s&&(l||r!=s)&&("TD"==r.nodeName||"TH"==r.nodeName)){i=a.getParent(r,"table"),i==c&&(l||(l=new e(o,i),l.setStartCell(s),o.getBody().style.webkitUserSelect="none"),l.setEndCell(r),d=!0),n=o.selection.getSel();try{n.removeAllRanges?n.removeAllRanges():n.empty()}catch(u){}t.preventDefault()}}var a=o.dom,l,s,c,d=!0;return o.on("MouseDown",function(e){2!=e.button&&(i(),s=a.getParent(e.target,"td,th"),c=a.getParent(s,"table"))}),o.on("mouseover",r),o.on("remove",function(){a.unbind(o.getDoc(),"mouseover",r)}),o.on("MouseUp",function(){function e(e,o){var r=new t(e,e);do{if(3==e.nodeType&&0!==n.trim(e.nodeValue).length)return void(o?i.setStart(e,0):i.setEnd(e,e.nodeValue.length));if("BR"==e.nodeName)return void(o?i.setStartBefore(e):i.setEndBefore(e))}while(e=o?r.next():r.prev())}var i,r=o.selection,d,u,f,m,p;if(s){if(l&&(o.getBody().style.webkitUserSelect=""),d=a.select("td.mce-item-selected,th.mce-item-selected"),d.length>0){i=a.createRng(),f=d[0],p=d[d.length-1],i.setStartBefore(f),i.setEndAfter(f),e(f,1),u=new t(f,a.getParent(d[0],"table"));do if("TD"==f.nodeName||"TH"==f.nodeName){if(!a.hasClass(f,"mce-item-selected"))break;m=f}while(f=u.next());e(m),r.setRng(i)}o.nodeChanged(),s=l=c=null}}),o.on("KeyUp",function(){i()}),{clear:i}}}),o(g,[s,u,m,c,p,d,h],function(e,t,n,o,i,r,a){function l(o){function i(e){return e?e.replace(/px$/,""):""}function a(e){return/^[0-9]+$/.test(e)&&(e+="px"),e}function l(e){s("left center right".split(" "),function(t){o.formatter.remove("align"+t,{},e)})}function c(){var e=o.dom,t,n;t=e.getParent(o.selection.getStart(),"table"),n={width:i(e.getStyle(t,"width")||e.getAttrib(t,"width")),height:i(e.getStyle(t,"height")||e.getAttrib(t,"height")),cellspacing:e.getAttrib(t,"cellspacing"),cellpadding:e.getAttrib(t,"cellpadding"),border:e.getAttrib(t,"border"),caption:!!e.select("caption",t)[0]},s("left center right".split(" "),function(e){o.formatter.matchNode(t,"align"+e)&&(n.align=e)}),o.windowManager.open({title:"Table properties",items:{type:"form",layout:"grid",columns:2,data:n,defaults:{type:"textbox",maxWidth:50},items:[{label:"Width",name:"width"},{label:"Height",name:"height"},{label:"Cell spacing",name:"cellspacing"},{label:"Cell padding",name:"cellpadding"},{label:"Border",name:"border"},{label:"Caption",name:"caption",type:"checkbox"},{label:"Alignment",minWidth:90,name:"align",type:"listbox",text:"None",maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]}]},onsubmit:function(){var n=this.toJSON(),i;o.undoManager.transact(function(){o.dom.setAttribs(t,{cellspacing:n.cellspacing,cellpadding:n.cellpadding,border:n.border}),o.dom.setStyles(t,{width:a(n.width),height:a(n.height)}),i=e.select("caption",t)[0],i&&!n.caption&&e.remove(i),!i&&n.caption&&(i=e.create("caption"),i.innerHTML=r.ie?"\xa0":'
',t.insertBefore(i,t.firstChild)),l(t),n.align&&o.formatter.apply("align"+n.align,{},t),o.focus(),o.addVisual()})}})}function d(e,t){o.windowManager.open({title:"Merge cells",body:[{label:"Cols",name:"cols",type:"textbox",size:10},{label:"Rows",name:"rows",type:"textbox",size:10}],onsubmit:function(){var n=this.toJSON();o.undoManager.transact(function(){e.merge(t,n.cols,n.rows)})}})}function u(){var e=o.dom,t,n,r=[];r=o.dom.select("td.mce-item-selected,th.mce-item-selected"),t=o.dom.getParent(o.selection.getStart(),"td,th"),!r.length&&t&&r.push(t),t=t||r[0],t&&(n={width:i(e.getStyle(t,"width")||e.getAttrib(t,"width")),height:i(e.getStyle(t,"height")||e.getAttrib(t,"height")),scope:e.getAttrib(t,"scope")},n.type=t.nodeName.toLowerCase(),s("left center right".split(" "),function(e){o.formatter.matchNode(t,"align"+e)&&(n.align=e)}),o.windowManager.open({title:"Cell properties",items:{type:"form",data:n,layout:"grid",columns:2,defaults:{type:"textbox",maxWidth:50},items:[{label:"Width",name:"width"},{label:"Height",name:"height"},{label:"Cell type",name:"type",type:"listbox",text:"None",minWidth:90,maxWidth:null,values:[{text:"Cell",value:"td"},{text:"Header cell",value:"th"}]},{label:"Scope",name:"scope",type:"listbox",text:"None",minWidth:90,maxWidth:null,values:[{text:"None",value:""},{text:"Row",value:"row"},{text:"Column",value:"col"},{text:"Row group",value:"rowgroup"},{text:"Column group",value:"colgroup"}]},{label:"Alignment",name:"align",type:"listbox",text:"None",minWidth:90,maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]}]},onsubmit:function(){var t=this.toJSON();o.undoManager.transact(function(){s(r,function(n){o.dom.setAttrib(n,"scope",t.scope),o.dom.setStyles(n,{width:a(t.width),height:a(t.height)}),t.type&&n.nodeName.toLowerCase()!=t.type&&(n=e.rename(n,t.type)),l(n),t.align&&o.formatter.apply("align"+t.align,{},n)}),o.focus()})}}))}function f(){var e=o.dom,t,n,r,c,d=[];t=o.dom.getParent(o.selection.getStart(),"table"),n=o.dom.getParent(o.selection.getStart(),"td,th"),s(t.rows,function(t){s(t.cells,function(o){return e.hasClass(o,"mce-item-selected")||o==n?(d.push(t),!1):void 0})}),r=d[0],r&&(c={height:i(e.getStyle(r,"height")||e.getAttrib(r,"height")),scope:e.getAttrib(r,"scope")},c.type=r.parentNode.nodeName.toLowerCase(),s("left center right".split(" "),function(e){o.formatter.matchNode(r,"align"+e)&&(c.align=e)}),o.windowManager.open({title:"Row properties",items:{type:"form",data:c,columns:2,defaults:{type:"textbox"},items:[{type:"listbox",name:"type",label:"Row type",text:"None",maxWidth:null,values:[{text:"Header",value:"thead"},{text:"Body",value:"tbody"},{text:"Footer",value:"tfoot"}]},{type:"listbox",name:"align",label:"Alignment",text:"None",maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]},{label:"Height",name:"height"}]},onsubmit:function(){var t=this.toJSON(),n,i,r;o.undoManager.transact(function(){var c=t.type;s(d,function(s){o.dom.setAttrib(s,"scope",t.scope),o.dom.setStyles(s,{height:a(t.height)}),c!=s.parentNode.nodeName.toLowerCase()&&(n=e.getParent(s,"table"),i=s.parentNode,r=e.select(c,n)[0],r||(r=e.create(c),n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r)),r.appendChild(s),i.hasChildNodes()||e.remove(i)),l(s),t.align&&o.formatter.apply("align"+t.align,{},s)}),o.focus()})}}))}function m(e){return function(){o.execCommand(e)}}function p(e,t){var n,i,a;for(a="",n=0;t>n;n++){for(a+="
",o.insertContent(a)}function g(e,t){function n(){e.disabled(!o.dom.getParent(o.selection.getStart(),t)),o.selection.selectorChanged(t,function(t){e.disabled(!t)})}o.initialized?n():o.on("init",n)}function h(){g(this,"table")}function v(){g(this,"td,th")}function b(){var e="";e='",i=0;e>i;i++)a+=" "}a+=""+(r.ie?" ":" ";a+="
")+"';for(var t=0;10>t;t++){e+="
",e+='";for(var n=0;10>n;n++)e+=' "}return e+="";e+="
"+t,e.removeChild(e.firstChild)}catch(r){var i=n.create("div");i.innerHTML="
"+t,d(p(i.childNodes),function(t,n){n&&e.canHaveHTML&&e.appendChild(t)})}}else e.innerHTML=t;return t})},getOuterHTML:function(e){var t,n=this;return(e=n.get(e))?1===e.nodeType&&n.hasOuterHTML?e.outerHTML:(t=(e.ownerDocument||n.doc).createElement("body"),t.appendChild(e.cloneNode(!0)),t.innerHTML):null},setOuterHTML:function(e,t,n){var r=this;return r.run(e,function(e){function i(){var i,o;for(o=n.createElement("body"),o.innerHTML=t,i=o.lastChild;i;)r.insertAfter(i.cloneNode(!0),e),i=i.previousSibling;r.remove(e)}if(1==e.nodeType)if(n=n||e.ownerDocument||r.doc,v)try{1==e.nodeType&&r.hasOuterHTML?e.outerHTML=t:i()}catch(o){i()}else i()})},decode:a.decode,encode:a.encodeAllRaw,insertAfter:function(e,t){return t=this.get(t),this.run(e,function(e){var n,r;return n=t.parentNode,r=t.nextSibling,r?n.insertBefore(e,r):n.appendChild(e),e})},replace:function(e,t,n){var r=this;return r.run(t,function(t){return f(t,"array")&&(e=e.cloneNode(!0)),n&&d(p(t.childNodes),function(t){e.appendChild(t)}),t.parentNode.replaceChild(e,t)})},rename:function(e,t){var n=this,r;return e.nodeName!=t.toUpperCase()&&(r=n.create(t),d(n.getAttribs(e),function(t){n.setAttrib(r,t.nodeName,n.getAttrib(e,t.nodeName))}),n.replace(r,e,1)),r||e},findCommonAncestor:function(e,t){for(var n=e,r;n;){for(r=t;r&&n!=r;)r=r.parentNode;if(n==r)break;n=n.parentNode}return!n&&e.ownerDocument?e.ownerDocument.documentElement:n},toHex:function(e){return this.styles.toHex(l.trim(e))},run:function(e,t,n){var r=this,i;return"string"==typeof e&&(e=r.get(e)),e?(n=n||this,e.nodeType||!e.length&&0!==e.length?t.call(n,e):(i=[],d(e,function(e,o){e&&("string"==typeof e&&(e=r.get(e)),i.push(t.call(n,e,o)))}),i)):!1},getAttribs:function(e){var t;if(e=this.get(e),!e)return[];if(v){if(t=[],"OBJECT"==e.nodeName)return e.attributes;"OPTION"===e.nodeName&&this.getAttrib(e,"selected")&&t.push({specified:1,nodeName:"selected"});var n=/<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi;return e.cloneNode(!1).outerHTML.replace(n,"").replace(/[\w:\-]+/gi,function(e){t.push({specified:1,nodeName:e})}),t}return e.attributes},isEmpty:function(e,t){var n=this,r,o,a,s,l,c=0;if(e=e.firstChild){s=new i(e,e.parentNode),t=t||n.schema?n.schema.getNonEmptyElements():null;do{if(a=e.nodeType,1===a){if(e.getAttribute("data-mce-bogus"))continue;if(l=e.nodeName.toLowerCase(),t&&t[l]){if("br"===l){c++;continue}return!1}for(o=n.getAttribs(e),r=e.attributes.length;r--;)if(l=e.attributes[r].nodeName,"name"===l||"data-mce-bookmark"===l)return!1}if(8==a)return!1;if(3===a&&!b.test(e.nodeValue))return!1}while(e=s.next())}return 1>=c},createRng:function(){var e=this.doc;return e.createRange?e.createRange():new o(this)},nodeIndex:function(e,t){var n=0,r,i;if(e)for(r=e.nodeType,e=e.previousSibling;e;e=e.previousSibling)i=e.nodeType,(!t||3!=i||i!=r&&e.nodeValue.length)&&(n++,r=i);return n},split:function(e,t,n){function r(e){function t(e){var t=e.previousSibling&&"SPAN"==e.previousSibling.nodeName,n=e.nextSibling&&"SPAN"==e.nextSibling.nodeName;return t&&n}var n,o=e.childNodes,a=e.nodeType;if(1!=a||"bookmark"!=e.getAttribute("data-mce-type")){for(n=o.length-1;n>=0;n--)r(o[n]);if(9!=a){if(3==a&&e.nodeValue.length>0){var s=m(e.nodeValue).length;if(!i.isBlock(e.parentNode)||s>0||0===s&&t(e))return}else if(1==a&&(o=e.childNodes,1==o.length&&o[0]&&1==o[0].nodeType&&"bookmark"==o[0].getAttribute("data-mce-type")&&e.parentNode.insertBefore(o[0],e),o.length||/^(br|hr|input|img)$/i.test(e.nodeName)))return;i.remove(e)}return e}}var i=this,o=i.createRng(),a,s,l;return e&&t?(o.setStart(e.parentNode,i.nodeIndex(e)),o.setEnd(t.parentNode,i.nodeIndex(t)),a=o.extractContents(),o=i.createRng(),o.setStart(t.parentNode,i.nodeIndex(t)+1),o.setEnd(e.parentNode,i.nodeIndex(e)+1),s=o.extractContents(),l=e.parentNode,l.insertBefore(r(a),e),n?l.replaceChild(n,t):l.insertBefore(t,e),l.insertBefore(r(s),e),i.remove(e),n||t):void 0},bind:function(e,t,n,r){var i=this;if(l.isArray(e)){for(var o=e.length;o--;)e[o]=i.bind(e[o],t,n,r);return e}return!i.settings.collect||e!==i.doc&&e!==i.win||i.boundEvents.push([e,t,n,r]),i.events.bind(e,t,n,r||i)},unbind:function(e,t,n){var r=this,i;if(l.isArray(e)){for(i=e.length;i--;)e[i]=r.unbind(e[i],t,n);return e}if(r.boundEvents&&(e===r.doc||e===r.win))for(i=r.boundEvents.length;i--;){var o=r.boundEvents[i];e!=o[0]||t&&t!=o[1]||n&&n!=o[2]||this.events.unbind(o[0],o[1],o[2])}return this.events.unbind(e,t,n)},fire:function(e,t,n){return this.events.fire(e,t,n)},getContentEditable:function(e){var t;return 1!=e.nodeType?null:(t=e.getAttribute("data-mce-contenteditable"),t&&"inherit"!==t?t:"inherit"!==e.contentEditable?e.contentEditable:null)},destroy:function(){var t=this;if(t.boundEvents){for(var n=t.boundEvents.length;n--;){var r=t.boundEvents[n];this.events.unbind(r[0],r[1],r[2])}t.boundEvents=null}e.setDocument&&e.setDocument(),t.win=t.doc=t.root=t.events=t.frag=null},dumpRng:function(e){return"startContainer: "+e.startContainer.nodeName+", startOffset: "+e.startOffset+", endContainer: "+e.endContainer.nodeName+", endOffset: "+e.endOffset},_findSib:function(e,t,n){var r=this,i=t;if(e)for("string"==typeof i&&(i=function(e){return r.is(e,t)}),e=e[n];e;e=e[n])if(i(e))return e;return null}},u.DOM=new u(document),u}),r(b,[y,p],function(e,t){function n(){function e(e,t){function n(){o.remove(s),a&&(a.onreadystatechange=a.onload=a=null),t()
-}function i(){"undefined"!=typeof console&&console.log&&console.log("Failed to load: "+e)}var o=r,a,s;s=o.uniqueId(),a=document.createElement("script"),a.id=s,a.type="text/javascript",a.src=e,"onreadystatechange"in a?a.onreadystatechange=function(){/loaded|complete/.test(a.readyState)&&n()}:a.onload=n,a.onerror=i,(document.getElementsByTagName("head")[0]||document.body).appendChild(a)}var t=0,n=1,a=2,s={},l=[],c={},u=[],d=0,f;this.isDone=function(e){return s[e]==a},this.markDone=function(e){s[e]=a},this.add=this.load=function(e,n,r){var i=s[e];i==f&&(l.push(e),s[e]=t),n&&(c[e]||(c[e]=[]),c[e].push({func:n,scope:r||this}))},this.loadQueue=function(e,t){this.loadScripts(l,e,t)},this.loadScripts=function(t,r,l){function p(e){i(c[e],function(e){e.func.call(e.scope)}),c[e]=f}var m;u.push({func:r,scope:l||this}),(m=function(){var r=o(t);t.length=0,i(r,function(t){return s[t]==a?void p(t):void(s[t]!=n&&(s[t]=n,d++,e(t,function(){s[t]=a,d--,p(t),m()})))}),d||(i(u,function(e){e.func.call(e.scope)}),u.length=0)})()}}var r=e.DOM,i=t.each,o=t.grep;return n.ScriptLoader=new n,n}),r(C,[b,p],function(e,n){function r(){var e=this;e.items=[],e.urls={},e.lookup={}}var i=n.each;return r.prototype={get:function(e){return this.lookup[e]?this.lookup[e].instance:t},dependencies:function(e){var t;return this.lookup[e]&&(t=this.lookup[e].dependencies),t||[]},requireLangPack:function(t,n){if(r.language&&r.languageLoad!==!1){if(n&&new RegExp("([, ]|\\b)"+r.language+"([, ]|\\b)").test(n)===!1)return;e.ScriptLoader.add(this.urls[t]+"/langs/"+r.language+".js")}},add:function(e,t,n){return this.items.push(t),this.lookup[e]={instance:t,dependencies:n},t},createUrl:function(e,t){return"object"==typeof t?t:{prefix:e.prefix,resource:t,suffix:e.suffix}},addComponents:function(t,n){var r=this.urls[t];i(n,function(t){e.ScriptLoader.add(r+"/"+t)})},load:function(n,o,a,s){function l(){var r=c.dependencies(n);i(r,function(e){var n=c.createUrl(o,e);c.load(n.resource,n,t,t)}),a&&a.call(s?s:e)}var c=this,u=o;c.urls[n]||("object"==typeof o&&(u=o.prefix+o.resource+o.suffix),0!==u.indexOf("/")&&-1==u.indexOf("://")&&(u=r.baseURL+"/"+u),c.urls[n]=u.substring(0,u.lastIndexOf("/")),c.lookup[n]?l():e.ScriptLoader.add(u,l,s))}},r.PluginManager=new r,r.ThemeManager=new r,r}),r(x,[],function(){function e(e,t,n){var r,i,o=n?"lastChild":"firstChild",a=n?"prev":"next";if(e[o])return e[o];if(e!==t){if(r=e[a])return r;for(i=e.parent;i&&i!==t;i=i.parent)if(r=i[a])return r}}function t(e,t){this.name=e,this.type=t,1===t&&(this.attributes=[],this.attributes.map={})}var n=/^[ \t\r\n]*$/,r={"#text":3,"#comment":8,"#cdata":4,"#pi":7,"#doctype":10,"#document-fragment":11};return t.prototype={replace:function(e){var t=this;return e.parent&&e.remove(),t.insert(e,t),t.remove(),t},attr:function(e,t){var n=this,r,i,o;if("string"!=typeof e){for(i in e)n.attr(i,e[i]);return n}if(r=n.attributes){if(t!==o){if(null===t){if(e in r.map)for(delete r.map[e],i=r.length;i--;)if(r[i].name===e)return r=r.splice(i,1),n;return n}if(e in r.map){for(i=r.length;i--;)if(r[i].name===e){r[i].value=t;break}}else r.push({name:e,value:t});return r.map[e]=t,n}return r.map[e]}},clone:function(){var e=this,n=new t(e.name,e.type),r,i,o,a,s;if(o=e.attributes){for(s=[],s.map={},r=0,i=o.length;i>r;r++)a=o[r],"id"!==a.name&&(s[s.length]={name:a.name,value:a.value},s.map[a.name]=a.value);n.attributes=s}return n.value=e.value,n.shortEnded=e.shortEnded,n},wrap:function(e){var t=this;return t.parent.insert(e,t),e.append(t),t},unwrap:function(){var e=this,t,n;for(t=e.firstChild;t;)n=t.next,e.insert(t,e,!0),t=n;e.remove()},remove:function(){var e=this,t=e.parent,n=e.next,r=e.prev;return t&&(t.firstChild===e?(t.firstChild=n,n&&(n.prev=null)):r.next=n,t.lastChild===e?(t.lastChild=r,r&&(r.next=null)):n.prev=r,e.parent=e.next=e.prev=null),e},append:function(e){var t=this,n;return e.parent&&e.remove(),n=t.lastChild,n?(n.next=e,e.prev=n,t.lastChild=e):t.lastChild=t.firstChild=e,e.parent=t,e},insert:function(e,t,n){var r;return e.parent&&e.remove(),r=t.parent||this,n?(t===r.firstChild?r.firstChild=e:t.prev.next=e,e.prev=t.prev,e.next=t,t.prev=e):(t===r.lastChild?r.lastChild=e:t.next.prev=e,e.next=t.next,e.prev=t,t.next=e),e.parent=r,e},getAll:function(t){var n=this,r,i=[];for(r=n.firstChild;r;r=e(r,n))r.name===t&&i.push(r);return i},empty:function(){var t=this,n,r,i;if(t.firstChild){for(n=[],i=t.firstChild;i;i=e(i,t))n.push(i);for(r=n.length;r--;)i=n[r],i.parent=i.firstChild=i.lastChild=i.next=i.prev=null}return t.firstChild=t.lastChild=null,t},isEmpty:function(t){var r=this,i=r.firstChild,o,a;if(i)do{if(1===i.type){if(i.attributes.map["data-mce-bogus"])continue;if(t[i.name])return!1;for(o=i.attributes.length;o--;)if(a=i.attributes[o].name,"name"===a||0===a.indexOf("data-mce-"))return!1}if(8===i.type)return!1;if(3===i.type&&!n.test(i.value))return!1}while(i=e(i,r));return!0},walk:function(t){return e(this,null,t)}},t.create=function(e,n){var i,o;if(i=new t(e,r[e]||1),n)for(o in n)i.attr(o,n[o]);return i},t}),r(w,[p],function(e){function t(e,t){return e?e.split(t||" "):[]}function n(e){function n(e,n,r){function i(e){var t={},n,r;for(n=0,r=e.length;r>n;n++)t[e[n]]={};return t}var o,l,c,u=arguments;for(r=r||[],n=n||"","string"==typeof r&&(r=t(r)),l=3;l
"+(r.item?r.item(0).outerHTML:r.htmlText),i.removeChild(i.firstChild)):i.innerHTML=r.toString(),/^\s/.test(i.innerHTML)&&(a=" "),/\s+$/.test(i.innerHTML)&&(s=" "),e.getInner=!0,e.content=n.isCollapsed()?"":a+n.serializer.serialize(i,e)+s,n.editor.fire("GetContent",e),e.content)},setContent:function(e,t){var n=this,r=n.getRng(),i,o=n.win.document,a,s;if(t=t||{format:"html"},t.set=!0,t.selection=!0,e=t.content=e,t.no_events||n.editor.fire("BeforeSetContent",t),e=t.content,r.insertNode){e+='_',r.startContainer==o&&r.endContainer==o?o.body.innerHTML=e:(r.deleteContents(),0===o.body.childNodes.length?o.body.innerHTML=e:r.createContextualFragment?r.insertNode(r.createContextualFragment(e)):(a=o.createDocumentFragment(),s=o.createElement("div"),a.appendChild(s),s.outerHTML=e,r.insertNode(a))),i=n.dom.get("__caret"),r=o.createRange(),r.setStartBefore(i),r.setEndBefore(i),n.setRng(r),n.dom.remove("__caret");try{n.setRng(r)}catch(l){}}else r.item&&(o.execCommand("Delete",!1,null),r=n.getRng()),/^\s+/.test(e)?(r.pasteHTML('_'+e),n.dom.remove("__mce_tmp")):r.pasteHTML(e);t.no_events||n.editor.fire("SetContent",t)},getStart:function(){var e=this,t=e.getRng(),n,r,i,o;if(t.duplicate||t.item){if(t.item)return t.item(0);for(i=t.duplicate(),i.collapse(1),n=i.parentElement(),n.ownerDocument!==e.dom.doc&&(n=e.dom.getRoot()),r=o=t.parentElement();o=o.parentNode;)if(o==n){n=r;break}return n}return n=t.startContainer,1==n.nodeType&&n.hasChildNodes()&&(n=n.childNodes[Math.min(n.childNodes.length-1,t.startOffset)]),n&&3==n.nodeType?n.parentNode:n},getEnd:function(){var e=this,t=e.getRng(),n,r;return t.duplicate||t.item?t.item?t.item(0):(t=t.duplicate(),t.collapse(0),n=t.parentElement(),n.ownerDocument!==e.dom.doc&&(n=e.dom.getRoot()),n&&"BODY"==n.nodeName?n.lastChild||n:n):(n=t.endContainer,r=t.endOffset,1==n.nodeType&&n.hasChildNodes()&&(n=n.childNodes[r>0?r-1:r]),n&&3==n.nodeType?n.parentNode:n)},getBookmark:function(e,t){function n(e,t){var n=0;return l(a.select(e),function(e,r){e==t&&(n=r)}),n}function r(e){function t(t){var n,r,i,o=t?"start":"end";n=e[o+"Container"],r=e[o+"Offset"],1==n.nodeType&&"TR"==n.nodeName&&(i=n.childNodes,n=i[Math.min(t?r:r-1,i.length-1)],n&&(r=t?0:n.childNodes.length,e["set"+(t?"Start":"End")](n,r)))}return t(!0),t(),e}function i(){function e(e,n){var i=e[n?"startContainer":"endContainer"],a=e[n?"startOffset":"endOffset"],s=[],l,c,u=0;if(3==i.nodeType){if(t)for(l=i.previousSibling;l&&3==l.nodeType;l=l.previousSibling)a+=l.nodeValue.length;s.push(a)}else c=i.childNodes,a>=c.length&&c.length&&(u=1,a=Math.max(0,c.length-1)),s.push(o.dom.nodeIndex(c[a],t)+u);for(;i&&i!=r;i=i.parentNode)s.push(o.dom.nodeIndex(i,t));return s}var n=o.getRng(!0),r=a.getRoot(),i={};return i.start=e(n,!0),o.isCollapsed()||(i.end=e(n)),i}var o=this,a=o.dom,s,c,u,d,f,p,m="",h;if(2==e)return p=o.getNode(),f=p?p.nodeName:null,"IMG"==f?{name:f,index:n(f,p)}:o.tridentSel?o.tridentSel.getBookmark(e):i();if(e)return{rng:o.getRng()};if(s=o.getRng(),u=a.uniqueId(),d=o.isCollapsed(),h="overflow:hidden;line-height:0px",s.duplicate||s.item){if(s.item)return p=s.item(0),f=p.nodeName,{name:f,index:n(f,p)};c=s.duplicate();try{s.collapse(),s.pasteHTML(''+m+""),d||(c.collapse(!1),s.moveToElementText(c.parentElement()),0===s.compareEndPoints("StartToEnd",c)&&c.move("character",-1),c.pasteHTML(''+m+""))}catch(g){return null}}else{if(p=o.getNode(),f=p.nodeName,"IMG"==f)return{name:f,index:n(f,p)};c=r(s.cloneRange()),d||(c.collapse(!1),c.insertNode(a.create("span",{"data-mce-type":"bookmark",id:u+"_end",style:h},m))),s=r(s),s.collapse(!0),s.insertNode(a.create("span",{"data-mce-type":"bookmark",id:u+"_start",style:h},m))}return o.moveToBookmark({id:u,keep:1}),{id:u}},moveToBookmark:function(e){function t(t){var n=e[t?"start":"end"],r,i,o,l;if(n){for(o=n[0],i=s,r=n.length-1;r>=1;r--){if(l=i.childNodes,n[r]>l.length-1)return;i=l[n[r]]}3===i.nodeType&&(o=Math.min(n[0],i.nodeValue.length)),1===i.nodeType&&(o=Math.min(n[0],i.childNodes.length)),t?a.setStart(i,o):a.setEnd(i,o)}return!0}function n(t){var n=o.get(e.id+"_"+t),r,i,a,s,d=e.keep;if(n&&(r=n.parentNode,"start"==t?(d?(r=n.firstChild,i=1):i=o.nodeIndex(n),u=p=r,m=h=i):(d?(r=n.firstChild,i=1):i=o.nodeIndex(n),p=r,h=i),!d)){for(s=n.previousSibling,a=n.nextSibling,l(c(n.childNodes),function(e){3==e.nodeType&&(e.nodeValue=e.nodeValue.replace(/\uFEFF/g,""))});n=o.get(e.id+"_"+t);)o.remove(n,1);s&&a&&s.nodeType==a.nodeType&&3==s.nodeType&&!f&&(i=s.nodeValue.length,s.appendData(a.nodeValue),o.remove(a),"start"==t?(u=p=s,m=h=i):(p=s,h=i))}}function r(e){return!o.isBlock(e)||e.innerHTML||d||(e.innerHTML='
'),e}var i=this,o=i.dom,a,s,u,p,m,h;if(e)if(e.start){if(a=o.createRng(),s=o.getRoot(),i.tridentSel)return i.tridentSel.moveToBookmark(e);t(!0)&&t()&&i.setRng(a)}else e.id?(n("start"),n("end"),u&&(a=o.createRng(),a.setStart(r(u),m),a.setEnd(r(p),h),i.setRng(a))):e.name?i.select(o.select(e.name)[e.index]):e.rng&&i.setRng(e.rng)},select:function(e,t){var n=this,r=n.dom,i=r.createRng(),o;if(n.lastFocusBookmark=null,e){if(!t&&n.controlSelection.controlSelect(e))return;o=r.nodeIndex(e),i.setStart(e.parentNode,o),i.setEnd(e.parentNode,o+1),t&&(n._moveEndPoint(i,e,!0),n._moveEndPoint(i,e)),n.setRng(i)}return e},isCollapsed:function(){var e=this,t=e.getRng(),n=e.getSel();return!t||t.item?!1:t.compareEndPoints?0===t.compareEndPoints("StartToEnd",t):!n||t.collapsed},collapse:function(e){var t=this,n=t.getRng(),r;n.item&&(r=n.item(0),n=t.win.document.body.createTextRange(),n.moveToElementText(r)),n.collapse(!!e),t.setRng(n)},getSel:function(){var e=this.win;return e.getSelection?e.getSelection():e.document.selection},getRng:function(e){function t(e,t,n){try{return t.compareBoundaryPoints(e,n)}catch(r){return-1}}var n=this,r,i,o,a=n.win.document,s;if(!e&&n.lastFocusBookmark){var l=n.lastFocusBookmark;return l.startContainer?(i=a.createRange(),i.setStart(l.startContainer,l.startOffset),i.setEnd(l.endContainer,l.endOffset)):i=l,i}if(e&&n.tridentSel)return n.tridentSel.getRangeAt(0);try{(r=n.getSel())&&(i=r.rangeCount>0?r.getRangeAt(0):r.createRange?r.createRange():a.createRange())}catch(c){}if(d&&i&&i.setStart&&a.selection){try{s=a.selection.createRange()}catch(c){}s&&s.item&&(o=s.item(0),i=a.createRange(),i.setStartBefore(o),i.setEndAfter(o))}return i||(i=a.createRange?a.createRange():a.body.createTextRange()),i.setStart&&9===i.startContainer.nodeType&&i.collapsed&&(o=n.dom.getRoot(),i.setStart(o,0),i.setEnd(o,0)),n.selectedRange&&n.explicitRange&&(0===t(i.START_TO_START,i,n.selectedRange)&&0===t(i.END_TO_END,i,n.selectedRange)?i=n.explicitRange:(n.selectedRange=null,n.explicitRange=null)),i},setRng:function(e,t){var n=this,r;if(e.select)try{e.select()}catch(i){}else if(n.tridentSel){if(e.cloneRange)try{return void n.tridentSel.addRange(e)}catch(i){}}else if(r=n.getSel()){n.explicitRange=e;try{r.removeAllRanges(),r.addRange(e)}catch(i){}t===!1&&r.extend&&(r.collapse(e.endContainer,e.endOffset),r.extend(e.startContainer,e.startOffset)),n.selectedRange=r.rangeCount>0?r.getRangeAt(0):null}},setNode:function(e){var t=this;return t.setContent(t.dom.getOuterHTML(e)),e},getNode:function(){function e(e,t){for(var n=e;e&&3===e.nodeType&&0===e.length;)e=t?e.nextSibling:e.previousSibling;return e||n}var t=this,n=t.getRng(),r,i=n.startContainer,o=n.endContainer,a=n.startOffset,s=n.endOffset,l=t.dom.getRoot();return n?n.setStart?(r=n.commonAncestorContainer,!n.collapsed&&(i==o&&2>s-a&&i.hasChildNodes()&&(r=i.childNodes[a]),3===i.nodeType&&3===o.nodeType&&(i=i.length===a?e(i.nextSibling,!0):i.parentNode,o=0===s?e(o.previousSibling,!1):o.parentNode,i&&i===o))?i:r&&3==r.nodeType?r.parentNode:r):(r=n.item?n.item(0):n.parentElement(),r.ownerDocument!==t.win.document&&(r=l),r):l},getSelectedBlocks:function(t,n){var r=this,i=r.dom,o,a,s=[];if(a=i.getRoot(),t=i.getParent(t||r.getStart(),i.isBlock),n=i.getParent(n||r.getEnd(),i.isBlock),t&&t!=a&&s.push(t),t&&n&&t!=n){o=t;for(var l=new e(t,a);(o=l.next())&&o!=n;)i.isBlock(o)&&s.push(o)}return n&&t!=n&&n!=a&&s.push(n),s},isForward:function(){var e=this.dom,t=this.getSel(),n,r;return t&&t.anchorNode&&t.focusNode?(n=e.createRng(),n.setStart(t.anchorNode,t.anchorOffset),n.collapse(!0),r=e.createRng(),r.setStart(t.focusNode,t.focusOffset),r.collapse(!0),n.compareBoundaryPoints(n.START_TO_START,r)<=0):!0},normalize:function(){var e=this,t=e.getRng();return!d&&new i(e.dom).normalize(t)&&e.setRng(t,e.isForward()),t},selectorChanged:function(e,t){var n=this,r;return n.selectorChangedData||(n.selectorChangedData={},r={},n.editor.on("NodeChange",function(e){var t=e.element,i=n.dom,o=i.getParents(t,null,i.getRoot()),a={};l(n.selectorChangedData,function(e,t){l(o,function(n){return i.is(n,t)?(r[t]||(l(e,function(e){e(!0,{node:n,selector:t,parents:o})}),r[t]=e),a[t]=e,!1):void 0})}),l(r,function(e,n){a[n]||(delete r[n],l(e,function(e){e(!1,{node:t,selector:n,parents:o})}))})})),n.selectorChangedData[e]||(n.selectorChangedData[e]=[]),n.selectorChangedData[e].push(t),n},getScrollContainer:function(){for(var e,t=this.dom.getRoot();t&&"BODY"!=t.nodeName;){if(t.scrollHeight>t.clientHeight){e=t;break}t=t.parentNode}return e},scrollIntoView:function(e){function t(e){for(var t=0,n=0,r=e;r&&r.nodeType;)t+=r.offsetLeft||0,n+=r.offsetTop||0,r=r.offsetParent;return{x:t,y:n}}var n,r,i=this,o=i.dom,a=o.getRoot(),s,l;if("BODY"!=a.nodeName){var c=i.getScrollContainer();if(c)return n=t(e).y-t(c).y,l=c.clientHeight,s=c.scrollTop,void((s>n||n+25>s+l)&&(c.scrollTop=s>n?n:n-l+25))}r=o.getViewPort(i.editor.getWin()),n=o.getPos(e).y,s=r.y,l=r.h,(n
'),n}function y(t){var n,r,i;if(3==R.nodeType&&(t?A>0:A
|)$/," "))),e}var a,s,l,c,d,f,p,m,h,g,v;/^ | $/.test(i)&&(i=o(i)),a=r.parser,s=new e({},r.schema),v='ÈB;',f={content:i,format:"html",selection:!0},r.fire("BeforeSetContent",f),i=f.content,-1==i.indexOf("{$caret}")&&(i+="{$caret}"),i=i.replace(/\{\$caret\}/,v),m=_.getRng();var y=m.startContainer||(m.parentElement?m.parentElement():null),b=r.getBody();y===b&&_.isCollapsed()&&w.isBlock(b.firstChild)&&w.isEmpty(b.firstChild)&&(m=w.createRng(),m.setStart(b.firstChild,0),m.setEnd(b.firstChild,0),_.setRng(m)),_.isCollapsed()||r.getDoc().execCommand("Delete",!1,null),l=_.getNode();var C={context:l.nodeName.toLowerCase()};if(d=a.parse(i,C),h=d.lastChild,"mce_marker"==h.attr("id"))for(p=h,h=h.prev;h;h=h.walk(!0))if(3==h.type||!w.isBlock(h.name)){h.parent.insert(p,h,"br"===h.name);break}if(C.invalid){for(_.setContent(v),l=_.getNode(),c=r.getBody(),9==l.nodeType?l=h=c:h=l;h!==c;)l=h,h=h.parentNode;i=l==c?c.innerHTML:w.getOuterHTML(l),i=s.serialize(a.parse(i.replace(//i,function(){return s.serialize(d)}))),l==c?w.setHTML(c,i):w.setOuterHTML(l,i)}else i=s.serialize(d),h=l.firstChild,g=l.lastChild,!h||h===g&&"BR"===h.nodeName?w.setHTML(l,i):_.setContent(i);p=w.get("mce_marker"),_.scrollIntoView(p),m=w.createRng(),h=p.previousSibling,h&&3==h.nodeType?(m.setStart(h,h.nodeValue.length),u||(g=p.nextSibling,g&&3==g.nodeType&&(h.appendData(g.data),g.parentNode.removeChild(g)))):(m.setStartBefore(p),m.setEndBefore(p)),w.remove(p),_.setRng(m),r.fire("SetContent",f),r.addVisual()},mceInsertRawHTML:function(e,t,n){_.setContent("tiny_mce_marker"),r.setContent(r.getContent().replace(/tiny_mce_marker/g,function(){return n}))},mceToggleFormat:function(e,t,n){b(n)},mceSetContent:function(e,t,n){r.setContent(n)},"Indent,Outdent":function(e){var t,n,o;t=E.indentation,n=/[a-z%]+$/i.exec(t),t=parseInt(t,10),m("InsertUnorderedList")||m("InsertOrderedList")?v(e):(E.forced_root_block||w.getParent(_.getNode(),w.isBlock)||S.apply("div"),i(_.getSelectedBlocks(),function(i){if("LI"!=i.nodeName){var a=r.getParam("indent_use_margin",!1)?"margin":"padding";a+="rtl"==w.getStyle(i,"direction",!0)?"Right":"Left","outdent"==e?(o=Math.max(0,parseInt(i.style[a]||0,10)-t),w.setStyle(i,a,o?o+n:"")):(o=parseInt(i.style[a]||0,10)+t+n,w.setStyle(i,a,o))}}))},mceRepaint:function(){if(c)try{C(d),_.getSel()&&_.getSel().selectAllChildren(r.getBody()),_.collapse(d),x()}catch(e){}},InsertHorizontalRule:function(){r.execCommand("mceInsertContent",!1,"
")},mceToggleVisualAid:function(){r.hasVisual=!r.hasVisual,r.addVisual()},mceReplaceContent:function(e,t,n){r.execCommand("mceInsertContent",!1,n.replace(/\{\$selection\}/g,_.getContent({format:"text"})))},mceInsertLink:function(e,t,n){var r;"string"==typeof n&&(n={href:n}),r=w.getParent(_.getNode(),"a"),n.href=n.href.replace(" ","%20"),r&&n.href||S.remove("link"),n.href&&S.apply("link",n,r)},selectAll:function(){var e=w.getRoot(),t;_.getRng().setStart?(t=w.createRng(),t.setStart(e,0),t.setEnd(e,e.childNodes.length),_.setRng(t)):(t=_.getRng(),t.item||(t.moveToElementText(e),t.select()))},"delete":function(){v("Delete");var e=r.getBody();w.isEmpty(e)&&(r.setContent(""),e.firstChild&&w.isBlock(e.firstChild)?r.selection.setCursorLocation(e.firstChild,0):r.selection.setCursorLocation(e,0))},mceNewDocument:function(){r.setContent("")}}),g({"JustifyLeft,JustifyCenter,JustifyRight,JustifyFull":function(e){var t="align"+e.substring(7),n=_.isCollapsed()?[w.getParent(_.getNode(),w.isBlock)]:_.getSelectedBlocks(),r=a(n,function(e){return!!S.matchNode(e,t)});return-1!==s(r,d)},"Bold,Italic,Underline,Strikethrough,Superscript,Subscript":function(e){return y(e)},mceBlockQuote:function(){return y("blockquote")},Outdent:function(){var e;if(E.inline_styles){if((e=w.getParent(_.getStart(),w.isBlock))&&parseInt(e.style.paddingLeft,10)>0)return d;if((e=w.getParent(_.getEnd(),w.isBlock))&&parseInt(e.style.paddingLeft,10)>0)return d}return m("InsertUnorderedList")||m("InsertOrderedList")||!E.inline_styles&&!!w.getParent(_.getNode(),"BLOCKQUOTE")},"InsertUnorderedList,InsertOrderedList":function(e){var t=w.getParent(_.getNode(),"ul,ol");return t&&("insertunorderedlist"===e&&"UL"===t.tagName||"insertorderedlist"===e&&"OL"===t.tagName)}},"state"),g({"FontSize,FontName":function(e){var t=0,n;return(n=w.getParent(_.getNode(),"span"))&&(t="fontsize"==e?n.style.fontSize:n.style.fontFamily.replace(/, /g,",").replace(/[\'\"]/g,"").toLowerCase()),t}},"value"),g({Undo:function(){r.undoManager.undo()},Redo:function(){r.undoManager.redo()}})}}),r(I,[p],function(e){function t(e,i){var o=this,a,s;if(e=r(e),i=o.settings=i||{},/^([\w\-]+):([^\/]{2})/i.test(e)||/^\s*#/.test(e))return void(o.source=e);var l=0===e.indexOf("//");0!==e.indexOf("/")||l||(e=(i.base_uri?i.base_uri.protocol||"http":"http")+"://mce_host"+e),/^[\w\-]*:?\/\//.test(e)||(s=i.base_uri?i.base_uri.path:new t(location.href).directory,e=""===i.base_uri.protocol?"//mce_host"+o.toAbsPath(s,e):(i.base_uri&&i.base_uri.protocol||"http")+"://mce_host"+o.toAbsPath(s,e)),e=e.replace(/@@/g,"(mce_at)"),e=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(e),n(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],function(t,n){var r=e[n];r&&(r=r.replace(/\(mce_at\)/g,"@@")),o[t]=r}),a=i.base_uri,a&&(o.protocol||(o.protocol=a.protocol),o.userInfo||(o.userInfo=a.userInfo),o.port||"mce_host"!==o.host||(o.port=a.port),o.host&&"mce_host"!==o.host||(o.host=a.host),o.source=""),l&&(o.protocol="")}var n=e.each,r=e.trim;return t.prototype={setPath:function(e){var t=this;e=/^(.*?)\/?(\w+)?$/.exec(e),t.path=e[0],t.directory=e[1],t.file=e[2],t.source="",t.getURI()},toRelative:function(e){var n=this,r;if("./"===e)return e;if(e=new t(e,{base_uri:n}),"mce_host"!=e.host&&n.host!=e.host&&e.host||n.port!=e.port||n.protocol!=e.protocol&&""!==e.protocol)return e.getURI();var i=n.getURI(),o=e.getURI();return i==o||"/"==i.charAt(i.length-1)&&i.substr(0,i.length-1)==o?i:(r=n.toRelPath(n.path,e.path),e.query&&(r+="?"+e.query),e.anchor&&(r+="#"+e.anchor),r)},toAbsolute:function(e,n){return e=new t(e,{base_uri:this}),e.getURI(this.host==e.host&&this.protocol==e.protocol?n:0)},toRelPath:function(e,t){var n,r=0,i="",o,a;if(e=e.substring(0,e.lastIndexOf("/")),e=e.split("/"),n=t.split("/"),e.length>=n.length)for(o=0,a=e.length;a>o;o++)if(o>=n.length||e[o]!=n[o]){r=o+1;break}if(e.length
";var v='javascript:(function(){document.open();document.domain="'+document.domain+'";var ed = window.parent.tinymce.get("'+t.id+'");document.write(ed.iframeHTML);document.close();ed.initContentBody(true);})()';if(document.domain!=location.hostname&&(u=v),s=E.add(l.iframeContainer,"iframe",{id:t.id+"_ifr",src:u||'javascript:""',frameBorder:"0",allowTransparency:"true",title:t.editorManager.translate("Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help"),style:{width:"100%",height:o,display:"block"}}),P)try{t.getDoc()}catch(y){s.src=u=v}t.contentAreaContainer=l.iframeContainer,l.editorContainer&&(E.get(l.editorContainer).style.display=t.orgDisplay),E.get(t.id).style.display="none",E.setAttrib(t.id,"aria-hidden",!0),u||t.initContentBody(),r=s=l=null},initContentBody:function(t){var n=this,o=n.settings,f=E.get(n.id),p=n.getDoc(),m,h;o.inline||(n.getElement().style.visibility=n.orgVisibility),t||o.content_editable||(p.open(),p.write(n.iframeHTML),p.close()),o.content_editable&&(n.on("remove",function(){var e=this.getBody();E.removeClass(e,"mce-content-body"),E.removeClass(e,"mce-edit-focus"),E.setAttrib(e,"tabIndex",null),E.setAttrib(e,"contentEditable",null)}),E.addClass(f,"mce-content-body"),f.tabIndex=-1,n.contentDocument=p=o.content_document||document,n.contentWindow=o.content_window||window,n.bodyElement=f,o.content_document=o.content_window=null,o.root_name=f.nodeName.toLowerCase()),m=n.getBody(),m.disabled=!0,o.readonly||(n.inline&&"static"==E.getStyle(m,"position",!0)&&(m.style.position="relative"),m.contentEditable=n.getParam("content_editable_state",!0)),m.disabled=!1,n.schema=new g(o),n.dom=new e(p,{keep_values:!0,url_converter:n.convertURL,url_converter_scope:n,hex_colors:o.force_hex_style_colors,class_filter:o.class_filter,update_styles:!0,root_element:o.content_editable?n.id:null,collect:o.content_editable,schema:n.schema,onSetAttrib:function(e){n.fire("SetAttrib",e)}}),n.parser=new v(o,n.schema),n.parser.addAttributeFilter("src,href,style",function(e,t){for(var r=e.length,i,o=n.dom,a,s;r--;)i=e[r],a=i.attr(t),s="data-mce-"+t,i.attributes.map[s]||("style"===t?i.attr(s,o.serializeStyle(o.parseStyle(a),i.name)):i.attr(s,n.convertURL(a,t,i.name)))}),n.parser.addNodeFilter("script",function(e){for(var t=e.length,n;t--;)n=e[t],n.attr("type","mce-"+(n.attr("type")||"text/javascript"))}),n.parser.addNodeFilter("#cdata",function(e){for(var t=e.length,n;t--;)n=e[t],n.type=8,n.name="#comment",n.value="[CDATA["+n.value+"]]"}),n.parser.addNodeFilter("p,h1,h2,h3,h4,h5,h6,div",function(e){for(var t=e.length,i,o=n.schema.getNonEmptyElements();t--;)i=e[t],i.isEmpty(o)&&(i.empty().append(new r("br",1)).shortEnded=!0)}),n.serializer=new i(o,n),n.selection=new a(n.dom,n.getWin(),n.serializer,n),n.formatter=new s(n),n.undoManager=new l(n),n.forceBlocks=new u(n),n.enterKey=new c(n),n.editorCommands=new d(n),n.fire("PreInit"),o.browser_spellcheck||o.gecko_spellcheck||(p.body.spellcheck=!1,E.setAttrib(m,"spellcheck","false")),n.fire("PostRender"),n.quirks=y(n),o.directionality&&(m.dir=o.directionality),o.nowrap&&(m.style.whiteSpace="nowrap"),o.protect&&n.on("BeforeSetContent",function(e){R(o.protect,function(t){e.content=e.content.replace(t,function(e){return""})})}),n.on("SetContent",function(){n.addVisual(n.getBody())}),o.padd_empty_editor&&n.on("PostProcess",function(e){e.content=e.content.replace(/^(
[\r\n]*)$/,"")}),n.load({initial:!0,format:"html"}),n.startContent=n.getContent({format:"raw"}),n.initialized=!0,R(n._pendingNativeEvents,function(e){n.dom.bind(_(n,e),e,function(e){n.fire(e.type,e)})}),n.fire("init"),n.focus(!0),n.nodeChanged({initial:!0}),n.execCallback("init_instance_callback",n),n.contentStyles.length>0&&(h="",R(n.contentStyles,function(e){h+=e+"\r\n"}),n.dom.addStyle(h)),R(n.contentCSS,function(e){n.loadedCSS[e]||(n.dom.loadCSS(e),n.loadedCSS[e]=!0)}),o.auto_focus&&setTimeout(function(){var e=n.editorManager.get(o.auto_focus);e.selection.select(e.getBody(),1),e.selection.collapse(1),e.getBody().focus(),e.getWin().focus()},100),f=p=m=null},focus:function(e){var t,n=this,r=n.selection,i=n.settings.content_editable,o,a,s=n.getDoc(),l;e||(o=r.getRng(),o.item&&(a=o.item(0)),n._refreshContentEditable(),i||(b.opera||n.getBody().focus(),n.getWin().focus()),(H||i)&&(l=n.getBody(),l.setActive&&b.ie<11?l.setActive():l.focus(),i&&r.normalize()),a&&a.ownerDocument==s&&(o=s.body.createControlRange(),o.addElement(a),o.select())),n.editorManager.activeEditor!=n&&((t=n.editorManager.activeEditor)&&t.fire("deactivate",{relatedTarget:n}),n.fire("activate",{relatedTarget:t})),n.editorManager.activeEditor=n},execCallback:function(e){var t=this,n=t.settings[e],r;if(n)return t.callbackLookup&&(r=t.callbackLookup[e])&&(n=r.func,r=r.scope),"string"==typeof n&&(r=n.replace(/\.\w+$/,""),r=r?D(r):0,n=D(n),t.callbackLookup=t.callbackLookup||{},t.callbackLookup[e]={func:n,scope:r}),n.apply(r||t,Array.prototype.slice.call(arguments,1))},translate:function(e){var t=this.settings.language||"en",n=this.editorManager.i18n;return e?n.data[t+"."+e]||e.replace(/\{\#([^\}]+)\}/g,function(e,r){return n.data[t+"."+r]||"{#"+r+"}"}):""},getLang:function(e,n){return this.editorManager.i18n.data[(this.settings.language||"en")+"."+e]||(n!==t?n:"{#"+e+"}")},getParam:function(e,t,n){var r=e in this.settings?this.settings[e]:t,i;return"hash"===n?(i={},"string"==typeof r?R(r.split(r.indexOf("=")>0?/[;,](?![^=;,]*(?:[;,]|$))/:","),function(e){e=e.split("="),i[L(e[0])]=L(e.length>1?e[1]:e)}):i=r,i):r},nodeChanged:function(){var e=this,t=e.selection,n,r,i;!e.initialized||e.settings.disable_nodechange||e.settings.readonly||(i=e.getBody(),n=t.getStart()||i,n=P&&n.ownerDocument!=e.getDoc()?e.getBody():n,"IMG"==n.nodeName&&t.isCollapsed()&&(n=n.parentNode),r=[],e.dom.getParent(n,function(e){return e===i?!0:void r.push(e)
-}),e.fire("NodeChange",{element:n,parents:r}))},addButton:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),t.text||t.icon||(t.icon=e),n.buttons=n.buttons||{},t.tooltip=t.tooltip||t.title,n.buttons[e]=t},addMenuItem:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),n.menuItems=n.menuItems||{},n.menuItems[e]=t},addCommand:function(e,t,n){this.execCommands[e]={func:t,scope:n||this}},addQueryStateHandler:function(e,t,n){this.queryStateCommands[e]={func:t,scope:n||this}},addQueryValueHandler:function(e,t,n){this.queryValueCommands[e]={func:t,scope:n||this}},addShortcut:function(e,t,n,r){this.shortcuts.add(e,t,n,r)},execCommand:function(e,t,n,r){var i=this,o=0,a;return/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(e)||r&&r.skip_focus||i.focus(),r=T({},r),r=i.fire("BeforeExecCommand",{command:e,ui:t,value:n}),r.isDefaultPrevented()?!1:(a=i.execCommands[e])&&a.func.call(a.scope,t,n)!==!0?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):(R(i.plugins,function(r){return r.execCommand&&r.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),o=!0,!1):void 0}),o?o:i.theme&&i.theme.execCommand&&i.theme.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):i.editorCommands.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):(i.getDoc().execCommand(e,t,n),void i.fire("ExecCommand",{command:e,ui:t,value:n})))},queryCommandState:function(e){var t=this,n,r;if(!t._isHidden()){if((n=t.queryStateCommands[e])&&(r=n.func.call(n.scope),r!==!0))return r;if(r=t.editorCommands.queryCommandState(e),-1!==r)return r;try{return t.getDoc().queryCommandState(e)}catch(i){}}},queryCommandValue:function(e){var n=this,r,i;if(!n._isHidden()){if((r=n.queryValueCommands[e])&&(i=r.func.call(r.scope),i!==!0))return i;if(i=n.editorCommands.queryCommandValue(e),i!==t)return i;try{return n.getDoc().queryCommandValue(e)}catch(o){}}},show:function(){var e=this;E.show(e.getContainer()),E.hide(e.id),e.load(),e.fire("show")},hide:function(){var e=this,t=e.getDoc();P&&t&&!e.inline&&t.execCommand("SelectAll"),e.save(),E.hide(e.getContainer()),E.setStyle(e.id,"display",e.orgDisplay),e.fire("hide")},isHidden:function(){return!E.isHidden(this.id)},setProgressState:function(e,t){this.fire("ProgressState",{state:e,time:t})},load:function(e){var n=this,r=n.getElement(),i;return r?(e=e||{},e.load=!0,i=n.setContent(r.value!==t?r.value:r.innerHTML,e),e.element=r,e.no_events||n.fire("LoadContent",e),e.element=r=null,i):void 0},save:function(e){var t=this,n=t.getElement(),r,i;if(n&&t.initialized)return e=e||{},e.save=!0,e.element=n,r=e.content=t.getContent(e),e.no_events||t.fire("SaveContent",e),r=e.content,/TEXTAREA|INPUT/i.test(n.nodeName)?n.value=r:(t.inline||(n.innerHTML=r),(i=E.getParent(t.id,"form"))&&R(i.elements,function(e){return e.name==t.id?(e.value=r,!1):void 0})),e.element=n=null,e.set_dirty!==!1&&(t.isNotDirty=!0),r},setContent:function(e,t){var n=this,r=n.getBody(),i;return t=t||{},t.format=t.format||"html",t.set=!0,t.content=e,t.no_events||n.fire("BeforeSetContent",t),e=t.content,0===e.length||/^\s+$/.test(e)?(i=n.settings.forced_root_block,i&&n.schema.isValidChild(r.nodeName.toLowerCase(),i.toLowerCase())?(e=P&&11>P?"":'
',e=n.dom.createHTML(i,n.settings.forced_root_block_attrs,e)):P||(e='
'),r.innerHTML=e,n.fire("SetContent",t)):("raw"!==t.format&&(e=new o({},n.schema).serialize(n.parser.parse(e,{isRootContent:!0}))),t.content=L(e),n.dom.setHTML(r,t.content),t.no_events||n.fire("SetContent",t)),t.content},getContent:function(e){var t=this,n,r=t.getBody();return e=e||{},e.format=e.format||"html",e.get=!0,e.getInner=!0,e.no_events||t.fire("BeforeGetContent",e),n="raw"==e.format?r.innerHTML:"text"==e.format?r.innerText||r.textContent:t.serializer.serialize(r,e),e.content="text"!=e.format?L(n):n,e.no_events||t.fire("GetContent",e),e.content},insertContent:function(e){this.execCommand("mceInsertContent",!1,e)},isDirty:function(){return!this.isNotDirty},getContainer:function(){var e=this;return e.container||(e.container=E.get(e.editorContainer||e.id+"_parent")),e.container},getContentAreaContainer:function(){return this.contentAreaContainer},getElement:function(){return E.get(this.settings.content_element||this.id)},getWin:function(){var e=this,t;return e.contentWindow||(t=E.get(e.id+"_ifr"),t&&(e.contentWindow=t.contentWindow)),e.contentWindow},getDoc:function(){var e=this,t;return e.contentDocument||(t=e.getWin(),t&&(e.contentDocument=t.document)),e.contentDocument},getBody:function(){return this.bodyElement||this.getDoc().body},convertURL:function(e,t,n){var r=this,i=r.settings;return i.urlconverter_callback?r.execCallback("urlconverter_callback",e,n,!0,t):!i.convert_urls||n&&"LINK"==n.nodeName||0===e.indexOf("file:")||0===e.length?e:i.relative_urls?r.documentBaseURI.toRelative(e):e=r.documentBaseURI.toAbsolute(e,i.remove_script_host)},addVisual:function(e){var n=this,r=n.settings,i=n.dom,o;e=e||n.getBody(),n.hasVisual===t&&(n.hasVisual=r.visual),R(i.select("table,a",e),function(e){var t;switch(e.nodeName){case"TABLE":return o=r.visual_table_class||"mce-item-table",t=i.getAttrib(e,"border"),void(t&&"0"!=t||(n.hasVisual?i.addClass(e,o):i.removeClass(e,o)));case"A":return void(i.getAttrib(e,"href",!1)||(t=i.getAttrib(e,"name")||e.id,o=r.visual_anchor_class||"mce-item-anchor",t&&(n.hasVisual?i.addClass(e,o):i.removeClass(e,o))))}}),n.fire("VisualAid",{element:e,hasVisual:n.hasVisual})},remove:function(){var e=this;if(!e.removed){e.save(),e.fire("remove"),e.off(),e.removed=1,e.hasHiddenInput&&E.remove(e.getElement().nextSibling),E.setStyle(e.id,"display",e.orgDisplay),e.settings.content_editable||(M.unbind(e.getWin()),M.unbind(e.getDoc()));var t=e.getContainer();M.unbind(e.getBody()),M.unbind(t),e.editorManager.remove(e),E.remove(t),e.destroy()}},bindNative:function(e){var t=this;t.settings.readonly||(t.initialized?t.dom.bind(_(t,e),e,function(n){t.fire(e,n)}):t._pendingNativeEvents?t._pendingNativeEvents.push(e):t._pendingNativeEvents=[e])},unbindNative:function(e){var t=this;t.initialized&&t.dom.unbind(e)},destroy:function(e){var t=this,n;if(!t.destroyed){if(!e&&!t.removed)return void t.remove();e&&H&&(M.unbind(t.getDoc()),M.unbind(t.getWin()),M.unbind(t.getBody())),e||(t.editorManager.off("beforeunload",t._beforeUnload),t.theme&&t.theme.destroy&&t.theme.destroy(),t.selection.destroy(),t.dom.destroy()),n=t.formElement,n&&(n._mceOldSubmit&&(n.submit=n._mceOldSubmit,n._mceOldSubmit=null),E.unbind(n,"submit reset",t.formEventDelegate)),t.contentAreaContainer=t.formElement=t.container=t.editorContainer=null,t.settings.content_element=t.bodyElement=t.contentDocument=t.contentWindow=null,t.selection&&(t.selection=t.selection.win=t.selection.dom=t.selection.dom.doc=null),t.destroyed=1}},_refreshContentEditable:function(){var e=this,t,n;e._isHidden()&&(t=e.getBody(),n=t.parentNode,n.removeChild(t),n.appendChild(t),t.focus())},_isHidden:function(){var e;return H?(e=this.selection.getSel(),!e||!e.rangeCount||0===e.rangeCount):0}},T(N.prototype,x),N}),r(at,[],function(){var e={};return{rtl:!1,add:function(t,n){for(var r in n)e[r]=n[r];this.rtl=this.rtl||"rtl"===e._dir},translate:function(t){if("undefined"==typeof t)return t;if("string"!=typeof t&&t.raw)return t.raw;if(t.push){var n=t.slice(1);t=(e[t[0]]||t[0]).replace(/\{([^\}]+)\}/g,function(e,t){return n[t]})}return e[t]||t},data:e}}),r(st,[y,g],function(e,t){function n(e){function a(){try{return document.activeElement}catch(e){return document.body}}function s(e){return e&&e.startContainer?{startContainer:e.startContainer,startOffset:e.startOffset,endContainer:e.endContainer,endOffset:e.endOffset}:e}function l(e,t){var n;return t.startContainer?(n=e.getDoc().createRange(),n.setStart(t.startContainer,t.startOffset),n.setEnd(t.endContainer,t.endOffset)):n=t,n}function c(e){return!!o.getParent(e,n.isEditorUIElement)}function u(e,t){for(var n=t.getBody();e;){if(e==n)return!0;e=e.parentNode}}function d(n){var d=n.editor;d.on("init",function(){(d.inline||t.ie)&&(d.on("nodechange keyup",function(){var e=document.activeElement;e&&e.id==d.id+"_ifr"&&(e=d.getBody()),u(e,d)&&(d.lastRng=d.selection.getRng())}),t.webkit&&!r&&(r=function(){var t=e.activeEditor;if(t&&t.selection){var n=t.selection.getRng();n&&!n.collapsed&&(d.lastRng=n)}},o.bind(document,"selectionchange",r)))}),d.on("setcontent",function(){d.lastRng=null}),d.on("mousedown",function(){d.selection.lastFocusBookmark=null}),d.on("focusin",function(){var t=e.focusedEditor;d.selection.lastFocusBookmark&&(d.selection.setRng(l(d,d.selection.lastFocusBookmark)),d.selection.lastFocusBookmark=null),t!=d&&(t&&t.fire("blur",{focusedEditor:d}),e.activeEditor=d,e.focusedEditor=d,d.fire("focus",{blurredEditor:t}),d.focus(!0)),d.lastRng=null}),d.on("focusout",function(){window.setTimeout(function(){var t=e.focusedEditor;c(a())||t!=d||(d.fire("blur",{focusedEditor:null}),e.focusedEditor=null,d.selection&&(d.selection.lastFocusBookmark=null))},0)}),i||(i=function(t){var n=e.activeEditor;n&&t.target.ownerDocument==document&&(n.selection&&(n.selection.lastFocusBookmark=s(n.lastRng)),c(t.target)||e.focusedEditor!=n||(n.fire("blur",{focusedEditor:null}),e.focusedEditor=null))},o.bind(document,"focusin",i))}function f(t){e.focusedEditor==t.editor&&(e.focusedEditor=null),e.activeEditor||(o.unbind(document,"selectionchange",r),o.unbind(document,"focusin",i),r=i=null)}e.on("AddEditor",d),e.on("RemoveEditor",f)}var r,i,o=e.DOM;return n.isEditorUIElement=function(e){return-1!==e.className.toString().indexOf("mce-")},n}),r(lt,[ot,y,I,g,p,rt,at,st],function(e,n,r,i,o,a,s,l){var c=n.DOM,u=o.explode,d=o.each,f=o.extend,p=0,m,h={majorVersion:"4",minorVersion:"0.20",releaseDate:"2014-03-18",editors:[],i18n:s,activeEditor:null,setup:function(){var e=this,t,n,i="",o;if(n=document.location.href.replace(/[\?#].*$/,"").replace(/[\/\\][^\/]+$/,""),/[\/\\]$/.test(n)||(n+="/"),o=window.tinymce||window.tinyMCEPreInit)t=o.base||o.baseURL,i=o.suffix;else for(var a=document.getElementsByTagName("script"),s=0;s';var l=25;for(o=0;o<10;o++){for(i+="
";var c={type:"container",html:i,onclick:function(a){var t=a.target;/^(TD|DIV)$/.test(t.nodeName)&&(e.execCommand("mceInsertContent",!1,tinymce.trim(t.innerText||t.textContent)),a.ctrlKey||n.close())},onmouseover:function(e){var t=a(e.target);t&&n.find("#preview").text(t.firstChild.firstChild.data)}};n=e.windowManager.open({title:"Special character",spacing:10,padding:10,items:[c,{type:"label",name:"preview",text:" ",style:"font-size: 40px; text-align: center",border:1,minWidth:100,minHeight:80}],buttons:[{text:"Close",onclick:function(){n.close()}}]})}var t=[["160","no-break space"],["38","ampersand"],["34","quotation mark"],["162","cent sign"],["8364","euro sign"],["163","pound sign"],["165","yen sign"],["169","copyright sign"],["174","registered sign"],["8482","trade mark sign"],["8240","per mille sign"],["181","micro sign"],["183","middle dot"],["8226","bullet"],["8230","three dot leader"],["8242","minutes / feet"],["8243","seconds / inches"],["167","section sign"],["182","paragraph sign"],["223","sharp s / ess-zed"],["8249","single left-pointing angle quotation mark"],["8250","single right-pointing angle quotation mark"],["171","left pointing guillemet"],["187","right pointing guillemet"],["8216","left single quotation mark"],["8217","right single quotation mark"],["8220","left double quotation mark"],["8221","right double quotation mark"],["8218","single low-9 quotation mark"],["8222","double low-9 quotation mark"],["60","less-than sign"],["62","greater-than sign"],["8804","less-than or equal to"],["8805","greater-than or equal to"],["8211","en dash"],["8212","em dash"],["175","macron"],["8254","overline"],["164","currency sign"],["166","broken bar"],["168","diaeresis"],["161","inverted exclamation mark"],["191","turned question mark"],["710","circumflex accent"],["732","small tilde"],["176","degree sign"],["8722","minus sign"],["177","plus-minus sign"],["247","division sign"],["8260","fraction slash"],["215","multiplication sign"],["185","superscript one"],["178","superscript two"],["179","superscript three"],["188","fraction one quarter"],["189","fraction one half"],["190","fraction three quarters"],["402","function / florin"],["8747","integral"],["8721","n-ary sumation"],["8734","infinity"],["8730","square root"],["8764","similar to"],["8773","approximately equal to"],["8776","almost equal to"],["8800","not equal to"],["8801","identical to"],["8712","element of"],["8713","not an element of"],["8715","contains as member"],["8719","n-ary product"],["8743","logical and"],["8744","logical or"],["172","not sign"],["8745","intersection"],["8746","union"],["8706","partial differential"],["8704","for all"],["8707","there exists"],["8709","diameter"],["8711","backward difference"],["8727","asterisk operator"],["8733","proportional to"],["8736","angle"],["180","acute accent"],["184","cedilla"],["170","feminine ordinal indicator"],["186","masculine ordinal indicator"],["8224","dagger"],["8225","double dagger"],["192","A - grave"],["193","A - acute"],["194","A - circumflex"],["195","A - tilde"],["196","A - diaeresis"],["197","A - ring above"],["198","ligature AE"],["199","C - cedilla"],["200","E - grave"],["201","E - acute"],["202","E - circumflex"],["203","E - diaeresis"],["204","I - grave"],["205","I - acute"],["206","I - circumflex"],["207","I - diaeresis"],["208","ETH"],["209","N - tilde"],["210","O - grave"],["211","O - acute"],["212","O - circumflex"],["213","O - tilde"],["214","O - diaeresis"],["216","O - slash"],["338","ligature OE"],["352","S - caron"],["217","U - grave"],["218","U - acute"],["219","U - circumflex"],["220","U - diaeresis"],["221","Y - acute"],["376","Y - diaeresis"],["222","THORN"],["224","a - grave"],["225","a - acute"],["226","a - circumflex"],["227","a - tilde"],["228","a - diaeresis"],["229","a - ring above"],["230","ligature ae"],["231","c - cedilla"],["232","e - grave"],["233","e - acute"],["234","e - circumflex"],["235","e - diaeresis"],["236","i - grave"],["237","i - acute"],["238","i - circumflex"],["239","i - diaeresis"],["240","eth"],["241","n - tilde"],["242","o - grave"],["243","o - acute"],["244","o - circumflex"],["245","o - tilde"],["246","o - diaeresis"],["248","o slash"],["339","ligature oe"],["353","s - caron"],["249","u - grave"],["250","u - acute"],["251","u - circumflex"],["252","u - diaeresis"],["253","y - acute"],["254","thorn"],["255","y - diaeresis"],["913","Alpha"],["914","Beta"],["915","Gamma"],["916","Delta"],["917","Epsilon"],["918","Zeta"],["919","Eta"],["920","Theta"],["921","Iota"],["922","Kappa"],["923","Lambda"],["924","Mu"],["925","Nu"],["926","Xi"],["927","Omicron"],["928","Pi"],["929","Rho"],["931","Sigma"],["932","Tau"],["933","Upsilon"],["934","Phi"],["935","Chi"],["936","Psi"],["937","Omega"],["945","alpha"],["946","beta"],["947","gamma"],["948","delta"],["949","epsilon"],["950","zeta"],["951","eta"],["952","theta"],["953","iota"],["954","kappa"],["955","lambda"],["956","mu"],["957","nu"],["958","xi"],["959","omicron"],["960","pi"],["961","rho"],["962","final sigma"],["963","sigma"],["964","tau"],["965","upsilon"],["966","phi"],["967","chi"],["968","psi"],["969","omega"],["8501","alef symbol"],["982","pi symbol"],["8476","real part symbol"],["978","upsilon - hook symbol"],["8472","Weierstrass p"],["8465","imaginary part"],["8592","leftwards arrow"],["8593","upwards arrow"],["8594","rightwards arrow"],["8595","downwards arrow"],["8596","left right arrow"],["8629","carriage return"],["8656","leftwards double arrow"],["8657","upwards double arrow"],["8658","rightwards double arrow"],["8659","downwards double arrow"],["8660","left right double arrow"],["8756","therefore"],["8834","subset of"],["8835","superset of"],["8836","not a subset of"],["8838","subset of or equal to"],["8839","superset of or equal to"],["8853","circled plus"],["8855","circled times"],["8869","perpendicular"],["8901","dot operator"],["8968","left ceiling"],["8969","right ceiling"],["8970","left floor"],["8971","right floor"],["9001","left-pointing angle bracket"],["9002","right-pointing angle bracket"],["9674","lozenge"],["9824","black spade suit"],["9827","black club suit"],["9829","black heart suit"],["9830","black diamond suit"],["8194","en space"],["8195","em space"],["8201","thin space"],["8204","zero width non-joiner"],["8205","zero width joiner"],["8206","left-to-right mark"],["8207","right-to-left mark"],["173","soft hyphen"]];e.addButton("charmap",{icon:"charmap",tooltip:"Special character",onclick:a}),e.addMenuItem("charmap",{icon:"charmap",text:"Special character",onclick:a,context:"insert"})});
-;tinymce.PluginManager.add("code",function(e){function o(){e.windowManager.open({title:"Source code",body:{type:"textbox",name:"code",multiline:!0,minWidth:e.getParam("code_dialog_width",600),minHeight:e.getParam("code_dialog_height",Math.min(tinymce.DOM.getViewPort().h-200,500)),value:e.getContent({source_view:!0}),spellcheck:!1,style:"direction: ltr; text-align: left"},onSubmit:function(o){e.focus(),e.undoManager.transact(function(){e.setContent(o.data.code)}),e.selection.setCursorLocation(),e.nodeChanged()}})}e.addCommand("mceCodeEditor",o),e.addButton("code",{icon:"code",tooltip:"Source code",onclick:o}),e.addMenuItem("code",{icon:"code",text:"Source code",context:"tools",onclick:o})});
-;tinymce.PluginManager.requireLangPack("codemirror"),tinymce.PluginManager.add("codemirror",function(e,t){function n(){e.focus(),e.selection.collapse(!0),e.selection.setContent('');var n,o=tinyMCE.baseURL.indexOf("/static/");n=o>0?tinyMCE.baseURL.substring(0,o):window.location.origin;var i="?CodeMirrorPath="+e.settings.codemirror.path+"&ParentOrigin="+window.location.origin,a=e.windowManager.open({title:"HTML source code",url:t+"/source.html"+i,width:800,height:550,resizable:!0,maximizable:!0,buttons:[{text:"OK",subtype:"primary",onclick:function(){s({type:"save"})}},{text:"Cancel",onclick:function(){s({type:"cancel"})}}]}),c=a.getEl().getElementsByTagName("iframe")[0].contentWindow,s=function(e){c.postMessage(e,n)},r=function(t){if(n===t.origin){var o;if("init"===t.data.type)o={content:e.getContent({source_view:!0})},e.fire("ShowCodeEditor",o),s({type:"init",content:o.content}),e.dom.remove(e.dom.select(".CmCaReT"));else if("setText"===t.data.type){o={content:t.data.text};var i=t.data.isDirty;e.fire("SaveCodeEditor",o),e.setContent(o.content);var c=e.dom.select("span#CmCaReT")[0];if(c)e.selection.scrollIntoView(c),e.selection.setCursorLocation(c,0),e.dom.remove(c);else{var r=e.getContent(),d=r.replace('',"");r!==d&&e.setContent(d)}e.isNotDirty=!i,i&&e.nodeChanged()}else"closeWindow"===t.data.type&&a.close()}};a.on("close",function(){window.removeEventListener("message",r)}),window.addEventListener("message",r,!1)}e.addButton("code",{title:"Edit HTML",text:"HTML",icon:!1,onclick:n}),e.addMenuItem("code",{icon:"code",text:"Edit HTML",context:"tools",onclick:n})});
-;tinymce.PluginManager.add("contextmenu",function(e){var n,t=e.settings.contextmenu_never_use_native;e.on("contextmenu",function(i){var o;if(!i.ctrlKey||t){if(i.preventDefault(),o=e.settings.contextmenu||"link image inserttable | cell row column deletetable",n)n.show();else{var c=[];tinymce.each(o.split(/[ ,]/),function(n){var t=e.menuItems[n];"|"==n&&(t={text:n}),t&&(t.shortcut="",c.push(t))});for(var a=0;a",r=0;r "}i+="
"]]):(e=n.filter(e,[[/\n\n/g,"
)$/,o+"$1"],[/\n/g,"
"]]),-1!=e.indexOf("
")&&(e=o+e)),r(e)}function o(){var t=i.dom,n=i.getBody(),r=i.dom.getViewPort(i.getWin()),a=r.y,o=20,s;if(h=i.selection.getRng(),i.inline&&(s=i.selection.getScrollContainer(),s&&(a=s.scrollTop)),h.getClientRects){var c=h.getClientRects();if(c.length)o=a+(c[0].top-t.getPos(n).y);else{o=a;var l=h.startContainer;l&&(3==l.nodeType&&l.parentNode!=n&&(l=l.parentNode),1==l.nodeType&&(o=t.getPos(l,s||n).y))}}v=t.add(i.getBody(),"div",{id:"mcepastebin",contentEditable:!0,"data-mce-bogus":"1",style:"position: absolute; top: "+o+"px;width: 10px; height: 10px; overflow: hidden; opacity: 0"},b),(e.ie||e.gecko)&&t.setStyle(v,"left","rtl"==t.getStyle(n,"direction",!0)?65535:-65535),t.bind(v,"beforedeactivate focusin focusout",function(e){e.stopPropagation()}),v.focus(),i.selection.select(v,!0)}function s(){if(v){for(var e;e=i.dom.get("mcepastebin");)i.dom.remove(e),i.dom.unbind(e);h&&i.selection.setRng(h)}x=!1,v=h=null}function c(){var e=b,t,n;for(t=i.dom.select("div[id=mcepastebin]"),n=t.length;n--;){var r=t[n].innerHTML;e==b&&(e=""),r.length>e.length&&(e=r)}return e}function l(e){var t={};if(e&&e.types){var n=e.getData("Text");n&&n.length>0&&(t["text/plain"]=n);for(var i=0;i \xa0 /gi,""),o(/<\/p>/gi,"\n"),o(/ |\u00a0/gi," "),o(/"/gi,'"'),o(/</gi,"<"),o(/>/gi,">"),o(/&/gi,"&"),t}(o.content))})})}();/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var e,n,r,t,a=tinymce.util.Tools.resolve("tinymce.PluginManager"),s=function(e,n){var r,t=(r=n,e.fire("insertCustomChar",{chr:r}).chr);e.execCommand("mceInsertContent",!1,t)},i=function(e){return function(){return e}},o=i(!1),c=i(!0),u=function(){return l},l=(e=function(e){return e.isNone()},{fold:function(e,n){return e()},is:o,isSome:o,isNone:c,getOr:r=function(e){return e},getOrThunk:n=function(e){return e()},getOrDie:function(e){throw new Error(e||"error: getOrDie called on none.")},getOrNull:i(null),getOrUndefined:i(undefined),or:r,orThunk:n,map:u,each:function(){},bind:u,exists:o,forall:c,filter:u,equals:e,equals_:e,toArray:function(){return[]},toString:i("none()")}),g=function(r){var e=i(r),n=function(){return a},t=function(e){return e(r)},a={fold:function(e,n){return n(r)},is:function(e){return r===e},isSome:c,isNone:o,getOr:e,getOrThunk:e,getOrDie:e,getOrNull:e,getOrUndefined:e,or:n,orThunk:n,map:function(e){return g(e(r))},each:function(e){e(r)},bind:t,exists:t,forall:t,filter:function(e){return e(r)?a:l},toArray:function(){return[r]},toString:function(){return"some("+r+")"},equals:function(e){return e.is(r)},equals_:function(e,n){return e.fold(o,function(e){return n(r,e)})}};return a},m={some:g,none:u,from:function(e){return null===e||e===undefined?l:g(e)}},f=(t="array",function(e){return r=typeof(n=e),(null===n?"null":"object"==r&&(Array.prototype.isPrototypeOf(n)||n.constructor&&"Array"===n.constructor.name)?"array":"object"==r&&(String.prototype.isPrototypeOf(n)||n.constructor&&"String"===n.constructor.name)?"string":r)===t;var n,r}),h=Array.prototype.push,p=function(e,n){for(var r=e.length,t=new Array(r),a=0;a
$/i])}function s(e){if(!n.isWordContent(e))return e;var a=[];t.each(r.schema.getBlockElements(),function(e,t){a.push(t)});var o=new RegExp("(?:
[\\s\\r\\n]+|
)*(<\\/?("+a.join("|")+")[^>]*>)(?:
[\\s\\r\\n]+|
)*","g");return e=i.filter(e,[[o,"$1"]]),e=i.filter(e,[[/
/g,"
"],[/
/g," "],[/
/g,"
"]])}function c(e){return(r.settings.paste_remove_styles||r.settings.paste_remove_styles_if_webkit!==!1)&&(e=e.replace(/ style=\"[^\"]+\"/g,"")),e}e.webkit&&(a(c),a(o)),e.ie&&a(s)}}),i(b,[x,d,g,y],function(e,t,n,i){var r;e.add("paste",function(e){function a(){"text"==s.pasteFormat?(this.active(!1),s.pasteFormat="html"):(s.pasteFormat="text",this.active(!0),r||(e.windowManager.alert("Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off."),r=!0))}var o=this,s,c=e.settings;o.clipboard=s=new t(e),o.quirks=new i(e),o.wordFilter=new n(e),e.settings.paste_as_text&&(o.clipboard.pasteFormat="text"),c.paste_preprocess&&e.on("PastePreProcess",function(e){c.paste_preprocess.call(o,o,e)}),c.paste_postprocess&&e.on("PastePostProcess",function(e){c.paste_postprocess.call(o,o,e)}),e.addCommand("mceInsertClipboardContent",function(e,t){t.content&&o.clipboard.pasteHtml(t.content),t.text&&o.clipboard.pasteText(t.text)}),e.paste_block_drop&&e.on("dragend dragover draggesture dragdrop drop drag",function(e){e.preventDefault(),e.stopPropagation()}),e.settings.paste_data_images||e.on("drop",function(e){var t=e.dataTransfer;t&&t.files&&t.files.length>0&&e.preventDefault()}),e.addButton("pastetext",{icon:"pastetext",tooltip:"Paste as text",onclick:a,active:"text"==o.clipboard.pasteFormat}),e.addMenuItem("pastetext",{text:"Paste as text",selectable:!0,active:s.pasteFormat,onclick:a})})}),o([c,d,g,y,b])}(this);
-;tinymce.PluginManager.add("print",function(t){t.addCommand("mcePrint",function(){t.getWin().print()}),t.addButton("print",{title:"Print",cmd:"mcePrint"}),t.addShortcut("Ctrl+P","","mcePrint"),t.addMenuItem("print",{text:"Print",cmd:"mcePrint",icon:"print",shortcut:"Ctrl+P",context:"file"})});
-;tinymce.PluginManager.add("save",function(e){function a(){var a;if(a=tinymce.DOM.getParent(e.id,"form"),!e.getParam("save_enablewhendirty",!0)||e.isDirty())return tinymce.triggerSave(),e.getParam("save_onsavecallback")?void(e.execCallback("save_onsavecallback",e)&&(e.startContent=tinymce.trim(e.getContent({format:"raw"})),e.nodeChanged())):void(a?(e.isNotDirty=!0,a.onsubmit&&!a.onsubmit()||("function"==typeof a.submit?a.submit():e.windowManager.alert("Error: Form submit field collision.")),e.nodeChanged()):e.windowManager.alert("Error: No form element found."))}function n(){var a=tinymce.trim(e.startContent);return e.getParam("save_oncancelcallback")?void e.execCallback("save_oncancelcallback",e):(e.setContent(a),e.undoManager.clear(),void e.nodeChanged())}function t(){var a=this;e.on("nodeChange",function(){a.disabled(e.getParam("save_enablewhendirty",!0)&&!e.isDirty())})}e.addCommand("mceSave",a),e.addCommand("mceCancel",n),e.addButton("save",{icon:"save",text:"Save",cmd:"mceSave",disabled:!0,onPostRender:t}),e.addButton("cancel",{text:"Cancel",icon:!1,cmd:"mceCancel",disabled:!0,onPostRender:t}),e.addShortcut("ctrl+s","","mceSave")});
-;!function(){function e(e,t,n,a,r){function i(e,t){if(t=t||0,!e[0])throw"findAndReplaceDOMText cannot handle zero-length matches";var n=e.index;if(t>0){var a=e[t];if(!a)throw"Invalid capture group";n+=e[0].indexOf(a),e[0]=a}return[n,n+e[0].length,[e[0]]]}function d(e){var t;if(3===e.nodeType)return e.data;if(h[e.nodeName]&&!u[e.nodeName])return"";if(t="",(u[e.nodeName]||m[e.nodeName])&&(t+="\n"),e=e.firstChild)do t+=d(e);while(e=e.nextSibling);return t}function o(e,t,n){var a,r,i,d,o=[],l=0,c=e,s=t.shift(),f=0;e:for(;;){if((u[c.nodeName]||m[c.nodeName])&&l++,3===c.nodeType&&(!r&&c.length+l>=s[1]?(r=c,d=s[1]-l):a&&o.push(c),!a&&c.length+l>s[0]&&(a=c,i=s[0]-l),l+=c.length),a&&r){if(c=n({startNode:a,startNodeIndex:i,endNode:r,endNodeIndex:d,innerNodes:o,match:s[2],matchIndex:f}),l-=r.length-d,a=null,r=null,o=[],s=t.shift(),f++,!s)break}else{if((!h[c.nodeName]||u[c.nodeName])&&c.firstChild){c=c.firstChild;continue}if(c.nextSibling){c=c.nextSibling;continue}}for(;;){if(c.nextSibling){c=c.nextSibling;break}if(c.parentNode===e)break e;c=c.parentNode}}}function l(e){var t;if("function"!=typeof e){var n=e.nodeType?e:f.createElement(e);t=function(e,t){var a=n.cloneNode(!1);return a.setAttribute("data-mce-index",t),e&&a.appendChild(f.createTextNode(e)),a}}else t=e;return function(e){var n,a,r,i=e.startNode,d=e.endNode,o=e.matchIndex;if(i===d){var l=i;r=l.parentNode,e.startNodeIndex>0&&(n=f.createTextNode(l.data.substring(0,e.startNodeIndex)),r.insertBefore(n,l));var c=t(e.match[0],o);return r.insertBefore(c,l),e.endNodeIndex
'),!1):void 0},"childNodes"),t=s(t,!1),d(t,"rowSpan",1),d(t,"colSpan",1),o?t.appendChild(o):n.ie||(t.innerHTML='
'),t}function g(){var e=I.createRng(),t;return i(I.select("tr",a),function(e){0===e.cells.length&&I.remove(e)}),0===I.select("tr",a).length?(e.setStartBefore(a),e.setEndBefore(a),E.setRng(e),void I.remove(a)):(i(I.select("thead,tbody,tfoot",a),function(e){0===e.rows.length&&I.remove(e)}),l(),void(B&&(t=A[Math.min(A.length-1,B.y)],t&&(E.select(t[Math.min(t.length-1,B.x)].elm,!0),E.collapse(!0)))))}function h(e,t,n,o){var i,r,a,l,s;for(i=A[t][e].elm.parentNode,a=1;n>=a;a++)if(i=I.getNext(i,"tr")){for(r=e;r>=0;r--)if(s=A[t+a][r].elm,s.parentNode==i){for(l=1;o>=l;l++)I.insertAfter(p(s),s);break}if(-1==r)for(l=1;o>=l;l++)i.insertBefore(p(i.cells[0]),i.cells[0])}}function v(){i(A,function(e,t){i(e,function(e,n){var i,r,a;if(u(e)&&(e=e.elm,i=o(e,"colspan"),r=o(e,"rowspan"),i>1||r>1)){for(d(e,"rowSpan",1),d(e,"colSpan",1),a=0;i-1>a;a++)I.insertAfter(p(e),e);h(n,t,r-1,i)}})})}function b(t,n,o){var r,a,s,f,m,p,h,b,y,w,x;if(t?(r=S(t),a=r.x,s=r.y,f=a+(n-1),m=s+(o-1)):(B=_=null,i(A,function(e,t){i(e,function(e,n){u(e)&&(B||(B={x:n,y:t}),_={x:n,y:t})})}),B&&(a=B.x,s=B.y,f=_.x,m=_.y)),b=c(a,s),y=c(f,m),b&&y&&b.part==y.part){for(v(),l(),b=c(a,s).elm,d(b,"colSpan",f-a+1),d(b,"rowSpan",m-s+1),h=s;m>=h;h++)for(p=a;f>=p;p++)A[h]&&A[h][p]&&(t=A[h][p].elm,t!=b&&(w=e.grep(t.childNodes),i(w,function(e){b.appendChild(e)}),w.length&&(w=e.grep(b.childNodes),x=0,i(w,function(e){"BR"==e.nodeName&&I.getAttrib(e,"data-mce-bogus")&&x++
'):n.dom.add(n.getBody(),"br",{"data-mce-bogus":"1"}))}),n.on("PreProcess",function(e){var t=e.node.lastChild;t&&("BR"==t.nodeName||1==t.childNodes.length&&("BR"==t.firstChild.nodeName||"\xa0"==t.firstChild.nodeValue))&&t.previousSibling&&"TABLE"==t.previousSibling.nodeName&&n.dom.remove(t)})}function s(){function e(e,t,n,o){var i=3,r=e.dom.getParent(t.startContainer,"TABLE"),a,l,s;return r&&(a=r.parentNode),l=t.startContainer.nodeType==i&&0===t.startOffset&&0===t.endOffset&&o&&("TR"==n.nodeName||n==a),s=("TD"==n.nodeName||"TH"==n.nodeName)&&!o,l||s}function t(){var t=n.selection.getRng(),o=n.selection.getNode(),i=n.dom.getParent(t.startContainer,"TD,TH");if(e(n,t,o,i)){i||(i=o);for(var r=i.lastChild;r.lastChild;)r=r.lastChild;t.setEnd(r,r.nodeValue.length),n.selection.setRng(t)}}n.on("KeyDown",function(){t()}),n.on("MouseDown",function(e){2!=e.button&&t()})}function c(){n.on("keydown",function(t){if((t.keyCode==e.DELETE||t.keyCode==e.BACKSPACE)&&!t.isDefaultPrevented()){var o=n.dom.getParent(n.selection.getStart(),"table");if(o){for(var i=n.dom.select("td,th",o),r=i.length;r--;)if(!n.dom.hasClass(i[r],"mce-item-selected"))return;t.preventDefault(),n.execCommand("mceTableDelete")}}})}c(),t.webkit&&(r(),s()),t.gecko&&(a(),l()),t.ie>10&&(a(),l())}}),o(m,[s,p,c],function(e,t,n){return function(o){function i(){o.getBody().style.webkitUserSelect="",d&&(o.dom.removeClass(o.dom.select("td.mce-item-selected,th.mce-item-selected"),"mce-item-selected"),d=!1)}function r(t){var n,i,r=t.target;if(s&&(l||r!=s)&&("TD"==r.nodeName||"TH"==r.nodeName)){i=a.getParent(r,"table"),i==c&&(l||(l=new e(o,i),l.setStartCell(s),o.getBody().style.webkitUserSelect="none"),l.setEndCell(r),d=!0),n=o.selection.getSel();try{n.removeAllRanges?n.removeAllRanges():n.empty()}catch(u){}t.preventDefault()}}var a=o.dom,l,s,c,d=!0;return o.on("MouseDown",function(e){2!=e.button&&(i(),s=a.getParent(e.target,"td,th"),c=a.getParent(s,"table"))}),o.on("mouseover",r),o.on("remove",function(){a.unbind(o.getDoc(),"mouseover",r)}),o.on("MouseUp",function(){function e(e,o){var r=new t(e,e);do{if(3==e.nodeType&&0!==n.trim(e.nodeValue).length)return void(o?i.setStart(e,0):i.setEnd(e,e.nodeValue.length));if("BR"==e.nodeName)return void(o?i.setStartBefore(e):i.setEndBefore(e))}while(e=o?r.next():r.prev())}var i,r=o.selection,d,u,f,m,p;if(s){if(l&&(o.getBody().style.webkitUserSelect=""),d=a.select("td.mce-item-selected,th.mce-item-selected"),d.length>0){i=a.createRng(),f=d[0],p=d[d.length-1],i.setStartBefore(f),i.setEndAfter(f),e(f,1),u=new t(f,a.getParent(d[0],"table"));do if("TD"==f.nodeName||"TH"==f.nodeName){if(!a.hasClass(f,"mce-item-selected"))break;m=f}while(f=u.next());e(m),r.setRng(i)}o.nodeChanged(),s=l=c=null}}),o.on("KeyUp",function(){i()}),{clear:i}}}),o(g,[s,u,m,c,p,d,h],function(e,t,n,o,i,r,a){function l(o){function i(e){return e?e.replace(/px$/,""):""}function a(e){return/^[0-9]+$/.test(e)&&(e+="px"),e}function l(e){s("left center right".split(" "),function(t){o.formatter.remove("align"+t,{},e)})}function c(){var e=o.dom,t,n;t=e.getParent(o.selection.getStart(),"table"),n={width:i(e.getStyle(t,"width")||e.getAttrib(t,"width")),height:i(e.getStyle(t,"height")||e.getAttrib(t,"height")),cellspacing:e.getAttrib(t,"cellspacing"),cellpadding:e.getAttrib(t,"cellpadding"),border:e.getAttrib(t,"border"),caption:!!e.select("caption",t)[0]},s("left center right".split(" "),function(e){o.formatter.matchNode(t,"align"+e)&&(n.align=e)}),o.windowManager.open({title:"Table properties",items:{type:"form",layout:"grid",columns:2,data:n,defaults:{type:"textbox",maxWidth:50},items:[{label:"Width",name:"width"},{label:"Height",name:"height"},{label:"Cell spacing",name:"cellspacing"},{label:"Cell padding",name:"cellpadding"},{label:"Border",name:"border"},{label:"Caption",name:"caption",type:"checkbox"},{label:"Alignment",minWidth:90,name:"align",type:"listbox",text:"None",maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]}]},onsubmit:function(){var n=this.toJSON(),i;o.undoManager.transact(function(){o.dom.setAttribs(t,{cellspacing:n.cellspacing,cellpadding:n.cellpadding,border:n.border}),o.dom.setStyles(t,{width:a(n.width),height:a(n.height)}),i=e.select("caption",t)[0],i&&!n.caption&&e.remove(i),!i&&n.caption&&(i=e.create("caption"),i.innerHTML=r.ie?"\xa0":'
',t.insertBefore(i,t.firstChild)),l(t),n.align&&o.formatter.apply("align"+n.align,{},t),o.focus(),o.addVisual()})}})}function d(e,t){o.windowManager.open({title:"Merge cells",body:[{label:"Cols",name:"cols",type:"textbox",size:10},{label:"Rows",name:"rows",type:"textbox",size:10}],onsubmit:function(){var n=this.toJSON();o.undoManager.transact(function(){e.merge(t,n.cols,n.rows)})}})}function u(){var e=o.dom,t,n,r=[];r=o.dom.select("td.mce-item-selected,th.mce-item-selected"),t=o.dom.getParent(o.selection.getStart(),"td,th"),!r.length&&t&&r.push(t),t=t||r[0],t&&(n={width:i(e.getStyle(t,"width")||e.getAttrib(t,"width")),height:i(e.getStyle(t,"height")||e.getAttrib(t,"height")),scope:e.getAttrib(t,"scope")},n.type=t.nodeName.toLowerCase(),s("left center right".split(" "),function(e){o.formatter.matchNode(t,"align"+e)&&(n.align=e)}),o.windowManager.open({title:"Cell properties",items:{type:"form",data:n,layout:"grid",columns:2,defaults:{type:"textbox",maxWidth:50},items:[{label:"Width",name:"width"},{label:"Height",name:"height"},{label:"Cell type",name:"type",type:"listbox",text:"None",minWidth:90,maxWidth:null,values:[{text:"Cell",value:"td"},{text:"Header cell",value:"th"}]},{label:"Scope",name:"scope",type:"listbox",text:"None",minWidth:90,maxWidth:null,values:[{text:"None",value:""},{text:"Row",value:"row"},{text:"Column",value:"col"},{text:"Row group",value:"rowgroup"},{text:"Column group",value:"colgroup"}]},{label:"Alignment",name:"align",type:"listbox",text:"None",minWidth:90,maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]}]},onsubmit:function(){var t=this.toJSON();o.undoManager.transact(function(){s(r,function(n){o.dom.setAttrib(n,"scope",t.scope),o.dom.setStyles(n,{width:a(t.width),height:a(t.height)}),t.type&&n.nodeName.toLowerCase()!=t.type&&(n=e.rename(n,t.type)),l(n),t.align&&o.formatter.apply("align"+t.align,{},n)}),o.focus()})}}))}function f(){var e=o.dom,t,n,r,c,d=[];t=o.dom.getParent(o.selection.getStart(),"table"),n=o.dom.getParent(o.selection.getStart(),"td,th"),s(t.rows,function(t){s(t.cells,function(o){return e.hasClass(o,"mce-item-selected")||o==n?(d.push(t),!1):void 0})}),r=d[0],r&&(c={height:i(e.getStyle(r,"height")||e.getAttrib(r,"height")),scope:e.getAttrib(r,"scope")},c.type=r.parentNode.nodeName.toLowerCase(),s("left center right".split(" "),function(e){o.formatter.matchNode(r,"align"+e)&&(c.align=e)}),o.windowManager.open({title:"Row properties",items:{type:"form",data:c,columns:2,defaults:{type:"textbox"},items:[{type:"listbox",name:"type",label:"Row type",text:"None",maxWidth:null,values:[{text:"Header",value:"thead"},{text:"Body",value:"tbody"},{text:"Footer",value:"tfoot"}]},{type:"listbox",name:"align",label:"Alignment",text:"None",maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]},{label:"Height",name:"height"}]},onsubmit:function(){var t=this.toJSON(),n,i,r;o.undoManager.transact(function(){var c=t.type;s(d,function(s){o.dom.setAttrib(s,"scope",t.scope),o.dom.setStyles(s,{height:a(t.height)}),c!=s.parentNode.nodeName.toLowerCase()&&(n=e.getParent(s,"table"),i=s.parentNode,r=e.select(c,n)[0],r||(r=e.create(c),n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r)),r.appendChild(s),i.hasChildNodes()||e.remove(i)),l(s),t.align&&o.formatter.apply("align"+t.align,{},s)}),o.focus()})}}))}function m(e){return function(){o.execCommand(e)}}function p(e,t){var n,i,a;for(a="",n=0;t>n;n++){for(a+="
",o.insertContent(a)}function g(e,t){function n(){e.disabled(!o.dom.getParent(o.selection.getStart(),t)),o.selection.selectorChanged(t,function(t){e.disabled(!t)})}o.initialized?n():o.on("init",n)}function h(){g(this,"table")}function v(){g(this,"td,th")}function b(){var e="";e='",i=0;e>i;i++)a+=" "}a+=""+(r.ie?" ":" ";a+="
")+"';for(var t=0;10>t;t++){e+="
",e+='";for(var n=0;10>n;n++)e+=' "}return e+="";e+=" ",n=0;i>n;n++)d=F*i+n,d>a?l+=" "}return l+=""}function r(t){var o,r=this.parent();(o=t.target.getAttribute("data-mce-color"))&&(this.lastId&&document.getElementById(this.lastId).setAttribute("aria-selected",!1),t.target.setAttribute("aria-selected",!0),this.lastId=t.target.id,r.hidePanel(),o="#"+o,r.color(o),e.execCommand(r.settings.selectcmd,!1,o))}function l(){var t=this;t._color&&e.execCommand(t.settings.selectcmd,!1,t._color)}e.addButton("forecolor",{type:"colorbutton",tooltip:"Text color",selectcmd:"ForeColor",panel:{role:"application",ariaRemember:!0,html:o,onclick:r},onclick:l}),e.addButton("backcolor",{type:"colorbutton",tooltip:"Background color",selectcmd:"HiliteColor",panel:{role:"application",ariaRemember:!0,html:o,onclick:r},onclick:l})});
-;tinymce.PluginManager.add("visualblocks",function(e,s){function o(){var s=this;s.active(a),e.on("VisualBlocks",function(){s.active(e.dom.hasClass(e.getBody(),"mce-visualblocks"))})}var l,t,a;window.NodeList&&(e.addCommand("mceVisualBlocks",function(){var o,c=e.dom;l||(l=c.uniqueId(),o=c.create("link",{id:l,rel:"stylesheet",href:s+"/css/visualblocks.css"}),e.getDoc().getElementsByTagName("head")[0].appendChild(o)),e.on("PreviewFormats AfterPreviewFormats",function(s){a&&c.toggleClass(e.getBody(),"mce-visualblocks","afterpreviewformats"==s.type)}),c.toggleClass(e.getBody(),"mce-visualblocks"),a=e.dom.hasClass(e.getBody(),"mce-visualblocks"),t&&t.active(c.hasClass(e.getBody(),"mce-visualblocks")),e.fire("VisualBlocks")}),e.addButton("visualblocks",{title:"Show blocks",cmd:"mceVisualBlocks",onPostRender:o}),e.addMenuItem("visualblocks",{text:"Show blocks",cmd:"mceVisualBlocks",onPostRender:o,selectable:!0,context:"view",prependToContext:!0}),e.on("init",function(){e.settings.visualblocks_default_state&&e.execCommand("mceVisualBlocks",!1,null,{skip_focus:!0})}),e.on("remove",function(){e.dom.removeClass(e.getBody(),"mce-visualblocks")}))});
\ No newline at end of file
+/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var r=function(e){if(null===e)return"null";if(e===undefined)return"undefined";var t=typeof e;return"object"==t&&(Array.prototype.isPrototypeOf(e)||e.constructor&&"Array"===e.constructor.name)?"array":"object"==t&&(String.prototype.isPrototypeOf(e)||e.constructor&&"String"===e.constructor.name)?"string":t},t=function(e){return{eq:e}},s=t(function(e,t){return e===t}),i=function(o){return t(function(e,t){if(e.length!==t.length)return!1;for(var n=e.length,r=0;r":(r=o[d],l+=' ');l+="
"+r).contents().slice(1).appendTo(t)}return r}}):t.html(r)},A=function(e,n,r,o,i){return _(e,function(e){var t="string"==typeof n?a.createElement(n):n;return R(t,r),o&&("string"!=typeof o&&o.nodeType?t.appendChild(o):"string"==typeof o&&T(t,o)),i?t:e.appendChild(t)})},D=function(e,t,n){return A(a.createElement(e),e,t,n,!0)},e=ri.decode,O=ri.encodeAllRaw,B=function(e,t){var n=h(e);return t?n.each(function(){for(var e;e=this.firstChild;)3===e.nodeType&&0===e.data.length?this.removeChild(e):this.parentNode.insertBefore(e,this)}).remove():n.remove(),1
|)<\\/"+u+">[\r\n]*|
[\r\n]*)$"),o=a.replace(s,"")}return"text"===t.format||no(Nt.fromDom(r))?t.content=o:t.content=xt.trim(o),t.no_events||e.fire("GetContent",t),t.content},Um=xt.each,zm=function(o){this.compare=function(e,t){if(e.nodeName!==t.nodeName)return!1;var n=function(n){var r={};return Um(o.getAttribs(n),function(e){var t=e.nodeName.toLowerCase();0!==t.indexOf("_")&&"style"!==t&&0!==t.indexOf("data-")&&(r[t]=o.getAttrib(n,t))}),r},r=function(e,t){var n,r;for(r in e)if(e.hasOwnProperty(r)){if(void 0===(n=t[r]))return!1;if(e[r]!==n)return!1;delete t[r]}for(r in t)if(t.hasOwnProperty(r))return!1;return!0};return!!r(n(e),n(t))&&(!!r(o.parseStyle(o.getAttrib(e,"style")),o.parseStyle(o.getAttrib(t,"style")))&&(!$l(e)&&!$l(t)))}},jm=function(n,r,o){return U.from(o.container()).filter(On).exists(function(e){var t=n?0:-1;return r(e.data.charAt(o.offset()+t))})},Hm=E(jm,!0,Kl),Vm=E(jm,!1,Kl),qm=function(e){var t=e.container();return On(t)&&(0===t.data.length||ao(t.data)&&Kf.isBookmarkNode(t.parentNode))},$m=function(t,n){return function(e){return U.from(Zc(t?0:-1,e)).filter(n).isSome()}},Wm=function(e){return Mn(e)&&"block"===Yn(Nt.fromDom(e),"display")},Km=function(e){return Un(e)&&!(Nn(t=e)&&"all"===t.getAttribute("data-mce-bogus"));var t},Xm=$m(!0,Wm),Ym=$m(!1,Wm),Gm=$m(!0,jn),Jm=$m(!1,jn),Qm=$m(!0,Tn),Zm=$m(!1,Tn),ep=$m(!0,Km),tp=$m(!1,Km),np=function(e){var t=qu(e,"br"),n=j(function(e){for(var t=[],n=e.dom;n;)t.push(Nt.fromDom(n)),n=n.lastChild;return t}(e).slice(-1),Gr);t.length===n.length&&$(n,ln)},rp=function(e){cn(e),un(e,Nt.fromHtml('
'))},op=function(n){Yt(n).each(function(t){Ht(t).each(function(e){Xr(n)&&Gr(t)&&Xr(e)&&ln(t)})})},ip=function(e,t,n){return At(t,e)?function(e,t){for(var n=A(t)?t:p,r=e.dom,o=[];null!==r.parentNode&&r.parentNode!==undefined;){var i=r.parentNode,a=Nt.fromDom(i);if(o.push(a),!0===n(a))break;r=i}return o}(e,function(e){return n(e)||Rt(e,t)}).slice(0,-1):[]},ap=function(e,t){return ip(e,t,p)},up=function(e,t){return[e].concat(ap(e,t))},sp=function(e,t,n){return Rl(e,t,n,qm)},cp=function(e,t){return K(up(Nt.fromDom(t.container()),e),Xr)},lp=function(e,n,r){return sp(e,n.dom,r).forall(function(t){return cp(n,r).fold(function(){return!1===Qc(t,r,n.dom)},function(e){return!1===Qc(t,r,n.dom)&&At(e,Nt.fromDom(t.container()))})})},fp=function(t,n,r){return cp(n,r).fold(function(){return sp(t,n.dom,r).forall(function(e){return!1===Qc(e,r,n.dom)})},function(e){return sp(t,e.dom,r).isNone()})},dp=E(fp,!1),mp=E(fp,!0),pp=E(lp,!1),gp=E(lp,!0),hp=function(e){return ul(e).exists(Gr)},vp=function(e,t,n){var r=j(up(Nt.fromDom(n.container()),t),Xr),o=Z(r).getOr(t);return kl(e,o.dom,n).filter(hp)},yp=function(e,t){return ul(t).exists(Gr)||vp(!0,e,t).isSome()},bp=function(e,t){return n=t,U.from(n.getNode(!0)).map(Nt.fromDom).exists(Gr)||vp(!1,e,t).isSome();var n},Cp=E(vp,!1),wp=E(vp,!0),xp=function(e){return Is.isTextPosition(e)&&!e.isAtStart()&&!e.isAtEnd()},Sp=function(e,t){var n=j(up(Nt.fromDom(t.container()),e),Xr);return Z(n).getOr(e)},Np=function(e,t){return xp(t)?Vm(t):Vm(t)||Dl(Sp(e,t).dom,t).exists(Vm)},Ep=function(e,t){return xp(t)?Hm(t):Hm(t)||Al(Sp(e,t).dom,t).exists(Hm)},kp=function(e){return ul(e).bind(function(e){return Sr(e,Pt)}).exists(function(e){return t=Yn(e,"white-space"),I(["pre","pre-wrap"],t);var t})},_p=function(e,t){return r=t,Dl(e.dom,r).isNone()||(n=t,Al(e.dom,n).isNone())||dp(e,t)||mp(e,t)||bp(e,t)||yp(e,t);var n,r},Rp=function(e,t){return!kp(t)&&(dp(e,t)||pp(e,t)||bp(e,t)||Np(e,t))},Tp=function(e,t){return!kp(t)&&(mp(e,t)||gp(e,t)||yp(e,t)||Ep(e,t))},Ap=function(e,t){return Rp(e,t)||Tp(e,(r=(n=t).container(),o=n.offset(),On(r)&&o
');return cn(e),un(e,t),U.some(Us.before(t.dom))}return U.none()},Yp=function(e,t,a){var n,r,o,i,u=Ht(e).filter(Lt),s=Vt(e).filter(Lt);return ln(e),r=s,o=t,i=function(e,t,n){var r=e.dom,o=t.dom,i=r.data.length;return Up(r,o,a),n.container()===o?Us(r,i):n},((n=u).isSome()&&r.isSome()&&o.isSome()?U.some(i(n.getOrDie(),r.getOrDie(),o.getOrDie())):U.none()).orThunk(function(){return a&&(u.each(function(e){return Fp(e.dom,e.dom.length)}),s.each(function(e){return Mp(e.dom,0)})),t})},Gp=function(t,n,e,r){void 0===r&&(r=!0);var o,i,a=$p(n,t.getBody(),e.dom),u=xr(e,E(Kp,t),(o=t.getBody(),function(e){return e.dom===o})),s=Yp(e,a,(i=e,me(t.schema.getTextInlineElements(),Dt(i))));t.dom.isEmpty(t.getBody())?(t.setContent(""),t.selection.setCursorLocation()):u.bind(Xp).fold(function(){r&&Wp(t,n,s)},function(e){r&&Wp(t,n,U.some(e))})},Jp=function(e,t){return{start:e,end:t}},Qp=gr([{removeTable:["element"]},{emptyCells:["cells"]},{deleteCellSelection:["rng","cell"]}]),Zp=function(e,t){return kr(Nt.fromDom(e),"td,th",t)},eg=function(e,t){return Nr(e,"table",t)},tg=function(e){return!Rt(e.start,e.end)},ng=function(e,t){return eg(e.start,t).bind(function(r){return eg(e.end,t).bind(function(e){return t=Rt(r,e),n=r,t?U.some(n):U.none();var t,n})})},rg=function(e){return qu(e,"td,th")},og=function(r,e){var t=Zp(e.startContainer,r),n=Zp(e.endContainer,r);return e.collapsed?U.none():as(t,n,Jp).fold(function(){return t.fold(function(){return n.bind(function(t){return eg(t,r).bind(function(e){return Z(rg(e)).map(function(e){return Jp(e,t)})})})},function(t){return eg(t,r).bind(function(e){return ee(rg(e)).map(function(e){return Jp(t,e)})})})},function(e){return ig(r,e)?U.none():(n=r,eg((t=e).start,n).bind(function(e){return ee(rg(e)).map(function(e){return Jp(t.start,e)})}));var t,n})},ig=function(e,t){return ng(t,e).isSome()},ag=function(e,t,n){return e.filter(function(e){return tg(e)&&ig(n,e)}).orThunk(function(){return og(n,t)}).bind(function(e){return ng(t=e,n).map(function(e){return{rng:t,table:e,cells:rg(e)}});var t})},ug=function(e,t){return X(e,function(e){return Rt(e,t)})},sg=function(e,r,o){return e.filter(function(e){return n=o,!tg(t=e)&&ng(t,n).exists(function(e){var t=e.dom.rows;return 1===t.length&&1===t[0].cells.length})&&Af(e.start,r);var t,n}).map(function(e){return e.start})},cg=function(n){return as(ug((r=n).cells,r.rng.start),ug(r.cells,r.rng.end),function(e,t){return r.cells.slice(e,t+1)}).map(function(e){var t=n.cells;return e.length===t.length?Qp.removeTable(n.table):Qp.emptyCells(e)});var r},lg=function(e,t){var n,r,o,i,a,u=(n=e,function(e){return Rt(n,e)}),s=(o=u,i=Zp((r=t).startContainer,o),a=Zp(r.endContainer,o),as(i,a,Jp));return sg(s,t,u).map(function(e){return Qp.deleteCellSelection(t,e)}).orThunk(function(){return ag(s,t,u).bind(cg)})},fg=function(e){var t;return(8===Ot(t=e)||"#comment"===Dt(t)?Ht:Yt)(e).bind(fg).orThunk(function(){return U.some(e)})},dg=function(e,t){return $(t,rp),e.selection.setCursorLocation(t[0].dom,0),!0},mg=function(e,t,n){t.deleteContents();var r,o,i=fg(n).getOr(n),a=Nt.fromDom(e.dom.getParent(i.dom,e.dom.isBlock));return Uo(a)&&(rp(a),e.selection.setCursorLocation(a.dom,0)),Rt(n,a)||(r=jt(a).is(n)?[]:jt(o=a).map(Wt).map(function(e){return j(e,function(e){return!Rt(o,e)})}).getOr([]),$(r.concat(Wt(n)),function(e){Rt(e,a)||At(e,a)||ln(e)})),!0},pg=function(e,t){return Gp(e,!1,t),!0},gg=function(n,e,r,t){return vg(e,t).fold(function(){return t=n,lg(e,r).map(function(e){return e.fold(E(pg,t),E(dg,t),E(mg,t))});var t},function(e){return yg(n,e)}).getOr(!1)},hg=function(e,t){return K(up(t,e),to)},vg=function(e,t){return K(up(t,e),function(e){return"caption"===Dt(e)})},yg=function(e,t){return rp(t),e.selection.setCursorLocation(t.dom,0),U.some(!0)},bg=function(u,s,c,l,f){return _l(c,u.getBody(),f).bind(function(e){return o=c,i=f,a=e,Ol((r=l).dom).bind(function(t){return Bl(r.dom).map(function(e){return o?i.isEqual(t)&&a.isEqual(e):i.isEqual(e)&&a.isEqual(t)})}).getOr(!0)?yg(u,l):(t=l,n=e,vg(s,Nt.fromDom(n.getNode())).map(function(e){return!1===Rt(e,t)}));var t,n,r,o,i,a}).or(U.some(!0))},Cg=function(o,i,a,e){var u=Us.fromRangeStart(o.selection.getRng());return hg(a,e).bind(function(e){return Uo(e)?yg(o,e):(t=a,n=e,r=u,_l(i,o.getBody(),r).bind(function(e){return hg(t,Nt.fromDom(e.getNode())).map(function(e){return!1===Rt(e,n)})}));var t,n,r}).getOr(!1)},wg=function(e,t){return(e?Qm:Zm)(t)},xg=function(a,u,r){var s=Nt.fromDom(a.getBody());return vg(s,r).fold(function(){return Cg(a,u,s,r)||(e=a,t=u,n=Us.fromRangeStart(e.selection.getRng()),wg(t,n)||kl(t,e.getBody(),n).exists(function(e){return wg(t,e)}));var e,t,n},function(e){return t=a,n=u,r=s,o=e,i=Us.fromRangeStart(t.selection.getRng()),(Uo(o)?yg(t,o):bg(t,r,n,o,i)).getOr(!1);var t,n,r,o,i})},Sg=function(e,t){var n,r,o,i,a,u=Nt.fromDom(e.selection.getStart(!0)),s=_f(e);return e.selection.isCollapsed()&&0===s.length?xg(e,t,u):(n=e,r=u,o=Nt.fromDom(n.getBody()),i=n.selection.getRng(),0!==(a=_f(n)).length?dg(n,a):gg(n,o,i,r))},Ng=function(a){var u=Us.fromRangeStart(a),s=Us.fromRangeEnd(a),c=a.commonAncestorContainer;return kl(!1,c,s).map(function(e){return!Qc(u,s,c)&&Qc(u,e,c)?(t=u.container(),n=u.offset(),r=e.container(),o=e.offset(),(i=document.createRange()).setStart(t,n),i.setEnd(r,o),i):a;var t,n,r,o,i}).getOr(a)},Eg=function(e){return e.collapsed?e:Ng(e)},kg=function(e,t){var n,r;return e.getBlockElements()[t.name]&&((r=t).firstChild&&r.firstChild===r.lastChild)&&("br"===(n=t.firstChild).name||n.value===oo)},_g=function(e,t){var n,r,o,i=t.firstChild,a=t.lastChild;return i&&"meta"===i.name&&(i=i.next),a&&"mce_marker"===a.attr("id")&&(a=a.prev),r=a,o=(n=e).getNonEmptyElements(),r&&(r.isEmpty(o)||kg(n,r))&&(a=a.prev),!(!i||i!==a)&&("ul"===i.name||"ol"===i.name)},Rg=function(e){return e&&e.firstChild&&e.firstChild===e.lastChild&&((t=e.firstChild).data===oo||In(t));var t},Tg=function(e){return 0
)?$/," "));var p=e.parser,g=n.merge,h=Tm({validate:e.getParam("validate")},e.schema),v='',y={content:t,format:"html",selection:!0,paste:n.paste};if((y=e.fire("BeforeSetContent",y)).isDefaultPrevented())e.fire("SetContent",{content:y.content,format:"html",selection:!0,paste:n.paste});else{-1===(t=y.content).indexOf("{$caret}")&&(t+="{$caret}"),t=t.replace(/\{\$caret\}/,v);var b,C,w=(a=d.getRng()).startContainer||(a.parentElement?a.parentElement():null),x=e.getBody();w===x&&d.isCollapsed()&&m.isBlock(x.firstChild)&&(b=e,(C=x.firstChild)&&!b.schema.getShortEndedElements()[C.nodeName])&&m.isEmpty(x.firstChild)&&((a=m.createRng()).setStart(x.firstChild,0),a.setEnd(x.firstChild,0),d.setRng(a)),d.isCollapsed()||Lg(e);var S,N,E,k,_,R,T,A,D,O,B,P,L,I,M={context:(r=d.getNode()).nodeName.toLowerCase(),data:n.data,insert:!0},F=p.parse(t,M);if(!0===n.paste&&_g(e.schema,F)&&Ag(m,r))return a=Bg(h,m,d.getRng(),F),d.setRng(a),void e.fire("SetContent",y);if(!function(e){for(var t=e;t=t.walk();)1===t.type&&t.attr("data-mce-fragment","1")}(F),"mce_marker"===(u=F.lastChild).attr("id"))for(u=(i=u).prev;u;u=u.walk(!0))if(3===u.type||!m.isBlock(u.name)){e.schema.isValidChild(u.parent.name,"span")&&u.parent.insert(i,u,"br"===u.name);break}if(e._selectionOverrides.showBlockCaretContainer(r),M.invalid){for(e.selection.setContent(v),r=d.getNode(),o=e.getBody(),9===r.nodeType?r=u=o:u=r;u!==o;)u=(r=u).parentNode;t=r===o?o.innerHTML:m.getOuterHTML(r),t=h.serialize(p.parse(t.replace(//i,function(){return h.serialize(F)}))),r===o?m.setHTML(o,t):m.setOuterHTML(r,t)}else t=h.serialize(F),S=e,N=t,"all"===(E=r).getAttribute("data-mce-bogus")?E.parentNode.insertBefore(S.dom.createFragment(N),E):(k=E.firstChild,_=E.lastChild,!k||k===_&&"BR"===k.nodeName?S.dom.setHTML(E,N):S.selection.setContent(N));T=g,O=(R=e).schema.getTextInlineElements(),B=R.dom,T&&(A=R.getBody(),D=new zm(B),xt.each(B.select("*[data-mce-fragment]"),function(e){for(var t=e.parentNode;t&&t!==A;t=t.parentNode)O[e.nodeName.toLowerCase()]&&D.compare(t,e)&&B.remove(e,!0)})),function(n,e){var t,r,o=n.dom,i=n.selection;if(e){i.scrollIntoView(e);var a=function(e){for(var t=n.getBody();e&&e!==t;e=e.parentNode)if("false"===o.getContentEditable(e))return e;return null}(e);if(a)return o.remove(e),i.select(a);var u=o.createRng(),s=e.previousSibling;s&&3===s.nodeType?(u.setStart(s,s.nodeValue.length),vt.ie||(r=e.nextSibling)&&3===r.nodeType&&(s.appendData(r.data),r.parentNode.removeChild(r))):(u.setStartBefore(e),u.setEndBefore(e));var c=o.getParent(e,o.isBlock);o.remove(e),c&&o.isEmpty(c)&&(n.$(c).empty(),u.setStart(c,0),u.setEnd(c,0),Pg(c)||c.getAttribute("data-mce-fragment")||!(t=function(e){var t=Us.fromRangeStart(e);if(t=wl(n.getBody()).next(t))return t.toRange()}(u))?o.add(c,o.create("br",{"data-mce-bogus":"1"})):(u=t,o.remove(c))),i.setRng(u)}}(e,m.get("mce_marker")),P=e.getBody(),xt.each(P.getElementsByTagName("*"),function(e){e.removeAttribute("data-mce-fragment")}),L=m,I=d.getStart(),U.from(L.getParent(I,"td,th")).map(Nt.fromDom).each(op),e.fire("SetContent",y),e.addVisual()}},Mg=function(e,t){t(e),e.firstChild&&Mg(e.firstChild,t),e.next&&Mg(e.next,t)},Fg=function(e,t,n){var r=function(e,n,t){var r={},o={},i=[];for(var a in t.firstChild&&Mg(t.firstChild,function(t){$(e,function(e){e.name===t.name&&(r[e.name]?r[e.name].nodes.push(t):r[e.name]={filter:e,nodes:[t]})}),$(n,function(e){"string"==typeof t.attr(e.name)&&(o[e.name]?o[e.name].nodes.push(t):o[e.name]={filter:e,nodes:[t]})})}),r)r.hasOwnProperty(a)&&i.push(r[a]);for(var u in o)o.hasOwnProperty(u)&&i.push(o[u]);return i}(e,t,n);$(r,function(t){$(t.filter.callbacks,function(e){e(t.nodes,t.filter.name,{})})})},Ug=function(e){return e instanceof Em},zg=function(e,t){var r;e.dom.setHTML(e.getBody(),t),pm(r=e)&&Ol(r.getBody()).each(function(e){var t=e.getNode(),n=Tn(t)?Ol(t).getOr(e):e;r.selection.setRng(n.toRange())})},jg=function(u,s,c){return c.format=c.format?c.format:"html",c.set=!0,c.content=Ug(s)?"":s,Ug(s)||c.no_events||(u.fire("BeforeSetContent",c),s=c.content),U.from(u.getBody()).fold(N(s),function(e){return Ug(s)?function(e,t,n,r){Fg(e.parser.getNodeFilters(),e.parser.getAttributeFilters(),n);var o=Tm({validate:e.validate},e.schema).serialize(n);return r.content=no(Nt.fromDom(t))?o:xt.trim(o),zg(e,r.content),r.no_events||e.fire("SetContent",r),n}(u,e,s,c):(t=u,n=e,o=c,0===(r=s).length||/^\s+$/.test(r)?(a='
',"TABLE"===n.nodeName?r=" ":/^(UL|OL)$/.test(n.nodeName)&&(r=""+a+"
',zg(t,r),t.fire("SetContent",o)):("raw"!==o.format&&(r=Tm({validate:t.validate},t.schema).serialize(t.parser.parse(r,{isRootContent:!0,insert:!0}))),o.content=no(Nt.fromDom(n))?r:xt.trim(r),zg(t,o.content),o.no_events||t.fire("SetContent",o)),o.content);var t,n,r,o,i,a})},Hg=nf,Vg=function(e,t,n){var r=e.formatter.get(n);if(r)for(var o=0;o
").append(n.childNodes)}))},lh[Bm="pre"]||(lh[Bm]=[]),lh[Bm].push(Pm);var mh=xt.each,ph=function(e){return Nn(e)&&!$l(e)&&!Ll(e)&&!Rn(e)},gh=function(e,t){for(var n=e;n;n=n[t]){if(On(n)&&0!==n.nodeValue.length)return e;if(Nn(n)&&!$l(n))return n}return e},hh=function(e,t,n){var r,o,i=new zm(e);if(t&&n&&(t=gh(t,"previousSibling"),n=gh(n,"nextSibling"),i.compare(t,n))){for(r=t.nextSibling;r&&r!==n;)r=(o=r).nextSibling,t.appendChild(o);return e.remove(n),xt.each(xt.grep(n.childNodes),function(e){t.appendChild(e)}),t}return n},vh=function(e,t,n,r){var o;r&&!1!==t.merge_siblings&&(o=hh(e,Jl(r),r),hh(e,o,Jl(o,!0)))},yh=function(e,t,n){mh(e.childNodes,function(e){ph(e)&&(t(e)&&n(e),e.hasChildNodes()&&yh(e,t,n))})},bh=function(t,n){return function(e){return!(!e||!of(t,e,n))}},Ch=function(r,o,i){return function(e){var t,n;r.setStyle(e,o,i),""===e.getAttribute("style")&&e.removeAttribute("style"),t=r,"SPAN"===(n=e).nodeName&&0===t.getAttribs(n).length&&t.remove(n,!0)}},wh=gr([{keep:[]},{rename:["name"]},{removed:[]}]),xh=/^(src|href|style)$/,Sh=xt.each,Nh=nf,Eh=function(e,t,n){return e.isChildOf(t,n)&&t!==n&&!e.isBlock(n)},kh=function(e,t,n){var r,o=t[n?"startContainer":"endContainer"],i=t[n?"startOffset":"endOffset"];return Nn(o)&&(r=o.childNodes.length-1,!n&&i&&i--,o=o.childNodes[r=o.nodeValue.length&&(o=new Hr(o,e.getBody()).next()||o),On(o)&&!n&&0===i&&(o=new Hr(o,e.getBody()).prev()||o),o},_h=function(e,t){var n=t?"firstChild":"lastChild";if(/^(TR|TH|TD)$/.test(e.nodeName)&&e[n]){var r=e[n];return"TR"===e.nodeName&&r[n]||r}return e},Rh=function(e,t,n,r){var o=e.create(n,r);return t.parentNode.insertBefore(o,t),o.appendChild(t),o},Th=function(e,t,n,r,o){var i=Nt.fromDom(t),a=Nt.fromDom(e.create(r,o)),u=(n?$t:qt)(i);return sn(a,u),n?(rn(i,a),an(a,i)):(on(i,a),un(a,i)),a.dom},Ah=function(e,t,n,r){return!(t=Jl(t,n,r))||"BR"===t.nodeName||e.isBlock(t)},Dh=function(e,r,o,t,i){var n,a,u,s,c,l=e.dom;if(u=l,!(Nh(s=t,(c=r).inline)||Nh(s,c.block)||c.selector&&(Nn(s)&&u.is(s,c.selector))||(a=t,r.links&&"A"===a.nodeName)))return wh.keep();var f,d,m,p,g,h,v,y=t;if(r.inline&&"all"===r.remove&&S(r.preserve_attributes)){var b=j(l.getAttribs(y),function(e){return I(r.preserve_attributes,e.name.toLowerCase())});if(l.removeAllAttribs(y),$(b,function(e){return l.setAttrib(y,e.name,e.value)}),0
'},qx=function(e,t){return e.nodeName===t||e.previousSibling&&e.previousSibling.nodeName===t},$x=function(e,t){return t&&e.isBlock(t)&&!/^(TD|TH|CAPTION|FORM)$/.test(t.nodeName)&&!/^(fixed|absolute)/i.test(t.style.position)&&"true"!==e.getContentEditable(t)},Wx=function(e,t,n){return!1===On(t)?n:e?1===n&&t.data.charAt(n-1)===io?0:n:n===t.data.length-1&&t.data.charAt(n)===io?t.data.length:n},Kx=function(e,t){for(var n,r=e.getRoot(),o=t;o!==r&&"false"!==e.getContentEditable(o);)"true"===e.getContentEditable(o)&&(n=o),o=o.parentNode;return o!==r?n:r},Xx=function(e,t){var n=fc(e);n&&n.toLowerCase()===t.tagName.toLowerCase()&&function(e,o,t){var i=e.dom;U.from(t.style).map(i.parseStyle).each(function(e){var t=Qn(Nt.fromDom(o)),n=xe(xe({},t),e);i.setStyles(o,n)});var n=U.from(t["class"]).map(function(e){return e.split(/\s+/)}),r=U.from(o.className).map(function(e){return j(e.split(/\s+/),function(e){return""!==e})});as(n,r,function(t,e){var n=j(e,function(e){return!I(t,e)}),r=Se(t,n);i.setAttrib(o,"class",r.join(" "))});var a=["style","class"],u=le(t,function(e,t){return!I(a,t)});i.setAttribs(o,u)}(e,t,dc(e))},Yx=function(a,e){var t,u,i,s,n,r,o,c,l,f=a.dom,d=a.schema,m=d.getNonEmptyElements(),p=a.selection.getRng(),g=function(e){var t,n=u,r=d.getTextInlineElements(),o=e||"TABLE"===c||"HR"===c?f.create(e||N):s.cloneNode(!1),i=o;if(!1===a.getParam("keep_styles",!0))f.setAttrib(o,"style",null),f.setAttrib(o,"class",null);else do{if(r[n.nodeName]){if(Ll(n)||$l(n))continue;t=n.cloneNode(!1),f.setAttrib(t,"id",""),o.hasChildNodes()?t.appendChild(o.firstChild):i=t,o.appendChild(t)}}while((n=n.parentNode)&&n!==E);return Xx(a,o),Vx(i),o},h=function(e){var t,n,r=Wx(e,u,i);if(On(u)&&(e?0
'},uN=function(e,t){var n,r,o,i,a=e.editorManager.translate("Rich Text Area. Press ALT-0 for help."),u=(n=e.id,r=a,t.height,o=e.getParam("iframe_attrs",{}),i=Nt.fromTag("iframe"),$n(i,o),$n(i,{id:n+"_ifr",frameBorder:"0",allowTransparency:"true",title:r}),zu(i,"tox-edit-area__iframe"),i.dom);u.onload=function(){u.onload=null,e.fire("load")};var s=function(e,t){if(document.domain!==window.location.hostname&&vt.browser.isIE()){var n=Gy("mce");e[n]=function(){oN(e)};var r='javascript:(function(){document.open();document.domain="'+document.domain+'";var ed = window.parent.tinymce.get("'+e.id+'");document.write(ed.iframeHTML);document.close();ed.'+n+"(true);})()";return iN.setAttrib(t,"src",r),!0}return!1}(e,u);return e.contentAreaContainer=t.iframeContainer,e.iframeElement=u,e.iframeHTML=aN(e),iN.add(t.iframeContainer,u),s},sN=bu.DOM,cN=function(t,n,e){var r=Fy.get(e),o=Fy.urls[e]||t.documentBaseUrl.replace(/\/$/,"");if(e=xt.trim(e),r&&-1===xt.inArray(n,e)){if(xt.each(Fy.dependencies(e),function(e){cN(t,n,e)}),t.plugins[e])return;try{var i=new r(t,o,t.$);(t.plugins[e]=i).init&&(i.init(t,o),n.push(e))}catch(pk){!function(e,t,n){var r=Au.translate(["Failed to initialize plugin: {0}",t]);Wy(r,n),Hy(e,r)}(t,e,pk)}}},lN=function(e){return e.replace(/^\-/,"")},fN=function(e){return{editorContainer:e,iframeContainer:e,api:{}}},dN=function(e){var t,n,r=e.getElement();return e.inline?fN(null):(t=r,n=sN.create("div"),sN.insertAfter(n,t),fN(n))},mN=function(e){var t,n,r,o=e.getElement();return e.orgDisplay=o.style.display,q(Cc(e))?e.theme.renderUI():A(Cc(e))?(n=(t=e).getElement(),(r=Cc(t)(t,n)).editorContainer.nodeType&&(r.editorContainer.id=r.editorContainer.id||t.id+"_parent"),r.iframeContainer&&r.iframeContainer.nodeType&&(r.iframeContainer.id=r.iframeContainer.id||t.id+"_iframecontainer"),r.height=r.iframeHeight?r.iframeHeight:n.offsetHeight,r):dN(e)},pN=function(e){var n,t,r,o,i,a,u,s,c;e.fire("ScriptsLoaded"),n=e,t=xt.trim(pc(n)),r=n.ui.registry.getAll().icons,o=xe(xe({},Ry.get("default").icons),Ry.get(t).icons),oe(o,function(e,t){me(r,t)||n.ui.registry.addIcon(t,e)}),u=Cc(i=e),q(u)?(i.settings.theme=lN(u),a=Uy.get(u),i.theme=new a(i,Uy.urls[u]),i.theme.init&&i.theme.init(i,Uy.urls[u]||i.documentBaseUrl.replace(/\/$/,""),i.$)):i.theme={},s=e,c=[],xt.each(xc(s).split(/[ ,]/),function(e){cN(s,c,lN(e))});var l=mN(e);e.ui=xe(xe({},e.ui),l.api);var f,d,m,p,g={editorContainer:l.editorContainer,iframeContainer:l.iframeContainer};return e.editorContainer=g.editorContainer?g.editorContainer:null,(f=e).contentCSS=f.contentCSS.concat(Ky(f)),e.inline?oN(e):(p=uN(d=e,m=g),m.editorContainer&&(iN.get(m.editorContainer).style.display=d.orgDisplay,d.hidden=iN.isHidden(m.editorContainer)),d.getElement().style.display="none",iN.setAttrib(d.id,"aria-hidden","true"),void(p||oN(d)))},gN=bu.DOM,hN=function(e){return"-"===e.charAt(0)},vN=function(e,t){var n,r=hc(t),o=t.getParam("language_url","","string");!1===Au.hasCode(r)&&"en"!==r&&(n=""!==o?o:t.editorManager.baseURL+"/langs/"+r+".js",e.add(n,V,undefined,function(){Vy(t,"LanguageLoadError",qy("language",n,r))}))},yN=function(t,e,n){return U.from(e).filter(function(e){return 0
"),o(/\[b\]/gi,""),o(/\[\/b\]/gi,""),o(/\[i\]/gi,""),o(/\[\/i\]/gi,""),o(/\[u\]/gi,""),o(/\[\/u\]/gi,""),o(/\[url=([^\]]+)\](.*?)\[\/url\]/gi,'$2'),o(/\[url\](.*?)\[\/url\]/gi,'$1'),o(/\[img\](.*?)\[\/img\]/gi,''),o(/\[color=(.*?)\](.*?)\[\/color\]/gi,'$2'),o(/\[code\](.*?)\[\/code\]/gi,'$1 '),o(/\[quote.*?\](.*?)\[\/quote\]/gi,'$1 '),t};o.add("bbcode",function(o){o.on("BeforeSetContent",function(o){o.content=t(o.content)}),o.on("PostProcess",function(o){o.set&&(o.content=t(o.content)),o.get&&(o.content=function(t){t=e.trim(t);var o=function(o,e){t=t.replace(o,e)};return o(/
]*>/gi,"[quote]"),o(/<\/blockquote>/gi,"[/quote]"),o(/
')}var c;var e=tinyMCE.baseURL.indexOf("/static/");if(e>0){c=tinyMCE.baseURL.substring(0,e)}else{c=window.location.origin}var t="?CodeMirrorPath="+l.settings.codemirror.path+"&ParentOrigin="+window.location.origin;var o=800;if(l.settings.codemirror.width){o=l.settings.codemirror.width}var n=550;if(l.settings.codemirror.height){n=l.settings.codemirror.height}var i=tinymce.majorVersion<5?[{text:"Ok",subtype:"primary",onclick:function(){var e=document.querySelectorAll(".mce-container-body>iframe")[0];e.contentWindow.submit();a.close()}},{text:"Cancel",onclick:"close"}]:[{type:"custom",text:"Ok",name:"codemirrorOk",primary:true},{type:"cancel",text:"Cancel",name:"codemirrorCancel"}];var r={title:"HTML source code",url:m+"/source.html"+t,width:o,height:n,resizable:true,maximizable:true,fullScreen:l.settings.codemirror.fullscreen,saveCursorPosition:false,buttons:i,onClose:function(){window.removeEventListener("message",d)}};if(tinymce.majorVersion>=5){r.onAction=function(e,t){if(t.name==="codemirrorOk"){s({type:"save"})}else if(t.name==="codemirrorCancel"){s({type:"cancel"});a.close()}}}var a=tinymce.majorVersion<5?l.windowManager.open(r):l.windowManager.openUrl(r);var s=function(e){a.sendMessage(e)};var d=function(e){if(c!==e.origin){return}var t;if(e.data.type==="init"){t={content:l.getContent({source_view:true})};l.fire("ShowCodeEditor",t);s({type:"init",content:t.content});l.dom.remove(l.dom.select(".CmCaReT"))}else if(e.data.type==="setText"){t={content:e.data.text};var o=e.data.isDirty;l.fire("SaveCodeEditor",t);l.setContent(t.content);var n=l.dom.select("span#CmCaReT")[0];if(n){l.selection.scrollIntoView(n);l.selection.setCursorLocation(n,0);l.dom.remove(n)}else{var i=l.getContent();var r=i.replace('',"");if(i!==r){l.setContent(r)}}l.isNotDirty=!o;if(o){l.nodeChanged()}}else if(e.data.type==="closeWindow"){a.close()}};window.addEventListener("message",d,false)}if(tinymce.majorVersion<5){l.addButton("code",{title:"Source code",icon:"code",onclick:e});l.addMenuItem("code",{icon:"code",text:"Source code",context:"tools",onclick:e})}else{l.ui.registry.addButton("code",{text:"HTML",tooltip:"Edit HTML",onAction:e});l.ui.registry.addMenuItem("code",{icon:"sourcecode",text:"Edit HTML",onAction:e,context:"tools"})}});/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var e=tinymce.util.Tools.resolve("tinymce.PluginManager"),o=function(o){var e=o.getContent({source_view:!0});o.windowManager.open({title:"Source Code",size:"large",body:{type:"panel",items:[{type:"textarea",name:"code"}]},buttons:[{type:"cancel",name:"cancel",text:"Cancel"},{type:"submit",name:"save",text:"Save",primary:!0}],initialData:{code:e},onSubmit:function(e){var t,n;t=o,n=e.getData().code,t.focus(),t.undoManager.transact(function(){t.setContent(n)}),t.selection.setCursorLocation(),t.nodeChanged(),e.close()}})};e.add("code",function(e){var t,n;return(t=e).addCommand("mceCodeEditor",function(){o(t)}),(n=e).ui.registry.addButton("code",{icon:"sourcecode",tooltip:"Source code",onAction:function(){return o(n)}}),n.ui.registry.addMenuItem("code",{icon:"sourcecode",text:"Source code",onAction:function(){return o(n)}}),{}})}();/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var e,n,t,a=tinymce.util.Tools.resolve("tinymce.PluginManager"),i=function(e){return function(){return e}},s=i(!1),o=i(!0),r=function(){return l},l=(e=function(e){return e.isNone()},{fold:function(e,n){return e()},is:s,isSome:s,isNone:o,getOr:t=function(e){return e},getOrThunk:n=function(e){return e()},getOrDie:function(e){throw new Error(e||"error: getOrDie called on none.")},getOrNull:i(null),getOrUndefined:i(undefined),or:t,orThunk:n,map:r,each:function(){},bind:r,exists:s,forall:o,filter:r,equals:e,equals_:e,toArray:function(){return[]},toString:i("none()")}),u=function(t){var e=i(t),n=function(){return r},a=function(e){return e(t)},r={fold:function(e,n){return n(t)},is:function(e){return t===e},isSome:o,isNone:s,getOr:e,getOrThunk:e,getOrDie:e,getOrNull:e,getOrUndefined:e,or:n,orThunk:n,map:function(e){return u(e(t))},each:function(e){e(t)},bind:a,exists:a,forall:a,filter:function(e){return e(t)?r:l},toArray:function(){return[t]},toString:function(){return"some("+t+")"},equals:function(e){return e.is(t)},equals_:function(e,n){return e.fold(s,function(e){return n(t,e)})}};return r},c={some:u,none:r,from:function(e){return null===e||e===undefined?l:u(e)}},d=tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");function p(e){return e&&"PRE"===e.nodeName&&-1!==e.className.indexOf("language-")}function g(t){return function(e,n){return t(n)}}var m="undefined"!=typeof window?window:Function("return this;")(),f={},h={exports:f},b={};!function(n,t,a,d){var e=window.Prism;window.Prism={manual:!0},function(e){"object"==typeof t&&void 0!==a?a.exports=e():"function"==typeof n&&n.amd?n([],e):("undefined"!=typeof window?window:void 0!==b?b:"undefined"!=typeof self?self:this).EphoxContactWrapper=e()}(function(){return function c(i,s,o){function l(n,e){if(!s[n]){if(!i[n]){var t="function"==typeof d&&d;if(!e&&t)return t(n,!0);if(u)return u(n,!0);var a=new Error("Cannot find module '"+n+"'");throw a.code="MODULE_NOT_FOUND",a}var r=s[n]={exports:{}};i[n][0].call(r.exports,function(e){return l(i[n][1][e]||e)},r,r.exports,c,i,s,o)}return s[n].exports}for(var u="function"==typeof d&&d,e=0;e
/gi,"\n"),o(/
/gi,"\n"),o(/
/gi,"\n"),o(/'+a+"
"),n.selection.select(n.$("#__new").removeAttr("id")[0])},function(e){n.dom.setAttrib(e,"class","language-"+t),e.innerHTML=a,w(n).highlightElement(e),n.selection.select(e)})}),e.close()}})},x=function(a){a.ui.registry.addToggleButton("codesample",{icon:"code-sample",tooltip:"Insert/edit code sample",onAction:function(){return k(a)},onSetup:function(t){var e=function(){var e,n;t.setActive((n=(e=a).selection.getStart(),e.dom.is(n,'pre[class*="language-"]')))};return a.on("NodeChange",e),function(){return a.off("NodeChange",e)}}}),a.ui.registry.addMenuItem("codesample",{text:"Code sample...",icon:"code-sample",onAction:function(){return k(a)}})};a.add("codesample",function(n){var t,r,a;r=(t=n).$,t.on("PreProcess",function(e){r("pre[contenteditable=false]",e.node).filter(g(p)).each(function(e,n){var t=r(n),a=n.textContent;t.attr("class",r.trim(t.attr("class"))),t.removeAttr("contentEditable"),t.empty().append(r("").each(function(){this.textContent=a}))})}),t.on("SetContent",function(){var e=r("pre").filter(g(p)).filter(function(e,n){return"false"!==n.contentEditable});e.length&&t.undoManager.transact(function(){e.each(function(e,n){r(n).find("br").each(function(e,n){n.parentNode.replaceChild(t.getDoc().createTextNode("\n"),n)}),n.contentEditable="false",n.innerHTML=t.dom.encode(n.textContent),w(t).highlightElement(n),n.className=r.trim(n.className)})})}),x(n),(a=n).addCommand("codesample",function(){var e=a.selection.getNode();a.selection.isCollapsed()||p(e)?k(a):a.formatter.toggle("code")}),n.on("dblclick",function(e){p(e.target)&&k(n)})})}();/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";tinymce.util.Tools.resolve("tinymce.PluginManager").add("colorpicker",function(){console.warn("Color picker plugin is now built in to the core editor, please remove it from your editor configuration")})}();/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";tinymce.util.Tools.resolve("tinymce.PluginManager").add("contextmenu",function(){console.warn("Context menu plugin is now built in to the core editor, please remove it from your editor configuration")})}();/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var n,t,e,o,r=tinymce.util.Tools.resolve("tinymce.PluginManager"),u=tinymce.util.Tools.resolve("tinymce.util.Tools"),i=function(n,t){var e,o=n.dom,r=n.selection.getSelectedBlocks();r.length&&(e=o.getAttrib(r[0],"dir"),u.each(r,function(n){o.getParent(n.parentNode,'*[dir="'+t+'"]',o.getRoot())||o.setAttrib(n,"dir",e!==t?t:null)}),n.nodeChanged())},c=function(n){return function(){return n}},f=c(!1),d=c(!0),l=function(){return m},m=(n=function(n){return n.isNone()},{fold:function(n,t){return n()},is:f,isSome:f,isNone:d,getOr:e=function(n){return n},getOrThunk:t=function(n){return n()},getOrDie:function(n){throw new Error(n||"error: getOrDie called on none.")},getOrNull:c(null),getOrUndefined:c(undefined),or:e,orThunk:t,map:l,each:function(){},bind:l,exists:f,forall:d,filter:l,equals:n,equals_:n,toArray:function(){return[]},toString:c("none()")}),a=function(e){var n=c(e),t=function(){return r},o=function(n){return n(e)},r={fold:function(n,t){return t(e)},is:function(n){return e===n},isSome:d,isNone:f,getOr:n,getOrThunk:n,getOrDie:n,getOrNull:n,getOrUndefined:n,or:t,orThunk:t,map:function(n){return a(n(e))},each:function(n){n(e)},bind:o,exists:o,forall:o,filter:function(n){return n(e)?r:m},toArray:function(){return[e]},toString:function(){return"some("+e+")"},equals:function(n){return n.is(e)},equals_:function(n,t){return n.fold(f,function(n){return t(e,n)})}};return r},s={some:a,none:l,from:function(n){return null===n||n===undefined?m:a(n)}},g=(o="function",function(n){return typeof n===o}),h=function(n){if(null===n||n===undefined)throw new Error("Node cannot be null or undefined");return{dom:n}},y={fromHtml:function(n,t){var e=(t||document).createElement("div");if(e.innerHTML=n,!e.hasChildNodes()||1
"+A.translate(["Plugins installed ({0}):",r])+"
'+A.translate("Premium plugins:")+"
The sections of the outer UI of the editor - the menubar, toolbar, sidebar and footer - are all keyboard navigable. As such, there are multiple ways to activate keyboard navigation:
\nFocusing the menubar or toolbar will start keyboard navigation at the first item in the menubar or toolbar, which will be highlighted with a gray background. Focusing the footer will start keyboard navigation at the first item in the element path, which will be highlighted with an underline.
\n\nWhen keyboard navigation is active, pressing tab will move the focus to the next major section of the UI, where applicable. These sections are:
\nPressing shift + tab will move backwards through the same sections, except when moving from the footer to the toolbar. Focusing the element path then pressing shift + tab will move focus to the first toolbar group, not the last.
\n\nKeyboard navigation within UI sections can usually be achieved using the left and right arrow keys. This includes:
\nIn all these UI sections, keyboard navigation will cycle within the section. For example, focusing the last button in a toolbar group then pressing right arrow will move focus to the first item in the same toolbar group.
\n\nTo execute a button, navigate the selection to the desired button and hit space or enter.
\n\nWhen focusing a menubar button or a toolbar button with a menu, pressing space, enter or down arrow will open the menu. When the menu opens the first item will be selected. To move up or down the menu, press the up or down arrow key respectively. This is the same for submenus, which can also be opened and closed using the left and right arrow keys.
\n\nTo close any active menu, hit the escape key. When a menu is closed the selection will be restored to its previous selection. This also works for closing submenus.
\n\nTo focus an open context toolbar such as the table context toolbar, press Ctrl + F9 (Windows) or ⌃F9 (MacOS).
\n\nContext toolbar navigation is the same as toolbar navigation, and context menu navigation is the same as standard menu navigation.
\n\nThere are two types of dialog UIs in TinyMCE: tabbed dialogs and non-tabbed dialogs.
\n\nWhen a non-tabbed dialog is opened, the first interactive component in the dialog will be focused. Users can navigate between interactive components by pressing tab. This includes any footer buttons. Navigation will cycle back to the first dialog component if tab is pressed while focusing the last component in the dialog. Pressing shift + tab will navigate backwards.
\n\nWhen a tabbed dialog is opened, the first button in the tab menu is focused. Pressing tab will navigate to the first interactive component in that tab, and will cycle through the tab\u2019s components, the footer buttons, then back to the tab button. To switch to another tab, focus the tab button for the current tab, then use the arrow keys to cycle through the tab buttons.
"}]},c=T(e),u=(i='TinyMCE '+(a=x.majorVersion,o=x.minorVersion,0===a.indexOf("@")?"X.X.X":a+"."+o)+"",{name:"versions",title:"Version",items:[{type:"htmlpanel",html:""+A.translate(["You are using {0}",i])+"
",presets:"document"}]}),h=m(((n={})[s.name]=s,n[l.name]=l,n[c.name]=c,n[u.name]=u,n),t.get());return r=e,d.from(r.getParam("help_tabs")).fold(function(){return t=f(e=h),-1!==(n=t.indexOf("versions"))&&(t.splice(n,1),t.push("versions")),{tabs:e,names:t};var e,t,n},function(e){return t=h,n={},a=p(e,function(e){return"string"==typeof e?(y(t,e)&&(n[e]=t[e]),e):(n[e.name]=e).name}),{tabs:n,names:a};var t,n,a})},M=function(o,i){return function(){var e=P(o,i),a=e.tabs,t=e.names,n={type:"tabpanel",tabs:function(e){for(var t=[],n=function(e){t.push(e)},a=0;aabcabc123
would produceabc
abc123
. - * - * @method split - * @param {Element} parentElm Parent element to split. - * @param {Element} splitElm Element to split at. - * @param {Element} replacementElm Optional replacement element to replace the split element with. - * @return {Element} Returns the split element or the replacement element if that is specified. - */ - split: function(parentElm, splitElm, replacementElm) { - var self = this, r = self.createRng(), bef, aft, pa; - - // W3C valid browsers tend to leave empty nodes to the left/right side of the contents - this makes sense - // but we don't want that in our code since it serves no purpose for the end user - // For example splitting this html at the bold element: - //text 1CHOPtext 2
- // would produce: - //text 1
CHOPtext 2
- // this function will then trim off empty edges and produce: - //text 1
CHOPtext 2
- function trimNode(node) { - var i, children = node.childNodes, type = node.nodeType; - - function surroundedBySpans(node) { - var previousIsSpan = node.previousSibling && node.previousSibling.nodeName == 'SPAN'; - var nextIsSpan = node.nextSibling && node.nextSibling.nodeName == 'SPAN'; - return previousIsSpan && nextIsSpan; - } - - if (type == 1 && node.getAttribute('data-mce-type') == 'bookmark') { - return; - } - - for (i = children.length - 1; i >= 0; i--) { - trimNode(children[i]); - } - - if (type != 9) { - // Keep non whitespace text nodes - if (type == 3 && node.nodeValue.length > 0) { - // If parent element isn't a block or there isn't any useful contents for example "" - // Also keep text nodes with only spaces if surrounded by spans. - // eg. "
a b
" should keep space between a and b - var trimmedLength = trim(node.nodeValue).length; - if (!self.isBlock(node.parentNode) || trimmedLength > 0 || trimmedLength === 0 && surroundedBySpans(node)) { - return; - } - } else if (type == 1) { - // If the only child is a bookmark then move it up - children = node.childNodes; - - // TODO fix this complex if - if (children.length == 1 && children[0] && children[0].nodeType == 1 && - children[0].getAttribute('data-mce-type') == 'bookmark') { - node.parentNode.insertBefore(children[0], node); - } - - // Keep non empty elements or img, hr etc - if (children.length || /^(br|hr|input|img)$/i.test(node.nodeName)) { - return; - } - } - - self.remove(node); - } - - return node; - } - - if (parentElm && splitElm) { - // Get before chunk - r.setStart(parentElm.parentNode, self.nodeIndex(parentElm)); - r.setEnd(splitElm.parentNode, self.nodeIndex(splitElm)); - bef = r.extractContents(); - - // Get after chunk - r = self.createRng(); - r.setStart(splitElm.parentNode, self.nodeIndex(splitElm) + 1); - r.setEnd(parentElm.parentNode, self.nodeIndex(parentElm) + 1); - aft = r.extractContents(); - - // Insert before chunk - pa = parentElm.parentNode; - pa.insertBefore(trimNode(bef), parentElm); - - // Insert middle chunk - if (replacementElm) { - pa.replaceChild(replacementElm, splitElm); - } else { - pa.insertBefore(splitElm, parentElm); - } - - // Insert after chunk - pa.insertBefore(trimNode(aft), parentElm); - self.remove(parentElm); - - return replacementElm || splitElm; - } - }, - - /** - * Adds an event handler to the specified object. - * - * @method bind - * @param {Element/Document/Window/Array} target Target element to bind events to. - * handler to or an array of elements/ids/documents. - * @param {String} name Name of event handler to add, for example: click. - * @param {function} func Function to execute when the event occurs. - * @param {Object} scope Optional scope to execute the function in. - * @return {function} Function callback handler the same as the one passed in. - */ - bind: function(target, name, func, scope) { - var self = this; - - if (Tools.isArray(target)) { - var i = target.length; - - while (i--) { - target[i] = self.bind(target[i], name, func, scope); - } - - return target; - } - - // Collect all window/document events bound by editor instance - if (self.settings.collect && (target === self.doc || target === self.win)) { - self.boundEvents.push([target, name, func, scope]); - } - - return self.events.bind(target, name, func, scope || self); - }, - - /** - * Removes the specified event handler by name and function from an element or collection of elements. - * - * @method unbind - * @param {Element/Document/Window/Array} target Target element to unbind events on. - * @param {String} name Event handler name, for example: "click" - * @param {function} func Function to remove. - * @return {bool/Array} Bool state of true if the handler was removed, or an array of states if multiple input elements - * were passed in. - */ - unbind: function(target, name, func) { - var self = this, i; - - if (Tools.isArray(target)) { - i = target.length; - - while (i--) { - target[i] = self.unbind(target[i], name, func); - } - - return target; - } - - // Remove any bound events matching the input - if (self.boundEvents && (target === self.doc || target === self.win)) { - i = self.boundEvents.length; - - while (i--) { - var item = self.boundEvents[i]; - - if (target == item[0] && (!name || name == item[1]) && (!func || func == item[2])) { - this.events.unbind(item[0], item[1], item[2]); - } - } - } - - return this.events.unbind(target, name, func); - }, - - /** - * Fires the specified event name with object on target. - * - * @method fire - * @param {Node/Document/Window} target Target element or object to fire event on. - * @param {String} name Name of the event to fire. - * @param {Object} evt Event object to send. - * @return {Event} Event object. - */ - fire: function(target, name, evt) { - return this.events.fire(target, name, evt); - }, - - // Returns the content editable state of a node - getContentEditable: function(node) { - var contentEditable; - - // Check type - if (node.nodeType != 1) { - return null; - } - - // Check for fake content editable - contentEditable = node.getAttribute("data-mce-contenteditable"); - if (contentEditable && contentEditable !== "inherit") { - return contentEditable; - } - - // Check for real content editable - return node.contentEditable !== "inherit" ? node.contentEditable : null; - }, - - /** - * Destroys all internal references to the DOM to solve IE leak issues. - * - * @method destroy - */ - destroy: function() { - var self = this; - - // Unbind all events bound to window/document by editor instance - if (self.boundEvents) { - var i = self.boundEvents.length; - - while (i--) { - var item = self.boundEvents[i]; - this.events.unbind(item[0], item[1], item[2]); - } - - self.boundEvents = null; - } - - // Restore sizzle document to window.document - // Since the current document might be removed producing "Permission denied" on IE see #6325 - if (Sizzle.setDocument) { - Sizzle.setDocument(); - } - - self.win = self.doc = self.root = self.events = self.frag = null; - }, - - // #ifdef debug - - dumpRng: function(r) { - return ( - 'startContainer: ' + r.startContainer.nodeName + - ', startOffset: ' + r.startOffset + - ', endContainer: ' + r.endContainer.nodeName + - ', endOffset: ' + r.endOffset - ); - }, - - // #endif - - _findSib: function(node, selector, name) { - var self = this, func = selector; - - if (node) { - // If expression make a function of it using is - if (typeof(func) == 'string') { - func = function(node) { - return self.is(node, selector); - }; - } - - // Loop all siblings - for (node = node[name]; node; node = node[name]) { - if (func(node)) { - return node; - } - } - } - - return null; - } - }; - - /** - * Instance of DOMUtils for the current document. - * - * @static - * @property DOM - * @type tinymce.dom.DOMUtils - * @example - * // Example of how to add a class to some element by id - * tinymce.DOM.addClass('someid', 'someclass'); - */ - DOMUtils.DOM = new DOMUtils(document); - - return DOMUtils; -}); - -// Included from: js/tinymce/classes/dom/ScriptLoader.js - -/** - * ScriptLoader.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/*globals console*/ - -/** - * This class handles asynchronous/synchronous loading of JavaScript files it will execute callbacks - * when various items gets loaded. This class is useful to load external JavaScript files. - * - * @class tinymce.dom.ScriptLoader - * @example - * // Load a script from a specific URL using the global script loader - * tinymce.ScriptLoader.load('somescript.js'); - * - * // Load a script using a unique instance of the script loader - * var scriptLoader = new tinymce.dom.ScriptLoader(); - * - * scriptLoader.load('somescript.js'); - * - * // Load multiple scripts - * var scriptLoader = new tinymce.dom.ScriptLoader(); - * - * scriptLoader.add('somescript1.js'); - * scriptLoader.add('somescript2.js'); - * scriptLoader.add('somescript3.js'); - * - * scriptLoader.loadQueue(function() { - * alert('All scripts are now loaded.'); - * }); - */ -define("tinymce/dom/ScriptLoader", [ - "tinymce/dom/DOMUtils", - "tinymce/util/Tools" -], function(DOMUtils, Tools) { - var DOM = DOMUtils.DOM; - var each = Tools.each, grep = Tools.grep; - - function ScriptLoader() { - var QUEUED = 0, - LOADING = 1, - LOADED = 2, - states = {}, - queue = [], - scriptLoadedCallbacks = {}, - queueLoadedCallbacks = [], - loading = 0, - undef; - - /** - * Loads a specific script directly without adding it to the load queue. - * - * @method load - * @param {String} url Absolute URL to script to add. - * @param {function} callback Optional callback function to execute ones this script gets loaded. - * @param {Object} scope Optional scope to execute callback in. - */ - function loadScript(url, callback) { - var dom = DOM, elm, id; - - // Execute callback when script is loaded - function done() { - dom.remove(id); - - if (elm) { - elm.onreadystatechange = elm.onload = elm = null; - } - - callback(); - } - - function error() { - /*eslint no-console:0 */ - - // Report the error so it's easier for people to spot loading errors - if (typeof(console) !== "undefined" && console.log) { - console.log("Failed to load: " + url); - } - - // We can't mark it as done if there is a load error since - // A) We don't want to produce 404 errors on the server and - // B) the onerror event won't fire on all browsers. - // done(); - } - - id = dom.uniqueId(); - - // Create new script element - elm = document.createElement('script'); - elm.id = id; - elm.type = 'text/javascript'; - elm.src = url; - - // Seems that onreadystatechange works better on IE 10 onload seems to fire incorrectly - if ("onreadystatechange" in elm) { - elm.onreadystatechange = function() { - if (/loaded|complete/.test(elm.readyState)) { - done(); - } - }; - } else { - elm.onload = done; - } - - // Add onerror event will get fired on some browsers but not all of them - elm.onerror = error; - - // Add script to document - (document.getElementsByTagName('head')[0] || document.body).appendChild(elm); - } - - /** - * Returns true/false if a script has been loaded or not. - * - * @method isDone - * @param {String} url URL to check for. - * @return {Boolean} true/false if the URL is loaded. - */ - this.isDone = function(url) { - return states[url] == LOADED; - }; - - /** - * Marks a specific script to be loaded. This can be useful if a script got loaded outside - * the script loader or to skip it from loading some script. - * - * @method markDone - * @param {string} u Absolute URL to the script to mark as loaded. - */ - this.markDone = function(url) { - states[url] = LOADED; - }; - - /** - * Adds a specific script to the load queue of the script loader. - * - * @method add - * @param {String} url Absolute URL to script to add. - * @param {function} callback Optional callback function to execute ones this script gets loaded. - * @param {Object} scope Optional scope to execute callback in. - */ - this.add = this.load = function(url, callback, scope) { - var state = states[url]; - - // Add url to load queue - if (state == undef) { - queue.push(url); - states[url] = QUEUED; - } - - if (callback) { - // Store away callback for later execution - if (!scriptLoadedCallbacks[url]) { - scriptLoadedCallbacks[url] = []; - } - - scriptLoadedCallbacks[url].push({ - func: callback, - scope: scope || this - }); - } - }; - - /** - * Starts the loading of the queue. - * - * @method loadQueue - * @param {function} callback Optional callback to execute when all queued items are loaded. - * @param {Object} scope Optional scope to execute the callback in. - */ - this.loadQueue = function(callback, scope) { - this.loadScripts(queue, callback, scope); - }; - - /** - * Loads the specified queue of files and executes the callback ones they are loaded. - * This method is generally not used outside this class but it might be useful in some scenarios. - * - * @method loadScripts - * @param {Array} scripts Array of queue items to load. - * @param {function} callback Optional callback to execute ones all items are loaded. - * @param {Object} scope Optional scope to execute callback in. - */ - this.loadScripts = function(scripts, callback, scope) { - var loadScripts; - - function execScriptLoadedCallbacks(url) { - // Execute URL callback functions - each(scriptLoadedCallbacks[url], function(callback) { - callback.func.call(callback.scope); - }); - - scriptLoadedCallbacks[url] = undef; - } - - queueLoadedCallbacks.push({ - func: callback, - scope: scope || this - }); - - loadScripts = function() { - var loadingScripts = grep(scripts); - - // Current scripts has been handled - scripts.length = 0; - - // Load scripts that needs to be loaded - each(loadingScripts, function(url) { - // Script is already loaded then execute script callbacks directly - if (states[url] == LOADED) { - execScriptLoadedCallbacks(url); - return; - } - - // Is script not loading then start loading it - if (states[url] != LOADING) { - states[url] = LOADING; - loading++; - - loadScript(url, function() { - states[url] = LOADED; - loading--; - - execScriptLoadedCallbacks(url); - - // Load more scripts if they where added by the recently loaded script - loadScripts(); - }); - } - }); - - // No scripts are currently loading then execute all pending queue loaded callbacks - if (!loading) { - each(queueLoadedCallbacks, function(callback) { - callback.func.call(callback.scope); - }); - - queueLoadedCallbacks.length = 0; - } - }; - - loadScripts(); - }; - } - - ScriptLoader.ScriptLoader = new ScriptLoader(); - - return ScriptLoader; -}); - -// Included from: js/tinymce/classes/AddOnManager.js - -/** - * AddOnManager.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles the loading of themes/plugins or other add-ons and their language packs. - * - * @class tinymce.AddOnManager - */ -define("tinymce/AddOnManager", [ - "tinymce/dom/ScriptLoader", - "tinymce/util/Tools" -], function(ScriptLoader, Tools) { - var each = Tools.each; - - function AddOnManager() { - var self = this; - - self.items = []; - self.urls = {}; - self.lookup = {}; - } - - AddOnManager.prototype = { - /** - * Returns the specified add on by the short name. - * - * @method get - * @param {String} name Add-on to look for. - * @return {tinymce.Theme/tinymce.Plugin} Theme or plugin add-on instance or undefined. - */ - get: function(name) { - if (this.lookup[name]) { - return this.lookup[name].instance; - } else { - return undefined; - } - }, - - dependencies: function(name) { - var result; - - if (this.lookup[name]) { - result = this.lookup[name].dependencies; - } - - return result || []; - }, - - /** - * Loads a language pack for the specified add-on. - * - * @method requireLangPack - * @param {String} name Short name of the add-on. - * @param {String} languages Optional comma or space separated list of languages to check if it matches the name. - */ - requireLangPack: function(name, languages) { - if (AddOnManager.language && AddOnManager.languageLoad !== false) { - if (languages && new RegExp('([, ]|\\b)' + AddOnManager.language + '([, ]|\\b)').test(languages) === false) { - return; - } - - ScriptLoader.ScriptLoader.add(this.urls[name] + '/langs/' + AddOnManager.language + '.js'); - } - }, - - /** - * Adds a instance of the add-on by it's short name. - * - * @method add - * @param {String} id Short name/id for the add-on. - * @param {tinymce.Theme/tinymce.Plugin} addOn Theme or plugin to add. - * @return {tinymce.Theme/tinymce.Plugin} The same theme or plugin instance that got passed in. - * @example - * // Create a simple plugin - * tinymce.create('tinymce.plugins.TestPlugin', { - * TestPlugin: function(ed, url) { - * ed.on('click', function(e) { - * ed.windowManager.alert('Hello World!'); - * }); - * } - * }); - * - * // Register plugin using the add method - * tinymce.PluginManager.add('test', tinymce.plugins.TestPlugin); - * - * // Initialize TinyMCE - * tinymce.init({ - * ... - * plugins: '-test' // Init the plugin but don't try to load it - * }); - */ - add: function(id, addOn, dependencies) { - this.items.push(addOn); - this.lookup[id] = {instance: addOn, dependencies: dependencies}; - - return addOn; - }, - - createUrl: function(baseUrl, dep) { - if (typeof dep === "object") { - return dep; - } else { - return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix}; - } - }, - - /** - * Add a set of components that will make up the add-on. Using the url of the add-on name as the base url. - * This should be used in development mode. A new compressor/javascript munger process will ensure that the - * components are put together into the plugin.js file and compressed correctly. - * - * @method addComponents - * @param {String} pluginName name of the plugin to load scripts from (will be used to get the base url for the plugins). - * @param {Array} scripts Array containing the names of the scripts to load. - */ - addComponents: function(pluginName, scripts) { - var pluginUrl = this.urls[pluginName]; - - each(scripts, function(script) { - ScriptLoader.ScriptLoader.add(pluginUrl + "/" + script); - }); - }, - - /** - * Loads an add-on from a specific url. - * - * @method load - * @param {String} name Short name of the add-on that gets loaded. - * @param {String} addOnUrl URL to the add-on that will get loaded. - * @param {function} callback Optional callback to execute ones the add-on is loaded. - * @param {Object} scope Optional scope to execute the callback in. - * @example - * // Loads a plugin from an external URL - * tinymce.PluginManager.load('myplugin', '/some/dir/someplugin/plugin.js'); - * - * // Initialize TinyMCE - * tinymce.init({ - * ... - * plugins: '-myplugin' // Don't try to load it again - * }); - */ - load: function(name, addOnUrl, callback, scope) { - var self = this, url = addOnUrl; - - function loadDependencies() { - var dependencies = self.dependencies(name); - - each(dependencies, function(dep) { - var newUrl = self.createUrl(addOnUrl, dep); - - self.load(newUrl.resource, newUrl, undefined, undefined); - }); - - if (callback) { - if (scope) { - callback.call(scope); - } else { - callback.call(ScriptLoader); - } - } - } - - if (self.urls[name]) { - return; - } - - if (typeof addOnUrl === "object") { - url = addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix; - } - - if (url.indexOf('/') !== 0 && url.indexOf('://') == -1) { - url = AddOnManager.baseURL + '/' + url; - } - - self.urls[name] = url.substring(0, url.lastIndexOf('/')); - - if (self.lookup[name]) { - loadDependencies(); - } else { - ScriptLoader.ScriptLoader.add(url, loadDependencies, scope); - } - } - }; - - AddOnManager.PluginManager = new AddOnManager(); - AddOnManager.ThemeManager = new AddOnManager(); - - return AddOnManager; -}); - -/** - * TinyMCE theme class. - * - * @class tinymce.Theme - */ - -/** - * This method is responsible for rendering/generating the overall user interface with toolbars, buttons, iframe containers etc. - * - * @method renderUI - * @param {Object} obj Object parameter containing the targetNode DOM node that will be replaced visually with an editor instance. - * @return {Object} an object with items like iframeContainer, editorContainer, sizeContainer, deltaWidth, deltaHeight. - */ - -/** - * Plugin base class, this is a pseudo class that describes how a plugin is to be created for TinyMCE. The methods below are all optional. - * - * @class tinymce.Plugin - * @example - * tinymce.PluginManager.add('example', function(editor, url) { - * // Add a button that opens a window - * editor.addButton('example', { - * text: 'My button', - * icon: false, - * onclick: function() { - * // Open window - * editor.windowManager.open({ - * title: 'Example plugin', - * body: [ - * {type: 'textbox', name: 'title', label: 'Title'} - * ], - * onsubmit: function(e) { - * // Insert content when the window form is submitted - * editor.insertContent('Title: ' + e.data.title); - * } - * }); - * } - * }); - * - * // Adds a menu item to the tools menu - * editor.addMenuItem('example', { - * text: 'Example plugin', - * context: 'tools', - * onclick: function() { - * // Open window with a specific url - * editor.windowManager.open({ - * title: 'TinyMCE site', - * url: 'http://www.tinymce.com', - * width: 800, - * height: 600, - * buttons: [{ - * text: 'Close', - * onclick: 'close' - * }] - * }); - * } - * }); - * }); - */ - -// Included from: js/tinymce/classes/html/Node.js - -/** - * Node.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is a minimalistic implementation of a DOM like node used by the DomParser class. - * - * @example - * var node = new tinymce.html.Node('strong', 1); - * someRoot.append(node); - * - * @class tinymce.html.Node - * @version 3.4 - */ -define("tinymce/html/Node", [], function() { - var whiteSpaceRegExp = /^[ \t\r\n]*$/, typeLookup = { - '#text': 3, - '#comment': 8, - '#cdata': 4, - '#pi': 7, - '#doctype': 10, - '#document-fragment': 11 - }; - - // Walks the tree left/right - function walk(node, root_node, prev) { - var sibling, parent, startName = prev ? 'lastChild' : 'firstChild', siblingName = prev ? 'prev' : 'next'; - - // Walk into nodes if it has a start - if (node[startName]) { - return node[startName]; - } - - // Return the sibling if it has one - if (node !== root_node) { - sibling = node[siblingName]; - - if (sibling) { - return sibling; - } - - // Walk up the parents to look for siblings - for (parent = node.parent; parent && parent !== root_node; parent = parent.parent) { - sibling = parent[siblingName]; - - if (sibling) { - return sibling; - } - } - } - } - - /** - * Constructs a new Node instance. - * - * @constructor - * @method Node - * @param {String} name Name of the node type. - * @param {Number} type Numeric type representing the node. - */ - function Node(name, type) { - this.name = name; - this.type = type; - - if (type === 1) { - this.attributes = []; - this.attributes.map = {}; - } - } - - Node.prototype = { - /** - * Replaces the current node with the specified one. - * - * @example - * someNode.replace(someNewNode); - * - * @method replace - * @param {tinymce.html.Node} node Node to replace the current node with. - * @return {tinymce.html.Node} The old node that got replaced. - */ - replace: function(node) { - var self = this; - - if (node.parent) { - node.remove(); - } - - self.insert(node, self); - self.remove(); - - return self; - }, - - /** - * Gets/sets or removes an attribute by name. - * - * @example - * someNode.attr("name", "value"); // Sets an attribute - * console.log(someNode.attr("name")); // Gets an attribute - * someNode.attr("name", null); // Removes an attribute - * - * @method attr - * @param {String} name Attribute name to set or get. - * @param {String} value Optional value to set. - * @return {String/tinymce.html.Node} String or undefined on a get operation or the current node on a set operation. - */ - attr: function(name, value) { - var self = this, attrs, i, undef; - - if (typeof name !== "string") { - for (i in name) { - self.attr(i, name[i]); - } - - return self; - } - - if ((attrs = self.attributes)) { - if (value !== undef) { - // Remove attribute - if (value === null) { - if (name in attrs.map) { - delete attrs.map[name]; - - i = attrs.length; - while (i--) { - if (attrs[i].name === name) { - attrs = attrs.splice(i, 1); - return self; - } - } - } - - return self; - } - - // Set attribute - if (name in attrs.map) { - // Set attribute - i = attrs.length; - while (i--) { - if (attrs[i].name === name) { - attrs[i].value = value; - break; - } - } - } else { - attrs.push({name: name, value: value}); - } - - attrs.map[name] = value; - - return self; - } else { - return attrs.map[name]; - } - } - }, - - /** - * Does a shallow clones the node into a new node. It will also exclude id attributes since - * there should only be one id per document. - * - * @example - * var clonedNode = node.clone(); - * - * @method clone - * @return {tinymce.html.Node} New copy of the original node. - */ - clone: function() { - var self = this, clone = new Node(self.name, self.type), i, l, selfAttrs, selfAttr, cloneAttrs; - - // Clone element attributes - if ((selfAttrs = self.attributes)) { - cloneAttrs = []; - cloneAttrs.map = {}; - - for (i = 0, l = selfAttrs.length; i < l; i++) { - selfAttr = selfAttrs[i]; - - // Clone everything except id - if (selfAttr.name !== 'id') { - cloneAttrs[cloneAttrs.length] = {name: selfAttr.name, value: selfAttr.value}; - cloneAttrs.map[selfAttr.name] = selfAttr.value; - } - } - - clone.attributes = cloneAttrs; - } - - clone.value = self.value; - clone.shortEnded = self.shortEnded; - - return clone; - }, - - /** - * Wraps the node in in another node. - * - * @example - * node.wrap(wrapperNode); - * - * @method wrap - */ - wrap: function(wrapper) { - var self = this; - - self.parent.insert(wrapper, self); - wrapper.append(self); - - return self; - }, - - /** - * Unwraps the node in other words it removes the node but keeps the children. - * - * @example - * node.unwrap(); - * - * @method unwrap - */ - unwrap: function() { - var self = this, node, next; - - for (node = self.firstChild; node; ) { - next = node.next; - self.insert(node, self, true); - node = next; - } - - self.remove(); - }, - - /** - * Removes the node from it's parent. - * - * @example - * node.remove(); - * - * @method remove - * @return {tinymce.html.Node} Current node that got removed. - */ - remove: function() { - var self = this, parent = self.parent, next = self.next, prev = self.prev; - - if (parent) { - if (parent.firstChild === self) { - parent.firstChild = next; - - if (next) { - next.prev = null; - } - } else { - prev.next = next; - } - - if (parent.lastChild === self) { - parent.lastChild = prev; - - if (prev) { - prev.next = null; - } - } else { - next.prev = prev; - } - - self.parent = self.next = self.prev = null; - } - - return self; - }, - - /** - * Appends a new node as a child of the current node. - * - * @example - * node.append(someNode); - * - * @method append - * @param {tinymce.html.Node} node Node to append as a child of the current one. - * @return {tinymce.html.Node} The node that got appended. - */ - append: function(node) { - var self = this, last; - - if (node.parent) { - node.remove(); - } - - last = self.lastChild; - if (last) { - last.next = node; - node.prev = last; - self.lastChild = node; - } else { - self.lastChild = self.firstChild = node; - } - - node.parent = self; - - return node; - }, - - /** - * Inserts a node at a specific position as a child of the current node. - * - * @example - * parentNode.insert(newChildNode, oldChildNode); - * - * @method insert - * @param {tinymce.html.Node} node Node to insert as a child of the current node. - * @param {tinymce.html.Node} ref_node Reference node to set node before/after. - * @param {Boolean} before Optional state to insert the node before the reference node. - * @return {tinymce.html.Node} The node that got inserted. - */ - insert: function(node, ref_node, before) { - var parent; - - if (node.parent) { - node.remove(); - } - - parent = ref_node.parent || this; - - if (before) { - if (ref_node === parent.firstChild) { - parent.firstChild = node; - } else { - ref_node.prev.next = node; - } - - node.prev = ref_node.prev; - node.next = ref_node; - ref_node.prev = node; - } else { - if (ref_node === parent.lastChild) { - parent.lastChild = node; - } else { - ref_node.next.prev = node; - } - - node.next = ref_node.next; - node.prev = ref_node; - ref_node.next = node; - } - - node.parent = parent; - - return node; - }, - - /** - * Get all children by name. - * - * @method getAll - * @param {String} name Name of the child nodes to collect. - * @return {Array} Array with child nodes matchin the specified name. - */ - getAll: function(name) { - var self = this, node, collection = []; - - for (node = self.firstChild; node; node = walk(node, self)) { - if (node.name === name) { - collection.push(node); - } - } - - return collection; - }, - - /** - * Removes all children of the current node. - * - * @method empty - * @return {tinymce.html.Node} The current node that got cleared. - */ - empty: function() { - var self = this, nodes, i, node; - - // Remove all children - if (self.firstChild) { - nodes = []; - - // Collect the children - for (node = self.firstChild; node; node = walk(node, self)) { - nodes.push(node); - } - - // Remove the children - i = nodes.length; - while (i--) { - node = nodes[i]; - node.parent = node.firstChild = node.lastChild = node.next = node.prev = null; - } - } - - self.firstChild = self.lastChild = null; - - return self; - }, - - /** - * Returns true/false if the node is to be considered empty or not. - * - * @example - * node.isEmpty({img: true}); - * @method isEmpty - * @param {Object} elements Name/value object with elements that are automatically treated as non empty elements. - * @return {Boolean} true/false if the node is empty or not. - */ - isEmpty: function(elements) { - var self = this, node = self.firstChild, i, name; - - if (node) { - do { - if (node.type === 1) { - // Ignore bogus elements - if (node.attributes.map['data-mce-bogus']) { - continue; - } - - // Keep empty elements likea
b
c will becomea
b
c
- * - * @example - * var parser = new tinymce.html.DomParser({validate: true}, schema); - * var rootNode = parser.parse('x
->x
- function trim(rootBlockNode) { - if (rootBlockNode) { - node = rootBlockNode.firstChild; - if (node && node.type == 3) { - node.value = node.value.replace(startWhiteSpaceRegExp, ''); - } - - node = rootBlockNode.lastChild; - if (node && node.type == 3) { - node.value = node.value.replace(endWhiteSpaceRegExp, ''); - } - } - } - - // Check if rootBlock is valid within rootNode for example if P is valid in H1 if H1 is the contentEditabe root - if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) { - return; - } - - while (node) { - next = node.next; - - if (node.type == 3 || (node.type == 1 && node.name !== 'p' && - !blockElements[node.name] && !node.attr('data-mce-type'))) { - if (!rootBlockNode) { - // Create a new root block element - rootBlockNode = createNode(rootBlockName, 1); - rootBlockNode.attr(settings.forced_root_block_attrs); - rootNode.insert(rootBlockNode, node); - rootBlockNode.append(node); - } else { - rootBlockNode.append(node); - } - } else { - trim(rootBlockNode); - rootBlockNode = null; - } - - node = next; - } - - trim(rootBlockNode); - } - - function createNode(name, type) { - var node = new Node(name, type), list; - - if (name in nodeFilters) { - list = matchedNodes[name]; - - if (list) { - list.push(node); - } else { - matchedNodes[name] = [node]; - } - } - - return node; - } - - function removeWhitespaceBefore(node) { - var textNode, textVal, sibling; - - for (textNode = node.prev; textNode && textNode.type === 3; ) { - textVal = textNode.value.replace(endWhiteSpaceRegExp, ''); - - if (textVal.length > 0) { - textNode.value = textVal; - textNode = textNode.prev; - } else { - sibling = textNode.prev; - textNode.remove(); - textNode = sibling; - } - } - } - - function cloneAndExcludeBlocks(input) { - var name, output = {}; - - for (name in input) { - if (name !== 'li' && name != 'p') { - output[name] = input[name]; - } - } - - return output; - } - - parser = new SaxParser({ - validate: validate, - allow_script_urls: settings.allow_script_urls, - allow_conditional_comments: settings.allow_conditional_comments, - - // Exclude P and LI from DOM parsing since it's treated better by the DOM parser - self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()), - - cdata: function(text) { - node.append(createNode('#cdata', 4)).value = text; - }, - - text: function(text, raw) { - var textNode; - - // Trim all redundant whitespace on non white space elements - if (!isInWhiteSpacePreservedElement) { - text = text.replace(allWhiteSpaceRegExp, ' '); - - if (node.lastChild && blockElements[node.lastChild.name]) { - text = text.replace(startWhiteSpaceRegExp, ''); - } - } - - // Do we need to create the node - if (text.length !== 0) { - textNode = createNode('#text', 3); - textNode.raw = !!raw; - node.append(textNode).value = text; - } - }, - - comment: function(text) { - node.append(createNode('#comment', 8)).value = text; - }, - - pi: function(name, text) { - node.append(createNode(name, 7)).value = text; - removeWhitespaceBefore(node); - }, - - doctype: function(text) { - var newNode; - - newNode = node.append(createNode('#doctype', 10)); - newNode.value = text; - removeWhitespaceBefore(node); - }, - - start: function(name, attrs, empty) { - var newNode, attrFiltersLen, elementRule, attrName, parent; - - elementRule = validate ? schema.getElementRule(name) : {}; - if (elementRule) { - newNode = createNode(elementRule.outputName || name, 1); - newNode.attributes = attrs; - newNode.shortEnded = empty; - - node.append(newNode); - - // Check if node is valid child of the parent node is the child is - // unknown we don't collect it since it's probably a custom element - parent = children[node.name]; - if (parent && children[newNode.name] && !parent[newNode.name]) { - invalidChildren.push(newNode); - } - - attrFiltersLen = attributeFilters.length; - while (attrFiltersLen--) { - attrName = attributeFilters[attrFiltersLen].name; - - if (attrName in attrs.map) { - list = matchedAttributes[attrName]; - - if (list) { - list.push(newNode); - } else { - matchedAttributes[attrName] = [newNode]; - } - } - } - - // Trim whitespace before block - if (blockElements[name]) { - removeWhitespaceBefore(newNode); - } - - // Change current node if the element wasn't empty i.e nota
- lastParent = node; - while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) { - lastParent = parent; - - if (blockElements[parent.name]) { - break; - } - - parent = parent.parent; - } - - if (lastParent === parent) { - textNode = new Node('#text', 3); - textNode.value = '\u00a0'; - node.replace(textNode); - } - } - } - }); - } - - // Force anchor names closed, unless the setting "allow_html_in_named_anchor" is explicitly included. - if (!settings.allow_html_in_named_anchor) { - self.addAttributeFilter('id,name', function(nodes) { - var i = nodes.length, sibling, prevSibling, parent, node; - - while (i--) { - node = nodes[i]; - if (node.name === 'a' && node.firstChild && !node.attr('href')) { - parent = node.parent; - - // Move children after current node - sibling = node.lastChild; - do { - prevSibling = sibling.prev; - parent.insert(sibling, node); - sibling = prevSibling; - } while (sibling); - } - } - }); - } - }; -}); - -// Included from: js/tinymce/classes/html/Writer.js - -/** - * Writer.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is used to write HTML tags out it can be used with the Serializer or the SaxParser. - * - * @class tinymce.html.Writer - * @example - * var writer = new tinymce.html.Writer({indent: true}); - * var parser = new tinymce.html.SaxParser(writer).parse('
.
- *
- * @method start
- * @param {String} name Name of the element.
- * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
- * @param {Boolean} empty Optional empty state if the tag should end like
.
- */
- start: function(name, attrs, empty) {
- var i, l, attr, value;
-
- if (indent && indentBefore[name] && html.length > 0) {
- value = html[html.length - 1];
-
- if (value.length > 0 && value !== '\n') {
- html.push('\n');
- }
- }
-
- html.push('<', name);
-
- if (attrs) {
- for (i = 0, l = attrs.length; i < l; i++) {
- attr = attrs[i];
- html.push(' ', attr.name, '="', encode(attr.value, true), '"');
- }
- }
-
- if (!empty || htmlOutput) {
- html[html.length] = '>';
- } else {
- html[html.length] = ' />';
- }
-
- if (empty && indent && indentAfter[name] && html.length > 0) {
- value = html[html.length - 1];
-
- if (value.length > 0 && value !== '\n') {
- html.push('\n');
- }
- }
- },
-
- /**
- * Writes the a end element such as
text
')); - * @class tinymce.html.Serializer - * @version 3.4 - */ -define("tinymce/html/Serializer", [ - "tinymce/html/Writer", - "tinymce/html/Schema" -], function(Writer, Schema) { - /** - * Constructs a new Serializer instance. - * - * @constructor - * @method Serializer - * @param {Object} settings Name/value settings object. - * @param {tinymce.html.Schema} schema Schema instance to use. - */ - return function(settings, schema) { - var self = this, writer = new Writer(settings); - - settings = settings || {}; - settings.validate = "validate" in settings ? settings.validate : true; - - self.schema = schema = schema || new Schema(); - self.writer = writer; - - /** - * Serializes the specified node into a string. - * - * @example - * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('text
')); - * @method serialize - * @param {tinymce.html.Node} node Node instance to serialize. - * @return {String} String with HTML based on DOM tree. - */ - self.serialize = function(node) { - var handlers, validate; - - validate = settings.validate; - - handlers = { - // #text - 3: function(node) { - writer.text(node.value, node.raw); - }, - - // #comment - 8: function(node) { - writer.comment(node.value); - }, - - // Processing instruction - 7: function(node) { - writer.pi(node.name, node.value); - }, - - // Doctype - 10: function(node) { - writer.doctype(node.value); - }, - - // CDATA - 4: function(node) { - writer.cdata(node.value); - }, - - // Document fragment - 11: function(node) { - if ((node = node.firstChild)) { - do { - walk(node); - } while ((node = node.next)); - } - } - }; - - writer.reset(); - - function walk(node) { - var handler = handlers[node.type], name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule; - - if (!handler) { - name = node.name; - isEmpty = node.shortEnded; - attrs = node.attributes; - - // Sort attributes - if (validate && attrs && attrs.length > 1) { - sortedAttrs = []; - sortedAttrs.map = {}; - - elementRule = schema.getElementRule(node.name); - for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) { - attrName = elementRule.attributesOrder[i]; - - if (attrName in attrs.map) { - attrValue = attrs.map[attrName]; - sortedAttrs.map[attrName] = attrValue; - sortedAttrs.push({name: attrName, value: attrValue}); - } - } - - for (i = 0, l = attrs.length; i < l; i++) { - attrName = attrs[i].name; - - if (!(attrName in sortedAttrs.map)) { - attrValue = attrs.map[attrName]; - sortedAttrs.map[attrName] = attrValue; - sortedAttrs.push({name: attrName, value: attrValue}); - } - } - - attrs = sortedAttrs; - } - - writer.start(node.name, attrs, isEmpty); - - if (!isEmpty) { - if ((node = node.firstChild)) { - do { - walk(node); - } while ((node = node.next)); - } - - writer.end(name); - } - } else { - handler(node); - } - } - - // Serialize element and treat all non elements as fragments - if (node.type == 1 && !settings.inner) { - walk(node); - } else { - handlers[11](node); - } - - return writer.getContent(); - }; - }; -}); - -// Included from: js/tinymce/classes/dom/Serializer.js - -/** - * Serializer.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is used to serialize DOM trees into a string. Consult the TinyMCE Wiki API for - * more details and examples on how to use this class. - * - * @class tinymce.dom.Serializer - */ -define("tinymce/dom/Serializer", [ - "tinymce/dom/DOMUtils", - "tinymce/html/DomParser", - "tinymce/html/Entities", - "tinymce/html/Serializer", - "tinymce/html/Node", - "tinymce/html/Schema", - "tinymce/Env", - "tinymce/util/Tools" -], function(DOMUtils, DomParser, Entities, Serializer, Node, Schema, Env, Tools) { - var each = Tools.each, trim = Tools.trim; - var DOM = DOMUtils.DOM; - - /** - * Constructs a new DOM serializer class. - * - * @constructor - * @method Serializer - * @param {Object} settings Serializer settings object. - * @param {tinymce.Editor} editor Optional editor to bind events to and get schema/dom from. - */ - return function(settings, editor) { - var dom, schema, htmlParser; - - if (editor) { - dom = editor.dom; - schema = editor.schema; - } - - // Default DOM and Schema if they are undefined - dom = dom || DOM; - schema = schema || new Schema(settings); - settings.entity_encoding = settings.entity_encoding || 'named'; - settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true; - - htmlParser = new DomParser(settings, schema); - - // Convert move data-mce-src, data-mce-href and data-mce-style into nodes or process them if needed - htmlParser.addAttributeFilter('src,href,style', function(nodes, name) { - var i = nodes.length, node, value, internalName = 'data-mce-' + name; - var urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope, undef; - - while (i--) { - node = nodes[i]; - - value = node.attributes.map[internalName]; - if (value !== undef) { - // Set external name to internal value and remove internal - node.attr(name, value.length > 0 ? value : null); - node.attr(internalName, null); - } else { - // No internal attribute found then convert the value we have in the DOM - value = node.attributes.map[name]; - - if (name === "style") { - value = dom.serializeStyle(dom.parseStyle(value), node.name); - } else if (urlConverter) { - value = urlConverter.call(urlConverterScope, value, name, node.name); - } - - node.attr(name, value.length > 0 ? value : null); - } - } - }); - - // Remove internal classes mceItem<..> or mceSelected - htmlParser.addAttributeFilter('class', function(nodes) { - var i = nodes.length, node, value; - - while (i--) { - node = nodes[i]; - value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, ''); - node.attr('class', value.length > 0 ? value : null); - } - }); - - // Remove bookmark elements - htmlParser.addAttributeFilter('data-mce-type', function(nodes, name, args) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i]; - - if (node.attributes.map['data-mce-type'] === 'bookmark' && !args.cleanup) { - node.remove(); - } - } - }); - - // Remove expando attributes - htmlParser.addAttributeFilter('data-mce-expando', function(nodes, name) { - var i = nodes.length; - - while (i--) { - nodes[i].attr(name, null); - } - }); - - htmlParser.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i].firstChild; - - if (node) { - node.value = Entities.decode(node.value); - } - } - }); - - // Force script into CDATA sections and remove the mce- prefix also add comments around styles - htmlParser.addNodeFilter('script,style', function(nodes, name) { - var i = nodes.length, node, value; - - function trim(value) { - /*jshint maxlen:255 */ - /*eslint max-len:0 */ - return value.replace(/()/g, '\n') - .replace(/^[\r\n]*|[\r\n]*$/g, '') - .replace(/^\s*(()?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, ''); - } - - while (i--) { - node = nodes[i]; - value = node.firstChild ? node.firstChild.value : ''; - - if (name === "script") { - // Remove mce- prefix from script elements and remove default text/javascript mime type (HTML5) - var type = (node.attr('type') || 'text/javascript').replace(/^mce\-/, ''); - node.attr('type', type === 'text/javascript' ? null : type); - - if (value.length > 0) { - node.firstChild.value = '// '; - } - } else { - if (value.length > 0) { - node.firstChild.value = ''; - } - } - } - }); - - // Convert comments to cdata and handle protected comments - htmlParser.addNodeFilter('#comment', function(nodes) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i]; - - if (node.value.indexOf('[CDATA[') === 0) { - node.name = '#cdata'; - node.type = 4; - node.value = node.value.replace(/^\[CDATA\[|\]\]$/g, ''); - } else if (node.value.indexOf('mce:protected ') === 0) { - node.name = "#text"; - node.type = 3; - node.raw = true; - node.value = unescape(node.value).substr(14); - } - } - }); - - htmlParser.addNodeFilter('xml:namespace,input', function(nodes, name) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i]; - if (node.type === 7) { - node.remove(); - } else if (node.type === 1) { - if (name === "input" && !("type" in node.attributes.map)) { - node.attr('type', 'text'); - } - } - } - }); - - // Fix list elements, TODO: Replace this later - if (settings.fix_list_elements) { - htmlParser.addNodeFilter('ul,ol', function(nodes) { - var i = nodes.length, node, parentNode; - - while (i--) { - node = nodes[i]; - parentNode = node.parent; - - if (parentNode.name === 'ul' || parentNode.name === 'ol') { - if (node.prev && node.prev.name === 'li') { - node.prev.append(node); - } - } - } - }); - } - - // Remove internal data attributes - htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style,data-mce-selected', function(nodes, name) { - var i = nodes.length; - - while (i--) { - nodes[i].attr(name, null); - } - }); - - // Return public methods - return { - /** - * Schema instance that was used to when the Serializer was constructed. - * - * @field {tinymce.html.Schema} schema - */ - schema: schema, - - /** - * Adds a node filter function to the parser used by the serializer, the parser will collect the specified nodes by name - * and then execute the callback ones it has finished parsing the document. - * - * @example - * parser.addNodeFilter('p,h1', function(nodes, name) { - * for (var i = 0; i < nodes.length; i++) { - * console.log(nodes[i].name); - * } - * }); - * @method addNodeFilter - * @method {String} name Comma separated list of nodes to collect. - * @param {function} callback Callback function to execute once it has collected nodes. - */ - addNodeFilter: htmlParser.addNodeFilter, - - /** - * Adds a attribute filter function to the parser used by the serializer, the parser will - * collect nodes that has the specified attributes - * and then execute the callback ones it has finished parsing the document. - * - * @example - * parser.addAttributeFilter('src,href', function(nodes, name) { - * for (var i = 0; i < nodes.length; i++) { - * console.log(nodes[i].name); - * } - * }); - * @method addAttributeFilter - * @method {String} name Comma separated list of nodes to collect. - * @param {function} callback Callback function to execute once it has collected nodes. - */ - addAttributeFilter: htmlParser.addAttributeFilter, - - /** - * Serializes the specified browser DOM node into a HTML string. - * - * @method serialize - * @param {DOMNode} node DOM node to serialize. - * @param {Object} args Arguments option that gets passed to event handlers. - */ - serialize: function(node, args) { - var self = this, impl, doc, oldDoc, htmlSerializer, content; - - // Explorer won't clone contents of script and style and the - // selected index of select elements are cleared on a clone operation. - if (Env.ie && dom.select('script,style,select,map').length > 0) { - content = node.innerHTML; - node = node.cloneNode(false); - dom.setHTML(node, content); - } else { - node = node.cloneNode(true); - } - - // Nodes needs to be attached to something in WebKit/Opera - // This fix will make DOM ranges and make Sizzle happy! - impl = node.ownerDocument.implementation; - if (impl.createHTMLDocument) { - // Create an empty HTML document - doc = impl.createHTMLDocument(""); - - // Add the element or it's children if it's a body element to the new document - each(node.nodeName == 'BODY' ? node.childNodes : [node], function(node) { - doc.body.appendChild(doc.importNode(node, true)); - }); - - // Grab first child or body element for serialization - if (node.nodeName != 'BODY') { - node = doc.body.firstChild; - } else { - node = doc.body; - } - - // set the new document in DOMUtils so createElement etc works - oldDoc = dom.doc; - dom.doc = doc; - } - - args = args || {}; - args.format = args.format || 'html'; - - // Don't wrap content if we want selected html - if (args.selection) { - args.forced_root_block = ''; - } - - // Pre process - if (!args.no_events) { - args.node = node; - self.onPreProcess(args); - } - - // Setup serializer - htmlSerializer = new Serializer(settings, schema); - - // Parse and serialize HTML - args.content = htmlSerializer.serialize( - htmlParser.parse(trim(args.getInner ? node.innerHTML : dom.getOuterHTML(node)), args) - ); - - // Replace all BOM characters for now until we can find a better solution - if (!args.cleanup) { - args.content = args.content.replace(/\uFEFF/g, ''); - } - - // Post process - if (!args.no_events) { - self.onPostProcess(args); - } - - // Restore the old document if it was changed - if (oldDoc) { - dom.doc = oldDoc; - } - - args.node = null; - - return args.content; - }, - - /** - * Adds valid elements rules to the serializers schema instance this enables you to specify things - * like what elements should be outputted and what attributes specific elements might have. - * Consult the Wiki for more details on this format. - * - * @method addRules - * @param {String} rules Valid elements rules string to add to schema. - */ - addRules: function(rules) { - schema.addValidElements(rules); - }, - - /** - * Sets the valid elements rules to the serializers schema instance this enables you to specify things - * like what elements should be outputted and what attributes specific elements might have. - * Consult the Wiki for more details on this format. - * - * @method setRules - * @param {String} rules Valid elements rules string. - */ - setRules: function(rules) { - schema.setValidElements(rules); - }, - - onPreProcess: function(args) { - if (editor) { - editor.fire('PreProcess', args); - } - }, - - onPostProcess: function(args) { - if (editor) { - editor.fire('PostProcess', args); - } - } - }; - }; -}); - -// Included from: js/tinymce/classes/dom/TridentSelection.js - -/** - * TridentSelection.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * Selection class for old explorer versions. This one fakes the - * native selection object available on modern browsers. - * - * @class tinymce.dom.TridentSelection - */ -define("tinymce/dom/TridentSelection", [], function() { - function Selection(selection) { - var self = this, dom = selection.dom, FALSE = false; - - function getPosition(rng, start) { - var checkRng, startIndex = 0, endIndex, inside, - children, child, offset, index, position = -1, parent; - - // Setup test range, collapse it and get the parent - checkRng = rng.duplicate(); - checkRng.collapse(start); - parent = checkRng.parentElement(); - - // Check if the selection is within the right document - if (parent.ownerDocument !== selection.dom.doc) { - return; - } - - // IE will report non editable elements as it's parent so look for an editable one - while (parent.contentEditable === "false") { - parent = parent.parentNode; - } - - // If parent doesn't have any children then return that we are inside the element - if (!parent.hasChildNodes()) { - return {node: parent, inside: 1}; - } - - // Setup node list and endIndex - children = parent.children; - endIndex = children.length - 1; - - // Perform a binary search for the position - while (startIndex <= endIndex) { - index = Math.floor((startIndex + endIndex) / 2); - - // Move selection to node and compare the ranges - child = children[index]; - checkRng.moveToElementText(child); - position = checkRng.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', rng); - - // Before/after or an exact match - if (position > 0) { - endIndex = index - 1; - } else if (position < 0) { - startIndex = index + 1; - } else { - return {node: child}; - } - } - - // Check if child position is before or we didn't find a position - if (position < 0) { - // No element child was found use the parent element and the offset inside that - if (!child) { - checkRng.moveToElementText(parent); - checkRng.collapse(true); - child = parent; - inside = true; - } else { - checkRng.collapse(false); - } - - // Walk character by character in text node until we hit the selected range endpoint, - // hit the end of document or parent isn't the right one - // We need to walk char by char since rng.text or rng.htmlText will trim line endings - offset = 0; - while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) { - if (checkRng.move('character', 1) === 0 || parent != checkRng.parentElement()) { - break; - } - - offset++; - } - } else { - // Child position is after the selection endpoint - checkRng.collapse(true); - - // Walk character by character in text node until we hit the selected range endpoint, hit - // the end of document or parent isn't the right one - offset = 0; - while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) { - if (checkRng.move('character', -1) === 0 || parent != checkRng.parentElement()) { - break; - } - - offset++; - } - } - - return {node: child, position: position, offset: offset, inside: inside}; - } - - // Returns a W3C DOM compatible range object by using the IE Range API - function getRange() { - var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed, tmpRange, element2, bookmark; - - // If selection is outside the current document just return an empty range - element = ieRange.item ? ieRange.item(0) : ieRange.parentElement(); - if (element.ownerDocument != dom.doc) { - return domRange; - } - - collapsed = selection.isCollapsed(); - - // Handle control selection - if (ieRange.item) { - domRange.setStart(element.parentNode, dom.nodeIndex(element)); - domRange.setEnd(domRange.startContainer, domRange.startOffset + 1); - - return domRange; - } - - function findEndPoint(start) { - var endPoint = getPosition(ieRange, start), container, offset, textNodeOffset = 0, sibling, undef, nodeValue; - - container = endPoint.node; - offset = endPoint.offset; - - if (endPoint.inside && !container.hasChildNodes()) { - domRange[start ? 'setStart' : 'setEnd'](container, 0); - return; - } - - if (offset === undef) { - domRange[start ? 'setStartBefore' : 'setEndAfter'](container); - return; - } - - if (endPoint.position < 0) { - sibling = endPoint.inside ? container.firstChild : container.nextSibling; - - if (!sibling) { - domRange[start ? 'setStartAfter' : 'setEndAfter'](container); - return; - } - - if (!offset) { - if (sibling.nodeType == 3) { - domRange[start ? 'setStart' : 'setEnd'](sibling, 0); - } else { - domRange[start ? 'setStartBefore' : 'setEndBefore'](sibling); - } - - return; - } - - // Find the text node and offset - while (sibling) { - nodeValue = sibling.nodeValue; - textNodeOffset += nodeValue.length; - - // We are at or passed the position we where looking for - if (textNodeOffset >= offset) { - container = sibling; - textNodeOffset -= offset; - textNodeOffset = nodeValue.length - textNodeOffset; - break; - } - - sibling = sibling.nextSibling; - } - } else { - // Find the text node and offset - sibling = container.previousSibling; - - if (!sibling) { - return domRange[start ? 'setStartBefore' : 'setEndBefore'](container); - } - - // If there isn't any text to loop then use the first position - if (!offset) { - if (container.nodeType == 3) { - domRange[start ? 'setStart' : 'setEnd'](sibling, container.nodeValue.length); - } else { - domRange[start ? 'setStartAfter' : 'setEndAfter'](sibling); - } - - return; - } - - while (sibling) { - textNodeOffset += sibling.nodeValue.length; - - // We are at or passed the position we where looking for - if (textNodeOffset >= offset) { - container = sibling; - textNodeOffset -= offset; - break; - } - - sibling = sibling.previousSibling; - } - } - - domRange[start ? 'setStart' : 'setEnd'](container, textNodeOffset); - } - - try { - // Find start point - findEndPoint(true); - - // Find end point if needed - if (!collapsed) { - findEndPoint(); - } - } catch (ex) { - // IE has a nasty bug where text nodes might throw "invalid argument" when you - // access the nodeValue or other properties of text nodes. This seems to happend when - // text nodes are split into two nodes by a delete/backspace call. So lets detect it and try to fix it. - if (ex.number == -2147024809) { - // Get the current selection - bookmark = self.getBookmark(2); - - // Get start element - tmpRange = ieRange.duplicate(); - tmpRange.collapse(true); - element = tmpRange.parentElement(); - - // Get end element - if (!collapsed) { - tmpRange = ieRange.duplicate(); - tmpRange.collapse(false); - element2 = tmpRange.parentElement(); - element2.innerHTML = element2.innerHTML; - } - - // Remove the broken elements - element.innerHTML = element.innerHTML; - - // Restore the selection - self.moveToBookmark(bookmark); - - // Since the range has moved we need to re-get it - ieRange = selection.getRng(); - - // Find start point - findEndPoint(true); - - // Find end point if needed - if (!collapsed) { - findEndPoint(); - } - } else { - throw ex; // Throw other errors - } - } - - return domRange; - } - - this.getBookmark = function(type) { - var rng = selection.getRng(), bookmark = {}; - - function getIndexes(node) { - var parent, root, children, i, indexes = []; - - parent = node.parentNode; - root = dom.getRoot().parentNode; - - while (parent != root && parent.nodeType !== 9) { - children = parent.children; - - i = children.length; - while (i--) { - if (node === children[i]) { - indexes.push(i); - break; - } - } - - node = parent; - parent = parent.parentNode; - } - - return indexes; - } - - function getBookmarkEndPoint(start) { - var position; - - position = getPosition(rng, start); - if (position) { - return { - position: position.position, - offset: position.offset, - indexes: getIndexes(position.node), - inside: position.inside - }; - } - } - - // Non ubstructive bookmark - if (type === 2) { - // Handle text selection - if (!rng.item) { - bookmark.start = getBookmarkEndPoint(true); - - if (!selection.isCollapsed()) { - bookmark.end = getBookmarkEndPoint(); - } - } else { - bookmark.start = {ctrl: true, indexes: getIndexes(rng.item(0))}; - } - } - - return bookmark; - }; - - this.moveToBookmark = function(bookmark) { - var rng, body = dom.doc.body; - - function resolveIndexes(indexes) { - var node, i, idx, children; - - node = dom.getRoot(); - for (i = indexes.length - 1; i >= 0; i--) { - children = node.children; - idx = indexes[i]; - - if (idx <= children.length - 1) { - node = children[idx]; - } - } - - return node; - } - - function setBookmarkEndPoint(start) { - var endPoint = bookmark[start ? 'start' : 'end'], moveLeft, moveRng, undef, offset; - - if (endPoint) { - moveLeft = endPoint.position > 0; - - moveRng = body.createTextRange(); - moveRng.moveToElementText(resolveIndexes(endPoint.indexes)); - - offset = endPoint.offset; - if (offset !== undef) { - moveRng.collapse(endPoint.inside || moveLeft); - moveRng.moveStart('character', moveLeft ? -offset : offset); - } else { - moveRng.collapse(start); - } - - rng.setEndPoint(start ? 'StartToStart' : 'EndToStart', moveRng); - - if (start) { - rng.collapse(true); - } - } - } - - if (bookmark.start) { - if (bookmark.start.ctrl) { - rng = body.createControlRange(); - rng.addElement(resolveIndexes(bookmark.start.indexes)); - rng.select(); - } else { - rng = body.createTextRange(); - setBookmarkEndPoint(true); - setBookmarkEndPoint(); - rng.select(); - } - } - }; - - this.addRange = function(rng) { - var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, sibling, - doc = selection.dom.doc, body = doc.body, nativeRng, ctrlElm; - - function setEndPoint(start) { - var container, offset, marker, tmpRng, nodes; - - marker = dom.create('a'); - container = start ? startContainer : endContainer; - offset = start ? startOffset : endOffset; - tmpRng = ieRng.duplicate(); - - if (container == doc || container == doc.documentElement) { - container = body; - offset = 0; - } - - if (container.nodeType == 3) { - container.parentNode.insertBefore(marker, container); - tmpRng.moveToElementText(marker); - tmpRng.moveStart('character', offset); - dom.remove(marker); - ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng); - } else { - nodes = container.childNodes; - - if (nodes.length) { - if (offset >= nodes.length) { - dom.insertAfter(marker, nodes[nodes.length - 1]); - } else { - container.insertBefore(marker, nodes[offset]); - } - - tmpRng.moveToElementText(marker); - } else if (container.canHaveHTML) { - // Empty node selection for example|
would become this:|
- sibling = startContainer.previousSibling; - if (sibling && !sibling.hasChildNodes() && dom.isBlock(sibling)) { - sibling.innerHTML = ''; - } else { - sibling = null; - } - - startContainer.innerHTML = ''; - ieRng.moveToElementText(startContainer.lastChild); - ieRng.select(); - dom.doc.selection.clear(); - startContainer.innerHTML = ''; - - if (sibling) { - sibling.innerHTML = ''; - } - return; - } else { - startOffset = dom.nodeIndex(startContainer); - startContainer = startContainer.parentNode; - } - } - - if (startOffset == endOffset - 1) { - try { - ctrlElm = startContainer.childNodes[startOffset]; - ctrlRng = body.createControlRange(); - ctrlRng.addElement(ctrlElm); - ctrlRng.select(); - - // Check if the range produced is on the correct element and is a control range - // On IE 8 it will select the parent contentEditable container if you select an inner element see: #5398 - nativeRng = selection.getRng(); - if (nativeRng.item && ctrlElm === nativeRng.item(0)) { - return; - } - } catch (ex) { - // Ignore - } - } - } - - // Set start/end point of selection - setEndPoint(true); - setEndPoint(); - - // Select the new range and scroll it into view - ieRng.select(); - }; - - // Expose range method - this.getRangeAt = getRange; - } - - return Selection; -}); - -// Included from: js/tinymce/classes/util/VK.js - -/** - * VK.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This file exposes a set of the common KeyCodes for use. Please grow it as needed. - */ -define("tinymce/util/VK", [ - "tinymce/Env" -], function(Env) { - return { - BACKSPACE: 8, - DELETE: 46, - DOWN: 40, - ENTER: 13, - LEFT: 37, - RIGHT: 39, - SPACEBAR: 32, - TAB: 9, - UP: 38, - - modifierPressed: function(e) { - return e.shiftKey || e.ctrlKey || e.altKey; - }, - - metaKeyPressed: function(e) { - // Check if ctrl or meta key is pressed also check if alt is false for Polish users - return (Env.mac ? e.metaKey : e.ctrlKey) && !e.altKey; - } - }; -}); - -// Included from: js/tinymce/classes/dom/ControlSelection.js - -/** - * ControlSelection.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles control selection of elements. Controls are elements - * that can be resized and needs to be selected as a whole. It adds custom resize handles - * to all browser engines that support properly disabling the built in resize logic. - * - * @class tinymce.dom.ControlSelection - */ -define("tinymce/dom/ControlSelection", [ - "tinymce/util/VK", - "tinymce/util/Tools", - "tinymce/Env" -], function(VK, Tools, Env) { - return function(selection, editor) { - var dom = editor.dom, each = Tools.each; - var selectedElm, selectedElmGhost, resizeHandles, selectedHandle, lastMouseDownEvent; - var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted; - var width, height, editableDoc = editor.getDoc(), rootDocument = document, isIE = Env.ie && Env.ie < 11; - - // Details about each resize handle how to scale etc - resizeHandles = { - // Name: x multiplier, y multiplier, delta size x, delta size y - n: [0.5, 0, 0, -1], - e: [1, 0.5, 1, 0], - s: [0.5, 1, 0, 1], - w: [0, 0.5, -1, 0], - nw: [0, 0, -1, -1], - ne: [1, 0, 1, -1], - se: [1, 1, 1, 1], - sw: [0, 1, -1, 1] - }; - - // Add CSS for resize handles, cloned element and selected - var rootClass = '.mce-content-body'; - editor.contentStyles.push( - rootClass + ' div.mce-resizehandle {' + - 'position: absolute;' + - 'border: 1px solid black;' + - 'background: #FFF;' + - 'width: 5px;' + - 'height: 5px;' + - 'z-index: 10000' + - '}' + - rootClass + ' .mce-resizehandle:hover {' + - 'background: #000' + - '}' + - rootClass + ' img[data-mce-selected], hr[data-mce-selected] {' + - 'outline: 1px solid black;' + - 'resize: none' + // Have been talks about implementing this in browsers - '}' + - rootClass + ' .mce-clonedresizable {' + - 'position: absolute;' + - (Env.gecko ? '' : 'outline: 1px dashed black;') + // Gecko produces trails while resizing - 'opacity: .5;' + - 'filter: alpha(opacity=50);' + - 'z-index: 10000' + - '}' - ); - - function isResizable(elm) { - var selector = editor.settings.object_resizing; - - if (selector === false || Env.iOS) { - return false; - } - - if (typeof selector != 'string') { - selector = 'table,img,div'; - } - - if (elm.getAttribute('data-mce-resize') === 'false') { - return false; - } - - return editor.dom.is(elm, selector); - } - - function resizeGhostElement(e) { - var deltaX, deltaY; - - // Calc new width/height - deltaX = e.screenX - startX; - deltaY = e.screenY - startY; - - // Calc new size - width = deltaX * selectedHandle[2] + startW; - height = deltaY * selectedHandle[3] + startH; - - // Never scale down lower than 5 pixels - width = width < 5 ? 5 : width; - height = height < 5 ? 5 : height; - - // Constrain proportions when modifier key is pressed or if the nw, ne, sw, se corners are moved on an image - if (VK.modifierPressed(e) || (selectedElm.nodeName == "IMG" && selectedHandle[2] * selectedHandle[3] !== 0)) { - width = Math.round(height / ratio); - height = Math.round(width * ratio); - } - - // Update ghost size - dom.setStyles(selectedElmGhost, { - width: width, - height: height - }); - - // Update ghost X position if needed - if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) { - dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width)); - } - - // Update ghost Y position if needed - if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) { - dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height)); - } - - if (!resizeStarted) { - editor.fire('ObjectResizeStart', {target: selectedElm, width: startW, height: startH}); - resizeStarted = true; - } - } - - function endGhostResize() { - resizeStarted = false; - - function setSizeProp(name, value) { - if (value) { - // Resize by using style or attribute - if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) { - dom.setStyle(selectedElm, name, value); - } else { - dom.setAttrib(selectedElm, name, value); - } - } - } - - // Set width/height properties - setSizeProp('width', width); - setSizeProp('height', height); - - dom.unbind(editableDoc, 'mousemove', resizeGhostElement); - dom.unbind(editableDoc, 'mouseup', endGhostResize); - - if (rootDocument != editableDoc) { - dom.unbind(rootDocument, 'mousemove', resizeGhostElement); - dom.unbind(rootDocument, 'mouseup', endGhostResize); - } - - // Remove ghost and update resize handle positions - dom.remove(selectedElmGhost); - - if (!isIE || selectedElm.nodeName == "TABLE") { - showResizeRect(selectedElm); - } - - editor.fire('ObjectResized', {target: selectedElm, width: width, height: height}); - editor.nodeChanged(); - } - - function showResizeRect(targetElm, mouseDownHandleName, mouseDownEvent) { - var position, targetWidth, targetHeight, e, rect, offsetParent = editor.getBody(); - - unbindResizeHandleEvents(); - - // Get position and size of target - position = dom.getPos(targetElm, offsetParent); - selectedElmX = position.x; - selectedElmY = position.y; - rect = targetElm.getBoundingClientRect(); // Fix for Gecko offsetHeight for table with caption - targetWidth = rect.width || (rect.right - rect.left); - targetHeight = rect.height || (rect.bottom - rect.top); - - // Reset width/height if user selects a new image/table - if (selectedElm != targetElm) { - detachResizeStartListener(); - selectedElm = targetElm; - width = height = 0; - } - - // Makes it possible to disable resizing - e = editor.fire('ObjectSelected', {target: targetElm}); - - if (isResizable(targetElm) && !e.isDefaultPrevented()) { - each(resizeHandles, function(handle, name) { - var handleElm, handlerContainerElm; - - function startDrag(e) { - startX = e.screenX; - startY = e.screenY; - startW = selectedElm.clientWidth; - startH = selectedElm.clientHeight; - ratio = startH / startW; - selectedHandle = handle; - - selectedElmGhost = selectedElm.cloneNode(true); - dom.addClass(selectedElmGhost, 'mce-clonedresizable'); - selectedElmGhost.contentEditable = false; // Hides IE move layer cursor - selectedElmGhost.unSelectabe = true; - dom.setStyles(selectedElmGhost, { - left: selectedElmX, - top: selectedElmY, - margin: 0 - }); - - selectedElmGhost.removeAttribute('data-mce-selected'); - editor.getBody().appendChild(selectedElmGhost); - - dom.bind(editableDoc, 'mousemove', resizeGhostElement); - dom.bind(editableDoc, 'mouseup', endGhostResize); - - if (rootDocument != editableDoc) { - dom.bind(rootDocument, 'mousemove', resizeGhostElement); - dom.bind(rootDocument, 'mouseup', endGhostResize); - } - } - - if (mouseDownHandleName) { - // Drag started by IE native resizestart - if (name == mouseDownHandleName) { - startDrag(mouseDownEvent); - } - - return; - } - - // Get existing or render resize handle - handleElm = dom.get('mceResizeHandle' + name); - if (!handleElm) { - handlerContainerElm = editor.getBody(); - - handleElm = dom.add(handlerContainerElm, 'div', { - id: 'mceResizeHandle' + name, - 'data-mce-bogus': true, - 'class': 'mce-resizehandle', - unselectable: true, - style: 'cursor:' + name + '-resize; margin:0; padding:0' - }); - - // Hides IE move layer cursor - // If we set it on Chrome we get this wounderful bug: #6725 - if (Env.ie) { - handleElm.contentEditable = false; - } - } else { - dom.show(handleElm); - } - - if (!handle.elm) { - dom.bind(handleElm, 'mousedown', function(e) { - e.stopImmediatePropagation(); - e.preventDefault(); - startDrag(e); - }); - - handle.elm = handleElm; - } - - /* - var halfHandleW = handleElm.offsetWidth / 2; - var halfHandleH = handleElm.offsetHeight / 2; - - // Position element - dom.setStyles(handleElm, { - left: Math.floor((targetWidth * handle[0] + selectedElmX) - halfHandleW + (handle[2] * halfHandleW)), - top: Math.floor((targetHeight * handle[1] + selectedElmY) - halfHandleH + (handle[3] * halfHandleH)) - }); - */ - - // Position element - dom.setStyles(handleElm, { - left: (targetWidth * handle[0] + selectedElmX) - (handleElm.offsetWidth / 2), - top: (targetHeight * handle[1] + selectedElmY) - (handleElm.offsetHeight / 2) - }); - }); - } else { - hideResizeRect(); - } - - selectedElm.setAttribute('data-mce-selected', '1'); - } - - function hideResizeRect() { - var name, handleElm; - - unbindResizeHandleEvents(); - - if (selectedElm) { - selectedElm.removeAttribute('data-mce-selected'); - } - - for (name in resizeHandles) { - handleElm = dom.get('mceResizeHandle' + name); - if (handleElm) { - dom.unbind(handleElm); - dom.remove(handleElm); - } - } - } - - function updateResizeRect(e) { - var controlElm; - - function isChildOrEqual(node, parent) { - if (node) { - do { - if (node === parent) { - return true; - } - } while ((node = node.parentNode)); - } - } - - // Remove data-mce-selected from all elements since they might have been copied using Ctrl+c/v - each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function(img) { - img.removeAttribute('data-mce-selected'); - }); - - controlElm = e.type == 'mousedown' ? e.target : selection.getNode(); - controlElm = dom.getParent(controlElm, isIE ? 'table' : 'table,img,hr'); - - if (isChildOrEqual(controlElm, editor.getBody())) { - disableGeckoResize(); - - if (isChildOrEqual(selection.getStart(), controlElm) && isChildOrEqual(selection.getEnd(), controlElm)) { - if (!isIE || (controlElm != selection.getStart() && selection.getStart().nodeName !== 'IMG')) { - showResizeRect(controlElm); - return; - } - } - } - - hideResizeRect(); - } - - function attachEvent(elm, name, func) { - if (elm && elm.attachEvent) { - elm.attachEvent('on' + name, func); - } - } - - function detachEvent(elm, name, func) { - if (elm && elm.detachEvent) { - elm.detachEvent('on' + name, func); - } - } - - function resizeNativeStart(e) { - var target = e.srcElement, pos, name, corner, cornerX, cornerY, relativeX, relativeY; - - pos = target.getBoundingClientRect(); - relativeX = lastMouseDownEvent.clientX - pos.left; - relativeY = lastMouseDownEvent.clientY - pos.top; - - // Figure out what corner we are draging on - for (name in resizeHandles) { - corner = resizeHandles[name]; - - cornerX = target.offsetWidth * corner[0]; - cornerY = target.offsetHeight * corner[1]; - - if (Math.abs(cornerX - relativeX) < 8 && Math.abs(cornerY - relativeY) < 8) { - selectedHandle = corner; - break; - } - } - - // Remove native selection and let the magic begin - resizeStarted = true; - editor.getDoc().selection.empty(); - showResizeRect(target, name, lastMouseDownEvent); - } - - function nativeControlSelect(e) { - var target = e.srcElement; - - if (target != selectedElm) { - detachResizeStartListener(); - - if (target.id.indexOf('mceResizeHandle') === 0) { - e.returnValue = false; - return; - } - - if (target.nodeName == 'IMG' || target.nodeName == 'TABLE') { - hideResizeRect(); - selectedElm = target; - attachEvent(target, 'resizestart', resizeNativeStart); - } - } - } - - function detachResizeStartListener() { - detachEvent(selectedElm, 'resizestart', resizeNativeStart); - } - - function unbindResizeHandleEvents() { - for (var name in resizeHandles) { - var handle = resizeHandles[name]; - - if (handle.elm) { - dom.unbind(handle.elm); - delete handle.elm; - } - } - } - - function disableGeckoResize() { - try { - // Disable object resizing on Gecko - editor.getDoc().execCommand('enableObjectResizing', false, false); - } catch (ex) { - // Ignore - } - } - - function controlSelect(elm) { - var ctrlRng; - - if (!isIE) { - return; - } - - ctrlRng = editableDoc.body.createControlRange(); - - try { - ctrlRng.addElement(elm); - ctrlRng.select(); - return true; - } catch (ex) { - // Ignore since the element can't be control selected for example a P tag - } - } - - editor.on('init', function() { - if (isIE) { - // Hide the resize rect on resize and reselect the image - editor.on('ObjectResized', function(e) { - if (e.target.nodeName != 'TABLE') { - hideResizeRect(); - controlSelect(e.target); - } - }); - - attachEvent(editor.getBody(), 'controlselect', nativeControlSelect); - - editor.on('mousedown', function(e) { - lastMouseDownEvent = e; - }); - } else { - disableGeckoResize(); - - if (Env.ie >= 11) { - // TODO: Drag/drop doesn't work - editor.on('mouseup', function(e) { - var nodeName = e.target.nodeName; - - if (/^(TABLE|IMG|HR)$/.test(nodeName)) { - editor.selection.select(e.target, nodeName == 'TABLE'); - editor.nodeChanged(); - } - }); - - editor.dom.bind(editor.getBody(), 'mscontrolselect', function(e) { - if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) { - e.preventDefault(); - - // This moves the selection from being a control selection to a text like selection like in WebKit #6753 - // TODO: Fix this the day IE works like other browsers without this nasty native ugly control selections. - if (e.target.tagName == 'IMG') { - window.setTimeout(function() { - editor.selection.select(e.target); - }, 0); - } - } - }); - } - } - - editor.on('nodechange mousedown mouseup ResizeEditor', updateResizeRect); - - // Update resize rect while typing in a table - editor.on('keydown keyup', function(e) { - if (selectedElm && selectedElm.nodeName == "TABLE") { - updateResizeRect(e); - } - }); - - // Hide rect on focusout since it would float on top of windows otherwise - //editor.on('focusout', hideResizeRect); - }); - - editor.on('remove', unbindResizeHandleEvents); - - function destroy() { - selectedElm = selectedElmGhost = null; - - if (isIE) { - detachResizeStartListener(); - detachEvent(editor.getBody(), 'controlselect', nativeControlSelect); - } - } - - return { - isResizable: isResizable, - showResizeRect: showResizeRect, - hideResizeRect: hideResizeRect, - updateResizeRect: updateResizeRect, - controlSelect: controlSelect, - destroy: destroy - }; - }; -}); - -// Included from: js/tinymce/classes/dom/RangeUtils.js - -/** - * Range.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * RangeUtils - * - * @class tinymce.dom.RangeUtils - * @private - */ -define("tinymce/dom/RangeUtils", [ - "tinymce/util/Tools", - "tinymce/dom/TreeWalker" -], function(Tools, TreeWalker) { - var each = Tools.each; - - function RangeUtils(dom) { - /** - * Walks the specified range like object and executes the callback for each sibling collection it finds. - * - * @method walk - * @param {Object} rng Range like object. - * @param {function} callback Callback function to execute for each sibling collection. - */ - this.walk = function(rng, callback) { - var startContainer = rng.startContainer, - startOffset = rng.startOffset, - endContainer = rng.endContainer, - endOffset = rng.endOffset, - ancestor, startPoint, - endPoint, node, parent, siblings, nodes; - - // Handle table cell selection the table plugin enables - // you to fake select table cells and perform formatting actions on them - nodes = dom.select('td.mce-item-selected,th.mce-item-selected'); - if (nodes.length > 0) { - each(nodes, function(node) { - callback([node]); - }); - - return; - } - - /** - * Excludes start/end text node if they are out side the range - * - * @private - * @param {Array} nodes Nodes to exclude items from. - * @return {Array} Array with nodes excluding the start/end container if needed. - */ - function exclude(nodes) { - var node; - - // First node is excluded - node = nodes[0]; - if (node.nodeType === 3 && node === startContainer && startOffset >= node.nodeValue.length) { - nodes.splice(0, 1); - } - - // Last node is excluded - node = nodes[nodes.length - 1]; - if (endOffset === 0 && nodes.length > 0 && node === endContainer && node.nodeType === 3) { - nodes.splice(nodes.length - 1, 1); - } - - return nodes; - } - - /** - * Collects siblings - * - * @private - * @param {Node} node Node to collect siblings from. - * @param {String} name Name of the sibling to check for. - * @return {Array} Array of collected siblings. - */ - function collectSiblings(node, name, end_node) { - var siblings = []; - - for (; node && node != end_node; node = node[name]) { - siblings.push(node); - } - - return siblings; - } - - /** - * Find an end point this is the node just before the common ancestor root. - * - * @private - * @param {Node} node Node to start at. - * @param {Node} root Root/ancestor element to stop just before. - * @return {Node} Node just before the root element. - */ - function findEndPoint(node, root) { - do { - if (node.parentNode == root) { - return node; - } - - node = node.parentNode; - } while(node); - } - - function walkBoundary(start_node, end_node, next) { - var siblingName = next ? 'nextSibling' : 'previousSibling'; - - for (node = start_node, parent = node.parentNode; node && node != end_node; node = parent) { - parent = node.parentNode; - siblings = collectSiblings(node == start_node ? node : node[siblingName], siblingName); - - if (siblings.length) { - if (!next) { - siblings.reverse(); - } - - callback(exclude(siblings)); - } - } - } - - // If index based start position then resolve it - if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) { - startContainer = startContainer.childNodes[startOffset]; - } - - // If index based end position then resolve it - if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) { - endContainer = endContainer.childNodes[Math.min(endOffset - 1, endContainer.childNodes.length - 1)]; - } - - // Same container - if (startContainer == endContainer) { - return callback(exclude([startContainer])); - } - - // Find common ancestor and end points - ancestor = dom.findCommonAncestor(startContainer, endContainer); - - // Process left side - for (node = startContainer; node; node = node.parentNode) { - if (node === endContainer) { - return walkBoundary(startContainer, ancestor, true); - } - - if (node === ancestor) { - break; - } - } - - // Process right side - for (node = endContainer; node; node = node.parentNode) { - if (node === startContainer) { - return walkBoundary(endContainer, ancestor); - } - - if (node === ancestor) { - break; - } - } - - // Find start/end point - startPoint = findEndPoint(startContainer, ancestor) || startContainer; - endPoint = findEndPoint(endContainer, ancestor) || endContainer; - - // Walk left leaf - walkBoundary(startContainer, startPoint, true); - - // Walk the middle from start to end point - siblings = collectSiblings( - startPoint == startContainer ? startPoint : startPoint.nextSibling, - 'nextSibling', - endPoint == endContainer ? endPoint.nextSibling : endPoint - ); - - if (siblings.length) { - callback(exclude(siblings)); - } - - // Walk right leaf - walkBoundary(endContainer, endPoint); - }; - - /** - * Splits the specified range at it's start/end points. - * - * @private - * @param {Range/RangeObject} rng Range to split. - * @return {Object} Range position object. - */ - this.split = function(rng) { - var startContainer = rng.startContainer, - startOffset = rng.startOffset, - endContainer = rng.endContainer, - endOffset = rng.endOffset; - - function splitText(node, offset) { - return node.splitText(offset); - } - - // Handle single text node - if (startContainer == endContainer && startContainer.nodeType == 3) { - if (startOffset > 0 && startOffset < startContainer.nodeValue.length) { - endContainer = splitText(startContainer, startOffset); - startContainer = endContainer.previousSibling; - - if (endOffset > startOffset) { - endOffset = endOffset - startOffset; - startContainer = endContainer = splitText(endContainer, endOffset).previousSibling; - endOffset = endContainer.nodeValue.length; - startOffset = 0; - } else { - endOffset = 0; - } - } - } else { - // Split startContainer text node if needed - if (startContainer.nodeType == 3 && startOffset > 0 && startOffset < startContainer.nodeValue.length) { - startContainer = splitText(startContainer, startOffset); - startOffset = 0; - } - - // Split endContainer text node if needed - if (endContainer.nodeType == 3 && endOffset > 0 && endOffset < endContainer.nodeValue.length) { - endContainer = splitText(endContainer, endOffset).previousSibling; - endOffset = endContainer.nodeValue.length; - } - } - - return { - startContainer: startContainer, - startOffset: startOffset, - endContainer: endContainer, - endOffset: endOffset - }; - }; - - /** - * Normalizes the specified range by finding the closest best suitable caret location. - * - * @private - * @param {Range} rng Range to normalize. - * @return {Boolean} True/false if the specified range was normalized or not. - */ - this.normalize = function(rng) { - var normalized, collapsed; - - function normalizeEndPoint(start) { - var container, offset, walker, body = dom.getRoot(), node, nonEmptyElementsMap, nodeName; - var directionLeft, isAfterNode; - - function hasBrBeforeAfter(node, left) { - var walker = new TreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || body); - - while ((node = walker[left ? 'prev' : 'next']())) { - if (node.nodeName === "BR") { - return true; - } - } - } - - function isPrevNode(node, name) { - return node.previousSibling && node.previousSibling.nodeName == name; - } - - // Walks the dom left/right to find a suitable text node to move the endpoint into - // It will only walk within the current parent block or body and will stop if it hits a block or a BR/IMG - function findTextNodeRelative(left, startNode) { - var walker, lastInlineElement, parentBlockContainer; - - startNode = startNode || container; - parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body; - - // Lean left before the BR element if it's the only BR within a block element. Gecko bug: #6680 - // This:
|
|
x|
]
- rng.moveToElementText(rng2.parentElement()); - if (rng.compareEndPoints('StartToEnd', rng2) === 0) { - rng2.move('character', -1); - } - - rng2.pasteHTML('' + chr + ''); - } - } catch (ex) { - // IE might throw unspecified error so lets ignore it - return null; - } - } else { - // Control selection - element = rng.item(0); - name = element.nodeName; - - return {name: name, index: findIndex(name, element)}; - } - } else { - element = self.getNode(); - name = element.nodeName; - if (name == 'IMG') { - return {name: name, index: findIndex(name, element)}; - } - - // W3C method - rng2 = normalizeTableCellSelection(rng.cloneRange()); - - // Insert end marker - if (!collapsed) { - rng2.collapse(false); - rng2.insertNode(dom.create('span', {'data-mce-type': "bookmark", id: id + '_end', style: styles}, chr)); - } - - rng = normalizeTableCellSelection(rng); - rng.collapse(true); - rng.insertNode(dom.create('span', {'data-mce-type': "bookmark", id: id + '_start', style: styles}, chr)); - } - - self.moveToBookmark({id: id, keep: 1}); - - return {id: id}; - }, - - /** - * Restores the selection to the specified bookmark. - * - * @method moveToBookmark - * @param {Object} bookmark Bookmark to restore selection from. - * @return {Boolean} true/false if it was successful or not. - * @example - * // Stores a bookmark of the current selection - * var bm = tinymce.activeEditor.selection.getBookmark(); - * - * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content'); - * - * // Restore the selection bookmark - * tinymce.activeEditor.selection.moveToBookmark(bm); - */ - moveToBookmark: function(bookmark) { - var self = this, dom = self.dom, rng, root, startContainer, endContainer, startOffset, endOffset; - - function setEndPoint(start) { - var point = bookmark[start ? 'start' : 'end'], i, node, offset, children; - - if (point) { - offset = point[0]; - - // Find container node - for (node = root, i = point.length - 1; i >= 1; i--) { - children = node.childNodes; - - if (point[i] > children.length - 1) { - return; - } - - node = children[point[i]]; - } - - // Move text offset to best suitable location - if (node.nodeType === 3) { - offset = Math.min(point[0], node.nodeValue.length); - } - - // Move element offset to best suitable location - if (node.nodeType === 1) { - offset = Math.min(point[0], node.childNodes.length); - } - - // Set offset within container node - if (start) { - rng.setStart(node, offset); - } else { - rng.setEnd(node, offset); - } - } - - return true; - } - - function restoreEndPoint(suffix) { - var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep; - - if (marker) { - node = marker.parentNode; - - if (suffix == 'start') { - if (!keep) { - idx = dom.nodeIndex(marker); - } else { - node = marker.firstChild; - idx = 1; - } - - startContainer = endContainer = node; - startOffset = endOffset = idx; - } else { - if (!keep) { - idx = dom.nodeIndex(marker); - } else { - node = marker.firstChild; - idx = 1; - } - - endContainer = node; - endOffset = idx; - } - - if (!keep) { - prev = marker.previousSibling; - next = marker.nextSibling; - - // Remove all marker text nodes - each(grep(marker.childNodes), function(node) { - if (node.nodeType == 3) { - node.nodeValue = node.nodeValue.replace(/\uFEFF/g, ''); - } - }); - - // Remove marker but keep children if for example contents where inserted into the marker - // Also remove duplicated instances of the marker for example by a - // split operation or by WebKit auto split on paste feature - while ((marker = dom.get(bookmark.id + '_' + suffix))) { - dom.remove(marker, 1); - } - - // If siblings are text nodes then merge them unless it's Opera since it some how removes the node - // and we are sniffing since adding a lot of detection code for a browser with 3% of the market - // isn't worth the effort. Sorry, Opera but it's just a fact - if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !isOpera) { - idx = prev.nodeValue.length; - prev.appendData(next.nodeValue); - dom.remove(next); - - if (suffix == 'start') { - startContainer = endContainer = prev; - startOffset = endOffset = idx; - } else { - endContainer = prev; - endOffset = idx; - } - } - } - } - } - - function addBogus(node) { - // Adds a bogus BR element for empty block elements - if (dom.isBlock(node) && !node.innerHTML && !isIE) { - node.innerHTML = '*texttext*
! - // This will reduce the number of wrapper elements that needs to be created - // Move start point up the tree - if (format[0].inline || format[0].block_expand) { - if (!format[0].inline || (startContainer.nodeType != 3 || startOffset === 0)) { - startContainer = findParentContainer(true); - } - - if (!format[0].inline || (endContainer.nodeType != 3 || endOffset === endContainer.nodeValue.length)) { - endContainer = findParentContainer(); - } - } - - // Expand start/end container to matching selector - if (format[0].selector && format[0].expand !== FALSE && !format[0].inline) { - // Find new startContainer/endContainer if there is better one - startContainer = findSelectorEndPoint(startContainer, 'previousSibling'); - endContainer = findSelectorEndPoint(endContainer, 'nextSibling'); - } - - // Expand start/end container to matching block element or text node - if (format[0].block || format[0].selector) { - // Find new startContainer/endContainer if there is better one - startContainer = findBlockEndPoint(startContainer, 'previousSibling'); - endContainer = findBlockEndPoint(endContainer, 'nextSibling'); - - // Non block element then try to expand up the leaf - if (format[0].block) { - if (!isBlock(startContainer)) { - startContainer = findParentContainer(true); - } - - if (!isBlock(endContainer)) { - endContainer = findParentContainer(); - } - } - } - - // Setup index for startContainer - if (startContainer.nodeType == 1) { - startOffset = nodeIndex(startContainer); - startContainer = startContainer.parentNode; - } - - // Setup index for endContainer - if (endContainer.nodeType == 1) { - endOffset = nodeIndex(endContainer) + 1; - endContainer = endContainer.parentNode; - } - - // Return new range like object - return { - startContainer: startContainer, - startOffset: startOffset, - endContainer: endContainer, - endOffset: endOffset - }; - } - - /** - * Removes the specified format for the specified node. It will also remove the node if it doesn't have - * any attributes if the format specifies it to do so. - * - * @private - * @param {Object} format Format object with items to remove from node. - * @param {Object} vars Name/value object with variables to apply to format. - * @param {Node} node Node to remove the format styles on. - * @param {Node} compare_node Optional compare node, if specified the styles will be compared to that node. - * @return {Boolean} True/false if the node was removed or not. - */ - function removeFormat(format, vars, node, compare_node) { - var i, attrs, stylesModified; - - // Check if node matches format - if (!matchName(node, format)) { - return FALSE; - } - - // Should we compare with format attribs and styles - if (format.remove != 'all') { - // Remove styles - each(format.styles, function(value, name) { - value = normalizeStyleValue(replaceVars(value, vars), name); - - // Indexed array - if (typeof(name) === 'number') { - name = value; - compare_node = 0; - } - - if (!compare_node || isEq(getStyle(compare_node, name), value)) { - dom.setStyle(node, name, ''); - } - - stylesModified = 1; - }); - - // Remove style attribute if it's empty - if (stylesModified && dom.getAttrib(node, 'style') === '') { - node.removeAttribute('style'); - node.removeAttribute('data-mce-style'); - } - - // Remove attributes - each(format.attributes, function(value, name) { - var valueOut; - - value = replaceVars(value, vars); - - // Indexed array - if (typeof(name) === 'number') { - name = value; - compare_node = 0; - } - - if (!compare_node || isEq(dom.getAttrib(compare_node, name), value)) { - // Keep internal classes - if (name == 'class') { - value = dom.getAttrib(node, name); - if (value) { - // Build new class value where everything is removed except the internal prefixed classes - valueOut = ''; - each(value.split(/\s+/), function(cls) { - if (/mce\w+/.test(cls)) { - valueOut += (valueOut ? ' ' : '') + cls; - } - }); - - // We got some internal classes left - if (valueOut) { - dom.setAttrib(node, name, valueOut); - return; - } - } - } - - // IE6 has a bug where the attribute doesn't get removed correctly - if (name == "class") { - node.removeAttribute('className'); - } - - // Remove mce prefixed attributes - if (MCE_ATTR_RE.test(name)) { - node.removeAttribute('data-mce-' + name); - } - - node.removeAttribute(name); - } - }); - - // Remove classes - each(format.classes, function(value) { - value = replaceVars(value, vars); - - if (!compare_node || dom.hasClass(compare_node, value)) { - dom.removeClass(node, value); - } - }); - - // Check for non internal attributes - attrs = dom.getAttribs(node); - for (i = 0; i < attrs.length; i++) { - if (attrs[i].nodeName.indexOf('_') !== 0) { - return FALSE; - } - } - } - - // Remove the inline child if it's empty for example or - if (format.remove != 'none') { - removeNode(node, format); - return TRUE; - } - } - - /** - * Removes the node and wrap it's children in paragraphs before doing so or - * appends BR elements to the beginning/end of the block element if forcedRootBlocks is disabled. - * - * If the div in the node below gets removed: - * text|
- formatNode.parentNode.replaceChild(caretContainer, formatNode); - } else { - // Insert caret container after the formated node - dom.insertAfter(caretContainer, formatNode); - } - - // Move selection to text node - selection.setCursorLocation(node, 1); - - // If the formatNode is empty, we can remove it safely. - if (dom.isEmpty(formatNode)) { - dom.remove(formatNode); - } - } - } - - // Checks if the parent caret container node isn't empty if that is the case it - // will remove the bogus state on all children that isn't empty - function unmarkBogusCaretParents() { - var caretContainer; - - caretContainer = getParentCaretContainer(selection.getStart()); - if (caretContainer && !dom.isEmpty(caretContainer)) { - walk(caretContainer, function(node) { - if (node.nodeType == 1 && node.id !== caretContainerId && !dom.isEmpty(node)) { - dom.setAttrib(node, 'data-mce-bogus', null); - } - }, 'childNodes'); - } - } - - // Only bind the caret events once - if (!ed._hasCaretEvents) { - // Mark current caret container elements as bogus when getting the contents so we don't end up with empty elements - markCaretContainersBogus = function() { - var nodes = [], i; - - if (isCaretContainerEmpty(getParentCaretContainer(selection.getStart()), nodes)) { - // Mark children - i = nodes.length; - while (i--) { - dom.setAttrib(nodes[i], 'data-mce-bogus', '1'); - } - } - }; - - disableCaretContainer = function(e) { - var keyCode = e.keyCode; - - removeCaretContainer(); - - // Remove caret container on keydown and it's a backspace, enter or left/right arrow keys - if (keyCode == 8 || keyCode == 37 || keyCode == 39) { - removeCaretContainer(getParentCaretContainer(selection.getStart())); - } - - unmarkBogusCaretParents(); - }; - - // Remove bogus state if they got filled by contents using editor.selection.setContent - ed.on('SetContent', function(e) { - if (e.selection) { - unmarkBogusCaretParents(); - } - }); - ed._hasCaretEvents = true; - } - - // Do apply or remove caret format - if (type == "apply") { - applyCaretFormat(); - } else { - removeCaretFormat(); - } - } - - /** - * Moves the start to the first suitable text node. - */ - function moveStart(rng) { - var container = rng.startContainer, - offset = rng.startOffset, isAtEndOfText, - walker, node, nodes, tmpNode; - - // Convert text node into index if possible - if (container.nodeType == 3 && offset >= container.nodeValue.length) { - // Get the parent container location and walk from there - offset = nodeIndex(container); - container = container.parentNode; - isAtEndOfText = true; - } - - // Move startContainer/startOffset in to a suitable node - if (container.nodeType == 1) { - nodes = container.childNodes; - container = nodes[Math.min(offset, nodes.length - 1)]; - walker = new TreeWalker(container, dom.getParent(container, dom.isBlock)); - - // If offset is at end of the parent node walk to the next one - if (offset > nodes.length - 1 || isAtEndOfText) { - walker.next(); - } - - for (node = walker.current(); node; node = walker.next()) { - if (node.nodeType == 3 && !isWhiteSpaceNode(node)) { - // IE has a "neat" feature where it moves the start node into the closest element - // we can avoid this by inserting an element before it and then remove it after we set the selection - tmpNode = dom.create('a', null, INVISIBLE_CHAR); - node.parentNode.insertBefore(tmpNode, node); - - // Set selection and remove tmpNode - rng.setStart(node, 0); - selection.setRng(rng); - dom.remove(tmpNode); - - return; - } - } - } - } - }; -}); - -// Included from: js/tinymce/classes/UndoManager.js - -/** - * UndoManager.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles the undo/redo history levels for the editor. Since the build in undo/redo has major drawbacks a custom one was needed. - * - * @class tinymce.UndoManager - */ -define("tinymce/UndoManager", [ - "tinymce/Env", - "tinymce/util/Tools" -], function(Env, Tools) { - var trim = Tools.trim, trimContentRegExp; - - trimContentRegExp = new RegExp([ - ']+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\\/span>', // Trim bogus spans like caret containers - 'x
becomes this:x
- function trimInlineElementsOnLeftSideOfBlock(block) { - var node = block, firstChilds = [], i; - - // Find inner most first child ex:*
- while ((node = node.firstChild)) { - if (dom.isBlock(node)) { - return; - } - - if (node.nodeType == 1 && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) { - firstChilds.push(node); - } - } - - i = firstChilds.length; - while (i--) { - node = firstChilds[i]; - if (!node.hasChildNodes() || (node.firstChild == node.lastChild && node.firstChild.nodeValue === '')) { - dom.remove(node); - } else { - // Remove see #5381 - if (node.nodeName == "A" && (node.innerText || node.textContent) === ' ') { - dom.remove(node); - } - } - } - } - - // Moves the caret to a suitable position within the root for example in the first non - // pure whitespace text node or before an image - function moveToCaretPosition(root) { - var walker, node, rng, lastNode = root, tempElm; - - function firstNonWhiteSpaceNodeSibling(node) { - while (node) { - if (node.nodeType == 1 || (node.nodeType == 3 && node.data && /[\r\n\s]/.test(node.data))) { - return node; - } - - node = node.nextSibling; - } - } - - // Old IE versions doesn't properly render blocks with br elements in them - // For exampletext|
text|text2
|
- rng = selection.getRng(); - var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null); - var body = editor.getBody(); - if (caretElement === body && selection.isCollapsed()) { - if (dom.isBlock(body.firstChild) && dom.isEmpty(body.firstChild)) { - rng = dom.createRng(); - rng.setStart(body.firstChild, 0); - rng.setEnd(body.firstChild, 0); - selection.setRng(rng); - } - } - - // Insert node maker where we will insert the new HTML and get it's parent - if (!selection.isCollapsed()) { - editor.getDoc().execCommand('Delete', false, null); - } - - parentNode = selection.getNode(); - - // Parse the fragment within the context of the parent node - var parserArgs = {context: parentNode.nodeName.toLowerCase()}; - fragment = parser.parse(value, parserArgs); - - // Move the caret to a more suitable location - node = fragment.lastChild; - if (node.attr('id') == 'mce_marker') { - marker = node; - - for (node = node.prev; node; node = node.walk(true)) { - if (node.type == 3 || !dom.isBlock(node.name)) { - node.parent.insert(marker, node, node.name === 'br'); - break; - } - } - } - - // If parser says valid we can insert the contents into that parent - if (!parserArgs.invalid) { - value = serializer.serialize(fragment); - - // Check if parent is empty or only has one BR element then set the innerHTML of that parent - node = parentNode.firstChild; - node2 = parentNode.lastChild; - if (!node || (node === node2 && node.nodeName === 'BR')) { - dom.setHTML(parentNode, value); - } else { - selection.setContent(value); - } - } else { - // If the fragment was invalid within that context then we need - // to parse and process the parent it's inserted into - - // Insert bookmark node and get the parent - selection.setContent(bookmarkHtml); - parentNode = selection.getNode(); - rootNode = editor.getBody(); - - // Opera will return the document node when selection is in root - if (parentNode.nodeType == 9) { - parentNode = node = rootNode; - } else { - node = parentNode; - } - - // Find the ancestor just before the root element - while (node !== rootNode) { - parentNode = node; - node = node.parentNode; - } - - // Get the outer/inner HTML depending on if we are in the root and parser and serialize that - value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode); - value = serializer.serialize( - parser.parse( - // Need to replace by using a function since $ in the contents would otherwise be a problem - value.replace(//i, function() { - return serializer.serialize(fragment); - }) - ) - ); - - // Set the inner/outer HTML depending on if we are in the root or not - if (parentNode == rootNode) { - dom.setHTML(rootNode, value); - } else { - dom.setOuterHTML(parentNode, value); - } - } - - marker = dom.get('mce_marker'); - selection.scrollIntoView(marker); - - // Move selection before marker and remove it - rng = dom.createRng(); - - // If previous sibling is a text node set the selection to the end of that node - node = marker.previousSibling; - if (node && node.nodeType == 3) { - rng.setStart(node, node.nodeValue.length); - - // TODO: Why can't we normalize on IE - if (!isIE) { - node2 = marker.nextSibling; - if (node2 && node2.nodeType == 3) { - node.appendData(node2.data); - node2.parentNode.removeChild(node2); - } - } - } else { - // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node - rng.setStartBefore(marker); - rng.setEndBefore(marker); - } - - // Remove the marker node and set the new range - dom.remove(marker); - selection.setRng(rng); - - // Dispatch after event and add any visual elements needed - editor.fire('SetContent', args); - editor.addVisual(); - }, - - mceInsertRawHTML: function(command, ui, value) { - selection.setContent('tiny_mce_marker'); - editor.setContent( - editor.getContent().replace(/tiny_mce_marker/g, function() { - return value; - }) - ); - }, - - mceToggleFormat: function(command, ui, value) { - toggleFormat(value); - }, - - mceSetContent: function(command, ui, value) { - editor.setContent(value); - }, - - 'Indent,Outdent': function(command) { - var intentValue, indentUnit, value; - - // Setup indent level - intentValue = settings.indentation; - indentUnit = /[a-z%]+$/i.exec(intentValue); - intentValue = parseInt(intentValue, 10); - - if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) { - // If forced_root_blocks is set to false we don't have a block to indent so lets create a div - if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) { - formatter.apply('div'); - } - - each(selection.getSelectedBlocks(), function(element) { - if (element.nodeName != "LI") { - var indentStyleName = editor.getParam('indent_use_margin', false) ? 'margin' : 'padding'; - - indentStyleName += dom.getStyle(element, 'direction', true) == 'rtl' ? 'Right' : 'Left'; - - if (command == 'outdent') { - value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue); - dom.setStyle(element, indentStyleName, value ? value + indentUnit : ''); - } else { - value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit; - dom.setStyle(element, indentStyleName, value); - } - } - }); - } else { - execNativeCommand(command); - } - }, - - mceRepaint: function() { - if (isGecko) { - try { - storeSelection(TRUE); - - if (selection.getSel()) { - selection.getSel().selectAllChildren(editor.getBody()); - } - - selection.collapse(TRUE); - restoreSelection(); - } catch (ex) { - // Ignore - } - } - }, - - InsertHorizontalRule: function() { - editor.execCommand('mceInsertContent', false, '|
- rng = selection.getRng(); - if (!rng.item) { - rng.moveToElementText(root); - rng.select(); - } - } - }, - - "delete": function() { - execNativeCommand("Delete"); - - // Check if body is empty after the delete call if so then set the contents - // to an empty string and move the caret to any block produced by that operation - // this fixes the issue with root blocks not being properly produced after a delete call on IE - var body = editor.getBody(); - - if (dom.isEmpty(body)) { - editor.setContent(''); - - if (body.firstChild && dom.isBlock(body.firstChild)) { - editor.selection.setCursorLocation(body.firstChild, 0); - } else { - editor.selection.setCursorLocation(body, 0); - } - } - }, - - mceNewDocument: function() { - editor.setContent(''); - } - }); - - // Add queryCommandState overrides - addCommands({ - // Override justify commands - 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) { - var name = 'align' + command.substring(7); - var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks(); - var matches = map(nodes, function(node) { - return !!formatter.matchNode(node, name); - }); - return inArray(matches, TRUE) !== -1; - }, - - 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) { - return isFormatMatch(command); - }, - - mceBlockQuote: function() { - return isFormatMatch('blockquote'); - }, - - Outdent: function() { - var node; - - if (settings.inline_styles) { - if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { - return TRUE; - } - - if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { - return TRUE; - } - } - - return ( - queryCommandState('InsertUnorderedList') || - queryCommandState('InsertOrderedList') || - (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')) - ); - }, - - 'InsertUnorderedList,InsertOrderedList': function(command) { - var list = dom.getParent(selection.getNode(), 'ul,ol'); - - return list && - ( - command === 'insertunorderedlist' && list.tagName === 'UL' || - command === 'insertorderedlist' && list.tagName === 'OL' - ); - } - }, 'state'); - - // Add queryCommandValue overrides - addCommands({ - 'FontSize,FontName': function(command) { - var value = 0, parent; - - if ((parent = dom.getParent(selection.getNode(), 'span'))) { - if (command == 'fontsize') { - value = parent.style.fontSize; - } else { - value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase(); - } - } - - return value; - } - }, 'value'); - - // Add undo manager logic - addCommands({ - Undo: function() { - editor.undoManager.undo(); - }, - - Redo: function() { - editor.undoManager.redo(); - } - }); - }; -}); - -// Included from: js/tinymce/classes/util/URI.js - -/** - * URI.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles parsing, modification and serialization of URI/URL strings. - * @class tinymce.util.URI - */ -define("tinymce/util/URI", [ - "tinymce/util/Tools" -], function(Tools) { - var each = Tools.each, trim = Tools.trim; - - /** - * Constructs a new URI instance. - * - * @constructor - * @method URI - * @param {String} url URI string to parse. - * @param {Object} settings Optional settings object. - */ - function URI(url, settings) { - var self = this, baseUri, base_url; - - // Trim whitespace - url = trim(url); - - // Default settings - settings = self.settings = settings || {}; - - // Strange app protocol that isn't http/https or local anchor - // For example: mailto,skype,tel etc. - if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) { - self.source = url; - return; - } - - var isProtocolRelative = url.indexOf('//') === 0; - - // Absolute path with no host, fake host and protocol - if (url.indexOf('/') === 0 && !isProtocolRelative) { - url = (settings.base_uri ? settings.base_uri.protocol || 'http' : 'http') + '://mce_host' + url; - } - - // Relative path http:// or protocol relative //path - if (!/^[\w\-]*:?\/\//.test(url)) { - base_url = settings.base_uri ? settings.base_uri.path : new URI(location.href).directory; - if (settings.base_uri.protocol === "") { - url = '//mce_host' + self.toAbsPath(base_url, url); - } else { - url = ((settings.base_uri && settings.base_uri.protocol) || 'http') + '://mce_host' + self.toAbsPath(base_url, url); - } - } - - // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri) - url = url.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something - - /*jshint maxlen: 255 */ - /*eslint max-len: 0 */ - url = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url); - - each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) { - var part = url[i]; - - // Zope 3 workaround, they use @@something - if (part) { - part = part.replace(/\(mce_at\)/g, '@@'); - } - - self[v] = part; - }); - - baseUri = settings.base_uri; - if (baseUri) { - if (!self.protocol) { - self.protocol = baseUri.protocol; - } - - if (!self.userInfo) { - self.userInfo = baseUri.userInfo; - } - - if (!self.port && self.host === 'mce_host') { - self.port = baseUri.port; - } - - if (!self.host || self.host === 'mce_host') { - self.host = baseUri.host; - } - - self.source = ''; - } - - if (isProtocolRelative) { - self.protocol = ''; - } - - //t.path = t.path || '/'; - } - - URI.prototype = { - /** - * Sets the internal path part of the URI. - * - * @method setPath - * @param {string} path Path string to set. - */ - setPath: function(path) { - var self = this; - - path = /^(.*?)\/?(\w+)?$/.exec(path); - - // Update path parts - self.path = path[0]; - self.directory = path[1]; - self.file = path[2]; - - // Rebuild source - self.source = ''; - self.getURI(); - }, - - /** - * Converts the specified URI into a relative URI based on the current URI instance location. - * - * @method toRelative - * @param {String} uri URI to convert into a relative path/URI. - * @return {String} Relative URI from the point specified in the current URI instance. - * @example - * // Converts an absolute URL to an relative URL url will be somedir/somefile.htm - * var url = new tinymce.util.URI('http://www.site.com/dir/').toRelative('http://www.site.com/dir/somedir/somefile.htm'); - */ - toRelative: function(uri) { - var self = this, output; - - if (uri === "./") { - return uri; - } - - uri = new URI(uri, {base_uri: self}); - - // Not on same domain/port or protocol - if ((uri.host != 'mce_host' && self.host != uri.host && uri.host) || self.port != uri.port || - (self.protocol != uri.protocol && uri.protocol !== "")) { - return uri.getURI(); - } - - var tu = self.getURI(), uu = uri.getURI(); - - // Allow usage of the base_uri when relative_urls = true - if (tu == uu || (tu.charAt(tu.length - 1) == "/" && tu.substr(0, tu.length - 1) == uu)) { - return tu; - } - - output = self.toRelPath(self.path, uri.path); - - // Add query - if (uri.query) { - output += '?' + uri.query; - } - - // Add anchor - if (uri.anchor) { - output += '#' + uri.anchor; - } - - return output; - }, - - /** - * Converts the specified URI into a absolute URI based on the current URI instance location. - * - * @method toAbsolute - * @param {String} uri URI to convert into a relative path/URI. - * @param {Boolean} noHost No host and protocol prefix. - * @return {String} Absolute URI from the point specified in the current URI instance. - * @example - * // Converts an relative URL to an absolute URL url will be http://www.site.com/dir/somedir/somefile.htm - * var url = new tinymce.util.URI('http://www.site.com/dir/').toAbsolute('somedir/somefile.htm'); - */ - toAbsolute: function(uri, noHost) { - uri = new URI(uri, {base_uri: this}); - - return uri.getURI(this.host == uri.host && this.protocol == uri.protocol ? noHost : 0); - }, - - /** - * Converts a absolute path into a relative path. - * - * @method toRelPath - * @param {String} base Base point to convert the path from. - * @param {String} path Absolute path to convert into a relative path. - */ - toRelPath: function(base, path) { - var items, breakPoint = 0, out = '', i, l; - - // Split the paths - base = base.substring(0, base.lastIndexOf('/')); - base = base.split('/'); - items = path.split('/'); - - if (base.length >= items.length) { - for (i = 0, l = base.length; i < l; i++) { - if (i >= items.length || base[i] != items[i]) { - breakPoint = i + 1; - break; - } - } - } - - if (base.length < items.length) { - for (i = 0, l = items.length; i < l; i++) { - if (i >= base.length || base[i] != items[i]) { - breakPoint = i + 1; - break; - } - } - } - - if (breakPoint === 1) { - return path; - } - - for (i = 0, l = base.length - (breakPoint - 1); i < l; i++) { - out += "../"; - } - - for (i = breakPoint - 1, l = items.length; i < l; i++) { - if (i != breakPoint - 1) { - out += "/" + items[i]; - } else { - out += items[i]; - } - } - - return out; - }, - - /** - * Converts a relative path into a absolute path. - * - * @method toAbsPath - * @param {String} base Base point to convert the path from. - * @param {String} path Relative path to convert into an absolute path. - */ - toAbsPath: function(base, path) { - var i, nb = 0, o = [], tr, outPath; - - // Split paths - tr = /\/$/.test(path) ? '/' : ''; - base = base.split('/'); - path = path.split('/'); - - // Remove empty chunks - each(base, function(k) { - if (k) { - o.push(k); - } - }); - - base = o; - - // Merge relURLParts chunks - for (i = path.length - 1, o = []; i >= 0; i--) { - // Ignore empty or . - if (path[i].length === 0 || path[i] === ".") { - continue; - } - - // Is parent - if (path[i] === '..') { - nb++; - continue; - } - - // Move up - if (nb > 0) { - nb--; - continue; - } - - o.push(path[i]); - } - - i = base.length - nb; - - // If /a/b/c or / - if (i <= 0) { - outPath = o.reverse().join('/'); - } else { - outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/'); - } - - // Add front / if it's needed - if (outPath.indexOf('/') !== 0) { - outPath = '/' + outPath; - } - - // Add traling / if it's needed - if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) { - outPath += tr; - } - - return outPath; - }, - - /** - * Returns the full URI of the internal structure. - * - * @method getURI - * @param {Boolean} noProtoHost Optional no host and protocol part. Defaults to false. - */ - getURI: function(noProtoHost) { - var s, self = this; - - // Rebuild source - if (!self.source || noProtoHost) { - s = ''; - - if (!noProtoHost) { - if (self.protocol) { - s += self.protocol + '://'; - } else { - s += '//'; - } - - if (self.userInfo) { - s += self.userInfo + '@'; - } - - if (self.host) { - s += self.host; - } - - if (self.port) { - s += ':' + self.port; - } - } - - if (self.path) { - s += self.path; - } - - if (self.query) { - s += '?' + self.query; - } - - if (self.anchor) { - s += '#' + self.anchor; - } - - self.source = s; - } - - return self.source; - } - }; - - return URI; -}); - -// Included from: js/tinymce/classes/util/Class.js - -/** - * Class.js - * - * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. - */ - -/** - * This utilitiy class is used for easier inheritage. - * - * Features: - * * Exposed super functions: this._super(); - * * Mixins - * * Dummy functions - * * Property functions: var value = object.value(); and object.value(newValue); - * * Static functions - * * Defaults settings - */ -define("tinymce/util/Class", [ - "tinymce/util/Tools" -], function(Tools) { - var each = Tools.each, extend = Tools.extend; - - var extendClass, initializing; - - function Class() { - } - - // Provides classical inheritance, based on code made by John Resig - Class.extend = extendClass = function(prop) { - var self = this, _super = self.prototype, prototype, name, member; - - // The dummy class constructor - function Class() { - var i, mixins, mixin, self = this; - - // All construction is actually done in the init method - if (!initializing) { - // Run class constuctor - if (self.init) { - self.init.apply(self, arguments); - } - - // Run mixin constructors - mixins = self.Mixins; - if (mixins) { - i = mixins.length; - while (i--) { - mixin = mixins[i]; - if (mixin.init) { - mixin.init.apply(self, arguments); - } - } - } - } - } - - // Dummy function, needs to be extended in order to provide functionality - function dummy() { - return this; - } - - // Creates a overloaded method for the class - // this enables you to use this._super(); to call the super function - function createMethod(name, fn) { - return function(){ - var self = this, tmp = self._super, ret; - - self._super = _super[name]; - ret = fn.apply(self, arguments); - self._super = tmp; - - return ret; - }; - } - - // Instantiate a base class (but only create the instance, - // don't run the init constructor) - initializing = true; - prototype = new self(); - initializing = false; - - // Add mixins - if (prop.Mixins) { - each(prop.Mixins, function(mixin) { - mixin = mixin; - - for (var name in mixin) { - if (name !== "init") { - prop[name] = mixin[name]; - } - } - }); - - if (_super.Mixins) { - prop.Mixins = _super.Mixins.concat(prop.Mixins); - } - } - - // Generate dummy methods - if (prop.Methods) { - each(prop.Methods.split(','), function(name) { - prop[name] = dummy; - }); - } - - // Generate property methods - if (prop.Properties) { - each(prop.Properties.split(','), function(name) { - var fieldName = '_' + name; - - prop[name] = function(value) { - var self = this, undef; - - // Set value - if (value !== undef) { - self[fieldName] = value; - - return self; - } - - // Get value - return self[fieldName]; - }; - }); - } - - // Static functions - if (prop.Statics) { - each(prop.Statics, function(func, name) { - Class[name] = func; - }); - } - - // Default settings - if (prop.Defaults && _super.Defaults) { - prop.Defaults = extend({}, _super.Defaults, prop.Defaults); - } - - // Copy the properties over onto the new prototype - for (name in prop) { - member = prop[name]; - - if (typeof member == "function" && _super[name]) { - prototype[name] = createMethod(name, member); - } else { - prototype[name] = member; - } - } - - // Populate our constructed prototype object - Class.prototype = prototype; - - // Enforce the constructor to be what we expect - Class.constructor = Class; - - // And make this class extendible - Class.extend = extendClass; - - return Class; - }; - - return Class; -}); - -// Included from: js/tinymce/classes/ui/Selector.js - -/** - * Selector.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/*eslint no-nested-ternary:0 */ - -/** - * Selector engine, enables you to select controls by using CSS like expressions. - * We currently only support basic CSS expressions to reduce the size of the core - * and the ones we support should be enough for most cases. - * - * @example - * Supported expressions: - * element - * element#name - * element.class - * element[attr] - * element[attr*=value] - * element[attr~=value] - * element[attr!=value] - * element[attr^=value] - * element[attr$=value] - * element: bug on IE 8 #6178
- DOMUtils.DOM.setHTML(elm, html);
- }
- };
-});
-
-// Included from: js/tinymce/classes/ui/Control.js
-
-/**
- * Control.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/*eslint consistent-this:0 */
-
-/**
- * This is the base class for all controls and containers. All UI control instances inherit
- * from this one as it has the base logic needed by all of them.
- *
- * @class tinymce.ui.Control
- */
-define("tinymce/ui/Control", [
- "tinymce/util/Class",
- "tinymce/util/Tools",
- "tinymce/ui/Collection",
- "tinymce/ui/DomUtils"
-], function(Class, Tools, Collection, DomUtils) {
- "use strict";
-
- var nativeEvents = Tools.makeMap("focusin focusout scroll click dblclick mousedown mouseup mousemove mouseover" +
- " mouseout mouseenter mouseleave wheel keydown keypress keyup contextmenu", " ");
-
- var elementIdCache = {};
- var hasMouseWheelEventSupport = "onmousewheel" in document;
- var hasWheelEventSupport = false;
-
- var Control = Class.extend({
- Statics: {
- elementIdCache: elementIdCache
- },
-
- isRtl: function() {
- return Control.rtl;
- },
-
- /**
- * Class/id prefix to use for all controls.
- *
- * @final
- * @field {String} classPrefix
- */
- classPrefix: "mce-",
-
- /**
- * Constructs a new control instance with the specified settings.
- *
- * @constructor
- * @param {Object} settings Name/value object with settings.
- * @setting {String} style Style CSS properties to add.
- * @setting {String} border Border box values example: 1 1 1 1
- * @setting {String} padding Padding box values example: 1 1 1 1
- * @setting {String} margin Margin box values example: 1 1 1 1
- * @setting {Number} minWidth Minimal width for the control.
- * @setting {Number} minHeight Minimal height for the control.
- * @setting {String} classes Space separated list of classes to add.
- * @setting {String} role WAI-ARIA role to use for control.
- * @setting {Boolean} hidden Is the control hidden by default.
- * @setting {Boolean} disabled Is the control disabled by default.
- * @setting {String} name Name of the control instance.
- */
- init: function(settings) {
- var self = this, classes, i;
-
- self.settings = settings = Tools.extend({}, self.Defaults, settings);
-
- // Initial states
- self._id = settings.id || DomUtils.id();
- self._text = self._name = '';
- self._width = self._height = 0;
- self._aria = {role: settings.role};
-
- // Setup classes
- classes = settings.classes;
- if (classes) {
- classes = classes.split(' ');
- classes.map = {};
- i = classes.length;
- while (i--) {
- classes.map[classes[i]] = true;
- }
- }
-
- self._classes = classes || [];
- self.visible(true);
-
- // Set some properties
- Tools.each('title text width height name classes visible disabled active value'.split(' '), function(name) {
- var value = settings[name], undef;
-
- if (value !== undef) {
- self[name](value);
- } else if (self['_' + name] === undef) {
- self['_' + name] = false;
- }
- });
-
- self.on('click', function() {
- if (self.disabled()) {
- return false;
- }
- });
-
- // TODO: Is this needed duplicate code see above?
- if (settings.classes) {
- Tools.each(settings.classes.split(' '), function(cls) {
- self.addClass(cls);
- });
- }
-
- /**
- * Name/value object with settings for the current control.
- *
- * @field {Object} settings
- */
- self.settings = settings;
-
- self._borderBox = self.parseBox(settings.border);
- self._paddingBox = self.parseBox(settings.padding);
- self._marginBox = self.parseBox(settings.margin);
-
- if (settings.hidden) {
- self.hide();
- }
- },
-
- // Will generate getter/setter methods for these properties
- Properties: 'parent,title,text,width,height,disabled,active,name,value',
-
- // Will generate empty dummy functions for these
- Methods: 'renderHtml',
-
- /**
- * Returns the root element to render controls into.
- *
- * @method getContainerElm
- * @return {Element} HTML DOM element to render into.
- */
- getContainerElm: function() {
- return document.body;
- },
-
- /**
- * Returns a control instance for the current DOM element.
- *
- * @method getParentCtrl
- * @param {Element} elm HTML dom element to get parent control from.
- * @return {tinymce.ui.Control} Control instance or undefined.
- */
- getParentCtrl: function(elm) {
- var ctrl, lookup = this.getRoot().controlIdLookup;
-
- while (elm && lookup) {
- ctrl = lookup[elm.id];
- if (ctrl) {
- break;
- }
-
- elm = elm.parentNode;
- }
-
- return ctrl;
- },
-
- /**
- * Parses the specified box value. A box value contains 1-4 properties in clockwise order.
- *
- * @method parseBox
- * @param {String/Number} value Box value "0 1 2 3" or "0" etc.
- * @return {Object} Object with top/right/bottom/left properties.
- * @private
- */
- parseBox: function(value) {
- var len, radix = 10;
-
- if (!value) {
- return;
- }
-
- if (typeof(value) === "number") {
- value = value || 0;
-
- return {
- top: value,
- left: value,
- bottom: value,
- right: value
- };
- }
-
- value = value.split(' ');
- len = value.length;
-
- if (len === 1) {
- value[1] = value[2] = value[3] = value[0];
- } else if (len === 2) {
- value[2] = value[0];
- value[3] = value[1];
- } else if (len === 3) {
- value[3] = value[1];
- }
-
- return {
- top: parseInt(value[0], radix) || 0,
- right: parseInt(value[1], radix) || 0,
- bottom: parseInt(value[2], radix) || 0,
- left: parseInt(value[3], radix) || 0
- };
- },
-
- borderBox: function() {
- return this._borderBox;
- },
-
- paddingBox: function() {
- return this._paddingBox;
- },
-
- marginBox: function() {
- return this._marginBox;
- },
-
- measureBox: function(elm, prefix) {
- function getStyle(name) {
- var defaultView = document.defaultView;
-
- if (defaultView) {
- // Remove camelcase
- name = name.replace(/[A-Z]/g, function(a) {
- return '-' + a;
- });
-
- return defaultView.getComputedStyle(elm, null).getPropertyValue(name);
- }
-
- return elm.currentStyle[name];
- }
-
- function getSide(name) {
- var val = parseFloat(getStyle(name), 10);
-
- return isNaN(val) ? 0 : val;
- }
-
- return {
- top: getSide(prefix + "TopWidth"),
- right: getSide(prefix + "RightWidth"),
- bottom: getSide(prefix + "BottomWidth"),
- left: getSide(prefix + "LeftWidth")
- };
- },
-
- /**
- * Initializes the current controls layout rect.
- * This will be executed by the layout managers to determine the
- * default minWidth/minHeight etc.
- *
- * @method initLayoutRect
- * @return {Object} Layout rect instance.
- */
- initLayoutRect: function() {
- var self = this, settings = self.settings, borderBox, layoutRect;
- var elm = self.getEl(), width, height, minWidth, minHeight, autoResize;
- var startMinWidth, startMinHeight, initialSize;
-
- // Measure the current element
- borderBox = self._borderBox = self._borderBox || self.measureBox(elm, 'border');
- self._paddingBox = self._paddingBox || self.measureBox(elm, 'padding');
- self._marginBox = self._marginBox || self.measureBox(elm, 'margin');
- initialSize = DomUtils.getSize(elm);
-
- // Setup minWidth/minHeight and width/height
- startMinWidth = settings.minWidth;
- startMinHeight = settings.minHeight;
- minWidth = startMinWidth || initialSize.width;
- minHeight = startMinHeight || initialSize.height;
- width = settings.width;
- height = settings.height;
- autoResize = settings.autoResize;
- autoResize = typeof(autoResize) != "undefined" ? autoResize : !width && !height;
-
- width = width || minWidth;
- height = height || minHeight;
-
- var deltaW = borderBox.left + borderBox.right;
- var deltaH = borderBox.top + borderBox.bottom;
-
- var maxW = settings.maxWidth || 0xFFFF;
- var maxH = settings.maxHeight || 0xFFFF;
-
- // Setup initial layout rect
- self._layoutRect = layoutRect = {
- x: settings.x || 0,
- y: settings.y || 0,
- w: width,
- h: height,
- deltaW: deltaW,
- deltaH: deltaH,
- contentW: width - deltaW,
- contentH: height - deltaH,
- innerW: width - deltaW,
- innerH: height - deltaH,
- startMinWidth: startMinWidth || 0,
- startMinHeight: startMinHeight || 0,
- minW: Math.min(minWidth, maxW),
- minH: Math.min(minHeight, maxH),
- maxW: maxW,
- maxH: maxH,
- autoResize: autoResize,
- scrollW: 0
- };
-
- self._lastLayoutRect = {};
-
- return layoutRect;
- },
-
- /**
- * Getter/setter for the current layout rect.
- *
- * @method layoutRect
- * @param {Object} [newRect] Optional new layout rect.
- * @return {tinymce.ui.Control/Object} Current control or rect object.
- */
- layoutRect: function(newRect) {
- var self = this, curRect = self._layoutRect, lastLayoutRect, size, deltaWidth, deltaHeight, undef, repaintControls;
-
- // Initialize default layout rect
- if (!curRect) {
- curRect = self.initLayoutRect();
- }
-
- // Set new rect values
- if (newRect) {
- // Calc deltas between inner and outer sizes
- deltaWidth = curRect.deltaW;
- deltaHeight = curRect.deltaH;
-
- // Set x position
- if (newRect.x !== undef) {
- curRect.x = newRect.x;
- }
-
- // Set y position
- if (newRect.y !== undef) {
- curRect.y = newRect.y;
- }
-
- // Set minW
- if (newRect.minW !== undef) {
- curRect.minW = newRect.minW;
- }
-
- // Set minH
- if (newRect.minH !== undef) {
- curRect.minH = newRect.minH;
- }
-
- // Set new width and calculate inner width
- size = newRect.w;
- if (size !== undef) {
- size = size < curRect.minW ? curRect.minW : size;
- size = size > curRect.maxW ? curRect.maxW : size;
- curRect.w = size;
- curRect.innerW = size - deltaWidth;
- }
-
- // Set new height and calculate inner height
- size = newRect.h;
- if (size !== undef) {
- size = size < curRect.minH ? curRect.minH : size;
- size = size > curRect.maxH ? curRect.maxH : size;
- curRect.h = size;
- curRect.innerH = size - deltaHeight;
- }
-
- // Set new inner width and calculate width
- size = newRect.innerW;
- if (size !== undef) {
- size = size < curRect.minW - deltaWidth ? curRect.minW - deltaWidth : size;
- size = size > curRect.maxW - deltaWidth ? curRect.maxW - deltaWidth : size;
- curRect.innerW = size;
- curRect.w = size + deltaWidth;
- }
-
- // Set new height and calculate inner height
- size = newRect.innerH;
- if (size !== undef) {
- size = size < curRect.minH - deltaHeight ? curRect.minH - deltaHeight : size;
- size = size > curRect.maxH - deltaHeight ? curRect.maxH - deltaHeight : size;
- curRect.innerH = size;
- curRect.h = size + deltaHeight;
- }
-
- // Set new contentW
- if (newRect.contentW !== undef) {
- curRect.contentW = newRect.contentW;
- }
-
- // Set new contentH
- if (newRect.contentH !== undef) {
- curRect.contentH = newRect.contentH;
- }
-
- // Compare last layout rect with the current one to see if we need to repaint or not
- lastLayoutRect = self._lastLayoutRect;
- if (lastLayoutRect.x !== curRect.x || lastLayoutRect.y !== curRect.y ||
- lastLayoutRect.w !== curRect.w || lastLayoutRect.h !== curRect.h) {
- repaintControls = Control.repaintControls;
-
- if (repaintControls) {
- if (repaintControls.map && !repaintControls.map[self._id]) {
- repaintControls.push(self);
- repaintControls.map[self._id] = true;
- }
- }
-
- lastLayoutRect.x = curRect.x;
- lastLayoutRect.y = curRect.y;
- lastLayoutRect.w = curRect.w;
- lastLayoutRect.h = curRect.h;
- }
-
- return self;
- }
-
- return curRect;
- },
-
- /**
- * Repaints the control after a layout operation.
- *
- * @method repaint
- */
- repaint: function() {
- var self = this, style, bodyStyle, rect, borderBox, borderW = 0, borderH = 0, lastRepaintRect, round;
-
- // Use Math.round on all values on IE < 9
- round = !document.createRange ? Math.round : function(value) {
- return value;
- };
-
- style = self.getEl().style;
- rect = self._layoutRect;
- lastRepaintRect = self._lastRepaintRect || {};
-
- borderBox = self._borderBox;
- borderW = borderBox.left + borderBox.right;
- borderH = borderBox.top + borderBox.bottom;
-
- if (rect.x !== lastRepaintRect.x) {
- style.left = round(rect.x) + 'px';
- lastRepaintRect.x = rect.x;
- }
-
- if (rect.y !== lastRepaintRect.y) {
- style.top = round(rect.y) + 'px';
- lastRepaintRect.y = rect.y;
- }
-
- if (rect.w !== lastRepaintRect.w) {
- style.width = round(rect.w - borderW) + 'px';
- lastRepaintRect.w = rect.w;
- }
-
- if (rect.h !== lastRepaintRect.h) {
- style.height = round(rect.h - borderH) + 'px';
- lastRepaintRect.h = rect.h;
- }
-
- // Update body if needed
- if (self._hasBody && rect.innerW !== lastRepaintRect.innerW) {
- bodyStyle = self.getEl('body').style;
- bodyStyle.width = round(rect.innerW) + 'px';
- lastRepaintRect.innerW = rect.innerW;
- }
-
- if (self._hasBody && rect.innerH !== lastRepaintRect.innerH) {
- bodyStyle = bodyStyle || self.getEl('body').style;
- bodyStyle.height = round(rect.innerH) + 'px';
- lastRepaintRect.innerH = rect.innerH;
- }
-
- self._lastRepaintRect = lastRepaintRect;
- self.fire('repaint', {}, false);
- },
-
- /**
- * Binds a callback to the specified event. This event can both be
- * native browser events like "click" or custom ones like PostRender.
- *
- * The callback function will be passed a DOM event like object that enables yout do stop propagation.
- *
- * @method on
- * @param {String} name Name of the event to bind. For example "click".
- * @param {String/function} callback Callback function to execute ones the event occurs.
- * @return {tinymce.ui.Control} Current control object.
- */
- on: function(name, callback) {
- var self = this, bindings, handlers, names, i;
-
- function resolveCallbackName(name) {
- var callback, scope;
-
- return function(e) {
- if (!callback) {
- self.parents().each(function(ctrl) {
- var callbacks = ctrl.settings.callbacks;
-
- if (callbacks && (callback = callbacks[name])) {
- scope = ctrl;
- return false;
- }
- });
- }
-
- return callback.call(scope, e);
- };
- }
-
- if (callback) {
- if (typeof(callback) == 'string') {
- callback = resolveCallbackName(callback);
- }
-
- names = name.toLowerCase().split(' ');
- i = names.length;
- while (i--) {
- name = names[i];
-
- bindings = self._bindings;
- if (!bindings) {
- bindings = self._bindings = {};
- }
-
- handlers = bindings[name];
- if (!handlers) {
- handlers = bindings[name] = [];
- }
-
- handlers.push(callback);
-
- if (nativeEvents[name]) {
- if (!self._nativeEvents) {
- self._nativeEvents = {name: true};
- } else {
- self._nativeEvents[name] = true;
- }
-
- if (self._rendered) {
- self.bindPendingEvents();
- }
- }
- }
- }
-
- return self;
- },
-
- /**
- * Unbinds the specified event and optionally a specific callback. If you omit the name
- * parameter all event handlers will be removed. If you omit the callback all event handles
- * by the specified name will be removed.
- *
- * @method off
- * @param {String} [name] Name for the event to unbind.
- * @param {function} [callback] Callback function to unbind.
- * @return {mxex.ui.Control} Current control object.
- */
- off: function(name, callback) {
- var self = this, i, bindings = self._bindings, handlers, bindingName, names, hi;
-
- if (bindings) {
- if (name) {
- names = name.toLowerCase().split(' ');
- i = names.length;
- while (i--) {
- name = names[i];
- handlers = bindings[name];
-
- // Unbind all handlers
- if (!name) {
- for (bindingName in bindings) {
- bindings[bindingName].length = 0;
- }
-
- return self;
- }
-
- if (handlers) {
- // Unbind all by name
- if (!callback) {
- handlers.length = 0;
- } else {
- // Unbind specific ones
- hi = handlers.length;
- while (hi--) {
- if (handlers[hi] === callback) {
- handlers.splice(hi, 1);
- }
- }
- }
- }
- }
- } else {
- self._bindings = [];
- }
- }
-
- return self;
- },
-
- /**
- * Fires the specified event by name and arguments on the control. This will execute all
- * bound event handlers.
- *
- * @method fire
- * @param {String} name Name of the event to fire.
- * @param {Object} [args] Arguments to pass to the event.
- * @param {Boolean} [bubble] Value to control bubbeling. Defaults to true.
- * @return {Object} Current arguments object.
- */
- fire: function(name, args, bubble) {
- var self = this, i, l, handlers, parentCtrl;
-
- name = name.toLowerCase();
-
- // Dummy function that gets replaced on the delegation state functions
- function returnFalse() {
- return false;
- }
-
- // Dummy function that gets replaced on the delegation state functions
- function returnTrue() {
- return true;
- }
-
- // Setup empty object if args is omited
- args = args || {};
-
- // Stick type into event object
- if (!args.type) {
- args.type = name;
- }
-
- // Stick control into event
- if (!args.control) {
- args.control = self;
- }
-
- // Add event delegation methods if they are missing
- if (!args.preventDefault) {
- // Add preventDefault method
- args.preventDefault = function() {
- args.isDefaultPrevented = returnTrue;
- };
-
- // Add stopPropagation
- args.stopPropagation = function() {
- args.isPropagationStopped = returnTrue;
- };
-
- // Add stopImmediatePropagation
- args.stopImmediatePropagation = function() {
- args.isImmediatePropagationStopped = returnTrue;
- };
-
- // Add event delegation states
- args.isDefaultPrevented = returnFalse;
- args.isPropagationStopped = returnFalse;
- args.isImmediatePropagationStopped = returnFalse;
- }
-
- if (self._bindings) {
- handlers = self._bindings[name];
-
- if (handlers) {
- for (i = 0, l = handlers.length; i < l; i++) {
- // Execute callback and break if the callback returns a false
- if (!args.isImmediatePropagationStopped() && handlers[i].call(self, args) === false) {
- break;
- }
- }
- }
- }
-
- // Bubble event up to parent controls
- if (bubble !== false) {
- parentCtrl = self.parent();
- while (parentCtrl && !args.isPropagationStopped()) {
- parentCtrl.fire(name, args, false);
- parentCtrl = parentCtrl.parent();
- }
- }
-
- return args;
- },
-
- /**
- * Returns true/false if the specified event has any listeners.
- *
- * @method hasEventListeners
- * @param {String} name Name of the event to check for.
- * @return {Boolean} True/false state if the event has listeners.
- */
- hasEventListeners: function(name) {
- return name in this._bindings;
- },
-
- /**
- * Returns a control collection with all parent controls.
- *
- * @method parents
- * @param {String} selector Optional selector expression to find parents.
- * @return {tinymce.ui.Collection} Collection with all parent controls.
- */
- parents: function(selector) {
- var self = this, ctrl, parents = new Collection();
-
- // Add each parent to collection
- for (ctrl = self.parent(); ctrl; ctrl = ctrl.parent()) {
- parents.add(ctrl);
- }
-
- // Filter away everything that doesn't match the selector
- if (selector) {
- parents = parents.filter(selector);
- }
-
- return parents;
- },
-
- /**
- * Returns the control next to the current control.
- *
- * @method next
- * @return {tinymce.ui.Control} Next control instance.
- */
- next: function() {
- var parentControls = this.parent().items();
-
- return parentControls[parentControls.indexOf(this) + 1];
- },
-
- /**
- * Returns the control previous to the current control.
- *
- * @method prev
- * @return {tinymce.ui.Control} Previous control instance.
- */
- prev: function() {
- var parentControls = this.parent().items();
-
- return parentControls[parentControls.indexOf(this) - 1];
- },
-
- /**
- * Find the common ancestor for two control instances.
- *
- * @method findCommonAncestor
- * @param {tinymce.ui.Control} ctrl1 First control.
- * @param {tinymce.ui.Control} ctrl2 Second control.
- * @return {tinymce.ui.Control} Ancestor control instance.
- */
- findCommonAncestor: function(ctrl1, ctrl2) {
- var parentCtrl;
-
- while (ctrl1) {
- parentCtrl = ctrl2;
-
- while (parentCtrl && ctrl1 != parentCtrl) {
- parentCtrl = parentCtrl.parent();
- }
-
- if (ctrl1 == parentCtrl) {
- break;
- }
-
- ctrl1 = ctrl1.parent();
- }
-
- return ctrl1;
- },
-
- /**
- * Returns true/false if the specific control has the specific class.
- *
- * @method hasClass
- * @param {String} cls Class to check for.
- * @param {String} [group] Sub element group name.
- * @return {Boolean} True/false if the control has the specified class.
- */
- hasClass: function(cls, group) {
- var classes = this._classes[group || 'control'];
-
- cls = this.classPrefix + cls;
-
- return classes && !!classes.map[cls];
- },
-
- /**
- * Adds the specified class to the control
- *
- * @method addClass
- * @param {String} cls Class to check for.
- * @param {String} [group] Sub element group name.
- * @return {tinymce.ui.Control} Current control object.
- */
- addClass: function(cls, group) {
- var self = this, classes, elm;
-
- cls = this.classPrefix + cls;
- classes = self._classes[group || 'control'];
-
- if (!classes) {
- classes = [];
- classes.map = {};
- self._classes[group || 'control'] = classes;
- }
-
- if (!classes.map[cls]) {
- classes.map[cls] = cls;
- classes.push(cls);
-
- if (self._rendered) {
- elm = self.getEl(group);
-
- if (elm) {
- elm.className = classes.join(' ');
- }
- }
- }
-
- return self;
- },
-
- /**
- * Removes the specified class from the control.
- *
- * @method removeClass
- * @param {String} cls Class to remove.
- * @param {String} [group] Sub element group name.
- * @return {tinymce.ui.Control} Current control object.
- */
- removeClass: function(cls, group) {
- var self = this, classes, i, elm;
-
- cls = this.classPrefix + cls;
- classes = self._classes[group || 'control'];
- if (classes && classes.map[cls]) {
- delete classes.map[cls];
-
- i = classes.length;
- while (i--) {
- if (classes[i] === cls) {
- classes.splice(i, 1);
- }
- }
- }
-
- if (self._rendered) {
- elm = self.getEl(group);
-
- if (elm) {
- elm.className = classes.join(' ');
- }
- }
-
- return self;
- },
-
- /**
- * Toggles the specified class on the control.
- *
- * @method toggleClass
- * @param {String} cls Class to remove.
- * @param {Boolean} state True/false state to add/remove class.
- * @param {String} [group] Sub element group name.
- * @return {tinymce.ui.Control} Current control object.
- */
- toggleClass: function(cls, state, group) {
- var self = this;
-
- if (state) {
- self.addClass(cls, group);
- } else {
- self.removeClass(cls, group);
- }
-
- return self;
- },
-
- /**
- * Returns the class string for the specified group name.
- *
- * @method classes
- * @param {String} [group] Group to get clases by.
- * @return {String} Classes for the specified group.
- */
- classes: function(group) {
- var classes = this._classes[group || 'control'];
-
- return classes ? classes.join(' ') : '';
- },
-
- /**
- * Sets the inner HTML of the control element.
- *
- * @method innerHtml
- * @param {String} html Html string to set as inner html.
- * @return {tinymce.ui.Control} Current control object.
- */
- innerHtml: function(html) {
- DomUtils.innerHtml(this.getEl(), html);
- return this;
- },
-
- /**
- * Returns the control DOM element or sub element.
- *
- * @method getEl
- * @param {String} [suffix] Suffix to get element by.
- * @param {Boolean} [dropCache] True if the cache for the element should be dropped.
- * @return {Element} HTML DOM element for the current control or it's children.
- */
- getEl: function(suffix, dropCache) {
- var elm, id = suffix ? this._id + '-' + suffix : this._id;
-
- elm = elementIdCache[id] = (dropCache === true ? null : elementIdCache[id]) || DomUtils.get(id);
-
- return elm;
- },
-
- /**
- * Sets/gets the visible for the control.
- *
- * @method visible
- * @param {Boolean} state Value to set to control.
- * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get.
- */
- visible: function(state) {
- var self = this, parentCtrl;
-
- if (typeof(state) !== "undefined") {
- if (self._visible !== state) {
- if (self._rendered) {
- self.getEl().style.display = state ? '' : 'none';
- }
-
- self._visible = state;
-
- // Parent container needs to reflow
- parentCtrl = self.parent();
- if (parentCtrl) {
- parentCtrl._lastRect = null;
- }
-
- self.fire(state ? 'show' : 'hide');
- }
-
- return self;
- }
-
- return self._visible;
- },
-
- /**
- * Sets the visible state to true.
- *
- * @method show
- * @return {tinymce.ui.Control} Current control instance.
- */
- show: function() {
- return this.visible(true);
- },
-
- /**
- * Sets the visible state to false.
- *
- * @method hide
- * @return {tinymce.ui.Control} Current control instance.
- */
- hide: function() {
- return this.visible(false);
- },
-
- /**
- * Focuses the current control.
- *
- * @method focus
- * @return {tinymce.ui.Control} Current control instance.
- */
- focus: function() {
- try {
- this.getEl().focus();
- } catch (ex) {
- // Ignore IE error
- }
-
- return this;
- },
-
- /**
- * Blurs the current control.
- *
- * @method blur
- * @return {tinymce.ui.Control} Current control instance.
- */
- blur: function() {
- this.getEl().blur();
-
- return this;
- },
-
- /**
- * Sets the specified aria property.
- *
- * @method aria
- * @param {String} name Name of the aria property to set.
- * @param {String} value Value of the aria property.
- * @return {tinymce.ui.Control} Current control instance.
- */
- aria: function(name, value) {
- var self = this, elm = self.getEl(self.ariaTarget);
-
- if (typeof(value) === "undefined") {
- return self._aria[name];
- } else {
- self._aria[name] = value;
- }
-
- if (self._rendered) {
- elm.setAttribute(name == 'role' ? name : 'aria-' + name, value);
- }
-
- return self;
- },
-
- /**
- * Encodes the specified string with HTML entities. It will also
- * translate the string to different languages.
- *
- * @method encode
- * @param {String/Object/Array} text Text to entity encode.
- * @param {Boolean} [translate=true] False if the contents shouldn't be translated.
- * @return {String} Encoded and possible traslated string.
- */
- encode: function(text, translate) {
- if (translate !== false && Control.translate) {
- text = Control.translate(text);
- }
-
- return (text || '').replace(/[&<>"]/g, function(match) {
- return '' + match.charCodeAt(0) + ';';
- });
- },
-
- /**
- * Adds items before the current control.
- *
- * @method before
- * @param {Array/tinymce.ui.Collection} items Array of items to prepend before this control.
- * @return {tinymce.ui.Control} Current control instance.
- */
- before: function(items) {
- var self = this, parent = self.parent();
-
- if (parent) {
- parent.insert(items, parent.items().indexOf(self), true);
- }
-
- return self;
- },
-
- /**
- * Adds items after the current control.
- *
- * @method after
- * @param {Array/tinymce.ui.Collection} items Array of items to append after this control.
- * @return {tinymce.ui.Control} Current control instance.
- */
- after: function(items) {
- var self = this, parent = self.parent();
-
- if (parent) {
- parent.insert(items, parent.items().indexOf(self));
- }
-
- return self;
- },
-
- /**
- * Removes the current control from DOM and from UI collections.
- *
- * @method remove
- * @return {tinymce.ui.Control} Current control instance.
- */
- remove: function() {
- var self = this, elm = self.getEl(), parent = self.parent(), newItems, i;
-
- if (self.items) {
- var controls = self.items().toArray();
- i = controls.length;
- while (i--) {
- controls[i].remove();
- }
- }
-
- if (parent && parent.items) {
- newItems = [];
-
- parent.items().each(function(item) {
- if (item !== self) {
- newItems.push(item);
- }
- });
-
- parent.items().set(newItems);
- parent._lastRect = null;
- }
-
- if (self._eventsRoot && self._eventsRoot == self) {
- DomUtils.off(elm);
- }
-
- var lookup = self.getRoot().controlIdLookup;
- if (lookup) {
- delete lookup[self._id];
- }
-
- delete elementIdCache[self._id];
-
- if (elm && elm.parentNode) {
- var nodes = elm.getElementsByTagName('*');
-
- i = nodes.length;
- while (i--) {
- delete elementIdCache[nodes[i].id];
- }
-
- elm.parentNode.removeChild(elm);
- }
-
- self._rendered = false;
-
- return self;
- },
-
- /**
- * Renders the control before the specified element.
- *
- * @method renderBefore
- * @param {Element} elm Element to render before.
- * @return {tinymce.ui.Control} Current control instance.
- */
- renderBefore: function(elm) {
- var self = this;
-
- elm.parentNode.insertBefore(DomUtils.createFragment(self.renderHtml()), elm);
- self.postRender();
-
- return self;
- },
-
- /**
- * Renders the control to the specified element.
- *
- * @method renderBefore
- * @param {Element} elm Element to render to.
- * @return {tinymce.ui.Control} Current control instance.
- */
- renderTo: function(elm) {
- var self = this;
-
- elm = elm || self.getContainerElm();
- elm.appendChild(DomUtils.createFragment(self.renderHtml()));
- self.postRender();
-
- return self;
- },
-
- /**
- * Post render method. Called after the control has been rendered to the target.
- *
- * @method postRender
- * @return {tinymce.ui.Control} Current control instance.
- */
- postRender: function() {
- var self = this, settings = self.settings, elm, box, parent, name, parentEventsRoot;
-
- // Bind on |ba
ab
|
- * - * Or: - *|
- if (!isDefaultPrevented(e) && (keyCode == DELETE || keyCode == BACKSPACE)) { - isCollapsed = editor.selection.isCollapsed(); - body = editor.getBody(); - - // Selection is collapsed but the editor isn't empty - if (isCollapsed && !dom.isEmpty(body)) { - return; - } - - // Selection isn't collapsed but not all the contents is selected - if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) { - return; - } - - // Manually empty the editor - e.preventDefault(); - editor.setContent(''); - - if (body.firstChild && dom.isBlock(body.firstChild)) { - editor.selection.setCursorLocation(body.firstChild, 0); - } else { - editor.selection.setCursorLocation(body, 0); - } - - editor.nodeChanged(); - } - }); - } - - /** - * WebKit doesn't select all the nodes in the body when you press Ctrl+A. - * IE selects more than the contents [a
] instead of[a]
see bug #6438 - * This selects the whole body so that backspace/delete logic will delete everything - */ - function selectAll() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode == 65 && VK.metaKeyPressed(e)) { - e.preventDefault(); - editor.execCommand('SelectAll'); - } - }); - } - - /** - * WebKit has a weird issue where it some times fails to properly convert keypresses to input method keystrokes. - * The IME on Mac doesn't initialize when it doesn't fire a proper focus event. - * - * This seems to happen when the user manages to click the documentElement element then the window doesn't get proper focus until - * you enter a character into the editor. - * - * It also happens when the first focus in made to the body. - * - * See: https://bugs.webkit.org/show_bug.cgi?id=83566 - */ - function inputMethodFocus() { - if (!editor.settings.content_editable) { - // Case 1 IME doesn't initialize if you focus the document - dom.bind(editor.getDoc(), 'focusin', function() { - selection.setRng(selection.getRng()); - }); - - // Case 2 IME doesn't initialize if you click the documentElement it also doesn't properly fire the focusin event - dom.bind(editor.getDoc(), 'mousedown', function(e) { - if (e.target == editor.getDoc().documentElement) { - editor.getBody().focus(); - selection.setRng(selection.getRng()); - } - }); - } - } - - /** - * Backspacing in FireFox/IE from a paragraph into a horizontal rule results in a floating text node because the - * browser just deletes the paragraph - the browser fails to merge the text node with a horizontal rule so it is - * left there. TinyMCE sees a floating text node and wraps it in a paragraph on the key up event (ForceBlocks.js - * addRootBlocks), meaning the action does nothing. With this code, FireFox/IE matche the behaviour of other - * browsers. - * - * It also fixes a bug on Firefox where it's impossible to delete HR elements. - */ - function removeHrOnBackspace() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { - if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { - var node = selection.getNode(); - var previousSibling = node.previousSibling; - - if (node.nodeName == 'HR') { - dom.remove(node); - e.preventDefault(); - return; - } - - if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") { - dom.remove(previousSibling); - e.preventDefault(); - } - } - } - }); - } - - /** - * Firefox 3.x has an issue where the body element won't get proper focus if you click out - * side it's rectangle. - */ - function focusBody() { - // Fix for a focus bug in FF 3.x where the body element - // wouldn't get proper focus if the user clicked on the HTML element - if (!window.Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4 - editor.on('mousedown', function(e) { - if (!isDefaultPrevented(e) && e.target.nodeName === "HTML") { - var body = editor.getBody(); - - // Blur the body it's focused but not correctly focused - body.blur(); - - // Refocus the body after a little while - setTimeout(function() { - body.focus(); - }, 0); - } - }); - } - } - - /** - * WebKit has a bug where it isn't possible to select image, hr or anchor elements - * by clicking on them so we need to fake that. - */ - function selectControlElements() { - editor.on('click', function(e) { - e = e.target; - - // Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250 - // WebKit can't even do simple things like selecting an image - // Needs tobe the setBaseAndExtend or it will fail to select floated images - if (/^(IMG|HR)$/.test(e.nodeName)) { - selection.getSel().setBaseAndExtent(e, 0, e, 1); - } - - if (e.nodeName == 'A' && dom.hasClass(e, 'mce-item-anchor')) { - selection.select(e); - } - - editor.nodeChanged(); - }); - } - - /** - * Fixes a Gecko bug where the style attribute gets added to the wrong element when deleting between two block elements. - * - * Fixes do backspace/delete on this: - *bla[ck
r]ed
- * - * Would become: - *bla|ed
- * - * Instead of: - *bla|ed
- */ - function removeStylesWhenDeletingAcrossBlockElements() { - function getAttributeApplyFunction() { - var template = dom.getAttribs(selection.getStart().cloneNode(false)); - - return function() { - var target = selection.getStart(); - - if (target !== editor.getBody()) { - dom.setAttrib(target, "style", null); - - each(template, function(attr) { - target.setAttributeNode(attr.cloneNode(true)); - }); - } - }; - } - - function isSelectionAcrossElements() { - return !selection.isCollapsed() && - dom.getParent(selection.getStart(), dom.isBlock) != dom.getParent(selection.getEnd(), dom.isBlock); - } - - editor.on('keypress', function(e) { - var applyAttributes; - - if (!isDefaultPrevented(e) && (e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) { - applyAttributes = getAttributeApplyFunction(); - editor.getDoc().execCommand('delete', false, null); - applyAttributes(); - e.preventDefault(); - return false; - } - }); - - dom.bind(editor.getDoc(), 'cut', function(e) { - var applyAttributes; - - if (!isDefaultPrevented(e) && isSelectionAcrossElements()) { - applyAttributes = getAttributeApplyFunction(); - - setTimeout(function() { - applyAttributes(); - }, 0); - } - }); - } - - /** - * Fire a nodeChanged when the selection is changed on WebKit this fixes selection issues on iOS5. It only fires the nodeChange - * event every 50ms since it would other wise update the UI when you type and it hogs the CPU. - */ - function selectionChangeNodeChanged() { - var lastRng, selectionTimer; - - editor.on('selectionchange', function() { - if (selectionTimer) { - clearTimeout(selectionTimer); - selectionTimer = 0; - } - - selectionTimer = window.setTimeout(function() { - if (editor.removed) { - return; - } - - var rng = selection.getRng(); - - // Compare the ranges to see if it was a real change or not - if (!lastRng || !RangeUtils.compareRanges(rng, lastRng)) { - editor.nodeChanged(); - lastRng = rng; - } - }, 50); - }); - } - - /** - * Screen readers on IE needs to have the role application set on the body. - */ - function ensureBodyHasRoleApplication() { - document.body.setAttribute("role", "application"); - } - - /** - * Backspacing into a table behaves differently depending upon browser type. - * Therefore, disable Backspace when cursor immediately follows a table. - */ - function disableBackspaceIntoATable() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { - if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { - var previousSibling = selection.getNode().previousSibling; - if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") { - e.preventDefault(); - return false; - } - } - } - }); - } - - /** - * Old IE versions can't properly render BR elements in PRE tags white in contentEditable mode. So this - * logic adds a \n before the BR so that it will get rendered. - */ - function addNewLinesBeforeBrInPre() { - // IE8+ rendering mode does the right thing with BR in PRE - if (getDocumentMode() > 7) { - return; - } - - // Enable display: none in area and add a specific class that hides all BR elements in PRE to - // avoid the caret from getting stuck at the BR elements while pressing the right arrow key - setEditorCommandState('RespectVisibilityInDesign', true); - editor.contentStyles.push('.mceHideBrInPre pre br {display: none}'); - dom.addClass(editor.getBody(), 'mceHideBrInPre'); - - // Adds a \n before all BR elements in PRE to get them visual - parser.addNodeFilter('pre', function(nodes) { - var i = nodes.length, brNodes, j, brElm, sibling; - - while (i--) { - brNodes = nodes[i].getAll('br'); - j = brNodes.length; - while (j--) { - brElm = brNodes[j]; - - // Add \n before BR in PRE elements on older IE:s so the new lines get rendered - sibling = brElm.prev; - if (sibling && sibling.type === 3 && sibling.value.charAt(sibling.value - 1) != '\n') { - sibling.value += '\n'; - } else { - brElm.parent.insert(new Node('#text', 3), brElm, true).value = '\n'; - } - } - } - }); - - // Removes any \n before BR elements in PRE since other browsers and in contentEditable=false mode they will be visible - serializer.addNodeFilter('pre', function(nodes) { - var i = nodes.length, brNodes, j, brElm, sibling; - - while (i--) { - brNodes = nodes[i].getAll('br'); - j = brNodes.length; - while (j--) { - brElm = brNodes[j]; - sibling = brElm.prev; - if (sibling && sibling.type == 3) { - sibling.value = sibling.value.replace(/\r?\n$/, ''); - } - } - } - }); - } - - /** - * Moves style width/height to attribute width/height when the user resizes an image on IE. - */ - function removePreSerializedStylesWhenSelectingControls() { - dom.bind(editor.getBody(), 'mouseup', function() { - var value, node = selection.getNode(); - - // Moved styles to attributes on IMG eements - if (node.nodeName == 'IMG') { - // Convert style width to width attribute - if ((value = dom.getStyle(node, 'width'))) { - dom.setAttrib(node, 'width', value.replace(/[^0-9%]+/g, '')); - dom.setStyle(node, 'width', ''); - } - - // Convert style height to height attribute - if ((value = dom.getStyle(node, 'height'))) { - dom.setAttrib(node, 'height', value.replace(/[^0-9%]+/g, '')); - dom.setStyle(node, 'height', ''); - } - } - }); - } - - /** - * Removes a blockquote when backspace is pressed at the beginning of it. - * - * For example: - *- * - * Becomes: - *|x
|x
- */ - function removeBlockQuoteOnBackSpace() { - // Add block quote deletion handler - editor.on('keydown', function(e) { - var rng, container, offset, root, parent; - - if (isDefaultPrevented(e) || e.keyCode != VK.BACKSPACE) { - return; - } - - rng = selection.getRng(); - container = rng.startContainer; - offset = rng.startOffset; - root = dom.getRoot(); - parent = container; - - if (!rng.collapsed || offset !== 0) { - return; - } - - while (parent && parent.parentNode && parent.parentNode.firstChild == parent && parent.parentNode != root) { - parent = parent.parentNode; - } - - // Is the cursor at the beginning of a blockquote? - if (parent.tagName === 'BLOCKQUOTE') { - // Remove the blockquote - editor.formatter.toggle('blockquote', null, parent); - - // Move the caret to the beginning of container - rng = dom.createRng(); - rng.setStart(container, 0); - rng.setEnd(container, 0); - selection.setRng(rng); - } - }); - } - - /** - * Sets various Gecko editing options on mouse down and before a execCommand to disable inline table editing that is broken etc. - */ - function setGeckoEditingOptions() { - function setOpts() { - editor._refreshContentEditable(); - - setEditorCommandState("StyleWithCSS", false); - setEditorCommandState("enableInlineTableEditing", false); - - if (!settings.object_resizing) { - setEditorCommandState("enableObjectResizing", false); - } - } - - if (!settings.readonly) { - editor.on('BeforeExecCommand MouseDown', setOpts); - } - } - - /** - * Fixes a gecko link bug, when a link is placed at the end of block elements there is - * no way to move the caret behind the link. This fix adds a bogus br element after the link. - * - * For example this: - * - * - * Becomes this: - * - */ - function addBrAfterLastLinks() { - function fixLinks() { - each(dom.select('a'), function(node) { - var parentNode = node.parentNode, root = dom.getRoot(); - - if (parentNode.lastChild === node) { - while (parentNode && !dom.isBlock(parentNode)) { - if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) { - return; - } - - parentNode = parentNode.parentNode; - } - - dom.add(parentNode, 'br', {'data-mce-bogus': 1}); - } - }); - } - - editor.on('SetContent ExecCommand', function(e) { - if (e.type == "setcontent" || e.command === 'mceInsertLink') { - fixLinks(); - } - }); - } - - /** - * WebKit will produce DIV elements here and there by default. But since TinyMCE uses paragraphs by - * default we want to change that behavior. - */ - function setDefaultBlockType() { - if (settings.forced_root_block) { - editor.on('init', function() { - setEditorCommandState('DefaultParagraphSeparator', settings.forced_root_block); - }); - } - } - - /** - * Removes ghost selections from images/tables on Gecko. - */ - function removeGhostSelection() { - editor.on('Undo Redo SetContent', function(e) { - if (!e.initial) { - editor.execCommand('mceRepaint'); - } - }); - } - - /** - * Deletes the selected image on IE instead of navigating to previous page. - */ - function deleteControlItemOnBackSpace() { - editor.on('keydown', function(e) { - var rng; - - if (!isDefaultPrevented(e) && e.keyCode == BACKSPACE) { - rng = editor.getDoc().selection.createRange(); - if (rng && rng.item) { - e.preventDefault(); - editor.undoManager.beforeChange(); - dom.remove(rng.item(0)); - editor.undoManager.add(); - } - } - }); - } - - /** - * IE10 doesn't properly render block elements with the right height until you add contents to them. - * This fixes that by adding a padding-right to all empty text block elements. - * See: https://connect.microsoft.com/IE/feedback/details/743881 - */ - function renderEmptyBlocksFix() { - var emptyBlocksCSS; - - // IE10+ - if (getDocumentMode() >= 10) { - emptyBlocksCSS = ''; - each('p div h1 h2 h3 h4 h5 h6'.split(' '), function(name, i) { - emptyBlocksCSS += (i > 0 ? ',' : '') + name + ':empty'; - }); - - editor.contentStyles.push(emptyBlocksCSS + '{padding-right: 1px !important}'); - } - } - - /** - * Old IE versions can't retain contents within noscript elements so this logic will store the contents - * as a attribute and the insert that value as it's raw text when the DOM is serialized. - */ - function keepNoScriptContents() { - if (getDocumentMode() < 9) { - parser.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node, textNode; - - while (i--) { - node = nodes[i]; - textNode = node.firstChild; - - if (textNode) { - node.attr('data-mce-innertext', textNode.value); - } - } - }); - - serializer.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node, textNode, value; - - while (i--) { - node = nodes[i]; - textNode = nodes[i].firstChild; - - if (textNode) { - textNode.value = Entities.decode(textNode.value); - } else { - // Old IE can't retain noscript value so an attribute is used to store it - value = node.attributes.map['data-mce-innertext']; - if (value) { - node.attr('data-mce-innertext', null); - textNode = new Node('#text', 3); - textNode.value = value; - textNode.raw = true; - node.append(textNode); - } - } - } - }); - } - } - - /** - * IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode. - */ - function fixCaretSelectionOfDocumentElementOnIe() { - var doc = dom.doc, body = doc.body, started, startRng, htmlElm; - - // Return range from point or null if it failed - function rngFromPoint(x, y) { - var rng = body.createTextRange(); - - try { - rng.moveToPoint(x, y); - } catch (ex) { - // IE sometimes throws and exception, so lets just ignore it - rng = null; - } - - return rng; - } - - // Fires while the selection is changing - function selectionChange(e) { - var pointRng; - - // Check if the button is down or not - if (e.button) { - // Create range from mouse position - pointRng = rngFromPoint(e.x, e.y); - - if (pointRng) { - // Check if pointRange is before/after selection then change the endPoint - if (pointRng.compareEndPoints('StartToStart', startRng) > 0) { - pointRng.setEndPoint('StartToStart', startRng); - } else { - pointRng.setEndPoint('EndToEnd', startRng); - } - - pointRng.select(); - } - } else { - endSelection(); - } - } - - // Removes listeners - function endSelection() { - var rng = doc.selection.createRange(); - - // If the range is collapsed then use the last start range - if (startRng && !rng.item && rng.compareEndPoints('StartToEnd', rng) === 0) { - startRng.select(); - } - - dom.unbind(doc, 'mouseup', endSelection); - dom.unbind(doc, 'mousemove', selectionChange); - startRng = started = 0; - } - - // Make HTML element unselectable since we are going to handle selection by hand - doc.documentElement.unselectable = true; - - // Detect when user selects outside BODY - dom.bind(doc, 'mousedown contextmenu', function(e) { - if (e.target.nodeName === 'HTML') { - if (started) { - endSelection(); - } - - // Detect vertical scrollbar, since IE will fire a mousedown on the scrollbar and have target set as HTML - htmlElm = doc.documentElement; - if (htmlElm.scrollHeight > htmlElm.clientHeight) { - return; - } - - started = 1; - // Setup start position - startRng = rngFromPoint(e.x, e.y); - if (startRng) { - // Listen for selection change events - dom.bind(doc, 'mouseup', endSelection); - dom.bind(doc, 'mousemove', selectionChange); - - dom.getRoot().focus(); - startRng.select(); - } - } - }); - } - - /** - * Fixes selection issues where the caret can be placed between two inline elements like a|b - * this fix will lean the caret right into the closest inline element. - */ - function normalizeSelection() { - // Normalize selection for example a|a becomes a|a except for Ctrl+A since it selects everything - editor.on('keyup focusin mouseup', function(e) { - if (e.keyCode != 65 || !VK.metaKeyPressed(e)) { - selection.normalize(); - } - }, true); - } - - /** - * Forces Gecko to render a broken image icon if it fails to load an image. - */ - function showBrokenImageIcon() { - editor.contentStyles.push( - 'img:-moz-broken {' + - '-moz-force-broken-image-icon:1;' + - 'min-width:24px;' + - 'min-height:24px' + - '}' - ); - } - - /** - * iOS has a bug where it's impossible to type if the document has a touchstart event - * bound and the user touches the document while having the on screen keyboard visible. - * - * The touch event moves the focus to the parent document while having the caret inside the iframe - * this fix moves the focus back into the iframe document. - */ - function restoreFocusOnKeyDown() { - if (!editor.inline) { - editor.on('keydown', function() { - if (document.activeElement == document.body) { - editor.getWin().focus(); - } - }); - } - } - - /** - * IE 11 has an annoying issue where you can't move focus into the editor - * by clicking on the white area HTML element. We used to be able to to fix this with - * the fixCaretSelectionOfDocumentElementOnIe fix. But since M$ removed the selection - * object it's not possible anymore. So we need to hack in a ungly CSS to force the - * body to be at least 150px. If the user clicks the HTML element out side this 150px region - * we simply move the focus into the first paragraph. Not ideal since you loose the - * positioning of the caret but goot enough for most cases. - */ - function bodyHeight() { - if (!editor.inline) { - editor.contentStyles.push('body {min-height: 150px}'); - editor.on('click', function(e) { - if (e.target.nodeName == 'HTML') { - editor.getBody().focus(); - editor.selection.normalize(); - editor.nodeChanged(); - } - }); - } - } - - /** - * Firefox on Mac OS will move the browser back to the previous page if you press CMD+Left arrow. - * You might then loose all your work so we need to block that behavior and replace it with our own. - */ - function blockCmdArrowNavigation() { - if (Env.mac) { - editor.on('keydown', function(e) { - if (VK.metaKeyPressed(e) && (e.keyCode == 37 || e.keyCode == 39)) { - e.preventDefault(); - editor.selection.getSel().modify('move', e.keyCode == 37 ? 'backward' : 'forward', 'word'); - } - }); - } - } - - /** - * Disables the autolinking in IE 9+ this is then re-enabled by the autolink plugin. - */ - function disableAutoUrlDetect() { - setEditorCommandState("AutoUrlDetect", false); - } - - /** - * IE 11 has a fantastic bug where it will produce two trailing BR elements to iframe bodies when - * the iframe is hidden by display: none on a parent container. The DOM is actually out of sync - * with innerHTML in this case. It's like IE adds shadow DOM BR elements that appears on innerHTML - * but not as the lastChild of the body. However is we add a BR element to the body then remove it - * it doesn't seem to add these BR elements makes sence right?! - * - * Example of what happens: text becomes text]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
[\r\n]*)$/, '');
- });
- }
-
- self.load({initial: true, format: 'html'});
- self.startContent = self.getContent({format: 'raw'});
-
- /**
- * Is set to true after the editor instance has been initialized
- *
- * @property initialized
- * @type Boolean
- * @example
- * function isEditorInitialized(editor) {
- * return editor && editor.initialized;
- * }
- */
- self.initialized = true;
-
- each(self._pendingNativeEvents, function(name) {
- self.dom.bind(getEventTarget(self, name), name, function(e) {
- self.fire(e.type, e);
- });
- });
-
- self.fire('init');
- self.focus(true);
- self.nodeChanged({initial: true});
- self.execCallback('init_instance_callback', self);
-
- // Add editor specific CSS styles
- if (self.contentStyles.length > 0) {
- contentCssText = '';
-
- each(self.contentStyles, function(style) {
- contentCssText += style + "\r\n";
- });
-
- self.dom.addStyle(contentCssText);
- }
-
- // Load specified content CSS last
- each(self.contentCSS, function(cssUrl) {
- if (!self.loadedCSS[cssUrl]) {
- self.dom.loadCSS(cssUrl);
- self.loadedCSS[cssUrl] = true;
- }
- });
-
- // Handle auto focus
- if (settings.auto_focus) {
- setTimeout(function () {
- var ed = self.editorManager.get(settings.auto_focus);
-
- ed.selection.select(ed.getBody(), 1);
- ed.selection.collapse(1);
- ed.getBody().focus();
- ed.getWin().focus();
- }, 100);
- }
-
- // Clean up references for IE
- targetElm = doc = body = null;
- },
-
- /**
- * Focuses/activates the editor. This will set this editor as the activeEditor in the tinymce collection
- * it will also place DOM focus inside the editor.
- *
- * @method focus
- * @param {Boolean} skip_focus Skip DOM focus. Just set is as the active editor.
- */
- focus: function(skip_focus) {
- var oed, self = this, selection = self.selection, contentEditable = self.settings.content_editable, rng;
- var controlElm, doc = self.getDoc(), body;
-
- if (!skip_focus) {
- // Get selected control element
- rng = selection.getRng();
- if (rng.item) {
- controlElm = rng.item(0);
- }
-
- self._refreshContentEditable();
-
- // Focus the window iframe
- if (!contentEditable) {
- // WebKit needs this call to fire focusin event properly see #5948
- // But Opera pre Blink engine will produce an empty selection so skip Opera
- if (!Env.opera) {
- self.getBody().focus();
- }
-
- self.getWin().focus();
- }
-
- // Focus the body as well since it's contentEditable
- if (isGecko || contentEditable) {
- body = self.getBody();
-
- // Check for setActive since it doesn't scroll to the element
- if (body.setActive && Env.ie < 11) {
- body.setActive();
- } else {
- body.focus();
- }
-
- if (contentEditable) {
- selection.normalize();
- }
- }
-
- // Restore selected control element
- // This is needed when for example an image is selected within a
- // layer a call to focus will then remove the control selection
- if (controlElm && controlElm.ownerDocument == doc) {
- rng = doc.body.createControlRange();
- rng.addElement(controlElm);
- rng.select();
- }
- }
-
- if (self.editorManager.activeEditor != self) {
- if ((oed = self.editorManager.activeEditor)) {
- oed.fire('deactivate', {relatedTarget: self});
- }
-
- self.fire('activate', {relatedTarget: oed});
- }
-
- self.editorManager.activeEditor = self;
- },
-
- /**
- * Executes a legacy callback. This method is useful to call old 2.x option callbacks.
- * There new event model is a better way to add callback so this method might be removed in the future.
- *
- * @method execCallback
- * @param {String} name Name of the callback to execute.
- * @return {Object} Return value passed from callback function.
- */
- execCallback: function(name) {
- var self = this, callback = self.settings[name], scope;
-
- if (!callback) {
- return;
- }
-
- // Look through lookup
- if (self.callbackLookup && (scope = self.callbackLookup[name])) {
- callback = scope.func;
- scope = scope.scope;
- }
-
- if (typeof(callback) === 'string') {
- scope = callback.replace(/\.\w+$/, '');
- scope = scope ? resolve(scope) : 0;
- callback = resolve(callback);
- self.callbackLookup = self.callbackLookup || {};
- self.callbackLookup[name] = {func: callback, scope: scope};
- }
-
- return callback.apply(scope || self, Array.prototype.slice.call(arguments, 1));
- },
-
- /**
- * Translates the specified string by replacing variables with language pack items it will also check if there is
- * a key mathcin the input.
- *
- * @method translate
- * @param {String} text String to translate by the language pack data.
- * @return {String} Translated string.
- */
- translate: function(text) {
- var lang = this.settings.language || 'en', i18n = this.editorManager.i18n;
-
- if (!text) {
- return '';
- }
-
- return i18n.data[lang + '.' + text] || text.replace(/\{\#([^\}]+)\}/g, function(a, b) {
- return i18n.data[lang + '.' + b] || '{#' + b + '}';
- });
- },
-
- /**
- * Returns a language pack item by name/key.
- *
- * @method getLang
- * @param {String} name Name/key to get from the language pack.
- * @param {String} defaultVal Optional default value to retrive.
- */
- getLang: function(name, defaultVal) {
- return (
- this.editorManager.i18n.data[(this.settings.language || 'en') + '.' + name] ||
- (defaultVal !== undefined ? defaultVal : '{#' + name + '}')
- );
- },
-
- /**
- * Returns a configuration parameter by name.
- *
- * @method getParam
- * @param {String} name Configruation parameter to retrive.
- * @param {String} defaultVal Optional default value to return.
- * @param {String} type Optional type parameter.
- * @return {String} Configuration parameter value or default value.
- * @example
- * // Returns a specific config value from the currently active editor
- * var someval = tinymce.activeEditor.getParam('myvalue');
- *
- * // Returns a specific config value from a specific editor instance by id
- * var someval2 = tinymce.get('my_editor').getParam('myvalue');
- */
- getParam: function(name, defaultVal, type) {
- var value = name in this.settings ? this.settings[name] : defaultVal, output;
-
- if (type === 'hash') {
- output = {};
-
- if (typeof(value) === 'string') {
- each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function(value) {
- value = value.split('=');
-
- if (value.length > 1) {
- output[trim(value[0])] = trim(value[1]);
- } else {
- output[trim(value[0])] = trim(value);
- }
- });
- } else {
- output = value;
- }
-
- return output;
- }
-
- return value;
- },
-
- /**
- * Distpaches out a onNodeChange event to all observers. This method should be called when you
- * need to update the UI states or element path etc.
- *
- * @method nodeChanged
- */
- nodeChanged: function() {
- var self = this, selection = self.selection, node, parents, root;
-
- // Fix for bug #1896577 it seems that this can not be fired while the editor is loading
- if (self.initialized && !self.settings.disable_nodechange && !self.settings.readonly) {
- // Get start node
- root = self.getBody();
- node = selection.getStart() || root;
- node = ie && node.ownerDocument != self.getDoc() ? self.getBody() : node; // Fix for IE initial state
-
- // Edge case for
|
]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
[\r\n]*)$/,"")}),n.load({initial:!0,format:"html"}),n.startContent=n.getContent({format:"raw"}),n.initialized=!0,R(n._pendingNativeEvents,function(e){n.dom.bind(_(n,e),e,function(e){n.fire(e.type,e)})}),n.fire("init"),n.focus(!0),n.nodeChanged({initial:!0}),n.execCallback("init_instance_callback",n),n.contentStyles.length>0&&(h="",R(n.contentStyles,function(e){h+=e+"\r\n"}),n.dom.addStyle(h)),R(n.contentCSS,function(e){n.loadedCSS[e]||(n.dom.loadCSS(e),n.loadedCSS[e]=!0)}),o.auto_focus&&setTimeout(function(){var e=n.editorManager.get(o.auto_focus);e.selection.select(e.getBody(),1),e.selection.collapse(1),e.getBody().focus(),e.getWin().focus()},100),f=p=m=null},focus:function(e){var t,n=this,r=n.selection,i=n.settings.content_editable,o,a,s=n.getDoc(),l;e||(o=r.getRng(),o.item&&(a=o.item(0)),n._refreshContentEditable(),i||(b.opera||n.getBody().focus(),n.getWin().focus()),(H||i)&&(l=n.getBody(),l.setActive&&b.ie<11?l.setActive():l.focus(),i&&r.normalize()),a&&a.ownerDocument==s&&(o=s.body.createControlRange(),o.addElement(a),o.select())),n.editorManager.activeEditor!=n&&((t=n.editorManager.activeEditor)&&t.fire("deactivate",{relatedTarget:n}),n.fire("activate",{relatedTarget:t})),n.editorManager.activeEditor=n},execCallback:function(e){var t=this,n=t.settings[e],r;if(n)return t.callbackLookup&&(r=t.callbackLookup[e])&&(n=r.func,r=r.scope),"string"==typeof n&&(r=n.replace(/\.\w+$/,""),r=r?D(r):0,n=D(n),t.callbackLookup=t.callbackLookup||{},t.callbackLookup[e]={func:n,scope:r}),n.apply(r||t,Array.prototype.slice.call(arguments,1))},translate:function(e){var t=this.settings.language||"en",n=this.editorManager.i18n;return e?n.data[t+"."+e]||e.replace(/\{\#([^\}]+)\}/g,function(e,r){return n.data[t+"."+r]||"{#"+r+"}"}):""},getLang:function(e,n){return this.editorManager.i18n.data[(this.settings.language||"en")+"."+e]||(n!==t?n:"{#"+e+"}")},getParam:function(e,t,n){var r=e in this.settings?this.settings[e]:t,i;return"hash"===n?(i={},"string"==typeof r?R(r.split(r.indexOf("=")>0?/[;,](?![^=;,]*(?:[;,]|$))/:","),function(e){e=e.split("="),i[L(e[0])]=L(e.length>1?e[1]:e)}):i=r,i):r},nodeChanged:function(){var e=this,t=e.selection,n,r,i;!e.initialized||e.settings.disable_nodechange||e.settings.readonly||(i=e.getBody(),n=t.getStart()||i,n=P&&n.ownerDocument!=e.getDoc()?e.getBody():n,"IMG"==n.nodeName&&t.isCollapsed()&&(n=n.parentNode),r=[],e.dom.getParent(n,function(e){return e===i?!0:void r.push(e)}),e.fire("NodeChange",{element:n,parents:r}))},addButton:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),t.text||t.icon||(t.icon=e),n.buttons=n.buttons||{},t.tooltip=t.tooltip||t.title,n.buttons[e]=t},addMenuItem:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),n.menuItems=n.menuItems||{},n.menuItems[e]=t},addCommand:function(e,t,n){this.execCommands[e]={func:t,scope:n||this}},addQueryStateHandler:function(e,t,n){this.queryStateCommands[e]={func:t,scope:n||this}},addQueryValueHandler:function(e,t,n){this.queryValueCommands[e]={func:t,scope:n||this}},addShortcut:function(e,t,n,r){this.shortcuts.add(e,t,n,r)},execCommand:function(e,t,n,r){var i=this,o=0,a;return/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(e)||r&&r.skip_focus||i.focus(),r=T({},r),r=i.fire("BeforeExecCommand",{command:e,ui:t,value:n}),r.isDefaultPrevented()?!1:(a=i.execCommands[e])&&a.func.call(a.scope,t,n)!==!0?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):(R(i.plugins,function(r){return r.execCommand&&r.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),o=!0,!1):void 0}),o?o:i.theme&&i.theme.execCommand&&i.theme.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):i.editorCommands.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):(i.getDoc().execCommand(e,t,n),void i.fire("ExecCommand",{command:e,ui:t,value:n})))},queryCommandState:function(e){var t=this,n,r;if(!t._isHidden()){if((n=t.queryStateCommands[e])&&(r=n.func.call(n.scope),r!==!0))return r;if(r=t.editorCommands.queryCommandState(e),-1!==r)return r;try{return t.getDoc().queryCommandState(e)}catch(i){}}},queryCommandValue:function(e){var n=this,r,i;if(!n._isHidden()){if((r=n.queryValueCommands[e])&&(i=r.func.call(r.scope),i!==!0))return i;if(i=n.editorCommands.queryCommandValue(e),i!==t)return i;try{return n.getDoc().queryCommandValue(e)}catch(o){}}},show:function(){var e=this;E.show(e.getContainer()),E.hide(e.id),e.load(),e.fire("show")},hide:function(){var e=this,t=e.getDoc();P&&t&&!e.inline&&t.execCommand("SelectAll"),e.save(),E.hide(e.getContainer()),E.setStyle(e.id,"display",e.orgDisplay),e.fire("hide")},isHidden:function(){return!E.isHidden(this.id)},setProgressState:function(e,t){this.fire("ProgressState",{state:e,time:t})},load:function(e){var n=this,r=n.getElement(),i;return r?(e=e||{},e.load=!0,i=n.setContent(r.value!==t?r.value:r.innerHTML,e),e.element=r,e.no_events||n.fire("LoadContent",e),e.element=r=null,i):void 0},save:function(e){var t=this,n=t.getElement(),r,i;if(n&&t.initialized)return e=e||{},e.save=!0,e.element=n,r=e.content=t.getContent(e),e.no_events||t.fire("SaveContent",e),r=e.content,/TEXTAREA|INPUT/i.test(n.nodeName)?n.value=r:(t.inline||(n.innerHTML=r),(i=E.getParent(t.id,"form"))&&R(i.elements,function(e){return e.name==t.id?(e.value=r,!1):void 0})),e.element=n=null,e.set_dirty!==!1&&(t.isNotDirty=!0),r},setContent:function(e,t){var n=this,r=n.getBody(),i;return t=t||{},t.format=t.format||"html",t.set=!0,t.content=e,t.no_events||n.fire("BeforeSetContent",t),e=t.content,0===e.length||/^\s+$/.test(e)?(i=n.settings.forced_root_block,i&&n.schema.isValidChild(r.nodeName.toLowerCase(),i.toLowerCase())?(e=P&&11>P?"":'
',e=n.dom.createHTML(i,n.settings.forced_root_block_attrs,e)):P||(e='
'),r.innerHTML=e,n.fire("SetContent",t)):("raw"!==t.format&&(e=new o({},n.schema).serialize(n.parser.parse(e,{isRootContent:!0}))),t.content=L(e),n.dom.setHTML(r,t.content),t.no_events||n.fire("SetContent",t)),t.content},getContent:function(e){var t=this,n,r=t.getBody();return e=e||{},e.format=e.format||"html",e.get=!0,e.getInner=!0,e.no_events||t.fire("BeforeGetContent",e),n="raw"==e.format?r.innerHTML:"text"==e.format?r.innerText||r.textContent:t.serializer.serialize(r,e),e.content="text"!=e.format?L(n):n,e.no_events||t.fire("GetContent",e),e.content},insertContent:function(e){this.execCommand("mceInsertContent",!1,e)},isDirty:function(){return!this.isNotDirty},getContainer:function(){var e=this;return e.container||(e.container=E.get(e.editorContainer||e.id+"_parent")),e.container},getContentAreaContainer:function(){return this.contentAreaContainer},getElement:function(){return E.get(this.settings.content_element||this.id)},getWin:function(){var e=this,t;return e.contentWindow||(t=E.get(e.id+"_ifr"),t&&(e.contentWindow=t.contentWindow)),e.contentWindow},getDoc:function(){var e=this,t;return e.contentDocument||(t=e.getWin(),t&&(e.contentDocument=t.document)),e.contentDocument},getBody:function(){return this.bodyElement||this.getDoc().body},convertURL:function(e,t,n){var r=this,i=r.settings;return i.urlconverter_callback?r.execCallback("urlconverter_callback",e,n,!0,t):!i.convert_urls||n&&"LINK"==n.nodeName||0===e.indexOf("file:")||0===e.length?e:i.relative_urls?r.documentBaseURI.toRelative(e):e=r.documentBaseURI.toAbsolute(e,i.remove_script_host)},addVisual:function(e){var n=this,r=n.settings,i=n.dom,o;e=e||n.getBody(),n.hasVisual===t&&(n.hasVisual=r.visual),R(i.select("table,a",e),function(e){var t;switch(e.nodeName){case"TABLE":return o=r.visual_table_class||"mce-item-table",t=i.getAttrib(e,"border"),void(t&&"0"!=t||(n.hasVisual?i.addClass(e,o):i.removeClass(e,o)));case"A":return void(i.getAttrib(e,"href",!1)||(t=i.getAttrib(e,"name")||e.id,o=r.visual_anchor_class||"mce-item-anchor",t&&(n.hasVisual?i.addClass(e,o):i.removeClass(e,o))))}}),n.fire("VisualAid",{element:e,hasVisual:n.hasVisual})},remove:function(){var e=this;if(!e.removed){e.save(),e.fire("remove"),e.off(),e.removed=1,e.hasHiddenInput&&E.remove(e.getElement().nextSibling),E.setStyle(e.id,"display",e.orgDisplay),e.settings.content_editable||(M.unbind(e.getWin()),M.unbind(e.getDoc()));var t=e.getContainer();M.unbind(e.getBody()),M.unbind(t),e.editorManager.remove(e),E.remove(t),e.destroy()}},bindNative:function(e){var t=this;t.settings.readonly||(t.initialized?t.dom.bind(_(t,e),e,function(n){t.fire(e,n)}):t._pendingNativeEvents?t._pendingNativeEvents.push(e):t._pendingNativeEvents=[e])},unbindNative:function(e){var t=this;t.initialized&&t.dom.unbind(e)},destroy:function(e){var t=this,n;if(!t.destroyed){if(!e&&!t.removed)return void t.remove();e&&H&&(M.unbind(t.getDoc()),M.unbind(t.getWin()),M.unbind(t.getBody())),e||(t.editorManager.off("beforeunload",t._beforeUnload),t.theme&&t.theme.destroy&&t.theme.destroy(),t.selection.destroy(),t.dom.destroy()),n=t.formElement,n&&(n._mceOldSubmit&&(n.submit=n._mceOldSubmit,n._mceOldSubmit=null),E.unbind(n,"submit reset",t.formEventDelegate)),t.contentAreaContainer=t.formElement=t.container=t.editorContainer=null,t.settings.content_element=t.bodyElement=t.contentDocument=t.contentWindow=null,t.selection&&(t.selection=t.selection.win=t.selection.dom=t.selection.dom.doc=null),t.destroyed=1}},_refreshContentEditable:function(){var e=this,t,n;e._isHidden()&&(t=e.getBody(),n=t.parentNode,n.removeChild(t),n.appendChild(t),t.focus())},_isHidden:function(){var e;return H?(e=this.selection.getSel(),!e||!e.rangeCount||0===e.rangeCount):0}},T(N.prototype,x),N}),r(ot,[],function(){var e={};return{rtl:!1,add:function(t,n){for(var r in n)e[r]=n[r];this.rtl=this.rtl||"rtl"===e._dir},translate:function(t){if("undefined"==typeof t)return t;if("string"!=typeof t&&t.raw)return t.raw;if(t.push){var n=t.slice(1);t=(e[t[0]]||t[0]).replace(/\{([^\}]+)\}/g,function(e,t){return n[t]})}return e[t]||t},data:e}}),r(at,[v,h],function(e,t){function n(e){function a(){try{return document.activeElement}catch(e){return document.body}}function s(e){return e&&e.startContainer?{startContainer:e.startContainer,startOffset:e.startOffset,endContainer:e.endContainer,endOffset:e.endOffset}:e}function l(e,t){var n;return t.startContainer?(n=e.getDoc().createRange(),n.setStart(t.startContainer,t.startOffset),n.setEnd(t.endContainer,t.endOffset)):n=t,n}function c(e){return!!o.getParent(e,n.isEditorUIElement)}function d(e,t){for(var n=t.getBody();e;){if(e==n)return!0;e=e.parentNode}}function u(n){var u=n.editor;u.on("init",function(){(u.inline||t.ie)&&(u.on("nodechange keyup",function(){var e=document.activeElement;e&&e.id==u.id+"_ifr"&&(e=u.getBody()),d(e,u)&&(u.lastRng=u.selection.getRng())}),t.webkit&&!r&&(r=function(){var t=e.activeEditor;if(t&&t.selection){var n=t.selection.getRng();n&&!n.collapsed&&(u.lastRng=n)}},o.bind(document,"selectionchange",r)))}),u.on("setcontent",function(){u.lastRng=null}),u.on("mousedown",function(){u.selection.lastFocusBookmark=null}),u.on("focusin",function(){var t=e.focusedEditor;u.selection.lastFocusBookmark&&(u.selection.setRng(l(u,u.selection.lastFocusBookmark)),u.selection.lastFocusBookmark=null),t!=u&&(t&&t.fire("blur",{focusedEditor:u}),e.activeEditor=u,e.focusedEditor=u,u.fire("focus",{blurredEditor:t}),u.focus(!0)),u.lastRng=null}),u.on("focusout",function(){window.setTimeout(function(){var t=e.focusedEditor;c(a())||t!=u||(u.fire("blur",{focusedEditor:null}),e.focusedEditor=null,u.selection&&(u.selection.lastFocusBookmark=null))},0)}),i||(i=function(t){var n=e.activeEditor;n&&t.target.ownerDocument==document&&(n.selection&&(n.selection.lastFocusBookmark=s(n.lastRng)),c(t.target)||e.focusedEditor!=n||(n.fire("blur",{focusedEditor:null}),e.focusedEditor=null))},o.bind(document,"focusin",i))}function f(t){e.focusedEditor==t.editor&&(e.focusedEditor=null),e.activeEditor||(o.unbind(document,"selectionchange",r),o.unbind(document,"focusin",i),r=i=null)}e.on("AddEditor",u),e.on("RemoveEditor",f)}var r,i,o=e.DOM;return n.isEditorUIElement=function(e){return-1!==e.className.toString().indexOf("mce-")},n}),r(st,[it,v,O,h,f,nt,ot,at],function(e,n,r,i,o,a,s,l){var c=n.DOM,d=o.explode,u=o.each,f=o.extend,p=0,m,h={majorVersion:"4",minorVersion:"0.20",releaseDate:"2014-03-18",editors:[],i18n:s,activeEditor:null,setup:function(){var e=this,t,n,i="",o;if(n=document.location.href.replace(/[\?#].*$/,"").replace(/[\/\\][^\/]+$/,""),/[\/\\]$/.test(n)||(n+="/"),o=window.tinymce||window.tinyMCEPreInit)t=o.base||o.baseURL,i=o.suffix;else for(var a=document.getElementsByTagName("script"),s=0;s
abcabc123
would produceabc
abc123
. - * - * @method split - * @param {Element} parentElm Parent element to split. - * @param {Element} splitElm Element to split at. - * @param {Element} replacementElm Optional replacement element to replace the split element with. - * @return {Element} Returns the split element or the replacement element if that is specified. - */ - split: function(parentElm, splitElm, replacementElm) { - var self = this, r = self.createRng(), bef, aft, pa; - - // W3C valid browsers tend to leave empty nodes to the left/right side of the contents - this makes sense - // but we don't want that in our code since it serves no purpose for the end user - // For example splitting this html at the bold element: - //text 1CHOPtext 2
- // would produce: - //text 1
CHOPtext 2
- // this function will then trim off empty edges and produce: - //text 1
CHOPtext 2
- function trimNode(node) { - var i, children = node.childNodes, type = node.nodeType; - - function surroundedBySpans(node) { - var previousIsSpan = node.previousSibling && node.previousSibling.nodeName == 'SPAN'; - var nextIsSpan = node.nextSibling && node.nextSibling.nodeName == 'SPAN'; - return previousIsSpan && nextIsSpan; - } - - if (type == 1 && node.getAttribute('data-mce-type') == 'bookmark') { - return; - } - - for (i = children.length - 1; i >= 0; i--) { - trimNode(children[i]); - } - - if (type != 9) { - // Keep non whitespace text nodes - if (type == 3 && node.nodeValue.length > 0) { - // If parent element isn't a block or there isn't any useful contents for example "" - // Also keep text nodes with only spaces if surrounded by spans. - // eg. "
a b
" should keep space between a and b - var trimmedLength = trim(node.nodeValue).length; - if (!self.isBlock(node.parentNode) || trimmedLength > 0 || trimmedLength === 0 && surroundedBySpans(node)) { - return; - } - } else if (type == 1) { - // If the only child is a bookmark then move it up - children = node.childNodes; - - // TODO fix this complex if - if (children.length == 1 && children[0] && children[0].nodeType == 1 && - children[0].getAttribute('data-mce-type') == 'bookmark') { - node.parentNode.insertBefore(children[0], node); - } - - // Keep non empty elements or img, hr etc - if (children.length || /^(br|hr|input|img)$/i.test(node.nodeName)) { - return; - } - } - - self.remove(node); - } - - return node; - } - - if (parentElm && splitElm) { - // Get before chunk - r.setStart(parentElm.parentNode, self.nodeIndex(parentElm)); - r.setEnd(splitElm.parentNode, self.nodeIndex(splitElm)); - bef = r.extractContents(); - - // Get after chunk - r = self.createRng(); - r.setStart(splitElm.parentNode, self.nodeIndex(splitElm) + 1); - r.setEnd(parentElm.parentNode, self.nodeIndex(parentElm) + 1); - aft = r.extractContents(); - - // Insert before chunk - pa = parentElm.parentNode; - pa.insertBefore(trimNode(bef), parentElm); - - // Insert middle chunk - if (replacementElm) { - pa.replaceChild(replacementElm, splitElm); - } else { - pa.insertBefore(splitElm, parentElm); - } - - // Insert after chunk - pa.insertBefore(trimNode(aft), parentElm); - self.remove(parentElm); - - return replacementElm || splitElm; - } - }, - - /** - * Adds an event handler to the specified object. - * - * @method bind - * @param {Element/Document/Window/Array} target Target element to bind events to. - * handler to or an array of elements/ids/documents. - * @param {String} name Name of event handler to add, for example: click. - * @param {function} func Function to execute when the event occurs. - * @param {Object} scope Optional scope to execute the function in. - * @return {function} Function callback handler the same as the one passed in. - */ - bind: function(target, name, func, scope) { - var self = this; - - if (Tools.isArray(target)) { - var i = target.length; - - while (i--) { - target[i] = self.bind(target[i], name, func, scope); - } - - return target; - } - - // Collect all window/document events bound by editor instance - if (self.settings.collect && (target === self.doc || target === self.win)) { - self.boundEvents.push([target, name, func, scope]); - } - - return self.events.bind(target, name, func, scope || self); - }, - - /** - * Removes the specified event handler by name and function from an element or collection of elements. - * - * @method unbind - * @param {Element/Document/Window/Array} target Target element to unbind events on. - * @param {String} name Event handler name, for example: "click" - * @param {function} func Function to remove. - * @return {bool/Array} Bool state of true if the handler was removed, or an array of states if multiple input elements - * were passed in. - */ - unbind: function(target, name, func) { - var self = this, i; - - if (Tools.isArray(target)) { - i = target.length; - - while (i--) { - target[i] = self.unbind(target[i], name, func); - } - - return target; - } - - // Remove any bound events matching the input - if (self.boundEvents && (target === self.doc || target === self.win)) { - i = self.boundEvents.length; - - while (i--) { - var item = self.boundEvents[i]; - - if (target == item[0] && (!name || name == item[1]) && (!func || func == item[2])) { - this.events.unbind(item[0], item[1], item[2]); - } - } - } - - return this.events.unbind(target, name, func); - }, - - /** - * Fires the specified event name with object on target. - * - * @method fire - * @param {Node/Document/Window} target Target element or object to fire event on. - * @param {String} name Name of the event to fire. - * @param {Object} evt Event object to send. - * @return {Event} Event object. - */ - fire: function(target, name, evt) { - return this.events.fire(target, name, evt); - }, - - // Returns the content editable state of a node - getContentEditable: function(node) { - var contentEditable; - - // Check type - if (node.nodeType != 1) { - return null; - } - - // Check for fake content editable - contentEditable = node.getAttribute("data-mce-contenteditable"); - if (contentEditable && contentEditable !== "inherit") { - return contentEditable; - } - - // Check for real content editable - return node.contentEditable !== "inherit" ? node.contentEditable : null; - }, - - /** - * Destroys all internal references to the DOM to solve IE leak issues. - * - * @method destroy - */ - destroy: function() { - var self = this; - - // Unbind all events bound to window/document by editor instance - if (self.boundEvents) { - var i = self.boundEvents.length; - - while (i--) { - var item = self.boundEvents[i]; - this.events.unbind(item[0], item[1], item[2]); - } - - self.boundEvents = null; - } - - // Restore sizzle document to window.document - // Since the current document might be removed producing "Permission denied" on IE see #6325 - if (Sizzle.setDocument) { - Sizzle.setDocument(); - } - - self.win = self.doc = self.root = self.events = self.frag = null; - }, - - // #ifdef debug - - dumpRng: function(r) { - return ( - 'startContainer: ' + r.startContainer.nodeName + - ', startOffset: ' + r.startOffset + - ', endContainer: ' + r.endContainer.nodeName + - ', endOffset: ' + r.endOffset - ); - }, - - // #endif - - _findSib: function(node, selector, name) { - var self = this, func = selector; - - if (node) { - // If expression make a function of it using is - if (typeof(func) == 'string') { - func = function(node) { - return self.is(node, selector); - }; - } - - // Loop all siblings - for (node = node[name]; node; node = node[name]) { - if (func(node)) { - return node; - } - } - } - - return null; - } - }; - - /** - * Instance of DOMUtils for the current document. - * - * @static - * @property DOM - * @type tinymce.dom.DOMUtils - * @example - * // Example of how to add a class to some element by id - * tinymce.DOM.addClass('someid', 'someclass'); - */ - DOMUtils.DOM = new DOMUtils(document); - - return DOMUtils; -}); - -// Included from: js/tinymce/classes/dom/ScriptLoader.js - -/** - * ScriptLoader.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/*globals console*/ - -/** - * This class handles asynchronous/synchronous loading of JavaScript files it will execute callbacks - * when various items gets loaded. This class is useful to load external JavaScript files. - * - * @class tinymce.dom.ScriptLoader - * @example - * // Load a script from a specific URL using the global script loader - * tinymce.ScriptLoader.load('somescript.js'); - * - * // Load a script using a unique instance of the script loader - * var scriptLoader = new tinymce.dom.ScriptLoader(); - * - * scriptLoader.load('somescript.js'); - * - * // Load multiple scripts - * var scriptLoader = new tinymce.dom.ScriptLoader(); - * - * scriptLoader.add('somescript1.js'); - * scriptLoader.add('somescript2.js'); - * scriptLoader.add('somescript3.js'); - * - * scriptLoader.loadQueue(function() { - * alert('All scripts are now loaded.'); - * }); - */ -define("tinymce/dom/ScriptLoader", [ - "tinymce/dom/DOMUtils", - "tinymce/util/Tools" -], function(DOMUtils, Tools) { - var DOM = DOMUtils.DOM; - var each = Tools.each, grep = Tools.grep; - - function ScriptLoader() { - var QUEUED = 0, - LOADING = 1, - LOADED = 2, - states = {}, - queue = [], - scriptLoadedCallbacks = {}, - queueLoadedCallbacks = [], - loading = 0, - undef; - - /** - * Loads a specific script directly without adding it to the load queue. - * - * @method load - * @param {String} url Absolute URL to script to add. - * @param {function} callback Optional callback function to execute ones this script gets loaded. - * @param {Object} scope Optional scope to execute callback in. - */ - function loadScript(url, callback) { - var dom = DOM, elm, id; - - // Execute callback when script is loaded - function done() { - dom.remove(id); - - if (elm) { - elm.onreadystatechange = elm.onload = elm = null; - } - - callback(); - } - - function error() { - /*eslint no-console:0 */ - - // Report the error so it's easier for people to spot loading errors - if (typeof(console) !== "undefined" && console.log) { - console.log("Failed to load: " + url); - } - - // We can't mark it as done if there is a load error since - // A) We don't want to produce 404 errors on the server and - // B) the onerror event won't fire on all browsers. - // done(); - } - - id = dom.uniqueId(); - - // Create new script element - elm = document.createElement('script'); - elm.id = id; - elm.type = 'text/javascript'; - elm.src = url; - - // Seems that onreadystatechange works better on IE 10 onload seems to fire incorrectly - if ("onreadystatechange" in elm) { - elm.onreadystatechange = function() { - if (/loaded|complete/.test(elm.readyState)) { - done(); - } - }; - } else { - elm.onload = done; - } - - // Add onerror event will get fired on some browsers but not all of them - elm.onerror = error; - - // Add script to document - (document.getElementsByTagName('head')[0] || document.body).appendChild(elm); - } - - /** - * Returns true/false if a script has been loaded or not. - * - * @method isDone - * @param {String} url URL to check for. - * @return {Boolean} true/false if the URL is loaded. - */ - this.isDone = function(url) { - return states[url] == LOADED; - }; - - /** - * Marks a specific script to be loaded. This can be useful if a script got loaded outside - * the script loader or to skip it from loading some script. - * - * @method markDone - * @param {string} u Absolute URL to the script to mark as loaded. - */ - this.markDone = function(url) { - states[url] = LOADED; - }; - - /** - * Adds a specific script to the load queue of the script loader. - * - * @method add - * @param {String} url Absolute URL to script to add. - * @param {function} callback Optional callback function to execute ones this script gets loaded. - * @param {Object} scope Optional scope to execute callback in. - */ - this.add = this.load = function(url, callback, scope) { - var state = states[url]; - - // Add url to load queue - if (state == undef) { - queue.push(url); - states[url] = QUEUED; - } - - if (callback) { - // Store away callback for later execution - if (!scriptLoadedCallbacks[url]) { - scriptLoadedCallbacks[url] = []; - } - - scriptLoadedCallbacks[url].push({ - func: callback, - scope: scope || this - }); - } - }; - - /** - * Starts the loading of the queue. - * - * @method loadQueue - * @param {function} callback Optional callback to execute when all queued items are loaded. - * @param {Object} scope Optional scope to execute the callback in. - */ - this.loadQueue = function(callback, scope) { - this.loadScripts(queue, callback, scope); - }; - - /** - * Loads the specified queue of files and executes the callback ones they are loaded. - * This method is generally not used outside this class but it might be useful in some scenarios. - * - * @method loadScripts - * @param {Array} scripts Array of queue items to load. - * @param {function} callback Optional callback to execute ones all items are loaded. - * @param {Object} scope Optional scope to execute callback in. - */ - this.loadScripts = function(scripts, callback, scope) { - var loadScripts; - - function execScriptLoadedCallbacks(url) { - // Execute URL callback functions - each(scriptLoadedCallbacks[url], function(callback) { - callback.func.call(callback.scope); - }); - - scriptLoadedCallbacks[url] = undef; - } - - queueLoadedCallbacks.push({ - func: callback, - scope: scope || this - }); - - loadScripts = function() { - var loadingScripts = grep(scripts); - - // Current scripts has been handled - scripts.length = 0; - - // Load scripts that needs to be loaded - each(loadingScripts, function(url) { - // Script is already loaded then execute script callbacks directly - if (states[url] == LOADED) { - execScriptLoadedCallbacks(url); - return; - } - - // Is script not loading then start loading it - if (states[url] != LOADING) { - states[url] = LOADING; - loading++; - - loadScript(url, function() { - states[url] = LOADED; - loading--; - - execScriptLoadedCallbacks(url); - - // Load more scripts if they where added by the recently loaded script - loadScripts(); - }); - } - }); - - // No scripts are currently loading then execute all pending queue loaded callbacks - if (!loading) { - each(queueLoadedCallbacks, function(callback) { - callback.func.call(callback.scope); - }); - - queueLoadedCallbacks.length = 0; - } - }; - - loadScripts(); - }; - } - - ScriptLoader.ScriptLoader = new ScriptLoader(); - - return ScriptLoader; -}); - -// Included from: js/tinymce/classes/AddOnManager.js - -/** - * AddOnManager.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles the loading of themes/plugins or other add-ons and their language packs. - * - * @class tinymce.AddOnManager - */ -define("tinymce/AddOnManager", [ - "tinymce/dom/ScriptLoader", - "tinymce/util/Tools" -], function(ScriptLoader, Tools) { - var each = Tools.each; - - function AddOnManager() { - var self = this; - - self.items = []; - self.urls = {}; - self.lookup = {}; - } - - AddOnManager.prototype = { - /** - * Returns the specified add on by the short name. - * - * @method get - * @param {String} name Add-on to look for. - * @return {tinymce.Theme/tinymce.Plugin} Theme or plugin add-on instance or undefined. - */ - get: function(name) { - if (this.lookup[name]) { - return this.lookup[name].instance; - } else { - return undefined; - } - }, - - dependencies: function(name) { - var result; - - if (this.lookup[name]) { - result = this.lookup[name].dependencies; - } - - return result || []; - }, - - /** - * Loads a language pack for the specified add-on. - * - * @method requireLangPack - * @param {String} name Short name of the add-on. - * @param {String} languages Optional comma or space separated list of languages to check if it matches the name. - */ - requireLangPack: function(name, languages) { - if (AddOnManager.language && AddOnManager.languageLoad !== false) { - if (languages && new RegExp('([, ]|\\b)' + AddOnManager.language + '([, ]|\\b)').test(languages) === false) { - return; - } - - ScriptLoader.ScriptLoader.add(this.urls[name] + '/langs/' + AddOnManager.language + '.js'); - } - }, - - /** - * Adds a instance of the add-on by it's short name. - * - * @method add - * @param {String} id Short name/id for the add-on. - * @param {tinymce.Theme/tinymce.Plugin} addOn Theme or plugin to add. - * @return {tinymce.Theme/tinymce.Plugin} The same theme or plugin instance that got passed in. - * @example - * // Create a simple plugin - * tinymce.create('tinymce.plugins.TestPlugin', { - * TestPlugin: function(ed, url) { - * ed.on('click', function(e) { - * ed.windowManager.alert('Hello World!'); - * }); - * } - * }); - * - * // Register plugin using the add method - * tinymce.PluginManager.add('test', tinymce.plugins.TestPlugin); - * - * // Initialize TinyMCE - * tinymce.init({ - * ... - * plugins: '-test' // Init the plugin but don't try to load it - * }); - */ - add: function(id, addOn, dependencies) { - this.items.push(addOn); - this.lookup[id] = {instance: addOn, dependencies: dependencies}; - - return addOn; - }, - - createUrl: function(baseUrl, dep) { - if (typeof dep === "object") { - return dep; - } else { - return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix}; - } - }, - - /** - * Add a set of components that will make up the add-on. Using the url of the add-on name as the base url. - * This should be used in development mode. A new compressor/javascript munger process will ensure that the - * components are put together into the plugin.js file and compressed correctly. - * - * @method addComponents - * @param {String} pluginName name of the plugin to load scripts from (will be used to get the base url for the plugins). - * @param {Array} scripts Array containing the names of the scripts to load. - */ - addComponents: function(pluginName, scripts) { - var pluginUrl = this.urls[pluginName]; - - each(scripts, function(script) { - ScriptLoader.ScriptLoader.add(pluginUrl + "/" + script); - }); - }, - - /** - * Loads an add-on from a specific url. - * - * @method load - * @param {String} name Short name of the add-on that gets loaded. - * @param {String} addOnUrl URL to the add-on that will get loaded. - * @param {function} callback Optional callback to execute ones the add-on is loaded. - * @param {Object} scope Optional scope to execute the callback in. - * @example - * // Loads a plugin from an external URL - * tinymce.PluginManager.load('myplugin', '/some/dir/someplugin/plugin.js'); - * - * // Initialize TinyMCE - * tinymce.init({ - * ... - * plugins: '-myplugin' // Don't try to load it again - * }); - */ - load: function(name, addOnUrl, callback, scope) { - var self = this, url = addOnUrl; - - function loadDependencies() { - var dependencies = self.dependencies(name); - - each(dependencies, function(dep) { - var newUrl = self.createUrl(addOnUrl, dep); - - self.load(newUrl.resource, newUrl, undefined, undefined); - }); - - if (callback) { - if (scope) { - callback.call(scope); - } else { - callback.call(ScriptLoader); - } - } - } - - if (self.urls[name]) { - return; - } - - if (typeof addOnUrl === "object") { - url = addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix; - } - - if (url.indexOf('/') !== 0 && url.indexOf('://') == -1) { - url = AddOnManager.baseURL + '/' + url; - } - - self.urls[name] = url.substring(0, url.lastIndexOf('/')); - - if (self.lookup[name]) { - loadDependencies(); - } else { - ScriptLoader.ScriptLoader.add(url, loadDependencies, scope); - } - } - }; - - AddOnManager.PluginManager = new AddOnManager(); - AddOnManager.ThemeManager = new AddOnManager(); - - return AddOnManager; -}); - -/** - * TinyMCE theme class. - * - * @class tinymce.Theme - */ - -/** - * This method is responsible for rendering/generating the overall user interface with toolbars, buttons, iframe containers etc. - * - * @method renderUI - * @param {Object} obj Object parameter containing the targetNode DOM node that will be replaced visually with an editor instance. - * @return {Object} an object with items like iframeContainer, editorContainer, sizeContainer, deltaWidth, deltaHeight. - */ - -/** - * Plugin base class, this is a pseudo class that describes how a plugin is to be created for TinyMCE. The methods below are all optional. - * - * @class tinymce.Plugin - * @example - * tinymce.PluginManager.add('example', function(editor, url) { - * // Add a button that opens a window - * editor.addButton('example', { - * text: 'My button', - * icon: false, - * onclick: function() { - * // Open window - * editor.windowManager.open({ - * title: 'Example plugin', - * body: [ - * {type: 'textbox', name: 'title', label: 'Title'} - * ], - * onsubmit: function(e) { - * // Insert content when the window form is submitted - * editor.insertContent('Title: ' + e.data.title); - * } - * }); - * } - * }); - * - * // Adds a menu item to the tools menu - * editor.addMenuItem('example', { - * text: 'Example plugin', - * context: 'tools', - * onclick: function() { - * // Open window with a specific url - * editor.windowManager.open({ - * title: 'TinyMCE site', - * url: 'http://www.tinymce.com', - * width: 800, - * height: 600, - * buttons: [{ - * text: 'Close', - * onclick: 'close' - * }] - * }); - * } - * }); - * }); - */ - -// Included from: js/tinymce/classes/html/Node.js - -/** - * Node.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is a minimalistic implementation of a DOM like node used by the DomParser class. - * - * @example - * var node = new tinymce.html.Node('strong', 1); - * someRoot.append(node); - * - * @class tinymce.html.Node - * @version 3.4 - */ -define("tinymce/html/Node", [], function() { - var whiteSpaceRegExp = /^[ \t\r\n]*$/, typeLookup = { - '#text': 3, - '#comment': 8, - '#cdata': 4, - '#pi': 7, - '#doctype': 10, - '#document-fragment': 11 - }; - - // Walks the tree left/right - function walk(node, root_node, prev) { - var sibling, parent, startName = prev ? 'lastChild' : 'firstChild', siblingName = prev ? 'prev' : 'next'; - - // Walk into nodes if it has a start - if (node[startName]) { - return node[startName]; - } - - // Return the sibling if it has one - if (node !== root_node) { - sibling = node[siblingName]; - - if (sibling) { - return sibling; - } - - // Walk up the parents to look for siblings - for (parent = node.parent; parent && parent !== root_node; parent = parent.parent) { - sibling = parent[siblingName]; - - if (sibling) { - return sibling; - } - } - } - } - - /** - * Constructs a new Node instance. - * - * @constructor - * @method Node - * @param {String} name Name of the node type. - * @param {Number} type Numeric type representing the node. - */ - function Node(name, type) { - this.name = name; - this.type = type; - - if (type === 1) { - this.attributes = []; - this.attributes.map = {}; - } - } - - Node.prototype = { - /** - * Replaces the current node with the specified one. - * - * @example - * someNode.replace(someNewNode); - * - * @method replace - * @param {tinymce.html.Node} node Node to replace the current node with. - * @return {tinymce.html.Node} The old node that got replaced. - */ - replace: function(node) { - var self = this; - - if (node.parent) { - node.remove(); - } - - self.insert(node, self); - self.remove(); - - return self; - }, - - /** - * Gets/sets or removes an attribute by name. - * - * @example - * someNode.attr("name", "value"); // Sets an attribute - * console.log(someNode.attr("name")); // Gets an attribute - * someNode.attr("name", null); // Removes an attribute - * - * @method attr - * @param {String} name Attribute name to set or get. - * @param {String} value Optional value to set. - * @return {String/tinymce.html.Node} String or undefined on a get operation or the current node on a set operation. - */ - attr: function(name, value) { - var self = this, attrs, i, undef; - - if (typeof name !== "string") { - for (i in name) { - self.attr(i, name[i]); - } - - return self; - } - - if ((attrs = self.attributes)) { - if (value !== undef) { - // Remove attribute - if (value === null) { - if (name in attrs.map) { - delete attrs.map[name]; - - i = attrs.length; - while (i--) { - if (attrs[i].name === name) { - attrs = attrs.splice(i, 1); - return self; - } - } - } - - return self; - } - - // Set attribute - if (name in attrs.map) { - // Set attribute - i = attrs.length; - while (i--) { - if (attrs[i].name === name) { - attrs[i].value = value; - break; - } - } - } else { - attrs.push({name: name, value: value}); - } - - attrs.map[name] = value; - - return self; - } else { - return attrs.map[name]; - } - } - }, - - /** - * Does a shallow clones the node into a new node. It will also exclude id attributes since - * there should only be one id per document. - * - * @example - * var clonedNode = node.clone(); - * - * @method clone - * @return {tinymce.html.Node} New copy of the original node. - */ - clone: function() { - var self = this, clone = new Node(self.name, self.type), i, l, selfAttrs, selfAttr, cloneAttrs; - - // Clone element attributes - if ((selfAttrs = self.attributes)) { - cloneAttrs = []; - cloneAttrs.map = {}; - - for (i = 0, l = selfAttrs.length; i < l; i++) { - selfAttr = selfAttrs[i]; - - // Clone everything except id - if (selfAttr.name !== 'id') { - cloneAttrs[cloneAttrs.length] = {name: selfAttr.name, value: selfAttr.value}; - cloneAttrs.map[selfAttr.name] = selfAttr.value; - } - } - - clone.attributes = cloneAttrs; - } - - clone.value = self.value; - clone.shortEnded = self.shortEnded; - - return clone; - }, - - /** - * Wraps the node in in another node. - * - * @example - * node.wrap(wrapperNode); - * - * @method wrap - */ - wrap: function(wrapper) { - var self = this; - - self.parent.insert(wrapper, self); - wrapper.append(self); - - return self; - }, - - /** - * Unwraps the node in other words it removes the node but keeps the children. - * - * @example - * node.unwrap(); - * - * @method unwrap - */ - unwrap: function() { - var self = this, node, next; - - for (node = self.firstChild; node; ) { - next = node.next; - self.insert(node, self, true); - node = next; - } - - self.remove(); - }, - - /** - * Removes the node from it's parent. - * - * @example - * node.remove(); - * - * @method remove - * @return {tinymce.html.Node} Current node that got removed. - */ - remove: function() { - var self = this, parent = self.parent, next = self.next, prev = self.prev; - - if (parent) { - if (parent.firstChild === self) { - parent.firstChild = next; - - if (next) { - next.prev = null; - } - } else { - prev.next = next; - } - - if (parent.lastChild === self) { - parent.lastChild = prev; - - if (prev) { - prev.next = null; - } - } else { - next.prev = prev; - } - - self.parent = self.next = self.prev = null; - } - - return self; - }, - - /** - * Appends a new node as a child of the current node. - * - * @example - * node.append(someNode); - * - * @method append - * @param {tinymce.html.Node} node Node to append as a child of the current one. - * @return {tinymce.html.Node} The node that got appended. - */ - append: function(node) { - var self = this, last; - - if (node.parent) { - node.remove(); - } - - last = self.lastChild; - if (last) { - last.next = node; - node.prev = last; - self.lastChild = node; - } else { - self.lastChild = self.firstChild = node; - } - - node.parent = self; - - return node; - }, - - /** - * Inserts a node at a specific position as a child of the current node. - * - * @example - * parentNode.insert(newChildNode, oldChildNode); - * - * @method insert - * @param {tinymce.html.Node} node Node to insert as a child of the current node. - * @param {tinymce.html.Node} ref_node Reference node to set node before/after. - * @param {Boolean} before Optional state to insert the node before the reference node. - * @return {tinymce.html.Node} The node that got inserted. - */ - insert: function(node, ref_node, before) { - var parent; - - if (node.parent) { - node.remove(); - } - - parent = ref_node.parent || this; - - if (before) { - if (ref_node === parent.firstChild) { - parent.firstChild = node; - } else { - ref_node.prev.next = node; - } - - node.prev = ref_node.prev; - node.next = ref_node; - ref_node.prev = node; - } else { - if (ref_node === parent.lastChild) { - parent.lastChild = node; - } else { - ref_node.next.prev = node; - } - - node.next = ref_node.next; - node.prev = ref_node; - ref_node.next = node; - } - - node.parent = parent; - - return node; - }, - - /** - * Get all children by name. - * - * @method getAll - * @param {String} name Name of the child nodes to collect. - * @return {Array} Array with child nodes matchin the specified name. - */ - getAll: function(name) { - var self = this, node, collection = []; - - for (node = self.firstChild; node; node = walk(node, self)) { - if (node.name === name) { - collection.push(node); - } - } - - return collection; - }, - - /** - * Removes all children of the current node. - * - * @method empty - * @return {tinymce.html.Node} The current node that got cleared. - */ - empty: function() { - var self = this, nodes, i, node; - - // Remove all children - if (self.firstChild) { - nodes = []; - - // Collect the children - for (node = self.firstChild; node; node = walk(node, self)) { - nodes.push(node); - } - - // Remove the children - i = nodes.length; - while (i--) { - node = nodes[i]; - node.parent = node.firstChild = node.lastChild = node.next = node.prev = null; - } - } - - self.firstChild = self.lastChild = null; - - return self; - }, - - /** - * Returns true/false if the node is to be considered empty or not. - * - * @example - * node.isEmpty({img: true}); - * @method isEmpty - * @param {Object} elements Name/value object with elements that are automatically treated as non empty elements. - * @return {Boolean} true/false if the node is empty or not. - */ - isEmpty: function(elements) { - var self = this, node = self.firstChild, i, name; - - if (node) { - do { - if (node.type === 1) { - // Ignore bogus elements - if (node.attributes.map['data-mce-bogus']) { - continue; - } - - // Keep empty elements likea
b
c will becomea
b
c
- * - * @example - * var parser = new tinymce.html.DomParser({validate: true}, schema); - * var rootNode = parser.parse('x
->x
- function trim(rootBlockNode) { - if (rootBlockNode) { - node = rootBlockNode.firstChild; - if (node && node.type == 3) { - node.value = node.value.replace(startWhiteSpaceRegExp, ''); - } - - node = rootBlockNode.lastChild; - if (node && node.type == 3) { - node.value = node.value.replace(endWhiteSpaceRegExp, ''); - } - } - } - - // Check if rootBlock is valid within rootNode for example if P is valid in H1 if H1 is the contentEditabe root - if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) { - return; - } - - while (node) { - next = node.next; - - if (node.type == 3 || (node.type == 1 && node.name !== 'p' && - !blockElements[node.name] && !node.attr('data-mce-type'))) { - if (!rootBlockNode) { - // Create a new root block element - rootBlockNode = createNode(rootBlockName, 1); - rootBlockNode.attr(settings.forced_root_block_attrs); - rootNode.insert(rootBlockNode, node); - rootBlockNode.append(node); - } else { - rootBlockNode.append(node); - } - } else { - trim(rootBlockNode); - rootBlockNode = null; - } - - node = next; - } - - trim(rootBlockNode); - } - - function createNode(name, type) { - var node = new Node(name, type), list; - - if (name in nodeFilters) { - list = matchedNodes[name]; - - if (list) { - list.push(node); - } else { - matchedNodes[name] = [node]; - } - } - - return node; - } - - function removeWhitespaceBefore(node) { - var textNode, textVal, sibling; - - for (textNode = node.prev; textNode && textNode.type === 3; ) { - textVal = textNode.value.replace(endWhiteSpaceRegExp, ''); - - if (textVal.length > 0) { - textNode.value = textVal; - textNode = textNode.prev; - } else { - sibling = textNode.prev; - textNode.remove(); - textNode = sibling; - } - } - } - - function cloneAndExcludeBlocks(input) { - var name, output = {}; - - for (name in input) { - if (name !== 'li' && name != 'p') { - output[name] = input[name]; - } - } - - return output; - } - - parser = new SaxParser({ - validate: validate, - allow_script_urls: settings.allow_script_urls, - allow_conditional_comments: settings.allow_conditional_comments, - - // Exclude P and LI from DOM parsing since it's treated better by the DOM parser - self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()), - - cdata: function(text) { - node.append(createNode('#cdata', 4)).value = text; - }, - - text: function(text, raw) { - var textNode; - - // Trim all redundant whitespace on non white space elements - if (!isInWhiteSpacePreservedElement) { - text = text.replace(allWhiteSpaceRegExp, ' '); - - if (node.lastChild && blockElements[node.lastChild.name]) { - text = text.replace(startWhiteSpaceRegExp, ''); - } - } - - // Do we need to create the node - if (text.length !== 0) { - textNode = createNode('#text', 3); - textNode.raw = !!raw; - node.append(textNode).value = text; - } - }, - - comment: function(text) { - node.append(createNode('#comment', 8)).value = text; - }, - - pi: function(name, text) { - node.append(createNode(name, 7)).value = text; - removeWhitespaceBefore(node); - }, - - doctype: function(text) { - var newNode; - - newNode = node.append(createNode('#doctype', 10)); - newNode.value = text; - removeWhitespaceBefore(node); - }, - - start: function(name, attrs, empty) { - var newNode, attrFiltersLen, elementRule, attrName, parent; - - elementRule = validate ? schema.getElementRule(name) : {}; - if (elementRule) { - newNode = createNode(elementRule.outputName || name, 1); - newNode.attributes = attrs; - newNode.shortEnded = empty; - - node.append(newNode); - - // Check if node is valid child of the parent node is the child is - // unknown we don't collect it since it's probably a custom element - parent = children[node.name]; - if (parent && children[newNode.name] && !parent[newNode.name]) { - invalidChildren.push(newNode); - } - - attrFiltersLen = attributeFilters.length; - while (attrFiltersLen--) { - attrName = attributeFilters[attrFiltersLen].name; - - if (attrName in attrs.map) { - list = matchedAttributes[attrName]; - - if (list) { - list.push(newNode); - } else { - matchedAttributes[attrName] = [newNode]; - } - } - } - - // Trim whitespace before block - if (blockElements[name]) { - removeWhitespaceBefore(newNode); - } - - // Change current node if the element wasn't empty i.e nota
- lastParent = node; - while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) { - lastParent = parent; - - if (blockElements[parent.name]) { - break; - } - - parent = parent.parent; - } - - if (lastParent === parent) { - textNode = new Node('#text', 3); - textNode.value = '\u00a0'; - node.replace(textNode); - } - } - } - }); - } - - // Force anchor names closed, unless the setting "allow_html_in_named_anchor" is explicitly included. - if (!settings.allow_html_in_named_anchor) { - self.addAttributeFilter('id,name', function(nodes) { - var i = nodes.length, sibling, prevSibling, parent, node; - - while (i--) { - node = nodes[i]; - if (node.name === 'a' && node.firstChild && !node.attr('href')) { - parent = node.parent; - - // Move children after current node - sibling = node.lastChild; - do { - prevSibling = sibling.prev; - parent.insert(sibling, node); - sibling = prevSibling; - } while (sibling); - } - } - }); - } - }; -}); - -// Included from: js/tinymce/classes/html/Writer.js - -/** - * Writer.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is used to write HTML tags out it can be used with the Serializer or the SaxParser. - * - * @class tinymce.html.Writer - * @example - * var writer = new tinymce.html.Writer({indent: true}); - * var parser = new tinymce.html.SaxParser(writer).parse('
.
- *
- * @method start
- * @param {String} name Name of the element.
- * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
- * @param {Boolean} empty Optional empty state if the tag should end like
.
- */
- start: function(name, attrs, empty) {
- var i, l, attr, value;
-
- if (indent && indentBefore[name] && html.length > 0) {
- value = html[html.length - 1];
-
- if (value.length > 0 && value !== '\n') {
- html.push('\n');
- }
- }
-
- html.push('<', name);
-
- if (attrs) {
- for (i = 0, l = attrs.length; i < l; i++) {
- attr = attrs[i];
- html.push(' ', attr.name, '="', encode(attr.value, true), '"');
- }
- }
-
- if (!empty || htmlOutput) {
- html[html.length] = '>';
- } else {
- html[html.length] = ' />';
- }
-
- if (empty && indent && indentAfter[name] && html.length > 0) {
- value = html[html.length - 1];
-
- if (value.length > 0 && value !== '\n') {
- html.push('\n');
- }
- }
- },
-
- /**
- * Writes the a end element such as
text
')); - * @class tinymce.html.Serializer - * @version 3.4 - */ -define("tinymce/html/Serializer", [ - "tinymce/html/Writer", - "tinymce/html/Schema" -], function(Writer, Schema) { - /** - * Constructs a new Serializer instance. - * - * @constructor - * @method Serializer - * @param {Object} settings Name/value settings object. - * @param {tinymce.html.Schema} schema Schema instance to use. - */ - return function(settings, schema) { - var self = this, writer = new Writer(settings); - - settings = settings || {}; - settings.validate = "validate" in settings ? settings.validate : true; - - self.schema = schema = schema || new Schema(); - self.writer = writer; - - /** - * Serializes the specified node into a string. - * - * @example - * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('text
')); - * @method serialize - * @param {tinymce.html.Node} node Node instance to serialize. - * @return {String} String with HTML based on DOM tree. - */ - self.serialize = function(node) { - var handlers, validate; - - validate = settings.validate; - - handlers = { - // #text - 3: function(node) { - writer.text(node.value, node.raw); - }, - - // #comment - 8: function(node) { - writer.comment(node.value); - }, - - // Processing instruction - 7: function(node) { - writer.pi(node.name, node.value); - }, - - // Doctype - 10: function(node) { - writer.doctype(node.value); - }, - - // CDATA - 4: function(node) { - writer.cdata(node.value); - }, - - // Document fragment - 11: function(node) { - if ((node = node.firstChild)) { - do { - walk(node); - } while ((node = node.next)); - } - } - }; - - writer.reset(); - - function walk(node) { - var handler = handlers[node.type], name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule; - - if (!handler) { - name = node.name; - isEmpty = node.shortEnded; - attrs = node.attributes; - - // Sort attributes - if (validate && attrs && attrs.length > 1) { - sortedAttrs = []; - sortedAttrs.map = {}; - - elementRule = schema.getElementRule(node.name); - for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) { - attrName = elementRule.attributesOrder[i]; - - if (attrName in attrs.map) { - attrValue = attrs.map[attrName]; - sortedAttrs.map[attrName] = attrValue; - sortedAttrs.push({name: attrName, value: attrValue}); - } - } - - for (i = 0, l = attrs.length; i < l; i++) { - attrName = attrs[i].name; - - if (!(attrName in sortedAttrs.map)) { - attrValue = attrs.map[attrName]; - sortedAttrs.map[attrName] = attrValue; - sortedAttrs.push({name: attrName, value: attrValue}); - } - } - - attrs = sortedAttrs; - } - - writer.start(node.name, attrs, isEmpty); - - if (!isEmpty) { - if ((node = node.firstChild)) { - do { - walk(node); - } while ((node = node.next)); - } - - writer.end(name); - } - } else { - handler(node); - } - } - - // Serialize element and treat all non elements as fragments - if (node.type == 1 && !settings.inner) { - walk(node); - } else { - handlers[11](node); - } - - return writer.getContent(); - }; - }; -}); - -// Included from: js/tinymce/classes/dom/Serializer.js - -/** - * Serializer.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is used to serialize DOM trees into a string. Consult the TinyMCE Wiki API for - * more details and examples on how to use this class. - * - * @class tinymce.dom.Serializer - */ -define("tinymce/dom/Serializer", [ - "tinymce/dom/DOMUtils", - "tinymce/html/DomParser", - "tinymce/html/Entities", - "tinymce/html/Serializer", - "tinymce/html/Node", - "tinymce/html/Schema", - "tinymce/Env", - "tinymce/util/Tools" -], function(DOMUtils, DomParser, Entities, Serializer, Node, Schema, Env, Tools) { - var each = Tools.each, trim = Tools.trim; - var DOM = DOMUtils.DOM; - - /** - * Constructs a new DOM serializer class. - * - * @constructor - * @method Serializer - * @param {Object} settings Serializer settings object. - * @param {tinymce.Editor} editor Optional editor to bind events to and get schema/dom from. - */ - return function(settings, editor) { - var dom, schema, htmlParser; - - if (editor) { - dom = editor.dom; - schema = editor.schema; - } - - // Default DOM and Schema if they are undefined - dom = dom || DOM; - schema = schema || new Schema(settings); - settings.entity_encoding = settings.entity_encoding || 'named'; - settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true; - - htmlParser = new DomParser(settings, schema); - - // Convert move data-mce-src, data-mce-href and data-mce-style into nodes or process them if needed - htmlParser.addAttributeFilter('src,href,style', function(nodes, name) { - var i = nodes.length, node, value, internalName = 'data-mce-' + name; - var urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope, undef; - - while (i--) { - node = nodes[i]; - - value = node.attributes.map[internalName]; - if (value !== undef) { - // Set external name to internal value and remove internal - node.attr(name, value.length > 0 ? value : null); - node.attr(internalName, null); - } else { - // No internal attribute found then convert the value we have in the DOM - value = node.attributes.map[name]; - - if (name === "style") { - value = dom.serializeStyle(dom.parseStyle(value), node.name); - } else if (urlConverter) { - value = urlConverter.call(urlConverterScope, value, name, node.name); - } - - node.attr(name, value.length > 0 ? value : null); - } - } - }); - - // Remove internal classes mceItem<..> or mceSelected - htmlParser.addAttributeFilter('class', function(nodes) { - var i = nodes.length, node, value; - - while (i--) { - node = nodes[i]; - value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, ''); - node.attr('class', value.length > 0 ? value : null); - } - }); - - // Remove bookmark elements - htmlParser.addAttributeFilter('data-mce-type', function(nodes, name, args) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i]; - - if (node.attributes.map['data-mce-type'] === 'bookmark' && !args.cleanup) { - node.remove(); - } - } - }); - - // Remove expando attributes - htmlParser.addAttributeFilter('data-mce-expando', function(nodes, name) { - var i = nodes.length; - - while (i--) { - nodes[i].attr(name, null); - } - }); - - htmlParser.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i].firstChild; - - if (node) { - node.value = Entities.decode(node.value); - } - } - }); - - // Force script into CDATA sections and remove the mce- prefix also add comments around styles - htmlParser.addNodeFilter('script,style', function(nodes, name) { - var i = nodes.length, node, value; - - function trim(value) { - /*jshint maxlen:255 */ - /*eslint max-len:0 */ - return value.replace(/()/g, '\n') - .replace(/^[\r\n]*|[\r\n]*$/g, '') - .replace(/^\s*(()?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, ''); - } - - while (i--) { - node = nodes[i]; - value = node.firstChild ? node.firstChild.value : ''; - - if (name === "script") { - // Remove mce- prefix from script elements and remove default text/javascript mime type (HTML5) - var type = (node.attr('type') || 'text/javascript').replace(/^mce\-/, ''); - node.attr('type', type === 'text/javascript' ? null : type); - - if (value.length > 0) { - node.firstChild.value = '// '; - } - } else { - if (value.length > 0) { - node.firstChild.value = ''; - } - } - } - }); - - // Convert comments to cdata and handle protected comments - htmlParser.addNodeFilter('#comment', function(nodes) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i]; - - if (node.value.indexOf('[CDATA[') === 0) { - node.name = '#cdata'; - node.type = 4; - node.value = node.value.replace(/^\[CDATA\[|\]\]$/g, ''); - } else if (node.value.indexOf('mce:protected ') === 0) { - node.name = "#text"; - node.type = 3; - node.raw = true; - node.value = unescape(node.value).substr(14); - } - } - }); - - htmlParser.addNodeFilter('xml:namespace,input', function(nodes, name) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i]; - if (node.type === 7) { - node.remove(); - } else if (node.type === 1) { - if (name === "input" && !("type" in node.attributes.map)) { - node.attr('type', 'text'); - } - } - } - }); - - // Fix list elements, TODO: Replace this later - if (settings.fix_list_elements) { - htmlParser.addNodeFilter('ul,ol', function(nodes) { - var i = nodes.length, node, parentNode; - - while (i--) { - node = nodes[i]; - parentNode = node.parent; - - if (parentNode.name === 'ul' || parentNode.name === 'ol') { - if (node.prev && node.prev.name === 'li') { - node.prev.append(node); - } - } - } - }); - } - - // Remove internal data attributes - htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style,data-mce-selected', function(nodes, name) { - var i = nodes.length; - - while (i--) { - nodes[i].attr(name, null); - } - }); - - // Return public methods - return { - /** - * Schema instance that was used to when the Serializer was constructed. - * - * @field {tinymce.html.Schema} schema - */ - schema: schema, - - /** - * Adds a node filter function to the parser used by the serializer, the parser will collect the specified nodes by name - * and then execute the callback ones it has finished parsing the document. - * - * @example - * parser.addNodeFilter('p,h1', function(nodes, name) { - * for (var i = 0; i < nodes.length; i++) { - * console.log(nodes[i].name); - * } - * }); - * @method addNodeFilter - * @method {String} name Comma separated list of nodes to collect. - * @param {function} callback Callback function to execute once it has collected nodes. - */ - addNodeFilter: htmlParser.addNodeFilter, - - /** - * Adds a attribute filter function to the parser used by the serializer, the parser will - * collect nodes that has the specified attributes - * and then execute the callback ones it has finished parsing the document. - * - * @example - * parser.addAttributeFilter('src,href', function(nodes, name) { - * for (var i = 0; i < nodes.length; i++) { - * console.log(nodes[i].name); - * } - * }); - * @method addAttributeFilter - * @method {String} name Comma separated list of nodes to collect. - * @param {function} callback Callback function to execute once it has collected nodes. - */ - addAttributeFilter: htmlParser.addAttributeFilter, - - /** - * Serializes the specified browser DOM node into a HTML string. - * - * @method serialize - * @param {DOMNode} node DOM node to serialize. - * @param {Object} args Arguments option that gets passed to event handlers. - */ - serialize: function(node, args) { - var self = this, impl, doc, oldDoc, htmlSerializer, content; - - // Explorer won't clone contents of script and style and the - // selected index of select elements are cleared on a clone operation. - if (Env.ie && dom.select('script,style,select,map').length > 0) { - content = node.innerHTML; - node = node.cloneNode(false); - dom.setHTML(node, content); - } else { - node = node.cloneNode(true); - } - - // Nodes needs to be attached to something in WebKit/Opera - // This fix will make DOM ranges and make Sizzle happy! - impl = node.ownerDocument.implementation; - if (impl.createHTMLDocument) { - // Create an empty HTML document - doc = impl.createHTMLDocument(""); - - // Add the element or it's children if it's a body element to the new document - each(node.nodeName == 'BODY' ? node.childNodes : [node], function(node) { - doc.body.appendChild(doc.importNode(node, true)); - }); - - // Grab first child or body element for serialization - if (node.nodeName != 'BODY') { - node = doc.body.firstChild; - } else { - node = doc.body; - } - - // set the new document in DOMUtils so createElement etc works - oldDoc = dom.doc; - dom.doc = doc; - } - - args = args || {}; - args.format = args.format || 'html'; - - // Don't wrap content if we want selected html - if (args.selection) { - args.forced_root_block = ''; - } - - // Pre process - if (!args.no_events) { - args.node = node; - self.onPreProcess(args); - } - - // Setup serializer - htmlSerializer = new Serializer(settings, schema); - - // Parse and serialize HTML - args.content = htmlSerializer.serialize( - htmlParser.parse(trim(args.getInner ? node.innerHTML : dom.getOuterHTML(node)), args) - ); - - // Replace all BOM characters for now until we can find a better solution - if (!args.cleanup) { - args.content = args.content.replace(/\uFEFF/g, ''); - } - - // Post process - if (!args.no_events) { - self.onPostProcess(args); - } - - // Restore the old document if it was changed - if (oldDoc) { - dom.doc = oldDoc; - } - - args.node = null; - - return args.content; - }, - - /** - * Adds valid elements rules to the serializers schema instance this enables you to specify things - * like what elements should be outputted and what attributes specific elements might have. - * Consult the Wiki for more details on this format. - * - * @method addRules - * @param {String} rules Valid elements rules string to add to schema. - */ - addRules: function(rules) { - schema.addValidElements(rules); - }, - - /** - * Sets the valid elements rules to the serializers schema instance this enables you to specify things - * like what elements should be outputted and what attributes specific elements might have. - * Consult the Wiki for more details on this format. - * - * @method setRules - * @param {String} rules Valid elements rules string. - */ - setRules: function(rules) { - schema.setValidElements(rules); - }, - - onPreProcess: function(args) { - if (editor) { - editor.fire('PreProcess', args); - } - }, - - onPostProcess: function(args) { - if (editor) { - editor.fire('PostProcess', args); - } - } - }; - }; -}); - -// Included from: js/tinymce/classes/dom/TridentSelection.js - -/** - * TridentSelection.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * Selection class for old explorer versions. This one fakes the - * native selection object available on modern browsers. - * - * @class tinymce.dom.TridentSelection - */ -define("tinymce/dom/TridentSelection", [], function() { - function Selection(selection) { - var self = this, dom = selection.dom, FALSE = false; - - function getPosition(rng, start) { - var checkRng, startIndex = 0, endIndex, inside, - children, child, offset, index, position = -1, parent; - - // Setup test range, collapse it and get the parent - checkRng = rng.duplicate(); - checkRng.collapse(start); - parent = checkRng.parentElement(); - - // Check if the selection is within the right document - if (parent.ownerDocument !== selection.dom.doc) { - return; - } - - // IE will report non editable elements as it's parent so look for an editable one - while (parent.contentEditable === "false") { - parent = parent.parentNode; - } - - // If parent doesn't have any children then return that we are inside the element - if (!parent.hasChildNodes()) { - return {node: parent, inside: 1}; - } - - // Setup node list and endIndex - children = parent.children; - endIndex = children.length - 1; - - // Perform a binary search for the position - while (startIndex <= endIndex) { - index = Math.floor((startIndex + endIndex) / 2); - - // Move selection to node and compare the ranges - child = children[index]; - checkRng.moveToElementText(child); - position = checkRng.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', rng); - - // Before/after or an exact match - if (position > 0) { - endIndex = index - 1; - } else if (position < 0) { - startIndex = index + 1; - } else { - return {node: child}; - } - } - - // Check if child position is before or we didn't find a position - if (position < 0) { - // No element child was found use the parent element and the offset inside that - if (!child) { - checkRng.moveToElementText(parent); - checkRng.collapse(true); - child = parent; - inside = true; - } else { - checkRng.collapse(false); - } - - // Walk character by character in text node until we hit the selected range endpoint, - // hit the end of document or parent isn't the right one - // We need to walk char by char since rng.text or rng.htmlText will trim line endings - offset = 0; - while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) { - if (checkRng.move('character', 1) === 0 || parent != checkRng.parentElement()) { - break; - } - - offset++; - } - } else { - // Child position is after the selection endpoint - checkRng.collapse(true); - - // Walk character by character in text node until we hit the selected range endpoint, hit - // the end of document or parent isn't the right one - offset = 0; - while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) { - if (checkRng.move('character', -1) === 0 || parent != checkRng.parentElement()) { - break; - } - - offset++; - } - } - - return {node: child, position: position, offset: offset, inside: inside}; - } - - // Returns a W3C DOM compatible range object by using the IE Range API - function getRange() { - var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed, tmpRange, element2, bookmark; - - // If selection is outside the current document just return an empty range - element = ieRange.item ? ieRange.item(0) : ieRange.parentElement(); - if (element.ownerDocument != dom.doc) { - return domRange; - } - - collapsed = selection.isCollapsed(); - - // Handle control selection - if (ieRange.item) { - domRange.setStart(element.parentNode, dom.nodeIndex(element)); - domRange.setEnd(domRange.startContainer, domRange.startOffset + 1); - - return domRange; - } - - function findEndPoint(start) { - var endPoint = getPosition(ieRange, start), container, offset, textNodeOffset = 0, sibling, undef, nodeValue; - - container = endPoint.node; - offset = endPoint.offset; - - if (endPoint.inside && !container.hasChildNodes()) { - domRange[start ? 'setStart' : 'setEnd'](container, 0); - return; - } - - if (offset === undef) { - domRange[start ? 'setStartBefore' : 'setEndAfter'](container); - return; - } - - if (endPoint.position < 0) { - sibling = endPoint.inside ? container.firstChild : container.nextSibling; - - if (!sibling) { - domRange[start ? 'setStartAfter' : 'setEndAfter'](container); - return; - } - - if (!offset) { - if (sibling.nodeType == 3) { - domRange[start ? 'setStart' : 'setEnd'](sibling, 0); - } else { - domRange[start ? 'setStartBefore' : 'setEndBefore'](sibling); - } - - return; - } - - // Find the text node and offset - while (sibling) { - nodeValue = sibling.nodeValue; - textNodeOffset += nodeValue.length; - - // We are at or passed the position we where looking for - if (textNodeOffset >= offset) { - container = sibling; - textNodeOffset -= offset; - textNodeOffset = nodeValue.length - textNodeOffset; - break; - } - - sibling = sibling.nextSibling; - } - } else { - // Find the text node and offset - sibling = container.previousSibling; - - if (!sibling) { - return domRange[start ? 'setStartBefore' : 'setEndBefore'](container); - } - - // If there isn't any text to loop then use the first position - if (!offset) { - if (container.nodeType == 3) { - domRange[start ? 'setStart' : 'setEnd'](sibling, container.nodeValue.length); - } else { - domRange[start ? 'setStartAfter' : 'setEndAfter'](sibling); - } - - return; - } - - while (sibling) { - textNodeOffset += sibling.nodeValue.length; - - // We are at or passed the position we where looking for - if (textNodeOffset >= offset) { - container = sibling; - textNodeOffset -= offset; - break; - } - - sibling = sibling.previousSibling; - } - } - - domRange[start ? 'setStart' : 'setEnd'](container, textNodeOffset); - } - - try { - // Find start point - findEndPoint(true); - - // Find end point if needed - if (!collapsed) { - findEndPoint(); - } - } catch (ex) { - // IE has a nasty bug where text nodes might throw "invalid argument" when you - // access the nodeValue or other properties of text nodes. This seems to happend when - // text nodes are split into two nodes by a delete/backspace call. So lets detect it and try to fix it. - if (ex.number == -2147024809) { - // Get the current selection - bookmark = self.getBookmark(2); - - // Get start element - tmpRange = ieRange.duplicate(); - tmpRange.collapse(true); - element = tmpRange.parentElement(); - - // Get end element - if (!collapsed) { - tmpRange = ieRange.duplicate(); - tmpRange.collapse(false); - element2 = tmpRange.parentElement(); - element2.innerHTML = element2.innerHTML; - } - - // Remove the broken elements - element.innerHTML = element.innerHTML; - - // Restore the selection - self.moveToBookmark(bookmark); - - // Since the range has moved we need to re-get it - ieRange = selection.getRng(); - - // Find start point - findEndPoint(true); - - // Find end point if needed - if (!collapsed) { - findEndPoint(); - } - } else { - throw ex; // Throw other errors - } - } - - return domRange; - } - - this.getBookmark = function(type) { - var rng = selection.getRng(), bookmark = {}; - - function getIndexes(node) { - var parent, root, children, i, indexes = []; - - parent = node.parentNode; - root = dom.getRoot().parentNode; - - while (parent != root && parent.nodeType !== 9) { - children = parent.children; - - i = children.length; - while (i--) { - if (node === children[i]) { - indexes.push(i); - break; - } - } - - node = parent; - parent = parent.parentNode; - } - - return indexes; - } - - function getBookmarkEndPoint(start) { - var position; - - position = getPosition(rng, start); - if (position) { - return { - position: position.position, - offset: position.offset, - indexes: getIndexes(position.node), - inside: position.inside - }; - } - } - - // Non ubstructive bookmark - if (type === 2) { - // Handle text selection - if (!rng.item) { - bookmark.start = getBookmarkEndPoint(true); - - if (!selection.isCollapsed()) { - bookmark.end = getBookmarkEndPoint(); - } - } else { - bookmark.start = {ctrl: true, indexes: getIndexes(rng.item(0))}; - } - } - - return bookmark; - }; - - this.moveToBookmark = function(bookmark) { - var rng, body = dom.doc.body; - - function resolveIndexes(indexes) { - var node, i, idx, children; - - node = dom.getRoot(); - for (i = indexes.length - 1; i >= 0; i--) { - children = node.children; - idx = indexes[i]; - - if (idx <= children.length - 1) { - node = children[idx]; - } - } - - return node; - } - - function setBookmarkEndPoint(start) { - var endPoint = bookmark[start ? 'start' : 'end'], moveLeft, moveRng, undef, offset; - - if (endPoint) { - moveLeft = endPoint.position > 0; - - moveRng = body.createTextRange(); - moveRng.moveToElementText(resolveIndexes(endPoint.indexes)); - - offset = endPoint.offset; - if (offset !== undef) { - moveRng.collapse(endPoint.inside || moveLeft); - moveRng.moveStart('character', moveLeft ? -offset : offset); - } else { - moveRng.collapse(start); - } - - rng.setEndPoint(start ? 'StartToStart' : 'EndToStart', moveRng); - - if (start) { - rng.collapse(true); - } - } - } - - if (bookmark.start) { - if (bookmark.start.ctrl) { - rng = body.createControlRange(); - rng.addElement(resolveIndexes(bookmark.start.indexes)); - rng.select(); - } else { - rng = body.createTextRange(); - setBookmarkEndPoint(true); - setBookmarkEndPoint(); - rng.select(); - } - } - }; - - this.addRange = function(rng) { - var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, sibling, - doc = selection.dom.doc, body = doc.body, nativeRng, ctrlElm; - - function setEndPoint(start) { - var container, offset, marker, tmpRng, nodes; - - marker = dom.create('a'); - container = start ? startContainer : endContainer; - offset = start ? startOffset : endOffset; - tmpRng = ieRng.duplicate(); - - if (container == doc || container == doc.documentElement) { - container = body; - offset = 0; - } - - if (container.nodeType == 3) { - container.parentNode.insertBefore(marker, container); - tmpRng.moveToElementText(marker); - tmpRng.moveStart('character', offset); - dom.remove(marker); - ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng); - } else { - nodes = container.childNodes; - - if (nodes.length) { - if (offset >= nodes.length) { - dom.insertAfter(marker, nodes[nodes.length - 1]); - } else { - container.insertBefore(marker, nodes[offset]); - } - - tmpRng.moveToElementText(marker); - } else if (container.canHaveHTML) { - // Empty node selection for example|
would become this:|
- sibling = startContainer.previousSibling; - if (sibling && !sibling.hasChildNodes() && dom.isBlock(sibling)) { - sibling.innerHTML = ''; - } else { - sibling = null; - } - - startContainer.innerHTML = ''; - ieRng.moveToElementText(startContainer.lastChild); - ieRng.select(); - dom.doc.selection.clear(); - startContainer.innerHTML = ''; - - if (sibling) { - sibling.innerHTML = ''; - } - return; - } else { - startOffset = dom.nodeIndex(startContainer); - startContainer = startContainer.parentNode; - } - } - - if (startOffset == endOffset - 1) { - try { - ctrlElm = startContainer.childNodes[startOffset]; - ctrlRng = body.createControlRange(); - ctrlRng.addElement(ctrlElm); - ctrlRng.select(); - - // Check if the range produced is on the correct element and is a control range - // On IE 8 it will select the parent contentEditable container if you select an inner element see: #5398 - nativeRng = selection.getRng(); - if (nativeRng.item && ctrlElm === nativeRng.item(0)) { - return; - } - } catch (ex) { - // Ignore - } - } - } - - // Set start/end point of selection - setEndPoint(true); - setEndPoint(); - - // Select the new range and scroll it into view - ieRng.select(); - }; - - // Expose range method - this.getRangeAt = getRange; - } - - return Selection; -}); - -// Included from: js/tinymce/classes/util/VK.js - -/** - * VK.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This file exposes a set of the common KeyCodes for use. Please grow it as needed. - */ -define("tinymce/util/VK", [ - "tinymce/Env" -], function(Env) { - return { - BACKSPACE: 8, - DELETE: 46, - DOWN: 40, - ENTER: 13, - LEFT: 37, - RIGHT: 39, - SPACEBAR: 32, - TAB: 9, - UP: 38, - - modifierPressed: function(e) { - return e.shiftKey || e.ctrlKey || e.altKey; - }, - - metaKeyPressed: function(e) { - // Check if ctrl or meta key is pressed also check if alt is false for Polish users - return (Env.mac ? e.metaKey : e.ctrlKey) && !e.altKey; - } - }; -}); - -// Included from: js/tinymce/classes/dom/ControlSelection.js - -/** - * ControlSelection.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles control selection of elements. Controls are elements - * that can be resized and needs to be selected as a whole. It adds custom resize handles - * to all browser engines that support properly disabling the built in resize logic. - * - * @class tinymce.dom.ControlSelection - */ -define("tinymce/dom/ControlSelection", [ - "tinymce/util/VK", - "tinymce/util/Tools", - "tinymce/Env" -], function(VK, Tools, Env) { - return function(selection, editor) { - var dom = editor.dom, each = Tools.each; - var selectedElm, selectedElmGhost, resizeHandles, selectedHandle, lastMouseDownEvent; - var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted; - var width, height, editableDoc = editor.getDoc(), rootDocument = document, isIE = Env.ie && Env.ie < 11; - - // Details about each resize handle how to scale etc - resizeHandles = { - // Name: x multiplier, y multiplier, delta size x, delta size y - n: [0.5, 0, 0, -1], - e: [1, 0.5, 1, 0], - s: [0.5, 1, 0, 1], - w: [0, 0.5, -1, 0], - nw: [0, 0, -1, -1], - ne: [1, 0, 1, -1], - se: [1, 1, 1, 1], - sw: [0, 1, -1, 1] - }; - - // Add CSS for resize handles, cloned element and selected - var rootClass = '.mce-content-body'; - editor.contentStyles.push( - rootClass + ' div.mce-resizehandle {' + - 'position: absolute;' + - 'border: 1px solid black;' + - 'background: #FFF;' + - 'width: 5px;' + - 'height: 5px;' + - 'z-index: 10000' + - '}' + - rootClass + ' .mce-resizehandle:hover {' + - 'background: #000' + - '}' + - rootClass + ' img[data-mce-selected], hr[data-mce-selected] {' + - 'outline: 1px solid black;' + - 'resize: none' + // Have been talks about implementing this in browsers - '}' + - rootClass + ' .mce-clonedresizable {' + - 'position: absolute;' + - (Env.gecko ? '' : 'outline: 1px dashed black;') + // Gecko produces trails while resizing - 'opacity: .5;' + - 'filter: alpha(opacity=50);' + - 'z-index: 10000' + - '}' - ); - - function isResizable(elm) { - var selector = editor.settings.object_resizing; - - if (selector === false || Env.iOS) { - return false; - } - - if (typeof selector != 'string') { - selector = 'table,img,div'; - } - - if (elm.getAttribute('data-mce-resize') === 'false') { - return false; - } - - return editor.dom.is(elm, selector); - } - - function resizeGhostElement(e) { - var deltaX, deltaY; - - // Calc new width/height - deltaX = e.screenX - startX; - deltaY = e.screenY - startY; - - // Calc new size - width = deltaX * selectedHandle[2] + startW; - height = deltaY * selectedHandle[3] + startH; - - // Never scale down lower than 5 pixels - width = width < 5 ? 5 : width; - height = height < 5 ? 5 : height; - - // Constrain proportions when modifier key is pressed or if the nw, ne, sw, se corners are moved on an image - if (VK.modifierPressed(e) || (selectedElm.nodeName == "IMG" && selectedHandle[2] * selectedHandle[3] !== 0)) { - width = Math.round(height / ratio); - height = Math.round(width * ratio); - } - - // Update ghost size - dom.setStyles(selectedElmGhost, { - width: width, - height: height - }); - - // Update ghost X position if needed - if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) { - dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width)); - } - - // Update ghost Y position if needed - if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) { - dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height)); - } - - if (!resizeStarted) { - editor.fire('ObjectResizeStart', {target: selectedElm, width: startW, height: startH}); - resizeStarted = true; - } - } - - function endGhostResize() { - resizeStarted = false; - - function setSizeProp(name, value) { - if (value) { - // Resize by using style or attribute - if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) { - dom.setStyle(selectedElm, name, value); - } else { - dom.setAttrib(selectedElm, name, value); - } - } - } - - // Set width/height properties - setSizeProp('width', width); - setSizeProp('height', height); - - dom.unbind(editableDoc, 'mousemove', resizeGhostElement); - dom.unbind(editableDoc, 'mouseup', endGhostResize); - - if (rootDocument != editableDoc) { - dom.unbind(rootDocument, 'mousemove', resizeGhostElement); - dom.unbind(rootDocument, 'mouseup', endGhostResize); - } - - // Remove ghost and update resize handle positions - dom.remove(selectedElmGhost); - - if (!isIE || selectedElm.nodeName == "TABLE") { - showResizeRect(selectedElm); - } - - editor.fire('ObjectResized', {target: selectedElm, width: width, height: height}); - editor.nodeChanged(); - } - - function showResizeRect(targetElm, mouseDownHandleName, mouseDownEvent) { - var position, targetWidth, targetHeight, e, rect, offsetParent = editor.getBody(); - - unbindResizeHandleEvents(); - - // Get position and size of target - position = dom.getPos(targetElm, offsetParent); - selectedElmX = position.x; - selectedElmY = position.y; - rect = targetElm.getBoundingClientRect(); // Fix for Gecko offsetHeight for table with caption - targetWidth = rect.width || (rect.right - rect.left); - targetHeight = rect.height || (rect.bottom - rect.top); - - // Reset width/height if user selects a new image/table - if (selectedElm != targetElm) { - detachResizeStartListener(); - selectedElm = targetElm; - width = height = 0; - } - - // Makes it possible to disable resizing - e = editor.fire('ObjectSelected', {target: targetElm}); - - if (isResizable(targetElm) && !e.isDefaultPrevented()) { - each(resizeHandles, function(handle, name) { - var handleElm, handlerContainerElm; - - function startDrag(e) { - startX = e.screenX; - startY = e.screenY; - startW = selectedElm.clientWidth; - startH = selectedElm.clientHeight; - ratio = startH / startW; - selectedHandle = handle; - - selectedElmGhost = selectedElm.cloneNode(true); - dom.addClass(selectedElmGhost, 'mce-clonedresizable'); - selectedElmGhost.contentEditable = false; // Hides IE move layer cursor - selectedElmGhost.unSelectabe = true; - dom.setStyles(selectedElmGhost, { - left: selectedElmX, - top: selectedElmY, - margin: 0 - }); - - selectedElmGhost.removeAttribute('data-mce-selected'); - editor.getBody().appendChild(selectedElmGhost); - - dom.bind(editableDoc, 'mousemove', resizeGhostElement); - dom.bind(editableDoc, 'mouseup', endGhostResize); - - if (rootDocument != editableDoc) { - dom.bind(rootDocument, 'mousemove', resizeGhostElement); - dom.bind(rootDocument, 'mouseup', endGhostResize); - } - } - - if (mouseDownHandleName) { - // Drag started by IE native resizestart - if (name == mouseDownHandleName) { - startDrag(mouseDownEvent); - } - - return; - } - - // Get existing or render resize handle - handleElm = dom.get('mceResizeHandle' + name); - if (!handleElm) { - handlerContainerElm = editor.getBody(); - - handleElm = dom.add(handlerContainerElm, 'div', { - id: 'mceResizeHandle' + name, - 'data-mce-bogus': true, - 'class': 'mce-resizehandle', - unselectable: true, - style: 'cursor:' + name + '-resize; margin:0; padding:0' - }); - - // Hides IE move layer cursor - // If we set it on Chrome we get this wounderful bug: #6725 - if (Env.ie) { - handleElm.contentEditable = false; - } - } else { - dom.show(handleElm); - } - - if (!handle.elm) { - dom.bind(handleElm, 'mousedown', function(e) { - e.stopImmediatePropagation(); - e.preventDefault(); - startDrag(e); - }); - - handle.elm = handleElm; - } - - /* - var halfHandleW = handleElm.offsetWidth / 2; - var halfHandleH = handleElm.offsetHeight / 2; - - // Position element - dom.setStyles(handleElm, { - left: Math.floor((targetWidth * handle[0] + selectedElmX) - halfHandleW + (handle[2] * halfHandleW)), - top: Math.floor((targetHeight * handle[1] + selectedElmY) - halfHandleH + (handle[3] * halfHandleH)) - }); - */ - - // Position element - dom.setStyles(handleElm, { - left: (targetWidth * handle[0] + selectedElmX) - (handleElm.offsetWidth / 2), - top: (targetHeight * handle[1] + selectedElmY) - (handleElm.offsetHeight / 2) - }); - }); - } else { - hideResizeRect(); - } - - selectedElm.setAttribute('data-mce-selected', '1'); - } - - function hideResizeRect() { - var name, handleElm; - - unbindResizeHandleEvents(); - - if (selectedElm) { - selectedElm.removeAttribute('data-mce-selected'); - } - - for (name in resizeHandles) { - handleElm = dom.get('mceResizeHandle' + name); - if (handleElm) { - dom.unbind(handleElm); - dom.remove(handleElm); - } - } - } - - function updateResizeRect(e) { - var controlElm; - - function isChildOrEqual(node, parent) { - if (node) { - do { - if (node === parent) { - return true; - } - } while ((node = node.parentNode)); - } - } - - // Remove data-mce-selected from all elements since they might have been copied using Ctrl+c/v - each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function(img) { - img.removeAttribute('data-mce-selected'); - }); - - controlElm = e.type == 'mousedown' ? e.target : selection.getNode(); - controlElm = dom.getParent(controlElm, isIE ? 'table' : 'table,img,hr'); - - if (isChildOrEqual(controlElm, editor.getBody())) { - disableGeckoResize(); - - if (isChildOrEqual(selection.getStart(), controlElm) && isChildOrEqual(selection.getEnd(), controlElm)) { - if (!isIE || (controlElm != selection.getStart() && selection.getStart().nodeName !== 'IMG')) { - showResizeRect(controlElm); - return; - } - } - } - - hideResizeRect(); - } - - function attachEvent(elm, name, func) { - if (elm && elm.attachEvent) { - elm.attachEvent('on' + name, func); - } - } - - function detachEvent(elm, name, func) { - if (elm && elm.detachEvent) { - elm.detachEvent('on' + name, func); - } - } - - function resizeNativeStart(e) { - var target = e.srcElement, pos, name, corner, cornerX, cornerY, relativeX, relativeY; - - pos = target.getBoundingClientRect(); - relativeX = lastMouseDownEvent.clientX - pos.left; - relativeY = lastMouseDownEvent.clientY - pos.top; - - // Figure out what corner we are draging on - for (name in resizeHandles) { - corner = resizeHandles[name]; - - cornerX = target.offsetWidth * corner[0]; - cornerY = target.offsetHeight * corner[1]; - - if (Math.abs(cornerX - relativeX) < 8 && Math.abs(cornerY - relativeY) < 8) { - selectedHandle = corner; - break; - } - } - - // Remove native selection and let the magic begin - resizeStarted = true; - editor.getDoc().selection.empty(); - showResizeRect(target, name, lastMouseDownEvent); - } - - function nativeControlSelect(e) { - var target = e.srcElement; - - if (target != selectedElm) { - detachResizeStartListener(); - - if (target.id.indexOf('mceResizeHandle') === 0) { - e.returnValue = false; - return; - } - - if (target.nodeName == 'IMG' || target.nodeName == 'TABLE') { - hideResizeRect(); - selectedElm = target; - attachEvent(target, 'resizestart', resizeNativeStart); - } - } - } - - function detachResizeStartListener() { - detachEvent(selectedElm, 'resizestart', resizeNativeStart); - } - - function unbindResizeHandleEvents() { - for (var name in resizeHandles) { - var handle = resizeHandles[name]; - - if (handle.elm) { - dom.unbind(handle.elm); - delete handle.elm; - } - } - } - - function disableGeckoResize() { - try { - // Disable object resizing on Gecko - editor.getDoc().execCommand('enableObjectResizing', false, false); - } catch (ex) { - // Ignore - } - } - - function controlSelect(elm) { - var ctrlRng; - - if (!isIE) { - return; - } - - ctrlRng = editableDoc.body.createControlRange(); - - try { - ctrlRng.addElement(elm); - ctrlRng.select(); - return true; - } catch (ex) { - // Ignore since the element can't be control selected for example a P tag - } - } - - editor.on('init', function() { - if (isIE) { - // Hide the resize rect on resize and reselect the image - editor.on('ObjectResized', function(e) { - if (e.target.nodeName != 'TABLE') { - hideResizeRect(); - controlSelect(e.target); - } - }); - - attachEvent(editor.getBody(), 'controlselect', nativeControlSelect); - - editor.on('mousedown', function(e) { - lastMouseDownEvent = e; - }); - } else { - disableGeckoResize(); - - if (Env.ie >= 11) { - // TODO: Drag/drop doesn't work - editor.on('mouseup', function(e) { - var nodeName = e.target.nodeName; - - if (/^(TABLE|IMG|HR)$/.test(nodeName)) { - editor.selection.select(e.target, nodeName == 'TABLE'); - editor.nodeChanged(); - } - }); - - editor.dom.bind(editor.getBody(), 'mscontrolselect', function(e) { - if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) { - e.preventDefault(); - - // This moves the selection from being a control selection to a text like selection like in WebKit #6753 - // TODO: Fix this the day IE works like other browsers without this nasty native ugly control selections. - if (e.target.tagName == 'IMG') { - window.setTimeout(function() { - editor.selection.select(e.target); - }, 0); - } - } - }); - } - } - - editor.on('nodechange mousedown mouseup ResizeEditor', updateResizeRect); - - // Update resize rect while typing in a table - editor.on('keydown keyup', function(e) { - if (selectedElm && selectedElm.nodeName == "TABLE") { - updateResizeRect(e); - } - }); - - // Hide rect on focusout since it would float on top of windows otherwise - //editor.on('focusout', hideResizeRect); - }); - - editor.on('remove', unbindResizeHandleEvents); - - function destroy() { - selectedElm = selectedElmGhost = null; - - if (isIE) { - detachResizeStartListener(); - detachEvent(editor.getBody(), 'controlselect', nativeControlSelect); - } - } - - return { - isResizable: isResizable, - showResizeRect: showResizeRect, - hideResizeRect: hideResizeRect, - updateResizeRect: updateResizeRect, - controlSelect: controlSelect, - destroy: destroy - }; - }; -}); - -// Included from: js/tinymce/classes/dom/RangeUtils.js - -/** - * Range.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * RangeUtils - * - * @class tinymce.dom.RangeUtils - * @private - */ -define("tinymce/dom/RangeUtils", [ - "tinymce/util/Tools", - "tinymce/dom/TreeWalker" -], function(Tools, TreeWalker) { - var each = Tools.each; - - function RangeUtils(dom) { - /** - * Walks the specified range like object and executes the callback for each sibling collection it finds. - * - * @method walk - * @param {Object} rng Range like object. - * @param {function} callback Callback function to execute for each sibling collection. - */ - this.walk = function(rng, callback) { - var startContainer = rng.startContainer, - startOffset = rng.startOffset, - endContainer = rng.endContainer, - endOffset = rng.endOffset, - ancestor, startPoint, - endPoint, node, parent, siblings, nodes; - - // Handle table cell selection the table plugin enables - // you to fake select table cells and perform formatting actions on them - nodes = dom.select('td.mce-item-selected,th.mce-item-selected'); - if (nodes.length > 0) { - each(nodes, function(node) { - callback([node]); - }); - - return; - } - - /** - * Excludes start/end text node if they are out side the range - * - * @private - * @param {Array} nodes Nodes to exclude items from. - * @return {Array} Array with nodes excluding the start/end container if needed. - */ - function exclude(nodes) { - var node; - - // First node is excluded - node = nodes[0]; - if (node.nodeType === 3 && node === startContainer && startOffset >= node.nodeValue.length) { - nodes.splice(0, 1); - } - - // Last node is excluded - node = nodes[nodes.length - 1]; - if (endOffset === 0 && nodes.length > 0 && node === endContainer && node.nodeType === 3) { - nodes.splice(nodes.length - 1, 1); - } - - return nodes; - } - - /** - * Collects siblings - * - * @private - * @param {Node} node Node to collect siblings from. - * @param {String} name Name of the sibling to check for. - * @return {Array} Array of collected siblings. - */ - function collectSiblings(node, name, end_node) { - var siblings = []; - - for (; node && node != end_node; node = node[name]) { - siblings.push(node); - } - - return siblings; - } - - /** - * Find an end point this is the node just before the common ancestor root. - * - * @private - * @param {Node} node Node to start at. - * @param {Node} root Root/ancestor element to stop just before. - * @return {Node} Node just before the root element. - */ - function findEndPoint(node, root) { - do { - if (node.parentNode == root) { - return node; - } - - node = node.parentNode; - } while(node); - } - - function walkBoundary(start_node, end_node, next) { - var siblingName = next ? 'nextSibling' : 'previousSibling'; - - for (node = start_node, parent = node.parentNode; node && node != end_node; node = parent) { - parent = node.parentNode; - siblings = collectSiblings(node == start_node ? node : node[siblingName], siblingName); - - if (siblings.length) { - if (!next) { - siblings.reverse(); - } - - callback(exclude(siblings)); - } - } - } - - // If index based start position then resolve it - if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) { - startContainer = startContainer.childNodes[startOffset]; - } - - // If index based end position then resolve it - if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) { - endContainer = endContainer.childNodes[Math.min(endOffset - 1, endContainer.childNodes.length - 1)]; - } - - // Same container - if (startContainer == endContainer) { - return callback(exclude([startContainer])); - } - - // Find common ancestor and end points - ancestor = dom.findCommonAncestor(startContainer, endContainer); - - // Process left side - for (node = startContainer; node; node = node.parentNode) { - if (node === endContainer) { - return walkBoundary(startContainer, ancestor, true); - } - - if (node === ancestor) { - break; - } - } - - // Process right side - for (node = endContainer; node; node = node.parentNode) { - if (node === startContainer) { - return walkBoundary(endContainer, ancestor); - } - - if (node === ancestor) { - break; - } - } - - // Find start/end point - startPoint = findEndPoint(startContainer, ancestor) || startContainer; - endPoint = findEndPoint(endContainer, ancestor) || endContainer; - - // Walk left leaf - walkBoundary(startContainer, startPoint, true); - - // Walk the middle from start to end point - siblings = collectSiblings( - startPoint == startContainer ? startPoint : startPoint.nextSibling, - 'nextSibling', - endPoint == endContainer ? endPoint.nextSibling : endPoint - ); - - if (siblings.length) { - callback(exclude(siblings)); - } - - // Walk right leaf - walkBoundary(endContainer, endPoint); - }; - - /** - * Splits the specified range at it's start/end points. - * - * @private - * @param {Range/RangeObject} rng Range to split. - * @return {Object} Range position object. - */ - this.split = function(rng) { - var startContainer = rng.startContainer, - startOffset = rng.startOffset, - endContainer = rng.endContainer, - endOffset = rng.endOffset; - - function splitText(node, offset) { - return node.splitText(offset); - } - - // Handle single text node - if (startContainer == endContainer && startContainer.nodeType == 3) { - if (startOffset > 0 && startOffset < startContainer.nodeValue.length) { - endContainer = splitText(startContainer, startOffset); - startContainer = endContainer.previousSibling; - - if (endOffset > startOffset) { - endOffset = endOffset - startOffset; - startContainer = endContainer = splitText(endContainer, endOffset).previousSibling; - endOffset = endContainer.nodeValue.length; - startOffset = 0; - } else { - endOffset = 0; - } - } - } else { - // Split startContainer text node if needed - if (startContainer.nodeType == 3 && startOffset > 0 && startOffset < startContainer.nodeValue.length) { - startContainer = splitText(startContainer, startOffset); - startOffset = 0; - } - - // Split endContainer text node if needed - if (endContainer.nodeType == 3 && endOffset > 0 && endOffset < endContainer.nodeValue.length) { - endContainer = splitText(endContainer, endOffset).previousSibling; - endOffset = endContainer.nodeValue.length; - } - } - - return { - startContainer: startContainer, - startOffset: startOffset, - endContainer: endContainer, - endOffset: endOffset - }; - }; - - /** - * Normalizes the specified range by finding the closest best suitable caret location. - * - * @private - * @param {Range} rng Range to normalize. - * @return {Boolean} True/false if the specified range was normalized or not. - */ - this.normalize = function(rng) { - var normalized, collapsed; - - function normalizeEndPoint(start) { - var container, offset, walker, body = dom.getRoot(), node, nonEmptyElementsMap, nodeName; - var directionLeft, isAfterNode; - - function hasBrBeforeAfter(node, left) { - var walker = new TreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || body); - - while ((node = walker[left ? 'prev' : 'next']())) { - if (node.nodeName === "BR") { - return true; - } - } - } - - function isPrevNode(node, name) { - return node.previousSibling && node.previousSibling.nodeName == name; - } - - // Walks the dom left/right to find a suitable text node to move the endpoint into - // It will only walk within the current parent block or body and will stop if it hits a block or a BR/IMG - function findTextNodeRelative(left, startNode) { - var walker, lastInlineElement, parentBlockContainer; - - startNode = startNode || container; - parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body; - - // Lean left before the BR element if it's the only BR within a block element. Gecko bug: #6680 - // This:
|
|
x|
]
- rng.moveToElementText(rng2.parentElement()); - if (rng.compareEndPoints('StartToEnd', rng2) === 0) { - rng2.move('character', -1); - } - - rng2.pasteHTML('' + chr + ''); - } - } catch (ex) { - // IE might throw unspecified error so lets ignore it - return null; - } - } else { - // Control selection - element = rng.item(0); - name = element.nodeName; - - return {name: name, index: findIndex(name, element)}; - } - } else { - element = self.getNode(); - name = element.nodeName; - if (name == 'IMG') { - return {name: name, index: findIndex(name, element)}; - } - - // W3C method - rng2 = normalizeTableCellSelection(rng.cloneRange()); - - // Insert end marker - if (!collapsed) { - rng2.collapse(false); - rng2.insertNode(dom.create('span', {'data-mce-type': "bookmark", id: id + '_end', style: styles}, chr)); - } - - rng = normalizeTableCellSelection(rng); - rng.collapse(true); - rng.insertNode(dom.create('span', {'data-mce-type': "bookmark", id: id + '_start', style: styles}, chr)); - } - - self.moveToBookmark({id: id, keep: 1}); - - return {id: id}; - }, - - /** - * Restores the selection to the specified bookmark. - * - * @method moveToBookmark - * @param {Object} bookmark Bookmark to restore selection from. - * @return {Boolean} true/false if it was successful or not. - * @example - * // Stores a bookmark of the current selection - * var bm = tinymce.activeEditor.selection.getBookmark(); - * - * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content'); - * - * // Restore the selection bookmark - * tinymce.activeEditor.selection.moveToBookmark(bm); - */ - moveToBookmark: function(bookmark) { - var self = this, dom = self.dom, rng, root, startContainer, endContainer, startOffset, endOffset; - - function setEndPoint(start) { - var point = bookmark[start ? 'start' : 'end'], i, node, offset, children; - - if (point) { - offset = point[0]; - - // Find container node - for (node = root, i = point.length - 1; i >= 1; i--) { - children = node.childNodes; - - if (point[i] > children.length - 1) { - return; - } - - node = children[point[i]]; - } - - // Move text offset to best suitable location - if (node.nodeType === 3) { - offset = Math.min(point[0], node.nodeValue.length); - } - - // Move element offset to best suitable location - if (node.nodeType === 1) { - offset = Math.min(point[0], node.childNodes.length); - } - - // Set offset within container node - if (start) { - rng.setStart(node, offset); - } else { - rng.setEnd(node, offset); - } - } - - return true; - } - - function restoreEndPoint(suffix) { - var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep; - - if (marker) { - node = marker.parentNode; - - if (suffix == 'start') { - if (!keep) { - idx = dom.nodeIndex(marker); - } else { - node = marker.firstChild; - idx = 1; - } - - startContainer = endContainer = node; - startOffset = endOffset = idx; - } else { - if (!keep) { - idx = dom.nodeIndex(marker); - } else { - node = marker.firstChild; - idx = 1; - } - - endContainer = node; - endOffset = idx; - } - - if (!keep) { - prev = marker.previousSibling; - next = marker.nextSibling; - - // Remove all marker text nodes - each(grep(marker.childNodes), function(node) { - if (node.nodeType == 3) { - node.nodeValue = node.nodeValue.replace(/\uFEFF/g, ''); - } - }); - - // Remove marker but keep children if for example contents where inserted into the marker - // Also remove duplicated instances of the marker for example by a - // split operation or by WebKit auto split on paste feature - while ((marker = dom.get(bookmark.id + '_' + suffix))) { - dom.remove(marker, 1); - } - - // If siblings are text nodes then merge them unless it's Opera since it some how removes the node - // and we are sniffing since adding a lot of detection code for a browser with 3% of the market - // isn't worth the effort. Sorry, Opera but it's just a fact - if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !isOpera) { - idx = prev.nodeValue.length; - prev.appendData(next.nodeValue); - dom.remove(next); - - if (suffix == 'start') { - startContainer = endContainer = prev; - startOffset = endOffset = idx; - } else { - endContainer = prev; - endOffset = idx; - } - } - } - } - } - - function addBogus(node) { - // Adds a bogus BR element for empty block elements - if (dom.isBlock(node) && !node.innerHTML && !isIE) { - node.innerHTML = '*texttext*
! - // This will reduce the number of wrapper elements that needs to be created - // Move start point up the tree - if (format[0].inline || format[0].block_expand) { - if (!format[0].inline || (startContainer.nodeType != 3 || startOffset === 0)) { - startContainer = findParentContainer(true); - } - - if (!format[0].inline || (endContainer.nodeType != 3 || endOffset === endContainer.nodeValue.length)) { - endContainer = findParentContainer(); - } - } - - // Expand start/end container to matching selector - if (format[0].selector && format[0].expand !== FALSE && !format[0].inline) { - // Find new startContainer/endContainer if there is better one - startContainer = findSelectorEndPoint(startContainer, 'previousSibling'); - endContainer = findSelectorEndPoint(endContainer, 'nextSibling'); - } - - // Expand start/end container to matching block element or text node - if (format[0].block || format[0].selector) { - // Find new startContainer/endContainer if there is better one - startContainer = findBlockEndPoint(startContainer, 'previousSibling'); - endContainer = findBlockEndPoint(endContainer, 'nextSibling'); - - // Non block element then try to expand up the leaf - if (format[0].block) { - if (!isBlock(startContainer)) { - startContainer = findParentContainer(true); - } - - if (!isBlock(endContainer)) { - endContainer = findParentContainer(); - } - } - } - - // Setup index for startContainer - if (startContainer.nodeType == 1) { - startOffset = nodeIndex(startContainer); - startContainer = startContainer.parentNode; - } - - // Setup index for endContainer - if (endContainer.nodeType == 1) { - endOffset = nodeIndex(endContainer) + 1; - endContainer = endContainer.parentNode; - } - - // Return new range like object - return { - startContainer: startContainer, - startOffset: startOffset, - endContainer: endContainer, - endOffset: endOffset - }; - } - - /** - * Removes the specified format for the specified node. It will also remove the node if it doesn't have - * any attributes if the format specifies it to do so. - * - * @private - * @param {Object} format Format object with items to remove from node. - * @param {Object} vars Name/value object with variables to apply to format. - * @param {Node} node Node to remove the format styles on. - * @param {Node} compare_node Optional compare node, if specified the styles will be compared to that node. - * @return {Boolean} True/false if the node was removed or not. - */ - function removeFormat(format, vars, node, compare_node) { - var i, attrs, stylesModified; - - // Check if node matches format - if (!matchName(node, format)) { - return FALSE; - } - - // Should we compare with format attribs and styles - if (format.remove != 'all') { - // Remove styles - each(format.styles, function(value, name) { - value = normalizeStyleValue(replaceVars(value, vars), name); - - // Indexed array - if (typeof(name) === 'number') { - name = value; - compare_node = 0; - } - - if (!compare_node || isEq(getStyle(compare_node, name), value)) { - dom.setStyle(node, name, ''); - } - - stylesModified = 1; - }); - - // Remove style attribute if it's empty - if (stylesModified && dom.getAttrib(node, 'style') === '') { - node.removeAttribute('style'); - node.removeAttribute('data-mce-style'); - } - - // Remove attributes - each(format.attributes, function(value, name) { - var valueOut; - - value = replaceVars(value, vars); - - // Indexed array - if (typeof(name) === 'number') { - name = value; - compare_node = 0; - } - - if (!compare_node || isEq(dom.getAttrib(compare_node, name), value)) { - // Keep internal classes - if (name == 'class') { - value = dom.getAttrib(node, name); - if (value) { - // Build new class value where everything is removed except the internal prefixed classes - valueOut = ''; - each(value.split(/\s+/), function(cls) { - if (/mce\w+/.test(cls)) { - valueOut += (valueOut ? ' ' : '') + cls; - } - }); - - // We got some internal classes left - if (valueOut) { - dom.setAttrib(node, name, valueOut); - return; - } - } - } - - // IE6 has a bug where the attribute doesn't get removed correctly - if (name == "class") { - node.removeAttribute('className'); - } - - // Remove mce prefixed attributes - if (MCE_ATTR_RE.test(name)) { - node.removeAttribute('data-mce-' + name); - } - - node.removeAttribute(name); - } - }); - - // Remove classes - each(format.classes, function(value) { - value = replaceVars(value, vars); - - if (!compare_node || dom.hasClass(compare_node, value)) { - dom.removeClass(node, value); - } - }); - - // Check for non internal attributes - attrs = dom.getAttribs(node); - for (i = 0; i < attrs.length; i++) { - if (attrs[i].nodeName.indexOf('_') !== 0) { - return FALSE; - } - } - } - - // Remove the inline child if it's empty for example or - if (format.remove != 'none') { - removeNode(node, format); - return TRUE; - } - } - - /** - * Removes the node and wrap it's children in paragraphs before doing so or - * appends BR elements to the beginning/end of the block element if forcedRootBlocks is disabled. - * - * If the div in the node below gets removed: - * text|
- formatNode.parentNode.replaceChild(caretContainer, formatNode); - } else { - // Insert caret container after the formated node - dom.insertAfter(caretContainer, formatNode); - } - - // Move selection to text node - selection.setCursorLocation(node, 1); - - // If the formatNode is empty, we can remove it safely. - if (dom.isEmpty(formatNode)) { - dom.remove(formatNode); - } - } - } - - // Checks if the parent caret container node isn't empty if that is the case it - // will remove the bogus state on all children that isn't empty - function unmarkBogusCaretParents() { - var caretContainer; - - caretContainer = getParentCaretContainer(selection.getStart()); - if (caretContainer && !dom.isEmpty(caretContainer)) { - walk(caretContainer, function(node) { - if (node.nodeType == 1 && node.id !== caretContainerId && !dom.isEmpty(node)) { - dom.setAttrib(node, 'data-mce-bogus', null); - } - }, 'childNodes'); - } - } - - // Only bind the caret events once - if (!ed._hasCaretEvents) { - // Mark current caret container elements as bogus when getting the contents so we don't end up with empty elements - markCaretContainersBogus = function() { - var nodes = [], i; - - if (isCaretContainerEmpty(getParentCaretContainer(selection.getStart()), nodes)) { - // Mark children - i = nodes.length; - while (i--) { - dom.setAttrib(nodes[i], 'data-mce-bogus', '1'); - } - } - }; - - disableCaretContainer = function(e) { - var keyCode = e.keyCode; - - removeCaretContainer(); - - // Remove caret container on keydown and it's a backspace, enter or left/right arrow keys - if (keyCode == 8 || keyCode == 37 || keyCode == 39) { - removeCaretContainer(getParentCaretContainer(selection.getStart())); - } - - unmarkBogusCaretParents(); - }; - - // Remove bogus state if they got filled by contents using editor.selection.setContent - ed.on('SetContent', function(e) { - if (e.selection) { - unmarkBogusCaretParents(); - } - }); - ed._hasCaretEvents = true; - } - - // Do apply or remove caret format - if (type == "apply") { - applyCaretFormat(); - } else { - removeCaretFormat(); - } - } - - /** - * Moves the start to the first suitable text node. - */ - function moveStart(rng) { - var container = rng.startContainer, - offset = rng.startOffset, isAtEndOfText, - walker, node, nodes, tmpNode; - - // Convert text node into index if possible - if (container.nodeType == 3 && offset >= container.nodeValue.length) { - // Get the parent container location and walk from there - offset = nodeIndex(container); - container = container.parentNode; - isAtEndOfText = true; - } - - // Move startContainer/startOffset in to a suitable node - if (container.nodeType == 1) { - nodes = container.childNodes; - container = nodes[Math.min(offset, nodes.length - 1)]; - walker = new TreeWalker(container, dom.getParent(container, dom.isBlock)); - - // If offset is at end of the parent node walk to the next one - if (offset > nodes.length - 1 || isAtEndOfText) { - walker.next(); - } - - for (node = walker.current(); node; node = walker.next()) { - if (node.nodeType == 3 && !isWhiteSpaceNode(node)) { - // IE has a "neat" feature where it moves the start node into the closest element - // we can avoid this by inserting an element before it and then remove it after we set the selection - tmpNode = dom.create('a', null, INVISIBLE_CHAR); - node.parentNode.insertBefore(tmpNode, node); - - // Set selection and remove tmpNode - rng.setStart(node, 0); - selection.setRng(rng); - dom.remove(tmpNode); - - return; - } - } - } - } - }; -}); - -// Included from: js/tinymce/classes/UndoManager.js - -/** - * UndoManager.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles the undo/redo history levels for the editor. Since the build in undo/redo has major drawbacks a custom one was needed. - * - * @class tinymce.UndoManager - */ -define("tinymce/UndoManager", [ - "tinymce/Env", - "tinymce/util/Tools" -], function(Env, Tools) { - var trim = Tools.trim, trimContentRegExp; - - trimContentRegExp = new RegExp([ - ']+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\\/span>', // Trim bogus spans like caret containers - 'x
becomes this:x
- function trimInlineElementsOnLeftSideOfBlock(block) { - var node = block, firstChilds = [], i; - - // Find inner most first child ex:*
- while ((node = node.firstChild)) { - if (dom.isBlock(node)) { - return; - } - - if (node.nodeType == 1 && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) { - firstChilds.push(node); - } - } - - i = firstChilds.length; - while (i--) { - node = firstChilds[i]; - if (!node.hasChildNodes() || (node.firstChild == node.lastChild && node.firstChild.nodeValue === '')) { - dom.remove(node); - } else { - // Remove see #5381 - if (node.nodeName == "A" && (node.innerText || node.textContent) === ' ') { - dom.remove(node); - } - } - } - } - - // Moves the caret to a suitable position within the root for example in the first non - // pure whitespace text node or before an image - function moveToCaretPosition(root) { - var walker, node, rng, lastNode = root, tempElm; - - function firstNonWhiteSpaceNodeSibling(node) { - while (node) { - if (node.nodeType == 1 || (node.nodeType == 3 && node.data && /[\r\n\s]/.test(node.data))) { - return node; - } - - node = node.nextSibling; - } - } - - // Old IE versions doesn't properly render blocks with br elements in them - // For exampletext|
text|text2
|
- rng = selection.getRng(); - var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null); - var body = editor.getBody(); - if (caretElement === body && selection.isCollapsed()) { - if (dom.isBlock(body.firstChild) && dom.isEmpty(body.firstChild)) { - rng = dom.createRng(); - rng.setStart(body.firstChild, 0); - rng.setEnd(body.firstChild, 0); - selection.setRng(rng); - } - } - - // Insert node maker where we will insert the new HTML and get it's parent - if (!selection.isCollapsed()) { - editor.getDoc().execCommand('Delete', false, null); - } - - parentNode = selection.getNode(); - - // Parse the fragment within the context of the parent node - var parserArgs = {context: parentNode.nodeName.toLowerCase()}; - fragment = parser.parse(value, parserArgs); - - // Move the caret to a more suitable location - node = fragment.lastChild; - if (node.attr('id') == 'mce_marker') { - marker = node; - - for (node = node.prev; node; node = node.walk(true)) { - if (node.type == 3 || !dom.isBlock(node.name)) { - node.parent.insert(marker, node, node.name === 'br'); - break; - } - } - } - - // If parser says valid we can insert the contents into that parent - if (!parserArgs.invalid) { - value = serializer.serialize(fragment); - - // Check if parent is empty or only has one BR element then set the innerHTML of that parent - node = parentNode.firstChild; - node2 = parentNode.lastChild; - if (!node || (node === node2 && node.nodeName === 'BR')) { - dom.setHTML(parentNode, value); - } else { - selection.setContent(value); - } - } else { - // If the fragment was invalid within that context then we need - // to parse and process the parent it's inserted into - - // Insert bookmark node and get the parent - selection.setContent(bookmarkHtml); - parentNode = selection.getNode(); - rootNode = editor.getBody(); - - // Opera will return the document node when selection is in root - if (parentNode.nodeType == 9) { - parentNode = node = rootNode; - } else { - node = parentNode; - } - - // Find the ancestor just before the root element - while (node !== rootNode) { - parentNode = node; - node = node.parentNode; - } - - // Get the outer/inner HTML depending on if we are in the root and parser and serialize that - value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode); - value = serializer.serialize( - parser.parse( - // Need to replace by using a function since $ in the contents would otherwise be a problem - value.replace(//i, function() { - return serializer.serialize(fragment); - }) - ) - ); - - // Set the inner/outer HTML depending on if we are in the root or not - if (parentNode == rootNode) { - dom.setHTML(rootNode, value); - } else { - dom.setOuterHTML(parentNode, value); - } - } - - marker = dom.get('mce_marker'); - selection.scrollIntoView(marker); - - // Move selection before marker and remove it - rng = dom.createRng(); - - // If previous sibling is a text node set the selection to the end of that node - node = marker.previousSibling; - if (node && node.nodeType == 3) { - rng.setStart(node, node.nodeValue.length); - - // TODO: Why can't we normalize on IE - if (!isIE) { - node2 = marker.nextSibling; - if (node2 && node2.nodeType == 3) { - node.appendData(node2.data); - node2.parentNode.removeChild(node2); - } - } - } else { - // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node - rng.setStartBefore(marker); - rng.setEndBefore(marker); - } - - // Remove the marker node and set the new range - dom.remove(marker); - selection.setRng(rng); - - // Dispatch after event and add any visual elements needed - editor.fire('SetContent', args); - editor.addVisual(); - }, - - mceInsertRawHTML: function(command, ui, value) { - selection.setContent('tiny_mce_marker'); - editor.setContent( - editor.getContent().replace(/tiny_mce_marker/g, function() { - return value; - }) - ); - }, - - mceToggleFormat: function(command, ui, value) { - toggleFormat(value); - }, - - mceSetContent: function(command, ui, value) { - editor.setContent(value); - }, - - 'Indent,Outdent': function(command) { - var intentValue, indentUnit, value; - - // Setup indent level - intentValue = settings.indentation; - indentUnit = /[a-z%]+$/i.exec(intentValue); - intentValue = parseInt(intentValue, 10); - - if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) { - // If forced_root_blocks is set to false we don't have a block to indent so lets create a div - if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) { - formatter.apply('div'); - } - - each(selection.getSelectedBlocks(), function(element) { - if (element.nodeName != "LI") { - var indentStyleName = editor.getParam('indent_use_margin', false) ? 'margin' : 'padding'; - - indentStyleName += dom.getStyle(element, 'direction', true) == 'rtl' ? 'Right' : 'Left'; - - if (command == 'outdent') { - value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue); - dom.setStyle(element, indentStyleName, value ? value + indentUnit : ''); - } else { - value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit; - dom.setStyle(element, indentStyleName, value); - } - } - }); - } else { - execNativeCommand(command); - } - }, - - mceRepaint: function() { - if (isGecko) { - try { - storeSelection(TRUE); - - if (selection.getSel()) { - selection.getSel().selectAllChildren(editor.getBody()); - } - - selection.collapse(TRUE); - restoreSelection(); - } catch (ex) { - // Ignore - } - } - }, - - InsertHorizontalRule: function() { - editor.execCommand('mceInsertContent', false, '|
- rng = selection.getRng(); - if (!rng.item) { - rng.moveToElementText(root); - rng.select(); - } - } - }, - - "delete": function() { - execNativeCommand("Delete"); - - // Check if body is empty after the delete call if so then set the contents - // to an empty string and move the caret to any block produced by that operation - // this fixes the issue with root blocks not being properly produced after a delete call on IE - var body = editor.getBody(); - - if (dom.isEmpty(body)) { - editor.setContent(''); - - if (body.firstChild && dom.isBlock(body.firstChild)) { - editor.selection.setCursorLocation(body.firstChild, 0); - } else { - editor.selection.setCursorLocation(body, 0); - } - } - }, - - mceNewDocument: function() { - editor.setContent(''); - } - }); - - // Add queryCommandState overrides - addCommands({ - // Override justify commands - 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) { - var name = 'align' + command.substring(7); - var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks(); - var matches = map(nodes, function(node) { - return !!formatter.matchNode(node, name); - }); - return inArray(matches, TRUE) !== -1; - }, - - 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) { - return isFormatMatch(command); - }, - - mceBlockQuote: function() { - return isFormatMatch('blockquote'); - }, - - Outdent: function() { - var node; - - if (settings.inline_styles) { - if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { - return TRUE; - } - - if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { - return TRUE; - } - } - - return ( - queryCommandState('InsertUnorderedList') || - queryCommandState('InsertOrderedList') || - (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')) - ); - }, - - 'InsertUnorderedList,InsertOrderedList': function(command) { - var list = dom.getParent(selection.getNode(), 'ul,ol'); - - return list && - ( - command === 'insertunorderedlist' && list.tagName === 'UL' || - command === 'insertorderedlist' && list.tagName === 'OL' - ); - } - }, 'state'); - - // Add queryCommandValue overrides - addCommands({ - 'FontSize,FontName': function(command) { - var value = 0, parent; - - if ((parent = dom.getParent(selection.getNode(), 'span'))) { - if (command == 'fontsize') { - value = parent.style.fontSize; - } else { - value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase(); - } - } - - return value; - } - }, 'value'); - - // Add undo manager logic - addCommands({ - Undo: function() { - editor.undoManager.undo(); - }, - - Redo: function() { - editor.undoManager.redo(); - } - }); - }; -}); - -// Included from: js/tinymce/classes/util/URI.js - -/** - * URI.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles parsing, modification and serialization of URI/URL strings. - * @class tinymce.util.URI - */ -define("tinymce/util/URI", [ - "tinymce/util/Tools" -], function(Tools) { - var each = Tools.each, trim = Tools.trim; - - /** - * Constructs a new URI instance. - * - * @constructor - * @method URI - * @param {String} url URI string to parse. - * @param {Object} settings Optional settings object. - */ - function URI(url, settings) { - var self = this, baseUri, base_url; - - // Trim whitespace - url = trim(url); - - // Default settings - settings = self.settings = settings || {}; - - // Strange app protocol that isn't http/https or local anchor - // For example: mailto,skype,tel etc. - if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) { - self.source = url; - return; - } - - var isProtocolRelative = url.indexOf('//') === 0; - - // Absolute path with no host, fake host and protocol - if (url.indexOf('/') === 0 && !isProtocolRelative) { - url = (settings.base_uri ? settings.base_uri.protocol || 'http' : 'http') + '://mce_host' + url; - } - - // Relative path http:// or protocol relative //path - if (!/^[\w\-]*:?\/\//.test(url)) { - base_url = settings.base_uri ? settings.base_uri.path : new URI(location.href).directory; - if (settings.base_uri.protocol === "") { - url = '//mce_host' + self.toAbsPath(base_url, url); - } else { - url = ((settings.base_uri && settings.base_uri.protocol) || 'http') + '://mce_host' + self.toAbsPath(base_url, url); - } - } - - // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri) - url = url.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something - - /*jshint maxlen: 255 */ - /*eslint max-len: 0 */ - url = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url); - - each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) { - var part = url[i]; - - // Zope 3 workaround, they use @@something - if (part) { - part = part.replace(/\(mce_at\)/g, '@@'); - } - - self[v] = part; - }); - - baseUri = settings.base_uri; - if (baseUri) { - if (!self.protocol) { - self.protocol = baseUri.protocol; - } - - if (!self.userInfo) { - self.userInfo = baseUri.userInfo; - } - - if (!self.port && self.host === 'mce_host') { - self.port = baseUri.port; - } - - if (!self.host || self.host === 'mce_host') { - self.host = baseUri.host; - } - - self.source = ''; - } - - if (isProtocolRelative) { - self.protocol = ''; - } - - //t.path = t.path || '/'; - } - - URI.prototype = { - /** - * Sets the internal path part of the URI. - * - * @method setPath - * @param {string} path Path string to set. - */ - setPath: function(path) { - var self = this; - - path = /^(.*?)\/?(\w+)?$/.exec(path); - - // Update path parts - self.path = path[0]; - self.directory = path[1]; - self.file = path[2]; - - // Rebuild source - self.source = ''; - self.getURI(); - }, - - /** - * Converts the specified URI into a relative URI based on the current URI instance location. - * - * @method toRelative - * @param {String} uri URI to convert into a relative path/URI. - * @return {String} Relative URI from the point specified in the current URI instance. - * @example - * // Converts an absolute URL to an relative URL url will be somedir/somefile.htm - * var url = new tinymce.util.URI('http://www.site.com/dir/').toRelative('http://www.site.com/dir/somedir/somefile.htm'); - */ - toRelative: function(uri) { - var self = this, output; - - if (uri === "./") { - return uri; - } - - uri = new URI(uri, {base_uri: self}); - - // Not on same domain/port or protocol - if ((uri.host != 'mce_host' && self.host != uri.host && uri.host) || self.port != uri.port || - (self.protocol != uri.protocol && uri.protocol !== "")) { - return uri.getURI(); - } - - var tu = self.getURI(), uu = uri.getURI(); - - // Allow usage of the base_uri when relative_urls = true - if (tu == uu || (tu.charAt(tu.length - 1) == "/" && tu.substr(0, tu.length - 1) == uu)) { - return tu; - } - - output = self.toRelPath(self.path, uri.path); - - // Add query - if (uri.query) { - output += '?' + uri.query; - } - - // Add anchor - if (uri.anchor) { - output += '#' + uri.anchor; - } - - return output; - }, - - /** - * Converts the specified URI into a absolute URI based on the current URI instance location. - * - * @method toAbsolute - * @param {String} uri URI to convert into a relative path/URI. - * @param {Boolean} noHost No host and protocol prefix. - * @return {String} Absolute URI from the point specified in the current URI instance. - * @example - * // Converts an relative URL to an absolute URL url will be http://www.site.com/dir/somedir/somefile.htm - * var url = new tinymce.util.URI('http://www.site.com/dir/').toAbsolute('somedir/somefile.htm'); - */ - toAbsolute: function(uri, noHost) { - uri = new URI(uri, {base_uri: this}); - - return uri.getURI(this.host == uri.host && this.protocol == uri.protocol ? noHost : 0); - }, - - /** - * Converts a absolute path into a relative path. - * - * @method toRelPath - * @param {String} base Base point to convert the path from. - * @param {String} path Absolute path to convert into a relative path. - */ - toRelPath: function(base, path) { - var items, breakPoint = 0, out = '', i, l; - - // Split the paths - base = base.substring(0, base.lastIndexOf('/')); - base = base.split('/'); - items = path.split('/'); - - if (base.length >= items.length) { - for (i = 0, l = base.length; i < l; i++) { - if (i >= items.length || base[i] != items[i]) { - breakPoint = i + 1; - break; - } - } - } - - if (base.length < items.length) { - for (i = 0, l = items.length; i < l; i++) { - if (i >= base.length || base[i] != items[i]) { - breakPoint = i + 1; - break; - } - } - } - - if (breakPoint === 1) { - return path; - } - - for (i = 0, l = base.length - (breakPoint - 1); i < l; i++) { - out += "../"; - } - - for (i = breakPoint - 1, l = items.length; i < l; i++) { - if (i != breakPoint - 1) { - out += "/" + items[i]; - } else { - out += items[i]; - } - } - - return out; - }, - - /** - * Converts a relative path into a absolute path. - * - * @method toAbsPath - * @param {String} base Base point to convert the path from. - * @param {String} path Relative path to convert into an absolute path. - */ - toAbsPath: function(base, path) { - var i, nb = 0, o = [], tr, outPath; - - // Split paths - tr = /\/$/.test(path) ? '/' : ''; - base = base.split('/'); - path = path.split('/'); - - // Remove empty chunks - each(base, function(k) { - if (k) { - o.push(k); - } - }); - - base = o; - - // Merge relURLParts chunks - for (i = path.length - 1, o = []; i >= 0; i--) { - // Ignore empty or . - if (path[i].length === 0 || path[i] === ".") { - continue; - } - - // Is parent - if (path[i] === '..') { - nb++; - continue; - } - - // Move up - if (nb > 0) { - nb--; - continue; - } - - o.push(path[i]); - } - - i = base.length - nb; - - // If /a/b/c or / - if (i <= 0) { - outPath = o.reverse().join('/'); - } else { - outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/'); - } - - // Add front / if it's needed - if (outPath.indexOf('/') !== 0) { - outPath = '/' + outPath; - } - - // Add traling / if it's needed - if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) { - outPath += tr; - } - - return outPath; - }, - - /** - * Returns the full URI of the internal structure. - * - * @method getURI - * @param {Boolean} noProtoHost Optional no host and protocol part. Defaults to false. - */ - getURI: function(noProtoHost) { - var s, self = this; - - // Rebuild source - if (!self.source || noProtoHost) { - s = ''; - - if (!noProtoHost) { - if (self.protocol) { - s += self.protocol + '://'; - } else { - s += '//'; - } - - if (self.userInfo) { - s += self.userInfo + '@'; - } - - if (self.host) { - s += self.host; - } - - if (self.port) { - s += ':' + self.port; - } - } - - if (self.path) { - s += self.path; - } - - if (self.query) { - s += '?' + self.query; - } - - if (self.anchor) { - s += '#' + self.anchor; - } - - self.source = s; - } - - return self.source; - } - }; - - return URI; -}); - -// Included from: js/tinymce/classes/util/Class.js - -/** - * Class.js - * - * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. - */ - -/** - * This utilitiy class is used for easier inheritage. - * - * Features: - * * Exposed super functions: this._super(); - * * Mixins - * * Dummy functions - * * Property functions: var value = object.value(); and object.value(newValue); - * * Static functions - * * Defaults settings - */ -define("tinymce/util/Class", [ - "tinymce/util/Tools" -], function(Tools) { - var each = Tools.each, extend = Tools.extend; - - var extendClass, initializing; - - function Class() { - } - - // Provides classical inheritance, based on code made by John Resig - Class.extend = extendClass = function(prop) { - var self = this, _super = self.prototype, prototype, name, member; - - // The dummy class constructor - function Class() { - var i, mixins, mixin, self = this; - - // All construction is actually done in the init method - if (!initializing) { - // Run class constuctor - if (self.init) { - self.init.apply(self, arguments); - } - - // Run mixin constructors - mixins = self.Mixins; - if (mixins) { - i = mixins.length; - while (i--) { - mixin = mixins[i]; - if (mixin.init) { - mixin.init.apply(self, arguments); - } - } - } - } - } - - // Dummy function, needs to be extended in order to provide functionality - function dummy() { - return this; - } - - // Creates a overloaded method for the class - // this enables you to use this._super(); to call the super function - function createMethod(name, fn) { - return function(){ - var self = this, tmp = self._super, ret; - - self._super = _super[name]; - ret = fn.apply(self, arguments); - self._super = tmp; - - return ret; - }; - } - - // Instantiate a base class (but only create the instance, - // don't run the init constructor) - initializing = true; - prototype = new self(); - initializing = false; - - // Add mixins - if (prop.Mixins) { - each(prop.Mixins, function(mixin) { - mixin = mixin; - - for (var name in mixin) { - if (name !== "init") { - prop[name] = mixin[name]; - } - } - }); - - if (_super.Mixins) { - prop.Mixins = _super.Mixins.concat(prop.Mixins); - } - } - - // Generate dummy methods - if (prop.Methods) { - each(prop.Methods.split(','), function(name) { - prop[name] = dummy; - }); - } - - // Generate property methods - if (prop.Properties) { - each(prop.Properties.split(','), function(name) { - var fieldName = '_' + name; - - prop[name] = function(value) { - var self = this, undef; - - // Set value - if (value !== undef) { - self[fieldName] = value; - - return self; - } - - // Get value - return self[fieldName]; - }; - }); - } - - // Static functions - if (prop.Statics) { - each(prop.Statics, function(func, name) { - Class[name] = func; - }); - } - - // Default settings - if (prop.Defaults && _super.Defaults) { - prop.Defaults = extend({}, _super.Defaults, prop.Defaults); - } - - // Copy the properties over onto the new prototype - for (name in prop) { - member = prop[name]; - - if (typeof member == "function" && _super[name]) { - prototype[name] = createMethod(name, member); - } else { - prototype[name] = member; - } - } - - // Populate our constructed prototype object - Class.prototype = prototype; - - // Enforce the constructor to be what we expect - Class.constructor = Class; - - // And make this class extendible - Class.extend = extendClass; - - return Class; - }; - - return Class; -}); - -// Included from: js/tinymce/classes/ui/Selector.js - -/** - * Selector.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/*eslint no-nested-ternary:0 */ - -/** - * Selector engine, enables you to select controls by using CSS like expressions. - * We currently only support basic CSS expressions to reduce the size of the core - * and the ones we support should be enough for most cases. - * - * @example - * Supported expressions: - * element - * element#name - * element.class - * element[attr] - * element[attr*=value] - * element[attr~=value] - * element[attr!=value] - * element[attr^=value] - * element[attr$=value] - * element: bug on IE 8 #6178
- DOMUtils.DOM.setHTML(elm, html);
- }
- };
-});
-
-// Included from: js/tinymce/classes/ui/Control.js
-
-/**
- * Control.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/*eslint consistent-this:0 */
-
-/**
- * This is the base class for all controls and containers. All UI control instances inherit
- * from this one as it has the base logic needed by all of them.
- *
- * @class tinymce.ui.Control
- */
-define("tinymce/ui/Control", [
- "tinymce/util/Class",
- "tinymce/util/Tools",
- "tinymce/ui/Collection",
- "tinymce/ui/DomUtils"
-], function(Class, Tools, Collection, DomUtils) {
- "use strict";
-
- var nativeEvents = Tools.makeMap("focusin focusout scroll click dblclick mousedown mouseup mousemove mouseover" +
- " mouseout mouseenter mouseleave wheel keydown keypress keyup contextmenu", " ");
-
- var elementIdCache = {};
- var hasMouseWheelEventSupport = "onmousewheel" in document;
- var hasWheelEventSupport = false;
-
- var Control = Class.extend({
- Statics: {
- elementIdCache: elementIdCache
- },
-
- isRtl: function() {
- return Control.rtl;
- },
-
- /**
- * Class/id prefix to use for all controls.
- *
- * @final
- * @field {String} classPrefix
- */
- classPrefix: "mce-",
-
- /**
- * Constructs a new control instance with the specified settings.
- *
- * @constructor
- * @param {Object} settings Name/value object with settings.
- * @setting {String} style Style CSS properties to add.
- * @setting {String} border Border box values example: 1 1 1 1
- * @setting {String} padding Padding box values example: 1 1 1 1
- * @setting {String} margin Margin box values example: 1 1 1 1
- * @setting {Number} minWidth Minimal width for the control.
- * @setting {Number} minHeight Minimal height for the control.
- * @setting {String} classes Space separated list of classes to add.
- * @setting {String} role WAI-ARIA role to use for control.
- * @setting {Boolean} hidden Is the control hidden by default.
- * @setting {Boolean} disabled Is the control disabled by default.
- * @setting {String} name Name of the control instance.
- */
- init: function(settings) {
- var self = this, classes, i;
-
- self.settings = settings = Tools.extend({}, self.Defaults, settings);
-
- // Initial states
- self._id = settings.id || DomUtils.id();
- self._text = self._name = '';
- self._width = self._height = 0;
- self._aria = {role: settings.role};
-
- // Setup classes
- classes = settings.classes;
- if (classes) {
- classes = classes.split(' ');
- classes.map = {};
- i = classes.length;
- while (i--) {
- classes.map[classes[i]] = true;
- }
- }
-
- self._classes = classes || [];
- self.visible(true);
-
- // Set some properties
- Tools.each('title text width height name classes visible disabled active value'.split(' '), function(name) {
- var value = settings[name], undef;
-
- if (value !== undef) {
- self[name](value);
- } else if (self['_' + name] === undef) {
- self['_' + name] = false;
- }
- });
-
- self.on('click', function() {
- if (self.disabled()) {
- return false;
- }
- });
-
- // TODO: Is this needed duplicate code see above?
- if (settings.classes) {
- Tools.each(settings.classes.split(' '), function(cls) {
- self.addClass(cls);
- });
- }
-
- /**
- * Name/value object with settings for the current control.
- *
- * @field {Object} settings
- */
- self.settings = settings;
-
- self._borderBox = self.parseBox(settings.border);
- self._paddingBox = self.parseBox(settings.padding);
- self._marginBox = self.parseBox(settings.margin);
-
- if (settings.hidden) {
- self.hide();
- }
- },
-
- // Will generate getter/setter methods for these properties
- Properties: 'parent,title,text,width,height,disabled,active,name,value',
-
- // Will generate empty dummy functions for these
- Methods: 'renderHtml',
-
- /**
- * Returns the root element to render controls into.
- *
- * @method getContainerElm
- * @return {Element} HTML DOM element to render into.
- */
- getContainerElm: function() {
- return document.body;
- },
-
- /**
- * Returns a control instance for the current DOM element.
- *
- * @method getParentCtrl
- * @param {Element} elm HTML dom element to get parent control from.
- * @return {tinymce.ui.Control} Control instance or undefined.
- */
- getParentCtrl: function(elm) {
- var ctrl, lookup = this.getRoot().controlIdLookup;
-
- while (elm && lookup) {
- ctrl = lookup[elm.id];
- if (ctrl) {
- break;
- }
-
- elm = elm.parentNode;
- }
-
- return ctrl;
- },
-
- /**
- * Parses the specified box value. A box value contains 1-4 properties in clockwise order.
- *
- * @method parseBox
- * @param {String/Number} value Box value "0 1 2 3" or "0" etc.
- * @return {Object} Object with top/right/bottom/left properties.
- * @private
- */
- parseBox: function(value) {
- var len, radix = 10;
-
- if (!value) {
- return;
- }
-
- if (typeof(value) === "number") {
- value = value || 0;
-
- return {
- top: value,
- left: value,
- bottom: value,
- right: value
- };
- }
-
- value = value.split(' ');
- len = value.length;
-
- if (len === 1) {
- value[1] = value[2] = value[3] = value[0];
- } else if (len === 2) {
- value[2] = value[0];
- value[3] = value[1];
- } else if (len === 3) {
- value[3] = value[1];
- }
-
- return {
- top: parseInt(value[0], radix) || 0,
- right: parseInt(value[1], radix) || 0,
- bottom: parseInt(value[2], radix) || 0,
- left: parseInt(value[3], radix) || 0
- };
- },
-
- borderBox: function() {
- return this._borderBox;
- },
-
- paddingBox: function() {
- return this._paddingBox;
- },
-
- marginBox: function() {
- return this._marginBox;
- },
-
- measureBox: function(elm, prefix) {
- function getStyle(name) {
- var defaultView = document.defaultView;
-
- if (defaultView) {
- // Remove camelcase
- name = name.replace(/[A-Z]/g, function(a) {
- return '-' + a;
- });
-
- return defaultView.getComputedStyle(elm, null).getPropertyValue(name);
- }
-
- return elm.currentStyle[name];
- }
-
- function getSide(name) {
- var val = parseFloat(getStyle(name), 10);
-
- return isNaN(val) ? 0 : val;
- }
-
- return {
- top: getSide(prefix + "TopWidth"),
- right: getSide(prefix + "RightWidth"),
- bottom: getSide(prefix + "BottomWidth"),
- left: getSide(prefix + "LeftWidth")
- };
- },
-
- /**
- * Initializes the current controls layout rect.
- * This will be executed by the layout managers to determine the
- * default minWidth/minHeight etc.
- *
- * @method initLayoutRect
- * @return {Object} Layout rect instance.
- */
- initLayoutRect: function() {
- var self = this, settings = self.settings, borderBox, layoutRect;
- var elm = self.getEl(), width, height, minWidth, minHeight, autoResize;
- var startMinWidth, startMinHeight, initialSize;
-
- // Measure the current element
- borderBox = self._borderBox = self._borderBox || self.measureBox(elm, 'border');
- self._paddingBox = self._paddingBox || self.measureBox(elm, 'padding');
- self._marginBox = self._marginBox || self.measureBox(elm, 'margin');
- initialSize = DomUtils.getSize(elm);
-
- // Setup minWidth/minHeight and width/height
- startMinWidth = settings.minWidth;
- startMinHeight = settings.minHeight;
- minWidth = startMinWidth || initialSize.width;
- minHeight = startMinHeight || initialSize.height;
- width = settings.width;
- height = settings.height;
- autoResize = settings.autoResize;
- autoResize = typeof(autoResize) != "undefined" ? autoResize : !width && !height;
-
- width = width || minWidth;
- height = height || minHeight;
-
- var deltaW = borderBox.left + borderBox.right;
- var deltaH = borderBox.top + borderBox.bottom;
-
- var maxW = settings.maxWidth || 0xFFFF;
- var maxH = settings.maxHeight || 0xFFFF;
-
- // Setup initial layout rect
- self._layoutRect = layoutRect = {
- x: settings.x || 0,
- y: settings.y || 0,
- w: width,
- h: height,
- deltaW: deltaW,
- deltaH: deltaH,
- contentW: width - deltaW,
- contentH: height - deltaH,
- innerW: width - deltaW,
- innerH: height - deltaH,
- startMinWidth: startMinWidth || 0,
- startMinHeight: startMinHeight || 0,
- minW: Math.min(minWidth, maxW),
- minH: Math.min(minHeight, maxH),
- maxW: maxW,
- maxH: maxH,
- autoResize: autoResize,
- scrollW: 0
- };
-
- self._lastLayoutRect = {};
-
- return layoutRect;
- },
-
- /**
- * Getter/setter for the current layout rect.
- *
- * @method layoutRect
- * @param {Object} [newRect] Optional new layout rect.
- * @return {tinymce.ui.Control/Object} Current control or rect object.
- */
- layoutRect: function(newRect) {
- var self = this, curRect = self._layoutRect, lastLayoutRect, size, deltaWidth, deltaHeight, undef, repaintControls;
-
- // Initialize default layout rect
- if (!curRect) {
- curRect = self.initLayoutRect();
- }
-
- // Set new rect values
- if (newRect) {
- // Calc deltas between inner and outer sizes
- deltaWidth = curRect.deltaW;
- deltaHeight = curRect.deltaH;
-
- // Set x position
- if (newRect.x !== undef) {
- curRect.x = newRect.x;
- }
-
- // Set y position
- if (newRect.y !== undef) {
- curRect.y = newRect.y;
- }
-
- // Set minW
- if (newRect.minW !== undef) {
- curRect.minW = newRect.minW;
- }
-
- // Set minH
- if (newRect.minH !== undef) {
- curRect.minH = newRect.minH;
- }
-
- // Set new width and calculate inner width
- size = newRect.w;
- if (size !== undef) {
- size = size < curRect.minW ? curRect.minW : size;
- size = size > curRect.maxW ? curRect.maxW : size;
- curRect.w = size;
- curRect.innerW = size - deltaWidth;
- }
-
- // Set new height and calculate inner height
- size = newRect.h;
- if (size !== undef) {
- size = size < curRect.minH ? curRect.minH : size;
- size = size > curRect.maxH ? curRect.maxH : size;
- curRect.h = size;
- curRect.innerH = size - deltaHeight;
- }
-
- // Set new inner width and calculate width
- size = newRect.innerW;
- if (size !== undef) {
- size = size < curRect.minW - deltaWidth ? curRect.minW - deltaWidth : size;
- size = size > curRect.maxW - deltaWidth ? curRect.maxW - deltaWidth : size;
- curRect.innerW = size;
- curRect.w = size + deltaWidth;
- }
-
- // Set new height and calculate inner height
- size = newRect.innerH;
- if (size !== undef) {
- size = size < curRect.minH - deltaHeight ? curRect.minH - deltaHeight : size;
- size = size > curRect.maxH - deltaHeight ? curRect.maxH - deltaHeight : size;
- curRect.innerH = size;
- curRect.h = size + deltaHeight;
- }
-
- // Set new contentW
- if (newRect.contentW !== undef) {
- curRect.contentW = newRect.contentW;
- }
-
- // Set new contentH
- if (newRect.contentH !== undef) {
- curRect.contentH = newRect.contentH;
- }
-
- // Compare last layout rect with the current one to see if we need to repaint or not
- lastLayoutRect = self._lastLayoutRect;
- if (lastLayoutRect.x !== curRect.x || lastLayoutRect.y !== curRect.y ||
- lastLayoutRect.w !== curRect.w || lastLayoutRect.h !== curRect.h) {
- repaintControls = Control.repaintControls;
-
- if (repaintControls) {
- if (repaintControls.map && !repaintControls.map[self._id]) {
- repaintControls.push(self);
- repaintControls.map[self._id] = true;
- }
- }
-
- lastLayoutRect.x = curRect.x;
- lastLayoutRect.y = curRect.y;
- lastLayoutRect.w = curRect.w;
- lastLayoutRect.h = curRect.h;
- }
-
- return self;
- }
-
- return curRect;
- },
-
- /**
- * Repaints the control after a layout operation.
- *
- * @method repaint
- */
- repaint: function() {
- var self = this, style, bodyStyle, rect, borderBox, borderW = 0, borderH = 0, lastRepaintRect, round;
-
- // Use Math.round on all values on IE < 9
- round = !document.createRange ? Math.round : function(value) {
- return value;
- };
-
- style = self.getEl().style;
- rect = self._layoutRect;
- lastRepaintRect = self._lastRepaintRect || {};
-
- borderBox = self._borderBox;
- borderW = borderBox.left + borderBox.right;
- borderH = borderBox.top + borderBox.bottom;
-
- if (rect.x !== lastRepaintRect.x) {
- style.left = round(rect.x) + 'px';
- lastRepaintRect.x = rect.x;
- }
-
- if (rect.y !== lastRepaintRect.y) {
- style.top = round(rect.y) + 'px';
- lastRepaintRect.y = rect.y;
- }
-
- if (rect.w !== lastRepaintRect.w) {
- style.width = round(rect.w - borderW) + 'px';
- lastRepaintRect.w = rect.w;
- }
-
- if (rect.h !== lastRepaintRect.h) {
- style.height = round(rect.h - borderH) + 'px';
- lastRepaintRect.h = rect.h;
- }
-
- // Update body if needed
- if (self._hasBody && rect.innerW !== lastRepaintRect.innerW) {
- bodyStyle = self.getEl('body').style;
- bodyStyle.width = round(rect.innerW) + 'px';
- lastRepaintRect.innerW = rect.innerW;
- }
-
- if (self._hasBody && rect.innerH !== lastRepaintRect.innerH) {
- bodyStyle = bodyStyle || self.getEl('body').style;
- bodyStyle.height = round(rect.innerH) + 'px';
- lastRepaintRect.innerH = rect.innerH;
- }
-
- self._lastRepaintRect = lastRepaintRect;
- self.fire('repaint', {}, false);
- },
-
- /**
- * Binds a callback to the specified event. This event can both be
- * native browser events like "click" or custom ones like PostRender.
- *
- * The callback function will be passed a DOM event like object that enables yout do stop propagation.
- *
- * @method on
- * @param {String} name Name of the event to bind. For example "click".
- * @param {String/function} callback Callback function to execute ones the event occurs.
- * @return {tinymce.ui.Control} Current control object.
- */
- on: function(name, callback) {
- var self = this, bindings, handlers, names, i;
-
- function resolveCallbackName(name) {
- var callback, scope;
-
- return function(e) {
- if (!callback) {
- self.parents().each(function(ctrl) {
- var callbacks = ctrl.settings.callbacks;
-
- if (callbacks && (callback = callbacks[name])) {
- scope = ctrl;
- return false;
- }
- });
- }
-
- return callback.call(scope, e);
- };
- }
-
- if (callback) {
- if (typeof(callback) == 'string') {
- callback = resolveCallbackName(callback);
- }
-
- names = name.toLowerCase().split(' ');
- i = names.length;
- while (i--) {
- name = names[i];
-
- bindings = self._bindings;
- if (!bindings) {
- bindings = self._bindings = {};
- }
-
- handlers = bindings[name];
- if (!handlers) {
- handlers = bindings[name] = [];
- }
-
- handlers.push(callback);
-
- if (nativeEvents[name]) {
- if (!self._nativeEvents) {
- self._nativeEvents = {name: true};
- } else {
- self._nativeEvents[name] = true;
- }
-
- if (self._rendered) {
- self.bindPendingEvents();
- }
- }
- }
- }
-
- return self;
- },
-
- /**
- * Unbinds the specified event and optionally a specific callback. If you omit the name
- * parameter all event handlers will be removed. If you omit the callback all event handles
- * by the specified name will be removed.
- *
- * @method off
- * @param {String} [name] Name for the event to unbind.
- * @param {function} [callback] Callback function to unbind.
- * @return {mxex.ui.Control} Current control object.
- */
- off: function(name, callback) {
- var self = this, i, bindings = self._bindings, handlers, bindingName, names, hi;
-
- if (bindings) {
- if (name) {
- names = name.toLowerCase().split(' ');
- i = names.length;
- while (i--) {
- name = names[i];
- handlers = bindings[name];
-
- // Unbind all handlers
- if (!name) {
- for (bindingName in bindings) {
- bindings[bindingName].length = 0;
- }
-
- return self;
- }
-
- if (handlers) {
- // Unbind all by name
- if (!callback) {
- handlers.length = 0;
- } else {
- // Unbind specific ones
- hi = handlers.length;
- while (hi--) {
- if (handlers[hi] === callback) {
- handlers.splice(hi, 1);
- }
- }
- }
- }
- }
- } else {
- self._bindings = [];
- }
- }
-
- return self;
- },
-
- /**
- * Fires the specified event by name and arguments on the control. This will execute all
- * bound event handlers.
- *
- * @method fire
- * @param {String} name Name of the event to fire.
- * @param {Object} [args] Arguments to pass to the event.
- * @param {Boolean} [bubble] Value to control bubbeling. Defaults to true.
- * @return {Object} Current arguments object.
- */
- fire: function(name, args, bubble) {
- var self = this, i, l, handlers, parentCtrl;
-
- name = name.toLowerCase();
-
- // Dummy function that gets replaced on the delegation state functions
- function returnFalse() {
- return false;
- }
-
- // Dummy function that gets replaced on the delegation state functions
- function returnTrue() {
- return true;
- }
-
- // Setup empty object if args is omited
- args = args || {};
-
- // Stick type into event object
- if (!args.type) {
- args.type = name;
- }
-
- // Stick control into event
- if (!args.control) {
- args.control = self;
- }
-
- // Add event delegation methods if they are missing
- if (!args.preventDefault) {
- // Add preventDefault method
- args.preventDefault = function() {
- args.isDefaultPrevented = returnTrue;
- };
-
- // Add stopPropagation
- args.stopPropagation = function() {
- args.isPropagationStopped = returnTrue;
- };
-
- // Add stopImmediatePropagation
- args.stopImmediatePropagation = function() {
- args.isImmediatePropagationStopped = returnTrue;
- };
-
- // Add event delegation states
- args.isDefaultPrevented = returnFalse;
- args.isPropagationStopped = returnFalse;
- args.isImmediatePropagationStopped = returnFalse;
- }
-
- if (self._bindings) {
- handlers = self._bindings[name];
-
- if (handlers) {
- for (i = 0, l = handlers.length; i < l; i++) {
- // Execute callback and break if the callback returns a false
- if (!args.isImmediatePropagationStopped() && handlers[i].call(self, args) === false) {
- break;
- }
- }
- }
- }
-
- // Bubble event up to parent controls
- if (bubble !== false) {
- parentCtrl = self.parent();
- while (parentCtrl && !args.isPropagationStopped()) {
- parentCtrl.fire(name, args, false);
- parentCtrl = parentCtrl.parent();
- }
- }
-
- return args;
- },
-
- /**
- * Returns true/false if the specified event has any listeners.
- *
- * @method hasEventListeners
- * @param {String} name Name of the event to check for.
- * @return {Boolean} True/false state if the event has listeners.
- */
- hasEventListeners: function(name) {
- return name in this._bindings;
- },
-
- /**
- * Returns a control collection with all parent controls.
- *
- * @method parents
- * @param {String} selector Optional selector expression to find parents.
- * @return {tinymce.ui.Collection} Collection with all parent controls.
- */
- parents: function(selector) {
- var self = this, ctrl, parents = new Collection();
-
- // Add each parent to collection
- for (ctrl = self.parent(); ctrl; ctrl = ctrl.parent()) {
- parents.add(ctrl);
- }
-
- // Filter away everything that doesn't match the selector
- if (selector) {
- parents = parents.filter(selector);
- }
-
- return parents;
- },
-
- /**
- * Returns the control next to the current control.
- *
- * @method next
- * @return {tinymce.ui.Control} Next control instance.
- */
- next: function() {
- var parentControls = this.parent().items();
-
- return parentControls[parentControls.indexOf(this) + 1];
- },
-
- /**
- * Returns the control previous to the current control.
- *
- * @method prev
- * @return {tinymce.ui.Control} Previous control instance.
- */
- prev: function() {
- var parentControls = this.parent().items();
-
- return parentControls[parentControls.indexOf(this) - 1];
- },
-
- /**
- * Find the common ancestor for two control instances.
- *
- * @method findCommonAncestor
- * @param {tinymce.ui.Control} ctrl1 First control.
- * @param {tinymce.ui.Control} ctrl2 Second control.
- * @return {tinymce.ui.Control} Ancestor control instance.
- */
- findCommonAncestor: function(ctrl1, ctrl2) {
- var parentCtrl;
-
- while (ctrl1) {
- parentCtrl = ctrl2;
-
- while (parentCtrl && ctrl1 != parentCtrl) {
- parentCtrl = parentCtrl.parent();
- }
-
- if (ctrl1 == parentCtrl) {
- break;
- }
-
- ctrl1 = ctrl1.parent();
- }
-
- return ctrl1;
- },
-
- /**
- * Returns true/false if the specific control has the specific class.
- *
- * @method hasClass
- * @param {String} cls Class to check for.
- * @param {String} [group] Sub element group name.
- * @return {Boolean} True/false if the control has the specified class.
- */
- hasClass: function(cls, group) {
- var classes = this._classes[group || 'control'];
-
- cls = this.classPrefix + cls;
-
- return classes && !!classes.map[cls];
- },
-
- /**
- * Adds the specified class to the control
- *
- * @method addClass
- * @param {String} cls Class to check for.
- * @param {String} [group] Sub element group name.
- * @return {tinymce.ui.Control} Current control object.
- */
- addClass: function(cls, group) {
- var self = this, classes, elm;
-
- cls = this.classPrefix + cls;
- classes = self._classes[group || 'control'];
-
- if (!classes) {
- classes = [];
- classes.map = {};
- self._classes[group || 'control'] = classes;
- }
-
- if (!classes.map[cls]) {
- classes.map[cls] = cls;
- classes.push(cls);
-
- if (self._rendered) {
- elm = self.getEl(group);
-
- if (elm) {
- elm.className = classes.join(' ');
- }
- }
- }
-
- return self;
- },
-
- /**
- * Removes the specified class from the control.
- *
- * @method removeClass
- * @param {String} cls Class to remove.
- * @param {String} [group] Sub element group name.
- * @return {tinymce.ui.Control} Current control object.
- */
- removeClass: function(cls, group) {
- var self = this, classes, i, elm;
-
- cls = this.classPrefix + cls;
- classes = self._classes[group || 'control'];
- if (classes && classes.map[cls]) {
- delete classes.map[cls];
-
- i = classes.length;
- while (i--) {
- if (classes[i] === cls) {
- classes.splice(i, 1);
- }
- }
- }
-
- if (self._rendered) {
- elm = self.getEl(group);
-
- if (elm) {
- elm.className = classes.join(' ');
- }
- }
-
- return self;
- },
-
- /**
- * Toggles the specified class on the control.
- *
- * @method toggleClass
- * @param {String} cls Class to remove.
- * @param {Boolean} state True/false state to add/remove class.
- * @param {String} [group] Sub element group name.
- * @return {tinymce.ui.Control} Current control object.
- */
- toggleClass: function(cls, state, group) {
- var self = this;
-
- if (state) {
- self.addClass(cls, group);
- } else {
- self.removeClass(cls, group);
- }
-
- return self;
- },
-
- /**
- * Returns the class string for the specified group name.
- *
- * @method classes
- * @param {String} [group] Group to get clases by.
- * @return {String} Classes for the specified group.
- */
- classes: function(group) {
- var classes = this._classes[group || 'control'];
-
- return classes ? classes.join(' ') : '';
- },
-
- /**
- * Sets the inner HTML of the control element.
- *
- * @method innerHtml
- * @param {String} html Html string to set as inner html.
- * @return {tinymce.ui.Control} Current control object.
- */
- innerHtml: function(html) {
- DomUtils.innerHtml(this.getEl(), html);
- return this;
- },
-
- /**
- * Returns the control DOM element or sub element.
- *
- * @method getEl
- * @param {String} [suffix] Suffix to get element by.
- * @param {Boolean} [dropCache] True if the cache for the element should be dropped.
- * @return {Element} HTML DOM element for the current control or it's children.
- */
- getEl: function(suffix, dropCache) {
- var elm, id = suffix ? this._id + '-' + suffix : this._id;
-
- elm = elementIdCache[id] = (dropCache === true ? null : elementIdCache[id]) || DomUtils.get(id);
-
- return elm;
- },
-
- /**
- * Sets/gets the visible for the control.
- *
- * @method visible
- * @param {Boolean} state Value to set to control.
- * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get.
- */
- visible: function(state) {
- var self = this, parentCtrl;
-
- if (typeof(state) !== "undefined") {
- if (self._visible !== state) {
- if (self._rendered) {
- self.getEl().style.display = state ? '' : 'none';
- }
-
- self._visible = state;
-
- // Parent container needs to reflow
- parentCtrl = self.parent();
- if (parentCtrl) {
- parentCtrl._lastRect = null;
- }
-
- self.fire(state ? 'show' : 'hide');
- }
-
- return self;
- }
-
- return self._visible;
- },
-
- /**
- * Sets the visible state to true.
- *
- * @method show
- * @return {tinymce.ui.Control} Current control instance.
- */
- show: function() {
- return this.visible(true);
- },
-
- /**
- * Sets the visible state to false.
- *
- * @method hide
- * @return {tinymce.ui.Control} Current control instance.
- */
- hide: function() {
- return this.visible(false);
- },
-
- /**
- * Focuses the current control.
- *
- * @method focus
- * @return {tinymce.ui.Control} Current control instance.
- */
- focus: function() {
- try {
- this.getEl().focus();
- } catch (ex) {
- // Ignore IE error
- }
-
- return this;
- },
-
- /**
- * Blurs the current control.
- *
- * @method blur
- * @return {tinymce.ui.Control} Current control instance.
- */
- blur: function() {
- this.getEl().blur();
-
- return this;
- },
-
- /**
- * Sets the specified aria property.
- *
- * @method aria
- * @param {String} name Name of the aria property to set.
- * @param {String} value Value of the aria property.
- * @return {tinymce.ui.Control} Current control instance.
- */
- aria: function(name, value) {
- var self = this, elm = self.getEl(self.ariaTarget);
-
- if (typeof(value) === "undefined") {
- return self._aria[name];
- } else {
- self._aria[name] = value;
- }
-
- if (self._rendered) {
- elm.setAttribute(name == 'role' ? name : 'aria-' + name, value);
- }
-
- return self;
- },
-
- /**
- * Encodes the specified string with HTML entities. It will also
- * translate the string to different languages.
- *
- * @method encode
- * @param {String/Object/Array} text Text to entity encode.
- * @param {Boolean} [translate=true] False if the contents shouldn't be translated.
- * @return {String} Encoded and possible traslated string.
- */
- encode: function(text, translate) {
- if (translate !== false && Control.translate) {
- text = Control.translate(text);
- }
-
- return (text || '').replace(/[&<>"]/g, function(match) {
- return '' + match.charCodeAt(0) + ';';
- });
- },
-
- /**
- * Adds items before the current control.
- *
- * @method before
- * @param {Array/tinymce.ui.Collection} items Array of items to prepend before this control.
- * @return {tinymce.ui.Control} Current control instance.
- */
- before: function(items) {
- var self = this, parent = self.parent();
-
- if (parent) {
- parent.insert(items, parent.items().indexOf(self), true);
- }
-
- return self;
- },
-
- /**
- * Adds items after the current control.
- *
- * @method after
- * @param {Array/tinymce.ui.Collection} items Array of items to append after this control.
- * @return {tinymce.ui.Control} Current control instance.
- */
- after: function(items) {
- var self = this, parent = self.parent();
-
- if (parent) {
- parent.insert(items, parent.items().indexOf(self));
- }
-
- return self;
- },
-
- /**
- * Removes the current control from DOM and from UI collections.
- *
- * @method remove
- * @return {tinymce.ui.Control} Current control instance.
- */
- remove: function() {
- var self = this, elm = self.getEl(), parent = self.parent(), newItems, i;
-
- if (self.items) {
- var controls = self.items().toArray();
- i = controls.length;
- while (i--) {
- controls[i].remove();
- }
- }
-
- if (parent && parent.items) {
- newItems = [];
-
- parent.items().each(function(item) {
- if (item !== self) {
- newItems.push(item);
- }
- });
-
- parent.items().set(newItems);
- parent._lastRect = null;
- }
-
- if (self._eventsRoot && self._eventsRoot == self) {
- DomUtils.off(elm);
- }
-
- var lookup = self.getRoot().controlIdLookup;
- if (lookup) {
- delete lookup[self._id];
- }
-
- delete elementIdCache[self._id];
-
- if (elm && elm.parentNode) {
- var nodes = elm.getElementsByTagName('*');
-
- i = nodes.length;
- while (i--) {
- delete elementIdCache[nodes[i].id];
- }
-
- elm.parentNode.removeChild(elm);
- }
-
- self._rendered = false;
-
- return self;
- },
-
- /**
- * Renders the control before the specified element.
- *
- * @method renderBefore
- * @param {Element} elm Element to render before.
- * @return {tinymce.ui.Control} Current control instance.
- */
- renderBefore: function(elm) {
- var self = this;
-
- elm.parentNode.insertBefore(DomUtils.createFragment(self.renderHtml()), elm);
- self.postRender();
-
- return self;
- },
-
- /**
- * Renders the control to the specified element.
- *
- * @method renderBefore
- * @param {Element} elm Element to render to.
- * @return {tinymce.ui.Control} Current control instance.
- */
- renderTo: function(elm) {
- var self = this;
-
- elm = elm || self.getContainerElm();
- elm.appendChild(DomUtils.createFragment(self.renderHtml()));
- self.postRender();
-
- return self;
- },
-
- /**
- * Post render method. Called after the control has been rendered to the target.
- *
- * @method postRender
- * @return {tinymce.ui.Control} Current control instance.
- */
- postRender: function() {
- var self = this, settings = self.settings, elm, box, parent, name, parentEventsRoot;
-
- // Bind on |ba
ab
|
- * - * Or: - *|
- if (!isDefaultPrevented(e) && (keyCode == DELETE || keyCode == BACKSPACE)) { - isCollapsed = editor.selection.isCollapsed(); - body = editor.getBody(); - - // Selection is collapsed but the editor isn't empty - if (isCollapsed && !dom.isEmpty(body)) { - return; - } - - // Selection isn't collapsed but not all the contents is selected - if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) { - return; - } - - // Manually empty the editor - e.preventDefault(); - editor.setContent(''); - - if (body.firstChild && dom.isBlock(body.firstChild)) { - editor.selection.setCursorLocation(body.firstChild, 0); - } else { - editor.selection.setCursorLocation(body, 0); - } - - editor.nodeChanged(); - } - }); - } - - /** - * WebKit doesn't select all the nodes in the body when you press Ctrl+A. - * IE selects more than the contents [a
] instead of[a]
see bug #6438 - * This selects the whole body so that backspace/delete logic will delete everything - */ - function selectAll() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode == 65 && VK.metaKeyPressed(e)) { - e.preventDefault(); - editor.execCommand('SelectAll'); - } - }); - } - - /** - * WebKit has a weird issue where it some times fails to properly convert keypresses to input method keystrokes. - * The IME on Mac doesn't initialize when it doesn't fire a proper focus event. - * - * This seems to happen when the user manages to click the documentElement element then the window doesn't get proper focus until - * you enter a character into the editor. - * - * It also happens when the first focus in made to the body. - * - * See: https://bugs.webkit.org/show_bug.cgi?id=83566 - */ - function inputMethodFocus() { - if (!editor.settings.content_editable) { - // Case 1 IME doesn't initialize if you focus the document - dom.bind(editor.getDoc(), 'focusin', function() { - selection.setRng(selection.getRng()); - }); - - // Case 2 IME doesn't initialize if you click the documentElement it also doesn't properly fire the focusin event - dom.bind(editor.getDoc(), 'mousedown', function(e) { - if (e.target == editor.getDoc().documentElement) { - editor.getBody().focus(); - selection.setRng(selection.getRng()); - } - }); - } - } - - /** - * Backspacing in FireFox/IE from a paragraph into a horizontal rule results in a floating text node because the - * browser just deletes the paragraph - the browser fails to merge the text node with a horizontal rule so it is - * left there. TinyMCE sees a floating text node and wraps it in a paragraph on the key up event (ForceBlocks.js - * addRootBlocks), meaning the action does nothing. With this code, FireFox/IE matche the behaviour of other - * browsers. - * - * It also fixes a bug on Firefox where it's impossible to delete HR elements. - */ - function removeHrOnBackspace() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { - if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { - var node = selection.getNode(); - var previousSibling = node.previousSibling; - - if (node.nodeName == 'HR') { - dom.remove(node); - e.preventDefault(); - return; - } - - if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") { - dom.remove(previousSibling); - e.preventDefault(); - } - } - } - }); - } - - /** - * Firefox 3.x has an issue where the body element won't get proper focus if you click out - * side it's rectangle. - */ - function focusBody() { - // Fix for a focus bug in FF 3.x where the body element - // wouldn't get proper focus if the user clicked on the HTML element - if (!window.Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4 - editor.on('mousedown', function(e) { - if (!isDefaultPrevented(e) && e.target.nodeName === "HTML") { - var body = editor.getBody(); - - // Blur the body it's focused but not correctly focused - body.blur(); - - // Refocus the body after a little while - setTimeout(function() { - body.focus(); - }, 0); - } - }); - } - } - - /** - * WebKit has a bug where it isn't possible to select image, hr or anchor elements - * by clicking on them so we need to fake that. - */ - function selectControlElements() { - editor.on('click', function(e) { - e = e.target; - - // Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250 - // WebKit can't even do simple things like selecting an image - // Needs tobe the setBaseAndExtend or it will fail to select floated images - if (/^(IMG|HR)$/.test(e.nodeName)) { - selection.getSel().setBaseAndExtent(e, 0, e, 1); - } - - if (e.nodeName == 'A' && dom.hasClass(e, 'mce-item-anchor')) { - selection.select(e); - } - - editor.nodeChanged(); - }); - } - - /** - * Fixes a Gecko bug where the style attribute gets added to the wrong element when deleting between two block elements. - * - * Fixes do backspace/delete on this: - *bla[ck
r]ed
- * - * Would become: - *bla|ed
- * - * Instead of: - *bla|ed
- */ - function removeStylesWhenDeletingAcrossBlockElements() { - function getAttributeApplyFunction() { - var template = dom.getAttribs(selection.getStart().cloneNode(false)); - - return function() { - var target = selection.getStart(); - - if (target !== editor.getBody()) { - dom.setAttrib(target, "style", null); - - each(template, function(attr) { - target.setAttributeNode(attr.cloneNode(true)); - }); - } - }; - } - - function isSelectionAcrossElements() { - return !selection.isCollapsed() && - dom.getParent(selection.getStart(), dom.isBlock) != dom.getParent(selection.getEnd(), dom.isBlock); - } - - editor.on('keypress', function(e) { - var applyAttributes; - - if (!isDefaultPrevented(e) && (e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) { - applyAttributes = getAttributeApplyFunction(); - editor.getDoc().execCommand('delete', false, null); - applyAttributes(); - e.preventDefault(); - return false; - } - }); - - dom.bind(editor.getDoc(), 'cut', function(e) { - var applyAttributes; - - if (!isDefaultPrevented(e) && isSelectionAcrossElements()) { - applyAttributes = getAttributeApplyFunction(); - - setTimeout(function() { - applyAttributes(); - }, 0); - } - }); - } - - /** - * Fire a nodeChanged when the selection is changed on WebKit this fixes selection issues on iOS5. It only fires the nodeChange - * event every 50ms since it would other wise update the UI when you type and it hogs the CPU. - */ - function selectionChangeNodeChanged() { - var lastRng, selectionTimer; - - editor.on('selectionchange', function() { - if (selectionTimer) { - clearTimeout(selectionTimer); - selectionTimer = 0; - } - - selectionTimer = window.setTimeout(function() { - if (editor.removed) { - return; - } - - var rng = selection.getRng(); - - // Compare the ranges to see if it was a real change or not - if (!lastRng || !RangeUtils.compareRanges(rng, lastRng)) { - editor.nodeChanged(); - lastRng = rng; - } - }, 50); - }); - } - - /** - * Screen readers on IE needs to have the role application set on the body. - */ - function ensureBodyHasRoleApplication() { - document.body.setAttribute("role", "application"); - } - - /** - * Backspacing into a table behaves differently depending upon browser type. - * Therefore, disable Backspace when cursor immediately follows a table. - */ - function disableBackspaceIntoATable() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { - if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { - var previousSibling = selection.getNode().previousSibling; - if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") { - e.preventDefault(); - return false; - } - } - } - }); - } - - /** - * Old IE versions can't properly render BR elements in PRE tags white in contentEditable mode. So this - * logic adds a \n before the BR so that it will get rendered. - */ - function addNewLinesBeforeBrInPre() { - // IE8+ rendering mode does the right thing with BR in PRE - if (getDocumentMode() > 7) { - return; - } - - // Enable display: none in area and add a specific class that hides all BR elements in PRE to - // avoid the caret from getting stuck at the BR elements while pressing the right arrow key - setEditorCommandState('RespectVisibilityInDesign', true); - editor.contentStyles.push('.mceHideBrInPre pre br {display: none}'); - dom.addClass(editor.getBody(), 'mceHideBrInPre'); - - // Adds a \n before all BR elements in PRE to get them visual - parser.addNodeFilter('pre', function(nodes) { - var i = nodes.length, brNodes, j, brElm, sibling; - - while (i--) { - brNodes = nodes[i].getAll('br'); - j = brNodes.length; - while (j--) { - brElm = brNodes[j]; - - // Add \n before BR in PRE elements on older IE:s so the new lines get rendered - sibling = brElm.prev; - if (sibling && sibling.type === 3 && sibling.value.charAt(sibling.value - 1) != '\n') { - sibling.value += '\n'; - } else { - brElm.parent.insert(new Node('#text', 3), brElm, true).value = '\n'; - } - } - } - }); - - // Removes any \n before BR elements in PRE since other browsers and in contentEditable=false mode they will be visible - serializer.addNodeFilter('pre', function(nodes) { - var i = nodes.length, brNodes, j, brElm, sibling; - - while (i--) { - brNodes = nodes[i].getAll('br'); - j = brNodes.length; - while (j--) { - brElm = brNodes[j]; - sibling = brElm.prev; - if (sibling && sibling.type == 3) { - sibling.value = sibling.value.replace(/\r?\n$/, ''); - } - } - } - }); - } - - /** - * Moves style width/height to attribute width/height when the user resizes an image on IE. - */ - function removePreSerializedStylesWhenSelectingControls() { - dom.bind(editor.getBody(), 'mouseup', function() { - var value, node = selection.getNode(); - - // Moved styles to attributes on IMG eements - if (node.nodeName == 'IMG') { - // Convert style width to width attribute - if ((value = dom.getStyle(node, 'width'))) { - dom.setAttrib(node, 'width', value.replace(/[^0-9%]+/g, '')); - dom.setStyle(node, 'width', ''); - } - - // Convert style height to height attribute - if ((value = dom.getStyle(node, 'height'))) { - dom.setAttrib(node, 'height', value.replace(/[^0-9%]+/g, '')); - dom.setStyle(node, 'height', ''); - } - } - }); - } - - /** - * Removes a blockquote when backspace is pressed at the beginning of it. - * - * For example: - *- * - * Becomes: - *|x
|x
- */ - function removeBlockQuoteOnBackSpace() { - // Add block quote deletion handler - editor.on('keydown', function(e) { - var rng, container, offset, root, parent; - - if (isDefaultPrevented(e) || e.keyCode != VK.BACKSPACE) { - return; - } - - rng = selection.getRng(); - container = rng.startContainer; - offset = rng.startOffset; - root = dom.getRoot(); - parent = container; - - if (!rng.collapsed || offset !== 0) { - return; - } - - while (parent && parent.parentNode && parent.parentNode.firstChild == parent && parent.parentNode != root) { - parent = parent.parentNode; - } - - // Is the cursor at the beginning of a blockquote? - if (parent.tagName === 'BLOCKQUOTE') { - // Remove the blockquote - editor.formatter.toggle('blockquote', null, parent); - - // Move the caret to the beginning of container - rng = dom.createRng(); - rng.setStart(container, 0); - rng.setEnd(container, 0); - selection.setRng(rng); - } - }); - } - - /** - * Sets various Gecko editing options on mouse down and before a execCommand to disable inline table editing that is broken etc. - */ - function setGeckoEditingOptions() { - function setOpts() { - editor._refreshContentEditable(); - - setEditorCommandState("StyleWithCSS", false); - setEditorCommandState("enableInlineTableEditing", false); - - if (!settings.object_resizing) { - setEditorCommandState("enableObjectResizing", false); - } - } - - if (!settings.readonly) { - editor.on('BeforeExecCommand MouseDown', setOpts); - } - } - - /** - * Fixes a gecko link bug, when a link is placed at the end of block elements there is - * no way to move the caret behind the link. This fix adds a bogus br element after the link. - * - * For example this: - * - * - * Becomes this: - * - */ - function addBrAfterLastLinks() { - function fixLinks() { - each(dom.select('a'), function(node) { - var parentNode = node.parentNode, root = dom.getRoot(); - - if (parentNode.lastChild === node) { - while (parentNode && !dom.isBlock(parentNode)) { - if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) { - return; - } - - parentNode = parentNode.parentNode; - } - - dom.add(parentNode, 'br', {'data-mce-bogus': 1}); - } - }); - } - - editor.on('SetContent ExecCommand', function(e) { - if (e.type == "setcontent" || e.command === 'mceInsertLink') { - fixLinks(); - } - }); - } - - /** - * WebKit will produce DIV elements here and there by default. But since TinyMCE uses paragraphs by - * default we want to change that behavior. - */ - function setDefaultBlockType() { - if (settings.forced_root_block) { - editor.on('init', function() { - setEditorCommandState('DefaultParagraphSeparator', settings.forced_root_block); - }); - } - } - - /** - * Removes ghost selections from images/tables on Gecko. - */ - function removeGhostSelection() { - editor.on('Undo Redo SetContent', function(e) { - if (!e.initial) { - editor.execCommand('mceRepaint'); - } - }); - } - - /** - * Deletes the selected image on IE instead of navigating to previous page. - */ - function deleteControlItemOnBackSpace() { - editor.on('keydown', function(e) { - var rng; - - if (!isDefaultPrevented(e) && e.keyCode == BACKSPACE) { - rng = editor.getDoc().selection.createRange(); - if (rng && rng.item) { - e.preventDefault(); - editor.undoManager.beforeChange(); - dom.remove(rng.item(0)); - editor.undoManager.add(); - } - } - }); - } - - /** - * IE10 doesn't properly render block elements with the right height until you add contents to them. - * This fixes that by adding a padding-right to all empty text block elements. - * See: https://connect.microsoft.com/IE/feedback/details/743881 - */ - function renderEmptyBlocksFix() { - var emptyBlocksCSS; - - // IE10+ - if (getDocumentMode() >= 10) { - emptyBlocksCSS = ''; - each('p div h1 h2 h3 h4 h5 h6'.split(' '), function(name, i) { - emptyBlocksCSS += (i > 0 ? ',' : '') + name + ':empty'; - }); - - editor.contentStyles.push(emptyBlocksCSS + '{padding-right: 1px !important}'); - } - } - - /** - * Old IE versions can't retain contents within noscript elements so this logic will store the contents - * as a attribute and the insert that value as it's raw text when the DOM is serialized. - */ - function keepNoScriptContents() { - if (getDocumentMode() < 9) { - parser.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node, textNode; - - while (i--) { - node = nodes[i]; - textNode = node.firstChild; - - if (textNode) { - node.attr('data-mce-innertext', textNode.value); - } - } - }); - - serializer.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node, textNode, value; - - while (i--) { - node = nodes[i]; - textNode = nodes[i].firstChild; - - if (textNode) { - textNode.value = Entities.decode(textNode.value); - } else { - // Old IE can't retain noscript value so an attribute is used to store it - value = node.attributes.map['data-mce-innertext']; - if (value) { - node.attr('data-mce-innertext', null); - textNode = new Node('#text', 3); - textNode.value = value; - textNode.raw = true; - node.append(textNode); - } - } - } - }); - } - } - - /** - * IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode. - */ - function fixCaretSelectionOfDocumentElementOnIe() { - var doc = dom.doc, body = doc.body, started, startRng, htmlElm; - - // Return range from point or null if it failed - function rngFromPoint(x, y) { - var rng = body.createTextRange(); - - try { - rng.moveToPoint(x, y); - } catch (ex) { - // IE sometimes throws and exception, so lets just ignore it - rng = null; - } - - return rng; - } - - // Fires while the selection is changing - function selectionChange(e) { - var pointRng; - - // Check if the button is down or not - if (e.button) { - // Create range from mouse position - pointRng = rngFromPoint(e.x, e.y); - - if (pointRng) { - // Check if pointRange is before/after selection then change the endPoint - if (pointRng.compareEndPoints('StartToStart', startRng) > 0) { - pointRng.setEndPoint('StartToStart', startRng); - } else { - pointRng.setEndPoint('EndToEnd', startRng); - } - - pointRng.select(); - } - } else { - endSelection(); - } - } - - // Removes listeners - function endSelection() { - var rng = doc.selection.createRange(); - - // If the range is collapsed then use the last start range - if (startRng && !rng.item && rng.compareEndPoints('StartToEnd', rng) === 0) { - startRng.select(); - } - - dom.unbind(doc, 'mouseup', endSelection); - dom.unbind(doc, 'mousemove', selectionChange); - startRng = started = 0; - } - - // Make HTML element unselectable since we are going to handle selection by hand - doc.documentElement.unselectable = true; - - // Detect when user selects outside BODY - dom.bind(doc, 'mousedown contextmenu', function(e) { - if (e.target.nodeName === 'HTML') { - if (started) { - endSelection(); - } - - // Detect vertical scrollbar, since IE will fire a mousedown on the scrollbar and have target set as HTML - htmlElm = doc.documentElement; - if (htmlElm.scrollHeight > htmlElm.clientHeight) { - return; - } - - started = 1; - // Setup start position - startRng = rngFromPoint(e.x, e.y); - if (startRng) { - // Listen for selection change events - dom.bind(doc, 'mouseup', endSelection); - dom.bind(doc, 'mousemove', selectionChange); - - dom.getRoot().focus(); - startRng.select(); - } - } - }); - } - - /** - * Fixes selection issues where the caret can be placed between two inline elements like a|b - * this fix will lean the caret right into the closest inline element. - */ - function normalizeSelection() { - // Normalize selection for example a|a becomes a|a except for Ctrl+A since it selects everything - editor.on('keyup focusin mouseup', function(e) { - if (e.keyCode != 65 || !VK.metaKeyPressed(e)) { - selection.normalize(); - } - }, true); - } - - /** - * Forces Gecko to render a broken image icon if it fails to load an image. - */ - function showBrokenImageIcon() { - editor.contentStyles.push( - 'img:-moz-broken {' + - '-moz-force-broken-image-icon:1;' + - 'min-width:24px;' + - 'min-height:24px' + - '}' - ); - } - - /** - * iOS has a bug where it's impossible to type if the document has a touchstart event - * bound and the user touches the document while having the on screen keyboard visible. - * - * The touch event moves the focus to the parent document while having the caret inside the iframe - * this fix moves the focus back into the iframe document. - */ - function restoreFocusOnKeyDown() { - if (!editor.inline) { - editor.on('keydown', function() { - if (document.activeElement == document.body) { - editor.getWin().focus(); - } - }); - } - } - - /** - * IE 11 has an annoying issue where you can't move focus into the editor - * by clicking on the white area HTML element. We used to be able to to fix this with - * the fixCaretSelectionOfDocumentElementOnIe fix. But since M$ removed the selection - * object it's not possible anymore. So we need to hack in a ungly CSS to force the - * body to be at least 150px. If the user clicks the HTML element out side this 150px region - * we simply move the focus into the first paragraph. Not ideal since you loose the - * positioning of the caret but goot enough for most cases. - */ - function bodyHeight() { - if (!editor.inline) { - editor.contentStyles.push('body {min-height: 150px}'); - editor.on('click', function(e) { - if (e.target.nodeName == 'HTML') { - editor.getBody().focus(); - editor.selection.normalize(); - editor.nodeChanged(); - } - }); - } - } - - /** - * Firefox on Mac OS will move the browser back to the previous page if you press CMD+Left arrow. - * You might then loose all your work so we need to block that behavior and replace it with our own. - */ - function blockCmdArrowNavigation() { - if (Env.mac) { - editor.on('keydown', function(e) { - if (VK.metaKeyPressed(e) && (e.keyCode == 37 || e.keyCode == 39)) { - e.preventDefault(); - editor.selection.getSel().modify('move', e.keyCode == 37 ? 'backward' : 'forward', 'word'); - } - }); - } - } - - /** - * Disables the autolinking in IE 9+ this is then re-enabled by the autolink plugin. - */ - function disableAutoUrlDetect() { - setEditorCommandState("AutoUrlDetect", false); - } - - /** - * IE 11 has a fantastic bug where it will produce two trailing BR elements to iframe bodies when - * the iframe is hidden by display: none on a parent container. The DOM is actually out of sync - * with innerHTML in this case. It's like IE adds shadow DOM BR elements that appears on innerHTML - * but not as the lastChild of the body. However is we add a BR element to the body then remove it - * it doesn't seem to add these BR elements makes sence right?! - * - * Example of what happens: text becomes text]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
[\r\n]*)$/, '');
- });
- }
-
- self.load({initial: true, format: 'html'});
- self.startContent = self.getContent({format: 'raw'});
-
- /**
- * Is set to true after the editor instance has been initialized
- *
- * @property initialized
- * @type Boolean
- * @example
- * function isEditorInitialized(editor) {
- * return editor && editor.initialized;
- * }
- */
- self.initialized = true;
-
- each(self._pendingNativeEvents, function(name) {
- self.dom.bind(getEventTarget(self, name), name, function(e) {
- self.fire(e.type, e);
- });
- });
-
- self.fire('init');
- self.focus(true);
- self.nodeChanged({initial: true});
- self.execCallback('init_instance_callback', self);
-
- // Add editor specific CSS styles
- if (self.contentStyles.length > 0) {
- contentCssText = '';
-
- each(self.contentStyles, function(style) {
- contentCssText += style + "\r\n";
- });
-
- self.dom.addStyle(contentCssText);
- }
-
- // Load specified content CSS last
- each(self.contentCSS, function(cssUrl) {
- if (!self.loadedCSS[cssUrl]) {
- self.dom.loadCSS(cssUrl);
- self.loadedCSS[cssUrl] = true;
- }
- });
-
- // Handle auto focus
- if (settings.auto_focus) {
- setTimeout(function () {
- var ed = self.editorManager.get(settings.auto_focus);
-
- ed.selection.select(ed.getBody(), 1);
- ed.selection.collapse(1);
- ed.getBody().focus();
- ed.getWin().focus();
- }, 100);
- }
-
- // Clean up references for IE
- targetElm = doc = body = null;
- },
-
- /**
- * Focuses/activates the editor. This will set this editor as the activeEditor in the tinymce collection
- * it will also place DOM focus inside the editor.
- *
- * @method focus
- * @param {Boolean} skip_focus Skip DOM focus. Just set is as the active editor.
- */
- focus: function(skip_focus) {
- var oed, self = this, selection = self.selection, contentEditable = self.settings.content_editable, rng;
- var controlElm, doc = self.getDoc(), body;
-
- if (!skip_focus) {
- // Get selected control element
- rng = selection.getRng();
- if (rng.item) {
- controlElm = rng.item(0);
- }
-
- self._refreshContentEditable();
-
- // Focus the window iframe
- if (!contentEditable) {
- // WebKit needs this call to fire focusin event properly see #5948
- // But Opera pre Blink engine will produce an empty selection so skip Opera
- if (!Env.opera) {
- self.getBody().focus();
- }
-
- self.getWin().focus();
- }
-
- // Focus the body as well since it's contentEditable
- if (isGecko || contentEditable) {
- body = self.getBody();
-
- // Check for setActive since it doesn't scroll to the element
- if (body.setActive && Env.ie < 11) {
- body.setActive();
- } else {
- body.focus();
- }
-
- if (contentEditable) {
- selection.normalize();
- }
- }
-
- // Restore selected control element
- // This is needed when for example an image is selected within a
- // layer a call to focus will then remove the control selection
- if (controlElm && controlElm.ownerDocument == doc) {
- rng = doc.body.createControlRange();
- rng.addElement(controlElm);
- rng.select();
- }
- }
-
- if (self.editorManager.activeEditor != self) {
- if ((oed = self.editorManager.activeEditor)) {
- oed.fire('deactivate', {relatedTarget: self});
- }
-
- self.fire('activate', {relatedTarget: oed});
- }
-
- self.editorManager.activeEditor = self;
- },
-
- /**
- * Executes a legacy callback. This method is useful to call old 2.x option callbacks.
- * There new event model is a better way to add callback so this method might be removed in the future.
- *
- * @method execCallback
- * @param {String} name Name of the callback to execute.
- * @return {Object} Return value passed from callback function.
- */
- execCallback: function(name) {
- var self = this, callback = self.settings[name], scope;
-
- if (!callback) {
- return;
- }
-
- // Look through lookup
- if (self.callbackLookup && (scope = self.callbackLookup[name])) {
- callback = scope.func;
- scope = scope.scope;
- }
-
- if (typeof(callback) === 'string') {
- scope = callback.replace(/\.\w+$/, '');
- scope = scope ? resolve(scope) : 0;
- callback = resolve(callback);
- self.callbackLookup = self.callbackLookup || {};
- self.callbackLookup[name] = {func: callback, scope: scope};
- }
-
- return callback.apply(scope || self, Array.prototype.slice.call(arguments, 1));
- },
-
- /**
- * Translates the specified string by replacing variables with language pack items it will also check if there is
- * a key mathcin the input.
- *
- * @method translate
- * @param {String} text String to translate by the language pack data.
- * @return {String} Translated string.
- */
- translate: function(text) {
- var lang = this.settings.language || 'en', i18n = this.editorManager.i18n;
-
- if (!text) {
- return '';
- }
-
- return i18n.data[lang + '.' + text] || text.replace(/\{\#([^\}]+)\}/g, function(a, b) {
- return i18n.data[lang + '.' + b] || '{#' + b + '}';
- });
- },
-
- /**
- * Returns a language pack item by name/key.
- *
- * @method getLang
- * @param {String} name Name/key to get from the language pack.
- * @param {String} defaultVal Optional default value to retrive.
- */
- getLang: function(name, defaultVal) {
- return (
- this.editorManager.i18n.data[(this.settings.language || 'en') + '.' + name] ||
- (defaultVal !== undefined ? defaultVal : '{#' + name + '}')
- );
- },
-
- /**
- * Returns a configuration parameter by name.
- *
- * @method getParam
- * @param {String} name Configruation parameter to retrive.
- * @param {String} defaultVal Optional default value to return.
- * @param {String} type Optional type parameter.
- * @return {String} Configuration parameter value or default value.
- * @example
- * // Returns a specific config value from the currently active editor
- * var someval = tinymce.activeEditor.getParam('myvalue');
- *
- * // Returns a specific config value from a specific editor instance by id
- * var someval2 = tinymce.get('my_editor').getParam('myvalue');
- */
- getParam: function(name, defaultVal, type) {
- var value = name in this.settings ? this.settings[name] : defaultVal, output;
-
- if (type === 'hash') {
- output = {};
-
- if (typeof(value) === 'string') {
- each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function(value) {
- value = value.split('=');
-
- if (value.length > 1) {
- output[trim(value[0])] = trim(value[1]);
- } else {
- output[trim(value[0])] = trim(value);
- }
- });
- } else {
- output = value;
- }
-
- return output;
- }
-
- return value;
- },
-
- /**
- * Distpaches out a onNodeChange event to all observers. This method should be called when you
- * need to update the UI states or element path etc.
- *
- * @method nodeChanged
- */
- nodeChanged: function() {
- var self = this, selection = self.selection, node, parents, root;
-
- // Fix for bug #1896577 it seems that this can not be fired while the editor is loading
- if (self.initialized && !self.settings.disable_nodechange && !self.settings.readonly) {
- // Get start node
- root = self.getBody();
- node = selection.getStart() || root;
- node = ie && node.ownerDocument != self.getDoc() ? self.getBody() : node; // Fix for IE initial state
-
- // Edge case for
|
\xA0
').append(targetClone); + newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild); + newRange.setEndAfter(targetClone); + } else { + $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp); + newRange.setStart($realSelectionContainer[0].firstChild, 1); + newRange.setEnd($realSelectionContainer[0].lastChild, 0); + } + $realSelectionContainer.css({ top: dom.getPos(node, editor.getBody()).y }); + $realSelectionContainer[0].focus(); + var sel = selection.getSel(); + sel.removeAllRanges(); + sel.addRange(newRange); + return newRange; + }; + var selectElement = function (elm) { + var targetClone = elm.cloneNode(true); + var e = editor.fire('ObjectSelected', { + target: elm, + targetClone: targetClone + }); + if (e.isDefaultPrevented()) { + return null; + } + var range = setupOffscreenSelection(elm, e.targetClone, targetClone); + var nodeElm = SugarElement.fromDom(elm); + each(descendants$1(SugarElement.fromDom(editor.getBody()), '*[data-mce-selected]'), function (elm) { + if (!eq$2(nodeElm, elm)) { + remove$1(elm, elementSelectionAttr); + } + }); + if (!dom.getAttrib(elm, elementSelectionAttr)) { + elm.setAttribute(elementSelectionAttr, '1'); + } + selectedElement = elm; + hideFakeCaret(); + return range; + }; + var setElementSelection = function (range, forward) { + if (!range) { + return null; + } + if (range.collapsed) { + if (!isRangeInCaretContainer(range)) { + var dir = forward ? 1 : -1; + var caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range); + var beforeNode = caretPosition.getNode(!forward); + if (isFakeCaretTarget(beforeNode)) { + return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false); + } + var afterNode = caretPosition.getNode(forward); + if (isFakeCaretTarget(afterNode)) { + return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false); + } + } + return null; + } + var startContainer = range.startContainer; + var startOffset = range.startOffset; + var endOffset = range.endOffset; + if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse$b(startContainer.parentNode)) { + startContainer = startContainer.parentNode; + startOffset = dom.nodeIndex(startContainer); + startContainer = startContainer.parentNode; + } + if (startContainer.nodeType !== 1) { + return null; + } + if (endOffset === startOffset + 1 && startContainer === range.endContainer) { + var node = startContainer.childNodes[startOffset]; + if (isFakeSelectionTargetElement(node)) { + return selectElement(node); + } + } + return null; + }; + var removeElementSelection = function () { + if (selectedElement) { + selectedElement.removeAttribute(elementSelectionAttr); + } + descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove); + selectedElement = null; + }; + var destroy = function () { + fakeCaret.destroy(); + selectedElement = null; + }; + var hideFakeCaret = function () { + fakeCaret.hide(); + }; + if (Env.ceFalse) { + registerEvents(); + } + return { + showCaret: showCaret, + showBlockCaretContainer: showBlockCaretContainer, + hideFakeCaret: hideFakeCaret, + destroy: destroy + }; + }; + + var Quirks = function (editor) { + var each = Tools.each; + var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser; + var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit; + var mceInternalUrlPrefix = 'data:text/mce-internal,'; + var mceInternalDataType = isIE ? 'Text' : 'URL'; + var setEditorCommandState = function (cmd, state) { + try { + editor.getDoc().execCommand(cmd, false, state); + } catch (ex) { + } + }; + var isDefaultPrevented = function (e) { + return e.isDefaultPrevented(); + }; + var setMceInternalContent = function (e) { + var selectionHtml, internalContent; + if (e.dataTransfer) { + if (editor.selection.isCollapsed() && e.target.tagName === 'IMG') { + selection.select(e.target); + } + selectionHtml = editor.selection.getContent(); + if (selectionHtml.length > 0) { + internalContent = mceInternalUrlPrefix + escape(editor.id) + ',' + escape(selectionHtml); + e.dataTransfer.setData(mceInternalDataType, internalContent); + } + } + }; + var getMceInternalContent = function (e) { + var internalContent; + if (e.dataTransfer) { + internalContent = e.dataTransfer.getData(mceInternalDataType); + if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) { + internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(','); + return { + id: unescape(internalContent[0]), + html: unescape(internalContent[1]) + }; + } + } + return null; + }; + var insertClipboardContents = function (content, internal) { + if (editor.queryCommandSupported('mceInsertClipboardContent')) { + editor.execCommand('mceInsertClipboardContent', false, { + content: content, + internal: internal + }); + } else { + editor.execCommand('mceInsertContent', false, content); + } + }; + var emptyEditorWhenDeleting = function () { + var serializeRng = function (rng) { + var body = dom.create('body'); + var contents = rng.cloneContents(); + body.appendChild(contents); + return selection.serializer.serialize(body, { format: 'html' }); + }; + var allContentsSelected = function (rng) { + var selection = serializeRng(rng); + var allRng = dom.createRng(); + allRng.selectNode(editor.getBody()); + var allSelection = serializeRng(allRng); + return selection === allSelection; + }; + editor.on('keydown', function (e) { + var keyCode = e.keyCode; + var isCollapsed, body; + if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE)) { + isCollapsed = editor.selection.isCollapsed(); + body = editor.getBody(); + if (isCollapsed && !dom.isEmpty(body)) { + return; + } + if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) { + return; + } + e.preventDefault(); + editor.setContent(''); + if (body.firstChild && dom.isBlock(body.firstChild)) { + editor.selection.setCursorLocation(body.firstChild, 0); + } else { + editor.selection.setCursorLocation(body, 0); + } + editor.nodeChanged(); + } + }); + }; + var selectAll = function () { + editor.shortcuts.add('meta+a', null, 'SelectAll'); + }; + var inputMethodFocus = function () { + if (!editor.inline) { + dom.bind(editor.getDoc(), 'mousedown mouseup', function (e) { + var rng; + if (e.target === editor.getDoc().documentElement) { + rng = selection.getRng(); + editor.getBody().focus(); + if (e.type === 'mousedown') { + if (isCaretContainer(rng.startContainer)) { + return; + } + selection.placeCaretAt(e.clientX, e.clientY); + } else { + selection.setRng(rng); + } + } + }); + } + }; + var removeHrOnBackspace = function () { + editor.on('keydown', function (e) { + if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { + if (!editor.getBody().getElementsByTagName('hr').length) { + return; + } + if (selection.isCollapsed() && selection.getRng().startOffset === 0) { + var node = selection.getNode(); + var previousSibling = node.previousSibling; + if (node.nodeName === 'HR') { + dom.remove(node); + e.preventDefault(); + return; + } + if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') { + dom.remove(previousSibling); + e.preventDefault(); + } + } + } + }); + }; + var focusBody = function () { + if (!Range.prototype.getClientRects) { + editor.on('mousedown', function (e) { + if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') { + var body_1 = editor.getBody(); + body_1.blur(); + Delay.setEditorTimeout(editor, function () { + body_1.focus(); + }); + } + }); + } + }; + var selectControlElements = function () { + editor.on('click', function (e) { + var target = e.target; + if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== 'false') { + e.preventDefault(); + editor.selection.select(target); + editor.nodeChanged(); + } + if (target.nodeName === 'A' && dom.hasClass(target, 'mce-item-anchor')) { + e.preventDefault(); + selection.select(target); + } + }); + }; + var removeStylesWhenDeletingAcrossBlockElements = function () { + var getAttributeApplyFunction = function () { + var template = dom.getAttribs(selection.getStart().cloneNode(false)); + return function () { + var target = selection.getStart(); + if (target !== editor.getBody()) { + dom.setAttrib(target, 'style', null); + each(template, function (attr) { + target.setAttributeNode(attr.cloneNode(true)); + }); + } + }; + }; + var isSelectionAcrossElements = function () { + return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock); + }; + editor.on('keypress', function (e) { + var applyAttributes; + if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) { + applyAttributes = getAttributeApplyFunction(); + editor.getDoc().execCommand('delete', false, null); + applyAttributes(); + e.preventDefault(); + return false; + } + }); + dom.bind(editor.getDoc(), 'cut', function (e) { + var applyAttributes; + if (!isDefaultPrevented(e) && isSelectionAcrossElements()) { + applyAttributes = getAttributeApplyFunction(); + Delay.setEditorTimeout(editor, function () { + applyAttributes(); + }); + } + }); + }; + var disableBackspaceIntoATable = function () { + editor.on('keydown', function (e) { + if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { + if (selection.isCollapsed() && selection.getRng().startOffset === 0) { + var previousSibling = selection.getNode().previousSibling; + if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') { + e.preventDefault(); + return false; + } + } + } + }); + }; + var removeBlockQuoteOnBackSpace = function () { + editor.on('keydown', function (e) { + var rng, parent; + if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) { + return; + } + rng = selection.getRng(); + var container = rng.startContainer; + var offset = rng.startOffset; + var root = dom.getRoot(); + parent = container; + if (!rng.collapsed || offset !== 0) { + return; + } + while (parent && parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) { + parent = parent.parentNode; + } + if (parent.tagName === 'BLOCKQUOTE') { + editor.formatter.toggle('blockquote', null, parent); + rng = dom.createRng(); + rng.setStart(container, 0); + rng.setEnd(container, 0); + selection.setRng(rng); + } + }); + }; + var setGeckoEditingOptions = function () { + var setOpts = function () { + setEditorCommandState('StyleWithCSS', false); + setEditorCommandState('enableInlineTableEditing', false); + if (!getObjectResizing(editor)) { + setEditorCommandState('enableObjectResizing', false); + } + }; + if (!isReadOnly(editor)) { + editor.on('BeforeExecCommand mousedown', setOpts); + } + }; + var addBrAfterLastLinks = function () { + var fixLinks = function () { + each(dom.select('a'), function (node) { + var parentNode = node.parentNode; + var root = dom.getRoot(); + if (parentNode.lastChild === node) { + while (parentNode && !dom.isBlock(parentNode)) { + if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) { + return; + } + parentNode = parentNode.parentNode; + } + dom.add(parentNode, 'br', { 'data-mce-bogus': 1 }); + } + }); + }; + editor.on('SetContent ExecCommand', function (e) { + if (e.type === 'setcontent' || e.command === 'mceInsertLink') { + fixLinks(); + } + }); + }; + var setDefaultBlockType = function () { + if (getForcedRootBlock(editor)) { + editor.on('init', function () { + setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor)); + }); + } + }; + var normalizeSelection = function () { + editor.on('keyup focusin mouseup', function (e) { + if (!VK.modifierPressed(e)) { + selection.normalize(); + } + }, true); + }; + var showBrokenImageIcon = function () { + editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}'); + }; + var restoreFocusOnKeyDown = function () { + if (!editor.inline) { + editor.on('keydown', function () { + if (document.activeElement === document.body) { + editor.getWin().focus(); + } + }); + } + }; + var bodyHeight = function () { + if (!editor.inline) { + editor.contentStyles.push('body {min-height: 150px}'); + editor.on('click', function (e) { + var rng; + if (e.target.nodeName === 'HTML') { + if (Env.ie > 11) { + editor.getBody().focus(); + return; + } + rng = editor.selection.getRng(); + editor.getBody().focus(); + editor.selection.setRng(rng); + editor.selection.normalize(); + editor.nodeChanged(); + } + }); + } + }; + var blockCmdArrowNavigation = function () { + if (Env.mac) { + editor.on('keydown', function (e) { + if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) { + e.preventDefault(); + var selection_1 = editor.selection.getSel(); + selection_1.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary'); + } + }); + } + }; + var disableAutoUrlDetect = function () { + setEditorCommandState('AutoUrlDetect', false); + }; + var tapLinksAndImages = function () { + editor.on('click', function (e) { + var elm = e.target; + do { + if (elm.tagName === 'A') { + e.preventDefault(); + return; + } + } while (elm = elm.parentNode); + }); + editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}'); + }; + var blockFormSubmitInsideEditor = function () { + editor.on('init', function () { + editor.dom.bind(editor.getBody(), 'submit', function (e) { + e.preventDefault(); + }); + }); + }; + var removeAppleInterchangeBrs = function () { + parser.addNodeFilter('br', function (nodes) { + var i = nodes.length; + while (i--) { + if (nodes[i].attr('class') === 'Apple-interchange-newline') { + nodes[i].remove(); + } + } + }); + }; + var ieInternalDragAndDrop = function () { + editor.on('dragstart', function (e) { + setMceInternalContent(e); + }); + editor.on('drop', function (e) { + if (!isDefaultPrevented(e)) { + var internalContent = getMceInternalContent(e); + if (internalContent && internalContent.id !== editor.id) { + e.preventDefault(); + var rng = fromPoint$1(e.x, e.y, editor.getDoc()); + selection.setRng(rng); + insertClipboardContents(internalContent.html, true); + } + } + }); + }; + var refreshContentEditable = function () { + }; + var isHidden = function () { + if (!isGecko || editor.removed) { + return false; + } + var sel = editor.selection.getSel(); + return !sel || !sel.rangeCount || sel.rangeCount === 0; + }; + removeBlockQuoteOnBackSpace(); + emptyEditorWhenDeleting(); + if (!Env.windowsPhone) { + normalizeSelection(); + } + if (isWebKit) { + inputMethodFocus(); + selectControlElements(); + setDefaultBlockType(); + blockFormSubmitInsideEditor(); + disableBackspaceIntoATable(); + removeAppleInterchangeBrs(); + if (Env.iOS) { + restoreFocusOnKeyDown(); + bodyHeight(); + tapLinksAndImages(); + } else { + selectAll(); + } + } + if (Env.ie >= 11) { + bodyHeight(); + disableBackspaceIntoATable(); + } + if (Env.ie) { + selectAll(); + disableAutoUrlDetect(); + ieInternalDragAndDrop(); + } + if (isGecko) { + removeHrOnBackspace(); + focusBody(); + removeStylesWhenDeletingAcrossBlockElements(); + setGeckoEditingOptions(); + addBrAfterLastLinks(); + showBrokenImageIcon(); + blockCmdArrowNavigation(); + disableBackspaceIntoATable(); + } + return { + refreshContentEditable: refreshContentEditable, + isHidden: isHidden + }; + }; + + var DOM$4 = DOMUtils$1.DOM; + var appendStyle = function (editor, text) { + var body = SugarElement.fromDom(editor.getBody()); + var container = getStyleContainer(getRootNode(body)); + var style = SugarElement.fromTag('style'); + set(style, 'type', 'text/css'); + append(style, SugarElement.fromText(text)); + append(container, style); + editor.on('remove', function () { + remove(style); + }); + }; + var getRootName = function (editor) { + return editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined; + }; + var removeUndefined = function (obj) { + return filter$1(obj, function (v) { + return isUndefined(v) === false; + }); + }; + var mkParserSettings = function (editor) { + var settings = editor.settings; + var blobCache = editor.editorUpload.blobCache; + return removeUndefined({ + allow_conditional_comments: settings.allow_conditional_comments, + allow_html_data_urls: settings.allow_html_data_urls, + allow_html_in_named_anchor: settings.allow_html_in_named_anchor, + allow_script_urls: settings.allow_script_urls, + allow_unsafe_link_target: settings.allow_unsafe_link_target, + convert_fonts_to_spans: settings.convert_fonts_to_spans, + fix_list_elements: settings.fix_list_elements, + font_size_legacy_values: settings.font_size_legacy_values, + forced_root_block: settings.forced_root_block, + forced_root_block_attrs: settings.forced_root_block_attrs, + padd_empty_with_br: settings.padd_empty_with_br, + preserve_cdata: settings.preserve_cdata, + remove_trailing_brs: settings.remove_trailing_brs, + inline_styles: settings.inline_styles, + root_name: getRootName(editor), + validate: true, + blob_cache: blobCache, + images_dataimg_filter: settings.images_dataimg_filter + }); + }; + var mkSerializerSettings = function (editor) { + var settings = editor.settings; + return __assign(__assign({}, mkParserSettings(editor)), removeUndefined({ + url_converter: settings.url_converter, + url_converter_scope: settings.url_converter_scope, + element_format: settings.element_format, + entities: settings.entities, + entity_encoding: settings.entity_encoding, + indent: settings.indent, + indent_after: settings.indent_after, + indent_before: settings.indent_before, + block_elements: settings.block_elements, + boolean_attributes: settings.boolean_attributes, + custom_elements: settings.custom_elements, + extended_valid_elements: settings.extended_valid_elements, + invalid_elements: settings.invalid_elements, + invalid_styles: settings.invalid_styles, + move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements, + non_empty_elements: settings.non_empty_elements, + schema: settings.schema, + self_closing_elements: settings.self_closing_elements, + short_ended_elements: settings.short_ended_elements, + special: settings.special, + text_block_elements: settings.text_block_elements, + text_inline_elements: settings.text_inline_elements, + valid_children: settings.valid_children, + valid_classes: settings.valid_classes, + valid_elements: settings.valid_elements, + valid_styles: settings.valid_styles, + verify_html: settings.verify_html, + whitespace_elements: settings.whitespace_elements + })); + }; + var createParser = function (editor) { + var parser = DomParser(mkParserSettings(editor), editor.schema); + parser.addAttributeFilter('src,href,style,tabindex', function (nodes, name) { + var i = nodes.length, node, value; + var dom = editor.dom; + var internalName = 'data-mce-' + name; + while (i--) { + node = nodes[i]; + value = node.attr(name); + if (value && !node.attr(internalName)) { + if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) { + continue; + } + if (name === 'style') { + value = dom.serializeStyle(dom.parseStyle(value), node.name); + if (!value.length) { + value = null; + } + node.attr(internalName, value); + node.attr(name, value); + } else if (name === 'tabindex') { + node.attr(internalName, value); + node.attr(name, null); + } else { + node.attr(internalName, editor.convertURL(value, name, node.name)); + } + } + } + }); + parser.addNodeFilter('script', function (nodes) { + var i = nodes.length; + while (i--) { + var node = nodes[i]; + var type = node.attr('type') || 'no/type'; + if (type.indexOf('mce-') !== 0) { + node.attr('type', 'mce-' + type); + } + } + }); + if (editor.settings.preserve_cdata) { + parser.addNodeFilter('#cdata', function (nodes) { + var i = nodes.length; + while (i--) { + var node = nodes[i]; + node.type = 8; + node.name = '#comment'; + node.value = '[CDATA[' + editor.dom.encode(node.value) + ']]'; + } + }); + } + parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function (nodes) { + var i = nodes.length; + var nonEmptyElements = editor.schema.getNonEmptyElements(); + while (i--) { + var node = nodes[i]; + if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) { + node.append(new AstNode('br', 1)).shortEnded = true; + } + } + }); + return parser; + }; + var autoFocus = function (editor) { + if (editor.settings.auto_focus) { + Delay.setEditorTimeout(editor, function () { + var focusEditor; + if (editor.settings.auto_focus === true) { + focusEditor = editor; + } else { + focusEditor = editor.editorManager.get(editor.settings.auto_focus); + } + if (!focusEditor.destroyed) { + focusEditor.focus(); + } + }, 100); + } + }; + var moveSelectionToFirstCaretPosition = function (editor) { + var root = editor.dom.getRoot(); + if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) { + firstPositionIn(root).each(function (pos) { + var node = pos.getNode(); + var caretPos = isTable(node) ? firstPositionIn(node).getOr(pos) : pos; + if (Env.browser.isIE()) { + storeNative(editor, caretPos.toRange()); + } else { + editor.selection.setRng(caretPos.toRange()); + } + }); + } + }; + var initEditor = function (editor) { + editor.bindPendingEventDelegates(); + editor.initialized = true; + fireInit(editor); + editor.focus(true); + moveSelectionToFirstCaretPosition(editor); + editor.nodeChanged({ initial: true }); + editor.execCallback('init_instance_callback', editor); + autoFocus(editor); + }; + var getStyleSheetLoader = function (editor) { + return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader; + }; + var loadContentCss = function (editor, css) { + var styleSheetLoader = getStyleSheetLoader(editor); + var loaded = function () { + editor.on('remove', function () { + return styleSheetLoader.unloadAll(css); + }); + initEditor(editor); + }; + styleSheetLoader.loadAll(css, loaded, loaded); + }; + var preInit = function (editor, rtcMode) { + var settings = editor.settings, doc = editor.getDoc(), body = editor.getBody(); + if (!settings.browser_spellcheck && !settings.gecko_spellcheck) { + doc.body.spellcheck = false; + DOM$4.setAttrib(body, 'spellcheck', 'false'); + } + editor.quirks = Quirks(editor); + firePostRender(editor); + var directionality = getDirectionality(editor); + if (directionality !== undefined) { + body.dir = directionality; + } + if (settings.protect) { + editor.on('BeforeSetContent', function (e) { + Tools.each(settings.protect, function (pattern) { + e.content = e.content.replace(pattern, function (str) { + return ''; + }); + }); + }); + } + editor.on('SetContent', function () { + editor.addVisual(editor.getBody()); + }); + if (rtcMode === false) { + editor.load({ + initial: true, + format: 'html' + }); + } + editor.startContent = editor.getContent({ format: 'raw' }); + editor.on('compositionstart compositionend', function (e) { + editor.composing = e.type === 'compositionstart'; + }); + if (editor.contentStyles.length > 0) { + var contentCssText_1 = ''; + Tools.each(editor.contentStyles, function (style) { + contentCssText_1 += style + '\r\n'; + }); + editor.dom.addStyle(contentCssText_1); + } + loadContentCss(editor, editor.contentCSS); + if (settings.content_style) { + appendStyle(editor, settings.content_style); + } + }; + var initContentBody = function (editor, skipWrite) { + var settings = editor.settings; + var targetElm = editor.getElement(); + var doc = editor.getDoc(); + if (!settings.inline) { + editor.getElement().style.visibility = editor.orgVisibility; + } + if (!skipWrite && !editor.inline) { + doc.open(); + doc.write(editor.iframeHTML); + doc.close(); + } + if (editor.inline) { + DOM$4.addClass(targetElm, 'mce-content-body'); + editor.contentDocument = doc = document; + editor.contentWindow = window; + editor.bodyElement = targetElm; + editor.contentAreaContainer = targetElm; + } + var body = editor.getBody(); + body.disabled = true; + editor.readonly = !!settings.readonly; + if (!editor.readonly) { + if (editor.inline && DOM$4.getStyle(body, 'position', true) === 'static') { + body.style.position = 'relative'; + } + body.contentEditable = editor.getParam('content_editable_state', true); + } + body.disabled = false; + editor.editorUpload = EditorUpload(editor); + editor.schema = Schema(settings); + editor.dom = DOMUtils$1(doc, { + keep_values: true, + url_converter: editor.convertURL, + url_converter_scope: editor, + hex_colors: settings.force_hex_style_colors, + update_styles: true, + root_element: editor.inline ? editor.getBody() : null, + collect: function () { + return editor.inline; + }, + schema: editor.schema, + contentCssCors: shouldUseContentCssCors(editor), + referrerPolicy: getReferrerPolicy(editor), + onSetAttrib: function (e) { + editor.fire('SetAttrib', e); + } + }); + editor.parser = createParser(editor); + editor.serializer = DomSerializer(mkSerializerSettings(editor), editor); + editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor); + editor.annotator = Annotator(editor); + editor.formatter = Formatter(editor); + editor.undoManager = UndoManager(editor); + editor._nodeChangeDispatcher = new NodeChange(editor); + editor._selectionOverrides = SelectionOverrides(editor); + setup$9(editor); + setup$j(editor); + if (!isRtc(editor)) { + setup$k(editor); + } + var caret = setup$i(editor); + setup$8(editor, caret); + setup$a(editor); + setup$7(editor); + firePreInit(editor); + setup$4(editor).fold(function () { + preInit(editor, false); + }, function (loadingRtc) { + editor.setProgressState(true); + loadingRtc.then(function (rtcMode) { + editor.setProgressState(false); + preInit(editor, rtcMode); + }); + }); + }; + + var DOM$5 = DOMUtils$1.DOM; + var relaxDomain = function (editor, ifr) { + if (document.domain !== window.location.hostname && Env.browser.isIE()) { + var bodyUuid = uuid('mce'); + editor[bodyUuid] = function () { + initContentBody(editor); + }; + var domainRelaxUrl = 'javascript:(function(){' + 'document.open();document.domain="' + document.domain + '";' + 'var ed = window.parent.tinymce.get("' + editor.id + '");document.write(ed.iframeHTML);' + 'document.close();ed.' + bodyUuid + '(true);})()'; + DOM$5.setAttrib(ifr, 'src', domainRelaxUrl); + return true; + } + return false; + }; + var createIframeElement = function (id, title, height, customAttrs) { + var iframe = SugarElement.fromTag('iframe'); + setAll(iframe, customAttrs); + setAll(iframe, { + id: id + '_ifr', + frameBorder: '0', + allowTransparency: 'true', + title: title + }); + add$3(iframe, 'tox-edit-area__iframe'); + return iframe; + }; + var getIframeHtml = function (editor) { + var iframeHTML = getDocType(editor) + ''; + if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) { + iframeHTML += ']*>( | |\s|\u00a0|)<\/p>[\r\n]*|
[\r\n]*)$/,"")}),n.load({initial:!0,format:"html"}),n.startContent=n.getContent({format:"raw"}),n.initialized=!0,R(n._pendingNativeEvents,function(e){n.dom.bind(_(n,e),e,function(e){n.fire(e.type,e)})}),n.fire("init"),n.focus(!0),n.nodeChanged({initial:!0}),n.execCallback("init_instance_callback",n),n.contentStyles.length>0&&(h="",R(n.contentStyles,function(e){h+=e+"\r\n"}),n.dom.addStyle(h)),R(n.contentCSS,function(e){n.loadedCSS[e]||(n.dom.loadCSS(e),n.loadedCSS[e]=!0)}),o.auto_focus&&setTimeout(function(){var e=n.editorManager.get(o.auto_focus);e.selection.select(e.getBody(),1),e.selection.collapse(1),e.getBody().focus(),e.getWin().focus()},100),f=p=m=null},focus:function(e){var t,n=this,r=n.selection,i=n.settings.content_editable,o,a,s=n.getDoc(),l;e||(o=r.getRng(),o.item&&(a=o.item(0)),n._refreshContentEditable(),i||(b.opera||n.getBody().focus(),n.getWin().focus()),(H||i)&&(l=n.getBody(),l.setActive&&b.ie<11?l.setActive():l.focus(),i&&r.normalize()),a&&a.ownerDocument==s&&(o=s.body.createControlRange(),o.addElement(a),o.select())),n.editorManager.activeEditor!=n&&((t=n.editorManager.activeEditor)&&t.fire("deactivate",{relatedTarget:n}),n.fire("activate",{relatedTarget:t})),n.editorManager.activeEditor=n},execCallback:function(e){var t=this,n=t.settings[e],r;if(n)return t.callbackLookup&&(r=t.callbackLookup[e])&&(n=r.func,r=r.scope),"string"==typeof n&&(r=n.replace(/\.\w+$/,""),r=r?D(r):0,n=D(n),t.callbackLookup=t.callbackLookup||{},t.callbackLookup[e]={func:n,scope:r}),n.apply(r||t,Array.prototype.slice.call(arguments,1))},translate:function(e){var t=this.settings.language||"en",n=this.editorManager.i18n;return e?n.data[t+"."+e]||e.replace(/\{\#([^\}]+)\}/g,function(e,r){return n.data[t+"."+r]||"{#"+r+"}"}):""},getLang:function(e,n){return this.editorManager.i18n.data[(this.settings.language||"en")+"."+e]||(n!==t?n:"{#"+e+"}")},getParam:function(e,t,n){var r=e in this.settings?this.settings[e]:t,i;return"hash"===n?(i={},"string"==typeof r?R(r.split(r.indexOf("=")>0?/[;,](?![^=;,]*(?:[;,]|$))/:","),function(e){e=e.split("="),i[L(e[0])]=L(e.length>1?e[1]:e)}):i=r,i):r},nodeChanged:function(){var e=this,t=e.selection,n,r,i;!e.initialized||e.settings.disable_nodechange||e.settings.readonly||(i=e.getBody(),n=t.getStart()||i,n=P&&n.ownerDocument!=e.getDoc()?e.getBody():n,"IMG"==n.nodeName&&t.isCollapsed()&&(n=n.parentNode),r=[],e.dom.getParent(n,function(e){return e===i?!0:void r.push(e)
-}),e.fire("NodeChange",{element:n,parents:r}))},addButton:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),t.text||t.icon||(t.icon=e),n.buttons=n.buttons||{},t.tooltip=t.tooltip||t.title,n.buttons[e]=t},addMenuItem:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),n.menuItems=n.menuItems||{},n.menuItems[e]=t},addCommand:function(e,t,n){this.execCommands[e]={func:t,scope:n||this}},addQueryStateHandler:function(e,t,n){this.queryStateCommands[e]={func:t,scope:n||this}},addQueryValueHandler:function(e,t,n){this.queryValueCommands[e]={func:t,scope:n||this}},addShortcut:function(e,t,n,r){this.shortcuts.add(e,t,n,r)},execCommand:function(e,t,n,r){var i=this,o=0,a;return/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(e)||r&&r.skip_focus||i.focus(),r=T({},r),r=i.fire("BeforeExecCommand",{command:e,ui:t,value:n}),r.isDefaultPrevented()?!1:(a=i.execCommands[e])&&a.func.call(a.scope,t,n)!==!0?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):(R(i.plugins,function(r){return r.execCommand&&r.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),o=!0,!1):void 0}),o?o:i.theme&&i.theme.execCommand&&i.theme.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):i.editorCommands.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):(i.getDoc().execCommand(e,t,n),void i.fire("ExecCommand",{command:e,ui:t,value:n})))},queryCommandState:function(e){var t=this,n,r;if(!t._isHidden()){if((n=t.queryStateCommands[e])&&(r=n.func.call(n.scope),r!==!0))return r;if(r=t.editorCommands.queryCommandState(e),-1!==r)return r;try{return t.getDoc().queryCommandState(e)}catch(i){}}},queryCommandValue:function(e){var n=this,r,i;if(!n._isHidden()){if((r=n.queryValueCommands[e])&&(i=r.func.call(r.scope),i!==!0))return i;if(i=n.editorCommands.queryCommandValue(e),i!==t)return i;try{return n.getDoc().queryCommandValue(e)}catch(o){}}},show:function(){var e=this;E.show(e.getContainer()),E.hide(e.id),e.load(),e.fire("show")},hide:function(){var e=this,t=e.getDoc();P&&t&&!e.inline&&t.execCommand("SelectAll"),e.save(),E.hide(e.getContainer()),E.setStyle(e.id,"display",e.orgDisplay),e.fire("hide")},isHidden:function(){return!E.isHidden(this.id)},setProgressState:function(e,t){this.fire("ProgressState",{state:e,time:t})},load:function(e){var n=this,r=n.getElement(),i;return r?(e=e||{},e.load=!0,i=n.setContent(r.value!==t?r.value:r.innerHTML,e),e.element=r,e.no_events||n.fire("LoadContent",e),e.element=r=null,i):void 0},save:function(e){var t=this,n=t.getElement(),r,i;if(n&&t.initialized)return e=e||{},e.save=!0,e.element=n,r=e.content=t.getContent(e),e.no_events||t.fire("SaveContent",e),r=e.content,/TEXTAREA|INPUT/i.test(n.nodeName)?n.value=r:(t.inline||(n.innerHTML=r),(i=E.getParent(t.id,"form"))&&R(i.elements,function(e){return e.name==t.id?(e.value=r,!1):void 0})),e.element=n=null,e.set_dirty!==!1&&(t.isNotDirty=!0),r},setContent:function(e,t){var n=this,r=n.getBody(),i;return t=t||{},t.format=t.format||"html",t.set=!0,t.content=e,t.no_events||n.fire("BeforeSetContent",t),e=t.content,0===e.length||/^\s+$/.test(e)?(i=n.settings.forced_root_block,i&&n.schema.isValidChild(r.nodeName.toLowerCase(),i.toLowerCase())?(e=P&&11>P?"":'
',e=n.dom.createHTML(i,n.settings.forced_root_block_attrs,e)):P||(e='
'),r.innerHTML=e,n.fire("SetContent",t)):("raw"!==t.format&&(e=new o({},n.schema).serialize(n.parser.parse(e,{isRootContent:!0}))),t.content=L(e),n.dom.setHTML(r,t.content),t.no_events||n.fire("SetContent",t)),t.content},getContent:function(e){var t=this,n,r=t.getBody();return e=e||{},e.format=e.format||"html",e.get=!0,e.getInner=!0,e.no_events||t.fire("BeforeGetContent",e),n="raw"==e.format?r.innerHTML:"text"==e.format?r.innerText||r.textContent:t.serializer.serialize(r,e),e.content="text"!=e.format?L(n):n,e.no_events||t.fire("GetContent",e),e.content},insertContent:function(e){this.execCommand("mceInsertContent",!1,e)},isDirty:function(){return!this.isNotDirty},getContainer:function(){var e=this;return e.container||(e.container=E.get(e.editorContainer||e.id+"_parent")),e.container},getContentAreaContainer:function(){return this.contentAreaContainer},getElement:function(){return E.get(this.settings.content_element||this.id)},getWin:function(){var e=this,t;return e.contentWindow||(t=E.get(e.id+"_ifr"),t&&(e.contentWindow=t.contentWindow)),e.contentWindow},getDoc:function(){var e=this,t;return e.contentDocument||(t=e.getWin(),t&&(e.contentDocument=t.document)),e.contentDocument},getBody:function(){return this.bodyElement||this.getDoc().body},convertURL:function(e,t,n){var r=this,i=r.settings;return i.urlconverter_callback?r.execCallback("urlconverter_callback",e,n,!0,t):!i.convert_urls||n&&"LINK"==n.nodeName||0===e.indexOf("file:")||0===e.length?e:i.relative_urls?r.documentBaseURI.toRelative(e):e=r.documentBaseURI.toAbsolute(e,i.remove_script_host)},addVisual:function(e){var n=this,r=n.settings,i=n.dom,o;e=e||n.getBody(),n.hasVisual===t&&(n.hasVisual=r.visual),R(i.select("table,a",e),function(e){var t;switch(e.nodeName){case"TABLE":return o=r.visual_table_class||"mce-item-table",t=i.getAttrib(e,"border"),void(t&&"0"!=t||(n.hasVisual?i.addClass(e,o):i.removeClass(e,o)));case"A":return void(i.getAttrib(e,"href",!1)||(t=i.getAttrib(e,"name")||e.id,o=r.visual_anchor_class||"mce-item-anchor",t&&(n.hasVisual?i.addClass(e,o):i.removeClass(e,o))))}}),n.fire("VisualAid",{element:e,hasVisual:n.hasVisual})},remove:function(){var e=this;if(!e.removed){e.save(),e.fire("remove"),e.off(),e.removed=1,e.hasHiddenInput&&E.remove(e.getElement().nextSibling),E.setStyle(e.id,"display",e.orgDisplay),e.settings.content_editable||(M.unbind(e.getWin()),M.unbind(e.getDoc()));var t=e.getContainer();M.unbind(e.getBody()),M.unbind(t),e.editorManager.remove(e),E.remove(t),e.destroy()}},bindNative:function(e){var t=this;t.settings.readonly||(t.initialized?t.dom.bind(_(t,e),e,function(n){t.fire(e,n)}):t._pendingNativeEvents?t._pendingNativeEvents.push(e):t._pendingNativeEvents=[e])},unbindNative:function(e){var t=this;t.initialized&&t.dom.unbind(e)},destroy:function(e){var t=this,n;if(!t.destroyed){if(!e&&!t.removed)return void t.remove();e&&H&&(M.unbind(t.getDoc()),M.unbind(t.getWin()),M.unbind(t.getBody())),e||(t.editorManager.off("beforeunload",t._beforeUnload),t.theme&&t.theme.destroy&&t.theme.destroy(),t.selection.destroy(),t.dom.destroy()),n=t.formElement,n&&(n._mceOldSubmit&&(n.submit=n._mceOldSubmit,n._mceOldSubmit=null),E.unbind(n,"submit reset",t.formEventDelegate)),t.contentAreaContainer=t.formElement=t.container=t.editorContainer=null,t.settings.content_element=t.bodyElement=t.contentDocument=t.contentWindow=null,t.selection&&(t.selection=t.selection.win=t.selection.dom=t.selection.dom.doc=null),t.destroyed=1}},_refreshContentEditable:function(){var e=this,t,n;e._isHidden()&&(t=e.getBody(),n=t.parentNode,n.removeChild(t),n.appendChild(t),t.focus())},_isHidden:function(){var e;return H?(e=this.selection.getSel(),!e||!e.rangeCount||0===e.rangeCount):0}},T(N.prototype,x),N}),r(at,[],function(){var e={};return{rtl:!1,add:function(t,n){for(var r in n)e[r]=n[r];this.rtl=this.rtl||"rtl"===e._dir},translate:function(t){if("undefined"==typeof t)return t;if("string"!=typeof t&&t.raw)return t.raw;if(t.push){var n=t.slice(1);t=(e[t[0]]||t[0]).replace(/\{([^\}]+)\}/g,function(e,t){return n[t]})}return e[t]||t},data:e}}),r(st,[y,g],function(e,t){function n(e){function a(){try{return document.activeElement}catch(e){return document.body}}function s(e){return e&&e.startContainer?{startContainer:e.startContainer,startOffset:e.startOffset,endContainer:e.endContainer,endOffset:e.endOffset}:e}function l(e,t){var n;return t.startContainer?(n=e.getDoc().createRange(),n.setStart(t.startContainer,t.startOffset),n.setEnd(t.endContainer,t.endOffset)):n=t,n}function c(e){return!!o.getParent(e,n.isEditorUIElement)}function u(e,t){for(var n=t.getBody();e;){if(e==n)return!0;e=e.parentNode}}function d(n){var d=n.editor;d.on("init",function(){(d.inline||t.ie)&&(d.on("nodechange keyup",function(){var e=document.activeElement;e&&e.id==d.id+"_ifr"&&(e=d.getBody()),u(e,d)&&(d.lastRng=d.selection.getRng())}),t.webkit&&!r&&(r=function(){var t=e.activeEditor;if(t&&t.selection){var n=t.selection.getRng();n&&!n.collapsed&&(d.lastRng=n)}},o.bind(document,"selectionchange",r)))}),d.on("setcontent",function(){d.lastRng=null}),d.on("mousedown",function(){d.selection.lastFocusBookmark=null}),d.on("focusin",function(){var t=e.focusedEditor;d.selection.lastFocusBookmark&&(d.selection.setRng(l(d,d.selection.lastFocusBookmark)),d.selection.lastFocusBookmark=null),t!=d&&(t&&t.fire("blur",{focusedEditor:d}),e.activeEditor=d,e.focusedEditor=d,d.fire("focus",{blurredEditor:t}),d.focus(!0)),d.lastRng=null}),d.on("focusout",function(){window.setTimeout(function(){var t=e.focusedEditor;c(a())||t!=d||(d.fire("blur",{focusedEditor:null}),e.focusedEditor=null,d.selection&&(d.selection.lastFocusBookmark=null))},0)}),i||(i=function(t){var n=e.activeEditor;n&&t.target.ownerDocument==document&&(n.selection&&(n.selection.lastFocusBookmark=s(n.lastRng)),c(t.target)||e.focusedEditor!=n||(n.fire("blur",{focusedEditor:null}),e.focusedEditor=null))},o.bind(document,"focusin",i))}function f(t){e.focusedEditor==t.editor&&(e.focusedEditor=null),e.activeEditor||(o.unbind(document,"selectionchange",r),o.unbind(document,"focusin",i),r=i=null)}e.on("AddEditor",d),e.on("RemoveEditor",f)}var r,i,o=e.DOM;return n.isEditorUIElement=function(e){return-1!==e.className.toString().indexOf("mce-")},n}),r(lt,[ot,y,I,g,p,rt,at,st],function(e,n,r,i,o,a,s,l){var c=n.DOM,u=o.explode,d=o.each,f=o.extend,p=0,m,h={majorVersion:"4",minorVersion:"0.20",releaseDate:"2014-03-18",editors:[],i18n:s,activeEditor:null,setup:function(){var e=this,t,n,i="",o;if(n=document.location.href.replace(/[\?#].*$/,"").replace(/[\/\\][^\/]+$/,""),/[\/\\]$/.test(n)||(n+="/"),o=window.tinymce||window.tinyMCEPreInit)t=o.base||o.baseURL,i=o.suffix;else for(var a=document.getElementsByTagName("script"),s=0;s
\xa0
').append(t),i.setStartAfter(o[0].firstChild.firstChild),i.setEndAfter(t)):(o.empty().append(oo).append(t).append(oo),i.setStart(o[0].firstChild,1),i.setEnd(o[0].lastChild,0)),o.css({top:l.getPos(e,u.getBody()).y}),o[0].focus();var a=c.getSel();return a.removeAllRanges(),a.addRange(i),i}(e,n.targetClone,t),o=Nt.fromDom(e);return $(qu(Nt.fromDom(u.getBody()),"*[data-mce-selected]"),function(e){Rt(o,e)||Kn(e,i)}),l.getAttrib(e,i)||e.setAttribute(i,"1"),s=e,S(),r},w=function(e,t){if(!e)return null;if(e.collapsed){if(!y(e)){var n=t?1:-1,r=al(n,d,e),o=r.getNode(!t);if(jc(o))return v(n,o,!!t&&!r.isAtEnd(),!1);var i=r.getNode(t);if(jc(i))return v(n,i,!t&&!r.isAtEnd(),!1)}return null}var a=e.startContainer,u=e.startOffset,s=e.endOffset;if(3===a.nodeType&&0===u&&XS(a.parentNode)&&(a=a.parentNode,u=l.nodeIndex(a),a=a.parentNode),1!==a.nodeType)return null;if(s===u+1&&a===e.endContainer){var c=a.childNodes[u];if(g(c))return C(c)}return null},x=function(){s&&s.removeAttribute(i),Er(Nt.fromDom(u.getBody()),"#"+p).each(ln),s=null},S=function(){m.hide()};return vt.ceFalse&&function(){u.on("mouseup",function(e){var t=r();t.collapsed&&Ly(u,e.clientX,e.clientY)&&Wb(u,t,!1).each(h)}),u.on("click",function(e){var t=YS(u,e.target);t&&(XS(t)&&(e.preventDefault(),u.focus()),KS(t)&&l.isChildOf(t,c.getNode())&&x())}),u.on("blur NewBlock",x),u.on("ResizeWindow FullscreenStateChanged",m.reposition);var a=function(e){var t=wl(e);if(!e.firstChild)return!1;var n,r=Us.before(e.firstChild),o=t.next(r);return o&&!(ep(n=o)||tp(n)||Gm(n)||Jm(n))},i=function(e,t){var n,r,o=l.getParent(e,f),i=l.getParent(t,f);return!(!o||e===i||!l.isChildOf(o,i)||!1!==XS(YS(u,o)))||o&&(n=o,r=i,!(l.getParent(n,f)===l.getParent(r,f)))&&a(o)};u.on("tap",function(e){var t=e.target,n=YS(u,t);XS(n)?(e.preventDefault(),$b(u,n).each(w)):g(t)&&$b(u,t).each(w)},!0),u.on("mousedown",function(e){var t,n,r,o=e.target;o!==d&&"HTML"!==o.nodeName&&!l.isChildOf(o,d)||!1===Ly(u,e.clientX,e.clientY)||((t=YS(u,o))?XS(t)?(e.preventDefault(),$b(u,t).each(w)):(x(),KS(t)&&e.shiftKey||Yf(e.clientX,e.clientY,c.getRng())||(S(),c.placeCaretAt(e.clientX,e.clientY))):g(o)?$b(u,o).each(w):!1===jc(o)&&(x(),S(),(n=$w(d,e.clientX,e.clientY))&&(i(o,n.node)||(e.preventDefault(),r=v(1,n.node,n.before,!1),u.getBody().focus(),h(r)))))}),u.on("keypress",function(e){Gf.modifierPressed(e)||XS(c.getNode())&&e.preventDefault()}),u.on("GetSelectionRange",function(e){var t=e.range;if(s){if(!s.parentNode)return void(s=null);(t=t.cloneRange()).selectNode(s),e.range=t}}),u.on("SetSelectionRange",function(e){e.range=b(e.range);var t=w(e.range,e.forward);t&&(e.range=t)});var n,e,o;u.on("AfterSetSelectionRange",function(e){var t,n=e.range,r=n.startContainer.parentNode;y(n)||"mcepastebin"===r.id||S(),t=r,l.hasClass(t,"mce-offscreen-selection")||x()}),u.on("copy",function(e){var t,n,r=e.clipboardData;e.isDefaultPrevented()||!e.clipboardData||vt.ie||(t=(n=l.get(p))?n.getElementsByTagName("*")[0]:n)&&(e.preventDefault(),r.clearData(),r.setData("text/html",t.outerHTML),r.setData("text/plain",t.outerText||t.innerText))}),WS(u),e=Pu(function(){var e,t;n.removed||!n.getBody().contains(document.activeElement)||(e=n.selection.getRng()).collapsed&&(t=Kb(n,e,!1),n.selection.setRng(t))},0),(n=u).on("focus",function(){e.throttle()}),n.on("blur",function(){e.cancel()}),(o=u).on("init",function(){o.on("focusin",function(e){var t,n,r=e.target;jn(r)&&(t=Xf(o.getBody(),r),n=Un(t)?t:r,o.selection.getNode()!==n&&$b(o,n).each(function(e){return o.selection.setRng(e)}))})})}(),{showCaret:v,showBlockCaretContainer:function(e){e.hasAttribute("data-mce-caret")&&(Co(e),h(r()),c.scrollIntoView(e))},hideFakeCaret:S,destroy:function(){m.destroy(),s=null}}},JS=function(u){var s,n,r,o=xt.each,c=Gf.BACKSPACE,l=Gf.DELETE,f=u.dom,d=u.selection,e=u.parser,t=vt.gecko,i=vt.ie,a=vt.webkit,m="data:text/mce-internal,",p=i?"Text":"URL",g=function(e,t){try{u.getDoc().execCommand(e,!1,t)}catch(n){}},h=function(e){return e.isDefaultPrevented()},v=function(){u.shortcuts.add("meta+a",null,"SelectAll")},y=function(){u.on("keydown",function(e){if(!h(e)&&e.keyCode===c&&d.isCollapsed()&&0===d.getRng().startOffset){var t=d.getNode().previousSibling;if(t&&t.nodeName&&"table"===t.nodeName.toLowerCase())return e.preventDefault(),!1}})},b=function(){u.inline||(u.contentStyles.push("body {min-height: 150px}"),u.on("click",function(e){var t;if("HTML"===e.target.nodeName){if(11PyBvr3MZs?NjlD$FYLy_qoU=_B_
zShB3wSHRPKu-@V8{`W9RFmS1Gp KCl_h UnW6JBw9JRa
zGGu@dLrv$~+iSw)%riJfa2JiwnJC{S>X~3@!Obp^Mw=1p1IScQR-_CUz$5N6t_g~V
z0zGV>YI3~3f@Ww1#;$B2(T=)iVMD~J!w3gDU;|Pub~Log9)kDrfAr~RdxPt(Z*Nh1
zs0mOSS&5mRc}yNsQxsf@w1zQ6>K5XGQ{@uL2%VjO{F0q;eUEQv8LFJsQZitTpN~&e
zmXU8CQ`FT(6`x!sdydq#P|;mGs8}BgBP9(Nl|mARt|)_T!$l+QEW}?W2z??Wi$zs=yH>o9K=bQioAE|Ye9OFc}N0?{@k$E
6etDJkyU99#SO1qI@1;4TYJKs*M!-^>uiyB2%#
znBW{B|Mn2M!nVnTrEpmy`#i4e0ZM;OeIoD!-i7w}Z$PB2?;BkAH_s0i)9Q#b)cT|l
z`d;JsocsxmBgpB!g1%?^`zR}I@fs@_&iaI&;GP)f)}i`j9|oPpQrX^<=UsJHZ9tx1
zlM*Wn*%hbv{V-{d*sJesL7&qmEvg^GO&^}+