repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
nhn/tui.editor
src/js/extensions/table/table.js
_changeHtml
function _changeHtml(html, onChangeTable) { const $tempDiv = $(`<div>${html}</div>`); const $tables = $tempDiv.find('table'); if ($tables.length) { $tables.get().forEach(tableElement => { const changedTableElement = onChangeTable(tableElement); $(tableElement).replaceWith(changedTableElement); }); html = $tempDiv.html(); } return html; }
javascript
function _changeHtml(html, onChangeTable) { const $tempDiv = $(`<div>${html}</div>`); const $tables = $tempDiv.find('table'); if ($tables.length) { $tables.get().forEach(tableElement => { const changedTableElement = onChangeTable(tableElement); $(tableElement).replaceWith(changedTableElement); }); html = $tempDiv.html(); } return html; }
[ "function", "_changeHtml", "(", "html", ",", "onChangeTable", ")", "{", "const", "$tempDiv", "=", "$", "(", "`", "${", "html", "}", "`", ")", ";", "const", "$tables", "=", "$tempDiv", ".", "find", "(", "'table'", ")", ";", "if", "(", "$tables", ".", "length", ")", "{", "$tables", ".", "get", "(", ")", ".", "forEach", "(", "tableElement", "=>", "{", "const", "changedTableElement", "=", "onChangeTable", "(", "tableElement", ")", ";", "$", "(", "tableElement", ")", ".", "replaceWith", "(", "changedTableElement", ")", ";", "}", ")", ";", "html", "=", "$tempDiv", ".", "html", "(", ")", ";", "}", "return", "html", ";", "}" ]
Change html by onChangeTable function. @param {string} html - original html @param {function} onChangeTable - function for changing html @returns {string} @private
[ "Change", "html", "by", "onChangeTable", "function", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/table.js#L80-L95
train
nhn/tui.editor
src/js/extensions/table/table.js
_snatchWysiwygCommand
function _snatchWysiwygCommand(commandWrapper) { const {command} = commandWrapper; if (!command.isWWType()) { return; } switch (command.getName()) { case 'AddRow': commandWrapper.command = wwAddRow; break; case 'AddCol': commandWrapper.command = wwAddCol; break; case 'RemoveRow': commandWrapper.command = wwRemoveRow; break; case 'RemoveCol': commandWrapper.command = wwRemoveCol; break; case 'AlignCol': commandWrapper.command = wwAlignCol; break; default: } }
javascript
function _snatchWysiwygCommand(commandWrapper) { const {command} = commandWrapper; if (!command.isWWType()) { return; } switch (command.getName()) { case 'AddRow': commandWrapper.command = wwAddRow; break; case 'AddCol': commandWrapper.command = wwAddCol; break; case 'RemoveRow': commandWrapper.command = wwRemoveRow; break; case 'RemoveCol': commandWrapper.command = wwRemoveCol; break; case 'AlignCol': commandWrapper.command = wwAlignCol; break; default: } }
[ "function", "_snatchWysiwygCommand", "(", "commandWrapper", ")", "{", "const", "{", "command", "}", "=", "commandWrapper", ";", "if", "(", "!", "command", ".", "isWWType", "(", ")", ")", "{", "return", ";", "}", "switch", "(", "command", ".", "getName", "(", ")", ")", "{", "case", "'AddRow'", ":", "commandWrapper", ".", "command", "=", "wwAddRow", ";", "break", ";", "case", "'AddCol'", ":", "commandWrapper", ".", "command", "=", "wwAddCol", ";", "break", ";", "case", "'RemoveRow'", ":", "commandWrapper", ".", "command", "=", "wwRemoveRow", ";", "break", ";", "case", "'RemoveCol'", ":", "commandWrapper", ".", "command", "=", "wwRemoveCol", ";", "break", ";", "case", "'AlignCol'", ":", "commandWrapper", ".", "command", "=", "wwAlignCol", ";", "break", ";", "default", ":", "}", "}" ]
Snatch wysiwyg command. @param {{command: object}} commandWrapper - wysiwyg command wrapper @private
[ "Snatch", "wysiwyg", "command", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/table.js#L102-L127
train
nhn/tui.editor
src/js/extensions/table/table.js
_bindEvents
function _bindEvents(eventManager) { eventManager.listen('convertorAfterMarkdownToHtmlConverted', html => _changeHtml(html, createMergedTable)); eventManager.listen('convertorBeforeHtmlToMarkdownConverted', html => _changeHtml(html, prepareTableUnmerge)); eventManager.listen('addCommandBefore', _snatchWysiwygCommand); }
javascript
function _bindEvents(eventManager) { eventManager.listen('convertorAfterMarkdownToHtmlConverted', html => _changeHtml(html, createMergedTable)); eventManager.listen('convertorBeforeHtmlToMarkdownConverted', html => _changeHtml(html, prepareTableUnmerge)); eventManager.listen('addCommandBefore', _snatchWysiwygCommand); }
[ "function", "_bindEvents", "(", "eventManager", ")", "{", "eventManager", ".", "listen", "(", "'convertorAfterMarkdownToHtmlConverted'", ",", "html", "=>", "_changeHtml", "(", "html", ",", "createMergedTable", ")", ")", ";", "eventManager", ".", "listen", "(", "'convertorBeforeHtmlToMarkdownConverted'", ",", "html", "=>", "_changeHtml", "(", "html", ",", "prepareTableUnmerge", ")", ")", ";", "eventManager", ".", "listen", "(", "'addCommandBefore'", ",", "_snatchWysiwygCommand", ")", ";", "}" ]
Bind events. @param {object} eventManager - eventManager instance @private
[ "Bind", "events", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/table.js#L134-L138
train
nhn/tui.editor
src/js/codemirror/continuelist.js
incrementRemainingMarkdownListNumbers
function incrementRemainingMarkdownListNumbers(cm, pos) { var startLine = pos.line, lookAhead = 0, skipCount = 0; var startItem = listRE.exec(cm.getLine(startLine)), startIndent = startItem[1]; do { lookAhead += 1; var nextLineNumber = startLine + lookAhead; var nextLine = cm.getLine(nextLineNumber), nextItem = listRE.exec(nextLine); if (nextItem) { var nextIndent = nextItem[1]; var newNumber = (parseInt(startItem[3], 10) + lookAhead - skipCount); var nextNumber = (parseInt(nextItem[3], 10)), itemNumber = nextNumber; if (startIndent === nextIndent && !isNaN(nextNumber)) { if (newNumber === nextNumber) itemNumber = nextNumber + 1; if (newNumber > nextNumber) itemNumber = newNumber + 1; cm.replaceRange( nextLine.replace(listRE, nextIndent + itemNumber + nextItem[4] + nextItem[5]), { line: nextLineNumber, ch: 0 }, { line: nextLineNumber, ch: nextLine.length }); } else { if (startIndent.length > nextIndent.length) return; // This doesn't run if the next line immediatley indents, as it is // not clear of the users intention (new indented item or same level) if ((startIndent.length < nextIndent.length) && (lookAhead === 1)) return; skipCount += 1; } } } while (nextItem); }
javascript
function incrementRemainingMarkdownListNumbers(cm, pos) { var startLine = pos.line, lookAhead = 0, skipCount = 0; var startItem = listRE.exec(cm.getLine(startLine)), startIndent = startItem[1]; do { lookAhead += 1; var nextLineNumber = startLine + lookAhead; var nextLine = cm.getLine(nextLineNumber), nextItem = listRE.exec(nextLine); if (nextItem) { var nextIndent = nextItem[1]; var newNumber = (parseInt(startItem[3], 10) + lookAhead - skipCount); var nextNumber = (parseInt(nextItem[3], 10)), itemNumber = nextNumber; if (startIndent === nextIndent && !isNaN(nextNumber)) { if (newNumber === nextNumber) itemNumber = nextNumber + 1; if (newNumber > nextNumber) itemNumber = newNumber + 1; cm.replaceRange( nextLine.replace(listRE, nextIndent + itemNumber + nextItem[4] + nextItem[5]), { line: nextLineNumber, ch: 0 }, { line: nextLineNumber, ch: nextLine.length }); } else { if (startIndent.length > nextIndent.length) return; // This doesn't run if the next line immediatley indents, as it is // not clear of the users intention (new indented item or same level) if ((startIndent.length < nextIndent.length) && (lookAhead === 1)) return; skipCount += 1; } } } while (nextItem); }
[ "function", "incrementRemainingMarkdownListNumbers", "(", "cm", ",", "pos", ")", "{", "var", "startLine", "=", "pos", ".", "line", ",", "lookAhead", "=", "0", ",", "skipCount", "=", "0", ";", "var", "startItem", "=", "listRE", ".", "exec", "(", "cm", ".", "getLine", "(", "startLine", ")", ")", ",", "startIndent", "=", "startItem", "[", "1", "]", ";", "do", "{", "lookAhead", "+=", "1", ";", "var", "nextLineNumber", "=", "startLine", "+", "lookAhead", ";", "var", "nextLine", "=", "cm", ".", "getLine", "(", "nextLineNumber", ")", ",", "nextItem", "=", "listRE", ".", "exec", "(", "nextLine", ")", ";", "if", "(", "nextItem", ")", "{", "var", "nextIndent", "=", "nextItem", "[", "1", "]", ";", "var", "newNumber", "=", "(", "parseInt", "(", "startItem", "[", "3", "]", ",", "10", ")", "+", "lookAhead", "-", "skipCount", ")", ";", "var", "nextNumber", "=", "(", "parseInt", "(", "nextItem", "[", "3", "]", ",", "10", ")", ")", ",", "itemNumber", "=", "nextNumber", ";", "if", "(", "startIndent", "===", "nextIndent", "&&", "!", "isNaN", "(", "nextNumber", ")", ")", "{", "if", "(", "newNumber", "===", "nextNumber", ")", "itemNumber", "=", "nextNumber", "+", "1", ";", "if", "(", "newNumber", ">", "nextNumber", ")", "itemNumber", "=", "newNumber", "+", "1", ";", "cm", ".", "replaceRange", "(", "nextLine", ".", "replace", "(", "listRE", ",", "nextIndent", "+", "itemNumber", "+", "nextItem", "[", "4", "]", "+", "nextItem", "[", "5", "]", ")", ",", "{", "line", ":", "nextLineNumber", ",", "ch", ":", "0", "}", ",", "{", "line", ":", "nextLineNumber", ",", "ch", ":", "nextLine", ".", "length", "}", ")", ";", "}", "else", "{", "if", "(", "startIndent", ".", "length", ">", "nextIndent", ".", "length", ")", "return", ";", "if", "(", "(", "startIndent", ".", "length", "<", "nextIndent", ".", "length", ")", "&&", "(", "lookAhead", "===", "1", ")", ")", "return", ";", "skipCount", "+=", "1", ";", "}", "}", "}", "while", "(", "nextItem", ")", ";", "}" ]
Auto-updating Markdown list numbers when a new item is added to the middle of a list
[ "Auto", "-", "updating", "Markdown", "list", "numbers", "when", "a", "new", "item", "is", "added", "to", "the", "middle", "of", "a", "list" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/codemirror/continuelist.js#L67-L100
train
nhn/tui.editor
src/js/codemirror/fixOrderedListNumber.js
fixNumber
function fixNumber(lineNumber, prevIndentLength, startIndex, cm) { let indent, delimiter, text, indentLength; let index = startIndex; let lineText = cm.getLine(lineNumber); do { [, indent, , , delimiter, text] = listRE.exec(lineText); indentLength = indent.length; if (indentLength === prevIndentLength) { // fix number cm.replaceRange(`${indent}${index}${delimiter}${text}`, { line: lineNumber, ch: 0 }, { line: lineNumber, ch: lineText.length }); index += 1; lineNumber += 1; } else if (indentLength > prevIndentLength) { // nested list start lineNumber = fixNumber(lineNumber, indentLength, 1, cm); } else { // nested list end return lineNumber; } lineText = cm.getLine(lineNumber); } while (listRE.test(lineText)); return lineNumber; }
javascript
function fixNumber(lineNumber, prevIndentLength, startIndex, cm) { let indent, delimiter, text, indentLength; let index = startIndex; let lineText = cm.getLine(lineNumber); do { [, indent, , , delimiter, text] = listRE.exec(lineText); indentLength = indent.length; if (indentLength === prevIndentLength) { // fix number cm.replaceRange(`${indent}${index}${delimiter}${text}`, { line: lineNumber, ch: 0 }, { line: lineNumber, ch: lineText.length }); index += 1; lineNumber += 1; } else if (indentLength > prevIndentLength) { // nested list start lineNumber = fixNumber(lineNumber, indentLength, 1, cm); } else { // nested list end return lineNumber; } lineText = cm.getLine(lineNumber); } while (listRE.test(lineText)); return lineNumber; }
[ "function", "fixNumber", "(", "lineNumber", ",", "prevIndentLength", ",", "startIndex", ",", "cm", ")", "{", "let", "indent", ",", "delimiter", ",", "text", ",", "indentLength", ";", "let", "index", "=", "startIndex", ";", "let", "lineText", "=", "cm", ".", "getLine", "(", "lineNumber", ")", ";", "do", "{", "[", ",", "indent", ",", ",", ",", "delimiter", ",", "text", "]", "=", "listRE", ".", "exec", "(", "lineText", ")", ";", "indentLength", "=", "indent", ".", "length", ";", "if", "(", "indentLength", "===", "prevIndentLength", ")", "{", "cm", ".", "replaceRange", "(", "`", "${", "indent", "}", "${", "index", "}", "${", "delimiter", "}", "${", "text", "}", "`", ",", "{", "line", ":", "lineNumber", ",", "ch", ":", "0", "}", ",", "{", "line", ":", "lineNumber", ",", "ch", ":", "lineText", ".", "length", "}", ")", ";", "index", "+=", "1", ";", "lineNumber", "+=", "1", ";", "}", "else", "if", "(", "indentLength", ">", "prevIndentLength", ")", "{", "lineNumber", "=", "fixNumber", "(", "lineNumber", ",", "indentLength", ",", "1", ",", "cm", ")", ";", "}", "else", "{", "return", "lineNumber", ";", "}", "lineText", "=", "cm", ".", "getLine", "(", "lineNumber", ")", ";", "}", "while", "(", "listRE", ".", "test", "(", "lineText", ")", ")", ";", "return", "lineNumber", ";", "}" ]
fix list numbers @param {number} lineNumber - line number of list item to be normalized @param {number} prevIndentLength - previous indent length @param {number} startIndex - start index @param {CodeMirror} cm - CodeMirror instance @returns {number} - next line number @ignore
[ "fix", "list", "numbers" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/codemirror/fixOrderedListNumber.js#L62-L94
train
nhn/tui.editor
src/js/codemirror/fixOrderedListNumber.js
findFirstListItem
function findFirstListItem(lineNumber, cm) { let nextLineNumber = lineNumber; let lineText = cm.getLine(lineNumber); while (listRE.test(lineText)) { nextLineNumber -= 1; lineText = cm.getLine(nextLineNumber); } if (lineNumber === nextLineNumber) { nextLineNumber = -1; } else { nextLineNumber += 1; } return nextLineNumber; }
javascript
function findFirstListItem(lineNumber, cm) { let nextLineNumber = lineNumber; let lineText = cm.getLine(lineNumber); while (listRE.test(lineText)) { nextLineNumber -= 1; lineText = cm.getLine(nextLineNumber); } if (lineNumber === nextLineNumber) { nextLineNumber = -1; } else { nextLineNumber += 1; } return nextLineNumber; }
[ "function", "findFirstListItem", "(", "lineNumber", ",", "cm", ")", "{", "let", "nextLineNumber", "=", "lineNumber", ";", "let", "lineText", "=", "cm", ".", "getLine", "(", "lineNumber", ")", ";", "while", "(", "listRE", ".", "test", "(", "lineText", ")", ")", "{", "nextLineNumber", "-=", "1", ";", "lineText", "=", "cm", ".", "getLine", "(", "nextLineNumber", ")", ";", "}", "if", "(", "lineNumber", "===", "nextLineNumber", ")", "{", "nextLineNumber", "=", "-", "1", ";", "}", "else", "{", "nextLineNumber", "+=", "1", ";", "}", "return", "nextLineNumber", ";", "}" ]
find line number of list item which contains given lineNumber @param {number} lineNumber - line number of list item @param {CodeMirror} cm - CodeMirror instance @returns {number} - line number of first list item @ignore
[ "find", "line", "number", "of", "list", "item", "which", "contains", "given", "lineNumber" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/codemirror/fixOrderedListNumber.js#L103-L119
train
nhn/tui.editor
src/js/wysiwygCommands/strike.js
styleStrike
function styleStrike(sq) { if (sq.hasFormat('S')) { sq.changeFormat(null, {tag: 'S'}); } else if (!sq.hasFormat('a') && !sq.hasFormat('PRE')) { if (sq.hasFormat('code')) { sq.changeFormat(null, {tag: 'code'}); } sq.strikethrough(); } }
javascript
function styleStrike(sq) { if (sq.hasFormat('S')) { sq.changeFormat(null, {tag: 'S'}); } else if (!sq.hasFormat('a') && !sq.hasFormat('PRE')) { if (sq.hasFormat('code')) { sq.changeFormat(null, {tag: 'code'}); } sq.strikethrough(); } }
[ "function", "styleStrike", "(", "sq", ")", "{", "if", "(", "sq", ".", "hasFormat", "(", "'S'", ")", ")", "{", "sq", ".", "changeFormat", "(", "null", ",", "{", "tag", ":", "'S'", "}", ")", ";", "}", "else", "if", "(", "!", "sq", ".", "hasFormat", "(", "'a'", ")", "&&", "!", "sq", ".", "hasFormat", "(", "'PRE'", ")", ")", "{", "if", "(", "sq", ".", "hasFormat", "(", "'code'", ")", ")", "{", "sq", ".", "changeFormat", "(", "null", ",", "{", "tag", ":", "'code'", "}", ")", ";", "}", "sq", ".", "strikethrough", "(", ")", ";", "}", "}" ]
Style strike. @param {object} sq - squire editor instance
[ "Style", "strike", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/strike.js#L44-L53
train
nhn/tui.editor
src/js/extensions/table/mergedTableAddCol.js
_createNewCell
function _createNewCell(rowData, rowIndex, colIndex, prevCell) { const cellData = rowData[colIndex]; let newCell; if (util.isExisty(cellData.colMergeWith)) { const {colMergeWith} = cellData; const merger = rowData[colMergeWith]; const lastMergedCellIndex = colMergeWith + merger.colspan - 1; if (util.isExisty(merger.rowMergeWith) && prevCell) { newCell = util.extend({}, prevCell); } else if (lastMergedCellIndex > colIndex) { merger.colspan += 1; newCell = util.extend({}, cellData); } } else if (cellData.colspan > 1) { cellData.colspan += 1; newCell = _createColMergedCell(colIndex, cellData.nodeName); } if (!newCell) { newCell = dataHandler.createBasicCell(rowIndex, colIndex + 1, cellData.nodeName); } return newCell; }
javascript
function _createNewCell(rowData, rowIndex, colIndex, prevCell) { const cellData = rowData[colIndex]; let newCell; if (util.isExisty(cellData.colMergeWith)) { const {colMergeWith} = cellData; const merger = rowData[colMergeWith]; const lastMergedCellIndex = colMergeWith + merger.colspan - 1; if (util.isExisty(merger.rowMergeWith) && prevCell) { newCell = util.extend({}, prevCell); } else if (lastMergedCellIndex > colIndex) { merger.colspan += 1; newCell = util.extend({}, cellData); } } else if (cellData.colspan > 1) { cellData.colspan += 1; newCell = _createColMergedCell(colIndex, cellData.nodeName); } if (!newCell) { newCell = dataHandler.createBasicCell(rowIndex, colIndex + 1, cellData.nodeName); } return newCell; }
[ "function", "_createNewCell", "(", "rowData", ",", "rowIndex", ",", "colIndex", ",", "prevCell", ")", "{", "const", "cellData", "=", "rowData", "[", "colIndex", "]", ";", "let", "newCell", ";", "if", "(", "util", ".", "isExisty", "(", "cellData", ".", "colMergeWith", ")", ")", "{", "const", "{", "colMergeWith", "}", "=", "cellData", ";", "const", "merger", "=", "rowData", "[", "colMergeWith", "]", ";", "const", "lastMergedCellIndex", "=", "colMergeWith", "+", "merger", ".", "colspan", "-", "1", ";", "if", "(", "util", ".", "isExisty", "(", "merger", ".", "rowMergeWith", ")", "&&", "prevCell", ")", "{", "newCell", "=", "util", ".", "extend", "(", "{", "}", ",", "prevCell", ")", ";", "}", "else", "if", "(", "lastMergedCellIndex", ">", "colIndex", ")", "{", "merger", ".", "colspan", "+=", "1", ";", "newCell", "=", "util", ".", "extend", "(", "{", "}", ",", "cellData", ")", ";", "}", "}", "else", "if", "(", "cellData", ".", "colspan", ">", "1", ")", "{", "cellData", ".", "colspan", "+=", "1", ";", "newCell", "=", "_createColMergedCell", "(", "colIndex", ",", "cellData", ".", "nodeName", ")", ";", "}", "if", "(", "!", "newCell", ")", "{", "newCell", "=", "dataHandler", ".", "createBasicCell", "(", "rowIndex", ",", "colIndex", "+", "1", ",", "cellData", ".", "nodeName", ")", ";", "}", "return", "newCell", ";", "}" ]
Create new cell data. @param {Array.<object>} rowData - row data of table data @param {number} rowIndex - row index of table data @param {number} colIndex - column index of table data @param {object | null} prevCell - previous cell data @returns {object} @private
[ "Create", "new", "cell", "data", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/mergedTableAddCol.js#L77-L102
train
nhn/tui.editor
src/js/extensions/table/mergedTableRemoveRow.js
_updateRowspan
function _updateRowspan(tableData, startRowIndex, endRowIndex) { util.range(startRowIndex, endRowIndex + 1).forEach(rowIndex => { tableData[rowIndex].forEach((cell, cellIndex) => { if (util.isExisty(cell.rowMergeWith)) { const merger = tableData[cell.rowMergeWith][cellIndex]; if (merger.rowspan) { merger.rowspan -= 1; } } else if (cell.rowspan > 1) { const lastMergedRowIndex = rowIndex + cell.rowspan - 1; cell.rowspan -= (endRowIndex - rowIndex + 1); if (lastMergedRowIndex > endRowIndex) { tableData[endRowIndex + 1][cellIndex] = util.extend({}, cell); } } }); }); }
javascript
function _updateRowspan(tableData, startRowIndex, endRowIndex) { util.range(startRowIndex, endRowIndex + 1).forEach(rowIndex => { tableData[rowIndex].forEach((cell, cellIndex) => { if (util.isExisty(cell.rowMergeWith)) { const merger = tableData[cell.rowMergeWith][cellIndex]; if (merger.rowspan) { merger.rowspan -= 1; } } else if (cell.rowspan > 1) { const lastMergedRowIndex = rowIndex + cell.rowspan - 1; cell.rowspan -= (endRowIndex - rowIndex + 1); if (lastMergedRowIndex > endRowIndex) { tableData[endRowIndex + 1][cellIndex] = util.extend({}, cell); } } }); }); }
[ "function", "_updateRowspan", "(", "tableData", ",", "startRowIndex", ",", "endRowIndex", ")", "{", "util", ".", "range", "(", "startRowIndex", ",", "endRowIndex", "+", "1", ")", ".", "forEach", "(", "rowIndex", "=>", "{", "tableData", "[", "rowIndex", "]", ".", "forEach", "(", "(", "cell", ",", "cellIndex", ")", "=>", "{", "if", "(", "util", ".", "isExisty", "(", "cell", ".", "rowMergeWith", ")", ")", "{", "const", "merger", "=", "tableData", "[", "cell", ".", "rowMergeWith", "]", "[", "cellIndex", "]", ";", "if", "(", "merger", ".", "rowspan", ")", "{", "merger", ".", "rowspan", "-=", "1", ";", "}", "}", "else", "if", "(", "cell", ".", "rowspan", ">", "1", ")", "{", "const", "lastMergedRowIndex", "=", "rowIndex", "+", "cell", ".", "rowspan", "-", "1", ";", "cell", ".", "rowspan", "-=", "(", "endRowIndex", "-", "rowIndex", "+", "1", ")", ";", "if", "(", "lastMergedRowIndex", ">", "endRowIndex", ")", "{", "tableData", "[", "endRowIndex", "+", "1", "]", "[", "cellIndex", "]", "=", "util", ".", "extend", "(", "{", "}", ",", "cell", ")", ";", "}", "}", "}", ")", ";", "}", ")", ";", "}" ]
Update rowspan to row merger. @param {Array.<Array.<object>>} tableData - table data @param {number} startRowIndex - start row index @param {number} endRowIndex - end row index @private
[ "Update", "rowspan", "to", "row", "merger", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/mergedTableRemoveRow.js#L64-L84
train
nhn/tui.editor
src/js/extensions/colorSyntax.js
wrapTextAndGetRange
function wrapTextAndGetRange(pre, text, post) { return { result: `${pre}${text}${post}`, from: pre.length, to: pre.length + text.length }; }
javascript
function wrapTextAndGetRange(pre, text, post) { return { result: `${pre}${text}${post}`, from: pre.length, to: pre.length + text.length }; }
[ "function", "wrapTextAndGetRange", "(", "pre", ",", "text", ",", "post", ")", "{", "return", "{", "result", ":", "`", "${", "pre", "}", "${", "text", "}", "${", "post", "}", "`", ",", "from", ":", "pre", ".", "length", ",", "to", ":", "pre", ".", "length", "+", "text", ".", "length", "}", ";", "}" ]
wrap text with pre & post and return with text range @param {string} pre - text pre @param {string} text - text @param {string} post - text post @returns {object} - wrapped text and range(from, to) @ignore
[ "wrap", "text", "with", "pre", "&", "post", "and", "return", "with", "text", "range" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/colorSyntax.js#L276-L282
train
nhn/tui.editor
src/js/extensions/colorSyntax.js
changeDecColorsToHex
function changeDecColorsToHex(color) { return color.replace(decimalColorRx, (colorValue, r, g, b) => { const hr = changeDecColorToHex(r); const hg = changeDecColorToHex(g); const hb = changeDecColorToHex(b); return `#${hr}${hg}${hb}`; }); }
javascript
function changeDecColorsToHex(color) { return color.replace(decimalColorRx, (colorValue, r, g, b) => { const hr = changeDecColorToHex(r); const hg = changeDecColorToHex(g); const hb = changeDecColorToHex(b); return `#${hr}${hg}${hb}`; }); }
[ "function", "changeDecColorsToHex", "(", "color", ")", "{", "return", "color", ".", "replace", "(", "decimalColorRx", ",", "(", "colorValue", ",", "r", ",", "g", ",", "b", ")", "=>", "{", "const", "hr", "=", "changeDecColorToHex", "(", "r", ")", ";", "const", "hg", "=", "changeDecColorToHex", "(", "g", ")", ";", "const", "hb", "=", "changeDecColorToHex", "(", "b", ")", ";", "return", "`", "${", "hr", "}", "${", "hg", "}", "${", "hb", "}", "`", ";", "}", ")", ";", "}" ]
Change decimal color values to hexadecimal color value @param {string} color Color value string @returns {string} @ignore
[ "Change", "decimal", "color", "values", "to", "hexadecimal", "color", "value" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/colorSyntax.js#L290-L298
train
nhn/tui.editor
src/js/extensions/colorSyntax.js
changeDecColorToHex
function changeDecColorToHex(color) { let hexColor = parseInt(color, 10); hexColor = hexColor.toString(16); hexColor = doubleZeroPad(hexColor); return hexColor; }
javascript
function changeDecColorToHex(color) { let hexColor = parseInt(color, 10); hexColor = hexColor.toString(16); hexColor = doubleZeroPad(hexColor); return hexColor; }
[ "function", "changeDecColorToHex", "(", "color", ")", "{", "let", "hexColor", "=", "parseInt", "(", "color", ",", "10", ")", ";", "hexColor", "=", "hexColor", ".", "toString", "(", "16", ")", ";", "hexColor", "=", "doubleZeroPad", "(", "hexColor", ")", ";", "return", "hexColor", ";", "}" ]
change individual dec color value to hex color @param {string} color - individual color value @returns {string} - zero padded color string @ignore
[ "change", "individual", "dec", "color", "value", "to", "hex", "color" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/colorSyntax.js#L306-L312
train
nhn/tui.editor
src/js/wysiwygCommands/code.js
removeUnnecessaryCodeInNextToRange
function removeUnnecessaryCodeInNextToRange(range) { if (domUtils.getNodeName(range.startContainer.nextSibling) === 'CODE' && domUtils.getTextLength(range.startContainer.nextSibling) === 0 ) { $(range.startContainer.nextSibling).remove(); } }
javascript
function removeUnnecessaryCodeInNextToRange(range) { if (domUtils.getNodeName(range.startContainer.nextSibling) === 'CODE' && domUtils.getTextLength(range.startContainer.nextSibling) === 0 ) { $(range.startContainer.nextSibling).remove(); } }
[ "function", "removeUnnecessaryCodeInNextToRange", "(", "range", ")", "{", "if", "(", "domUtils", ".", "getNodeName", "(", "range", ".", "startContainer", ".", "nextSibling", ")", "===", "'CODE'", "&&", "domUtils", ".", "getTextLength", "(", "range", ".", "startContainer", ".", "nextSibling", ")", "===", "0", ")", "{", "$", "(", "range", ".", "startContainer", ".", "nextSibling", ")", ".", "remove", "(", ")", ";", "}", "}" ]
removeUnnecessaryCodeInNextToRange Remove unnecessary code tag next to range, code tag made by squire @param {Range} range range object
[ "removeUnnecessaryCodeInNextToRange", "Remove", "unnecessary", "code", "tag", "next", "to", "range", "code", "tag", "made", "by", "squire" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/code.js#L49-L55
train
nhn/tui.editor
src/js/wysiwygCommands/code.js
styleCode
function styleCode(editor, sq) { if (!sq.hasFormat('PRE') && sq.hasFormat('code')) { sq.changeFormat(null, {tag: 'code'}); removeUnnecessaryCodeInNextToRange(editor.getSelection().cloneRange()); } else if (!sq.hasFormat('a') && !sq.hasFormat('PRE')) { if (sq.hasFormat('b')) { sq.removeBold(); } else if (sq.hasFormat('i')) { sq.removeItalic(); } sq.changeFormat({tag: 'code'}); const range = sq.getSelection().cloneRange(); range.setStart(range.endContainer, range.endOffset); range.collapse(true); sq.setSelection(range); } }
javascript
function styleCode(editor, sq) { if (!sq.hasFormat('PRE') && sq.hasFormat('code')) { sq.changeFormat(null, {tag: 'code'}); removeUnnecessaryCodeInNextToRange(editor.getSelection().cloneRange()); } else if (!sq.hasFormat('a') && !sq.hasFormat('PRE')) { if (sq.hasFormat('b')) { sq.removeBold(); } else if (sq.hasFormat('i')) { sq.removeItalic(); } sq.changeFormat({tag: 'code'}); const range = sq.getSelection().cloneRange(); range.setStart(range.endContainer, range.endOffset); range.collapse(true); sq.setSelection(range); } }
[ "function", "styleCode", "(", "editor", ",", "sq", ")", "{", "if", "(", "!", "sq", ".", "hasFormat", "(", "'PRE'", ")", "&&", "sq", ".", "hasFormat", "(", "'code'", ")", ")", "{", "sq", ".", "changeFormat", "(", "null", ",", "{", "tag", ":", "'code'", "}", ")", ";", "removeUnnecessaryCodeInNextToRange", "(", "editor", ".", "getSelection", "(", ")", ".", "cloneRange", "(", ")", ")", ";", "}", "else", "if", "(", "!", "sq", ".", "hasFormat", "(", "'a'", ")", "&&", "!", "sq", ".", "hasFormat", "(", "'PRE'", ")", ")", "{", "if", "(", "sq", ".", "hasFormat", "(", "'b'", ")", ")", "{", "sq", ".", "removeBold", "(", ")", ";", "}", "else", "if", "(", "sq", ".", "hasFormat", "(", "'i'", ")", ")", "{", "sq", ".", "removeItalic", "(", ")", ";", "}", "sq", ".", "changeFormat", "(", "{", "tag", ":", "'code'", "}", ")", ";", "const", "range", "=", "sq", ".", "getSelection", "(", ")", ".", "cloneRange", "(", ")", ";", "range", ".", "setStart", "(", "range", ".", "endContainer", ",", "range", ".", "endOffset", ")", ";", "range", ".", "collapse", "(", "true", ")", ";", "sq", ".", "setSelection", "(", "range", ")", ";", "}", "}" ]
Style code. @param {object} editor - editor instance @param {object} sq - squire editor instance
[ "Style", "code", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/code.js#L62-L81
train
nhn/tui.editor
src/js/wwCodeBlockManager.js
sanitizeHtmlCode
function sanitizeHtmlCode(code) { return code ? code.replace(/[<>&]/g, tag => tagEntities[tag] || tag) : ''; }
javascript
function sanitizeHtmlCode(code) { return code ? code.replace(/[<>&]/g, tag => tagEntities[tag] || tag) : ''; }
[ "function", "sanitizeHtmlCode", "(", "code", ")", "{", "return", "code", "?", "code", ".", "replace", "(", "/", "[<>&]", "/", "g", ",", "tag", "=>", "tagEntities", "[", "tag", "]", "||", "tag", ")", ":", "''", ";", "}" ]
Sanitize HTML code @param {string} code code string @returns {string} @ignore
[ "Sanitize", "HTML", "code" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wwCodeBlockManager.js#L388-L390
train
nhn/tui.editor
src/js/extensions/table/tableRenderer.js
_createCellHtml
function _createCellHtml(cell) { let attrs = cell.colspan > 1 ? ` colspan="${cell.colspan}"` : ''; attrs += cell.rowspan > 1 ? ` rowspan="${cell.rowspan}"` : ''; attrs += cell.align ? ` align="${cell.align}"` : ''; return `<${cell.nodeName}${attrs}>${cell.content}</${cell.nodeName}>`; }
javascript
function _createCellHtml(cell) { let attrs = cell.colspan > 1 ? ` colspan="${cell.colspan}"` : ''; attrs += cell.rowspan > 1 ? ` rowspan="${cell.rowspan}"` : ''; attrs += cell.align ? ` align="${cell.align}"` : ''; return `<${cell.nodeName}${attrs}>${cell.content}</${cell.nodeName}>`; }
[ "function", "_createCellHtml", "(", "cell", ")", "{", "let", "attrs", "=", "cell", ".", "colspan", ">", "1", "?", "`", "${", "cell", ".", "colspan", "}", "`", ":", "''", ";", "attrs", "+=", "cell", ".", "rowspan", ">", "1", "?", "`", "${", "cell", ".", "rowspan", "}", "`", ":", "''", ";", "attrs", "+=", "cell", ".", "align", "?", "`", "${", "cell", ".", "align", "}", "`", ":", "''", ";", "return", "`", "${", "cell", ".", "nodeName", "}", "${", "attrs", "}", "${", "cell", ".", "content", "}", "${", "cell", ".", "nodeName", "}", "`", ";", "}" ]
Create cell html. @param {object} cell - cell data of table base data @returns {string} @private
[ "Create", "cell", "html", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableRenderer.js#L15-L21
train
nhn/tui.editor
src/js/extensions/table/tableRenderer.js
_createTheadOrTbodyHtml
function _createTheadOrTbodyHtml(trs, wrapperNodeName) { let html = ''; if (trs.length) { html = trs.map(tr => { const tdHtml = tr.map(_createCellHtml).join(''); return `<tr>${tdHtml}</tr>`; }).join(''); html = `<${wrapperNodeName}>${html}</${wrapperNodeName}>`; } return html; }
javascript
function _createTheadOrTbodyHtml(trs, wrapperNodeName) { let html = ''; if (trs.length) { html = trs.map(tr => { const tdHtml = tr.map(_createCellHtml).join(''); return `<tr>${tdHtml}</tr>`; }).join(''); html = `<${wrapperNodeName}>${html}</${wrapperNodeName}>`; } return html; }
[ "function", "_createTheadOrTbodyHtml", "(", "trs", ",", "wrapperNodeName", ")", "{", "let", "html", "=", "''", ";", "if", "(", "trs", ".", "length", ")", "{", "html", "=", "trs", ".", "map", "(", "tr", "=>", "{", "const", "tdHtml", "=", "tr", ".", "map", "(", "_createCellHtml", ")", ".", "join", "(", "''", ")", ";", "return", "`", "${", "tdHtml", "}", "`", ";", "}", ")", ".", "join", "(", "''", ")", ";", "html", "=", "`", "${", "wrapperNodeName", "}", "${", "html", "}", "${", "wrapperNodeName", "}", "`", ";", "}", "return", "html", ";", "}" ]
Create html for thead or tbody. @param {Array.<Array.<object>>} trs - tr list @param {string} wrapperNodeName - wrapper node name like THEAD, TBODY @returns {string} @private
[ "Create", "html", "for", "thead", "or", "tbody", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableRenderer.js#L30-L43
train
nhn/tui.editor
src/js/extensions/table/tableRenderer.js
createTableHtml
function createTableHtml(renderData) { const thead = [renderData[0]]; const tbody = renderData.slice(1); const theadHtml = _createTheadOrTbodyHtml(thead, 'THEAD'); const tbodyHtml = _createTheadOrTbodyHtml(tbody, 'TBODY'); const className = renderData.className ? ` class="${renderData.className}"` : ''; return `<table${className}>${theadHtml + tbodyHtml}</renderData>`; }
javascript
function createTableHtml(renderData) { const thead = [renderData[0]]; const tbody = renderData.slice(1); const theadHtml = _createTheadOrTbodyHtml(thead, 'THEAD'); const tbodyHtml = _createTheadOrTbodyHtml(tbody, 'TBODY'); const className = renderData.className ? ` class="${renderData.className}"` : ''; return `<table${className}>${theadHtml + tbodyHtml}</renderData>`; }
[ "function", "createTableHtml", "(", "renderData", ")", "{", "const", "thead", "=", "[", "renderData", "[", "0", "]", "]", ";", "const", "tbody", "=", "renderData", ".", "slice", "(", "1", ")", ";", "const", "theadHtml", "=", "_createTheadOrTbodyHtml", "(", "thead", ",", "'THEAD'", ")", ";", "const", "tbodyHtml", "=", "_createTheadOrTbodyHtml", "(", "tbody", ",", "'TBODY'", ")", ";", "const", "className", "=", "renderData", ".", "className", "?", "`", "${", "renderData", ".", "className", "}", "`", ":", "''", ";", "return", "`", "${", "className", "}", "${", "theadHtml", "+", "tbodyHtml", "}", "`", ";", "}" ]
Create table html. @param {Array.<Array.<object>>} renderData - table data for render @returns {string} @private
[ "Create", "table", "html", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableRenderer.js#L51-L59
train
nhn/tui.editor
src/js/extensions/table/tableRenderer.js
replaceTable
function replaceTable($table, tableData) { const cellIndexData = tableDataHandler.createCellIndexData(tableData); const renderData = tableDataHandler.createRenderData(tableData, cellIndexData); const $newTable = $(createTableHtml(renderData)); $table.replaceWith($newTable); return $newTable; }
javascript
function replaceTable($table, tableData) { const cellIndexData = tableDataHandler.createCellIndexData(tableData); const renderData = tableDataHandler.createRenderData(tableData, cellIndexData); const $newTable = $(createTableHtml(renderData)); $table.replaceWith($newTable); return $newTable; }
[ "function", "replaceTable", "(", "$table", ",", "tableData", ")", "{", "const", "cellIndexData", "=", "tableDataHandler", ".", "createCellIndexData", "(", "tableData", ")", ";", "const", "renderData", "=", "tableDataHandler", ".", "createRenderData", "(", "tableData", ",", "cellIndexData", ")", ";", "const", "$newTable", "=", "$", "(", "createTableHtml", "(", "renderData", ")", ")", ";", "$table", ".", "replaceWith", "(", "$newTable", ")", ";", "return", "$newTable", ";", "}" ]
Replace table. @param {jQuery} $table - table jQuery element @param {Array.<Array.<object>>} tableData - table data @returns {jQuery} @ignore
[ "Replace", "table", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableRenderer.js#L68-L76
train
nhn/tui.editor
src/js/extensions/table/tableRenderer.js
focusToCell
function focusToCell(sq, range, targetCell) { range.selectNodeContents(targetCell); range.collapse(true); sq.setSelection(range); }
javascript
function focusToCell(sq, range, targetCell) { range.selectNodeContents(targetCell); range.collapse(true); sq.setSelection(range); }
[ "function", "focusToCell", "(", "sq", ",", "range", ",", "targetCell", ")", "{", "range", ".", "selectNodeContents", "(", "targetCell", ")", ";", "range", ".", "collapse", "(", "true", ")", ";", "sq", ".", "setSelection", "(", "range", ")", ";", "}" ]
Focus to cell. @param {squireext} sq - squire instance @param {range} range - range object @param {HTMLElement} targetCell - cell element for focus @ignore
[ "Focus", "to", "cell", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableRenderer.js#L85-L89
train
nhn/tui.editor
src/js/extensions/table/unmergeCell.js
_updateMergedCells
function _updateMergedCells(tableData, startRowIndex, startColIndex, rowspan, colspan) { const limitRowIndex = startRowIndex + rowspan; const limitColIndex = startColIndex + colspan; const colRange = util.range(startColIndex, limitColIndex); util.range(startRowIndex, limitRowIndex).forEach(rowIndex => { const rowData = tableData[rowIndex]; const startIndex = (rowIndex === startRowIndex) ? 1 : 0; colRange.slice(startIndex).forEach(colIndex => { rowData[colIndex] = dataHandler.createBasicCell(rowIndex, colIndex, rowData[colIndex].nodeName); }); }); }
javascript
function _updateMergedCells(tableData, startRowIndex, startColIndex, rowspan, colspan) { const limitRowIndex = startRowIndex + rowspan; const limitColIndex = startColIndex + colspan; const colRange = util.range(startColIndex, limitColIndex); util.range(startRowIndex, limitRowIndex).forEach(rowIndex => { const rowData = tableData[rowIndex]; const startIndex = (rowIndex === startRowIndex) ? 1 : 0; colRange.slice(startIndex).forEach(colIndex => { rowData[colIndex] = dataHandler.createBasicCell(rowIndex, colIndex, rowData[colIndex].nodeName); }); }); }
[ "function", "_updateMergedCells", "(", "tableData", ",", "startRowIndex", ",", "startColIndex", ",", "rowspan", ",", "colspan", ")", "{", "const", "limitRowIndex", "=", "startRowIndex", "+", "rowspan", ";", "const", "limitColIndex", "=", "startColIndex", "+", "colspan", ";", "const", "colRange", "=", "util", ".", "range", "(", "startColIndex", ",", "limitColIndex", ")", ";", "util", ".", "range", "(", "startRowIndex", ",", "limitRowIndex", ")", ".", "forEach", "(", "rowIndex", "=>", "{", "const", "rowData", "=", "tableData", "[", "rowIndex", "]", ";", "const", "startIndex", "=", "(", "rowIndex", "===", "startRowIndex", ")", "?", "1", ":", "0", ";", "colRange", ".", "slice", "(", "startIndex", ")", ".", "forEach", "(", "colIndex", "=>", "{", "rowData", "[", "colIndex", "]", "=", "dataHandler", ".", "createBasicCell", "(", "rowIndex", ",", "colIndex", ",", "rowData", "[", "colIndex", "]", ".", "nodeName", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Update merged cell data to basic cell data. @param {Array.<Array.<object>>} tableData - table data @param {number} startRowIndex - start row index @param {number} startColIndex - start col index @param {number} rowspan - rowspan property of merger cell @param {number} colspan - colspan property of merger cell @private
[ "Update", "merged", "cell", "data", "to", "basic", "cell", "data", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/unmergeCell.js#L79-L92
train
nhn/tui.editor
src/js/extensions/table/mergedTableRemoveCol.js
_updateColspan
function _updateColspan(tableData, startColIndex, endColIndex) { tableData.forEach(rowData => { util.range(startColIndex, endColIndex + 1).forEach(colIndex => { const cellData = rowData [colIndex]; if (util.isExisty(cellData.colMergeWith)) { const merger = rowData [cellData.colMergeWith]; if (merger.colspan) { merger.colspan -= 1; } } else if (cellData.colspan > 1) { const lastMergedCellIndex = colIndex + cellData.colspan - 1; cellData.colspan -= (endColIndex - colIndex + 1); if (lastMergedCellIndex > endColIndex) { rowData [endColIndex + 1] = util.extend({}, cellData); } } }); }); }
javascript
function _updateColspan(tableData, startColIndex, endColIndex) { tableData.forEach(rowData => { util.range(startColIndex, endColIndex + 1).forEach(colIndex => { const cellData = rowData [colIndex]; if (util.isExisty(cellData.colMergeWith)) { const merger = rowData [cellData.colMergeWith]; if (merger.colspan) { merger.colspan -= 1; } } else if (cellData.colspan > 1) { const lastMergedCellIndex = colIndex + cellData.colspan - 1; cellData.colspan -= (endColIndex - colIndex + 1); if (lastMergedCellIndex > endColIndex) { rowData [endColIndex + 1] = util.extend({}, cellData); } } }); }); }
[ "function", "_updateColspan", "(", "tableData", ",", "startColIndex", ",", "endColIndex", ")", "{", "tableData", ".", "forEach", "(", "rowData", "=>", "{", "util", ".", "range", "(", "startColIndex", ",", "endColIndex", "+", "1", ")", ".", "forEach", "(", "colIndex", "=>", "{", "const", "cellData", "=", "rowData", "[", "colIndex", "]", ";", "if", "(", "util", ".", "isExisty", "(", "cellData", ".", "colMergeWith", ")", ")", "{", "const", "merger", "=", "rowData", "[", "cellData", ".", "colMergeWith", "]", ";", "if", "(", "merger", ".", "colspan", ")", "{", "merger", ".", "colspan", "-=", "1", ";", "}", "}", "else", "if", "(", "cellData", ".", "colspan", ">", "1", ")", "{", "const", "lastMergedCellIndex", "=", "colIndex", "+", "cellData", ".", "colspan", "-", "1", ";", "cellData", ".", "colspan", "-=", "(", "endColIndex", "-", "colIndex", "+", "1", ")", ";", "if", "(", "lastMergedCellIndex", ">", "endColIndex", ")", "{", "rowData", "[", "endColIndex", "+", "1", "]", "=", "util", ".", "extend", "(", "{", "}", ",", "cellData", ")", ";", "}", "}", "}", ")", ";", "}", ")", ";", "}" ]
Update colspan to col merger. @param {Array.<Array.<object>>} tableData - table data @param {number} startColIndex - start col index @param {number} endColIndex - end col index @private
[ "Update", "colspan", "to", "col", "merger", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/mergedTableRemoveCol.js#L64-L86
train
nhn/tui.editor
src/js/extensions/mark/viewerMarkerHelper.js
getRange
function getRange() { const selection = window.getSelection(); let range; if (selection && selection.rangeCount) { range = selection.getRangeAt(0).cloneRange(); } else { range = document.createRange(); range.selectNodeContents(this.preview.$el[0]); range.collapse(true); } return range; }
javascript
function getRange() { const selection = window.getSelection(); let range; if (selection && selection.rangeCount) { range = selection.getRangeAt(0).cloneRange(); } else { range = document.createRange(); range.selectNodeContents(this.preview.$el[0]); range.collapse(true); } return range; }
[ "function", "getRange", "(", ")", "{", "const", "selection", "=", "window", ".", "getSelection", "(", ")", ";", "let", "range", ";", "if", "(", "selection", "&&", "selection", ".", "rangeCount", ")", "{", "range", "=", "selection", ".", "getRangeAt", "(", "0", ")", ".", "cloneRange", "(", ")", ";", "}", "else", "{", "range", "=", "document", ".", "createRange", "(", ")", ";", "range", ".", "selectNodeContents", "(", "this", ".", "preview", ".", "$el", "[", "0", "]", ")", ";", "range", ".", "collapse", "(", "true", ")", ";", "}", "return", "range", ";", "}" ]
getRange get current range @returns {Range} @ignore
[ "getRange", "get", "current", "range" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/mark/viewerMarkerHelper.js#L207-L220
train
nhn/tui.editor
src/js/markdownItPlugins/markdownitTaskPlugin.js
removeMarkdownTaskFormatText
function removeMarkdownTaskFormatText(token) { // '[X] ' length is 4 // FIXED: we don't need first space token.content = token.content.slice(4); token.children[0].content = token.children[0].content.slice(4); }
javascript
function removeMarkdownTaskFormatText(token) { // '[X] ' length is 4 // FIXED: we don't need first space token.content = token.content.slice(4); token.children[0].content = token.children[0].content.slice(4); }
[ "function", "removeMarkdownTaskFormatText", "(", "token", ")", "{", "token", ".", "content", "=", "token", ".", "content", ".", "slice", "(", "4", ")", ";", "token", ".", "children", "[", "0", "]", ".", "content", "=", "token", ".", "children", "[", "0", "]", ".", "content", ".", "slice", "(", "4", ")", ";", "}" ]
Remove task format text for rendering @param {object} token Token object @ignore
[ "Remove", "task", "format", "text", "for", "rendering" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/markdownItPlugins/markdownitTaskPlugin.js#L47-L52
train
nhn/tui.editor
src/js/markdownItPlugins/markdownitTaskPlugin.js
isChecked
function isChecked(token) { var checked = false; if (token.content.indexOf('[x]') === 0 || token.content.indexOf('[X]') === 0) { checked = true; } return checked; }
javascript
function isChecked(token) { var checked = false; if (token.content.indexOf('[x]') === 0 || token.content.indexOf('[X]') === 0) { checked = true; } return checked; }
[ "function", "isChecked", "(", "token", ")", "{", "var", "checked", "=", "false", ";", "if", "(", "token", ".", "content", ".", "indexOf", "(", "'[x]'", ")", "===", "0", "||", "token", ".", "content", ".", "indexOf", "(", "'[X]'", ")", "===", "0", ")", "{", "checked", "=", "true", ";", "}", "return", "checked", ";", "}" ]
Return boolean value whether task checked or not @param {object} token Token object @returns {boolean} @ignore
[ "Return", "boolean", "value", "whether", "task", "checked", "or", "not" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/markdownItPlugins/markdownitTaskPlugin.js#L60-L68
train
nhn/tui.editor
src/js/markdownItPlugins/markdownitTaskPlugin.js
setTokenAttribute
function setTokenAttribute(token, attributeName, attributeValue) { var index = token.attrIndex(attributeName); var attr = [attributeName, attributeValue]; if (index < 0) { token.attrPush(attr); } else { token.attrs[index] = attr; } }
javascript
function setTokenAttribute(token, attributeName, attributeValue) { var index = token.attrIndex(attributeName); var attr = [attributeName, attributeValue]; if (index < 0) { token.attrPush(attr); } else { token.attrs[index] = attr; } }
[ "function", "setTokenAttribute", "(", "token", ",", "attributeName", ",", "attributeValue", ")", "{", "var", "index", "=", "token", ".", "attrIndex", "(", "attributeName", ")", ";", "var", "attr", "=", "[", "attributeName", ",", "attributeValue", "]", ";", "if", "(", "index", "<", "0", ")", "{", "token", ".", "attrPush", "(", "attr", ")", ";", "}", "else", "{", "token", ".", "attrs", "[", "index", "]", "=", "attr", ";", "}", "}" ]
Set attribute of passed token @param {object} token Token object @param {string} attributeName Attribute name for set @param {string} attributeValue Attribute value for set @ignore
[ "Set", "attribute", "of", "passed", "token" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/markdownItPlugins/markdownitTaskPlugin.js#L77-L86
train
nhn/tui.editor
src/js/markdownItPlugins/markdownitTaskPlugin.js
isTaskListItemToken
function isTaskListItemToken(tokens, index) { return tokens[index].type === 'inline' && tokens[index - 1].type === 'paragraph_open' && tokens[index - 2].type === 'list_item_open' && (tokens[index].content.indexOf('[ ]') === 0 || tokens[index].content.indexOf('[x]') === 0 || tokens[index].content.indexOf('[X]') === 0); }
javascript
function isTaskListItemToken(tokens, index) { return tokens[index].type === 'inline' && tokens[index - 1].type === 'paragraph_open' && tokens[index - 2].type === 'list_item_open' && (tokens[index].content.indexOf('[ ]') === 0 || tokens[index].content.indexOf('[x]') === 0 || tokens[index].content.indexOf('[X]') === 0); }
[ "function", "isTaskListItemToken", "(", "tokens", ",", "index", ")", "{", "return", "tokens", "[", "index", "]", ".", "type", "===", "'inline'", "&&", "tokens", "[", "index", "-", "1", "]", ".", "type", "===", "'paragraph_open'", "&&", "tokens", "[", "index", "-", "2", "]", ".", "type", "===", "'list_item_open'", "&&", "(", "tokens", "[", "index", "]", ".", "content", ".", "indexOf", "(", "'[ ]'", ")", "===", "0", "||", "tokens", "[", "index", "]", ".", "content", ".", "indexOf", "(", "'[x]'", ")", "===", "0", "||", "tokens", "[", "index", "]", ".", "content", ".", "indexOf", "(", "'[X]'", ")", "===", "0", ")", ";", "}" ]
Return boolean value whether task list item or not @param {array} tokens Token object @param {number} index Number of token index @returns {boolean} @ignore
[ "Return", "boolean", "value", "whether", "task", "list", "item", "or", "not" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/markdownItPlugins/markdownitTaskPlugin.js#L95-L102
train
nhn/tui.editor
src/js/wysiwygCommands/tableRemoveCol.js
getCellByRange
function getCellByRange(range) { let cell = range.startContainer; if (domUtils.getNodeName(cell) === 'TD' || domUtils.getNodeName(cell) === 'TH') { cell = $(cell); } else { cell = $(cell).parentsUntil('tr'); } return cell; }
javascript
function getCellByRange(range) { let cell = range.startContainer; if (domUtils.getNodeName(cell) === 'TD' || domUtils.getNodeName(cell) === 'TH') { cell = $(cell); } else { cell = $(cell).parentsUntil('tr'); } return cell; }
[ "function", "getCellByRange", "(", "range", ")", "{", "let", "cell", "=", "range", ".", "startContainer", ";", "if", "(", "domUtils", ".", "getNodeName", "(", "cell", ")", "===", "'TD'", "||", "domUtils", ".", "getNodeName", "(", "cell", ")", "===", "'TH'", ")", "{", "cell", "=", "$", "(", "cell", ")", ";", "}", "else", "{", "cell", "=", "$", "(", "cell", ")", ".", "parentsUntil", "(", "'tr'", ")", ";", "}", "return", "cell", ";", "}" ]
Get cell by range object @param {Range} range range @returns {HTMLElement|Node}
[ "Get", "cell", "by", "range", "object" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableRemoveCol.js#L68-L78
train
nhn/tui.editor
src/js/wysiwygCommands/tableRemoveCol.js
removeMultipleColsByCells
function removeMultipleColsByCells($cells) { const numberOfCells = $cells.length; for (let i = 0; i < numberOfCells; i += 1) { const $cellToDelete = $cells.eq(i); if ($cellToDelete.length > 0) { removeColByCell($cells.eq(i)); } } }
javascript
function removeMultipleColsByCells($cells) { const numberOfCells = $cells.length; for (let i = 0; i < numberOfCells; i += 1) { const $cellToDelete = $cells.eq(i); if ($cellToDelete.length > 0) { removeColByCell($cells.eq(i)); } } }
[ "function", "removeMultipleColsByCells", "(", "$cells", ")", "{", "const", "numberOfCells", "=", "$cells", ".", "length", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "numberOfCells", ";", "i", "+=", "1", ")", "{", "const", "$cellToDelete", "=", "$cells", ".", "eq", "(", "i", ")", ";", "if", "(", "$cellToDelete", ".", "length", ">", "0", ")", "{", "removeColByCell", "(", "$cells", ".", "eq", "(", "i", ")", ")", ";", "}", "}", "}" ]
Remove columns by given cells @param {jQuery} $cells - jQuery table cells
[ "Remove", "columns", "by", "given", "cells" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableRemoveCol.js#L84-L92
train
nhn/tui.editor
src/js/wysiwygCommands/tableRemoveCol.js
removeColByCell
function removeColByCell($cell) { const index = $cell.index(); $cell.parents('table').find('tr').each((n, tr) => { $(tr).children().eq(index).remove(); }); }
javascript
function removeColByCell($cell) { const index = $cell.index(); $cell.parents('table').find('tr').each((n, tr) => { $(tr).children().eq(index).remove(); }); }
[ "function", "removeColByCell", "(", "$cell", ")", "{", "const", "index", "=", "$cell", ".", "index", "(", ")", ";", "$cell", ".", "parents", "(", "'table'", ")", ".", "find", "(", "'tr'", ")", ".", "each", "(", "(", "n", ",", "tr", ")", "=>", "{", "$", "(", "tr", ")", ".", "children", "(", ")", ".", "eq", "(", "index", ")", ".", "remove", "(", ")", ";", "}", ")", ";", "}" ]
Remove column by given cell @param {jQuery} $cell - jQuery wrapped table cell
[ "Remove", "column", "by", "given", "cell" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableRemoveCol.js#L98-L104
train
nhn/tui.editor
src/js/wysiwygCommands/tableRemoveCol.js
focusToCell
function focusToCell(sq, $cell, tableMgr) { const nextFocusCell = $cell.get(0); if ($cell.length && $.contains(document, $cell)) { const range = sq.getSelection(); range.selectNodeContents($cell[0]); range.collapse(true); sq.setSelection(range); tableMgr.setLastCellNode(nextFocusCell); } }
javascript
function focusToCell(sq, $cell, tableMgr) { const nextFocusCell = $cell.get(0); if ($cell.length && $.contains(document, $cell)) { const range = sq.getSelection(); range.selectNodeContents($cell[0]); range.collapse(true); sq.setSelection(range); tableMgr.setLastCellNode(nextFocusCell); } }
[ "function", "focusToCell", "(", "sq", ",", "$cell", ",", "tableMgr", ")", "{", "const", "nextFocusCell", "=", "$cell", ".", "get", "(", "0", ")", ";", "if", "(", "$cell", ".", "length", "&&", "$", ".", "contains", "(", "document", ",", "$cell", ")", ")", "{", "const", "range", "=", "sq", ".", "getSelection", "(", ")", ";", "range", ".", "selectNodeContents", "(", "$cell", "[", "0", "]", ")", ";", "range", ".", "collapse", "(", "true", ")", ";", "sq", ".", "setSelection", "(", "range", ")", ";", "tableMgr", ".", "setLastCellNode", "(", "nextFocusCell", ")", ";", "}", "}" ]
Focus to given cell @param {Squire} sq - Squire instance @param {jQuery} $cell - jQuery wrapped table cell @param {object} tableMgr - Table manager instance
[ "Focus", "to", "given", "cell" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableRemoveCol.js#L112-L123
train
nhn/tui.editor
src/js/wysiwygCommands/bold.js
styleBold
function styleBold(sq) { if (sq.hasFormat('b') || sq.hasFormat('strong')) { sq.changeFormat(null, {tag: 'b'}); } else if (!sq.hasFormat('a') && !sq.hasFormat('PRE')) { if (sq.hasFormat('code')) { sq.changeFormat(null, {tag: 'code'}); } sq.bold(); } }
javascript
function styleBold(sq) { if (sq.hasFormat('b') || sq.hasFormat('strong')) { sq.changeFormat(null, {tag: 'b'}); } else if (!sq.hasFormat('a') && !sq.hasFormat('PRE')) { if (sq.hasFormat('code')) { sq.changeFormat(null, {tag: 'code'}); } sq.bold(); } }
[ "function", "styleBold", "(", "sq", ")", "{", "if", "(", "sq", ".", "hasFormat", "(", "'b'", ")", "||", "sq", ".", "hasFormat", "(", "'strong'", ")", ")", "{", "sq", ".", "changeFormat", "(", "null", ",", "{", "tag", ":", "'b'", "}", ")", ";", "}", "else", "if", "(", "!", "sq", ".", "hasFormat", "(", "'a'", ")", "&&", "!", "sq", ".", "hasFormat", "(", "'PRE'", ")", ")", "{", "if", "(", "sq", ".", "hasFormat", "(", "'code'", ")", ")", "{", "sq", ".", "changeFormat", "(", "null", ",", "{", "tag", ":", "'code'", "}", ")", ";", "}", "sq", ".", "bold", "(", ")", ";", "}", "}" ]
Style bold. @param {object} sq - squire editor instance
[ "Style", "bold", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/bold.js#L43-L52
train
nhn/tui.editor
src/js/extensions/table/wwMergedTableManager.js
any
function any(arr, contition) { let result = false; util.forEach(arr, item => { result = contition(item); return !result; }); return result; }
javascript
function any(arr, contition) { let result = false; util.forEach(arr, item => { result = contition(item); return !result; }); return result; }
[ "function", "any", "(", "arr", ",", "contition", ")", "{", "let", "result", "=", "false", ";", "util", ".", "forEach", "(", "arr", ",", "item", "=>", "{", "result", "=", "contition", "(", "item", ")", ";", "return", "!", "result", ";", "}", ")", ";", "return", "result", ";", "}" ]
Whether one of them is true or not. @param {Array} arr - target array @param {function} contition - condition function @returns {boolean} @ignore
[ "Whether", "one", "of", "them", "is", "true", "or", "not", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/wwMergedTableManager.js#L543-L553
train
nhn/tui.editor
src/js/wysiwygCommands/tableAddCol.js
getNumberOfCols
function getNumberOfCols(wwe) { const selectionMgr = wwe.componentManager.getManager('tableSelection'); const $selectedCells = selectionMgr.getSelectedCells(); let length = 1; if ($selectedCells.length > 0) { const maxLength = $selectedCells.get(0).parentNode.querySelectorAll('td, th').length; length = Math.min(maxLength, $selectedCells.length); } return length; }
javascript
function getNumberOfCols(wwe) { const selectionMgr = wwe.componentManager.getManager('tableSelection'); const $selectedCells = selectionMgr.getSelectedCells(); let length = 1; if ($selectedCells.length > 0) { const maxLength = $selectedCells.get(0).parentNode.querySelectorAll('td, th').length; length = Math.min(maxLength, $selectedCells.length); } return length; }
[ "function", "getNumberOfCols", "(", "wwe", ")", "{", "const", "selectionMgr", "=", "wwe", ".", "componentManager", ".", "getManager", "(", "'tableSelection'", ")", ";", "const", "$selectedCells", "=", "selectionMgr", ".", "getSelectedCells", "(", ")", ";", "let", "length", "=", "1", ";", "if", "(", "$selectedCells", ".", "length", ">", "0", ")", "{", "const", "maxLength", "=", "$selectedCells", ".", "get", "(", "0", ")", ".", "parentNode", ".", "querySelectorAll", "(", "'td, th'", ")", ".", "length", ";", "length", "=", "Math", ".", "min", "(", "maxLength", ",", "$selectedCells", ".", "length", ")", ";", "}", "return", "length", ";", "}" ]
get number of selected cols @param {WysiwygEditor} wwe - wysiwyg editor instance @returns {number} - number of selected cols @ignore
[ "get", "number", "of", "selected", "cols" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableAddCol.js#L49-L60
train
nhn/tui.editor
src/js/wysiwygCommands/tableAddCol.js
addColToCellAfter
function addColToCellAfter($cell, numberOfCols = 1) { const index = $cell.index(); let cellToAdd; $cell.parents('table').find('tr').each((n, tr) => { const isTBody = domUtils.getNodeName(tr.parentNode) === 'TBODY'; const isMSIE = util.browser.msie; const cell = tr.children[index]; for (let i = 0; i < numberOfCols; i += 1) { if (isTBody) { cellToAdd = document.createElement('td'); } else { cellToAdd = document.createElement('th'); } if (!isMSIE) { cellToAdd.appendChild(document.createElement('br')); } $(cellToAdd).insertAfter(cell); } }); }
javascript
function addColToCellAfter($cell, numberOfCols = 1) { const index = $cell.index(); let cellToAdd; $cell.parents('table').find('tr').each((n, tr) => { const isTBody = domUtils.getNodeName(tr.parentNode) === 'TBODY'; const isMSIE = util.browser.msie; const cell = tr.children[index]; for (let i = 0; i < numberOfCols; i += 1) { if (isTBody) { cellToAdd = document.createElement('td'); } else { cellToAdd = document.createElement('th'); } if (!isMSIE) { cellToAdd.appendChild(document.createElement('br')); } $(cellToAdd).insertAfter(cell); } }); }
[ "function", "addColToCellAfter", "(", "$cell", ",", "numberOfCols", "=", "1", ")", "{", "const", "index", "=", "$cell", ".", "index", "(", ")", ";", "let", "cellToAdd", ";", "$cell", ".", "parents", "(", "'table'", ")", ".", "find", "(", "'tr'", ")", ".", "each", "(", "(", "n", ",", "tr", ")", "=>", "{", "const", "isTBody", "=", "domUtils", ".", "getNodeName", "(", "tr", ".", "parentNode", ")", "===", "'TBODY'", ";", "const", "isMSIE", "=", "util", ".", "browser", ".", "msie", ";", "const", "cell", "=", "tr", ".", "children", "[", "index", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "numberOfCols", ";", "i", "+=", "1", ")", "{", "if", "(", "isTBody", ")", "{", "cellToAdd", "=", "document", ".", "createElement", "(", "'td'", ")", ";", "}", "else", "{", "cellToAdd", "=", "document", ".", "createElement", "(", "'th'", ")", ";", "}", "if", "(", "!", "isMSIE", ")", "{", "cellToAdd", ".", "appendChild", "(", "document", ".", "createElement", "(", "'br'", ")", ")", ";", "}", "$", "(", "cellToAdd", ")", ".", "insertAfter", "(", "cell", ")", ";", "}", "}", ")", ";", "}" ]
Add column to after the current cell @param {jQuery} $cell - jQuery wrapped table cell @param {number} [numberOfCols=1] - number of cols @ignore
[ "Add", "column", "to", "after", "the", "current", "cell" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableAddCol.js#L86-L106
train
nhn/tui.editor
src/js/wysiwygCommands/tableAddCol.js
focusToNextCell
function focusToNextCell(sq, $cell) { const range = sq.getSelection(); range.selectNodeContents($cell.next()[0]); range.collapse(true); sq.setSelection(range); }
javascript
function focusToNextCell(sq, $cell) { const range = sq.getSelection(); range.selectNodeContents($cell.next()[0]); range.collapse(true); sq.setSelection(range); }
[ "function", "focusToNextCell", "(", "sq", ",", "$cell", ")", "{", "const", "range", "=", "sq", ".", "getSelection", "(", ")", ";", "range", ".", "selectNodeContents", "(", "$cell", ".", "next", "(", ")", "[", "0", "]", ")", ";", "range", ".", "collapse", "(", "true", ")", ";", "sq", ".", "setSelection", "(", "range", ")", ";", "}" ]
Focus to next cell @param {Squire} sq - Squire instance @param {jQuery} $cell - jQuery wrapped table cell @ignore
[ "Focus", "to", "next", "cell" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableAddCol.js#L114-L121
train
nhn/tui.editor
src/js/extensions/uml.js
umlExtension
function umlExtension(editor, options = {}) { const { rendererURL = DEFAULT_RENDERER_URL } = options; /** * render html from uml * @param {string} umlCode - plant uml code text * @returns {string} - rendered html */ function plantUMLReplacer(umlCode) { let renderedHTML; try { if (!plantumlEncoder) { throw new Error('plantuml-encoder dependency required'); } renderedHTML = `<img src="${rendererURL}${plantumlEncoder.encode(umlCode)}" />`; } catch (err) { renderedHTML = `Error occurred on encoding uml: ${err.message}`; } return renderedHTML; } const {codeBlockLanguages} = editor.options; UML_LANGUAGES.forEach(umlLanguage => { if (codeBlockLanguages.indexOf(umlLanguage) < 0) { codeBlockLanguages.push(umlLanguage); } codeBlockManager.setReplacer(umlLanguage, plantUMLReplacer); }); }
javascript
function umlExtension(editor, options = {}) { const { rendererURL = DEFAULT_RENDERER_URL } = options; /** * render html from uml * @param {string} umlCode - plant uml code text * @returns {string} - rendered html */ function plantUMLReplacer(umlCode) { let renderedHTML; try { if (!plantumlEncoder) { throw new Error('plantuml-encoder dependency required'); } renderedHTML = `<img src="${rendererURL}${plantumlEncoder.encode(umlCode)}" />`; } catch (err) { renderedHTML = `Error occurred on encoding uml: ${err.message}`; } return renderedHTML; } const {codeBlockLanguages} = editor.options; UML_LANGUAGES.forEach(umlLanguage => { if (codeBlockLanguages.indexOf(umlLanguage) < 0) { codeBlockLanguages.push(umlLanguage); } codeBlockManager.setReplacer(umlLanguage, plantUMLReplacer); }); }
[ "function", "umlExtension", "(", "editor", ",", "options", "=", "{", "}", ")", "{", "const", "{", "rendererURL", "=", "DEFAULT_RENDERER_URL", "}", "=", "options", ";", "function", "plantUMLReplacer", "(", "umlCode", ")", "{", "let", "renderedHTML", ";", "try", "{", "if", "(", "!", "plantumlEncoder", ")", "{", "throw", "new", "Error", "(", "'plantuml-encoder dependency required'", ")", ";", "}", "renderedHTML", "=", "`", "${", "rendererURL", "}", "${", "plantumlEncoder", ".", "encode", "(", "umlCode", ")", "}", "`", ";", "}", "catch", "(", "err", ")", "{", "renderedHTML", "=", "`", "${", "err", ".", "message", "}", "`", ";", "}", "return", "renderedHTML", ";", "}", "const", "{", "codeBlockLanguages", "}", "=", "editor", ".", "options", ";", "UML_LANGUAGES", ".", "forEach", "(", "umlLanguage", "=>", "{", "if", "(", "codeBlockLanguages", ".", "indexOf", "(", "umlLanguage", ")", "<", "0", ")", "{", "codeBlockLanguages", ".", "push", "(", "umlLanguage", ")", ";", "}", "codeBlockManager", ".", "setReplacer", "(", "umlLanguage", ",", "plantUMLReplacer", ")", ";", "}", ")", ";", "}" ]
plant uml plugin @param {Editor} editor - editor @param {object} [options={}] - plugin options @param {string} options.rendererURL - plant uml renderer url @ignore
[ "plant", "uml", "plugin" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/uml.js#L20-L52
train
nhn/tui.editor
src/js/extensions/uml.js
plantUMLReplacer
function plantUMLReplacer(umlCode) { let renderedHTML; try { if (!plantumlEncoder) { throw new Error('plantuml-encoder dependency required'); } renderedHTML = `<img src="${rendererURL}${plantumlEncoder.encode(umlCode)}" />`; } catch (err) { renderedHTML = `Error occurred on encoding uml: ${err.message}`; } return renderedHTML; }
javascript
function plantUMLReplacer(umlCode) { let renderedHTML; try { if (!plantumlEncoder) { throw new Error('plantuml-encoder dependency required'); } renderedHTML = `<img src="${rendererURL}${plantumlEncoder.encode(umlCode)}" />`; } catch (err) { renderedHTML = `Error occurred on encoding uml: ${err.message}`; } return renderedHTML; }
[ "function", "plantUMLReplacer", "(", "umlCode", ")", "{", "let", "renderedHTML", ";", "try", "{", "if", "(", "!", "plantumlEncoder", ")", "{", "throw", "new", "Error", "(", "'plantuml-encoder dependency required'", ")", ";", "}", "renderedHTML", "=", "`", "${", "rendererURL", "}", "${", "plantumlEncoder", ".", "encode", "(", "umlCode", ")", "}", "`", ";", "}", "catch", "(", "err", ")", "{", "renderedHTML", "=", "`", "${", "err", ".", "message", "}", "`", ";", "}", "return", "renderedHTML", ";", "}" ]
render html from uml @param {string} umlCode - plant uml code text @returns {string} - rendered html
[ "render", "html", "from", "uml" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/uml.js#L30-L43
train
nhn/tui.editor
src/js/extensions/table/mergedTableUI.js
_changeContent
function _changeContent(popupTableUtils) { const POPUP_CONTENT = [ `<button type="button" class="te-table-add-row">${i18n.get('Add row')}</button>`, `<button type="button" class="te-table-add-col">${i18n.get('Add col')}</button>`, `<button type="button" class="te-table-remove-row">${i18n.get('Remove row')}</button>`, `<button type="button" class="te-table-remove-col">${i18n.get('Remove col')}</button>`, '<hr/>', `<button type="button" class="te-table-merge">${i18n.get('Merge cells')}</button>`, `<button type="button" class="te-table-unmerge">${i18n.get('Unmerge cells')}</button>`, '<hr/>', `<button type="button" class="te-table-col-align-left">${i18n.get('Align left')}</button>`, `<button type="button" class="te-table-col-align-center">${i18n.get('Align center')}</button>`, `<button type="button" class="te-table-col-align-right">${i18n.get('Align right')}</button>`, '<hr/>', `<button type="button" class="te-table-remove">${i18n.get('Remove table')}</button>` ].join(''); const $popupContent = $(POPUP_CONTENT); popupTableUtils.setContent($popupContent); }
javascript
function _changeContent(popupTableUtils) { const POPUP_CONTENT = [ `<button type="button" class="te-table-add-row">${i18n.get('Add row')}</button>`, `<button type="button" class="te-table-add-col">${i18n.get('Add col')}</button>`, `<button type="button" class="te-table-remove-row">${i18n.get('Remove row')}</button>`, `<button type="button" class="te-table-remove-col">${i18n.get('Remove col')}</button>`, '<hr/>', `<button type="button" class="te-table-merge">${i18n.get('Merge cells')}</button>`, `<button type="button" class="te-table-unmerge">${i18n.get('Unmerge cells')}</button>`, '<hr/>', `<button type="button" class="te-table-col-align-left">${i18n.get('Align left')}</button>`, `<button type="button" class="te-table-col-align-center">${i18n.get('Align center')}</button>`, `<button type="button" class="te-table-col-align-right">${i18n.get('Align right')}</button>`, '<hr/>', `<button type="button" class="te-table-remove">${i18n.get('Remove table')}</button>` ].join(''); const $popupContent = $(POPUP_CONTENT); popupTableUtils.setContent($popupContent); }
[ "function", "_changeContent", "(", "popupTableUtils", ")", "{", "const", "POPUP_CONTENT", "=", "[", "`", "${", "i18n", ".", "get", "(", "'Add row'", ")", "}", "`", ",", "`", "${", "i18n", ".", "get", "(", "'Add col'", ")", "}", "`", ",", "`", "${", "i18n", ".", "get", "(", "'Remove row'", ")", "}", "`", ",", "`", "${", "i18n", ".", "get", "(", "'Remove col'", ")", "}", "`", ",", "'<hr/>'", ",", "`", "${", "i18n", ".", "get", "(", "'Merge cells'", ")", "}", "`", ",", "`", "${", "i18n", ".", "get", "(", "'Unmerge cells'", ")", "}", "`", ",", "'<hr/>'", ",", "`", "${", "i18n", ".", "get", "(", "'Align left'", ")", "}", "`", ",", "`", "${", "i18n", ".", "get", "(", "'Align center'", ")", "}", "`", ",", "`", "${", "i18n", ".", "get", "(", "'Align right'", ")", "}", "`", ",", "'<hr/>'", ",", "`", "${", "i18n", ".", "get", "(", "'Remove table'", ")", "}", "`", "]", ".", "join", "(", "''", ")", ";", "const", "$popupContent", "=", "$", "(", "POPUP_CONTENT", ")", ";", "popupTableUtils", ".", "setContent", "(", "$popupContent", ")", ";", "}" ]
Change contextmenu content. @param {object} popupTableUtils - PopupTableUtils instance for managing contextmenu of table @private
[ "Change", "contextmenu", "content", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/mergedTableUI.js#L15-L34
train
nhn/tui.editor
src/js/extensions/table/mergedTableUI.js
_bindEvents
function _bindEvents(popupTableUtils, eventManager, selectionManager) { const $popupContent = popupTableUtils.$content; const $mergeBtn = $($popupContent[5]); const $unmergeBtn = $($popupContent[6]); const $separator = $($popupContent[7]); popupTableUtils.on('click .te-table-merge', () => { eventManager.emit('command', 'MergeCells'); }); popupTableUtils.on('click .te-table-unmerge', () => { eventManager.emit('command', 'UnmergeCells'); }); eventManager.listen('openPopupTableUtils', () => { const $selectedCells = selectionManager.getSelectedCells(); const selectedCellCount = $selectedCells.length; if (selectedCellCount) { if (selectedCellCount < 2 || selectionManager.hasSelectedBothThAndTd($selectedCells)) { $mergeBtn.hide(); } else { $mergeBtn.show(); } if ($selectedCells.is('[rowspan], [colspan]')) { $unmergeBtn.show(); } else { $unmergeBtn.hide(); } $separator.show(); } else { $mergeBtn.hide(); $unmergeBtn.hide(); $separator.hide(); } }); }
javascript
function _bindEvents(popupTableUtils, eventManager, selectionManager) { const $popupContent = popupTableUtils.$content; const $mergeBtn = $($popupContent[5]); const $unmergeBtn = $($popupContent[6]); const $separator = $($popupContent[7]); popupTableUtils.on('click .te-table-merge', () => { eventManager.emit('command', 'MergeCells'); }); popupTableUtils.on('click .te-table-unmerge', () => { eventManager.emit('command', 'UnmergeCells'); }); eventManager.listen('openPopupTableUtils', () => { const $selectedCells = selectionManager.getSelectedCells(); const selectedCellCount = $selectedCells.length; if (selectedCellCount) { if (selectedCellCount < 2 || selectionManager.hasSelectedBothThAndTd($selectedCells)) { $mergeBtn.hide(); } else { $mergeBtn.show(); } if ($selectedCells.is('[rowspan], [colspan]')) { $unmergeBtn.show(); } else { $unmergeBtn.hide(); } $separator.show(); } else { $mergeBtn.hide(); $unmergeBtn.hide(); $separator.hide(); } }); }
[ "function", "_bindEvents", "(", "popupTableUtils", ",", "eventManager", ",", "selectionManager", ")", "{", "const", "$popupContent", "=", "popupTableUtils", ".", "$content", ";", "const", "$mergeBtn", "=", "$", "(", "$popupContent", "[", "5", "]", ")", ";", "const", "$unmergeBtn", "=", "$", "(", "$popupContent", "[", "6", "]", ")", ";", "const", "$separator", "=", "$", "(", "$popupContent", "[", "7", "]", ")", ";", "popupTableUtils", ".", "on", "(", "'click .te-table-merge'", ",", "(", ")", "=>", "{", "eventManager", ".", "emit", "(", "'command'", ",", "'MergeCells'", ")", ";", "}", ")", ";", "popupTableUtils", ".", "on", "(", "'click .te-table-unmerge'", ",", "(", ")", "=>", "{", "eventManager", ".", "emit", "(", "'command'", ",", "'UnmergeCells'", ")", ";", "}", ")", ";", "eventManager", ".", "listen", "(", "'openPopupTableUtils'", ",", "(", ")", "=>", "{", "const", "$selectedCells", "=", "selectionManager", ".", "getSelectedCells", "(", ")", ";", "const", "selectedCellCount", "=", "$selectedCells", ".", "length", ";", "if", "(", "selectedCellCount", ")", "{", "if", "(", "selectedCellCount", "<", "2", "||", "selectionManager", ".", "hasSelectedBothThAndTd", "(", "$selectedCells", ")", ")", "{", "$mergeBtn", ".", "hide", "(", ")", ";", "}", "else", "{", "$mergeBtn", ".", "show", "(", ")", ";", "}", "if", "(", "$selectedCells", ".", "is", "(", "'[rowspan], [colspan]'", ")", ")", "{", "$unmergeBtn", ".", "show", "(", ")", ";", "}", "else", "{", "$unmergeBtn", ".", "hide", "(", ")", ";", "}", "$separator", ".", "show", "(", ")", ";", "}", "else", "{", "$mergeBtn", ".", "hide", "(", ")", ";", "$unmergeBtn", ".", "hide", "(", ")", ";", "$separator", ".", "hide", "(", ")", ";", "}", "}", ")", ";", "}" ]
Bind events for merge feature of contextmenu. @param {object} popupTableUtils - PopupTableUtils instance for managing contextmenu of table @param {object} eventManager - event manager instance of editor @param {object} selectionManager - table selection manager instance @private
[ "Bind", "events", "for", "merge", "feature", "of", "contextmenu", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/mergedTableUI.js#L43-L80
train
nhn/tui.editor
src/js/extensions/table/mergedTableUI.js
updateContextMenu
function updateContextMenu(popupTableUtils, eventManager, selectionManager) { _changeContent(popupTableUtils); _bindEvents(popupTableUtils, eventManager, selectionManager); }
javascript
function updateContextMenu(popupTableUtils, eventManager, selectionManager) { _changeContent(popupTableUtils); _bindEvents(popupTableUtils, eventManager, selectionManager); }
[ "function", "updateContextMenu", "(", "popupTableUtils", ",", "eventManager", ",", "selectionManager", ")", "{", "_changeContent", "(", "popupTableUtils", ")", ";", "_bindEvents", "(", "popupTableUtils", ",", "eventManager", ",", "selectionManager", ")", ";", "}" ]
Update contextmenu UI. @param {object} popupTableUtils - PopupTableUtils instance for managing contextmenu of table @param {object} eventManager - event manager instance of editor @param {object} selectionManager - table selection manager instance @ignore
[ "Update", "contextmenu", "UI", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/mergedTableUI.js#L89-L92
train
nhn/tui.editor
src/js/extensions/table/mergedTableAlignCol.js
_align
function _align(headRowData, startColIndex, endColIndex, alignDirection) { util.range(startColIndex, endColIndex + 1).forEach(colIndex => { const headCellData = headRowData[colIndex]; if (util.isExisty(headCellData.colMergeWith)) { headRowData[headCellData.colMergeWith].align = alignDirection; } else { headCellData.align = alignDirection; } }); }
javascript
function _align(headRowData, startColIndex, endColIndex, alignDirection) { util.range(startColIndex, endColIndex + 1).forEach(colIndex => { const headCellData = headRowData[colIndex]; if (util.isExisty(headCellData.colMergeWith)) { headRowData[headCellData.colMergeWith].align = alignDirection; } else { headCellData.align = alignDirection; } }); }
[ "function", "_align", "(", "headRowData", ",", "startColIndex", ",", "endColIndex", ",", "alignDirection", ")", "{", "util", ".", "range", "(", "startColIndex", ",", "endColIndex", "+", "1", ")", ".", "forEach", "(", "colIndex", "=>", "{", "const", "headCellData", "=", "headRowData", "[", "colIndex", "]", ";", "if", "(", "util", ".", "isExisty", "(", "headCellData", ".", "colMergeWith", ")", ")", "{", "headRowData", "[", "headCellData", ".", "colMergeWith", "]", ".", "align", "=", "alignDirection", ";", "}", "else", "{", "headCellData", ".", "align", "=", "alignDirection", ";", "}", "}", ")", ";", "}" ]
Align to table header. @param {Array.<object>} headRowData - head row data @param {number} startColIndex - start column index for styling align @param {number} endColIndex - end column index for styling align @param {string} alignDirection - align direction @private
[ "Align", "to", "table", "header", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/mergedTableAlignCol.js#L58-L68
train
nhn/tui.editor
src/js/wysiwygCommands/codeBlock.js
focusToFirstCode
function focusToFirstCode($pre, wwe) { const range = wwe.getEditor().getSelection().cloneRange(); $pre.removeClass(CODEBLOCK_CLASS_TEMP); range.setStartBefore($pre.get(0).firstChild); range.collapse(true); wwe.getEditor().setSelection(range); }
javascript
function focusToFirstCode($pre, wwe) { const range = wwe.getEditor().getSelection().cloneRange(); $pre.removeClass(CODEBLOCK_CLASS_TEMP); range.setStartBefore($pre.get(0).firstChild); range.collapse(true); wwe.getEditor().setSelection(range); }
[ "function", "focusToFirstCode", "(", "$pre", ",", "wwe", ")", "{", "const", "range", "=", "wwe", ".", "getEditor", "(", ")", ".", "getSelection", "(", ")", ".", "cloneRange", "(", ")", ";", "$pre", ".", "removeClass", "(", "CODEBLOCK_CLASS_TEMP", ")", ";", "range", ".", "setStartBefore", "(", "$pre", ".", "get", "(", "0", ")", ".", "firstChild", ")", ";", "range", ".", "collapse", "(", "true", ")", ";", "wwe", ".", "getEditor", "(", ")", ".", "setSelection", "(", "range", ")", ";", "}" ]
focusToFirstCode Focus to first code tag content of pre tag @param {jQuery} $pre pre tag @param {WysiwygEditor} wwe wysiwygEditor
[ "focusToFirstCode", "Focus", "to", "first", "code", "tag", "content", "of", "pre", "tag" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/codeBlock.js#L54-L62
train
nhn/tui.editor
src/js/wysiwygCommands/codeBlock.js
getCodeBlockBody
function getCodeBlockBody(range, wwe) { const mgr = wwe.componentManager.getManager('codeblock'); let codeBlock; if (range.collapsed) { codeBlock = '<br>'; } else { const contents = range.extractContents(); const nodes = util.toArray(contents.childNodes); const tempDiv = $('<div>').append(mgr.prepareToPasteOnCodeblock(nodes)); codeBlock = tempDiv.html(); } return codeBlock; }
javascript
function getCodeBlockBody(range, wwe) { const mgr = wwe.componentManager.getManager('codeblock'); let codeBlock; if (range.collapsed) { codeBlock = '<br>'; } else { const contents = range.extractContents(); const nodes = util.toArray(contents.childNodes); const tempDiv = $('<div>').append(mgr.prepareToPasteOnCodeblock(nodes)); codeBlock = tempDiv.html(); } return codeBlock; }
[ "function", "getCodeBlockBody", "(", "range", ",", "wwe", ")", "{", "const", "mgr", "=", "wwe", ".", "componentManager", ".", "getManager", "(", "'codeblock'", ")", ";", "let", "codeBlock", ";", "if", "(", "range", ".", "collapsed", ")", "{", "codeBlock", "=", "'<br>'", ";", "}", "else", "{", "const", "contents", "=", "range", ".", "extractContents", "(", ")", ";", "const", "nodes", "=", "util", ".", "toArray", "(", "contents", ".", "childNodes", ")", ";", "const", "tempDiv", "=", "$", "(", "'<div>'", ")", ".", "append", "(", "mgr", ".", "prepareToPasteOnCodeblock", "(", "nodes", ")", ")", ";", "codeBlock", "=", "tempDiv", ".", "html", "(", ")", ";", "}", "return", "codeBlock", ";", "}" ]
getCodeBlockBody get text wrapped by code @param {object} range range object @param {object} wwe wysiwyg editor @returns {string}
[ "getCodeBlockBody", "get", "text", "wrapped", "by", "code" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/codeBlock.js#L70-L83
train
nhn/tui.editor
src/js/wwTableManager.js
tableCellGenerator
function tableCellGenerator(amount, tagName) { const brHTMLString = '<br />'; const cellString = `<${tagName}>${brHTMLString}</${tagName}>`; let tdString = ''; for (let i = 0; i < amount; i += 1) { tdString = tdString + cellString; } return tdString; }
javascript
function tableCellGenerator(amount, tagName) { const brHTMLString = '<br />'; const cellString = `<${tagName}>${brHTMLString}</${tagName}>`; let tdString = ''; for (let i = 0; i < amount; i += 1) { tdString = tdString + cellString; } return tdString; }
[ "function", "tableCellGenerator", "(", "amount", ",", "tagName", ")", "{", "const", "brHTMLString", "=", "'<br />'", ";", "const", "cellString", "=", "`", "${", "tagName", "}", "${", "brHTMLString", "}", "${", "tagName", "}", "`", ";", "let", "tdString", "=", "''", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "amount", ";", "i", "+=", "1", ")", "{", "tdString", "=", "tdString", "+", "cellString", ";", "}", "return", "tdString", ";", "}" ]
Generate table cell HTML text @param {number} amount Amount of cells @param {string} tagName Tag name of cell 'td' or 'th' @private @returns {string}
[ "Generate", "table", "cell", "HTML", "text" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wwTableManager.js#L1274-L1284
train
nhn/tui.editor
src/js/extensions/table/mergedTableCreator.js
_findIndex
function _findIndex(arr, onFind) { let foundIndex = -1; util.forEach(arr, (item, index) => { let nextFind = true; if (onFind(item, index)) { foundIndex = index; nextFind = false; } return nextFind; }); return foundIndex; }
javascript
function _findIndex(arr, onFind) { let foundIndex = -1; util.forEach(arr, (item, index) => { let nextFind = true; if (onFind(item, index)) { foundIndex = index; nextFind = false; } return nextFind; }); return foundIndex; }
[ "function", "_findIndex", "(", "arr", ",", "onFind", ")", "{", "let", "foundIndex", "=", "-", "1", ";", "util", ".", "forEach", "(", "arr", ",", "(", "item", ",", "index", ")", "=>", "{", "let", "nextFind", "=", "true", ";", "if", "(", "onFind", "(", "item", ",", "index", ")", ")", "{", "foundIndex", "=", "index", ";", "nextFind", "=", "false", ";", "}", "return", "nextFind", ";", "}", ")", ";", "return", "foundIndex", ";", "}" ]
Find index by onFind function. @param {Array} arr - target array @param {function} onFind - find function @returns {number} @private
[ "Find", "index", "by", "onFind", "function", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/mergedTableCreator.js#L80-L94
train
nhn/tui.editor
src/js/wysiwygCommands/table.js
focusToFirstTh
function focusToFirstTh(sq, $table) { const range = sq.getSelection(); range.selectNodeContents($table.find('th')[0]); range.collapse(true); sq.setSelection(range); }
javascript
function focusToFirstTh(sq, $table) { const range = sq.getSelection(); range.selectNodeContents($table.find('th')[0]); range.collapse(true); sq.setSelection(range); }
[ "function", "focusToFirstTh", "(", "sq", ",", "$table", ")", "{", "const", "range", "=", "sq", ".", "getSelection", "(", ")", ";", "range", ".", "selectNodeContents", "(", "$table", ".", "find", "(", "'th'", ")", "[", "0", "]", ")", ";", "range", ".", "collapse", "(", "true", ")", ";", "sq", ".", "setSelection", "(", "range", ")", ";", "}" ]
Focus to first th @param {Squire} sq Squire instance @param {jQuery} $table jQuery wrapped table element
[ "Focus", "to", "first", "th" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/table.js#L54-L60
train
nhn/tui.editor
src/js/wysiwygCommands/table.js
makeHeader
function makeHeader(col, data) { let header = '<thead><tr>'; let index = 0; while (col) { header += '<th>'; if (data) { header += data[index]; index += 1; } header += '</th>'; col -= 1; } header += '</tr></thead>'; return header; }
javascript
function makeHeader(col, data) { let header = '<thead><tr>'; let index = 0; while (col) { header += '<th>'; if (data) { header += data[index]; index += 1; } header += '</th>'; col -= 1; } header += '</tr></thead>'; return header; }
[ "function", "makeHeader", "(", "col", ",", "data", ")", "{", "let", "header", "=", "'<thead><tr>'", ";", "let", "index", "=", "0", ";", "while", "(", "col", ")", "{", "header", "+=", "'<th>'", ";", "if", "(", "data", ")", "{", "header", "+=", "data", "[", "index", "]", ";", "index", "+=", "1", ";", "}", "header", "+=", "'</th>'", ";", "col", "-=", "1", ";", "}", "header", "+=", "'</tr></thead>'", ";", "return", "header", ";", "}" ]
makeHeader make table header html string @param {number} col column count @param {string} data cell data @returns {string} html string
[ "makeHeader", "make", "table", "header", "html", "string" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/table.js#L69-L88
train
nhn/tui.editor
src/js/wysiwygCommands/table.js
makeBody
function makeBody(col, row, data) { let body = '<tbody>'; let index = col; for (let irow = 0; irow < row; irow += 1) { body += '<tr>'; for (let icol = 0; icol < col; icol += 1) { body += '<td>'; if (data) { body += data[index]; index += 1; } body += '</td>'; } body += '</tr>'; } body += '</tbody>'; return body; }
javascript
function makeBody(col, row, data) { let body = '<tbody>'; let index = col; for (let irow = 0; irow < row; irow += 1) { body += '<tr>'; for (let icol = 0; icol < col; icol += 1) { body += '<td>'; if (data) { body += data[index]; index += 1; } body += '</td>'; } body += '</tr>'; } body += '</tbody>'; return body; }
[ "function", "makeBody", "(", "col", ",", "row", ",", "data", ")", "{", "let", "body", "=", "'<tbody>'", ";", "let", "index", "=", "col", ";", "for", "(", "let", "irow", "=", "0", ";", "irow", "<", "row", ";", "irow", "+=", "1", ")", "{", "body", "+=", "'<tr>'", ";", "for", "(", "let", "icol", "=", "0", ";", "icol", "<", "col", ";", "icol", "+=", "1", ")", "{", "body", "+=", "'<td>'", ";", "if", "(", "data", ")", "{", "body", "+=", "data", "[", "index", "]", ";", "index", "+=", "1", ";", "}", "body", "+=", "'</td>'", ";", "}", "body", "+=", "'</tr>'", ";", "}", "body", "+=", "'</tbody>'", ";", "return", "body", ";", "}" ]
makeBody make table body html string @param {number} col column count @param {number} row row count @param {string} data cell data @returns {string} html string
[ "makeBody", "make", "table", "body", "html", "string" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/table.js#L98-L122
train
nhn/tui.editor
src/js/markdownCommands/heading.js
getHeadingMarkdown
function getHeadingMarkdown(text, size) { const foundedHeading = text.match(FIND_HEADING_RX); let heading = ''; do { heading += '#'; size -= 1; } while (size > 0); if (foundedHeading) { [, text] = text.split(foundedHeading[0]); } return `${heading} ${text}`; }
javascript
function getHeadingMarkdown(text, size) { const foundedHeading = text.match(FIND_HEADING_RX); let heading = ''; do { heading += '#'; size -= 1; } while (size > 0); if (foundedHeading) { [, text] = text.split(foundedHeading[0]); } return `${heading} ${text}`; }
[ "function", "getHeadingMarkdown", "(", "text", ",", "size", ")", "{", "const", "foundedHeading", "=", "text", ".", "match", "(", "FIND_HEADING_RX", ")", ";", "let", "heading", "=", "''", ";", "do", "{", "heading", "+=", "'#'", ";", "size", "-=", "1", ";", "}", "while", "(", "size", ">", "0", ")", ";", "if", "(", "foundedHeading", ")", "{", "[", ",", "text", "]", "=", "text", ".", "split", "(", "foundedHeading", "[", "0", "]", ")", ";", "}", "return", "`", "${", "heading", "}", "${", "text", "}", "`", ";", "}" ]
Get heading markdown @param {string} text Source test @param {number} size size @returns {string}
[ "Get", "heading", "markdown" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/markdownCommands/heading.js#L65-L79
train
nhn/tui.editor
src/js/extensions/chart/chart.js
parseCode2DataAndOptions
function parseCode2DataAndOptions(code, callback) { code = trimKeepingTabs(code); const [firstCode, secondCode] = code.split(/\n{2,}/); // try to parse first code block as `options` let options = parseCode2ChartOption(firstCode); const url = options && options.editorChart && options.editorChart.url; // if first code block is `options` and has `url` option, fetch data from url let dataAndOptions; if (util.isString(url)) { // url option provided // fetch data from url const success = dataCode => { dataAndOptions = _parseCode2DataAndOptions(dataCode, firstCode); callback(dataAndOptions); }; const fail = () => callback(null); $.get(url).done(success).fail(fail); } else { // else first block is `data` dataAndOptions = _parseCode2DataAndOptions(firstCode, secondCode); callback(dataAndOptions); } }
javascript
function parseCode2DataAndOptions(code, callback) { code = trimKeepingTabs(code); const [firstCode, secondCode] = code.split(/\n{2,}/); // try to parse first code block as `options` let options = parseCode2ChartOption(firstCode); const url = options && options.editorChart && options.editorChart.url; // if first code block is `options` and has `url` option, fetch data from url let dataAndOptions; if (util.isString(url)) { // url option provided // fetch data from url const success = dataCode => { dataAndOptions = _parseCode2DataAndOptions(dataCode, firstCode); callback(dataAndOptions); }; const fail = () => callback(null); $.get(url).done(success).fail(fail); } else { // else first block is `data` dataAndOptions = _parseCode2DataAndOptions(firstCode, secondCode); callback(dataAndOptions); } }
[ "function", "parseCode2DataAndOptions", "(", "code", ",", "callback", ")", "{", "code", "=", "trimKeepingTabs", "(", "code", ")", ";", "const", "[", "firstCode", ",", "secondCode", "]", "=", "code", ".", "split", "(", "/", "\\n{2,}", "/", ")", ";", "let", "options", "=", "parseCode2ChartOption", "(", "firstCode", ")", ";", "const", "url", "=", "options", "&&", "options", ".", "editorChart", "&&", "options", ".", "editorChart", ".", "url", ";", "let", "dataAndOptions", ";", "if", "(", "util", ".", "isString", "(", "url", ")", ")", "{", "const", "success", "=", "dataCode", "=>", "{", "dataAndOptions", "=", "_parseCode2DataAndOptions", "(", "dataCode", ",", "firstCode", ")", ";", "callback", "(", "dataAndOptions", ")", ";", "}", ";", "const", "fail", "=", "(", ")", "=>", "callback", "(", "null", ")", ";", "$", ".", "get", "(", "url", ")", ".", "done", "(", "success", ")", ".", "fail", "(", "fail", ")", ";", "}", "else", "{", "dataAndOptions", "=", "_parseCode2DataAndOptions", "(", "firstCode", ",", "secondCode", ")", ";", "callback", "(", "dataAndOptions", ")", ";", "}", "}" ]
parse data and options for tui.chart data format can be csv, tsv options format is colon separated keys & values @param {string} code - plain text format data & options @param {Function} callback - callback which provides json format data & options @ignore
[ "parse", "data", "and", "options", "for", "tui", ".", "chart", "data", "format", "can", "be", "csv", "tsv", "options", "format", "is", "colon", "separated", "keys", "&", "values" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/chart/chart.js#L67-L92
train
nhn/tui.editor
src/js/extensions/chart/chart.js
_parseCode2DataAndOptions
function _parseCode2DataAndOptions(dataCode, optionCode) { const data = parseDSV2ChartData(dataCode); const options = parseCode2ChartOption(optionCode); return { data, options }; }
javascript
function _parseCode2DataAndOptions(dataCode, optionCode) { const data = parseDSV2ChartData(dataCode); const options = parseCode2ChartOption(optionCode); return { data, options }; }
[ "function", "_parseCode2DataAndOptions", "(", "dataCode", ",", "optionCode", ")", "{", "const", "data", "=", "parseDSV2ChartData", "(", "dataCode", ")", ";", "const", "options", "=", "parseCode2ChartOption", "(", "optionCode", ")", ";", "return", "{", "data", ",", "options", "}", ";", "}" ]
parse codes to chart data & options Object @param {string} dataCode - code block containing chart data @param {string} optionCode - code block containing chart options @returns {Object} - tui.chart data & options @see https://nhn.github.io/tui.chart/latest/tui.chart.html @ignore
[ "parse", "codes", "to", "chart", "data", "&", "options", "Object" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/chart/chart.js#L102-L110
train
nhn/tui.editor
src/js/extensions/chart/chart.js
detectDelimiter
function detectDelimiter(code) { code = trimKeepingTabs(code); // chunk first max 10 lines to detect const chunk = code.split(REGEX_LINE_ENDING).slice(0, 10).join('\n'); // calc delta for each delimiters // then pick a delimiter having the minimum value delta return DSV_DELIMITERS.map(delimiter => ({ delimiter, delta: calcDSVDelta(chunk, delimiter) })).sort((a, b) => ( a.delta - b.delta ))[0].delimiter; }
javascript
function detectDelimiter(code) { code = trimKeepingTabs(code); // chunk first max 10 lines to detect const chunk = code.split(REGEX_LINE_ENDING).slice(0, 10).join('\n'); // calc delta for each delimiters // then pick a delimiter having the minimum value delta return DSV_DELIMITERS.map(delimiter => ({ delimiter, delta: calcDSVDelta(chunk, delimiter) })).sort((a, b) => ( a.delta - b.delta ))[0].delimiter; }
[ "function", "detectDelimiter", "(", "code", ")", "{", "code", "=", "trimKeepingTabs", "(", "code", ")", ";", "const", "chunk", "=", "code", ".", "split", "(", "REGEX_LINE_ENDING", ")", ".", "slice", "(", "0", ",", "10", ")", ".", "join", "(", "'\\n'", ")", ";", "\\n", "}" ]
detect delimiter the comma, tab, regex @param {string} code - code to detect delimiter @returns {string|RegExp} - detected delimiter @ignore
[ "detect", "delimiter", "the", "comma", "tab", "regex" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/chart/chart.js#L118-L132
train
nhn/tui.editor
src/js/extensions/chart/chart.js
parseDSV2ChartData
function parseDSV2ChartData(code, delimiter) { // trim all heading/trailing blank lines code = trimKeepingTabs(code); csv.COLUMN_SEPARATOR = delimiter || detectDelimiter(code); let dsv = csv.parse(code); // trim all values in 2D array dsv = dsv.map(arr => arr.map(val => val.trim())); // test a first row for legends. ['anything', '1', '2', '3'] === false, ['anything', 't1', '2', 't3'] === true const hasLegends = dsv[0].filter((v, i) => i > 0).reduce((hasNaN, item) => hasNaN || !isNumeric(item), false); const legends = hasLegends ? dsv.shift() : []; // test a first column for categories const hasCategories = dsv.slice(1).reduce((hasNaN, row) => hasNaN || !isNumeric(row[0]), false); const categories = hasCategories ? dsv.map(arr => arr.shift()) : []; if (hasCategories) { legends.shift(); } // transpose dsv, parse number // [['1','2','3'] [[1,4,7] // ['4','5','6'] => [2,5,8] // ['7','8','9']] [3,6,9]] dsv = dsv[0].map((t, i) => dsv.map(x => parseFloat(x[i]))); // make series const series = dsv.map((data, i) => hasLegends ? { name: legends[i], data } : { data }); return { categories, series }; }
javascript
function parseDSV2ChartData(code, delimiter) { // trim all heading/trailing blank lines code = trimKeepingTabs(code); csv.COLUMN_SEPARATOR = delimiter || detectDelimiter(code); let dsv = csv.parse(code); // trim all values in 2D array dsv = dsv.map(arr => arr.map(val => val.trim())); // test a first row for legends. ['anything', '1', '2', '3'] === false, ['anything', 't1', '2', 't3'] === true const hasLegends = dsv[0].filter((v, i) => i > 0).reduce((hasNaN, item) => hasNaN || !isNumeric(item), false); const legends = hasLegends ? dsv.shift() : []; // test a first column for categories const hasCategories = dsv.slice(1).reduce((hasNaN, row) => hasNaN || !isNumeric(row[0]), false); const categories = hasCategories ? dsv.map(arr => arr.shift()) : []; if (hasCategories) { legends.shift(); } // transpose dsv, parse number // [['1','2','3'] [[1,4,7] // ['4','5','6'] => [2,5,8] // ['7','8','9']] [3,6,9]] dsv = dsv[0].map((t, i) => dsv.map(x => parseFloat(x[i]))); // make series const series = dsv.map((data, i) => hasLegends ? { name: legends[i], data } : { data }); return { categories, series }; }
[ "function", "parseDSV2ChartData", "(", "code", ",", "delimiter", ")", "{", "code", "=", "trimKeepingTabs", "(", "code", ")", ";", "csv", ".", "COLUMN_SEPARATOR", "=", "delimiter", "||", "detectDelimiter", "(", "code", ")", ";", "let", "dsv", "=", "csv", ".", "parse", "(", "code", ")", ";", "dsv", "=", "dsv", ".", "map", "(", "arr", "=>", "arr", ".", "map", "(", "val", "=>", "val", ".", "trim", "(", ")", ")", ")", ";", "const", "hasLegends", "=", "dsv", "[", "0", "]", ".", "filter", "(", "(", "v", ",", "i", ")", "=>", "i", ">", "0", ")", ".", "reduce", "(", "(", "hasNaN", ",", "item", ")", "=>", "hasNaN", "||", "!", "isNumeric", "(", "item", ")", ",", "false", ")", ";", "const", "legends", "=", "hasLegends", "?", "dsv", ".", "shift", "(", ")", ":", "[", "]", ";", "const", "hasCategories", "=", "dsv", ".", "slice", "(", "1", ")", ".", "reduce", "(", "(", "hasNaN", ",", "row", ")", "=>", "hasNaN", "||", "!", "isNumeric", "(", "row", "[", "0", "]", ")", ",", "false", ")", ";", "const", "categories", "=", "hasCategories", "?", "dsv", ".", "map", "(", "arr", "=>", "arr", ".", "shift", "(", ")", ")", ":", "[", "]", ";", "if", "(", "hasCategories", ")", "{", "legends", ".", "shift", "(", ")", ";", "}", "dsv", "=", "dsv", "[", "0", "]", ".", "map", "(", "(", "t", ",", "i", ")", "=>", "dsv", ".", "map", "(", "x", "=>", "parseFloat", "(", "x", "[", "i", "]", ")", ")", ")", ";", "const", "series", "=", "dsv", ".", "map", "(", "(", "data", ",", "i", ")", "=>", "hasLegends", "?", "{", "name", ":", "legends", "[", "i", "]", ",", "data", "}", ":", "{", "data", "}", ")", ";", "return", "{", "categories", ",", "series", "}", ";", "}" ]
parse csv, tsv to chart data @param {string} code - data code @param {string|RegExp} delimiter - delimiter @returns {Object} - tui.chart data @see https://nhn.github.io/tui.chart/latest/tui.chart.html @ignore
[ "parse", "csv", "tsv", "to", "chart", "data" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/chart/chart.js#L177-L216
train
nhn/tui.editor
src/js/extensions/chart/chart.js
parseURL2ChartData
function parseURL2ChartData(url, callback) { const success = code => { const chartData = parseDSV2ChartData(code); callback(chartData); }; const fail = () => callback(null); $.get(url).done(success).fail(fail); }
javascript
function parseURL2ChartData(url, callback) { const success = code => { const chartData = parseDSV2ChartData(code); callback(chartData); }; const fail = () => callback(null); $.get(url).done(success).fail(fail); }
[ "function", "parseURL2ChartData", "(", "url", ",", "callback", ")", "{", "const", "success", "=", "code", "=>", "{", "const", "chartData", "=", "parseDSV2ChartData", "(", "code", ")", ";", "callback", "(", "chartData", ")", ";", "}", ";", "const", "fail", "=", "(", ")", "=>", "callback", "(", "null", ")", ";", "$", ".", "get", "(", "url", ")", ".", "done", "(", "success", ")", ".", "fail", "(", "fail", ")", ";", "}" ]
parse code from url @param {string} url - remote csv/tsv file url @param {Function} callback - callback function @ignore
[ "parse", "code", "from", "url" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/chart/chart.js#L224-L233
train
nhn/tui.editor
src/js/extensions/chart/chart.js
parseCode2ChartOption
function parseCode2ChartOption(optionCode) { const reservedKeys = ['type', 'url']; let options = {}; if (util.isUndefined(optionCode)) { return options; } const optionLines = optionCode.split(REGEX_LINE_ENDING); optionLines.forEach(line => { let [keyString, ...values] = line.split(OPTION_DELIMITER); let value = values.join(OPTION_DELIMITER); keyString = keyString.trim(); if (value.length === 0) { return; } try { value = JSON.parse(value.trim()); } catch (e) { value = value.trim(); } // parse keys let [...keys] = keyString.split('.'); let topKey = keys[0]; if (util.inArray(topKey, reservedKeys) >= 0) { // reserved keys for chart plugin option keys.unshift('editorChart'); } else if (keys.length === 1) { // short names for `chart` keys.unshift('chart'); } else if (topKey === 'x' || topKey === 'y') { // short-handed keys keys[0] = `${topKey}Axis`; } let option = options; for (let i = 0; i < keys.length; i += 1) { let key = keys[i]; option[key] = option[key] || (keys.length - 1 === i ? value : {}); option = option[key]; } }); return options; }
javascript
function parseCode2ChartOption(optionCode) { const reservedKeys = ['type', 'url']; let options = {}; if (util.isUndefined(optionCode)) { return options; } const optionLines = optionCode.split(REGEX_LINE_ENDING); optionLines.forEach(line => { let [keyString, ...values] = line.split(OPTION_DELIMITER); let value = values.join(OPTION_DELIMITER); keyString = keyString.trim(); if (value.length === 0) { return; } try { value = JSON.parse(value.trim()); } catch (e) { value = value.trim(); } // parse keys let [...keys] = keyString.split('.'); let topKey = keys[0]; if (util.inArray(topKey, reservedKeys) >= 0) { // reserved keys for chart plugin option keys.unshift('editorChart'); } else if (keys.length === 1) { // short names for `chart` keys.unshift('chart'); } else if (topKey === 'x' || topKey === 'y') { // short-handed keys keys[0] = `${topKey}Axis`; } let option = options; for (let i = 0; i < keys.length; i += 1) { let key = keys[i]; option[key] = option[key] || (keys.length - 1 === i ? value : {}); option = option[key]; } }); return options; }
[ "function", "parseCode2ChartOption", "(", "optionCode", ")", "{", "const", "reservedKeys", "=", "[", "'type'", ",", "'url'", "]", ";", "let", "options", "=", "{", "}", ";", "if", "(", "util", ".", "isUndefined", "(", "optionCode", ")", ")", "{", "return", "options", ";", "}", "const", "optionLines", "=", "optionCode", ".", "split", "(", "REGEX_LINE_ENDING", ")", ";", "optionLines", ".", "forEach", "(", "line", "=>", "{", "let", "[", "keyString", ",", "...", "values", "]", "=", "line", ".", "split", "(", "OPTION_DELIMITER", ")", ";", "let", "value", "=", "values", ".", "join", "(", "OPTION_DELIMITER", ")", ";", "keyString", "=", "keyString", ".", "trim", "(", ")", ";", "if", "(", "value", ".", "length", "===", "0", ")", "{", "return", ";", "}", "try", "{", "value", "=", "JSON", ".", "parse", "(", "value", ".", "trim", "(", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "value", "=", "value", ".", "trim", "(", ")", ";", "}", "let", "[", "...", "keys", "]", "=", "keyString", ".", "split", "(", "'.'", ")", ";", "let", "topKey", "=", "keys", "[", "0", "]", ";", "if", "(", "util", ".", "inArray", "(", "topKey", ",", "reservedKeys", ")", ">=", "0", ")", "{", "keys", ".", "unshift", "(", "'editorChart'", ")", ";", "}", "else", "if", "(", "keys", ".", "length", "===", "1", ")", "{", "keys", ".", "unshift", "(", "'chart'", ")", ";", "}", "else", "if", "(", "topKey", "===", "'x'", "||", "topKey", "===", "'y'", ")", "{", "keys", "[", "0", "]", "=", "`", "${", "topKey", "}", "`", ";", "}", "let", "option", "=", "options", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "+=", "1", ")", "{", "let", "key", "=", "keys", "[", "i", "]", ";", "option", "[", "key", "]", "=", "option", "[", "key", "]", "||", "(", "keys", ".", "length", "-", "1", "===", "i", "?", "value", ":", "{", "}", ")", ";", "option", "=", "option", "[", "key", "]", ";", "}", "}", ")", ";", "return", "options", ";", "}" ]
parse option code @param {string} optionCode - option code @returns {Object} - tui.chart option string @see https://nhn.github.io/tui.chart/latest/tui.chart.html @ignore
[ "parse", "option", "code" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/chart/chart.js#L242-L287
train
nhn/tui.editor
src/js/extensions/chart/chart.js
setDefaultOptions
function setDefaultOptions(chartOptions, extensionOptions, chartContainer) { // chart options scaffolding chartOptions = util.extend({ editorChart: {}, chart: {}, chartExportMenu: {}, usageStatistics: extensionOptions.usageStatistics }, chartOptions); // set default extension options extensionOptions = util.extend(DEFAULT_CHART_OPTIONS, extensionOptions); // determine width, height let {width, height} = chartOptions.chart; const isWidthUndefined = util.isUndefined(width); const isHeightUndefined = util.isUndefined(height); if (isWidthUndefined || isHeightUndefined) { // if no width or height specified, set width and height to container width const { width: containerWidth } = chartContainer.getBoundingClientRect(); width = isWidthUndefined ? extensionOptions.width : width; height = isHeightUndefined ? extensionOptions.height : height; width = width === 'auto' ? containerWidth : width; height = height === 'auto' ? containerWidth : height; } width = Math.min(extensionOptions.maxWidth, width); height = Math.min(extensionOptions.maxHeight, height); chartOptions.chart.width = Math.max(extensionOptions.minWidth, width); chartOptions.chart.height = Math.max(extensionOptions.minHeight, height); // default chart type chartOptions.editorChart.type = chartOptions.editorChart.type ? `${chartOptions.editorChart.type}Chart` : 'columnChart'; // default visibility of export menu chartOptions.chartExportMenu.visible = chartOptions.chartExportMenu.visible || false; return chartOptions; }
javascript
function setDefaultOptions(chartOptions, extensionOptions, chartContainer) { // chart options scaffolding chartOptions = util.extend({ editorChart: {}, chart: {}, chartExportMenu: {}, usageStatistics: extensionOptions.usageStatistics }, chartOptions); // set default extension options extensionOptions = util.extend(DEFAULT_CHART_OPTIONS, extensionOptions); // determine width, height let {width, height} = chartOptions.chart; const isWidthUndefined = util.isUndefined(width); const isHeightUndefined = util.isUndefined(height); if (isWidthUndefined || isHeightUndefined) { // if no width or height specified, set width and height to container width const { width: containerWidth } = chartContainer.getBoundingClientRect(); width = isWidthUndefined ? extensionOptions.width : width; height = isHeightUndefined ? extensionOptions.height : height; width = width === 'auto' ? containerWidth : width; height = height === 'auto' ? containerWidth : height; } width = Math.min(extensionOptions.maxWidth, width); height = Math.min(extensionOptions.maxHeight, height); chartOptions.chart.width = Math.max(extensionOptions.minWidth, width); chartOptions.chart.height = Math.max(extensionOptions.minHeight, height); // default chart type chartOptions.editorChart.type = chartOptions.editorChart.type ? `${chartOptions.editorChart.type}Chart` : 'columnChart'; // default visibility of export menu chartOptions.chartExportMenu.visible = chartOptions.chartExportMenu.visible || false; return chartOptions; }
[ "function", "setDefaultOptions", "(", "chartOptions", ",", "extensionOptions", ",", "chartContainer", ")", "{", "chartOptions", "=", "util", ".", "extend", "(", "{", "editorChart", ":", "{", "}", ",", "chart", ":", "{", "}", ",", "chartExportMenu", ":", "{", "}", ",", "usageStatistics", ":", "extensionOptions", ".", "usageStatistics", "}", ",", "chartOptions", ")", ";", "extensionOptions", "=", "util", ".", "extend", "(", "DEFAULT_CHART_OPTIONS", ",", "extensionOptions", ")", ";", "let", "{", "width", ",", "height", "}", "=", "chartOptions", ".", "chart", ";", "const", "isWidthUndefined", "=", "util", ".", "isUndefined", "(", "width", ")", ";", "const", "isHeightUndefined", "=", "util", ".", "isUndefined", "(", "height", ")", ";", "if", "(", "isWidthUndefined", "||", "isHeightUndefined", ")", "{", "const", "{", "width", ":", "containerWidth", "}", "=", "chartContainer", ".", "getBoundingClientRect", "(", ")", ";", "width", "=", "isWidthUndefined", "?", "extensionOptions", ".", "width", ":", "width", ";", "height", "=", "isHeightUndefined", "?", "extensionOptions", ".", "height", ":", "height", ";", "width", "=", "width", "===", "'auto'", "?", "containerWidth", ":", "width", ";", "height", "=", "height", "===", "'auto'", "?", "containerWidth", ":", "height", ";", "}", "width", "=", "Math", ".", "min", "(", "extensionOptions", ".", "maxWidth", ",", "width", ")", ";", "height", "=", "Math", ".", "min", "(", "extensionOptions", ".", "maxHeight", ",", "height", ")", ";", "chartOptions", ".", "chart", ".", "width", "=", "Math", ".", "max", "(", "extensionOptions", ".", "minWidth", ",", "width", ")", ";", "chartOptions", ".", "chart", ".", "height", "=", "Math", ".", "max", "(", "extensionOptions", ".", "minHeight", ",", "height", ")", ";", "chartOptions", ".", "editorChart", ".", "type", "=", "chartOptions", ".", "editorChart", ".", "type", "?", "`", "${", "chartOptions", ".", "editorChart", ".", "type", "}", "`", ":", "'columnChart'", ";", "chartOptions", ".", "chartExportMenu", ".", "visible", "=", "chartOptions", ".", "chartExportMenu", ".", "visible", "||", "false", ";", "return", "chartOptions", ";", "}" ]
set default options @param {Object} chartOptions - tui.chart options @param {Object} extensionOptions - extension options @param {HTMLElement} chartContainer - chart container @returns {Object} - options @see https://nhn.github.io/tui.chart/latest/tui.chart.html @ignore
[ "set", "default", "options" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/chart/chart.js#L319-L357
train
nhn/tui.editor
src/js/extensions/chart/chart.js
chartReplacer
function chartReplacer(codeBlockChartDataAndOptions, extensionOptions) { const randomId = `chart-${Math.random().toString(36).substr(2, 10)}`; let renderedHTML = `<div id="${randomId}" class="chart" />`; setTimeout(() => { const chartContainer = document.querySelector(`#${randomId}`); try { parseCode2DataAndOptions(codeBlockChartDataAndOptions, ({data, options: chartOptions}) => { chartOptions = setDefaultOptions(chartOptions, extensionOptions, chartContainer); const chartType = chartOptions.editorChart.type; if (SUPPORTED_CHART_TYPES.indexOf(chartType) < 0) { chartContainer.innerHTML = `invalid chart type. type: bar, column, line, area, pie`; } else if (CATEGORY_CHART_TYPES.indexOf(chartType) > -1 && data.categories.length !== data.series[0].data.length) { chartContainer.innerHTML = 'invalid chart data'; } else { chart[chartType](chartContainer, data, chartOptions); } }); } catch (e) { chartContainer.innerHTML = 'invalid chart data'; } }, 0); return renderedHTML; }
javascript
function chartReplacer(codeBlockChartDataAndOptions, extensionOptions) { const randomId = `chart-${Math.random().toString(36).substr(2, 10)}`; let renderedHTML = `<div id="${randomId}" class="chart" />`; setTimeout(() => { const chartContainer = document.querySelector(`#${randomId}`); try { parseCode2DataAndOptions(codeBlockChartDataAndOptions, ({data, options: chartOptions}) => { chartOptions = setDefaultOptions(chartOptions, extensionOptions, chartContainer); const chartType = chartOptions.editorChart.type; if (SUPPORTED_CHART_TYPES.indexOf(chartType) < 0) { chartContainer.innerHTML = `invalid chart type. type: bar, column, line, area, pie`; } else if (CATEGORY_CHART_TYPES.indexOf(chartType) > -1 && data.categories.length !== data.series[0].data.length) { chartContainer.innerHTML = 'invalid chart data'; } else { chart[chartType](chartContainer, data, chartOptions); } }); } catch (e) { chartContainer.innerHTML = 'invalid chart data'; } }, 0); return renderedHTML; }
[ "function", "chartReplacer", "(", "codeBlockChartDataAndOptions", ",", "extensionOptions", ")", "{", "const", "randomId", "=", "`", "${", "Math", ".", "random", "(", ")", ".", "toString", "(", "36", ")", ".", "substr", "(", "2", ",", "10", ")", "}", "`", ";", "let", "renderedHTML", "=", "`", "${", "randomId", "}", "`", ";", "setTimeout", "(", "(", ")", "=>", "{", "const", "chartContainer", "=", "document", ".", "querySelector", "(", "`", "${", "randomId", "}", "`", ")", ";", "try", "{", "parseCode2DataAndOptions", "(", "codeBlockChartDataAndOptions", ",", "(", "{", "data", ",", "options", ":", "chartOptions", "}", ")", "=>", "{", "chartOptions", "=", "setDefaultOptions", "(", "chartOptions", ",", "extensionOptions", ",", "chartContainer", ")", ";", "const", "chartType", "=", "chartOptions", ".", "editorChart", ".", "type", ";", "if", "(", "SUPPORTED_CHART_TYPES", ".", "indexOf", "(", "chartType", ")", "<", "0", ")", "{", "chartContainer", ".", "innerHTML", "=", "`", "`", ";", "}", "else", "if", "(", "CATEGORY_CHART_TYPES", ".", "indexOf", "(", "chartType", ")", ">", "-", "1", "&&", "data", ".", "categories", ".", "length", "!==", "data", ".", "series", "[", "0", "]", ".", "data", ".", "length", ")", "{", "chartContainer", ".", "innerHTML", "=", "'invalid chart data'", ";", "}", "else", "{", "chart", "[", "chartType", "]", "(", "chartContainer", ",", "data", ",", "chartOptions", ")", ";", "}", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "chartContainer", ".", "innerHTML", "=", "'invalid chart data'", ";", "}", "}", ",", "0", ")", ";", "return", "renderedHTML", ";", "}" ]
replace html from chart data @param {string} codeBlockChartDataAndOptions - chart data text @param {Object} extensionOptions - chart extension options @returns {string} - rendered html @ignore
[ "replace", "html", "from", "chart", "data" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/chart/chart.js#L366-L392
train
nhn/tui.editor
src/js/extensions/chart/chart.js
_reduceToTSV
function _reduceToTSV(arr) { // 2D array => quoted TSV row array // [['a', 'b b'], [1, 2]] => ['a\t"b b"', '1\t2'] return arr.reduce((acc, row) => { // ['a', 'b b', 'c c'] => ['a', '"b b"', '"c c"'] const quoted = row.map(text => { if (!isNumeric(text) && text.indexOf(' ') >= 0) { text = `"${text}"`; } return text; }); // ['a', '"b b"', '"c c"'] => 'a\t"b b"\t"c c"' acc.push(quoted.join('\t')); return acc; }, []); }
javascript
function _reduceToTSV(arr) { // 2D array => quoted TSV row array // [['a', 'b b'], [1, 2]] => ['a\t"b b"', '1\t2'] return arr.reduce((acc, row) => { // ['a', 'b b', 'c c'] => ['a', '"b b"', '"c c"'] const quoted = row.map(text => { if (!isNumeric(text) && text.indexOf(' ') >= 0) { text = `"${text}"`; } return text; }); // ['a', '"b b"', '"c c"'] => 'a\t"b b"\t"c c"' acc.push(quoted.join('\t')); return acc; }, []); }
[ "function", "_reduceToTSV", "(", "arr", ")", "{", "return", "arr", ".", "reduce", "(", "(", "acc", ",", "row", ")", "=>", "{", "const", "quoted", "=", "row", ".", "map", "(", "text", "=>", "{", "if", "(", "!", "isNumeric", "(", "text", ")", "&&", "text", ".", "indexOf", "(", "' '", ")", ">=", "0", ")", "{", "text", "=", "`", "${", "text", "}", "`", ";", "}", "return", "text", ";", "}", ")", ";", "acc", ".", "push", "(", "quoted", ".", "join", "(", "'\\t'", ")", ")", ";", "\\t", "}", ",", "return", "acc", ";", ")", ";", "}" ]
reduce 2D array to TSV rows @param {Array.<Array.<string>>} arr - 2d array @returns {Array.<string>} - TSV row array @ignore
[ "reduce", "2D", "array", "to", "TSV", "rows" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/chart/chart.js#L400-L417
train
nhn/tui.editor
src/js/extensions/chart/chart.js
_setWwCodeBlockManagerForChart
function _setWwCodeBlockManagerForChart(editor) { const componentManager = editor.wwEditor.componentManager; componentManager.removeManager('codeblock'); componentManager.addManager(class extends WwCodeBlockManager { /** * Convert table nodes into code block as TSV * @memberof WwCodeBlockManager * @param {Array.<Node>} nodes Node array * @returns {HTMLElement} Code block element */ convertNodesToText(nodes) { if (nodes.length !== 1 || nodes[0].tagName !== 'TABLE') { return super.convertNodesToText(nodes); } const node = nodes.shift(); let str = ''; // convert table to 2-dim array const cells = [].slice.call(node.rows).map( row => [].slice.call(row.cells).map( cell => cell.innerText.trim() ) ); const tsvRows = _reduceToTSV(cells); str += tsvRows.reduce((acc, row) => acc + `${row}\n`, []); return str; } }); }
javascript
function _setWwCodeBlockManagerForChart(editor) { const componentManager = editor.wwEditor.componentManager; componentManager.removeManager('codeblock'); componentManager.addManager(class extends WwCodeBlockManager { /** * Convert table nodes into code block as TSV * @memberof WwCodeBlockManager * @param {Array.<Node>} nodes Node array * @returns {HTMLElement} Code block element */ convertNodesToText(nodes) { if (nodes.length !== 1 || nodes[0].tagName !== 'TABLE') { return super.convertNodesToText(nodes); } const node = nodes.shift(); let str = ''; // convert table to 2-dim array const cells = [].slice.call(node.rows).map( row => [].slice.call(row.cells).map( cell => cell.innerText.trim() ) ); const tsvRows = _reduceToTSV(cells); str += tsvRows.reduce((acc, row) => acc + `${row}\n`, []); return str; } }); }
[ "function", "_setWwCodeBlockManagerForChart", "(", "editor", ")", "{", "const", "componentManager", "=", "editor", ".", "wwEditor", ".", "componentManager", ";", "componentManager", ".", "removeManager", "(", "'codeblock'", ")", ";", "componentManager", ".", "addManager", "(", "class", "extends", "WwCodeBlockManager", "{", "convertNodesToText", "(", "nodes", ")", "{", "if", "(", "nodes", ".", "length", "!==", "1", "||", "nodes", "[", "0", "]", ".", "tagName", "!==", "'TABLE'", ")", "{", "return", "super", ".", "convertNodesToText", "(", "nodes", ")", ";", "}", "const", "node", "=", "nodes", ".", "shift", "(", ")", ";", "let", "str", "=", "''", ";", "const", "cells", "=", "[", "]", ".", "slice", ".", "call", "(", "node", ".", "rows", ")", ".", "map", "(", "row", "=>", "[", "]", ".", "slice", ".", "call", "(", "row", ".", "cells", ")", ".", "map", "(", "cell", "=>", "cell", ".", "innerText", ".", "trim", "(", ")", ")", ")", ";", "const", "tsvRows", "=", "_reduceToTSV", "(", "cells", ")", ";", "str", "+=", "tsvRows", ".", "reduce", "(", "(", "acc", ",", "row", ")", "=>", "acc", "+", "`", "${", "row", "}", "\\n", "`", ",", "[", "]", ")", ";", "return", "str", ";", "}", "}", ")", ";", "}" ]
override WwCodeBlockManager to enclose pasting data strings from wysiwyg in quotes @param {Editor} editor - editor @ignore
[ "override", "WwCodeBlockManager", "to", "enclose", "pasting", "data", "strings", "from", "wysiwyg", "in", "quotes" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/chart/chart.js#L424-L455
train
nhn/tui.editor
src/js/extensions/chart/chart.js
_onMDPasteBefore
function _onMDPasteBefore(cm, {source, data: eventData}) { if (!_isFromCodeBlockInCodeMirror(cm, source, eventData)) { return; } const code = eventData.text.join('\n'); const delta = calcDSVDelta(code, '\t'); if (delta === 0) { csv.COLUMN_SEPARATOR = '\t'; const parsed = _reduceToTSV(csv.parse(code)); eventData.update(eventData.from, eventData.to, parsed); } }
javascript
function _onMDPasteBefore(cm, {source, data: eventData}) { if (!_isFromCodeBlockInCodeMirror(cm, source, eventData)) { return; } const code = eventData.text.join('\n'); const delta = calcDSVDelta(code, '\t'); if (delta === 0) { csv.COLUMN_SEPARATOR = '\t'; const parsed = _reduceToTSV(csv.parse(code)); eventData.update(eventData.from, eventData.to, parsed); } }
[ "function", "_onMDPasteBefore", "(", "cm", ",", "{", "source", ",", "data", ":", "eventData", "}", ")", "{", "if", "(", "!", "_isFromCodeBlockInCodeMirror", "(", "cm", ",", "source", ",", "eventData", ")", ")", "{", "return", ";", "}", "const", "code", "=", "eventData", ".", "text", ".", "join", "(", "'\\n'", ")", ";", "\\n", "const", "delta", "=", "calcDSVDelta", "(", "code", ",", "'\\t'", ")", ";", "}" ]
enclose pasting data strings from markdown in quotes wysiwyg event should be treated separately. because pasteBefore event from wysiwyg has been already processed table data to string, on the other hand we need a table element @param {CodeMirror} cm - markdown codemirror editor @param {string} source - event source @param {Object} data - event data @ignore
[ "enclose", "pasting", "data", "strings", "from", "markdown", "in", "quotes", "wysiwyg", "event", "should", "be", "treated", "separately", ".", "because", "pasteBefore", "event", "from", "wysiwyg", "has", "been", "already", "processed", "table", "data", "to", "string", "on", "the", "other", "hand", "we", "need", "a", "table", "element" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/chart/chart.js#L486-L499
train
nhn/tui.editor
src/js/wysiwygCommands/tableAddRow.js
getSelectedRowsLength
function getSelectedRowsLength(wwe) { const selectionMgr = wwe.componentManager.getManager('tableSelection'); const $selectedCells = selectionMgr.getSelectedCells(); let length = 1; if ($selectedCells.length > 1) { const first = $selectedCells.first().get(0); const last = $selectedCells.last().get(0); const range = selectionMgr.getSelectionRangeFromTable(first, last); length = range.to.row - range.from.row + 1; } return length; }
javascript
function getSelectedRowsLength(wwe) { const selectionMgr = wwe.componentManager.getManager('tableSelection'); const $selectedCells = selectionMgr.getSelectedCells(); let length = 1; if ($selectedCells.length > 1) { const first = $selectedCells.first().get(0); const last = $selectedCells.last().get(0); const range = selectionMgr.getSelectionRangeFromTable(first, last); length = range.to.row - range.from.row + 1; } return length; }
[ "function", "getSelectedRowsLength", "(", "wwe", ")", "{", "const", "selectionMgr", "=", "wwe", ".", "componentManager", ".", "getManager", "(", "'tableSelection'", ")", ";", "const", "$selectedCells", "=", "selectionMgr", ".", "getSelectedCells", "(", ")", ";", "let", "length", "=", "1", ";", "if", "(", "$selectedCells", ".", "length", ">", "1", ")", "{", "const", "first", "=", "$selectedCells", ".", "first", "(", ")", ".", "get", "(", "0", ")", ";", "const", "last", "=", "$selectedCells", ".", "last", "(", ")", ".", "get", "(", "0", ")", ";", "const", "range", "=", "selectionMgr", ".", "getSelectionRangeFromTable", "(", "first", ",", "last", ")", ";", "length", "=", "range", ".", "to", ".", "row", "-", "range", ".", "from", ".", "row", "+", "1", ";", "}", "return", "length", ";", "}" ]
get number of selected rows @param {WysiwygEditor} wwe - wysiwygEditor instance @returns {number} - number of selected rows @ignore
[ "get", "number", "of", "selected", "rows" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableAddRow.js#L59-L72
train
nhn/tui.editor
src/js/wysiwygCommands/tableAddRow.js
getNewRow
function getNewRow($tr) { const cloned = $tr.clone(); const htmlString = util.browser.msie ? '' : '<br />'; cloned.find('td').html(htmlString); return cloned; }
javascript
function getNewRow($tr) { const cloned = $tr.clone(); const htmlString = util.browser.msie ? '' : '<br />'; cloned.find('td').html(htmlString); return cloned; }
[ "function", "getNewRow", "(", "$tr", ")", "{", "const", "cloned", "=", "$tr", ".", "clone", "(", ")", ";", "const", "htmlString", "=", "util", ".", "browser", ".", "msie", "?", "''", ":", "'<br />'", ";", "cloned", ".", "find", "(", "'td'", ")", ".", "html", "(", "htmlString", ")", ";", "return", "cloned", ";", "}" ]
Get new row of given row @param {jQuery} $tr - jQuery wrapped table row @returns {jQuery} - new cloned jquery element @ignore
[ "Get", "new", "row", "of", "given", "row" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableAddRow.js#L80-L87
train
nhn/tui.editor
src/js/htmlSanitizer.js
leaveOnlyWhitelistAttribute
function leaveOnlyWhitelistAttribute($html) { $html.find('*').each((index, node) => { const attrs = node.attributes; const blacklist = util.toArray(attrs).filter(attr => { const isHTMLAttr = attr.name.match(HTML_ATTR_LIST_RX); const isSVGAttr = attr.name.match(SVG_ATTR_LIST_RX); return !isHTMLAttr && !isSVGAttr; }); util.forEachArray(blacklist, attr => { // Edge svg attribute name returns uppercase bug. error guard. // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/5579311/ if (attrs.getNamedItem(attr.name)) { attrs.removeNamedItem(attr.name); } }); }); }
javascript
function leaveOnlyWhitelistAttribute($html) { $html.find('*').each((index, node) => { const attrs = node.attributes; const blacklist = util.toArray(attrs).filter(attr => { const isHTMLAttr = attr.name.match(HTML_ATTR_LIST_RX); const isSVGAttr = attr.name.match(SVG_ATTR_LIST_RX); return !isHTMLAttr && !isSVGAttr; }); util.forEachArray(blacklist, attr => { // Edge svg attribute name returns uppercase bug. error guard. // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/5579311/ if (attrs.getNamedItem(attr.name)) { attrs.removeNamedItem(attr.name); } }); }); }
[ "function", "leaveOnlyWhitelistAttribute", "(", "$html", ")", "{", "$html", ".", "find", "(", "'*'", ")", ".", "each", "(", "(", "index", ",", "node", ")", "=>", "{", "const", "attrs", "=", "node", ".", "attributes", ";", "const", "blacklist", "=", "util", ".", "toArray", "(", "attrs", ")", ".", "filter", "(", "attr", "=>", "{", "const", "isHTMLAttr", "=", "attr", ".", "name", ".", "match", "(", "HTML_ATTR_LIST_RX", ")", ";", "const", "isSVGAttr", "=", "attr", ".", "name", ".", "match", "(", "SVG_ATTR_LIST_RX", ")", ";", "return", "!", "isHTMLAttr", "&&", "!", "isSVGAttr", ";", "}", ")", ";", "util", ".", "forEachArray", "(", "blacklist", ",", "attr", "=>", "{", "if", "(", "attrs", ".", "getNamedItem", "(", "attr", ".", "name", ")", ")", "{", "attrs", ".", "removeNamedItem", "(", "attr", ".", "name", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Leave only white list attributes @private @param {jQuery} $html jQuery instance
[ "Leave", "only", "white", "list", "attributes" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/htmlSanitizer.js#L65-L83
train
nhn/tui.editor
src/js/htmlSanitizer.js
finalizeHtml
function finalizeHtml($html, needHtmlText) { let returnValue; if (needHtmlText) { returnValue = $html[0].innerHTML; } else { const frag = document.createDocumentFragment(); const childNodes = util.toArray($html[0].childNodes); const {length} = childNodes; for (let i = 0; i < length; i += 1) { frag.appendChild(childNodes[i]); } returnValue = frag; } return returnValue; }
javascript
function finalizeHtml($html, needHtmlText) { let returnValue; if (needHtmlText) { returnValue = $html[0].innerHTML; } else { const frag = document.createDocumentFragment(); const childNodes = util.toArray($html[0].childNodes); const {length} = childNodes; for (let i = 0; i < length; i += 1) { frag.appendChild(childNodes[i]); } returnValue = frag; } return returnValue; }
[ "function", "finalizeHtml", "(", "$html", ",", "needHtmlText", ")", "{", "let", "returnValue", ";", "if", "(", "needHtmlText", ")", "{", "returnValue", "=", "$html", "[", "0", "]", ".", "innerHTML", ";", "}", "else", "{", "const", "frag", "=", "document", ".", "createDocumentFragment", "(", ")", ";", "const", "childNodes", "=", "util", ".", "toArray", "(", "$html", "[", "0", "]", ".", "childNodes", ")", ";", "const", "{", "length", "}", "=", "childNodes", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "frag", ".", "appendChild", "(", "childNodes", "[", "i", "]", ")", ";", "}", "returnValue", "=", "frag", ";", "}", "return", "returnValue", ";", "}" ]
Finalize html result @private @param {jQuery} $html jQuery instance @param {boolean} needHtmlText pass true if need html text @returns {string|DocumentFragment} result
[ "Finalize", "html", "result" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/htmlSanitizer.js#L92-L109
train
nhn/tui.editor
src/js/extensions/table/tableRangeHandler.js
_findUnmergedRange
function _findUnmergedRange(tableData, $start, $end) { const cellIndexData = tableDataHandler.createCellIndexData(tableData); const startCellIndex = tableDataHandler.findCellIndex(cellIndexData, $start); const endCellIndex = tableDataHandler.findCellIndex(cellIndexData, $end); let startRowIndex, endRowIndex, startColIndex, endColIndex; if (startCellIndex.rowIndex > endCellIndex.rowIndex) { startRowIndex = endCellIndex.rowIndex; endRowIndex = startCellIndex.rowIndex; } else { startRowIndex = startCellIndex.rowIndex; endRowIndex = endCellIndex.rowIndex; } if (startCellIndex.colIndex > endCellIndex.colIndex) { startColIndex = endCellIndex.colIndex; endColIndex = startCellIndex.colIndex; } else { startColIndex = startCellIndex.colIndex; endColIndex = endCellIndex.colIndex; } return { start: { rowIndex: startRowIndex, colIndex: startColIndex }, end: { rowIndex: endRowIndex, colIndex: endColIndex } }; }
javascript
function _findUnmergedRange(tableData, $start, $end) { const cellIndexData = tableDataHandler.createCellIndexData(tableData); const startCellIndex = tableDataHandler.findCellIndex(cellIndexData, $start); const endCellIndex = tableDataHandler.findCellIndex(cellIndexData, $end); let startRowIndex, endRowIndex, startColIndex, endColIndex; if (startCellIndex.rowIndex > endCellIndex.rowIndex) { startRowIndex = endCellIndex.rowIndex; endRowIndex = startCellIndex.rowIndex; } else { startRowIndex = startCellIndex.rowIndex; endRowIndex = endCellIndex.rowIndex; } if (startCellIndex.colIndex > endCellIndex.colIndex) { startColIndex = endCellIndex.colIndex; endColIndex = startCellIndex.colIndex; } else { startColIndex = startCellIndex.colIndex; endColIndex = endCellIndex.colIndex; } return { start: { rowIndex: startRowIndex, colIndex: startColIndex }, end: { rowIndex: endRowIndex, colIndex: endColIndex } }; }
[ "function", "_findUnmergedRange", "(", "tableData", ",", "$start", ",", "$end", ")", "{", "const", "cellIndexData", "=", "tableDataHandler", ".", "createCellIndexData", "(", "tableData", ")", ";", "const", "startCellIndex", "=", "tableDataHandler", ".", "findCellIndex", "(", "cellIndexData", ",", "$start", ")", ";", "const", "endCellIndex", "=", "tableDataHandler", ".", "findCellIndex", "(", "cellIndexData", ",", "$end", ")", ";", "let", "startRowIndex", ",", "endRowIndex", ",", "startColIndex", ",", "endColIndex", ";", "if", "(", "startCellIndex", ".", "rowIndex", ">", "endCellIndex", ".", "rowIndex", ")", "{", "startRowIndex", "=", "endCellIndex", ".", "rowIndex", ";", "endRowIndex", "=", "startCellIndex", ".", "rowIndex", ";", "}", "else", "{", "startRowIndex", "=", "startCellIndex", ".", "rowIndex", ";", "endRowIndex", "=", "endCellIndex", ".", "rowIndex", ";", "}", "if", "(", "startCellIndex", ".", "colIndex", ">", "endCellIndex", ".", "colIndex", ")", "{", "startColIndex", "=", "endCellIndex", ".", "colIndex", ";", "endColIndex", "=", "startCellIndex", ".", "colIndex", ";", "}", "else", "{", "startColIndex", "=", "startCellIndex", ".", "colIndex", ";", "endColIndex", "=", "endCellIndex", ".", "colIndex", ";", "}", "return", "{", "start", ":", "{", "rowIndex", ":", "startRowIndex", ",", "colIndex", ":", "startColIndex", "}", ",", "end", ":", "{", "rowIndex", ":", "endRowIndex", ",", "colIndex", ":", "endColIndex", "}", "}", ";", "}" ]
Find unmerged table range. @param {Array.<Array.<object>>} tableData - table data @param {jQuery} $start - start talbe cell jQuery element @param {jQuery} $end - end table cell jQuery element @returns {{ start: {rowIndex: number, colIndex: number}, end: {rowIndex: number, colIndex: number} }} @private
[ "Find", "unmerged", "table", "range", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableRangeHandler.js#L21-L53
train
nhn/tui.editor
src/js/extensions/table/tableRangeHandler.js
_expandRowMergedRange
function _expandRowMergedRange(tableData, tableRange, rangeType) { const {rowIndex} = tableRange[rangeType]; const rowData = tableData[rowIndex]; util.range(tableRange.start.colIndex, tableRange.end.colIndex + 1).forEach(colIndex => { const cellData = rowData[colIndex]; const {rowMergeWith} = cellData; let lastRowMergedIndex = -1; if (util.isExisty(rowMergeWith)) { if (rowMergeWith < tableRange.start.rowIndex) { tableRange.start.rowIndex = rowMergeWith; } lastRowMergedIndex = rowMergeWith + tableData[rowMergeWith][colIndex].rowspan - 1; } else if (cellData.rowspan > 1) { lastRowMergedIndex = rowIndex + cellData.rowspan - 1; } if (lastRowMergedIndex > tableRange.end.rowIndex) { tableRange.end.rowIndex = lastRowMergedIndex; } }); }
javascript
function _expandRowMergedRange(tableData, tableRange, rangeType) { const {rowIndex} = tableRange[rangeType]; const rowData = tableData[rowIndex]; util.range(tableRange.start.colIndex, tableRange.end.colIndex + 1).forEach(colIndex => { const cellData = rowData[colIndex]; const {rowMergeWith} = cellData; let lastRowMergedIndex = -1; if (util.isExisty(rowMergeWith)) { if (rowMergeWith < tableRange.start.rowIndex) { tableRange.start.rowIndex = rowMergeWith; } lastRowMergedIndex = rowMergeWith + tableData[rowMergeWith][colIndex].rowspan - 1; } else if (cellData.rowspan > 1) { lastRowMergedIndex = rowIndex + cellData.rowspan - 1; } if (lastRowMergedIndex > tableRange.end.rowIndex) { tableRange.end.rowIndex = lastRowMergedIndex; } }); }
[ "function", "_expandRowMergedRange", "(", "tableData", ",", "tableRange", ",", "rangeType", ")", "{", "const", "{", "rowIndex", "}", "=", "tableRange", "[", "rangeType", "]", ";", "const", "rowData", "=", "tableData", "[", "rowIndex", "]", ";", "util", ".", "range", "(", "tableRange", ".", "start", ".", "colIndex", ",", "tableRange", ".", "end", ".", "colIndex", "+", "1", ")", ".", "forEach", "(", "colIndex", "=>", "{", "const", "cellData", "=", "rowData", "[", "colIndex", "]", ";", "const", "{", "rowMergeWith", "}", "=", "cellData", ";", "let", "lastRowMergedIndex", "=", "-", "1", ";", "if", "(", "util", ".", "isExisty", "(", "rowMergeWith", ")", ")", "{", "if", "(", "rowMergeWith", "<", "tableRange", ".", "start", ".", "rowIndex", ")", "{", "tableRange", ".", "start", ".", "rowIndex", "=", "rowMergeWith", ";", "}", "lastRowMergedIndex", "=", "rowMergeWith", "+", "tableData", "[", "rowMergeWith", "]", "[", "colIndex", "]", ".", "rowspan", "-", "1", ";", "}", "else", "if", "(", "cellData", ".", "rowspan", ">", "1", ")", "{", "lastRowMergedIndex", "=", "rowIndex", "+", "cellData", ".", "rowspan", "-", "1", ";", "}", "if", "(", "lastRowMergedIndex", ">", "tableRange", ".", "end", ".", "rowIndex", ")", "{", "tableRange", ".", "end", ".", "rowIndex", "=", "lastRowMergedIndex", ";", "}", "}", ")", ";", "}" ]
Expand table range by row merge properties like rowspan, rowMergeWith. @param {Array.<Array.<object>>} tableData - table data @param {{ start: {rowIndex: number, colIndex: number}, end: {rowIndex: number, colIndex: number} }} tableRange - table range @param {string} rangeType - range type like start, end @private
[ "Expand", "table", "range", "by", "row", "merge", "properties", "like", "rowspan", "rowMergeWith", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableRangeHandler.js#L65-L88
train
nhn/tui.editor
src/js/extensions/table/tableRangeHandler.js
_expandColMergedRange
function _expandColMergedRange(tableData, tableRange, rowIndex, colIndex) { const rowData = tableData[rowIndex]; const cellData = rowData[colIndex]; const {colMergeWith} = cellData; let lastColMergedIndex = -1; if (util.isExisty(colMergeWith)) { if (colMergeWith < tableRange.start.colIndex) { tableRange.start.colIndex = colMergeWith; } lastColMergedIndex = colMergeWith + rowData[colMergeWith].colspan - 1; } else if (cellData.colspan > 1) { lastColMergedIndex = colIndex + cellData.colspan - 1; } if (lastColMergedIndex > tableRange.end.colIndex) { tableRange.end.colIndex = lastColMergedIndex; } }
javascript
function _expandColMergedRange(tableData, tableRange, rowIndex, colIndex) { const rowData = tableData[rowIndex]; const cellData = rowData[colIndex]; const {colMergeWith} = cellData; let lastColMergedIndex = -1; if (util.isExisty(colMergeWith)) { if (colMergeWith < tableRange.start.colIndex) { tableRange.start.colIndex = colMergeWith; } lastColMergedIndex = colMergeWith + rowData[colMergeWith].colspan - 1; } else if (cellData.colspan > 1) { lastColMergedIndex = colIndex + cellData.colspan - 1; } if (lastColMergedIndex > tableRange.end.colIndex) { tableRange.end.colIndex = lastColMergedIndex; } }
[ "function", "_expandColMergedRange", "(", "tableData", ",", "tableRange", ",", "rowIndex", ",", "colIndex", ")", "{", "const", "rowData", "=", "tableData", "[", "rowIndex", "]", ";", "const", "cellData", "=", "rowData", "[", "colIndex", "]", ";", "const", "{", "colMergeWith", "}", "=", "cellData", ";", "let", "lastColMergedIndex", "=", "-", "1", ";", "if", "(", "util", ".", "isExisty", "(", "colMergeWith", ")", ")", "{", "if", "(", "colMergeWith", "<", "tableRange", ".", "start", ".", "colIndex", ")", "{", "tableRange", ".", "start", ".", "colIndex", "=", "colMergeWith", ";", "}", "lastColMergedIndex", "=", "colMergeWith", "+", "rowData", "[", "colMergeWith", "]", ".", "colspan", "-", "1", ";", "}", "else", "if", "(", "cellData", ".", "colspan", ">", "1", ")", "{", "lastColMergedIndex", "=", "colIndex", "+", "cellData", ".", "colspan", "-", "1", ";", "}", "if", "(", "lastColMergedIndex", ">", "tableRange", ".", "end", ".", "colIndex", ")", "{", "tableRange", ".", "end", ".", "colIndex", "=", "lastColMergedIndex", ";", "}", "}" ]
Expand table range by column merge properties like colspan, colMergeWith. @param {Array.<Array.<object>>} tableData - table data @param {{ start: {rowIndex: number, colIndex: number}, end: {rowIndex: number, colIndex: number} }} tableRange - table range @param {number} rowIndex - row index @param {number} colIndex - column index @private
[ "Expand", "table", "range", "by", "column", "merge", "properties", "like", "colspan", "colMergeWith", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableRangeHandler.js#L101-L120
train
nhn/tui.editor
src/js/extensions/table/tableRangeHandler.js
_expandMergedRange
function _expandMergedRange(tableData, tableRange) { let rangeStr = ''; while (rangeStr !== JSON.stringify(tableRange)) { rangeStr = JSON.stringify(tableRange); _expandRowMergedRange(tableData, tableRange, 'start'); _expandRowMergedRange(tableData, tableRange, 'end'); util.range(tableRange.start.rowIndex, tableRange.end.rowIndex + 1).forEach(rowIndex => { _expandColMergedRange(tableData, tableRange, rowIndex, tableRange.start.colIndex); _expandColMergedRange(tableData, tableRange, rowIndex, tableRange.end.colIndex); }); } return tableRange; }
javascript
function _expandMergedRange(tableData, tableRange) { let rangeStr = ''; while (rangeStr !== JSON.stringify(tableRange)) { rangeStr = JSON.stringify(tableRange); _expandRowMergedRange(tableData, tableRange, 'start'); _expandRowMergedRange(tableData, tableRange, 'end'); util.range(tableRange.start.rowIndex, tableRange.end.rowIndex + 1).forEach(rowIndex => { _expandColMergedRange(tableData, tableRange, rowIndex, tableRange.start.colIndex); _expandColMergedRange(tableData, tableRange, rowIndex, tableRange.end.colIndex); }); } return tableRange; }
[ "function", "_expandMergedRange", "(", "tableData", ",", "tableRange", ")", "{", "let", "rangeStr", "=", "''", ";", "while", "(", "rangeStr", "!==", "JSON", ".", "stringify", "(", "tableRange", ")", ")", "{", "rangeStr", "=", "JSON", ".", "stringify", "(", "tableRange", ")", ";", "_expandRowMergedRange", "(", "tableData", ",", "tableRange", ",", "'start'", ")", ";", "_expandRowMergedRange", "(", "tableData", ",", "tableRange", ",", "'end'", ")", ";", "util", ".", "range", "(", "tableRange", ".", "start", ".", "rowIndex", ",", "tableRange", ".", "end", ".", "rowIndex", "+", "1", ")", ".", "forEach", "(", "rowIndex", "=>", "{", "_expandColMergedRange", "(", "tableData", ",", "tableRange", ",", "rowIndex", ",", "tableRange", ".", "start", ".", "colIndex", ")", ";", "_expandColMergedRange", "(", "tableData", ",", "tableRange", ",", "rowIndex", ",", "tableRange", ".", "end", ".", "colIndex", ")", ";", "}", ")", ";", "}", "return", "tableRange", ";", "}" ]
Expand table range by merge properties like colspan, rowspan. @param {Array.<Array.<object>>} tableData - table data @param {{ start: {rowIndex: number, colIndex: number}, end: {rowIndex: number, colIndex: number} }} tableRange - table range @returns {{ start: {rowIndex: number, colIndex: number}, end: {rowIndex: number, colIndex: number} }} @private
[ "Expand", "table", "range", "by", "merge", "properties", "like", "colspan", "rowspan", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableRangeHandler.js#L135-L151
train
nhn/tui.editor
src/js/extensions/table/tableRangeHandler.js
getTableSelectionRange
function getTableSelectionRange(tableData, $selectedCells, $startContainer) { const cellIndexData = tableDataHandler.createCellIndexData(tableData); const tableRange = {}; if ($selectedCells.length) { const startRange = tableDataHandler.findCellIndex(cellIndexData, $selectedCells.first()); const endRange = util.extend({}, startRange); $selectedCells.each((index, cell) => { const cellIndex = tableDataHandler.findCellIndex(cellIndexData, $(cell)); const cellData = tableData[cellIndex.rowIndex][cellIndex.colIndex]; const lastRowMergedIndex = cellIndex.rowIndex + cellData.rowspan - 1; const lastColMergedIndex = cellIndex.colIndex + cellData.colspan - 1; endRange.rowIndex = Math.max(endRange.rowIndex, lastRowMergedIndex); endRange.colIndex = Math.max(endRange.colIndex, lastColMergedIndex); }); tableRange.start = startRange; tableRange.end = endRange; } else { const cellIndex = tableDataHandler.findCellIndex(cellIndexData, $startContainer); tableRange.start = cellIndex; tableRange.end = util.extend({}, cellIndex); } return tableRange; }
javascript
function getTableSelectionRange(tableData, $selectedCells, $startContainer) { const cellIndexData = tableDataHandler.createCellIndexData(tableData); const tableRange = {}; if ($selectedCells.length) { const startRange = tableDataHandler.findCellIndex(cellIndexData, $selectedCells.first()); const endRange = util.extend({}, startRange); $selectedCells.each((index, cell) => { const cellIndex = tableDataHandler.findCellIndex(cellIndexData, $(cell)); const cellData = tableData[cellIndex.rowIndex][cellIndex.colIndex]; const lastRowMergedIndex = cellIndex.rowIndex + cellData.rowspan - 1; const lastColMergedIndex = cellIndex.colIndex + cellData.colspan - 1; endRange.rowIndex = Math.max(endRange.rowIndex, lastRowMergedIndex); endRange.colIndex = Math.max(endRange.colIndex, lastColMergedIndex); }); tableRange.start = startRange; tableRange.end = endRange; } else { const cellIndex = tableDataHandler.findCellIndex(cellIndexData, $startContainer); tableRange.start = cellIndex; tableRange.end = util.extend({}, cellIndex); } return tableRange; }
[ "function", "getTableSelectionRange", "(", "tableData", ",", "$selectedCells", ",", "$startContainer", ")", "{", "const", "cellIndexData", "=", "tableDataHandler", ".", "createCellIndexData", "(", "tableData", ")", ";", "const", "tableRange", "=", "{", "}", ";", "if", "(", "$selectedCells", ".", "length", ")", "{", "const", "startRange", "=", "tableDataHandler", ".", "findCellIndex", "(", "cellIndexData", ",", "$selectedCells", ".", "first", "(", ")", ")", ";", "const", "endRange", "=", "util", ".", "extend", "(", "{", "}", ",", "startRange", ")", ";", "$selectedCells", ".", "each", "(", "(", "index", ",", "cell", ")", "=>", "{", "const", "cellIndex", "=", "tableDataHandler", ".", "findCellIndex", "(", "cellIndexData", ",", "$", "(", "cell", ")", ")", ";", "const", "cellData", "=", "tableData", "[", "cellIndex", ".", "rowIndex", "]", "[", "cellIndex", ".", "colIndex", "]", ";", "const", "lastRowMergedIndex", "=", "cellIndex", ".", "rowIndex", "+", "cellData", ".", "rowspan", "-", "1", ";", "const", "lastColMergedIndex", "=", "cellIndex", ".", "colIndex", "+", "cellData", ".", "colspan", "-", "1", ";", "endRange", ".", "rowIndex", "=", "Math", ".", "max", "(", "endRange", ".", "rowIndex", ",", "lastRowMergedIndex", ")", ";", "endRange", ".", "colIndex", "=", "Math", ".", "max", "(", "endRange", ".", "colIndex", ",", "lastColMergedIndex", ")", ";", "}", ")", ";", "tableRange", ".", "start", "=", "startRange", ";", "tableRange", ".", "end", "=", "endRange", ";", "}", "else", "{", "const", "cellIndex", "=", "tableDataHandler", ".", "findCellIndex", "(", "cellIndexData", ",", "$startContainer", ")", ";", "tableRange", ".", "start", "=", "cellIndex", ";", "tableRange", ".", "end", "=", "util", ".", "extend", "(", "{", "}", ",", "cellIndex", ")", ";", "}", "return", "tableRange", ";", "}" ]
Get table selection range. @param {Array.<Array.<object>>} tableData - table data @param {jQuery} $selectedCells - selected cells jQuery elements @param {jQuery} $startContainer - start container jQuery element of text range @returns {{ start: {rowIndex: number, colIndex: number}, end: {rowIndex: number, colIndex: number} }} @ignore
[ "Get", "table", "selection", "range", "." ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/table/tableRangeHandler.js#L181-L209
train
nhn/tui.editor
src/js/wysiwygCommands/tableAlignCol.js
setAlignAttributeToTableCells
function setAlignAttributeToTableCells($table, alignDirection, selectionInformation) { const isDivided = selectionInformation.isDivided || false; const start = selectionInformation.startColumnIndex; const end = selectionInformation.endColumnIndex; const columnLength = $table.find('tr').eq(0).find('td,th').length; $table.find('tr').each((n, tr) => { $(tr).children('td,th').each((index, cell) => { if (isDivided && ((start <= index && index <= columnLength) || (index <= end)) ) { $(cell).attr('align', alignDirection); } else if ((start <= index && index <= end)) { $(cell).attr('align', alignDirection); } }); }); }
javascript
function setAlignAttributeToTableCells($table, alignDirection, selectionInformation) { const isDivided = selectionInformation.isDivided || false; const start = selectionInformation.startColumnIndex; const end = selectionInformation.endColumnIndex; const columnLength = $table.find('tr').eq(0).find('td,th').length; $table.find('tr').each((n, tr) => { $(tr).children('td,th').each((index, cell) => { if (isDivided && ((start <= index && index <= columnLength) || (index <= end)) ) { $(cell).attr('align', alignDirection); } else if ((start <= index && index <= end)) { $(cell).attr('align', alignDirection); } }); }); }
[ "function", "setAlignAttributeToTableCells", "(", "$table", ",", "alignDirection", ",", "selectionInformation", ")", "{", "const", "isDivided", "=", "selectionInformation", ".", "isDivided", "||", "false", ";", "const", "start", "=", "selectionInformation", ".", "startColumnIndex", ";", "const", "end", "=", "selectionInformation", ".", "endColumnIndex", ";", "const", "columnLength", "=", "$table", ".", "find", "(", "'tr'", ")", ".", "eq", "(", "0", ")", ".", "find", "(", "'td,th'", ")", ".", "length", ";", "$table", ".", "find", "(", "'tr'", ")", ".", "each", "(", "(", "n", ",", "tr", ")", "=>", "{", "$", "(", "tr", ")", ".", "children", "(", "'td,th'", ")", ".", "each", "(", "(", "index", ",", "cell", ")", "=>", "{", "if", "(", "isDivided", "&&", "(", "(", "start", "<=", "index", "&&", "index", "<=", "columnLength", ")", "||", "(", "index", "<=", "end", ")", ")", ")", "{", "$", "(", "cell", ")", ".", "attr", "(", "'align'", ",", "alignDirection", ")", ";", "}", "else", "if", "(", "(", "start", "<=", "index", "&&", "index", "<=", "end", ")", ")", "{", "$", "(", "cell", ")", ".", "attr", "(", "'align'", ",", "alignDirection", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Set Column align @param {jQuery} $table jQuery wrapped TABLE @param {string} alignDirection 'left' or 'center' or 'right' @param {{ startColumnIndex: number, endColumnIndex: number, isDivided: boolean }} selectionInformation start, end column index and boolean value for whether range divided or not
[ "Set", "Column", "align" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableAlignCol.js#L55-L72
train
nhn/tui.editor
src/js/wysiwygCommands/tableAlignCol.js
getSelectionInformation
function getSelectionInformation($table, rangeInformation) { const columnLength = $table.find('tr').eq(0).find('td,th').length; const { from, to } = rangeInformation; let startColumnIndex, endColumnIndex, isDivided; if (from.row === to.row) { startColumnIndex = from.cell; endColumnIndex = to.cell; } else if (from.row < to.row) { if (from.cell <= to.cell) { startColumnIndex = 0; endColumnIndex = columnLength - 1; } else { startColumnIndex = from.cell; endColumnIndex = to.cell; isDivided = true; } } return { startColumnIndex, endColumnIndex, isDivided }; }
javascript
function getSelectionInformation($table, rangeInformation) { const columnLength = $table.find('tr').eq(0).find('td,th').length; const { from, to } = rangeInformation; let startColumnIndex, endColumnIndex, isDivided; if (from.row === to.row) { startColumnIndex = from.cell; endColumnIndex = to.cell; } else if (from.row < to.row) { if (from.cell <= to.cell) { startColumnIndex = 0; endColumnIndex = columnLength - 1; } else { startColumnIndex = from.cell; endColumnIndex = to.cell; isDivided = true; } } return { startColumnIndex, endColumnIndex, isDivided }; }
[ "function", "getSelectionInformation", "(", "$table", ",", "rangeInformation", ")", "{", "const", "columnLength", "=", "$table", ".", "find", "(", "'tr'", ")", ".", "eq", "(", "0", ")", ".", "find", "(", "'td,th'", ")", ".", "length", ";", "const", "{", "from", ",", "to", "}", "=", "rangeInformation", ";", "let", "startColumnIndex", ",", "endColumnIndex", ",", "isDivided", ";", "if", "(", "from", ".", "row", "===", "to", ".", "row", ")", "{", "startColumnIndex", "=", "from", ".", "cell", ";", "endColumnIndex", "=", "to", ".", "cell", ";", "}", "else", "if", "(", "from", ".", "row", "<", "to", ".", "row", ")", "{", "if", "(", "from", ".", "cell", "<=", "to", ".", "cell", ")", "{", "startColumnIndex", "=", "0", ";", "endColumnIndex", "=", "columnLength", "-", "1", ";", "}", "else", "{", "startColumnIndex", "=", "from", ".", "cell", ";", "endColumnIndex", "=", "to", ".", "cell", ";", "isDivided", "=", "true", ";", "}", "}", "return", "{", "startColumnIndex", ",", "endColumnIndex", ",", "isDivided", "}", ";", "}" ]
Return start, end column index and boolean value for whether range divided or not @param {jQuery} $table jQuery wrapped TABLE @param {{startColumnIndex: number, endColumnIndex: number}} rangeInformation Range information @returns {{startColumnIndex: number, endColumnIndex: number, isDivided: boolean}}
[ "Return", "start", "end", "column", "index", "and", "boolean", "value", "for", "whether", "range", "divided", "or", "not" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableAlignCol.js#L80-L107
train
nhn/tui.editor
src/js/wysiwygCommands/tableAlignCol.js
getRangeInformation
function getRangeInformation(range, selectionMgr) { const $selectedCells = selectionMgr.getSelectedCells(); let rangeInformation, startCell; if ($selectedCells.length) { rangeInformation = selectionMgr.getSelectionRangeFromTable($selectedCells.first().get(0), $selectedCells.last().get(0)); } else { const {startContainer} = range; startCell = domUtil.isTextNode(startContainer) ? $(startContainer).parent('td,th')[0] : startContainer; rangeInformation = selectionMgr.getSelectionRangeFromTable(startCell, startCell); } return rangeInformation; }
javascript
function getRangeInformation(range, selectionMgr) { const $selectedCells = selectionMgr.getSelectedCells(); let rangeInformation, startCell; if ($selectedCells.length) { rangeInformation = selectionMgr.getSelectionRangeFromTable($selectedCells.first().get(0), $selectedCells.last().get(0)); } else { const {startContainer} = range; startCell = domUtil.isTextNode(startContainer) ? $(startContainer).parent('td,th')[0] : startContainer; rangeInformation = selectionMgr.getSelectionRangeFromTable(startCell, startCell); } return rangeInformation; }
[ "function", "getRangeInformation", "(", "range", ",", "selectionMgr", ")", "{", "const", "$selectedCells", "=", "selectionMgr", ".", "getSelectedCells", "(", ")", ";", "let", "rangeInformation", ",", "startCell", ";", "if", "(", "$selectedCells", ".", "length", ")", "{", "rangeInformation", "=", "selectionMgr", ".", "getSelectionRangeFromTable", "(", "$selectedCells", ".", "first", "(", ")", ".", "get", "(", "0", ")", ",", "$selectedCells", ".", "last", "(", ")", ".", "get", "(", "0", ")", ")", ";", "}", "else", "{", "const", "{", "startContainer", "}", "=", "range", ";", "startCell", "=", "domUtil", ".", "isTextNode", "(", "startContainer", ")", "?", "$", "(", "startContainer", ")", ".", "parent", "(", "'td,th'", ")", "[", "0", "]", ":", "startContainer", ";", "rangeInformation", "=", "selectionMgr", ".", "getSelectionRangeFromTable", "(", "startCell", ",", "startCell", ")", ";", "}", "return", "rangeInformation", ";", "}" ]
Get range information @param {Range} range Range object @param {object} selectionMgr Table selection manager @returns {object}
[ "Get", "range", "information" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/wysiwygCommands/tableAlignCol.js#L115-L129
train
nhn/tui.editor
src/js/extensions/taskCounter.js
taskCounterExtension
function taskCounterExtension(editor) { editor.getTaskCount = () => { let found, count; if (editor.isViewer()) { count = editor.preview.$el.find('.task-list-item').length; } else if (editor.isMarkdownMode()) { found = editor.mdEditor.getValue().match(FIND_TASK_RX); count = found ? found.length : 0; } else { count = editor.wwEditor.get$Body().find('.task-list-item').length; } return count; }; editor.getCheckedTaskCount = () => { let found, count; if (editor.isViewer()) { count = editor.preview.$el.find('.task-list-item.checked').length; } else if (editor.isMarkdownMode()) { found = editor.mdEditor.getValue().match(FIND_CHECKED_TASK_RX); count = found ? found.length : 0; } else { count = editor.wwEditor.get$Body().find('.task-list-item.checked').length; } return count; }; }
javascript
function taskCounterExtension(editor) { editor.getTaskCount = () => { let found, count; if (editor.isViewer()) { count = editor.preview.$el.find('.task-list-item').length; } else if (editor.isMarkdownMode()) { found = editor.mdEditor.getValue().match(FIND_TASK_RX); count = found ? found.length : 0; } else { count = editor.wwEditor.get$Body().find('.task-list-item').length; } return count; }; editor.getCheckedTaskCount = () => { let found, count; if (editor.isViewer()) { count = editor.preview.$el.find('.task-list-item.checked').length; } else if (editor.isMarkdownMode()) { found = editor.mdEditor.getValue().match(FIND_CHECKED_TASK_RX); count = found ? found.length : 0; } else { count = editor.wwEditor.get$Body().find('.task-list-item.checked').length; } return count; }; }
[ "function", "taskCounterExtension", "(", "editor", ")", "{", "editor", ".", "getTaskCount", "=", "(", ")", "=>", "{", "let", "found", ",", "count", ";", "if", "(", "editor", ".", "isViewer", "(", ")", ")", "{", "count", "=", "editor", ".", "preview", ".", "$el", ".", "find", "(", "'.task-list-item'", ")", ".", "length", ";", "}", "else", "if", "(", "editor", ".", "isMarkdownMode", "(", ")", ")", "{", "found", "=", "editor", ".", "mdEditor", ".", "getValue", "(", ")", ".", "match", "(", "FIND_TASK_RX", ")", ";", "count", "=", "found", "?", "found", ".", "length", ":", "0", ";", "}", "else", "{", "count", "=", "editor", ".", "wwEditor", ".", "get$Body", "(", ")", ".", "find", "(", "'.task-list-item'", ")", ".", "length", ";", "}", "return", "count", ";", "}", ";", "editor", ".", "getCheckedTaskCount", "=", "(", ")", "=>", "{", "let", "found", ",", "count", ";", "if", "(", "editor", ".", "isViewer", "(", ")", ")", "{", "count", "=", "editor", ".", "preview", ".", "$el", ".", "find", "(", "'.task-list-item.checked'", ")", ".", "length", ";", "}", "else", "if", "(", "editor", ".", "isMarkdownMode", "(", ")", ")", "{", "found", "=", "editor", ".", "mdEditor", ".", "getValue", "(", ")", ".", "match", "(", "FIND_CHECKED_TASK_RX", ")", ";", "count", "=", "found", "?", "found", ".", "length", ":", "0", ";", "}", "else", "{", "count", "=", "editor", ".", "wwEditor", ".", "get$Body", "(", ")", ".", "find", "(", "'.task-list-item.checked'", ")", ".", "length", ";", "}", "return", "count", ";", "}", ";", "}" ]
task counter extension @param {Editor} editor - editor instance @ignore
[ "task", "counter", "extension" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/taskCounter.js#L15-L45
train
nhn/tui.editor
src/js/extensions/scrollSync/scrollSync.js
changeButtonVisiblityStateIfNeed
function changeButtonVisiblityStateIfNeed() { if (editor.mdPreviewStyle === 'vertical' && editor.currentMode === 'markdown') { button.$el.show(); $divider.show(); } else { button.$el.hide(); $divider.hide(); } }
javascript
function changeButtonVisiblityStateIfNeed() { if (editor.mdPreviewStyle === 'vertical' && editor.currentMode === 'markdown') { button.$el.show(); $divider.show(); } else { button.$el.hide(); $divider.hide(); } }
[ "function", "changeButtonVisiblityStateIfNeed", "(", ")", "{", "if", "(", "editor", ".", "mdPreviewStyle", "===", "'vertical'", "&&", "editor", ".", "currentMode", "===", "'markdown'", ")", "{", "button", ".", "$el", ".", "show", "(", ")", ";", "$divider", ".", "show", "(", ")", ";", "}", "else", "{", "button", ".", "$el", ".", "hide", "(", ")", ";", "$divider", ".", "hide", "(", ")", ";", "}", "}" ]
change button visiblity state
[ "change", "button", "visiblity", "state" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/scrollSync/scrollSync.js#L86-L94
train
nhn/tui.editor
src/js/extensions/mark/mark.js
getHelper
function getHelper() { let helper; if (editor.isViewer()) { helper = vmh; } else if (editor.isWysiwygMode()) { helper = wmh; } else { helper = mmh; } return helper; }
javascript
function getHelper() { let helper; if (editor.isViewer()) { helper = vmh; } else if (editor.isWysiwygMode()) { helper = wmh; } else { helper = mmh; } return helper; }
[ "function", "getHelper", "(", ")", "{", "let", "helper", ";", "if", "(", "editor", ".", "isViewer", "(", ")", ")", "{", "helper", "=", "vmh", ";", "}", "else", "if", "(", "editor", ".", "isWysiwygMode", "(", ")", ")", "{", "helper", "=", "wmh", ";", "}", "else", "{", "helper", "=", "mmh", ";", "}", "return", "helper", ";", "}" ]
getHelper Get helper for current situation @returns {object} helper
[ "getHelper", "Get", "helper", "for", "current", "situation" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/mark/mark.js#L42-L54
train
nhn/tui.editor
src/js/extensions/mark/mark.js
updateMarkWhenResizing
function updateMarkWhenResizing() { const helper = getHelper(); ml.getAll().forEach(marker => { helper.updateMarkerWithExtraInfo(marker); }); editor.eventManager.emit('markerUpdated', ml.getAll()); }
javascript
function updateMarkWhenResizing() { const helper = getHelper(); ml.getAll().forEach(marker => { helper.updateMarkerWithExtraInfo(marker); }); editor.eventManager.emit('markerUpdated', ml.getAll()); }
[ "function", "updateMarkWhenResizing", "(", ")", "{", "const", "helper", "=", "getHelper", "(", ")", ";", "ml", ".", "getAll", "(", ")", ".", "forEach", "(", "marker", "=>", "{", "helper", ".", "updateMarkerWithExtraInfo", "(", "marker", ")", ";", "}", ")", ";", "editor", ".", "eventManager", ".", "emit", "(", "'markerUpdated'", ",", "ml", ".", "getAll", "(", ")", ")", ";", "}" ]
Update mark when resizing
[ "Update", "mark", "when", "resizing" ]
e75ab08c2a7ab07d1143e318f7cde135c5e3002e
https://github.com/nhn/tui.editor/blob/e75ab08c2a7ab07d1143e318f7cde135c5e3002e/src/js/extensions/mark/mark.js#L59-L67
train
semantic-release/semantic-release
lib/git.js
getTagHead
async function getTagHead(tagName, execaOpts) { try { return await execa.stdout('git', ['rev-list', '-1', tagName], execaOpts); } catch (error) { debug(error); } }
javascript
async function getTagHead(tagName, execaOpts) { try { return await execa.stdout('git', ['rev-list', '-1', tagName], execaOpts); } catch (error) { debug(error); } }
[ "async", "function", "getTagHead", "(", "tagName", ",", "execaOpts", ")", "{", "try", "{", "return", "await", "execa", ".", "stdout", "(", "'git'", ",", "[", "'rev-list'", ",", "'-1'", ",", "tagName", "]", ",", "execaOpts", ")", ";", "}", "catch", "(", "error", ")", "{", "debug", "(", "error", ")", ";", "}", "}" ]
Get the commit sha for a given tag. @param {String} tagName Tag name for which to retrieve the commit sha. @param {Object} [execaOpts] Options to pass to `execa`. @return {string} The commit sha of the tag in parameter or `null`.
[ "Get", "the", "commit", "sha", "for", "a", "given", "tag", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L12-L18
train
semantic-release/semantic-release
lib/git.js
getTags
async function getTags(execaOpts) { return (await execa.stdout('git', ['tag'], execaOpts)) .split('\n') .map(tag => tag.trim()) .filter(Boolean); }
javascript
async function getTags(execaOpts) { return (await execa.stdout('git', ['tag'], execaOpts)) .split('\n') .map(tag => tag.trim()) .filter(Boolean); }
[ "async", "function", "getTags", "(", "execaOpts", ")", "{", "return", "(", "await", "execa", ".", "stdout", "(", "'git'", ",", "[", "'tag'", "]", ",", "execaOpts", ")", ")", ".", "split", "(", "'\\n'", ")", ".", "\\n", "map", ".", "(", "tag", "=>", "tag", ".", "trim", "(", ")", ")", "filter", ";", "}" ]
Get all the repository tags. @param {Object} [execaOpts] Options to pass to `execa`. @return {Array<String>} List of git tags. @throws {Error} If the `git` command fails.
[ "Get", "all", "the", "repository", "tags", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L28-L33
train
semantic-release/semantic-release
lib/git.js
isRefInHistory
async function isRefInHistory(ref, execaOpts) { try { await execa('git', ['merge-base', '--is-ancestor', ref, 'HEAD'], execaOpts); return true; } catch (error) { if (error.code === 1) { return false; } debug(error); throw error; } }
javascript
async function isRefInHistory(ref, execaOpts) { try { await execa('git', ['merge-base', '--is-ancestor', ref, 'HEAD'], execaOpts); return true; } catch (error) { if (error.code === 1) { return false; } debug(error); throw error; } }
[ "async", "function", "isRefInHistory", "(", "ref", ",", "execaOpts", ")", "{", "try", "{", "await", "execa", "(", "'git'", ",", "[", "'merge-base'", ",", "'--is-ancestor'", ",", "ref", ",", "'HEAD'", "]", ",", "execaOpts", ")", ";", "return", "true", ";", "}", "catch", "(", "error", ")", "{", "if", "(", "error", ".", "code", "===", "1", ")", "{", "return", "false", ";", "}", "debug", "(", "error", ")", ";", "throw", "error", ";", "}", "}" ]
Verify if the `ref` is in the direct history of the current branch. @param {String} ref The reference to look for. @param {Object} [execaOpts] Options to pass to `execa`. @return {Boolean} `true` if the reference is in the history of the current branch, falsy otherwise.
[ "Verify", "if", "the", "ref", "is", "in", "the", "direct", "history", "of", "the", "current", "branch", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L43-L55
train
semantic-release/semantic-release
lib/git.js
fetch
async function fetch(repositoryUrl, execaOpts) { try { await execa('git', ['fetch', '--unshallow', '--tags', repositoryUrl], execaOpts); } catch (error) { await execa('git', ['fetch', '--tags', repositoryUrl], execaOpts); } }
javascript
async function fetch(repositoryUrl, execaOpts) { try { await execa('git', ['fetch', '--unshallow', '--tags', repositoryUrl], execaOpts); } catch (error) { await execa('git', ['fetch', '--tags', repositoryUrl], execaOpts); } }
[ "async", "function", "fetch", "(", "repositoryUrl", ",", "execaOpts", ")", "{", "try", "{", "await", "execa", "(", "'git'", ",", "[", "'fetch'", ",", "'--unshallow'", ",", "'--tags'", ",", "repositoryUrl", "]", ",", "execaOpts", ")", ";", "}", "catch", "(", "error", ")", "{", "await", "execa", "(", "'git'", ",", "[", "'fetch'", ",", "'--tags'", ",", "repositoryUrl", "]", ",", "execaOpts", ")", ";", "}", "}" ]
Unshallow the git repository if necessary and fetch all the tags. @param {String} repositoryUrl The remote repository URL. @param {Object} [execaOpts] Options to pass to `execa`.
[ "Unshallow", "the", "git", "repository", "if", "necessary", "and", "fetch", "all", "the", "tags", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L63-L69
train
semantic-release/semantic-release
lib/git.js
repoUrl
async function repoUrl(execaOpts) { try { return await execa.stdout('git', ['config', '--get', 'remote.origin.url'], execaOpts); } catch (error) { debug(error); } }
javascript
async function repoUrl(execaOpts) { try { return await execa.stdout('git', ['config', '--get', 'remote.origin.url'], execaOpts); } catch (error) { debug(error); } }
[ "async", "function", "repoUrl", "(", "execaOpts", ")", "{", "try", "{", "return", "await", "execa", ".", "stdout", "(", "'git'", ",", "[", "'config'", ",", "'--get'", ",", "'remote.origin.url'", "]", ",", "execaOpts", ")", ";", "}", "catch", "(", "error", ")", "{", "debug", "(", "error", ")", ";", "}", "}" ]
Get the repository remote URL. @param {Object} [execaOpts] Options to pass to `execa`. @return {string} The value of the remote git URL.
[ "Get", "the", "repository", "remote", "URL", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L89-L95
train
semantic-release/semantic-release
lib/git.js
isGitRepo
async function isGitRepo(execaOpts) { try { return (await execa('git', ['rev-parse', '--git-dir'], execaOpts)).code === 0; } catch (error) { debug(error); } }
javascript
async function isGitRepo(execaOpts) { try { return (await execa('git', ['rev-parse', '--git-dir'], execaOpts)).code === 0; } catch (error) { debug(error); } }
[ "async", "function", "isGitRepo", "(", "execaOpts", ")", "{", "try", "{", "return", "(", "await", "execa", "(", "'git'", ",", "[", "'rev-parse'", ",", "'--git-dir'", "]", ",", "execaOpts", ")", ")", ".", "code", "===", "0", ";", "}", "catch", "(", "error", ")", "{", "debug", "(", "error", ")", ";", "}", "}" ]
Test if the current working directory is a Git repository. @param {Object} [execaOpts] Options to pass to `execa`. @return {Boolean} `true` if the current working directory is in a git repository, falsy otherwise.
[ "Test", "if", "the", "current", "working", "directory", "is", "a", "Git", "repository", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L104-L110
train
semantic-release/semantic-release
lib/git.js
verifyAuth
async function verifyAuth(repositoryUrl, branch, execaOpts) { try { await execa('git', ['push', '--dry-run', repositoryUrl, `HEAD:${branch}`], execaOpts); } catch (error) { debug(error); throw error; } }
javascript
async function verifyAuth(repositoryUrl, branch, execaOpts) { try { await execa('git', ['push', '--dry-run', repositoryUrl, `HEAD:${branch}`], execaOpts); } catch (error) { debug(error); throw error; } }
[ "async", "function", "verifyAuth", "(", "repositoryUrl", ",", "branch", ",", "execaOpts", ")", "{", "try", "{", "await", "execa", "(", "'git'", ",", "[", "'push'", ",", "'--dry-run'", ",", "repositoryUrl", ",", "`", "${", "branch", "}", "`", "]", ",", "execaOpts", ")", ";", "}", "catch", "(", "error", ")", "{", "debug", "(", "error", ")", ";", "throw", "error", ";", "}", "}" ]
Verify the write access authorization to remote repository with push dry-run. @param {String} repositoryUrl The remote repository URL. @param {String} branch The repositoru branch for which to verify write access. @param {Object} [execaOpts] Options to pass to `execa`. @throws {Error} if not authorized to push.
[ "Verify", "the", "write", "access", "authorization", "to", "remote", "repository", "with", "push", "dry", "-", "run", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L121-L128
train
semantic-release/semantic-release
lib/git.js
verifyTagName
async function verifyTagName(tagName, execaOpts) { try { return (await execa('git', ['check-ref-format', `refs/tags/${tagName}`], execaOpts)).code === 0; } catch (error) { debug(error); } }
javascript
async function verifyTagName(tagName, execaOpts) { try { return (await execa('git', ['check-ref-format', `refs/tags/${tagName}`], execaOpts)).code === 0; } catch (error) { debug(error); } }
[ "async", "function", "verifyTagName", "(", "tagName", ",", "execaOpts", ")", "{", "try", "{", "return", "(", "await", "execa", "(", "'git'", ",", "[", "'check-ref-format'", ",", "`", "${", "tagName", "}", "`", "]", ",", "execaOpts", ")", ")", ".", "code", "===", "0", ";", "}", "catch", "(", "error", ")", "{", "debug", "(", "error", ")", ";", "}", "}" ]
Verify a tag name is a valid Git reference. @param {String} tagName the tag name to verify. @param {Object} [execaOpts] Options to pass to `execa`. @return {Boolean} `true` if valid, falsy otherwise.
[ "Verify", "a", "tag", "name", "is", "a", "valid", "Git", "reference", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L162-L168
train
semantic-release/semantic-release
lib/git.js
isBranchUpToDate
async function isBranchUpToDate(branch, execaOpts) { const remoteHead = await execa.stdout('git', ['ls-remote', '--heads', 'origin', branch], execaOpts); try { return await isRefInHistory(remoteHead.match(/^(\w+)?/)[1], execaOpts); } catch (error) { debug(error); } }
javascript
async function isBranchUpToDate(branch, execaOpts) { const remoteHead = await execa.stdout('git', ['ls-remote', '--heads', 'origin', branch], execaOpts); try { return await isRefInHistory(remoteHead.match(/^(\w+)?/)[1], execaOpts); } catch (error) { debug(error); } }
[ "async", "function", "isBranchUpToDate", "(", "branch", ",", "execaOpts", ")", "{", "const", "remoteHead", "=", "await", "execa", ".", "stdout", "(", "'git'", ",", "[", "'ls-remote'", ",", "'--heads'", ",", "'origin'", ",", "branch", "]", ",", "execaOpts", ")", ";", "try", "{", "return", "await", "isRefInHistory", "(", "remoteHead", ".", "match", "(", "/", "^(\\w+)?", "/", ")", "[", "1", "]", ",", "execaOpts", ")", ";", "}", "catch", "(", "error", ")", "{", "debug", "(", "error", ")", ";", "}", "}" ]
Verify the local branch is up to date with the remote one. @param {String} branch The repository branch for which to verify status. @param {Object} [execaOpts] Options to pass to `execa`. @return {Boolean} `true` is the HEAD of the current local branch is the same as the HEAD of the remote branch, falsy otherwise.
[ "Verify", "the", "local", "branch", "is", "up", "to", "date", "with", "the", "remote", "one", "." ]
edf382f88838ed543c0b76cb6c914cca1fc1ddd1
https://github.com/semantic-release/semantic-release/blob/edf382f88838ed543c0b76cb6c914cca1fc1ddd1/lib/git.js#L178-L185
train
mochajs/mocha
lib/reporters/doc.js
Doc
function Doc(runner, options) { Base.call(this, runner, options); var indents = 2; function indent() { return Array(indents).join(' '); } runner.on(EVENT_SUITE_BEGIN, function(suite) { if (suite.root) { return; } ++indents; console.log('%s<section class="suite">', indent()); ++indents; console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title)); console.log('%s<dl>', indent()); }); runner.on(EVENT_SUITE_END, function(suite) { if (suite.root) { return; } console.log('%s</dl>', indent()); --indents; console.log('%s</section>', indent()); --indents; }); runner.on(EVENT_TEST_PASS, function(test) { console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title)); var code = utils.escape(utils.clean(test.body)); console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code); }); runner.on(EVENT_TEST_FAIL, function(test, err) { console.log( '%s <dt class="error">%s</dt>', indent(), utils.escape(test.title) ); var code = utils.escape(utils.clean(test.body)); console.log( '%s <dd class="error"><pre><code>%s</code></pre></dd>', indent(), code ); console.log('%s <dd class="error">%s</dd>', indent(), utils.escape(err)); }); }
javascript
function Doc(runner, options) { Base.call(this, runner, options); var indents = 2; function indent() { return Array(indents).join(' '); } runner.on(EVENT_SUITE_BEGIN, function(suite) { if (suite.root) { return; } ++indents; console.log('%s<section class="suite">', indent()); ++indents; console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title)); console.log('%s<dl>', indent()); }); runner.on(EVENT_SUITE_END, function(suite) { if (suite.root) { return; } console.log('%s</dl>', indent()); --indents; console.log('%s</section>', indent()); --indents; }); runner.on(EVENT_TEST_PASS, function(test) { console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title)); var code = utils.escape(utils.clean(test.body)); console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code); }); runner.on(EVENT_TEST_FAIL, function(test, err) { console.log( '%s <dt class="error">%s</dt>', indent(), utils.escape(test.title) ); var code = utils.escape(utils.clean(test.body)); console.log( '%s <dd class="error"><pre><code>%s</code></pre></dd>', indent(), code ); console.log('%s <dd class="error">%s</dd>', indent(), utils.escape(err)); }); }
[ "function", "Doc", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "indents", "=", "2", ";", "function", "indent", "(", ")", "{", "return", "Array", "(", "indents", ")", ".", "join", "(", "' '", ")", ";", "}", "runner", ".", "on", "(", "EVENT_SUITE_BEGIN", ",", "function", "(", "suite", ")", "{", "if", "(", "suite", ".", "root", ")", "{", "return", ";", "}", "++", "indents", ";", "console", ".", "log", "(", "'%s<section class=\"suite\">'", ",", "indent", "(", ")", ")", ";", "++", "indents", ";", "console", ".", "log", "(", "'%s<h1>%s</h1>'", ",", "indent", "(", ")", ",", "utils", ".", "escape", "(", "suite", ".", "title", ")", ")", ";", "console", ".", "log", "(", "'%s<dl>'", ",", "indent", "(", ")", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_SUITE_END", ",", "function", "(", "suite", ")", "{", "if", "(", "suite", ".", "root", ")", "{", "return", ";", "}", "console", ".", "log", "(", "'%s</dl>'", ",", "indent", "(", ")", ")", ";", "--", "indents", ";", "console", ".", "log", "(", "'%s</section>'", ",", "indent", "(", ")", ")", ";", "--", "indents", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "console", ".", "log", "(", "'%s <dt>%s</dt>'", ",", "indent", "(", ")", ",", "utils", ".", "escape", "(", "test", ".", "title", ")", ")", ";", "var", "code", "=", "utils", ".", "escape", "(", "utils", ".", "clean", "(", "test", ".", "body", ")", ")", ";", "console", ".", "log", "(", "'%s <dd><pre><code>%s</code></pre></dd>'", ",", "indent", "(", ")", ",", "code", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", "test", ",", "err", ")", "{", "console", ".", "log", "(", "'%s <dt class=\"error\">%s</dt>'", ",", "indent", "(", ")", ",", "utils", ".", "escape", "(", "test", ".", "title", ")", ")", ";", "var", "code", "=", "utils", ".", "escape", "(", "utils", ".", "clean", "(", "test", ".", "body", ")", ")", ";", "console", ".", "log", "(", "'%s <dd class=\"error\"><pre><code>%s</code></pre></dd>'", ",", "indent", "(", ")", ",", "code", ")", ";", "console", ".", "log", "(", "'%s <dd class=\"error\">%s</dd>'", ",", "indent", "(", ")", ",", "utils", ".", "escape", "(", "err", ")", ")", ";", "}", ")", ";", "}" ]
Constructs a new `Doc` reporter instance. @public @class @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "Doc", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/doc.js#L33-L83
train
mochajs/mocha
lib/runnable.js
multiple
function multiple(err) { if (emitted) { return; } emitted = true; var msg = 'done() called multiple times'; if (err && err.message) { err.message += " (and Mocha's " + msg + ')'; self.emit('error', err); } else { self.emit('error', new Error(msg)); } }
javascript
function multiple(err) { if (emitted) { return; } emitted = true; var msg = 'done() called multiple times'; if (err && err.message) { err.message += " (and Mocha's " + msg + ')'; self.emit('error', err); } else { self.emit('error', new Error(msg)); } }
[ "function", "multiple", "(", "err", ")", "{", "if", "(", "emitted", ")", "{", "return", ";", "}", "emitted", "=", "true", ";", "var", "msg", "=", "'done() called multiple times'", ";", "if", "(", "err", "&&", "err", ".", "message", ")", "{", "err", ".", "message", "+=", "\" (and Mocha's \"", "+", "msg", "+", "')'", ";", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", "else", "{", "self", ".", "emit", "(", "'error'", ",", "new", "Error", "(", "msg", ")", ")", ";", "}", "}" ]
called multiple times
[ "called", "multiple", "times" ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/runnable.js#L303-L315
train
mochajs/mocha
lib/browser/growl.js
function() { // If user hasn't responded yet... "No notification for you!" (Seinfeld) Promise.race([promise, Promise.resolve(undefined)]) .then(canNotify) .then(function() { display(runner); }) .catch(notPermitted); }
javascript
function() { // If user hasn't responded yet... "No notification for you!" (Seinfeld) Promise.race([promise, Promise.resolve(undefined)]) .then(canNotify) .then(function() { display(runner); }) .catch(notPermitted); }
[ "function", "(", ")", "{", "Promise", ".", "race", "(", "[", "promise", ",", "Promise", ".", "resolve", "(", "undefined", ")", "]", ")", ".", "then", "(", "canNotify", ")", ".", "then", "(", "function", "(", ")", "{", "display", "(", "runner", ")", ";", "}", ")", ".", "catch", "(", "notPermitted", ")", ";", "}" ]
Attempt notification.
[ "Attempt", "notification", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/browser/growl.js#L47-L55
train
mochajs/mocha
lib/browser/growl.js
isPermitted
function isPermitted() { var permitted = { granted: function allow() { return Promise.resolve(true); }, denied: function deny() { return Promise.resolve(false); }, default: function ask() { return Notification.requestPermission().then(function(permission) { return permission === 'granted'; }); } }; return permitted[Notification.permission](); }
javascript
function isPermitted() { var permitted = { granted: function allow() { return Promise.resolve(true); }, denied: function deny() { return Promise.resolve(false); }, default: function ask() { return Notification.requestPermission().then(function(permission) { return permission === 'granted'; }); } }; return permitted[Notification.permission](); }
[ "function", "isPermitted", "(", ")", "{", "var", "permitted", "=", "{", "granted", ":", "function", "allow", "(", ")", "{", "return", "Promise", ".", "resolve", "(", "true", ")", ";", "}", ",", "denied", ":", "function", "deny", "(", ")", "{", "return", "Promise", ".", "resolve", "(", "false", ")", ";", "}", ",", "default", ":", "function", "ask", "(", ")", "{", "return", "Notification", ".", "requestPermission", "(", ")", ".", "then", "(", "function", "(", "permission", ")", "{", "return", "permission", "===", "'granted'", ";", "}", ")", ";", "}", "}", ";", "return", "permitted", "[", "Notification", ".", "permission", "]", "(", ")", ";", "}" ]
Checks if browser notification is permitted by user. @private @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Notification/permission|Notification.permission} @see {@link Mocha#growl} @see {@link Mocha#isGrowlPermitted} @returns {Promise<boolean>} promise determining if browser notification permissible when fulfilled.
[ "Checks", "if", "browser", "notification", "is", "permitted", "by", "user", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/browser/growl.js#L70-L86
train
mochajs/mocha
lib/browser/growl.js
display
function display(runner) { var stats = runner.stats; var symbol = { cross: '\u274C', tick: '\u2705' }; var logo = require('../../package').notifyLogo; var _message; var message; var title; if (stats.failures) { _message = stats.failures + ' of ' + stats.tests + ' tests failed'; message = symbol.cross + ' ' + _message; title = 'Failed'; } else { _message = stats.passes + ' tests passed in ' + stats.duration + 'ms'; message = symbol.tick + ' ' + _message; title = 'Passed'; } // Send notification var options = { badge: logo, body: message, dir: 'ltr', icon: logo, lang: 'en-US', name: 'mocha', requireInteraction: false, timestamp: Date.now() }; var notification = new Notification(title, options); // Autoclose after brief delay (makes various browsers act same) var FORCE_DURATION = 4000; setTimeout(notification.close.bind(notification), FORCE_DURATION); }
javascript
function display(runner) { var stats = runner.stats; var symbol = { cross: '\u274C', tick: '\u2705' }; var logo = require('../../package').notifyLogo; var _message; var message; var title; if (stats.failures) { _message = stats.failures + ' of ' + stats.tests + ' tests failed'; message = symbol.cross + ' ' + _message; title = 'Failed'; } else { _message = stats.passes + ' tests passed in ' + stats.duration + 'ms'; message = symbol.tick + ' ' + _message; title = 'Passed'; } // Send notification var options = { badge: logo, body: message, dir: 'ltr', icon: logo, lang: 'en-US', name: 'mocha', requireInteraction: false, timestamp: Date.now() }; var notification = new Notification(title, options); // Autoclose after brief delay (makes various browsers act same) var FORCE_DURATION = 4000; setTimeout(notification.close.bind(notification), FORCE_DURATION); }
[ "function", "display", "(", "runner", ")", "{", "var", "stats", "=", "runner", ".", "stats", ";", "var", "symbol", "=", "{", "cross", ":", "'\\u274C'", ",", "\\u274C", "}", ";", "tick", ":", "'\\u2705'", "\\u2705", "var", "logo", "=", "require", "(", "'../../package'", ")", ".", "notifyLogo", ";", "var", "_message", ";", "var", "message", ";", "var", "title", ";", "if", "(", "stats", ".", "failures", ")", "{", "_message", "=", "stats", ".", "failures", "+", "' of '", "+", "stats", ".", "tests", "+", "' tests failed'", ";", "message", "=", "symbol", ".", "cross", "+", "' '", "+", "_message", ";", "title", "=", "'Failed'", ";", "}", "else", "{", "_message", "=", "stats", ".", "passes", "+", "' tests passed in '", "+", "stats", ".", "duration", "+", "'ms'", ";", "message", "=", "symbol", ".", "tick", "+", "' '", "+", "_message", ";", "title", "=", "'Passed'", ";", "}", "var", "options", "=", "{", "badge", ":", "logo", ",", "body", ":", "message", ",", "dir", ":", "'ltr'", ",", "icon", ":", "logo", ",", "lang", ":", "'en-US'", ",", "name", ":", "'mocha'", ",", "requireInteraction", ":", "false", ",", "timestamp", ":", "Date", ".", "now", "(", ")", "}", ";", "var", "notification", "=", "new", "Notification", "(", "title", ",", "options", ")", ";", "}" ]
Displays the notification. @private @param {Runner} runner - Runner instance.
[ "Displays", "the", "notification", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/browser/growl.js#L121-L158
train
mochajs/mocha
lib/suite.js
Suite
function Suite(title, parentContext, isRoot) { if (!utils.isString(title)) { throw createInvalidArgumentTypeError( 'Suite argument "title" must be a string. Received type "' + typeof title + '"', 'title', 'string' ); } this.title = title; function Context() {} Context.prototype = parentContext; this.ctx = new Context(); this.suites = []; this.tests = []; this.pending = false; this._beforeEach = []; this._beforeAll = []; this._afterEach = []; this._afterAll = []; this.root = isRoot === true; this._timeout = 2000; this._enableTimeouts = true; this._slow = 75; this._bail = false; this._retries = -1; this._onlyTests = []; this._onlySuites = []; this.delayed = false; this.on('newListener', function(event) { if (deprecatedEvents[event]) { utils.deprecate( 'Event "' + event + '" is deprecated. Please let the Mocha team know about your use case: https://git.io/v6Lwm' ); } }); }
javascript
function Suite(title, parentContext, isRoot) { if (!utils.isString(title)) { throw createInvalidArgumentTypeError( 'Suite argument "title" must be a string. Received type "' + typeof title + '"', 'title', 'string' ); } this.title = title; function Context() {} Context.prototype = parentContext; this.ctx = new Context(); this.suites = []; this.tests = []; this.pending = false; this._beforeEach = []; this._beforeAll = []; this._afterEach = []; this._afterAll = []; this.root = isRoot === true; this._timeout = 2000; this._enableTimeouts = true; this._slow = 75; this._bail = false; this._retries = -1; this._onlyTests = []; this._onlySuites = []; this.delayed = false; this.on('newListener', function(event) { if (deprecatedEvents[event]) { utils.deprecate( 'Event "' + event + '" is deprecated. Please let the Mocha team know about your use case: https://git.io/v6Lwm' ); } }); }
[ "function", "Suite", "(", "title", ",", "parentContext", ",", "isRoot", ")", "{", "if", "(", "!", "utils", ".", "isString", "(", "title", ")", ")", "{", "throw", "createInvalidArgumentTypeError", "(", "'Suite argument \"title\" must be a string. Received type \"'", "+", "typeof", "title", "+", "'\"'", ",", "'title'", ",", "'string'", ")", ";", "}", "this", ".", "title", "=", "title", ";", "function", "Context", "(", ")", "{", "}", "Context", ".", "prototype", "=", "parentContext", ";", "this", ".", "ctx", "=", "new", "Context", "(", ")", ";", "this", ".", "suites", "=", "[", "]", ";", "this", ".", "tests", "=", "[", "]", ";", "this", ".", "pending", "=", "false", ";", "this", ".", "_beforeEach", "=", "[", "]", ";", "this", ".", "_beforeAll", "=", "[", "]", ";", "this", ".", "_afterEach", "=", "[", "]", ";", "this", ".", "_afterAll", "=", "[", "]", ";", "this", ".", "root", "=", "isRoot", "===", "true", ";", "this", ".", "_timeout", "=", "2000", ";", "this", ".", "_enableTimeouts", "=", "true", ";", "this", ".", "_slow", "=", "75", ";", "this", ".", "_bail", "=", "false", ";", "this", ".", "_retries", "=", "-", "1", ";", "this", ".", "_onlyTests", "=", "[", "]", ";", "this", ".", "_onlySuites", "=", "[", "]", ";", "this", ".", "delayed", "=", "false", ";", "this", ".", "on", "(", "'newListener'", ",", "function", "(", "event", ")", "{", "if", "(", "deprecatedEvents", "[", "event", "]", ")", "{", "utils", ".", "deprecate", "(", "'Event \"'", "+", "event", "+", "'\" is deprecated. Please let the Mocha team know about your use case: https://git.io/v6Lwm'", ")", ";", "}", "}", ")", ";", "}" ]
Constructs a new `Suite` instance with the given `title`, `ctx`, and `isRoot`. @public @class @extends EventEmitter @see {@link https://nodejs.org/api/events.html#events_class_eventemitter|EventEmitter} @param {string} title - Suite title. @param {Context} parentContext - Parent context instance. @param {boolean} [isRoot=false] - Whether this is the root suite.
[ "Constructs", "a", "new", "Suite", "instance", "with", "the", "given", "title", "ctx", "and", "isRoot", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/suite.js#L48-L88
train
mochajs/mocha
lib/reporters/json.js
JSONReporter
function JSONReporter(runner, options) { Base.call(this, runner, options); var self = this; var tests = []; var pending = []; var failures = []; var passes = []; runner.on(EVENT_TEST_END, function(test) { tests.push(test); }); runner.on(EVENT_TEST_PASS, function(test) { passes.push(test); }); runner.on(EVENT_TEST_FAIL, function(test) { failures.push(test); }); runner.on(EVENT_TEST_PENDING, function(test) { pending.push(test); }); runner.once(EVENT_RUN_END, function() { var obj = { stats: self.stats, tests: tests.map(clean), pending: pending.map(clean), failures: failures.map(clean), passes: passes.map(clean) }; runner.testResults = obj; process.stdout.write(JSON.stringify(obj, null, 2)); }); }
javascript
function JSONReporter(runner, options) { Base.call(this, runner, options); var self = this; var tests = []; var pending = []; var failures = []; var passes = []; runner.on(EVENT_TEST_END, function(test) { tests.push(test); }); runner.on(EVENT_TEST_PASS, function(test) { passes.push(test); }); runner.on(EVENT_TEST_FAIL, function(test) { failures.push(test); }); runner.on(EVENT_TEST_PENDING, function(test) { pending.push(test); }); runner.once(EVENT_RUN_END, function() { var obj = { stats: self.stats, tests: tests.map(clean), pending: pending.map(clean), failures: failures.map(clean), passes: passes.map(clean) }; runner.testResults = obj; process.stdout.write(JSON.stringify(obj, null, 2)); }); }
[ "function", "JSONReporter", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "self", "=", "this", ";", "var", "tests", "=", "[", "]", ";", "var", "pending", "=", "[", "]", ";", "var", "failures", "=", "[", "]", ";", "var", "passes", "=", "[", "]", ";", "runner", ".", "on", "(", "EVENT_TEST_END", ",", "function", "(", "test", ")", "{", "tests", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "passes", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", "test", ")", "{", "failures", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PENDING", ",", "function", "(", "test", ")", "{", "pending", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_END", ",", "function", "(", ")", "{", "var", "obj", "=", "{", "stats", ":", "self", ".", "stats", ",", "tests", ":", "tests", ".", "map", "(", "clean", ")", ",", "pending", ":", "pending", ".", "map", "(", "clean", ")", ",", "failures", ":", "failures", ".", "map", "(", "clean", ")", ",", "passes", ":", "passes", ".", "map", "(", "clean", ")", "}", ";", "runner", ".", "testResults", "=", "obj", ";", "process", ".", "stdout", ".", "write", "(", "JSON", ".", "stringify", "(", "obj", ",", "null", ",", "2", ")", ")", ";", "}", ")", ";", "}" ]
Constructs a new `JSON` reporter instance. @public @class JSON @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "JSON", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/json.js#L33-L71
train
mochajs/mocha
lib/reporters/json.js
clean
function clean(test) { var err = test.err || {}; if (err instanceof Error) { err = errorJSON(err); } return { title: test.title, fullTitle: test.fullTitle(), duration: test.duration, currentRetry: test.currentRetry(), err: cleanCycles(err) }; }
javascript
function clean(test) { var err = test.err || {}; if (err instanceof Error) { err = errorJSON(err); } return { title: test.title, fullTitle: test.fullTitle(), duration: test.duration, currentRetry: test.currentRetry(), err: cleanCycles(err) }; }
[ "function", "clean", "(", "test", ")", "{", "var", "err", "=", "test", ".", "err", "||", "{", "}", ";", "if", "(", "err", "instanceof", "Error", ")", "{", "err", "=", "errorJSON", "(", "err", ")", ";", "}", "return", "{", "title", ":", "test", ".", "title", ",", "fullTitle", ":", "test", ".", "fullTitle", "(", ")", ",", "duration", ":", "test", ".", "duration", ",", "currentRetry", ":", "test", ".", "currentRetry", "(", ")", ",", "err", ":", "cleanCycles", "(", "err", ")", "}", ";", "}" ]
Return a plain-object representation of `test` free of cyclic properties etc. @private @param {Object} test @return {Object}
[ "Return", "a", "plain", "-", "object", "representation", "of", "test", "free", "of", "cyclic", "properties", "etc", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/json.js#L81-L94
train
mochajs/mocha
lib/reporters/xunit.js
XUnit
function XUnit(runner, options) { Base.call(this, runner, options); var stats = this.stats; var tests = []; var self = this; // the name of the test suite, as it will appear in the resulting XML file var suiteName; // the default name of the test suite if none is provided var DEFAULT_SUITE_NAME = 'Mocha Tests'; if (options && options.reporterOptions) { if (options.reporterOptions.output) { if (!fs.createWriteStream) { throw createUnsupportedError('file output not supported in browser'); } mkdirp.sync(path.dirname(options.reporterOptions.output)); self.fileStream = fs.createWriteStream(options.reporterOptions.output); } // get the suite name from the reporter options (if provided) suiteName = options.reporterOptions.suiteName; } // fall back to the default suite name suiteName = suiteName || DEFAULT_SUITE_NAME; runner.on(EVENT_TEST_PENDING, function(test) { tests.push(test); }); runner.on(EVENT_TEST_PASS, function(test) { tests.push(test); }); runner.on(EVENT_TEST_FAIL, function(test) { tests.push(test); }); runner.once(EVENT_RUN_END, function() { self.write( tag( 'testsuite', { name: suiteName, tests: stats.tests, failures: 0, errors: stats.failures, skipped: stats.tests - stats.failures - stats.passes, timestamp: new Date().toUTCString(), time: stats.duration / 1000 || 0 }, false ) ); tests.forEach(function(t) { self.test(t); }); self.write('</testsuite>'); }); }
javascript
function XUnit(runner, options) { Base.call(this, runner, options); var stats = this.stats; var tests = []; var self = this; // the name of the test suite, as it will appear in the resulting XML file var suiteName; // the default name of the test suite if none is provided var DEFAULT_SUITE_NAME = 'Mocha Tests'; if (options && options.reporterOptions) { if (options.reporterOptions.output) { if (!fs.createWriteStream) { throw createUnsupportedError('file output not supported in browser'); } mkdirp.sync(path.dirname(options.reporterOptions.output)); self.fileStream = fs.createWriteStream(options.reporterOptions.output); } // get the suite name from the reporter options (if provided) suiteName = options.reporterOptions.suiteName; } // fall back to the default suite name suiteName = suiteName || DEFAULT_SUITE_NAME; runner.on(EVENT_TEST_PENDING, function(test) { tests.push(test); }); runner.on(EVENT_TEST_PASS, function(test) { tests.push(test); }); runner.on(EVENT_TEST_FAIL, function(test) { tests.push(test); }); runner.once(EVENT_RUN_END, function() { self.write( tag( 'testsuite', { name: suiteName, tests: stats.tests, failures: 0, errors: stats.failures, skipped: stats.tests - stats.failures - stats.passes, timestamp: new Date().toUTCString(), time: stats.duration / 1000 || 0 }, false ) ); tests.forEach(function(t) { self.test(t); }); self.write('</testsuite>'); }); }
[ "function", "XUnit", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "stats", "=", "this", ".", "stats", ";", "var", "tests", "=", "[", "]", ";", "var", "self", "=", "this", ";", "var", "suiteName", ";", "var", "DEFAULT_SUITE_NAME", "=", "'Mocha Tests'", ";", "if", "(", "options", "&&", "options", ".", "reporterOptions", ")", "{", "if", "(", "options", ".", "reporterOptions", ".", "output", ")", "{", "if", "(", "!", "fs", ".", "createWriteStream", ")", "{", "throw", "createUnsupportedError", "(", "'file output not supported in browser'", ")", ";", "}", "mkdirp", ".", "sync", "(", "path", ".", "dirname", "(", "options", ".", "reporterOptions", ".", "output", ")", ")", ";", "self", ".", "fileStream", "=", "fs", ".", "createWriteStream", "(", "options", ".", "reporterOptions", ".", "output", ")", ";", "}", "suiteName", "=", "options", ".", "reporterOptions", ".", "suiteName", ";", "}", "suiteName", "=", "suiteName", "||", "DEFAULT_SUITE_NAME", ";", "runner", ".", "on", "(", "EVENT_TEST_PENDING", ",", "function", "(", "test", ")", "{", "tests", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "tests", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", "test", ")", "{", "tests", ".", "push", "(", "test", ")", ";", "}", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_END", ",", "function", "(", ")", "{", "self", ".", "write", "(", "tag", "(", "'testsuite'", ",", "{", "name", ":", "suiteName", ",", "tests", ":", "stats", ".", "tests", ",", "failures", ":", "0", ",", "errors", ":", "stats", ".", "failures", ",", "skipped", ":", "stats", ".", "tests", "-", "stats", ".", "failures", "-", "stats", ".", "passes", ",", "timestamp", ":", "new", "Date", "(", ")", ".", "toUTCString", "(", ")", ",", "time", ":", "stats", ".", "duration", "/", "1000", "||", "0", "}", ",", "false", ")", ")", ";", "tests", ".", "forEach", "(", "function", "(", "t", ")", "{", "self", ".", "test", "(", "t", ")", ";", "}", ")", ";", "self", ".", "write", "(", "'</testsuite>'", ")", ";", "}", ")", ";", "}" ]
Constructs a new `XUnit` reporter instance. @public @class @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "XUnit", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/xunit.js#L46-L111
train
mochajs/mocha
lib/reporters/base.js
Base
function Base(runner, options) { var failures = (this.failures = []); if (!runner) { throw new TypeError('Missing runner argument'); } this.options = options || {}; this.runner = runner; this.stats = runner.stats; // assigned so Reporters keep a closer reference runner.on(EVENT_TEST_PASS, function(test) { if (test.duration > test.slow()) { test.speed = 'slow'; } else if (test.duration > test.slow() / 2) { test.speed = 'medium'; } else { test.speed = 'fast'; } }); runner.on(EVENT_TEST_FAIL, function(test, err) { if (showDiff(err)) { stringifyDiffObjs(err); } test.err = err; failures.push(test); }); }
javascript
function Base(runner, options) { var failures = (this.failures = []); if (!runner) { throw new TypeError('Missing runner argument'); } this.options = options || {}; this.runner = runner; this.stats = runner.stats; // assigned so Reporters keep a closer reference runner.on(EVENT_TEST_PASS, function(test) { if (test.duration > test.slow()) { test.speed = 'slow'; } else if (test.duration > test.slow() / 2) { test.speed = 'medium'; } else { test.speed = 'fast'; } }); runner.on(EVENT_TEST_FAIL, function(test, err) { if (showDiff(err)) { stringifyDiffObjs(err); } test.err = err; failures.push(test); }); }
[ "function", "Base", "(", "runner", ",", "options", ")", "{", "var", "failures", "=", "(", "this", ".", "failures", "=", "[", "]", ")", ";", "if", "(", "!", "runner", ")", "{", "throw", "new", "TypeError", "(", "'Missing runner argument'", ")", ";", "}", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "runner", "=", "runner", ";", "this", ".", "stats", "=", "runner", ".", "stats", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "if", "(", "test", ".", "duration", ">", "test", ".", "slow", "(", ")", ")", "{", "test", ".", "speed", "=", "'slow'", ";", "}", "else", "if", "(", "test", ".", "duration", ">", "test", ".", "slow", "(", ")", "/", "2", ")", "{", "test", ".", "speed", "=", "'medium'", ";", "}", "else", "{", "test", ".", "speed", "=", "'fast'", ";", "}", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", "test", ",", "err", ")", "{", "if", "(", "showDiff", "(", "err", ")", ")", "{", "stringifyDiffObjs", "(", "err", ")", ";", "}", "test", ".", "err", "=", "err", ";", "failures", ".", "push", "(", "test", ")", ";", "}", ")", ";", "}" ]
Constructs a new `Base` reporter instance. @description All other reporters generally inherit from this reporter. @public @class @memberof Mocha.reporters @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "Base", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/base.js#L272-L299
train
mochajs/mocha
lib/reporters/base.js
errorDiff
function errorDiff(actual, expected) { return diff .diffWordsWithSpace(actual, expected) .map(function(str) { if (str.added) { return colorLines('diff added', str.value); } if (str.removed) { return colorLines('diff removed', str.value); } return str.value; }) .join(''); }
javascript
function errorDiff(actual, expected) { return diff .diffWordsWithSpace(actual, expected) .map(function(str) { if (str.added) { return colorLines('diff added', str.value); } if (str.removed) { return colorLines('diff removed', str.value); } return str.value; }) .join(''); }
[ "function", "errorDiff", "(", "actual", ",", "expected", ")", "{", "return", "diff", ".", "diffWordsWithSpace", "(", "actual", ",", "expected", ")", ".", "map", "(", "function", "(", "str", ")", "{", "if", "(", "str", ".", "added", ")", "{", "return", "colorLines", "(", "'diff added'", ",", "str", ".", "value", ")", ";", "}", "if", "(", "str", ".", "removed", ")", "{", "return", "colorLines", "(", "'diff removed'", ",", "str", ".", "value", ")", ";", "}", "return", "str", ".", "value", ";", "}", ")", ".", "join", "(", "''", ")", ";", "}" ]
Returns character diff for `err`. @private @param {String} actual @param {String} expected @return {string} the diff
[ "Returns", "character", "diff", "for", "err", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/base.js#L442-L455
train
mochajs/mocha
lib/reporters/base.js
colorLines
function colorLines(name, str) { return str .split('\n') .map(function(str) { return color(name, str); }) .join('\n'); }
javascript
function colorLines(name, str) { return str .split('\n') .map(function(str) { return color(name, str); }) .join('\n'); }
[ "function", "colorLines", "(", "name", ",", "str", ")", "{", "return", "str", ".", "split", "(", "'\\n'", ")", ".", "\\n", "map", ".", "(", "function", "(", "str", ")", "{", "return", "color", "(", "name", ",", "str", ")", ";", "}", ")", "join", ";", "}" ]
Colors lines for `str`, using the color `name`. @private @param {string} name @param {string} str @return {string}
[ "Colors", "lines", "for", "str", "using", "the", "color", "name", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/base.js#L465-L472
train
mochajs/mocha
lib/reporters/tap.js
TAP
function TAP(runner, options) { Base.call(this, runner, options); var self = this; var n = 1; var tapVersion = '12'; if (options && options.reporterOptions) { if (options.reporterOptions.tapVersion) { tapVersion = options.reporterOptions.tapVersion.toString(); } } this._producer = createProducer(tapVersion); runner.once(EVENT_RUN_BEGIN, function() { var ntests = runner.grepTotal(runner.suite); self._producer.writeVersion(); self._producer.writePlan(ntests); }); runner.on(EVENT_TEST_END, function() { ++n; }); runner.on(EVENT_TEST_PENDING, function(test) { self._producer.writePending(n, test); }); runner.on(EVENT_TEST_PASS, function(test) { self._producer.writePass(n, test); }); runner.on(EVENT_TEST_FAIL, function(test, err) { self._producer.writeFail(n, test, err); }); runner.once(EVENT_RUN_END, function() { self._producer.writeEpilogue(runner.stats); }); }
javascript
function TAP(runner, options) { Base.call(this, runner, options); var self = this; var n = 1; var tapVersion = '12'; if (options && options.reporterOptions) { if (options.reporterOptions.tapVersion) { tapVersion = options.reporterOptions.tapVersion.toString(); } } this._producer = createProducer(tapVersion); runner.once(EVENT_RUN_BEGIN, function() { var ntests = runner.grepTotal(runner.suite); self._producer.writeVersion(); self._producer.writePlan(ntests); }); runner.on(EVENT_TEST_END, function() { ++n; }); runner.on(EVENT_TEST_PENDING, function(test) { self._producer.writePending(n, test); }); runner.on(EVENT_TEST_PASS, function(test) { self._producer.writePass(n, test); }); runner.on(EVENT_TEST_FAIL, function(test, err) { self._producer.writeFail(n, test, err); }); runner.once(EVENT_RUN_END, function() { self._producer.writeEpilogue(runner.stats); }); }
[ "function", "TAP", "(", "runner", ",", "options", ")", "{", "Base", ".", "call", "(", "this", ",", "runner", ",", "options", ")", ";", "var", "self", "=", "this", ";", "var", "n", "=", "1", ";", "var", "tapVersion", "=", "'12'", ";", "if", "(", "options", "&&", "options", ".", "reporterOptions", ")", "{", "if", "(", "options", ".", "reporterOptions", ".", "tapVersion", ")", "{", "tapVersion", "=", "options", ".", "reporterOptions", ".", "tapVersion", ".", "toString", "(", ")", ";", "}", "}", "this", ".", "_producer", "=", "createProducer", "(", "tapVersion", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_BEGIN", ",", "function", "(", ")", "{", "var", "ntests", "=", "runner", ".", "grepTotal", "(", "runner", ".", "suite", ")", ";", "self", ".", "_producer", ".", "writeVersion", "(", ")", ";", "self", ".", "_producer", ".", "writePlan", "(", "ntests", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_END", ",", "function", "(", ")", "{", "++", "n", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PENDING", ",", "function", "(", "test", ")", "{", "self", ".", "_producer", ".", "writePending", "(", "n", ",", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_PASS", ",", "function", "(", "test", ")", "{", "self", ".", "_producer", ".", "writePass", "(", "n", ",", "test", ")", ";", "}", ")", ";", "runner", ".", "on", "(", "EVENT_TEST_FAIL", ",", "function", "(", "test", ",", "err", ")", "{", "self", ".", "_producer", ".", "writeFail", "(", "n", ",", "test", ",", "err", ")", ";", "}", ")", ";", "runner", ".", "once", "(", "EVENT_RUN_END", ",", "function", "(", ")", "{", "self", ".", "_producer", ".", "writeEpilogue", "(", "runner", ".", "stats", ")", ";", "}", ")", ";", "}" ]
Constructs a new `TAP` reporter instance. @public @class @memberof Mocha.reporters @extends Mocha.reporters.Base @param {Runner} runner - Instance triggers reporter actions. @param {Object} [options] - runner options
[ "Constructs", "a", "new", "TAP", "reporter", "instance", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/tap.js#L37-L77
train
mochajs/mocha
lib/reporters/tap.js
println
function println(format, varArgs) { var vargs = Array.from(arguments); vargs[0] += '\n'; process.stdout.write(sprintf.apply(null, vargs)); }
javascript
function println(format, varArgs) { var vargs = Array.from(arguments); vargs[0] += '\n'; process.stdout.write(sprintf.apply(null, vargs)); }
[ "function", "println", "(", "format", ",", "varArgs", ")", "{", "var", "vargs", "=", "Array", ".", "from", "(", "arguments", ")", ";", "vargs", "[", "0", "]", "+=", "'\\n'", ";", "\\n", "}" ]
Writes newline-terminated formatted string to reporter output stream. @private @param {string} format - `printf`-like format string @param {...*} [varArgs] - Format string arguments
[ "Writes", "newline", "-", "terminated", "formatted", "string", "to", "reporter", "output", "stream", "." ]
9b00fedb610241e33f7592c40164e42a38a793cf
https://github.com/mochajs/mocha/blob/9b00fedb610241e33f7592c40164e42a38a793cf/lib/reporters/tap.js#L102-L106
train