code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function debounce(func, wait, immediate) { let timeout; return function() { const context = this; const args = arguments; const later = () => { timeout = null; if (!immediate) { func.apply(context, args); } }; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; }
Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If `immediate` is passed, trigger the function on the leading edge, instead of the trailing. @param {Function} func @param {Number} wait @param {Boolean} immediate @return {Function}
debounce
javascript
summernote/summernote
src/js/core/func.js
https://github.com/summernote/summernote/blob/master/src/js/core/func.js
MIT
later = () => { timeout = null; if (!immediate) { func.apply(context, args); } }
Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If `immediate` is passed, trigger the function on the leading edge, instead of the trailing. @param {Function} func @param {Number} wait @param {Boolean} immediate @return {Function}
later
javascript
summernote/summernote
src/js/core/func.js
https://github.com/summernote/summernote/blob/master/src/js/core/func.js
MIT
later = () => { timeout = null; if (!immediate) { func.apply(context, args); } }
Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If `immediate` is passed, trigger the function on the leading edge, instead of the trailing. @param {Function} func @param {Number} wait @param {Boolean} immediate @return {Function}
later
javascript
summernote/summernote
src/js/core/func.js
https://github.com/summernote/summernote/blob/master/src/js/core/func.js
MIT
function head(array) { return array[0]; }
returns the first item of an array. @param {Array} array
head
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function last(array) { return array[array.length - 1]; }
returns the last item of an array. @param {Array} array
last
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function initial(array) { return array.slice(0, array.length - 1); }
returns everything but the last entry of the array. @param {Array} array
initial
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function tail(array) { return array.slice(1); }
returns the rest of the items in an array. @param {Array} array
tail
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function all(array, pred) { for (let idx = 0, len = array.length; idx < len; idx++) { if (!pred(array[idx])) { return false; } } return true; }
returns true if all of the values in the array pass the predicate truth test.
all
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function contains(array, item) { if (array && array.length && item) { if (array.indexOf) { return array.indexOf(item) !== -1; } else if (array.contains) { // `DOMTokenList` doesn't implement `.indexOf`, but it implements `.contains` return array.contains(item); } } return false; }
returns true if the value is present in the list.
contains
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function sum(array, fn) { fn = fn || func.self; return array.reduce(function(memo, v) { return memo + fn(v); }, 0); }
get sum from a list @param {Array} array - array @param {Function} fn - iterator
sum
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function from(collection) { const result = []; const length = collection.length; let idx = -1; while (++idx < length) { result[idx] = collection[idx]; } return result; }
returns a copy of the collection with array type. @param {Collection} collection - collection eg) node.childNodes, ...
from
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function isEmpty(array) { return !array || !array.length; }
returns whether list is empty or not
isEmpty
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function clusterBy(array, fn) { if (!array.length) { return []; } const aTail = tail(array); return aTail.reduce(function(memo, v) { const aLast = last(memo); if (fn(last(aLast), v)) { aLast[aLast.length] = v; } else { memo[memo.length] = [v]; } return memo; }, [[head(array)]]); }
cluster elements by predicate function. @param {Array} array - array @param {Function} fn - predicate function for cluster rule @param {Array[]}
clusterBy
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function compact(array) { const aResult = []; for (let idx = 0, len = array.length; idx < len; idx++) { if (array[idx]) { aResult.push(array[idx]); } } return aResult; }
returns a copy of the array with all false values removed @param {Array} array - array @param {Function} fn - predicate function for cluster rule
compact
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function unique(array) { const results = []; for (let idx = 0, len = array.length; idx < len; idx++) { if (!contains(results, array[idx])) { results.push(array[idx]); } } return results; }
produces a duplicate-free version of the array @param {Array} array
unique
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function next(array, item) { if (array && array.length && item) { const idx = array.indexOf(item); return idx === -1 ? null : array[idx + 1]; } return null; }
returns next item. @param {Array} array
next
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function prev(array, item) { if (array && array.length && item) { const idx = array.indexOf(item); return idx === -1 ? null : array[idx - 1]; } return null; }
returns prev item. @param {Array} array
prev
javascript
summernote/summernote
src/js/core/lists.js
https://github.com/summernote/summernote/blob/master/src/js/core/lists.js
MIT
function textRangeToPoint(textRange, isStart) { let container = textRange.parentElement(); let offset; const tester = document.body.createTextRange(); let prevContainer; const childNodes = lists.from(container.childNodes); for (offset = 0; offset < childNodes.length; offset++) { if (dom.isText(childNodes[offset])) { continue; } tester.moveToElementText(childNodes[offset]); if (tester.compareEndPoints('StartToStart', textRange) >= 0) { break; } prevContainer = childNodes[offset]; } if (offset !== 0 && dom.isText(childNodes[offset - 1])) { const textRangeStart = document.body.createTextRange(); let curTextNode = null; textRangeStart.moveToElementText(prevContainer || container); textRangeStart.collapse(!prevContainer); curTextNode = prevContainer ? prevContainer.nextSibling : container.firstChild; const pointTester = textRange.duplicate(); pointTester.setEndPoint('StartToStart', textRangeStart); let textCount = pointTester.text.replace(/[\r\n]/g, '').length; while (textCount > curTextNode.nodeValue.length && curTextNode.nextSibling) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } // [workaround] enforce IE to re-reference curTextNode, hack const dummy = curTextNode.nodeValue; // eslint-disable-line if (isStart && curTextNode.nextSibling && dom.isText(curTextNode.nextSibling) && textCount === curTextNode.nodeValue.length) { textCount -= curTextNode.nodeValue.length; curTextNode = curTextNode.nextSibling; } container = curTextNode; offset = textCount; } return { cont: container, offset: offset, }; }
return boundaryPoint from TextRange, inspired by Andy Na's HuskyRange.js @param {TextRange} textRange @param {Boolean} isStart @return {BoundaryPoint} @see http://msdn.microsoft.com/en-us/library/ie/ms535872(v=vs.85).aspx
textRangeToPoint
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
function pointToTextRange(point) { const textRangeInfo = function(container, offset) { let node, isCollapseToStart; if (dom.isText(container)) { const prevTextNodes = dom.listPrev(container, func.not(dom.isText)); const prevContainer = lists.last(prevTextNodes).previousSibling; node = prevContainer || container.parentNode; offset += lists.sum(lists.tail(prevTextNodes), dom.nodeLength); isCollapseToStart = !prevContainer; } else { node = container.childNodes[offset] || container; if (dom.isText(node)) { return textRangeInfo(node, 0); } offset = 0; isCollapseToStart = false; } return { node: node, collapseToStart: isCollapseToStart, offset: offset, }; }; const textRange = document.body.createTextRange(); const info = textRangeInfo(point.node, point.offset); textRange.moveToElementText(info.node); textRange.collapse(info.collapseToStart); textRange.moveStart('character', info.offset); return textRange; }
return TextRange from boundary point (inspired by google closure-library) @param {BoundaryPoint} point @return {TextRange}
pointToTextRange
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
textRangeInfo = function(container, offset) { let node, isCollapseToStart; if (dom.isText(container)) { const prevTextNodes = dom.listPrev(container, func.not(dom.isText)); const prevContainer = lists.last(prevTextNodes).previousSibling; node = prevContainer || container.parentNode; offset += lists.sum(lists.tail(prevTextNodes), dom.nodeLength); isCollapseToStart = !prevContainer; } else { node = container.childNodes[offset] || container; if (dom.isText(node)) { return textRangeInfo(node, 0); } offset = 0; isCollapseToStart = false; } return { node: node, collapseToStart: isCollapseToStart, offset: offset, }; }
return TextRange from boundary point (inspired by google closure-library) @param {BoundaryPoint} point @return {TextRange}
textRangeInfo
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
textRangeInfo = function(container, offset) { let node, isCollapseToStart; if (dom.isText(container)) { const prevTextNodes = dom.listPrev(container, func.not(dom.isText)); const prevContainer = lists.last(prevTextNodes).previousSibling; node = prevContainer || container.parentNode; offset += lists.sum(lists.tail(prevTextNodes), dom.nodeLength); isCollapseToStart = !prevContainer; } else { node = container.childNodes[offset] || container; if (dom.isText(node)) { return textRangeInfo(node, 0); } offset = 0; isCollapseToStart = false; } return { node: node, collapseToStart: isCollapseToStart, offset: offset, }; }
return TextRange from boundary point (inspired by google closure-library) @param {BoundaryPoint} point @return {TextRange}
textRangeInfo
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
constructor(sc, so, ec, eo) { this.sc = sc; this.so = so; this.ec = ec; this.eo = eo; // isOnEditable: judge whether range is on editable or not this.isOnEditable = this.makeIsOn(dom.isEditable); // isOnList: judge whether range is on list node or not this.isOnList = this.makeIsOn(dom.isList); // isOnAnchor: judge whether range is on anchor node or not this.isOnAnchor = this.makeIsOn(dom.isAnchor); // isOnCell: judge whether range is on cell node or not this.isOnCell = this.makeIsOn(dom.isCell); // isOnData: judge whether range is on data node or not this.isOnData = this.makeIsOn(dom.isData); }
Wrapped Range @constructor @param {Node} sc - start container @param {Number} so - start offset @param {Node} ec - end container @param {Number} eo - end offset
constructor
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
nativeRange() { if (env.isW3CRangeSupport) { const w3cRange = document.createRange(); w3cRange.setStart(this.sc, this.so); w3cRange.setEnd(this.ec, this.eo); return w3cRange; } else { const textRange = pointToTextRange({ node: this.sc, offset: this.so, }); textRange.setEndPoint('EndToEnd', pointToTextRange({ node: this.ec, offset: this.eo, })); return textRange; } }
Wrapped Range @constructor @param {Node} sc - start container @param {Number} so - start offset @param {Node} ec - end container @param {Number} eo - end offset
nativeRange
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
getPoints() { return { sc: this.sc, so: this.so, ec: this.ec, eo: this.eo, }; }
Wrapped Range @constructor @param {Node} sc - start container @param {Number} so - start offset @param {Node} ec - end container @param {Number} eo - end offset
getPoints
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
getStartPoint() { return { node: this.sc, offset: this.so, }; }
Wrapped Range @constructor @param {Node} sc - start container @param {Number} so - start offset @param {Node} ec - end container @param {Number} eo - end offset
getStartPoint
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
getEndPoint() { return { node: this.ec, offset: this.eo, }; }
Wrapped Range @constructor @param {Node} sc - start container @param {Number} so - start offset @param {Node} ec - end container @param {Number} eo - end offset
getEndPoint
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
scrollIntoView(container) { const height = $(container).height(); if (container.scrollTop + height < this.sc.offsetTop) { container.scrollTop += Math.abs(container.scrollTop + height - this.sc.offsetTop); } return this; }
Moves the scrollbar to start container(sc) of current range @return {WrappedRange}
scrollIntoView
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
getVisiblePoint = function(point, isLeftToRight) { if (!point) { return point; } // Just use the given point [XXX:Adhoc] // - case 01. if the point is on the middle of the node // - case 02. if the point is on the right edge and prefer to choose left node // - case 03. if the point is on the left edge and prefer to choose right node // - case 04. if the point is on the right edge and prefer to choose right node but the node is void // - case 05. if the point is on the left edge and prefer to choose left node but the node is void // - case 06. if the point is on the block node and there is no children if (dom.isVisiblePoint(point)) { if (!dom.isEdgePoint(point) || (dom.isRightEdgePoint(point) && !isLeftToRight) || (dom.isLeftEdgePoint(point) && isLeftToRight) || (dom.isRightEdgePoint(point) && isLeftToRight && dom.isVoid(point.node.nextSibling)) || (dom.isLeftEdgePoint(point) && !isLeftToRight && dom.isVoid(point.node.previousSibling)) || (dom.isBlock(point.node) && dom.isEmpty(point.node))) { return point; } } // point on block's edge const block = dom.ancestor(point.node, dom.isBlock); let hasRightNode = false; if (!hasRightNode) { const prevPoint = dom.prevPoint(point) || { node: null }; hasRightNode = (dom.isLeftEdgePointOf(point, block) || dom.isVoid(prevPoint.node)) && !isLeftToRight; } let hasLeftNode = false; if (!hasLeftNode) { const nextPoint = dom.nextPoint(point) || { node: null }; hasLeftNode = (dom.isRightEdgePointOf(point, block) || dom.isVoid(nextPoint.node)) && isLeftToRight; } if (hasRightNode || hasLeftNode) { // returns point already on visible point if (dom.isVisiblePoint(point)) { return point; } // reverse direction isLeftToRight = !isLeftToRight; } const nextPoint = isLeftToRight ? dom.nextPointUntil(dom.nextPoint(point), dom.isVisiblePoint) : dom.prevPointUntil(dom.prevPoint(point), dom.isVisiblePoint); return nextPoint || point; }
@param {BoundaryPoint} point @param {Boolean} isLeftToRight - true: prefer to choose right node - false: prefer to choose left node @return {BoundaryPoint}
getVisiblePoint
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
getVisiblePoint = function(point, isLeftToRight) { if (!point) { return point; } // Just use the given point [XXX:Adhoc] // - case 01. if the point is on the middle of the node // - case 02. if the point is on the right edge and prefer to choose left node // - case 03. if the point is on the left edge and prefer to choose right node // - case 04. if the point is on the right edge and prefer to choose right node but the node is void // - case 05. if the point is on the left edge and prefer to choose left node but the node is void // - case 06. if the point is on the block node and there is no children if (dom.isVisiblePoint(point)) { if (!dom.isEdgePoint(point) || (dom.isRightEdgePoint(point) && !isLeftToRight) || (dom.isLeftEdgePoint(point) && isLeftToRight) || (dom.isRightEdgePoint(point) && isLeftToRight && dom.isVoid(point.node.nextSibling)) || (dom.isLeftEdgePoint(point) && !isLeftToRight && dom.isVoid(point.node.previousSibling)) || (dom.isBlock(point.node) && dom.isEmpty(point.node))) { return point; } } // point on block's edge const block = dom.ancestor(point.node, dom.isBlock); let hasRightNode = false; if (!hasRightNode) { const prevPoint = dom.prevPoint(point) || { node: null }; hasRightNode = (dom.isLeftEdgePointOf(point, block) || dom.isVoid(prevPoint.node)) && !isLeftToRight; } let hasLeftNode = false; if (!hasLeftNode) { const nextPoint = dom.nextPoint(point) || { node: null }; hasLeftNode = (dom.isRightEdgePointOf(point, block) || dom.isVoid(nextPoint.node)) && isLeftToRight; } if (hasRightNode || hasLeftNode) { // returns point already on visible point if (dom.isVisiblePoint(point)) { return point; } // reverse direction isLeftToRight = !isLeftToRight; } const nextPoint = isLeftToRight ? dom.nextPointUntil(dom.nextPoint(point), dom.isVisiblePoint) : dom.prevPointUntil(dom.prevPoint(point), dom.isVisiblePoint); return nextPoint || point; }
@param {BoundaryPoint} point @param {Boolean} isLeftToRight - true: prefer to choose right node - false: prefer to choose left node @return {BoundaryPoint}
getVisiblePoint
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
nodes(pred, options) { pred = pred || func.ok; const includeAncestor = options && options.includeAncestor; const fullyContains = options && options.fullyContains; // TODO compare points and sort const startPoint = this.getStartPoint(); const endPoint = this.getEndPoint(); const nodes = []; const leftEdgeNodes = []; dom.walkPoint(startPoint, endPoint, function(point) { if (dom.isEditable(point.node)) { return; } let node; if (fullyContains) { if (dom.isLeftEdgePoint(point)) { leftEdgeNodes.push(point.node); } if (dom.isRightEdgePoint(point) && lists.contains(leftEdgeNodes, point.node)) { node = point.node; } } else if (includeAncestor) { node = dom.ancestor(point.node, pred); } else { node = point.node; } if (node && pred(node)) { nodes.push(node); } }, true); return lists.unique(nodes); }
returns matched nodes on range @param {Function} [pred] - predicate function @param {Object} [options] @param {Boolean} [options.includeAncestor] @param {Boolean} [options.fullyContains] @return {Node[]}
nodes
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
commonAncestor() { return dom.commonAncestor(this.sc, this.ec); }
returns commonAncestor of range @return {Element} - commonAncestor
commonAncestor
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
expand(pred) { const startAncestor = dom.ancestor(this.sc, pred); const endAncestor = dom.ancestor(this.ec, pred); if (!startAncestor && !endAncestor) { return new WrappedRange(this.sc, this.so, this.ec, this.eo); } const boundaryPoints = this.getPoints(); if (startAncestor) { boundaryPoints.sc = startAncestor; boundaryPoints.so = 0; } if (endAncestor) { boundaryPoints.ec = endAncestor; boundaryPoints.eo = dom.nodeLength(endAncestor); } return new WrappedRange( boundaryPoints.sc, boundaryPoints.so, boundaryPoints.ec, boundaryPoints.eo ); }
returns expanded range by pred @param {Function} pred - predicate function @return {WrappedRange}
expand
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
deleteContents() { if (this.isCollapsed()) { return this; } const rng = this.splitText(); const nodes = rng.nodes(null, { fullyContains: true, }); // find new cursor point const point = dom.prevPointUntil(rng.getStartPoint(), function(point) { return !lists.contains(nodes, point.node); }); const emptyParents = []; $.each(nodes, function(idx, node) { // find empty parents const parent = node.parentNode; if (point.node !== parent && dom.nodeLength(parent) === 1) { emptyParents.push(parent); } dom.remove(node, false); }); // remove empty parents $.each(emptyParents, function(idx, node) { dom.remove(node, false); }); return new WrappedRange( point.node, point.offset, point.node, point.offset ).normalize(); }
delete contents on range @return {WrappedRange}
deleteContents
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
isCollapsed() { return this.sc === this.ec && this.so === this.eo; }
returns whether range was collapsed or not
isCollapsed
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
wrapBodyInlineWithPara() { if (dom.isBodyContainer(this.sc) && dom.isEmpty(this.sc)) { this.sc.innerHTML = dom.emptyPara; return new WrappedRange(this.sc.firstChild, 0, this.sc.firstChild, 0); } /** * [workaround] firefox often create range on not visible point. so normalize here. * - firefox: |<p>text</p>| * - chrome: <p>|text|</p> */ const rng = this.normalize(); if (dom.isParaInline(this.sc) || dom.isPara(this.sc)) { return rng; } // find inline top ancestor let topAncestor; if (dom.isInline(rng.sc)) { const ancestors = dom.listAncestor(rng.sc, func.not(dom.isInline)); topAncestor = lists.last(ancestors); if (!dom.isInline(topAncestor)) { topAncestor = ancestors[ancestors.length - 2] || rng.sc.childNodes[rng.so]; } } else { topAncestor = rng.sc.childNodes[rng.so > 0 ? rng.so - 1 : 0]; } if (topAncestor) { // siblings not in paragraph let inlineSiblings = dom.listPrev(topAncestor, dom.isParaInline).reverse(); inlineSiblings = inlineSiblings.concat(dom.listNext(topAncestor.nextSibling, dom.isParaInline)); // wrap with paragraph if (inlineSiblings.length) { const para = dom.wrap(lists.head(inlineSiblings), 'p'); dom.appendChildNodes(para, lists.tail(inlineSiblings)); } } return this.normalize(); }
wrap inline nodes which children of body with paragraph @return {WrappedRange}
wrapBodyInlineWithPara
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
insertNode(node, doNotInsertPara = false) { let rng = this; if (dom.isText(node) || dom.isInline(node)) { rng = this.wrapBodyInlineWithPara().deleteContents(); } const info = dom.splitPoint(rng.getStartPoint(), dom.isInline(node)); if (info.rightNode) { info.rightNode.parentNode.insertBefore(node, info.rightNode); if (dom.isEmpty(info.rightNode) && (doNotInsertPara || dom.isPara(node))) { info.rightNode.parentNode.removeChild(info.rightNode); } } else { info.container.appendChild(node); } return node; }
insert node at current cursor @param {Node} node @param {Boolean} doNotInsertPara - default is false, removes added <p> that's added if true @return {Node}
insertNode
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
toString() { const nativeRng = this.nativeRange(); return env.isW3CRangeSupport ? nativeRng.toString() : nativeRng.text; }
returns text in range @return {String}
toString
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
getWordRange(findAfter) { let endPoint = this.getEndPoint(); if (!dom.isCharPoint(endPoint)) { return this; } const startPoint = dom.prevPointUntil(endPoint, function(point) { return !dom.isCharPoint(point); }); if (findAfter) { endPoint = dom.nextPointUntil(endPoint, function(point) { return !dom.isCharPoint(point); }); } return new WrappedRange( startPoint.node, startPoint.offset, endPoint.node, endPoint.offset ); }
returns range for word before cursor @param {Boolean} [findAfter] - find after cursor, default: false @return {WrappedRange}
getWordRange
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
getWordsRange(findAfter) { var endPoint = this.getEndPoint(); var isNotTextPoint = function(point) { return !dom.isCharPoint(point) && !dom.isSpacePoint(point); }; if (isNotTextPoint(endPoint)) { return this; } var startPoint = dom.prevPointUntil(endPoint, isNotTextPoint); if (findAfter) { endPoint = dom.nextPointUntil(endPoint, isNotTextPoint); } return new WrappedRange( startPoint.node, startPoint.offset, endPoint.node, endPoint.offset ); }
returns range for words before cursor @param {Boolean} [findAfter] - find after cursor, default: false @return {WrappedRange}
getWordsRange
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
isNotTextPoint = function(point) { return !dom.isCharPoint(point) && !dom.isSpacePoint(point); }
returns range for words before cursor @param {Boolean} [findAfter] - find after cursor, default: false @return {WrappedRange}
isNotTextPoint
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
getWordsMatchRange(regex) { var endPoint = this.getEndPoint(); var startPoint = dom.prevPointUntil(endPoint, function(point) { if (!dom.isCharPoint(point) && !dom.isSpacePoint(point)) { return true; } var rng = new WrappedRange( point.node, point.offset, endPoint.node, endPoint.offset ); var result = regex.exec(rng.toString()); return result && result.index === 0; }); var rng = new WrappedRange( startPoint.node, startPoint.offset, endPoint.node, endPoint.offset ); var text = rng.toString(); var result = regex.exec(text); if (result && result[0].length === text.length) { return rng; } else { return null; } }
returns range for words before cursor that match with a Regex example: range: 'hi @Peter Pan' regex: '/@[a-z ]+/i' return range: '@Peter Pan' @param {RegExp} [regex] @return {WrappedRange|null}
getWordsMatchRange
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
bookmark(editable) { return { s: { path: dom.makeOffsetPath(editable, this.sc), offset: this.so, }, e: { path: dom.makeOffsetPath(editable, this.ec), offset: this.eo, }, }; }
create offsetPath bookmark @param {Node} editable
bookmark
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
paraBookmark(paras) { return { s: { path: lists.tail(dom.makeOffsetPath(lists.head(paras), this.sc)), offset: this.so, }, e: { path: lists.tail(dom.makeOffsetPath(lists.last(paras), this.ec)), offset: this.eo, }, }; }
create offsetPath bookmark base on paragraph @param {Node[]} paras
paraBookmark
javascript
summernote/summernote
src/js/core/range.js
https://github.com/summernote/summernote/blob/master/src/js/core/range.js
MIT
toggleList(listName, editable) { const rng = range.create(editable).wrapBodyInlineWithPara(); let paras = rng.nodes(dom.isPara, { includeAncestor: true }); const bookmark = rng.paraBookmark(paras); const clustereds = lists.clusterBy(paras, func.peq2('parentNode')); // paragraph to list if (lists.find(paras, dom.isPurePara)) { let wrappedParas = []; $.each(clustereds, (idx, paras) => { wrappedParas = wrappedParas.concat(this.wrapList(paras, listName)); }); paras = wrappedParas; // list to paragraph or change list style } else { const diffLists = rng .nodes(dom.isList, { includeAncestor: true, }) .filter((listNode) => { return !$.nodeName(listNode, listName); }); if (diffLists.length) { $.each(diffLists, (idx, listNode) => { dom.replace(listNode, listName); }); } else { paras = this.releaseList(clustereds, true); } } range.createFromParaBookmark(bookmark, paras).select(); }
toggle list @param {String} listName - OL or UL
toggleList
javascript
summernote/summernote
src/js/editing/Bullet.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Bullet.js
MIT
wrapList(paras, listName) { const head = lists.head(paras); const last = lists.last(paras); const prevList = dom.isList(head.previousSibling) && head.previousSibling; const nextList = dom.isList(last.nextSibling) && last.nextSibling; const listNode = prevList || dom.insertAfter(dom.create(listName || 'UL'), last); // P to LI paras = paras.map((para) => { return dom.isPurePara(para) ? dom.replace(para, 'LI') : para; }); // append to list(<ul>, <ol>) dom.appendChildNodes(listNode, paras, true); if (nextList) { dom.appendChildNodes(listNode, lists.from(nextList.childNodes), true); dom.remove(nextList); } return paras; }
@param {Node[]} paras @param {String} listName @return {Node[]}
wrapList
javascript
summernote/summernote
src/js/editing/Bullet.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Bullet.js
MIT
releaseList(clustereds, isEscapseToBody) { let releasedParas = []; $.each(clustereds, (idx, paras) => { const head = lists.head(paras); const last = lists.last(paras); const headList = isEscapseToBody ? dom.lastAncestor(head, dom.isList) : head.parentNode; const parentItem = headList.parentNode; if (headList.parentNode.nodeName === 'LI') { paras.map((para) => { const newList = this.findNextSiblings(para); if (parentItem.nextSibling) { parentItem.parentNode.insertBefore(para, parentItem.nextSibling); } else { parentItem.parentNode.appendChild(para); } if (newList.length) { this.wrapList(newList, headList.nodeName); para.appendChild(newList[0].parentNode); } }); if (headList.children.length === 0) { parentItem.removeChild(headList); } if (parentItem.childNodes.length === 0) { parentItem.parentNode.removeChild(parentItem); } } else { const lastList = headList.childNodes.length > 1 ? dom.splitTree( headList, { node: last.parentNode, offset: dom.position(last) + 1, }, { isSkipPaddingBlankHTML: true, }, ) : null; const middleList = dom.splitTree( headList, { node: head.parentNode, offset: dom.position(head), }, { isSkipPaddingBlankHTML: true, }, ); paras = isEscapseToBody ? dom.listDescendant(middleList, dom.isLi) : lists.from(middleList.childNodes).filter(dom.isLi); // LI to P if (isEscapseToBody || !dom.isList(headList.parentNode)) { paras = paras.map((para) => { return dom.replace(para, 'P'); }); } $.each(lists.from(paras).reverse(), (idx, para) => { dom.insertAfter(para, headList); }); // remove empty lists const rootLists = lists.compact([headList, middleList, lastList]); $.each(rootLists, (idx, rootList) => { const listNodes = [rootList].concat(dom.listDescendant(rootList, dom.isList)); $.each(listNodes.reverse(), (idx, listNode) => { if (!dom.nodeLength(listNode)) { dom.remove(listNode, true); } }); }); } releasedParas = releasedParas.concat(paras); }); return releasedParas; }
@method releaseList @param {Array[]} clustereds @param {Boolean} isEscapseToBody @return {Node[]}
releaseList
javascript
summernote/summernote
src/js/editing/Bullet.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Bullet.js
MIT
appendToPrevious(node) { return node.previousSibling ? dom.appendChildNodes(node.previousSibling, [node]) : this.wrapList([node], 'LI'); }
@method appendToPrevious Appends list to previous list item, if none exist it wraps the list in a new list item. @param {HTMLNode} ListItem @return {HTMLNode}
appendToPrevious
javascript
summernote/summernote
src/js/editing/Bullet.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Bullet.js
MIT
findList(node) { return node ? lists.find(node.children, (child) => ['OL', 'UL'].indexOf(child.nodeName) > -1) : null; }
@method findList Finds an existing list in list item @param {HTMLNode} ListItem @return {Array[]}
findList
javascript
summernote/summernote
src/js/editing/Bullet.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Bullet.js
MIT
findNextSiblings(node) { const siblings = []; while (node.nextSibling) { siblings.push(node.nextSibling); node = node.nextSibling; } return siblings; }
@method findNextSiblings Finds all list item siblings that follow it @param {HTMLNode} ListItem @return {HTMLNode}
findNextSiblings
javascript
summernote/summernote
src/js/editing/Bullet.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Bullet.js
MIT
rewind() { // Create snap shot if not yet recorded if (this.$editable.html() !== this.stack[this.stackOffset].contents) { this.recordUndo(); } // Return to the first available snapshot. this.stackOffset = 0; // Apply that snapshot. this.applySnapshot(this.stack[this.stackOffset]); }
@method rewind Rewinds the history stack back to the first snapshot taken. Leaves the stack intact, so that "Redo" can still be used.
rewind
javascript
summernote/summernote
src/js/editing/History.js
https://github.com/summernote/summernote/blob/master/src/js/editing/History.js
MIT
reset() { // Clear the stack. this.stack = []; // Restore stackOffset to its original value. this.stackOffset = -1; // Clear the editable area. this.$editable.html(''); // Record our first snapshot (of nothing). this.recordUndo(); }
@method reset Resets the history stack completely; reverting to an empty editor.
reset
javascript
summernote/summernote
src/js/editing/History.js
https://github.com/summernote/summernote/blob/master/src/js/editing/History.js
MIT
jQueryCSS($obj, propertyNames) { const result = {}; $.each(propertyNames, (idx, propertyName) => { result[propertyName] = $obj.css(propertyName); }); return result; }
@method jQueryCSS [workaround] for old jQuery passing an array of style properties to .css() will result in an object of property-value pairs. (compability with version < 1.9) @private @param {jQuery} $obj @param {Array} propertyNames - An array of one or more CSS properties. @return {Object}
jQueryCSS
javascript
summernote/summernote
src/js/editing/Style.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Style.js
MIT
fromNode($node) { const properties = ['font-family', 'font-size', 'text-align', 'list-style-type', 'line-height']; const styleInfo = this.jQueryCSS($node, properties) || {}; const fontSize = $node[0].style.fontSize || styleInfo['font-size']; styleInfo['font-size'] = parseInt(fontSize, 10); styleInfo['font-size-unit'] = fontSize.match(/[a-z%]+$/); return styleInfo; }
returns style object from node @param {jQuery} $node @return {Object}
fromNode
javascript
summernote/summernote
src/js/editing/Style.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Style.js
MIT
stylePara(rng, styleInfo) { $.each(rng.nodes(dom.isPara, { includeAncestor: true, }), (idx, para) => { $(para).css(styleInfo); }); }
paragraph level style @param {WrappedRange} rng @param {Object} styleInfo
stylePara
javascript
summernote/summernote
src/js/editing/Style.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Style.js
MIT
styleNodes(rng, options) { rng = rng.splitText(); const nodeName = (options && options.nodeName) || 'SPAN'; const expandClosestSibling = !!(options && options.expandClosestSibling); const onlyPartialContains = !!(options && options.onlyPartialContains); if (rng.isCollapsed()) { return [rng.insertNode(dom.create(nodeName))]; } let pred = dom.makePredByNodeName(nodeName); const nodes = rng.nodes(dom.isText, { fullyContains: true, }).map((text) => { return dom.singleChildAncestor(text, pred) || dom.wrap(text, nodeName); }); if (expandClosestSibling) { if (onlyPartialContains) { const nodesInRange = rng.nodes(); // compose with partial contains predication pred = func.and(pred, (node) => { return lists.contains(nodesInRange, node); }); } return nodes.map((node) => { const siblings = dom.withClosestSiblings(node, pred); const head = lists.head(siblings); const tails = lists.tail(siblings); $.each(tails, (idx, elem) => { dom.appendChildNodes(head, elem.childNodes); dom.remove(elem); }); return lists.head(siblings); }); } else { return nodes; } }
insert and returns styleNodes on range. @param {WrappedRange} rng @param {Object} [options] - options for styleNodes @param {String} [options.nodeName] - default: `SPAN` @param {Boolean} [options.expandClosestSibling] - default: `false` @param {Boolean} [options.onlyPartialContains] - default: `false` @return {Node[]}
styleNodes
javascript
summernote/summernote
src/js/editing/Style.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Style.js
MIT
current(rng) { const $cont = $(!dom.isElement(rng.sc) ? rng.sc.parentNode : rng.sc); let styleInfo = this.fromNode($cont); // document.queryCommandState for toggle state // [workaround] prevent Firefox nsresult: "0x80004005 (NS_ERROR_FAILURE)" try { styleInfo = $.extend(styleInfo, { 'font-bold': document.queryCommandState('bold') ? 'bold' : 'normal', 'font-italic': document.queryCommandState('italic') ? 'italic' : 'normal', 'font-underline': document.queryCommandState('underline') ? 'underline' : 'normal', 'font-subscript': document.queryCommandState('subscript') ? 'subscript' : 'normal', 'font-superscript': document.queryCommandState('superscript') ? 'superscript' : 'normal', 'font-strikethrough': document.queryCommandState('strikethrough') ? 'strikethrough' : 'normal', 'font-family': document.queryCommandValue('fontname') || styleInfo['font-family'], }); } catch (e) { // eslint-disable-next-line } // list-style-type to list-style(unordered, ordered) if (!rng.isOnList()) { styleInfo['list-style'] = 'none'; } else { const orderedTypes = ['circle', 'disc', 'disc-leading-zero', 'square']; const isUnordered = orderedTypes.indexOf(styleInfo['list-style-type']) > -1; styleInfo['list-style'] = isUnordered ? 'unordered' : 'ordered'; } const para = dom.ancestor(rng.sc, dom.isPara); if (para && para.style['line-height']) { styleInfo['line-height'] = para.style.lineHeight; } else { const lineHeight = parseInt(styleInfo['line-height'], 10) / parseInt(styleInfo['font-size'], 10); styleInfo['line-height'] = lineHeight.toFixed(1); } styleInfo.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor); styleInfo.ancestors = dom.listAncestor(rng.sc, dom.isEditable); styleInfo.range = rng; return styleInfo; }
get current style on cursor @param {WrappedRange} rng @return {Object} - object contains style properties.
current
javascript
summernote/summernote
src/js/editing/Style.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Style.js
MIT
TableResultAction = function(startPoint, where, action, domTable) { const _startPoint = { 'colPos': 0, 'rowPos': 0 }; const _virtualTable = []; const _actionCellList = []; /// /////////////////////////////////////////// // Private functions /// /////////////////////////////////////////// /** * Set the startPoint of action. */ function setStartPoint() { if (!startPoint || !startPoint.tagName || (startPoint.tagName.toLowerCase() !== 'td' && startPoint.tagName.toLowerCase() !== 'th')) { // Impossible to identify start Cell point return; } _startPoint.colPos = startPoint.cellIndex; if (!startPoint.parentElement || !startPoint.parentElement.tagName || startPoint.parentElement.tagName.toLowerCase() !== 'tr') { // Impossible to identify start Row point return; } _startPoint.rowPos = startPoint.parentElement.rowIndex; } /** * Define virtual table position info object. * * @param {int} rowIndex Index position in line of virtual table. * @param {int} cellIndex Index position in column of virtual table. * @param {object} baseRow Row affected by this position. * @param {object} baseCell Cell affected by this position. * @param {bool} isSpan Inform if it is an span cell/row. */ function setVirtualTablePosition(rowIndex, cellIndex, baseRow, baseCell, isRowSpan, isColSpan, isVirtualCell) { const objPosition = { 'baseRow': baseRow, 'baseCell': baseCell, 'isRowSpan': isRowSpan, 'isColSpan': isColSpan, 'isVirtual': isVirtualCell, }; if (!_virtualTable[rowIndex]) { _virtualTable[rowIndex] = []; } _virtualTable[rowIndex][cellIndex] = objPosition; } /** * Create action cell object. * * @param {object} virtualTableCellObj Object of specific position on virtual table. * @param {enum} resultAction Action to be applied in that item. */ function getActionCell(virtualTableCellObj, resultAction, virtualRowPosition, virtualColPosition) { return { 'baseCell': virtualTableCellObj.baseCell, 'action': resultAction, 'virtualTable': { 'rowIndex': virtualRowPosition, 'cellIndex': virtualColPosition, }, }; } /** * Recover free index of row to append Cell. * * @param {int} rowIndex Index of row to find free space. * @param {int} cellIndex Index of cell to find free space in table. */ function recoverCellIndex(rowIndex, cellIndex) { if (!_virtualTable[rowIndex]) { return cellIndex; } if (!_virtualTable[rowIndex][cellIndex]) { return cellIndex; } let newCellIndex = cellIndex; while (_virtualTable[rowIndex][newCellIndex]) { newCellIndex++; if (!_virtualTable[rowIndex][newCellIndex]) { return newCellIndex; } } } /** * Recover info about row and cell and add information to virtual table. * * @param {object} row Row to recover information. * @param {object} cell Cell to recover information. */ function addCellInfoToVirtual(row, cell) { const cellIndex = recoverCellIndex(row.rowIndex, cell.cellIndex); const cellHasColspan = (cell.colSpan > 1); const cellHasRowspan = (cell.rowSpan > 1); const isThisSelectedCell = (row.rowIndex === _startPoint.rowPos && cell.cellIndex === _startPoint.colPos); setVirtualTablePosition(row.rowIndex, cellIndex, row, cell, cellHasRowspan, cellHasColspan, false); // Add span rows to virtual Table. const rowspanNumber = cell.attributes.rowSpan ? parseInt(cell.attributes.rowSpan.value, 10) : 0; if (rowspanNumber > 1) { for (let rp = 1; rp < rowspanNumber; rp++) { const rowspanIndex = row.rowIndex + rp; adjustStartPoint(rowspanIndex, cellIndex, cell, isThisSelectedCell); setVirtualTablePosition(rowspanIndex, cellIndex, row, cell, true, cellHasColspan, true); } } // Add span cols to virtual table. const colspanNumber = cell.attributes.colSpan ? parseInt(cell.attributes.colSpan.value, 10) : 0; if (colspanNumber > 1) { for (let cp = 1; cp < colspanNumber; cp++) { const cellspanIndex = recoverCellIndex(row.rowIndex, (cellIndex + cp)); adjustStartPoint(row.rowIndex, cellspanIndex, cell, isThisSelectedCell); setVirtualTablePosition(row.rowIndex, cellspanIndex, row, cell, cellHasRowspan, true, true); } } } /** * Process validation and adjust of start point if needed * * @param {int} rowIndex * @param {int} cellIndex * @param {object} cell * @param {bool} isSelectedCell */ function adjustStartPoint(rowIndex, cellIndex, cell, isSelectedCell) { if (rowIndex === _startPoint.rowPos && _startPoint.colPos >= cell.cellIndex && cell.cellIndex <= cellIndex && !isSelectedCell) { _startPoint.colPos++; } } /** * Create virtual table of cells with all cells, including span cells. */ function createVirtualTable() { const rows = domTable.rows; for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) { const cells = rows[rowIndex].cells; for (let cellIndex = 0; cellIndex < cells.length; cellIndex++) { addCellInfoToVirtual(rows[rowIndex], cells[cellIndex]); } } } /** * Get action to be applied on the cell. * * @param {object} cell virtual table cell to apply action */ function getDeleteResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; case TableResultAction.where.Row: if (!cell.isVirtual && cell.isRowSpan) { return TableResultAction.resultAction.AddCell; } else if (cell.isRowSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; } return TableResultAction.resultAction.RemoveCell; } /** * Get action to be applied on the cell. * * @param {object} cell virtual table cell to apply action */ function getAddResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isRowSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; case TableResultAction.where.Row: if (cell.isRowSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isColSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; } return TableResultAction.resultAction.AddCell; } function init() { setStartPoint(); createVirtualTable(); } /// /////////////////////////////////////////// // Public functions /// /////////////////////////////////////////// /** * Recover array os what to do in table. */ this.getActionList = function() { const fixedRow = (where === TableResultAction.where.Row) ? _startPoint.rowPos : -1; const fixedCol = (where === TableResultAction.where.Column) ? _startPoint.colPos : -1; let actualPosition = 0; let canContinue = true; while (canContinue) { const rowPosition = (fixedRow >= 0) ? fixedRow : actualPosition; const colPosition = (fixedCol >= 0) ? fixedCol : actualPosition; const row = _virtualTable[rowPosition]; if (!row) { canContinue = false; return _actionCellList; } const cell = row[colPosition]; if (!cell) { canContinue = false; return _actionCellList; } // Define action to be applied in this cell let resultAction = TableResultAction.resultAction.Ignore; switch (action) { case TableResultAction.requestAction.Add: resultAction = getAddResultActionToCell(cell); break; case TableResultAction.requestAction.Delete: resultAction = getDeleteResultActionToCell(cell); break; } _actionCellList.push(getActionCell(cell, resultAction, rowPosition, colPosition)); actualPosition++; } return _actionCellList; }; init(); }
@class Create a virtual table to create what actions to do in change. @param {object} startPoint Cell selected to apply change. @param {enum} where Where change will be applied Row or Col. Use enum: TableResultAction.where @param {enum} action Action to be applied. Use enum: TableResultAction.requestAction @param {object} domTable Dom element of table to make changes.
TableResultAction
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
TableResultAction = function(startPoint, where, action, domTable) { const _startPoint = { 'colPos': 0, 'rowPos': 0 }; const _virtualTable = []; const _actionCellList = []; /// /////////////////////////////////////////// // Private functions /// /////////////////////////////////////////// /** * Set the startPoint of action. */ function setStartPoint() { if (!startPoint || !startPoint.tagName || (startPoint.tagName.toLowerCase() !== 'td' && startPoint.tagName.toLowerCase() !== 'th')) { // Impossible to identify start Cell point return; } _startPoint.colPos = startPoint.cellIndex; if (!startPoint.parentElement || !startPoint.parentElement.tagName || startPoint.parentElement.tagName.toLowerCase() !== 'tr') { // Impossible to identify start Row point return; } _startPoint.rowPos = startPoint.parentElement.rowIndex; } /** * Define virtual table position info object. * * @param {int} rowIndex Index position in line of virtual table. * @param {int} cellIndex Index position in column of virtual table. * @param {object} baseRow Row affected by this position. * @param {object} baseCell Cell affected by this position. * @param {bool} isSpan Inform if it is an span cell/row. */ function setVirtualTablePosition(rowIndex, cellIndex, baseRow, baseCell, isRowSpan, isColSpan, isVirtualCell) { const objPosition = { 'baseRow': baseRow, 'baseCell': baseCell, 'isRowSpan': isRowSpan, 'isColSpan': isColSpan, 'isVirtual': isVirtualCell, }; if (!_virtualTable[rowIndex]) { _virtualTable[rowIndex] = []; } _virtualTable[rowIndex][cellIndex] = objPosition; } /** * Create action cell object. * * @param {object} virtualTableCellObj Object of specific position on virtual table. * @param {enum} resultAction Action to be applied in that item. */ function getActionCell(virtualTableCellObj, resultAction, virtualRowPosition, virtualColPosition) { return { 'baseCell': virtualTableCellObj.baseCell, 'action': resultAction, 'virtualTable': { 'rowIndex': virtualRowPosition, 'cellIndex': virtualColPosition, }, }; } /** * Recover free index of row to append Cell. * * @param {int} rowIndex Index of row to find free space. * @param {int} cellIndex Index of cell to find free space in table. */ function recoverCellIndex(rowIndex, cellIndex) { if (!_virtualTable[rowIndex]) { return cellIndex; } if (!_virtualTable[rowIndex][cellIndex]) { return cellIndex; } let newCellIndex = cellIndex; while (_virtualTable[rowIndex][newCellIndex]) { newCellIndex++; if (!_virtualTable[rowIndex][newCellIndex]) { return newCellIndex; } } } /** * Recover info about row and cell and add information to virtual table. * * @param {object} row Row to recover information. * @param {object} cell Cell to recover information. */ function addCellInfoToVirtual(row, cell) { const cellIndex = recoverCellIndex(row.rowIndex, cell.cellIndex); const cellHasColspan = (cell.colSpan > 1); const cellHasRowspan = (cell.rowSpan > 1); const isThisSelectedCell = (row.rowIndex === _startPoint.rowPos && cell.cellIndex === _startPoint.colPos); setVirtualTablePosition(row.rowIndex, cellIndex, row, cell, cellHasRowspan, cellHasColspan, false); // Add span rows to virtual Table. const rowspanNumber = cell.attributes.rowSpan ? parseInt(cell.attributes.rowSpan.value, 10) : 0; if (rowspanNumber > 1) { for (let rp = 1; rp < rowspanNumber; rp++) { const rowspanIndex = row.rowIndex + rp; adjustStartPoint(rowspanIndex, cellIndex, cell, isThisSelectedCell); setVirtualTablePosition(rowspanIndex, cellIndex, row, cell, true, cellHasColspan, true); } } // Add span cols to virtual table. const colspanNumber = cell.attributes.colSpan ? parseInt(cell.attributes.colSpan.value, 10) : 0; if (colspanNumber > 1) { for (let cp = 1; cp < colspanNumber; cp++) { const cellspanIndex = recoverCellIndex(row.rowIndex, (cellIndex + cp)); adjustStartPoint(row.rowIndex, cellspanIndex, cell, isThisSelectedCell); setVirtualTablePosition(row.rowIndex, cellspanIndex, row, cell, cellHasRowspan, true, true); } } } /** * Process validation and adjust of start point if needed * * @param {int} rowIndex * @param {int} cellIndex * @param {object} cell * @param {bool} isSelectedCell */ function adjustStartPoint(rowIndex, cellIndex, cell, isSelectedCell) { if (rowIndex === _startPoint.rowPos && _startPoint.colPos >= cell.cellIndex && cell.cellIndex <= cellIndex && !isSelectedCell) { _startPoint.colPos++; } } /** * Create virtual table of cells with all cells, including span cells. */ function createVirtualTable() { const rows = domTable.rows; for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) { const cells = rows[rowIndex].cells; for (let cellIndex = 0; cellIndex < cells.length; cellIndex++) { addCellInfoToVirtual(rows[rowIndex], cells[cellIndex]); } } } /** * Get action to be applied on the cell. * * @param {object} cell virtual table cell to apply action */ function getDeleteResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; case TableResultAction.where.Row: if (!cell.isVirtual && cell.isRowSpan) { return TableResultAction.resultAction.AddCell; } else if (cell.isRowSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; } return TableResultAction.resultAction.RemoveCell; } /** * Get action to be applied on the cell. * * @param {object} cell virtual table cell to apply action */ function getAddResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isRowSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; case TableResultAction.where.Row: if (cell.isRowSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isColSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; } return TableResultAction.resultAction.AddCell; } function init() { setStartPoint(); createVirtualTable(); } /// /////////////////////////////////////////// // Public functions /// /////////////////////////////////////////// /** * Recover array os what to do in table. */ this.getActionList = function() { const fixedRow = (where === TableResultAction.where.Row) ? _startPoint.rowPos : -1; const fixedCol = (where === TableResultAction.where.Column) ? _startPoint.colPos : -1; let actualPosition = 0; let canContinue = true; while (canContinue) { const rowPosition = (fixedRow >= 0) ? fixedRow : actualPosition; const colPosition = (fixedCol >= 0) ? fixedCol : actualPosition; const row = _virtualTable[rowPosition]; if (!row) { canContinue = false; return _actionCellList; } const cell = row[colPosition]; if (!cell) { canContinue = false; return _actionCellList; } // Define action to be applied in this cell let resultAction = TableResultAction.resultAction.Ignore; switch (action) { case TableResultAction.requestAction.Add: resultAction = getAddResultActionToCell(cell); break; case TableResultAction.requestAction.Delete: resultAction = getDeleteResultActionToCell(cell); break; } _actionCellList.push(getActionCell(cell, resultAction, rowPosition, colPosition)); actualPosition++; } return _actionCellList; }; init(); }
@class Create a virtual table to create what actions to do in change. @param {object} startPoint Cell selected to apply change. @param {enum} where Where change will be applied Row or Col. Use enum: TableResultAction.where @param {enum} action Action to be applied. Use enum: TableResultAction.requestAction @param {object} domTable Dom element of table to make changes.
TableResultAction
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
function setVirtualTablePosition(rowIndex, cellIndex, baseRow, baseCell, isRowSpan, isColSpan, isVirtualCell) { const objPosition = { 'baseRow': baseRow, 'baseCell': baseCell, 'isRowSpan': isRowSpan, 'isColSpan': isColSpan, 'isVirtual': isVirtualCell, }; if (!_virtualTable[rowIndex]) { _virtualTable[rowIndex] = []; } _virtualTable[rowIndex][cellIndex] = objPosition; }
Define virtual table position info object. @param {int} rowIndex Index position in line of virtual table. @param {int} cellIndex Index position in column of virtual table. @param {object} baseRow Row affected by this position. @param {object} baseCell Cell affected by this position. @param {bool} isSpan Inform if it is an span cell/row.
setVirtualTablePosition
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
function getActionCell(virtualTableCellObj, resultAction, virtualRowPosition, virtualColPosition) { return { 'baseCell': virtualTableCellObj.baseCell, 'action': resultAction, 'virtualTable': { 'rowIndex': virtualRowPosition, 'cellIndex': virtualColPosition, }, }; }
Create action cell object. @param {object} virtualTableCellObj Object of specific position on virtual table. @param {enum} resultAction Action to be applied in that item.
getActionCell
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
function recoverCellIndex(rowIndex, cellIndex) { if (!_virtualTable[rowIndex]) { return cellIndex; } if (!_virtualTable[rowIndex][cellIndex]) { return cellIndex; } let newCellIndex = cellIndex; while (_virtualTable[rowIndex][newCellIndex]) { newCellIndex++; if (!_virtualTable[rowIndex][newCellIndex]) { return newCellIndex; } } }
Recover free index of row to append Cell. @param {int} rowIndex Index of row to find free space. @param {int} cellIndex Index of cell to find free space in table.
recoverCellIndex
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
function addCellInfoToVirtual(row, cell) { const cellIndex = recoverCellIndex(row.rowIndex, cell.cellIndex); const cellHasColspan = (cell.colSpan > 1); const cellHasRowspan = (cell.rowSpan > 1); const isThisSelectedCell = (row.rowIndex === _startPoint.rowPos && cell.cellIndex === _startPoint.colPos); setVirtualTablePosition(row.rowIndex, cellIndex, row, cell, cellHasRowspan, cellHasColspan, false); // Add span rows to virtual Table. const rowspanNumber = cell.attributes.rowSpan ? parseInt(cell.attributes.rowSpan.value, 10) : 0; if (rowspanNumber > 1) { for (let rp = 1; rp < rowspanNumber; rp++) { const rowspanIndex = row.rowIndex + rp; adjustStartPoint(rowspanIndex, cellIndex, cell, isThisSelectedCell); setVirtualTablePosition(rowspanIndex, cellIndex, row, cell, true, cellHasColspan, true); } } // Add span cols to virtual table. const colspanNumber = cell.attributes.colSpan ? parseInt(cell.attributes.colSpan.value, 10) : 0; if (colspanNumber > 1) { for (let cp = 1; cp < colspanNumber; cp++) { const cellspanIndex = recoverCellIndex(row.rowIndex, (cellIndex + cp)); adjustStartPoint(row.rowIndex, cellspanIndex, cell, isThisSelectedCell); setVirtualTablePosition(row.rowIndex, cellspanIndex, row, cell, cellHasRowspan, true, true); } } }
Recover info about row and cell and add information to virtual table. @param {object} row Row to recover information. @param {object} cell Cell to recover information.
addCellInfoToVirtual
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
function adjustStartPoint(rowIndex, cellIndex, cell, isSelectedCell) { if (rowIndex === _startPoint.rowPos && _startPoint.colPos >= cell.cellIndex && cell.cellIndex <= cellIndex && !isSelectedCell) { _startPoint.colPos++; } }
Process validation and adjust of start point if needed @param {int} rowIndex @param {int} cellIndex @param {object} cell @param {bool} isSelectedCell
adjustStartPoint
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
function createVirtualTable() { const rows = domTable.rows; for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) { const cells = rows[rowIndex].cells; for (let cellIndex = 0; cellIndex < cells.length; cellIndex++) { addCellInfoToVirtual(rows[rowIndex], cells[cellIndex]); } } }
Create virtual table of cells with all cells, including span cells.
createVirtualTable
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
function getDeleteResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; case TableResultAction.where.Row: if (!cell.isVirtual && cell.isRowSpan) { return TableResultAction.resultAction.AddCell; } else if (cell.isRowSpan) { return TableResultAction.resultAction.SubtractSpanCount; } break; } return TableResultAction.resultAction.RemoveCell; }
Get action to be applied on the cell. @param {object} cell virtual table cell to apply action
getDeleteResultActionToCell
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
function getAddResultActionToCell(cell) { switch (where) { case TableResultAction.where.Column: if (cell.isColSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isRowSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; case TableResultAction.where.Row: if (cell.isRowSpan) { return TableResultAction.resultAction.SumSpanCount; } else if (cell.isColSpan && cell.isVirtual) { return TableResultAction.resultAction.Ignore; } break; } return TableResultAction.resultAction.AddCell; }
Get action to be applied on the cell. @param {object} cell virtual table cell to apply action
getAddResultActionToCell
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
function init() { setStartPoint(); createVirtualTable(); }
Get action to be applied on the cell. @param {object} cell virtual table cell to apply action
init
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
tab(rng, isShift) { const cell = dom.ancestor(rng.commonAncestor(), dom.isCell); const table = dom.ancestor(cell, dom.isTable); const cells = dom.listDescendant(table, dom.isCell); const nextCell = lists[isShift ? 'prev' : 'next'](cells, cell); if (nextCell) { range.create(nextCell, 0).select(); } }
handle tab key @param {WrappedRange} rng @param {Boolean} isShift
tab
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
addRow(rng, position) { const cell = dom.ancestor(rng.commonAncestor(), dom.isCell); const currentTr = $(cell).closest('tr'); const trAttributes = this.recoverAttributes(currentTr); const html = $('<tr' + trAttributes + '></tr>'); const vTable = new TableResultAction(cell, TableResultAction.where.Row, TableResultAction.requestAction.Add, $(currentTr).closest('table')[0]); const actions = vTable.getActionList(); for (let idCell = 0; idCell < actions.length; idCell++) { const currentCell = actions[idCell]; const tdAttributes = this.recoverAttributes(currentCell.baseCell); switch (currentCell.action) { case TableResultAction.resultAction.AddCell: html.append('<td' + tdAttributes + '>' + dom.blank + '</td>'); break; case TableResultAction.resultAction.SumSpanCount: { if (position === 'top') { const baseCellTr = currentCell.baseCell.parent; const isTopFromRowSpan = (!baseCellTr ? 0 : currentCell.baseCell.closest('tr').rowIndex) <= currentTr[0].rowIndex; if (isTopFromRowSpan) { const newTd = $('<div></div>').append($('<td' + tdAttributes + '>' + dom.blank + '</td>').removeAttr('rowspan')).html(); html.append(newTd); break; } } let rowspanNumber = parseInt(currentCell.baseCell.rowSpan, 10); rowspanNumber++; currentCell.baseCell.setAttribute('rowSpan', rowspanNumber); } break; } } if (position === 'top') { currentTr.before(html); } else { const cellHasRowspan = (cell.rowSpan > 1); if (cellHasRowspan) { const lastTrIndex = currentTr[0].rowIndex + (cell.rowSpan - 2); $($(currentTr).parent().find('tr')[lastTrIndex]).after($(html)); return; } currentTr.after(html); } }
Add a new row @param {WrappedRange} rng @param {String} position (top/bottom) @return {Node}
addRow
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
addCol(rng, position) { const cell = dom.ancestor(rng.commonAncestor(), dom.isCell); const row = $(cell).closest('tr'); const rowsGroup = $(row).siblings(); rowsGroup.push(row); const vTable = new TableResultAction(cell, TableResultAction.where.Column, TableResultAction.requestAction.Add, $(row).closest('table')[0]); const actions = vTable.getActionList(); for (let actionIndex = 0; actionIndex < actions.length; actionIndex++) { const currentCell = actions[actionIndex]; const tdAttributes = this.recoverAttributes(currentCell.baseCell); switch (currentCell.action) { case TableResultAction.resultAction.AddCell: if (position === 'right') { $(currentCell.baseCell).after('<td' + tdAttributes + '>' + dom.blank + '</td>'); } else { $(currentCell.baseCell).before('<td' + tdAttributes + '>' + dom.blank + '</td>'); } break; case TableResultAction.resultAction.SumSpanCount: if (position === 'right') { let colspanNumber = parseInt(currentCell.baseCell.colSpan, 10); colspanNumber++; currentCell.baseCell.setAttribute('colSpan', colspanNumber); } else { $(currentCell.baseCell).before('<td' + tdAttributes + '>' + dom.blank + '</td>'); } break; } } }
Add a new col @param {WrappedRange} rng @param {String} position (left/right) @return {Node}
addCol
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
recoverAttributes(el) { let resultStr = ''; if (!el) { return resultStr; } const attrList = el.attributes || []; for (let i = 0; i < attrList.length; i++) { if (attrList[i].name.toLowerCase() === 'id') { continue; } if (attrList[i].specified) { resultStr += ' ' + attrList[i].name + '=\'' + attrList[i].value + '\''; } } return resultStr; }
Add a new col @param {WrappedRange} rng @param {String} position (left/right) @return {Node}
recoverAttributes
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
deleteRow(rng) { const cell = dom.ancestor(rng.commonAncestor(), dom.isCell); const row = $(cell).closest('tr'); const cellPos = row.children('td, th').index($(cell)); const rowPos = row[0].rowIndex; const vTable = new TableResultAction(cell, TableResultAction.where.Row, TableResultAction.requestAction.Delete, $(row).closest('table')[0]); const actions = vTable.getActionList(); for (let actionIndex = 0; actionIndex < actions.length; actionIndex++) { if (!actions[actionIndex]) { continue; } const baseCell = actions[actionIndex].baseCell; const virtualPosition = actions[actionIndex].virtualTable; const hasRowspan = (baseCell.rowSpan && baseCell.rowSpan > 1); let rowspanNumber = (hasRowspan) ? parseInt(baseCell.rowSpan, 10) : 0; switch (actions[actionIndex].action) { case TableResultAction.resultAction.Ignore: continue; case TableResultAction.resultAction.AddCell: { const nextRow = row.next('tr')[0]; if (!nextRow) { continue; } const cloneRow = row[0].cells[cellPos]; if (hasRowspan) { if (rowspanNumber > 2) { rowspanNumber--; nextRow.insertBefore(cloneRow, nextRow.cells[cellPos]); nextRow.cells[cellPos].setAttribute('rowSpan', rowspanNumber); nextRow.cells[cellPos].innerHTML = ''; } else if (rowspanNumber === 2) { nextRow.insertBefore(cloneRow, nextRow.cells[cellPos]); nextRow.cells[cellPos].removeAttribute('rowSpan'); nextRow.cells[cellPos].innerHTML = ''; } } } continue; case TableResultAction.resultAction.SubtractSpanCount: if (hasRowspan) { if (rowspanNumber > 2) { rowspanNumber--; baseCell.setAttribute('rowSpan', rowspanNumber); if (virtualPosition.rowIndex !== rowPos && baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } else if (rowspanNumber === 2) { baseCell.removeAttribute('rowSpan'); if (virtualPosition.rowIndex !== rowPos && baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } } continue; case TableResultAction.resultAction.RemoveCell: // Do not need remove cell because row will be deleted. continue; } } row.remove(); }
Delete current row @param {WrappedRange} rng @return {Node}
deleteRow
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
deleteCol(rng) { const cell = dom.ancestor(rng.commonAncestor(), dom.isCell); const row = $(cell).closest('tr'); const cellPos = row.children('td, th').index($(cell)); const vTable = new TableResultAction(cell, TableResultAction.where.Column, TableResultAction.requestAction.Delete, $(row).closest('table')[0]); const actions = vTable.getActionList(); for (let actionIndex = 0; actionIndex < actions.length; actionIndex++) { if (!actions[actionIndex]) { continue; } switch (actions[actionIndex].action) { case TableResultAction.resultAction.Ignore: continue; case TableResultAction.resultAction.SubtractSpanCount: { const baseCell = actions[actionIndex].baseCell; const hasColspan = (baseCell.colSpan && baseCell.colSpan > 1); if (hasColspan) { let colspanNumber = (baseCell.colSpan) ? parseInt(baseCell.colSpan, 10) : 0; if (colspanNumber > 2) { colspanNumber--; baseCell.setAttribute('colSpan', colspanNumber); if (baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } else if (colspanNumber === 2) { baseCell.removeAttribute('colSpan'); if (baseCell.cellIndex === cellPos) { baseCell.innerHTML = ''; } } } } continue; case TableResultAction.resultAction.RemoveCell: dom.remove(actions[actionIndex].baseCell, true); continue; } } }
Delete current col @param {WrappedRange} rng @return {Node}
deleteCol
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
createTable(colCount, rowCount, options) { const tds = []; let tdHTML; for (let idxCol = 0; idxCol < colCount; idxCol++) { tds.push('<td>' + dom.blank + '</td>'); } tdHTML = tds.join(''); const trs = []; let trHTML; for (let idxRow = 0; idxRow < rowCount; idxRow++) { trs.push('<tr>' + tdHTML + '</tr>'); } trHTML = trs.join(''); const $table = $('<table>' + trHTML + '</table>'); if (options && options.tableClassName) { $table.addClass(options.tableClassName); } return $table[0]; }
create empty table element @param {Number} rowCount @param {Number} colCount @return {Node}
createTable
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
deleteTable(rng) { const cell = dom.ancestor(rng.commonAncestor(), dom.isCell); $(cell).closest('table').remove(); }
Delete current table @param {WrappedRange} rng @return {Node}
deleteTable
javascript
summernote/summernote
src/js/editing/Table.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Table.js
MIT
insertTab(rng, tabsize) { const tab = dom.createText(new Array(tabsize + 1).join(dom.NBSP_CHAR)); rng = rng.deleteContents(); rng.insertNode(tab, true); rng = range.create(tab, tabsize); rng.select(); }
insert tab @param {WrappedRange} rng @param {Number} tabsize
insertTab
javascript
summernote/summernote
src/js/editing/Typing.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Typing.js
MIT
insertParagraph(editable, rng) { rng = rng || range.create(editable); // deleteContents on range. rng = rng.deleteContents(); // Wrap range if it needs to be wrapped by paragraph rng = rng.wrapBodyInlineWithPara(); // finding paragraph const splitRoot = dom.ancestor(rng.sc, dom.isPara); let nextPara; // on paragraph: split paragraph if (splitRoot) { // if it is an empty line with li if (dom.isLi(splitRoot) && (dom.isEmpty(splitRoot) || dom.deepestChildIsEmpty(splitRoot))) { // toggle UL/OL and escape this.bullet.toggleList(splitRoot.parentNode.nodeName); return; } else { let blockquote = null; if (this.options.blockquoteBreakingLevel === 1) { blockquote = dom.ancestor(splitRoot, dom.isBlockquote); } else if (this.options.blockquoteBreakingLevel === 2) { blockquote = dom.lastAncestor(splitRoot, dom.isBlockquote); } if (blockquote) { // We're inside a blockquote and options ask us to break it nextPara = $(dom.emptyPara)[0]; // If the split is right before a <br>, remove it so that there's no "empty line" // after the split in the new blockquote created if (dom.isRightEdgePoint(rng.getStartPoint()) && dom.isBR(rng.sc.nextSibling)) { $(rng.sc.nextSibling).remove(); } const split = dom.splitTree(blockquote, rng.getStartPoint(), { isDiscardEmptySplits: true }); if (split) { split.parentNode.insertBefore(nextPara, split); } else { dom.insertAfter(nextPara, blockquote); // There's no split if we were at the end of the blockquote } } else { nextPara = dom.splitTree(splitRoot, rng.getStartPoint()); // not a blockquote, just insert the paragraph let emptyAnchors = dom.listDescendant(splitRoot, dom.isEmptyAnchor); emptyAnchors = emptyAnchors.concat(dom.listDescendant(nextPara, dom.isEmptyAnchor)); $.each(emptyAnchors, (idx, anchor) => { dom.remove(anchor); }); // replace empty heading, pre or custom-made styleTag with P tag if ((dom.isHeading(nextPara) || dom.isPre(nextPara) || dom.isCustomStyleTag(nextPara)) && dom.isEmpty(nextPara)) { nextPara = dom.replace(nextPara, 'p'); } } } // no paragraph: insert empty paragraph } else { const next = rng.sc.childNodes[rng.so]; nextPara = $(dom.emptyPara)[0]; if (next) { rng.sc.insertBefore(nextPara, next); } else { rng.sc.appendChild(nextPara); } } range.create(nextPara, 0).normalize().select().scrollIntoView(editable); }
insert paragraph @param {jQuery} $editable @param {WrappedRange} rng Can be used in unit tests to "mock" the range blockquoteBreakingLevel 0 - No break, the new paragraph remains inside the quote 1 - Break the first blockquote in the ancestors list 2 - Break all blockquotes, so that the new paragraph is not quoted (this is the default)
insertParagraph
javascript
summernote/summernote
src/js/editing/Typing.js
https://github.com/summernote/summernote/blob/master/src/js/editing/Typing.js
MIT
addImagePopoverButtons() { // Image Size Buttons this.context.memo('button.resizeFull', () => { return this.button({ contents: '<span class="note-fontsize-10">100%</span>', tooltip: this.lang.image.resizeFull, click: this.context.createInvokeHandler('editor.resize', '1'), }).render(); }); this.context.memo('button.resizeHalf', () => { return this.button({ contents: '<span class="note-fontsize-10">50%</span>', tooltip: this.lang.image.resizeHalf, click: this.context.createInvokeHandler('editor.resize', '0.5'), }).render(); }); this.context.memo('button.resizeQuarter', () => { return this.button({ contents: '<span class="note-fontsize-10">25%</span>', tooltip: this.lang.image.resizeQuarter, click: this.context.createInvokeHandler('editor.resize', '0.25'), }).render(); }); this.context.memo('button.resizeNone', () => { return this.button({ contents: this.ui.icon(this.options.icons.rollback), tooltip: this.lang.image.resizeNone, click: this.context.createInvokeHandler('editor.resize', '0'), }).render(); }); // Float Buttons this.context.memo('button.floatLeft', () => { return this.button({ contents: this.ui.icon(this.options.icons.floatLeft), tooltip: this.lang.image.floatLeft, click: this.context.createInvokeHandler('editor.floatMe', 'left'), }).render(); }); this.context.memo('button.floatRight', () => { return this.button({ contents: this.ui.icon(this.options.icons.floatRight), tooltip: this.lang.image.floatRight, click: this.context.createInvokeHandler('editor.floatMe', 'right'), }).render(); }); this.context.memo('button.floatNone', () => { return this.button({ contents: this.ui.icon(this.options.icons.rollback), tooltip: this.lang.image.floatNone, click: this.context.createInvokeHandler('editor.floatMe', 'none'), }).render(); }); // Remove Buttons this.context.memo('button.removeMedia', () => { return this.button({ contents: this.ui.icon(this.options.icons.trash), tooltip: this.lang.image.remove, click: this.context.createInvokeHandler('editor.removeMedia'), }).render(); }); }
image: [ ['imageResize', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']], ['float', ['floatLeft', 'floatRight', 'floatNone']], ['remove', ['removeMedia']], ],
addImagePopoverButtons
javascript
summernote/summernote
src/js/module/Buttons.js
https://github.com/summernote/summernote/blob/master/src/js/module/Buttons.js
MIT
addLinkPopoverButtons() { this.context.memo('button.linkDialogShow', () => { return this.button({ contents: this.ui.icon(this.options.icons.link), tooltip: this.lang.link.edit, click: this.context.createInvokeHandler('linkDialog.show'), }).render(); }); this.context.memo('button.unlink', () => { return this.button({ contents: this.ui.icon(this.options.icons.unlink), tooltip: this.lang.link.unlink, click: this.context.createInvokeHandler('editor.unlink'), }).render(); }); }
image: [ ['imageResize', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']], ['float', ['floatLeft', 'floatRight', 'floatNone']], ['remove', ['removeMedia']], ],
addLinkPopoverButtons
javascript
summernote/summernote
src/js/module/Buttons.js
https://github.com/summernote/summernote/blob/master/src/js/module/Buttons.js
MIT
addTablePopoverButtons() { this.context.memo('button.addRowUp', () => { return this.button({ className: 'btn-md', contents: this.ui.icon(this.options.icons.rowAbove), tooltip: this.lang.table.addRowAbove, click: this.context.createInvokeHandler('editor.addRow', 'top'), }).render(); }); this.context.memo('button.addRowDown', () => { return this.button({ className: 'btn-md', contents: this.ui.icon(this.options.icons.rowBelow), tooltip: this.lang.table.addRowBelow, click: this.context.createInvokeHandler('editor.addRow', 'bottom'), }).render(); }); this.context.memo('button.addColLeft', () => { return this.button({ className: 'btn-md', contents: this.ui.icon(this.options.icons.colBefore), tooltip: this.lang.table.addColLeft, click: this.context.createInvokeHandler('editor.addCol', 'left'), }).render(); }); this.context.memo('button.addColRight', () => { return this.button({ className: 'btn-md', contents: this.ui.icon(this.options.icons.colAfter), tooltip: this.lang.table.addColRight, click: this.context.createInvokeHandler('editor.addCol', 'right'), }).render(); }); this.context.memo('button.deleteRow', () => { return this.button({ className: 'btn-md', contents: this.ui.icon(this.options.icons.rowRemove), tooltip: this.lang.table.delRow, click: this.context.createInvokeHandler('editor.deleteRow'), }).render(); }); this.context.memo('button.deleteCol', () => { return this.button({ className: 'btn-md', contents: this.ui.icon(this.options.icons.colRemove), tooltip: this.lang.table.delCol, click: this.context.createInvokeHandler('editor.deleteCol'), }).render(); }); this.context.memo('button.deleteTable', () => { return this.button({ className: 'btn-md', contents: this.ui.icon(this.options.icons.trash), tooltip: this.lang.table.delTable, click: this.context.createInvokeHandler('editor.deleteTable'), }).render(); }); }
table : [ ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']], ['delete', ['deleteRow', 'deleteCol', 'deleteTable']] ],
addTablePopoverButtons
javascript
summernote/summernote
src/js/module/Buttons.js
https://github.com/summernote/summernote/blob/master/src/js/module/Buttons.js
MIT
build($container, groups) { for (let groupIdx = 0, groupLen = groups.length; groupIdx < groupLen; groupIdx++) { const group = groups[groupIdx]; const groupName = Array.isArray(group) ? group[0] : group; const buttons = Array.isArray(group) ? ((group.length === 1) ? [group[0]] : group[1]) : [group]; const $group = this.ui.buttonGroup({ className: 'note-' + groupName, }).render(); for (let idx = 0, len = buttons.length; idx < len; idx++) { const btn = this.context.memo('button.' + buttons[idx]); if (btn) { $group.append(typeof btn === 'function' ? btn(this.context) : btn); } } $group.appendTo($container); } }
table : [ ['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']], ['delete', ['deleteRow', 'deleteCol', 'deleteTable']] ],
build
javascript
summernote/summernote
src/js/module/Buttons.js
https://github.com/summernote/summernote/blob/master/src/js/module/Buttons.js
MIT
pasteByEvent(event) { if (this.context.isDisabled()) { return; } const clipboardData = event.originalEvent.clipboardData; if (clipboardData && clipboardData.items && clipboardData.items.length) { const clipboardFiles = clipboardData.files; const clipboardText = clipboardData.getData('Text'); // paste img file if (clipboardFiles.length > 0 && this.options.allowClipboardImagePasting) { this.context.invoke('editor.insertImagesOrCallback', clipboardFiles); event.preventDefault(); } // paste text with maxTextLength check if (clipboardText.length > 0 && this.context.invoke('editor.isLimited', clipboardText.length)) { event.preventDefault(); } } else if (window.clipboardData) { // for IE let text = window.clipboardData.getData('text'); if (this.context.invoke('editor.isLimited', text.length)) { event.preventDefault(); } } // Call editor.afterCommand after proceeding default event handler setTimeout(() => { this.context.invoke('editor.afterCommand'); }, 10); }
paste by clipboard event @param {Event} event
pasteByEvent
javascript
summernote/summernote
src/js/module/Clipboard.js
https://github.com/summernote/summernote/blob/master/src/js/module/Clipboard.js
MIT
purify(value) { if (this.options.codeviewFilter) { // filter code view regex value = value.replace(this.options.codeviewFilterRegex, ''); // allow specific iframe tag if (this.options.codeviewIframeFilter) { const whitelist = this.options.codeviewIframeWhitelistSrc.concat(this.options.codeviewIframeWhitelistSrcBase); value = value.replace(/(<iframe.*?>.*?(?:<\/iframe>)?)/gi, function(tag) { // remove if src attribute is duplicated if (/<.+src(?==?('|"|\s)?)[\s\S]+src(?=('|"|\s)?)[^>]*?>/i.test(tag)) { return ''; } for (const src of whitelist) { // pass if src is trusted if ((new RegExp('src="(https?:)?\/\/' + src.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '\/(.+)"')).test(tag)) { return tag; } } return ''; }); } } return value; }
purify input value @param value @returns {*}
purify
javascript
summernote/summernote
src/js/module/Codeview.js
https://github.com/summernote/summernote/blob/master/src/js/module/Codeview.js
MIT
initialize() { // bind custom events this.$editable.on('keydown', (event) => { if (event.keyCode === key.code.ENTER) { this.context.triggerEvent('enter', event); } this.context.triggerEvent('keydown', event); // keep a snapshot to limit text on input event this.snapshot = this.history.makeSnapshot(); this.hasKeyShortCut = false; if (!event.isDefaultPrevented()) { if (this.options.shortcuts) { this.hasKeyShortCut = this.handleKeyMap(event); } else { this.preventDefaultEditableShortCuts(event); } } if (this.isLimited(1, event)) { const lastRange = this.getLastRange(); if (lastRange.eo - lastRange.so === 0) { return false; } } this.setLastRange(); // record undo in the key event except keyMap. if (this.options.recordEveryKeystroke) { if (this.hasKeyShortCut === false) { this.history.recordUndo(); } } }).on('keyup', (event) => { this.setLastRange(); this.context.triggerEvent('keyup', event); }).on('focus', (event) => { this.setLastRange(); this.context.triggerEvent('focus', event); }).on('blur', (event) => { this.context.triggerEvent('blur', event); }).on('mousedown', (event) => { this.context.triggerEvent('mousedown', event); }).on('mouseup', (event) => { this.setLastRange(); this.history.recordUndo(); this.context.triggerEvent('mouseup', event); }).on('scroll', (event) => { this.context.triggerEvent('scroll', event); }).on('paste', (event) => { this.setLastRange(); this.context.triggerEvent('paste', event); }).on('copy', (event) => { this.context.triggerEvent('copy', event); }).on('input', () => { // To limit composition characters (e.g. Korean) if (this.isLimited(0) && this.snapshot) { this.history.applySnapshot(this.snapshot); } }); this.$editable.attr('spellcheck', this.options.spellCheck); this.$editable.attr('autocorrect', this.options.spellCheck); if (this.options.disableGrammar) { this.$editable.attr('data-gramm', false); } // init content before set event this.$editable.html(dom.html(this.$note) || dom.emptyPara); this.$editable.on(env.inputEventName, func.debounce(() => { this.context.triggerEvent('change', this.$editable.html(), this.$editable); }, 10)); this.$editable.on('focusin', (event) => { this.context.triggerEvent('focusin', event); }).on('focusout', (event) => { this.context.triggerEvent('focusout', event); }); if (this.options.airMode) { if (this.options.overrideContextMenu) { this.$editor.on('contextmenu', (event) => { this.context.triggerEvent('contextmenu', event); return false; }); } } else { if (this.options.width) { this.$editor.outerWidth(this.options.width); } if (this.options.height) { this.$editable.outerHeight(this.options.height); } if (this.options.maxHeight) { this.$editable.css('max-height', this.options.maxHeight); } if (this.options.minHeight) { this.$editable.css('min-height', this.options.minHeight); } } this.history.recordUndo(); this.setLastRange(); }
resize overlay element @param {String} value
initialize
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
handleKeyMap(event) { const keyMap = this.options.keyMap[env.isMac ? 'mac' : 'pc']; const keys = []; if (event.metaKey) { keys.push('CMD'); } if (event.ctrlKey && !event.altKey) { keys.push('CTRL'); } if (event.shiftKey) { keys.push('SHIFT'); } const keyName = key.nameFromCode[event.keyCode]; if (keyName) { keys.push(keyName); } const eventName = keyMap[keys.join('+')]; if (keyName === 'TAB' && !this.options.tabDisable) { this.afterCommand(); } else if (eventName) { if (this.context.invoke(eventName) !== false) { event.preventDefault(); return true; } } else if (key.isEdit(event.keyCode)) { if (key.isRemove(event.keyCode)) { this.context.invoke('removed'); } this.afterCommand(); } return false; }
resize overlay element @param {String} value
handleKeyMap
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
preventDefaultEditableShortCuts(event) { // B(Bold, 66) / I(Italic, 73) / U(Underline, 85) if ((event.ctrlKey || event.metaKey) && lists.contains([66, 73, 85], event.keyCode)) { event.preventDefault(); } }
resize overlay element @param {String} value
preventDefaultEditableShortCuts
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
isLimited(pad, event) { pad = pad || 0; if (typeof event !== 'undefined') { if (key.isMove(event.keyCode) || key.isNavigation(event.keyCode) || (event.ctrlKey || event.metaKey) || lists.contains([key.code.BACKSPACE, key.code.DELETE], event.keyCode)) { return false; } } if (this.options.maxTextLength > 0) { if ((this.$editable.text().length + pad) > this.options.maxTextLength) { return true; } } return false; }
resize overlay element @param {String} value
isLimited
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
checkLinkUrl(linkUrl) { if (MAILTO_PATTERN.test(linkUrl)) { return 'mailto://' + linkUrl; } else if (TEL_PATTERN.test(linkUrl)) { return 'tel://' + linkUrl; } else if (!URL_SCHEME_PATTERN.test(linkUrl)) { return 'http://' + linkUrl; } return linkUrl; }
resize overlay element @param {String} value
checkLinkUrl
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
createRangeFromList(lst) { const startRange = range.createFromNodeBefore(lists.head(lst)); const startPoint = startRange.getStartPoint(); const endRange = range.createFromNodeAfter(lists.last(lst)); const endPoint = endRange.getEndPoint(); return range.create( startPoint.node, startPoint.offset, endPoint.node, endPoint.offset ); }
create a new range from the list of elements @param {list} dom element list @return {WrappedRange}
createRangeFromList
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
setLastRange(rng) { if (rng) { this.lastRange = rng; } else { this.lastRange = range.create(this.editable); if ($(this.lastRange.sc).closest('.note-editable').length === 0) { this.lastRange = range.createFromBodyElement(this.editable); } } }
set the last range if given rng is exist, set rng as the last range or create a new range at the end of the document @param {WrappedRange} rng
setLastRange
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
getLastRange() { if (!this.lastRange) { this.setLastRange(); } return this.lastRange; }
get the last range if there is a saved last range, return it or create a new range and return it @return {WrappedRange}
getLastRange
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
saveRange(thenCollapse) { if (thenCollapse) { this.getLastRange().collapse().select(); } }
saveRange save current range @param {Boolean} [thenCollapse=false]
saveRange
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
currentStyle() { let rng = range.create(); if (rng) { rng = rng.normalize(); } return rng ? this.style.current(rng) : this.style.fromNode(this.$editable); }
currentStyle current style @return {Object|Boolean} unfocus
currentStyle
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
styleFromNode($node) { return this.style.fromNode($node); }
style from node @param {jQuery} $node @return {Object}
styleFromNode
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
wrapCommand(fn) { return function() { this.beforeCommand(); fn.apply(this, arguments); this.afterCommand(); }; }
run given function between beforeCommand and afterCommand
wrapCommand
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
insertImage(src, param) { return createImage(src, param).then(($image) => { this.beforeCommand(); if (typeof param === 'function') { param($image); } else { if (typeof param === 'string') { $image.attr('data-filename', param); } $image.css('width', Math.min(this.$editable.width(), $image.width())); } $image.show(); this.getLastRange().insertNode($image[0]); this.setLastRange(range.createFromNodeAfter($image[0]).select()); this.afterCommand(); }).fail((e) => { this.context.triggerEvent('image.upload.error', e); }); }
insert image @param {String} src @param {String|Function} param @return {Promise}
insertImage
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
getSelectedText() { let rng = this.getLastRange(); // if range on anchor, expand range with anchor if (rng.isOnAnchor()) { rng = range.createFromNode(dom.ancestor(rng.sc, dom.isAnchor)); } return rng.toString(); }
return selected plain text @return {String} text
getSelectedText
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
onFormatBlock(tagName, $target) { // [workaround] for MSIE, IE need `<` document.execCommand('FormatBlock', false, env.isMSIE ? '<' + tagName + '>' : tagName); // support custom class if ($target && $target.length) { // find the exact element has given tagName if ($target[0].tagName.toUpperCase() !== tagName.toUpperCase()) { $target = $target.find(tagName); } if ($target && $target.length) { const currentRange = this.createRange(); const $parent = $([currentRange.sc, currentRange.ec]).closest(tagName); // remove class added for current block $parent.removeClass(); const className = $target[0].className || ''; if (className) { $parent.addClass(className); } } } }
return selected plain text @return {String} text
onFormatBlock
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
fontStyling(target, value) { const rng = this.getLastRange(); if (rng !== '') { const spans = this.style.styleNodes(rng); this.$editor.find('.note-status-output').html(''); $(spans).css(target, value); // [workaround] added styled bogus span for style // - also bogus character needed for cursor position if (rng.isCollapsed()) { const firstSpan = lists.head(spans); if (firstSpan && !dom.nodeLength(firstSpan)) { firstSpan.innerHTML = dom.ZERO_WIDTH_NBSP_CHAR; range.createFromNode(firstSpan.firstChild).select(); this.setLastRange(); this.$editable.data(KEY_BOGUS, firstSpan); } } else { rng.select(); } } else { const noteStatusOutput = $.now(); this.$editor.find('.note-status-output').html('<div id="note-status-output-' + noteStatusOutput + '" class="alert alert-info">' + this.lang.output.noSelection + '</div>'); setTimeout(function() { $('#note-status-output-' + noteStatusOutput).remove(); }, 5000); } }
return selected plain text @return {String} text
fontStyling
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT
getLinkInfo() { if (!this.hasFocus()) { this.focus(); } const rng = this.getLastRange().expand(dom.isAnchor); // Get the first anchor on range(for edit). const $anchor = $(lists.head(rng.nodes(dom.isAnchor))); const linkInfo = { range: rng, text: rng.toString(), url: $anchor.length ? $anchor.attr('href') : '', }; // When anchor exists, if ($anchor.length) { // Set isNewWindow by checking its target. linkInfo.isNewWindow = $anchor.attr('target') === '_blank'; } return linkInfo; }
returns link info @return {Object} @return {WrappedRange} return.range @return {String} return.text @return {Boolean} [return.isNewWindow=true] @return {String} [return.url=""]
getLinkInfo
javascript
summernote/summernote
src/js/module/Editor.js
https://github.com/summernote/summernote/blob/master/src/js/module/Editor.js
MIT