first commit

This commit is contained in:
2026-08-07 12:53:18 +09:00
commit 0b0415f0f4
1523 changed files with 496649 additions and 0 deletions

View File

@@ -0,0 +1,456 @@
/**
* BookmarkManager.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This class handles selection bookmarks.
*
* @class tinymce.dom.BookmarkManager
*/
define("tinymce/dom/BookmarkManager", [
"tinymce/Env",
"tinymce/util/Tools",
"tinymce/caret/CaretContainer",
"tinymce/caret/CaretBookmark",
"tinymce/caret/CaretPosition",
"tinymce/dom/NodeType"
], function(Env, Tools, CaretContainer, CaretBookmark, CaretPosition, NodeType) {
var isContentEditableFalse = NodeType.isContentEditableFalse;
/**
* Constructs a new BookmarkManager instance for a specific selection instance.
*
* @constructor
* @method BookmarkManager
* @param {tinymce.dom.Selection} selection Selection instance to handle bookmarks for.
*/
function BookmarkManager(selection) {
var dom = selection.dom;
/**
* 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);
*/
this.getBookmark = function(type, normalized) {
var rng, rng2, id, collapsed, name, element, chr = '', styles;
function findIndex(name, element) {
var count = 0;
Tools.each(dom.select(name), function(node) {
if (node.getAttribute('data-mce-bogus') === 'all') {
return;
}
if (node == element) {
return false;
}
count++;
});
return count;
}
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(rng) {
var 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(dom.nodeIndex(childNodes[offset], normalized) + after);
}
for (; container && container != root; container = container.parentNode) {
point.push(dom.nodeIndex(container, normalized));
}
return point;
}
bookmark.start = getPoint(rng, true);
if (!selection.isCollapsed()) {
bookmark.end = getPoint(rng);
}
return bookmark;
}
function findAdjacentContentEditableFalseElm(rng) {
function findSibling(node) {
var sibling;
if (CaretContainer.isCaretContainer(node)) {
if (NodeType.isText(node) && CaretContainer.isCaretContainerBlock(node)) {
node = node.parentNode;
}
sibling = node.previousSibling;
if (isContentEditableFalse(sibling)) {
return sibling;
}
sibling = node.nextSibling;
if (isContentEditableFalse(sibling)) {
return sibling;
}
}
}
return findSibling(rng.startContainer) || findSibling(rng.endContainer);
}
if (type == 2) {
element = selection.getNode();
name = element ? element.nodeName : null;
rng = selection.getRng();
if (isContentEditableFalse(element) || name == 'IMG') {
return {name: name, index: findIndex(name, element)};
}
if (selection.tridentSel) {
return selection.tridentSel.getBookmark(type);
}
element = findAdjacentContentEditableFalseElm(rng);
if (element) {
name = element.tagName;
return {name: name, index: findIndex(name, element)};
}
return getLocation(rng);
}
if (type == 3) {
rng = selection.getRng();
return {
start: CaretBookmark.create(dom.getRoot(), CaretPosition.fromRangeStart(rng)),
end: CaretBookmark.create(dom.getRoot(), CaretPosition.fromRangeEnd(rng))
};
}
// Handle simple range
if (type) {
return {rng: selection.getRng()};
}
rng = selection.getRng();
id = dom.uniqueId();
collapsed = selection.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('<span data-mce-type="bookmark" id="' + id + '_start" style="' + styles + '">' + chr + '</span>');
// Insert end marker
if (!collapsed) {
rng2.collapse(false);
// Detect the empty space after block elements in IE and move the
// end back one character <p></p>] becomes <p>]</p>
rng.moveToElementText(rng2.parentElement());
if (rng.compareEndPoints('StartToEnd', rng2) === 0) {
rng2.move('character', -1);
}
rng2.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_end" style="' + styles + '">' + chr + '</span>');
}
} 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 = selection.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));
}
selection.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);
*/
this.moveToBookmark = function(bookmark) {
var 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
Tools.each(Tools.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 && !Env.opera) {
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 && !Env.ie) {
node.innerHTML = '<br data-mce-bogus="1" />';
}
return node;
}
function resolveCaretPositionBookmark() {
var rng, pos;
rng = dom.createRng();
pos = CaretBookmark.resolve(dom.getRoot(), bookmark.start);
rng.setStart(pos.container(), pos.offset());
pos = CaretBookmark.resolve(dom.getRoot(), bookmark.end);
rng.setEnd(pos.container(), pos.offset());
return rng;
}
if (bookmark) {
if (Tools.isArray(bookmark.start)) {
rng = dom.createRng();
root = dom.getRoot();
if (selection.tridentSel) {
return selection.tridentSel.moveToBookmark(bookmark);
}
if (setEndPoint(true) && setEndPoint()) {
selection.setRng(rng);
}
} else if (typeof bookmark.start == 'string') {
selection.setRng(resolveCaretPositionBookmark(bookmark));
} 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);
selection.setRng(rng);
}
} else if (bookmark.name) {
selection.select(dom.select(bookmark.name)[bookmark.index]);
} else if (bookmark.rng) {
selection.setRng(bookmark.rng);
}
}
};
}
/**
* Returns true/false if the specified node is a bookmark node or not.
*
* @static
* @method isBookmarkNode
* @param {DOMNode} node DOM Node to check if it's a bookmark node or not.
* @return {Boolean} true/false if the node is a bookmark node or not.
*/
BookmarkManager.isBookmarkNode = function(node) {
return node && node.tagName === 'SPAN' && node.getAttribute('data-mce-type') === 'bookmark';
};
return BookmarkManager;
});

View File

@@ -0,0 +1,629 @@
/**
* ControlSelection.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* 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/util/Delay",
"tinymce/Env",
"tinymce/dom/NodeType"
], function(VK, Tools, Delay, Env, NodeType) {
var isContentEditableFalse = NodeType.isContentEditableFalse;
return function(selection, editor) {
var dom = editor.dom, each = Tools.each;
var selectedElm, selectedElmGhost, resizeHelper, 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;
var abs = Math.abs, round = Math.round, rootElement = editor.getBody(), startScrollWidth, startScrollHeight;
// 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: 7px;' +
'height: 7px;' +
'z-index: 10000' +
'}' +
rootClass + ' .mce-resizehandle:hover {' +
'background: #000' +
'}' +
rootClass + ' img[data-mce-selected],' + rootClass + ' 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' +
'}' +
rootClass + ' .mce-resize-helper {' +
'background: #555;' +
'background: rgba(0,0,0,0.75);' +
'border-radius: 3px;' +
'border: 1px;' +
'color: white;' +
'display: none;' +
'font-family: sans-serif;' +
'font-size: 12px;' +
'white-space: nowrap;' +
'line-height: 14px;' +
'margin: 5px 10px;' +
'padding: 5px;' +
'position: absolute;' +
'z-index: 10001' +
'}'
);
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;
}
if (elm == editor.getBody()) {
return false;
}
return editor.dom.is(elm, selector);
}
function resizeGhostElement(e) {
var deltaX, deltaY, proportional;
var resizeHelperX, resizeHelperY;
// 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;
if (selectedElm.nodeName == "IMG" && editor.settings.resize_img_proportional !== false) {
proportional = !VK.modifierPressed(e);
} else {
proportional = VK.modifierPressed(e) || (selectedElm.nodeName == "IMG" && selectedHandle[2] * selectedHandle[3] !== 0);
}
// Constrain proportions
if (proportional) {
if (abs(deltaX) > abs(deltaY)) {
height = round(width * ratio);
width = round(height / ratio);
} else {
width = round(height / ratio);
height = round(width * ratio);
}
}
// Update ghost size
dom.setStyles(selectedElmGhost, {
width: width,
height: height
});
// Update resize helper position
resizeHelperX = selectedHandle.startPos.x + deltaX;
resizeHelperY = selectedHandle.startPos.y + deltaY;
resizeHelperX = resizeHelperX > 0 ? resizeHelperX : 0;
resizeHelperY = resizeHelperY > 0 ? resizeHelperY : 0;
dom.setStyles(resizeHelper, {
left: resizeHelperX,
top: resizeHelperY,
display: 'block'
});
resizeHelper.innerHTML = width + ' &times; ' + 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));
}
// Calculate how must overflow we got
deltaX = rootElement.scrollWidth - startScrollWidth;
deltaY = rootElement.scrollHeight - startScrollHeight;
// Re-position the resize helper based on the overflow
if (deltaX + deltaY !== 0) {
dom.setStyles(resizeHelper, {
left: resizeHelperX - deltaX,
top: resizeHelperY - deltaY
});
}
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/helper and update resize handle positions
dom.remove(selectedElmGhost);
dom.remove(resizeHelper);
if (!isIE || selectedElm.nodeName == "TABLE") {
showResizeRect(selectedElm);
}
editor.fire('ObjectResized', {target: selectedElm, width: width, height: height});
dom.setAttrib(selectedElm, 'style', dom.getAttrib(selectedElm, 'style'));
editor.nodeChanged();
}
function showResizeRect(targetElm, mouseDownHandleName, mouseDownEvent) {
var position, targetWidth, targetHeight, e, rect;
hideResizeRect();
unbindResizeHandleEvents();
// Get position and size of target
position = dom.getPos(targetElm, rootElement);
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;
function startDrag(e) {
startX = e.screenX;
startY = e.screenY;
startW = selectedElm.clientWidth;
startH = selectedElm.clientHeight;
ratio = startH / startW;
selectedHandle = handle;
handle.startPos = {
x: targetWidth * handle[0] + selectedElmX,
y: targetHeight * handle[1] + selectedElmY
};
startScrollWidth = rootElement.scrollWidth;
startScrollHeight = rootElement.scrollHeight;
selectedElmGhost = selectedElm.cloneNode(true);
dom.addClass(selectedElmGhost, 'mce-clonedresizable');
dom.setAttrib(selectedElmGhost, 'data-mce-bogus', 'all');
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');
rootElement.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);
}
resizeHelper = dom.add(rootElement, 'div', {
'class': 'mce-resize-helper',
'data-mce-bogus': 'all'
}, startW + ' &times; ' + startH);
}
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) {
dom.remove(handleElm);
}
handleElm = dom.add(rootElement, 'div', {
id: 'mceResizeHandle' + name,
'data-mce-bogus': 'all',
'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;
}
dom.bind(handleElm, 'mousedown', function(e) {
e.stopImmediatePropagation();
e.preventDefault();
startDrag(e);
});
handle.elm = handleElm;
// 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 startElm, controlElm;
function isChildOrEqual(node, parent) {
if (node) {
do {
if (node === parent) {
return true;
}
} while ((node = node.parentNode));
}
}
// Ignore all events while resizing or if the editor instance was removed
if (resizeStarted || editor.removed) {
return;
}
// 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.$(controlElm).closest(isIE ? 'table' : 'table,img,hr')[0];
if (isChildOrEqual(controlElm, rootElement)) {
disableGeckoResize();
startElm = selection.getStart(true);
if (isChildOrEqual(startElm, controlElm) && isChildOrEqual(selection.getEnd(true), controlElm)) {
if (!isIE || (controlElm != startElm && startElm.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 (abs(cornerX - relativeX) < 8 && abs(cornerY - relativeY) < 8) {
selectedHandle = corner;
break;
}
}
// Remove native selection and let the magic begin
resizeStarted = true;
editor.fire('ObjectResizeStart', {
target: selectedElm,
width: selectedElm.clientWidth,
height: selectedElm.clientHeight
});
editor.getDoc().selection.empty();
showResizeRect(target, name, lastMouseDownEvent);
}
function preventDefault(e) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false; // IE
}
}
function nativeControlSelect(e) {
var target = e.srcElement;
if (isContentEditableFalse(target)) {
preventDefault(e);
return;
}
if (target != selectedElm) {
editor.fire('ObjectSelected', {target: target});
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(rootElement, 'controlselect', nativeControlSelect);
editor.on('mousedown', function(e) {
lastMouseDownEvent = e;
});
} else {
disableGeckoResize();
// Sniff sniff, hard to feature detect this stuff
if (Env.ie >= 11) {
// Needs to be mousedown for drag/drop to work on IE 11
// Needs to be click on Edge to properly select images
editor.on('mousedown click', function(e) {
var nodeName = e.target.nodeName;
if (!resizeStarted && /^(TABLE|IMG|HR)$/.test(nodeName)) {
editor.selection.select(e.target, nodeName == 'TABLE');
// Only fire once since nodeChange is expensive
if (e.type == 'mousedown') {
editor.nodeChanged();
}
}
});
editor.dom.bind(rootElement, 'mscontrolselect', function(e) {
function delayedSelect(node) {
Delay.setEditorTimeout(editor, function() {
editor.selection.select(node);
});
}
if (isContentEditableFalse(e.target)) {
e.preventDefault();
delayedSelect(e.target);
return;
}
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') {
delayedSelect(e.target);
}
}
});
}
}
var throttledUpdateResizeRect = Delay.throttle(updateResizeRect);
editor.on('nodechange ResizeEditor ResizeWindow drop', throttledUpdateResizeRect);
// Update resize rect while typing in a table
editor.on('keydown keyup', function(e) {
if (selectedElm && selectedElm.nodeName == "TABLE") {
throttledUpdateResizeRect(e);
}
});
editor.on('hide blur', hideResizeRect);
// 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(rootElement, 'controlselect', nativeControlSelect);
}
}
return {
isResizable: isResizable,
showResizeRect: showResizeRect,
hideResizeRect: hideResizeRect,
updateResizeRect: updateResizeRect,
controlSelect: controlSelect,
destroy: destroy
};
};
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,64 @@
/**
* Dimensions.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This module measures nodes and returns client rects. The client rects has an
* extra node property.
*
* @private
* @class tinymce.dom.Dimensions
*/
define("tinymce/dom/Dimensions", [
"tinymce/util/Arr",
"tinymce/dom/NodeType",
"tinymce/geom/ClientRect"
], function(Arr, NodeType, ClientRect) {
function getClientRects(node) {
function toArrayWithNode(clientRects) {
return Arr.map(clientRects, function(clientRect) {
clientRect = ClientRect.clone(clientRect);
clientRect.node = node;
return clientRect;
});
}
if (Arr.isArray(node)) {
return Arr.reduce(node, function(result, node) {
return result.concat(getClientRects(node));
}, []);
}
if (NodeType.isElement(node)) {
return toArrayWithNode(node.getClientRects());
}
if (NodeType.isText(node)) {
var rng = node.ownerDocument.createRange();
rng.setStart(node, 0);
rng.setEnd(node, node.data.length);
return toArrayWithNode(rng.getClientRects());
}
}
return {
/**
* Returns the client rects for a specific node.
*
* @method getClientRects
* @param {Array/DOMNode} node Node or array of nodes to get client rects on.
* @param {Array} Array of client rects with a extra node property.
*/
getClientRects: getClientRects
};
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,118 @@
/**
* ElementUtils.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* Utility class for various element specific functions.
*
* @private
* @class tinymce.dom.ElementUtils
*/
define("tinymce/dom/ElementUtils", [
"tinymce/dom/BookmarkManager",
"tinymce/util/Tools"
], function(BookmarkManager, Tools) {
var each = Tools.each;
function ElementUtils(dom) {
/**
* Compares two nodes and checks if it's attributes and styles matches.
* This doesn't compare classes as items since their order is significant.
*
* @method compare
* @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.
*/
this.compare = function(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 (typeof value == "undefined") {
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 !BookmarkManager.isBookmarkNode(node1) && !BookmarkManager.isBookmarkNode(node2);
};
}
return ElementUtils;
});

View File

@@ -0,0 +1,583 @@
/**
* EventUtils.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*jshint loopfunc:true*/
/*eslint no-loop-func:0 */
/**
* This class wraps the browsers native event logic with more convenient methods.
*
* @class tinymce.dom.EventUtils
*/
define("tinymce/dom/EventUtils", [
"tinymce/util/Delay"
], function(Delay) {
"use strict";
var eventExpandoPrefix = "mce-data-";
var mouseEventRe = /^(?:mouse|contextmenu)|click/;
var deprecated = {keyLocation: 1, layerX: 1, layerY: 1, returnValue: 1, webkitMovementX: 1, webkitMovementY: 1};
/**
* Binds a native event to a callback on the speified target.
*/
function addEvent(target, name, callback, capture) {
if (target.addEventListener) {
target.addEventListener(name, callback, capture || false);
} else if (target.attachEvent) {
target.attachEvent('on' + name, callback);
}
}
/**
* Unbinds a native event callback on the specified target.
*/
function removeEvent(target, name, callback, capture) {
if (target.removeEventListener) {
target.removeEventListener(name, callback, capture || false);
} else if (target.detachEvent) {
target.detachEvent('on' + name, callback);
}
}
/**
* Normalizes a native event object or just adds the event specific methods on a custom event.
*/
function fix(originalEvent, data) {
var name, event = data || {}, undef;
// 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;
}
// Copy all properties from the original event
for (name in originalEvent) {
// layerX/layerY is deprecated in Chrome and produces a warning
if (!deprecated[name]) {
event[name] = originalEvent[name];
}
}
// Normalize target IE uses srcElement
if (!event.target) {
event.target = event.srcElement || document;
}
// When target element is inside Shadow DOM we need to take first element from path
// otherwise we'll get Shadow Root parent, not actual target element
// Normalize target for WebComponents v0 implementation (in Chrome)
if (event.path) {
event.target = event.path[0];
}
// Normalize target for WebComponents v1 implementation (standard)
if (event.deepPath) {
event.target = event.deepPath[0];
}
// Calculate pageX/Y if missing and clientX/Y available
if (originalEvent && mouseEventRe.test(originalEvent.type) && originalEvent.pageX === undef && originalEvent.clientX !== undef) {
var eventDoc = event.target.ownerDocument || document;
var doc = eventDoc.documentElement;
var body = eventDoc.body;
event.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0);
}
// Add preventDefault method
event.preventDefault = function() {
event.isDefaultPrevented = returnTrue;
// Execute preventDefault on the original event object
if (originalEvent) {
if (originalEvent.preventDefault) {
originalEvent.preventDefault();
} else {
originalEvent.returnValue = false; // IE
}
}
};
// Add stopPropagation
event.stopPropagation = function() {
event.isPropagationStopped = returnTrue;
// Execute stopPropagation on the original event object
if (originalEvent) {
if (originalEvent.stopPropagation) {
originalEvent.stopPropagation();
} else {
originalEvent.cancelBubble = true; // IE
}
}
};
// Add stopImmediatePropagation
event.stopImmediatePropagation = function() {
event.isImmediatePropagationStopped = returnTrue;
event.stopPropagation();
};
// Add event delegation states
if (!event.isDefaultPrevented) {
event.isDefaultPrevented = returnFalse;
event.isPropagationStopped = returnFalse;
event.isImmediatePropagationStopped = returnFalse;
}
// Add missing metaKey for IE 8
if (typeof event.metaKey == 'undefined') {
event.metaKey = false;
}
return event;
}
/**
* Bind a DOMContentLoaded event across browsers and executes the callback once the page DOM is initialized.
* It will also set/check the domLoaded state of the event_utils instance so ready isn't called multiple times.
*/
function bindOnReady(win, callback, eventUtils) {
var doc = win.document, event = {type: 'ready'};
if (eventUtils.domLoaded) {
callback(event);
return;
}
// Gets called when the DOM is ready
function readyHandler() {
if (!eventUtils.domLoaded) {
eventUtils.domLoaded = true;
callback(event);
}
}
function waitForDomLoaded() {
// Check complete or interactive state if there is a body
// element on some iframes IE 8 will produce a null body
if (doc.readyState === "complete" || (doc.readyState === "interactive" && doc.body)) {
removeEvent(doc, "readystatechange", waitForDomLoaded);
readyHandler();
}
}
function tryScroll() {
try {
// If IE is used, use the trick by Diego Perini licensed under MIT by request to the author.
// http://javascript.nwbox.com/IEContentLoaded/
doc.documentElement.doScroll("left");
} catch (ex) {
Delay.setTimeout(tryScroll);
return;
}
readyHandler();
}
// Use W3C method
if (doc.addEventListener) {
if (doc.readyState === "complete") {
readyHandler();
} else {
addEvent(win, 'DOMContentLoaded', readyHandler);
}
} else {
// Use IE method
addEvent(doc, "readystatechange", waitForDomLoaded);
// Wait until we can scroll, when we can the DOM is initialized
if (doc.documentElement.doScroll && win.self === win.top) {
tryScroll();
}
}
// Fallback if any of the above methods should fail for some odd reason
addEvent(win, 'load', readyHandler);
}
/**
* This class enables you to bind/unbind native events to elements and normalize it's behavior across browsers.
*/
function EventUtils() {
var self = this, events = {}, count, expando, hasFocusIn, hasMouseEnterLeave, mouseEnterLeave;
expando = eventExpandoPrefix + (+new Date()).toString(32);
hasMouseEnterLeave = "onmouseenter" in document.documentElement;
hasFocusIn = "onfocusin" in document.documentElement;
mouseEnterLeave = {mouseenter: 'mouseover', mouseleave: 'mouseout'};
count = 1;
// State if the DOMContentLoaded was executed or not
self.domLoaded = false;
self.events = events;
/**
* Executes all event handler callbacks for a specific event.
*
* @private
* @param {Event} evt Event object.
* @param {String} id Expando id value to look for.
*/
function executeHandlers(evt, id) {
var callbackList, i, l, callback, container = events[id];
callbackList = container && container[evt.type];
if (callbackList) {
for (i = 0, l = callbackList.length; i < l; i++) {
callback = callbackList[i];
// Check if callback exists might be removed if a unbind is called inside the callback
if (callback && callback.func.call(callback.scope, evt) === false) {
evt.preventDefault();
}
// Should we stop propagation to immediate listeners
if (evt.isImmediatePropagationStopped()) {
return;
}
}
}
}
/**
* Binds a callback to an event on the specified target.
*
* @method bind
* @param {Object} target Target node/window or custom object.
* @param {String} names Name of the event to bind.
* @param {function} callback Callback function to execute when the event occurs.
* @param {Object} scope Scope to call the callback function on, defaults to target.
* @return {function} Callback function that got bound.
*/
self.bind = function(target, names, callback, scope) {
var id, callbackList, i, name, fakeName, nativeHandler, capture, win = window;
// Native event handler function patches the event and executes the callbacks for the expando
function defaultNativeHandler(evt) {
executeHandlers(fix(evt || win.event), id);
}
// Don't bind to text nodes or comments
if (!target || target.nodeType === 3 || target.nodeType === 8) {
return;
}
// Create or get events id for the target
if (!target[expando]) {
id = count++;
target[expando] = id;
events[id] = {};
} else {
id = target[expando];
}
// Setup the specified scope or use the target as a default
scope = scope || target;
// Split names and bind each event, enables you to bind multiple events with one call
names = names.split(' ');
i = names.length;
while (i--) {
name = names[i];
nativeHandler = defaultNativeHandler;
fakeName = capture = false;
// Use ready instead of DOMContentLoaded
if (name === "DOMContentLoaded") {
name = "ready";
}
// DOM is already ready
if (self.domLoaded && name === "ready" && target.readyState == 'complete') {
callback.call(scope, fix({type: name}));
continue;
}
// Handle mouseenter/mouseleaver
if (!hasMouseEnterLeave) {
fakeName = mouseEnterLeave[name];
if (fakeName) {
nativeHandler = function(evt) {
var current, related;
current = evt.currentTarget;
related = evt.relatedTarget;
// Check if related is inside the current target if it's not then the event should
// be ignored since it's a mouseover/mouseout inside the element
if (related && current.contains) {
// Use contains for performance
related = current.contains(related);
} else {
while (related && related !== current) {
related = related.parentNode;
}
}
// Fire fake event
if (!related) {
evt = fix(evt || win.event);
evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
evt.target = current;
executeHandlers(evt, id);
}
};
}
}
// Fake bubbling of focusin/focusout
if (!hasFocusIn && (name === "focusin" || name === "focusout")) {
capture = true;
fakeName = name === "focusin" ? "focus" : "blur";
nativeHandler = function(evt) {
evt = fix(evt || win.event);
evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
executeHandlers(evt, id);
};
}
// Setup callback list and bind native event
callbackList = events[id][name];
if (!callbackList) {
events[id][name] = callbackList = [{func: callback, scope: scope}];
callbackList.fakeName = fakeName;
callbackList.capture = capture;
//callbackList.callback = callback;
// Add the nativeHandler to the callback list so that we can later unbind it
callbackList.nativeHandler = nativeHandler;
// Check if the target has native events support
if (name === "ready") {
bindOnReady(target, nativeHandler, self);
} else {
addEvent(target, fakeName || name, nativeHandler, capture);
}
} else {
if (name === "ready" && self.domLoaded) {
callback({type: name});
} else {
// If it already has an native handler then just push the callback
callbackList.push({func: callback, scope: scope});
}
}
}
target = callbackList = 0; // Clean memory for IE
return callback;
};
/**
* Unbinds the specified event by name, name and callback or all events on the target.
*
* @method unbind
* @param {Object} target Target node/window or custom object.
* @param {String} names Optional event name to unbind.
* @param {function} callback Optional callback function to unbind.
* @return {EventUtils} Event utils instance.
*/
self.unbind = function(target, names, callback) {
var id, callbackList, i, ci, name, eventMap;
// Don't bind to text nodes or comments
if (!target || target.nodeType === 3 || target.nodeType === 8) {
return self;
}
// Unbind event or events if the target has the expando
id = target[expando];
if (id) {
eventMap = events[id];
// Specific callback
if (names) {
names = names.split(' ');
i = names.length;
while (i--) {
name = names[i];
callbackList = eventMap[name];
// Unbind the event if it exists in the map
if (callbackList) {
// Remove specified callback
if (callback) {
ci = callbackList.length;
while (ci--) {
if (callbackList[ci].func === callback) {
var nativeHandler = callbackList.nativeHandler;
var fakeName = callbackList.fakeName, capture = callbackList.capture;
// Clone callbackList since unbind inside a callback would otherwise break the handlers loop
callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
callbackList.nativeHandler = nativeHandler;
callbackList.fakeName = fakeName;
callbackList.capture = capture;
eventMap[name] = callbackList;
}
}
}
// Remove all callbacks if there isn't a specified callback or there is no callbacks left
if (!callback || callbackList.length === 0) {
delete eventMap[name];
removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
}
}
}
} else {
// All events for a specific element
for (name in eventMap) {
callbackList = eventMap[name];
removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
}
eventMap = {};
}
// Check if object is empty, if it isn't then we won't remove the expando map
for (name in eventMap) {
return self;
}
// Delete event object
delete events[id];
// Remove expando from target
try {
// IE will fail here since it can't delete properties from window
delete target[expando];
} catch (ex) {
// IE will set it to null
target[expando] = null;
}
}
return self;
};
/**
* Fires the specified event on the specified target.
*
* @method fire
* @param {Object} target Target node/window or custom object.
* @param {String} name Event name to fire.
* @param {Object} args Optional arguments to send to the observers.
* @return {EventUtils} Event utils instance.
*/
self.fire = function(target, name, args) {
var id;
// Don't bind to text nodes or comments
if (!target || target.nodeType === 3 || target.nodeType === 8) {
return self;
}
// Build event object by patching the args
args = fix(null, args);
args.type = name;
args.target = target;
do {
// Found an expando that means there is listeners to execute
id = target[expando];
if (id) {
executeHandlers(args, id);
}
// Walk up the DOM
target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
} while (target && !args.isPropagationStopped());
return self;
};
/**
* Removes all bound event listeners for the specified target. This will also remove any bound
* listeners to child nodes within that target.
*
* @method clean
* @param {Object} target Target node/window object.
* @return {EventUtils} Event utils instance.
*/
self.clean = function(target) {
var i, children, unbind = self.unbind;
// Don't bind to text nodes or comments
if (!target || target.nodeType === 3 || target.nodeType === 8) {
return self;
}
// Unbind any element on the specified target
if (target[expando]) {
unbind(target);
}
// Target doesn't have getElementsByTagName it's probably a window object then use it's document to find the children
if (!target.getElementsByTagName) {
target = target.document;
}
// Remove events from each child element
if (target && target.getElementsByTagName) {
unbind(target);
children = target.getElementsByTagName('*');
i = children.length;
while (i--) {
target = children[i];
if (target[expando]) {
unbind(target);
}
}
}
return self;
};
/**
* Destroys the event object. Call this on IE to remove memory leaks.
*/
self.destroy = function() {
events = {};
};
// Legacy function for canceling events
self.cancel = function(e) {
if (e) {
e.preventDefault();
e.stopImmediatePropagation();
}
return false;
};
}
EventUtils.Event = new EventUtils();
EventUtils.Event.bind(window, 'ready', function() {});
return EventUtils;
});

View File

@@ -0,0 +1,50 @@
/**
* NodePath.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* Handles paths of nodes within an element.
*
* @private
* @class tinymce.dom.NodePath
*/
define("tinymce/dom/NodePath", [
"tinymce/dom/DOMUtils"
], function(DOMUtils) {
function create(rootNode, targetNode, normalized) {
var path = [];
for (; targetNode && targetNode != rootNode; targetNode = targetNode.parentNode) {
path.push(DOMUtils.nodeIndex(targetNode, normalized));
}
return path;
}
function resolve(rootNode, path) {
var i, node, children;
for (node = rootNode, i = path.length - 1; i >= 0; i--) {
children = node.childNodes;
if (path[i] > children.length - 1) {
return null;
}
node = children[path[i]];
}
return node;
}
return {
create: create,
resolve: resolve
};
});

View File

@@ -0,0 +1,110 @@
/**
* NodeType.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* Contains various node validation functions.
*
* @private
* @class tinymce.dom.NodeType
*/
define("tinymce/dom/NodeType", [], function() {
function isNodeType(type) {
return function(node) {
return !!node && node.nodeType == type;
};
}
var isElement = isNodeType(1);
function matchNodeNames(names) {
names = names.toLowerCase().split(' ');
return function(node) {
var i, name;
if (node && node.nodeType) {
name = node.nodeName.toLowerCase();
for (i = 0; i < names.length; i++) {
if (name === names[i]) {
return true;
}
}
}
return false;
};
}
function matchStyleValues(name, values) {
values = values.toLowerCase().split(' ');
return function(node) {
var i, cssValue;
if (isElement(node)) {
for (i = 0; i < values.length; i++) {
cssValue = getComputedStyle(node, null).getPropertyValue(name);
if (cssValue === values[i]) {
return true;
}
}
}
return false;
};
}
function hasPropValue(propName, propValue) {
return function(node) {
return isElement(node) && node[propName] === propValue;
};
}
function hasAttributeValue(attrName, attrValue) {
return function(node) {
return isElement(node) && node.getAttribute(attrName) === attrValue;
};
}
function isBogus(node) {
return isElement(node) && node.hasAttribute('data-mce-bogus');
}
function hasContentEditableState(value) {
return function(node) {
if (isElement(node)) {
if (node.contentEditable === value) {
return true;
}
if (node.getAttribute('data-mce-contenteditable') === value) {
return true;
}
}
return false;
};
}
return {
isText: isNodeType(3),
isElement: isElement,
isComment: isNodeType(8),
isBr: matchNodeNames('br'),
isContentEditableTrue: hasContentEditableState('true'),
isContentEditableFalse: hasContentEditableState('false'),
matchNodeNames: matchNodeNames,
hasPropValue: hasPropValue,
hasAttributeValue: hasAttributeValue,
matchStyleValues: matchStyleValues,
isBogus: isBogus
};
});

View File

@@ -0,0 +1,785 @@
/**
* Range.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* Old IE Range.
*
* @private
* @class tinymce.dom.Range
*/
define("tinymce/dom/Range", [
"tinymce/util/Tools"
], function(Tools) {
// Range constructor
function Range(dom) {
var self = this,
doc = dom.doc,
EXTRACT = 0,
CLONE = 1,
DELETE = 2,
TRUE = true,
FALSE = false,
START_OFFSET = 'startOffset',
START_CONTAINER = 'startContainer',
END_CONTAINER = 'endContainer',
END_OFFSET = 'endOffset',
extend = Tools.extend,
nodeIndex = dom.nodeIndex;
function createDocumentFragment() {
return doc.createDocumentFragment();
}
function setStart(n, o) {
_setEndPoint(TRUE, n, o);
}
function setEnd(n, o) {
_setEndPoint(FALSE, n, o);
}
function setStartBefore(n) {
setStart(n.parentNode, nodeIndex(n));
}
function setStartAfter(n) {
setStart(n.parentNode, nodeIndex(n) + 1);
}
function setEndBefore(n) {
setEnd(n.parentNode, nodeIndex(n));
}
function setEndAfter(n) {
setEnd(n.parentNode, nodeIndex(n) + 1);
}
function collapse(ts) {
if (ts) {
self[END_CONTAINER] = self[START_CONTAINER];
self[END_OFFSET] = self[START_OFFSET];
} else {
self[START_CONTAINER] = self[END_CONTAINER];
self[START_OFFSET] = self[END_OFFSET];
}
self.collapsed = TRUE;
}
function selectNode(n) {
setStartBefore(n);
setEndAfter(n);
}
function selectNodeContents(n) {
setStart(n, 0);
setEnd(n, n.nodeType === 1 ? n.childNodes.length : n.nodeValue.length);
}
function compareBoundaryPoints(h, r) {
var sc = self[START_CONTAINER], so = self[START_OFFSET], ec = self[END_CONTAINER], eo = self[END_OFFSET],
rsc = r.startContainer, rso = r.startOffset, rec = r.endContainer, reo = r.endOffset;
// Check START_TO_START
if (h === 0) {
return _compareBoundaryPoints(sc, so, rsc, rso);
}
// Check START_TO_END
if (h === 1) {
return _compareBoundaryPoints(ec, eo, rsc, rso);
}
// Check END_TO_END
if (h === 2) {
return _compareBoundaryPoints(ec, eo, rec, reo);
}
// Check END_TO_START
if (h === 3) {
return _compareBoundaryPoints(sc, so, rec, reo);
}
}
function deleteContents() {
_traverse(DELETE);
}
function extractContents() {
return _traverse(EXTRACT);
}
function cloneContents() {
return _traverse(CLONE);
}
function insertNode(n) {
var startContainer = this[START_CONTAINER],
startOffset = this[START_OFFSET], nn, o;
// Node is TEXT_NODE or CDATA
if ((startContainer.nodeType === 3 || startContainer.nodeType === 4) && startContainer.nodeValue) {
if (!startOffset) {
// At the start of text
startContainer.parentNode.insertBefore(n, startContainer);
} else if (startOffset >= startContainer.nodeValue.length) {
// At the end of text
dom.insertAfter(n, startContainer);
} else {
// Middle, need to split
nn = startContainer.splitText(startOffset);
startContainer.parentNode.insertBefore(n, nn);
}
} else {
// Insert element node
if (startContainer.childNodes.length > 0) {
o = startContainer.childNodes[startOffset];
}
if (o) {
startContainer.insertBefore(n, o);
} else {
if (startContainer.nodeType == 3) {
dom.insertAfter(n, startContainer);
} else {
startContainer.appendChild(n);
}
}
}
}
function surroundContents(n) {
var f = self.extractContents();
self.insertNode(n);
n.appendChild(f);
self.selectNode(n);
}
function cloneRange() {
return extend(new Range(dom), {
startContainer: self[START_CONTAINER],
startOffset: self[START_OFFSET],
endContainer: self[END_CONTAINER],
endOffset: self[END_OFFSET],
collapsed: self.collapsed,
commonAncestorContainer: self.commonAncestorContainer
});
}
// Private methods
function _getSelectedNode(container, offset) {
var child;
// TEXT_NODE
if (container.nodeType == 3) {
return container;
}
if (offset < 0) {
return container;
}
child = container.firstChild;
while (child && offset > 0) {
--offset;
child = child.nextSibling;
}
if (child) {
return child;
}
return container;
}
function _isCollapsed() {
return (self[START_CONTAINER] == self[END_CONTAINER] && self[START_OFFSET] == self[END_OFFSET]);
}
function _compareBoundaryPoints(containerA, offsetA, containerB, offsetB) {
var c, offsetC, n, cmnRoot, childA, childB;
// In the first case the boundary-points have the same container. A is before B
// if its offset is less than the offset of B, A is equal to B if its offset is
// equal to the offset of B, and A is after B if its offset is greater than the
// offset of B.
if (containerA == containerB) {
if (offsetA == offsetB) {
return 0; // equal
}
if (offsetA < offsetB) {
return -1; // before
}
return 1; // after
}
// In the second case a child node C of the container of A is an ancestor
// container of B. In this case, A is before B if the offset of A is less than or
// equal to the index of the child node C and A is after B otherwise.
c = containerB;
while (c && c.parentNode != containerA) {
c = c.parentNode;
}
if (c) {
offsetC = 0;
n = containerA.firstChild;
while (n != c && offsetC < offsetA) {
offsetC++;
n = n.nextSibling;
}
if (offsetA <= offsetC) {
return -1; // before
}
return 1; // after
}
// In the third case a child node C of the container of B is an ancestor container
// of A. In this case, A is before B if the index of the child node C is less than
// the offset of B and A is after B otherwise.
c = containerA;
while (c && c.parentNode != containerB) {
c = c.parentNode;
}
if (c) {
offsetC = 0;
n = containerB.firstChild;
while (n != c && offsetC < offsetB) {
offsetC++;
n = n.nextSibling;
}
if (offsetC < offsetB) {
return -1; // before
}
return 1; // after
}
// In the fourth case, none of three other cases hold: the containers of A and B
// are siblings or descendants of sibling nodes. In this case, A is before B if
// the container of A is before the container of B in a pre-order traversal of the
// Ranges' context tree and A is after B otherwise.
cmnRoot = dom.findCommonAncestor(containerA, containerB);
childA = containerA;
while (childA && childA.parentNode != cmnRoot) {
childA = childA.parentNode;
}
if (!childA) {
childA = cmnRoot;
}
childB = containerB;
while (childB && childB.parentNode != cmnRoot) {
childB = childB.parentNode;
}
if (!childB) {
childB = cmnRoot;
}
if (childA == childB) {
return 0; // equal
}
n = cmnRoot.firstChild;
while (n) {
if (n == childA) {
return -1; // before
}
if (n == childB) {
return 1; // after
}
n = n.nextSibling;
}
}
function _setEndPoint(st, n, o) {
var ec, sc;
if (st) {
self[START_CONTAINER] = n;
self[START_OFFSET] = o;
} else {
self[END_CONTAINER] = n;
self[END_OFFSET] = o;
}
// If one boundary-point of a Range is set to have a root container
// other than the current one for the Range, the Range is collapsed to
// the new position. This enforces the restriction that both boundary-
// points of a Range must have the same root container.
ec = self[END_CONTAINER];
while (ec.parentNode) {
ec = ec.parentNode;
}
sc = self[START_CONTAINER];
while (sc.parentNode) {
sc = sc.parentNode;
}
if (sc == ec) {
// The start position of a Range is guaranteed to never be after the
// end position. To enforce this restriction, if the start is set to
// be at a position after the end, the Range is collapsed to that
// position.
if (_compareBoundaryPoints(self[START_CONTAINER], self[START_OFFSET], self[END_CONTAINER], self[END_OFFSET]) > 0) {
self.collapse(st);
}
} else {
self.collapse(st);
}
self.collapsed = _isCollapsed();
self.commonAncestorContainer = dom.findCommonAncestor(self[START_CONTAINER], self[END_CONTAINER]);
}
function _traverse(how) {
var c, endContainerDepth = 0, startContainerDepth = 0, p, depthDiff, startNode, endNode, sp, ep;
if (self[START_CONTAINER] == self[END_CONTAINER]) {
return _traverseSameContainer(how);
}
for (c = self[END_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) {
if (p == self[START_CONTAINER]) {
return _traverseCommonStartContainer(c, how);
}
++endContainerDepth;
}
for (c = self[START_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) {
if (p == self[END_CONTAINER]) {
return _traverseCommonEndContainer(c, how);
}
++startContainerDepth;
}
depthDiff = startContainerDepth - endContainerDepth;
startNode = self[START_CONTAINER];
while (depthDiff > 0) {
startNode = startNode.parentNode;
depthDiff--;
}
endNode = self[END_CONTAINER];
while (depthDiff < 0) {
endNode = endNode.parentNode;
depthDiff++;
}
// ascend the ancestor hierarchy until we have a common parent.
for (sp = startNode.parentNode, ep = endNode.parentNode; sp != ep; sp = sp.parentNode, ep = ep.parentNode) {
startNode = sp;
endNode = ep;
}
return _traverseCommonAncestors(startNode, endNode, how);
}
function _traverseSameContainer(how) {
var frag, s, sub, n, cnt, sibling, xferNode, start, len;
if (how != DELETE) {
frag = createDocumentFragment();
}
// If selection is empty, just return the fragment
if (self[START_OFFSET] == self[END_OFFSET]) {
return frag;
}
// Text node needs special case handling
if (self[START_CONTAINER].nodeType == 3) { // TEXT_NODE
// get the substring
s = self[START_CONTAINER].nodeValue;
sub = s.substring(self[START_OFFSET], self[END_OFFSET]);
// set the original text node to its new value
if (how != CLONE) {
n = self[START_CONTAINER];
start = self[START_OFFSET];
len = self[END_OFFSET] - self[START_OFFSET];
if (start === 0 && len >= n.nodeValue.length - 1) {
n.parentNode.removeChild(n);
} else {
n.deleteData(start, len);
}
// Nothing is partially selected, so collapse to start point
self.collapse(TRUE);
}
if (how == DELETE) {
return;
}
if (sub.length > 0) {
frag.appendChild(doc.createTextNode(sub));
}
return frag;
}
// Copy nodes between the start/end offsets.
n = _getSelectedNode(self[START_CONTAINER], self[START_OFFSET]);
cnt = self[END_OFFSET] - self[START_OFFSET];
while (n && cnt > 0) {
sibling = n.nextSibling;
xferNode = _traverseFullySelected(n, how);
if (frag) {
frag.appendChild(xferNode);
}
--cnt;
n = sibling;
}
// Nothing is partially selected, so collapse to start point
if (how != CLONE) {
self.collapse(TRUE);
}
return frag;
}
function _traverseCommonStartContainer(endAncestor, how) {
var frag, n, endIdx, cnt, sibling, xferNode;
if (how != DELETE) {
frag = createDocumentFragment();
}
n = _traverseRightBoundary(endAncestor, how);
if (frag) {
frag.appendChild(n);
}
endIdx = nodeIndex(endAncestor);
cnt = endIdx - self[START_OFFSET];
if (cnt <= 0) {
// Collapse to just before the endAncestor, which
// is partially selected.
if (how != CLONE) {
self.setEndBefore(endAncestor);
self.collapse(FALSE);
}
return frag;
}
n = endAncestor.previousSibling;
while (cnt > 0) {
sibling = n.previousSibling;
xferNode = _traverseFullySelected(n, how);
if (frag) {
frag.insertBefore(xferNode, frag.firstChild);
}
--cnt;
n = sibling;
}
// Collapse to just before the endAncestor, which
// is partially selected.
if (how != CLONE) {
self.setEndBefore(endAncestor);
self.collapse(FALSE);
}
return frag;
}
function _traverseCommonEndContainer(startAncestor, how) {
var frag, startIdx, n, cnt, sibling, xferNode;
if (how != DELETE) {
frag = createDocumentFragment();
}
n = _traverseLeftBoundary(startAncestor, how);
if (frag) {
frag.appendChild(n);
}
startIdx = nodeIndex(startAncestor);
++startIdx; // Because we already traversed it
cnt = self[END_OFFSET] - startIdx;
n = startAncestor.nextSibling;
while (n && cnt > 0) {
sibling = n.nextSibling;
xferNode = _traverseFullySelected(n, how);
if (frag) {
frag.appendChild(xferNode);
}
--cnt;
n = sibling;
}
if (how != CLONE) {
self.setStartAfter(startAncestor);
self.collapse(TRUE);
}
return frag;
}
function _traverseCommonAncestors(startAncestor, endAncestor, how) {
var n, frag, startOffset, endOffset, cnt, sibling, nextSibling;
if (how != DELETE) {
frag = createDocumentFragment();
}
n = _traverseLeftBoundary(startAncestor, how);
if (frag) {
frag.appendChild(n);
}
startOffset = nodeIndex(startAncestor);
endOffset = nodeIndex(endAncestor);
++startOffset;
cnt = endOffset - startOffset;
sibling = startAncestor.nextSibling;
while (cnt > 0) {
nextSibling = sibling.nextSibling;
n = _traverseFullySelected(sibling, how);
if (frag) {
frag.appendChild(n);
}
sibling = nextSibling;
--cnt;
}
n = _traverseRightBoundary(endAncestor, how);
if (frag) {
frag.appendChild(n);
}
if (how != CLONE) {
self.setStartAfter(startAncestor);
self.collapse(TRUE);
}
return frag;
}
function _traverseRightBoundary(root, how) {
var next = _getSelectedNode(self[END_CONTAINER], self[END_OFFSET] - 1), parent, clonedParent;
var prevSibling, clonedChild, clonedGrandParent, isFullySelected = next != self[END_CONTAINER];
if (next == root) {
return _traverseNode(next, isFullySelected, FALSE, how);
}
parent = next.parentNode;
clonedParent = _traverseNode(parent, FALSE, FALSE, how);
while (parent) {
while (next) {
prevSibling = next.previousSibling;
clonedChild = _traverseNode(next, isFullySelected, FALSE, how);
if (how != DELETE) {
clonedParent.insertBefore(clonedChild, clonedParent.firstChild);
}
isFullySelected = TRUE;
next = prevSibling;
}
if (parent == root) {
return clonedParent;
}
next = parent.previousSibling;
parent = parent.parentNode;
clonedGrandParent = _traverseNode(parent, FALSE, FALSE, how);
if (how != DELETE) {
clonedGrandParent.appendChild(clonedParent);
}
clonedParent = clonedGrandParent;
}
}
function _traverseLeftBoundary(root, how) {
var next = _getSelectedNode(self[START_CONTAINER], self[START_OFFSET]), isFullySelected = next != self[START_CONTAINER];
var parent, clonedParent, nextSibling, clonedChild, clonedGrandParent;
if (next == root) {
return _traverseNode(next, isFullySelected, TRUE, how);
}
parent = next.parentNode;
clonedParent = _traverseNode(parent, FALSE, TRUE, how);
while (parent) {
while (next) {
nextSibling = next.nextSibling;
clonedChild = _traverseNode(next, isFullySelected, TRUE, how);
if (how != DELETE) {
clonedParent.appendChild(clonedChild);
}
isFullySelected = TRUE;
next = nextSibling;
}
if (parent == root) {
return clonedParent;
}
next = parent.nextSibling;
parent = parent.parentNode;
clonedGrandParent = _traverseNode(parent, FALSE, TRUE, how);
if (how != DELETE) {
clonedGrandParent.appendChild(clonedParent);
}
clonedParent = clonedGrandParent;
}
}
function _traverseNode(n, isFullySelected, isLeft, how) {
var txtValue, newNodeValue, oldNodeValue, offset, newNode;
if (isFullySelected) {
return _traverseFullySelected(n, how);
}
// TEXT_NODE
if (n.nodeType == 3) {
txtValue = n.nodeValue;
if (isLeft) {
offset = self[START_OFFSET];
newNodeValue = txtValue.substring(offset);
oldNodeValue = txtValue.substring(0, offset);
} else {
offset = self[END_OFFSET];
newNodeValue = txtValue.substring(0, offset);
oldNodeValue = txtValue.substring(offset);
}
if (how != CLONE) {
n.nodeValue = oldNodeValue;
}
if (how == DELETE) {
return;
}
newNode = dom.clone(n, FALSE);
newNode.nodeValue = newNodeValue;
return newNode;
}
if (how == DELETE) {
return;
}
return dom.clone(n, FALSE);
}
function _traverseFullySelected(n, how) {
if (how != DELETE) {
return how == CLONE ? dom.clone(n, TRUE) : n;
}
n.parentNode.removeChild(n);
}
function toStringIE() {
return dom.create('body', null, cloneContents()).outerText;
}
extend(self, {
// Initial states
startContainer: doc,
startOffset: 0,
endContainer: doc,
endOffset: 0,
collapsed: TRUE,
commonAncestorContainer: doc,
// Range constants
START_TO_START: 0,
START_TO_END: 1,
END_TO_END: 2,
END_TO_START: 3,
// Public methods
setStart: setStart,
setEnd: setEnd,
setStartBefore: setStartBefore,
setStartAfter: setStartAfter,
setEndBefore: setEndBefore,
setEndAfter: setEndAfter,
collapse: collapse,
selectNode: selectNode,
selectNodeContents: selectNodeContents,
compareBoundaryPoints: compareBoundaryPoints,
deleteContents: deleteContents,
extractContents: extractContents,
cloneContents: cloneContents,
insertNode: insertNode,
surroundContents: surroundContents,
cloneRange: cloneRange,
toStringIE: toStringIE
});
return self;
}
// Older IE versions doesn't let you override toString by it's constructor so we have to stick it in the prototype
Range.prototype.toString = function() {
return this.toStringIE();
};
return Range;
});

View File

@@ -0,0 +1,628 @@
/**
* RangeUtils.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This class contains a few utility methods for ranges.
*
* @class tinymce.dom.RangeUtils
*/
define("tinymce/dom/RangeUtils", [
"tinymce/util/Tools",
"tinymce/dom/TreeWalker",
"tinymce/dom/NodeType",
"tinymce/caret/CaretContainer"
], function(Tools, TreeWalker, NodeType, CaretContainer) {
var each = Tools.each,
isContentEditableFalse = NodeType.isContentEditableFalse,
isCaretContainer = CaretContainer.isCaretContainer;
function getEndChild(container, index) {
var childNodes = container.childNodes;
index--;
if (index > childNodes.length - 1) {
index = childNodes.length - 1;
} else if (index < 0) {
index = 0;
}
return childNodes[index] || container;
}
function RangeUtils(dom) {
/**
* Walks the specified range like object and executes the callback for each sibling collection it finds.
*
* @private
* @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[data-mce-selected],th[data-mce-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.
* @param {Node} end_node
* @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 = getEndChild(endContainer, endOffset);
}
// 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;
var directionLeft, isAfterNode;
function isTableCell(node) {
return node && /^(TD|TH|CAPTION)$/.test(node.nodeName);
}
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 hasContentEditableFalseParent(node) {
while (node && node != body) {
if (isContentEditableFalse(node)) {
return true;
}
node = node.parentNode;
}
return false;
}
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: <p><br>|</p> becomes <p>|<br></p>
if (left && startNode.nodeName == 'BR' && isAfterNode && dom.isEmpty(parentBlockContainer)) {
container = startNode.parentNode;
offset = dom.nodeIndex(startNode);
normalized = true;
return;
}
// Walk left until we hit a text node we can move to or a block/br/img
walker = new TreeWalker(startNode, parentBlockContainer);
while ((node = walker[left ? 'prev' : 'next']())) {
// Break if we hit a non content editable node
if (dom.getContentEditableParent(node) === "false" || isCaretContainer(node)) {
return;
}
// Found text node that has a length
if (node.nodeType === 3 && node.nodeValue.length > 0) {
container = node;
offset = left ? node.nodeValue.length : 0;
normalized = true;
return;
}
// Break if we find a block or a BR/IMG/INPUT etc
if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
return;
}
lastInlineElement = node;
}
// Only fetch the last inline element when in caret mode for now
if (collapsed && lastInlineElement) {
container = lastInlineElement;
normalized = true;
offset = 0;
}
}
container = rng[(start ? 'start' : 'end') + 'Container'];
offset = rng[(start ? 'start' : 'end') + 'Offset'];
isAfterNode = container.nodeType == 1 && offset === container.childNodes.length;
nonEmptyElementsMap = dom.schema.getNonEmptyElements();
directionLeft = start;
if (isCaretContainer(container)) {
return;
}
if (container.nodeType == 1 && offset > container.childNodes.length - 1) {
directionLeft = false;
}
// If the container is a document move it to the body element
if (container.nodeType === 9) {
container = dom.getRoot();
offset = 0;
}
// If the container is body try move it into the closest text node or position
if (container === body) {
// If start is before/after a image, table etc
if (directionLeft) {
node = container.childNodes[offset > 0 ? offset - 1 : 0];
if (node) {
if (isCaretContainer(node)) {
return;
}
if (nonEmptyElementsMap[node.nodeName] || node.nodeName == "TABLE") {
return;
}
}
}
// Resolve the index
if (container.hasChildNodes()) {
offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
container = container.childNodes[offset];
offset = 0;
if (hasContentEditableFalseParent(container) || isCaretContainer(container)) {
return;
}
// Don't walk into elements that doesn't have any child nodes like a IMG
if (container.hasChildNodes() && !/TABLE/.test(container.nodeName)) {
// Walk the DOM to find a text node to place the caret at or a BR
node = container;
walker = new TreeWalker(container, body);
do {
if (isContentEditableFalse(node) || isCaretContainer(node)) {
normalized = false;
break;
}
// Found a text node use that position
if (node.nodeType === 3 && node.nodeValue.length > 0) {
offset = directionLeft ? 0 : node.nodeValue.length;
container = node;
normalized = true;
break;
}
// Found a BR/IMG element that we can place the caret before
if (nonEmptyElementsMap[node.nodeName.toLowerCase()] && !isTableCell(node)) {
offset = dom.nodeIndex(node);
container = node.parentNode;
// Put caret after image when moving the end point
if (node.nodeName == "IMG" && !directionLeft) {
offset++;
}
normalized = true;
break;
}
} while ((node = (directionLeft ? walker.next() : walker.prev())));
}
}
}
// Lean the caret to the left if possible
if (collapsed) {
// So this: <b>x</b><i>|x</i>
// Becomes: <b>x|</b><i>x</i>
// Seems that only gecko has issues with this
if (container.nodeType === 3 && offset === 0) {
findTextNodeRelative(true);
}
// Lean left into empty inline elements when the caret is before a BR
// So this: <i><b></b><i>|<br></i>
// Becomes: <i><b>|</b><i><br></i>
// Seems that only gecko has issues with this.
// Special edge case for <p><a>x</a>|<br></p> since we don't want <p><a>x|</a><br></p>
if (container.nodeType === 1) {
node = container.childNodes[offset];
// Offset is after the containers last child
// then use the previous child for normalization
if (!node) {
node = container.childNodes[offset - 1];
}
if (node && node.nodeName === 'BR' && !isPrevNode(node, 'A') &&
!hasBrBeforeAfter(node) && !hasBrBeforeAfter(node, true)) {
findTextNodeRelative(true, node);
}
}
}
// Lean the start of the selection right if possible
// So this: x[<b>x]</b>
// Becomes: x<b>[x]</b>
if (directionLeft && !collapsed && container.nodeType === 3 && offset === container.nodeValue.length) {
findTextNodeRelative(false);
}
// Set endpoint if it was normalized
if (normalized) {
rng['set' + (start ? 'Start' : 'End')](container, offset);
}
}
collapsed = rng.collapsed;
normalizeEndPoint(true);
if (!collapsed) {
normalizeEndPoint();
}
// If it was collapsed then make sure it still is
if (normalized && collapsed) {
rng.collapse(true);
}
return normalized;
};
}
/**
* Compares two ranges and checks if they are equal.
*
* @static
* @method compareRanges
* @param {DOMRange} rng1 First range to compare.
* @param {DOMRange} rng2 First range to compare.
* @return {Boolean} true/false if the ranges are equal.
*/
RangeUtils.compareRanges = function(rng1, rng2) {
if (rng1 && rng2) {
// Compare native IE ranges
if (rng1.item || rng1.duplicate) {
// Both are control ranges and the selected element matches
if (rng1.item && rng2.item && rng1.item(0) === rng2.item(0)) {
return true;
}
// Both are text ranges and the range matches
if (rng1.isEqual && rng2.isEqual && rng2.isEqual(rng1)) {
return true;
}
} else {
// Compare w3c ranges
return rng1.startContainer == rng2.startContainer && rng1.startOffset == rng2.startOffset;
}
}
return false;
};
/**
* Finds the closest selection rect tries to get the range from that.
*/
function findClosestIeRange(clientX, clientY, doc) {
var element, rng, rects;
element = doc.elementFromPoint(clientX, clientY);
rng = doc.body.createTextRange();
if (element.tagName == 'HTML') {
element = doc.body;
}
rng.moveToElementText(element);
rects = Tools.toArray(rng.getClientRects());
rects = rects.sort(function(a, b) {
a = Math.abs(Math.max(a.top - clientY, a.bottom - clientY));
b = Math.abs(Math.max(b.top - clientY, b.bottom - clientY));
return a - b;
});
if (rects.length > 0) {
clientY = (rects[0].bottom + rects[0].top) / 2;
try {
rng.moveToPoint(clientX, clientY);
rng.collapse(true);
return rng;
} catch (ex) {
// At least we tried
}
}
return null;
}
/**
* Gets the caret range for the given x/y location.
*
* @static
* @method getCaretRangeFromPoint
* @param {Number} clientX X coordinate for range
* @param {Number} clientY Y coordinate for range
* @param {Document} doc Document that x/y are relative to
* @returns {Range} caret range
*/
RangeUtils.getCaretRangeFromPoint = function(clientX, clientY, doc) {
var rng, point;
if (doc.caretPositionFromPoint) {
point = doc.caretPositionFromPoint(clientX, clientY);
rng = doc.createRange();
rng.setStart(point.offsetNode, point.offset);
rng.collapse(true);
} else if (doc.caretRangeFromPoint) {
rng = doc.caretRangeFromPoint(clientX, clientY);
} else if (doc.body.createTextRange) {
rng = doc.body.createTextRange();
try {
rng.moveToPoint(clientX, clientY);
rng.collapse(true);
} catch (ex) {
rng = findClosestIeRange(clientX, clientY, doc);
}
}
return rng;
};
RangeUtils.getSelectedNode = function(range) {
var startContainer = range.startContainer,
startOffset = range.startOffset;
if (startContainer.hasChildNodes() && range.endOffset == startOffset + 1) {
return startContainer.childNodes[startOffset];
}
return null;
};
RangeUtils.getNode = function(container, offset) {
if (container.nodeType == 1 && container.hasChildNodes()) {
if (offset >= container.childNodes.length) {
offset = container.childNodes.length - 1;
}
container = container.childNodes[offset];
}
return container;
};
return RangeUtils;
});

View File

@@ -0,0 +1,254 @@
/**
* ScriptLoader.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* 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.
*/
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 = Tools._addCacheSuffix(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} url 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;
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,506 @@
/**
* Serializer.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* 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/SaxParser",
"tinymce/html/Entities",
"tinymce/html/Serializer",
"tinymce/html/Node",
"tinymce/html/Schema",
"tinymce/Env",
"tinymce/util/Tools",
"tinymce/text/Zwsp"
], function(DOMUtils, DomParser, SaxParser, Entities, Serializer, Node, Schema, Env, Tools, Zwsp) {
var each = Tools.each, trim = Tools.trim;
var DOM = DOMUtils.DOM, tempAttrs = ["data-mce-selected"];
/**
* 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. So this fix simply removes the last two
* BR elements at the end of the document.
*
* Example of what happens: <body>text</body> becomes <body>text<br><br></body>
*/
function trimTrailingBr(rootNode) {
var brNode1, brNode2;
function isBr(node) {
return node && node.name === 'br';
}
brNode1 = rootNode.lastChild;
if (isBr(brNode1)) {
brNode2 = brNode1.prev;
if (isBr(brNode2)) {
brNode1.remove();
brNode2.remove();
}
}
}
/**
* 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;
}
function trimHtml(html) {
var trimContentRegExp = new RegExp([
'<span[^>]+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\\/span>', // Trim bogus spans like caret containers
'\\s?(' + tempAttrs.join('|') + ')="[^"]+"' // Trim temporaty data-mce prefixed attributes like data-mce-selected
].join('|'), 'gi');
html = Zwsp.trim(html.replace(trimContentRegExp, ''));
return html;
}
/**
* Returns a trimmed version of the editor contents to be used for the undo level. This
* will remove any data-mce-bogus="all" marked elements since these are used for UI it will also
* remove the data-mce-selected attributes used for selection of objects and caret containers.
* It will keep all data-mce-bogus="1" elements since these can be used to place the caret etc and will
* be removed by the serialization logic when you save.
*
* @private
* @return {String} HTML contents of the editor excluding some internal bogus elements.
*/
function getTrimmedContent() {
var content = editor.getBody().innerHTML;
var bogusAllRegExp = /<(\w+) [^>]*data-mce-bogus="all"[^>]*>/g;
var endTagIndex, index, matchLength, matches, shortEndedElements, schema = editor.schema;
content = trimHtml(content);
shortEndedElements = schema.getShortEndedElements();
// Remove all bogus elements marked with "all"
while ((matches = bogusAllRegExp.exec(content))) {
index = bogusAllRegExp.lastIndex;
matchLength = matches[0].length;
if (shortEndedElements[matches[1]]) {
endTagIndex = index;
} else {
endTagIndex = SaxParser.findEndTag(schema, content, index);
}
content = content.substring(0, index - matchLength) + content.substring(endTagIndex);
bogusAllRegExp.lastIndex = index - matchLength;
}
return trim(content);
}
function addTempAttr(name) {
if (Tools.inArray(tempAttrs, name) === -1) {
htmlParser.addAttributeFilter(name, function(nodes, name) {
var i = nodes.length;
while (i--) {
nodes[i].attr(name, null);
}
});
tempAttrs.push(name);
}
}
// 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 tabindex back to elements when serializing contents
htmlParser.addAttributeFilter('data-mce-tabindex', function(nodes, name) {
var i = nodes.length, node;
while (i--) {
node = nodes[i];
node.attr('tabindex', node.attributes.map['data-mce-tabindex']);
node.attr(name, null);
}
});
// 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');
if (value) {
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();
}
}
});
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, type;
function trim(value) {
/*jshint maxlen:255 */
/*eslint max-len:0 */
return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n')
.replace(/^[\r\n]*|[\r\n]*$/g, '')
.replace(/^\s*((<!--)?(\s*\/\/)?\s*<!\[CDATA\[|(<!--\s*)?\/\*\s*<!\[CDATA\[\s*\*\/|(\/\/)?\s*<!--|\/\*\s*<!--\s*\*\/)\s*[\r\n]*/gi, '')
.replace(/\s*(\/\*\s*\]\]>\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 type since the user specified
// a script element without type attribute
type = node.attr('type');
if (type) {
node.attr('type', type == 'mce-no/type' ? null : type.replace(/^mce\-/, ''));
}
if (value.length > 0) {
node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
}
} else {
if (value.length > 0) {
node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
}
}
}
});
// 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,data-mce-expando,' +
'data-mce-type,data-mce-resize',
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, rootNode;
// 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);
}
// Parse HTML
rootNode = htmlParser.parse(trim(args.getInner ? node.innerHTML : dom.getOuterHTML(node)), args);
trimTrailingBr(rootNode);
// Serialize HTML
htmlSerializer = new Serializer(settings, schema);
args.content = htmlSerializer.serialize(rootNode);
// Replace all BOM characters for now until we can find a better solution
if (!args.cleanup) {
args.content = Zwsp.trim(args.content);
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);
}
},
/**
* Adds a temporary internal attribute these attributes will get removed on undo and
* when getting contents out of the editor.
*
* @method addTempAttr
* @param {String} name string
*/
addTempAttr: addTempAttr,
// Internal
trimHtml: trimHtml,
getTrimmedContent: getTrimmedContent
};
};
});

View File

@@ -0,0 +1,23 @@
/**
* Sizzle.jQuery.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* 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;
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,190 @@
/**
* StyleSheetLoader.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* 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", [
"tinymce/util/Tools",
"tinymce/util/Delay"
], function(Tools, Delay) {
"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) {
Delay.setTimeout(waitCallback);
} 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);
}
url = Tools._addCacheSuffix(url);
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;
}
// Use the id owner on older webkits
waitForWebKitLinkLoaded();
}
appendToHead(link);
link.href = url;
}
this.load = load;
};
});

View File

@@ -0,0 +1,127 @@
/**
* TreeWalker.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* 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
* @example
* var walker = new tinymce.dom.TreeWalker(startNode);
*
* do {
* console.log(walker.current());
* } while (walker.next());
*/
define("tinymce/dom/TreeWalker", [], function() {
/**
* Constructs a new TreeWalker instance.
*
* @constructor
* @method TreeWalker
* @param {Node} startNode Node to start walking from.
* @param {node} rootNode Optional root node to never walk out of.
*/
return function(startNode, rootNode) {
var node = startNode;
function findSibling(node, startName, siblingName, shallow) {
var sibling, parent;
if (node) {
// Walk into nodes if it has a start
if (!shallow && node[startName]) {
return node[startName];
}
// Return the sibling if it has one
if (node != rootNode) {
sibling = node[siblingName];
if (sibling) {
return sibling;
}
// Walk up the parents to look for siblings
for (parent = node.parentNode; parent && parent != rootNode; parent = parent.parentNode) {
sibling = parent[siblingName];
if (sibling) {
return sibling;
}
}
}
}
}
function findPreviousNode(node, startName, siblingName, shallow) {
var sibling, parent, child;
if (node) {
sibling = node[siblingName];
if (rootNode && sibling === rootNode) {
return;
}
if (sibling) {
if (!shallow) {
// Walk up the parents to look for siblings
for (child = sibling[startName]; child; child = child[startName]) {
if (!child[startName]) {
return child;
}
}
}
return sibling;
}
parent = node.parentNode;
if (parent && parent !== rootNode) {
return parent;
}
}
}
/**
* 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;
};
this.prev2 = function(shallow) {
node = findPreviousNode(node, 'lastChild', 'previousSibling', shallow);
return node;
};
};
});

View File

@@ -0,0 +1,508 @@
/**
* TridentSelection.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* 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.
*
* @private
* @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) {
if (sibling.nodeType == 3) {
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) {
if (sibling.nodeType == 3) {
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 happen when
// text nodes are split into two nodes by a delete/backspace call.
// So let us detect 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 <div>|</div>
// Setting innerHTML with a span marker then remove that marker seems to keep empty block elements open
container.innerHTML = '<span>&#xFEFF;</span>';
marker = container.firstChild;
tmpRng.moveToElementText(marker);
tmpRng.collapse(FALSE); // Collapse false works better than true for some odd reason
}
ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng);
dom.remove(marker);
}
}
// Setup some shorter versions
startContainer = rng.startContainer;
startOffset = rng.startOffset;
endContainer = rng.endContainer;
endOffset = rng.endOffset;
ieRng = body.createTextRange();
// If single element selection then try making a control selection out of it
if (startContainer == endContainer && startContainer.nodeType == 1) {
// Trick to place the caret inside an empty block element like <p></p>
if (startOffset == endOffset && !startContainer.hasChildNodes()) {
if (startContainer.canHaveHTML) {
// Check if previous sibling is an empty block if it is then we need to render it
// IE would otherwise move the caret into the sibling instead of the empty startContainer see: #5236
// Example this: <p></p><p>|</p> would become this: <p>|</p><p></p>
sibling = startContainer.previousSibling;
if (sibling && !sibling.hasChildNodes() && dom.isBlock(sibling)) {
sibling.innerHTML = '&#xFEFF;';
} else {
sibling = null;
}
startContainer.innerHTML = '<span>&#xFEFF;</span><span>&#xFEFF;</span>';
ieRng.moveToElementText(startContainer.lastChild);
ieRng.select();
dom.doc.selection.clear();
startContainer.innerHTML = '';
if (sibling) {
sibling.innerHTML = '';
}
return;
}
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;
});