How to use getSelectionStart method in Testcafe

Best JavaScript code snippet using testcafe

textarea-markdown-editor.js

Source:textarea-markdown-editor.js Github

copy

Full Screen

...140 match = currentLine.match(listFormat);141 if (!match) {142 return;143 }144 pos = this.getSelectionStart();145 if (text[pos] && text[pos] !== "\n") {146 return;147 }148 if (match[5].length <= 0) {149 this.removeCurrentLine(text);150 return;151 }152 extSpace = e.ctrlKey ? this.tabSpaces : '';153 this.insert(text, "\n" + extSpace + match[1]);154 e.preventDefault();155 return typeof (base = this.options).onInsertedList === "function" ? base.onInsertedList(e) : void 0;156 };157 MarkdownEditor.prototype.toggleCheck = function(e, text, currentLine) {158 var line, matches, pos;159 matches = currentLine.match(listFormat);160 if (!matches) {161 return;162 }163 if (!matches[4]) {164 return;165 }166 line = '';167 if (matches[4] === 'x') {168 line = currentLine.replace('[x]', '[ ]');169 } else {170 line = currentLine.replace('[ ]', '[x]');171 }172 pos = this.getSelectionStart();173 this.replaceCurrentLine(text, pos, currentLine, line);174 return e.preventDefault();175 };176 MarkdownEditor.prototype.replaceCurrentLine = function(text, pos, oldLine, newLine) {177 var beginPos;178 beginPos = this.getPosBeginningOfLine(text, pos);179 return this.replace(text, newLine, beginPos, beginPos + oldLine.length);180 };181 MarkdownEditor.prototype.supportInputTableFormat = function(e) {182 var base, char, currentLine, i, k, l, len, m, match, pos, prevPos, ref, ref1, row, rows, selectionStart, sep, text;183 text = this.getTextArray();184 currentLine = this.replaceEscapedPipe(this.getCurrentLine(text));185 selectionStart = this.getSelectionStart();186 match = currentLine.match(rowFormat);187 if (!match) {188 return;189 }190 if (this.isTableHeader(text)) {191 return;192 }193 if (selectionStart === this.getPosBeginningOfLine(text, selectionStart)) {194 return;195 }196 if (currentLine.match(emptyRowFormat) && this.isTableBody(text)) {197 this.removeCurrentLine(text);198 return;199 }200 e.preventDefault();201 rows = -1;202 for (k = 0, len = currentLine.length; k < len; k++) {203 char = currentLine[k];204 if (char === '|') {205 rows++;206 }207 }208 prevPos = this.getPosEndOfLine(text);209 sep = '';210 if (!this.isTableBody(text)) {211 sep = "\n|";212 for (i = l = 0, ref = rows; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {213 sep += " " + this.options.tableSeparator + " |";214 }215 }216 row = "\n|";217 for (i = m = 0, ref1 = rows; 0 <= ref1 ? m < ref1 : m > ref1; i = 0 <= ref1 ? ++m : --m) {218 row += ' |';219 }220 this.insert(text, sep + row, prevPos);221 pos = prevPos + sep.length + row.length - rows * 3 + 1;222 this.setSelectionRange(pos, pos);223 return typeof (base = this.options).onInsertedTable === "function" ? base.onInsertedTable(e) : void 0;224 };225 MarkdownEditor.prototype.supportCodeblockFormat = function(e) {226 var base, currentLine, match, selectionStart, text;227 text = this.getTextArray();228 selectionStart = this.getSelectionStart();229 currentLine = this.getCurrentLine(text);230 match = currentLine.match(beginCodeblockFormat);231 if (text[selectionStart + 1] && text[selectionStart + 1] !== "\n") {232 return;233 }234 if (!match) {235 return;236 }237 if (!this.requireCodeblockEnd(text, selectionStart)) {238 return;239 }240 e.preventDefault();241 this.insert(text, "\n\n" + match[1]);242 this.setSelectionRange(selectionStart + 1, selectionStart + 1);243 return typeof (base = this.options).onInsertedCodeblock === "function" ? base.onInsertedCodeblock(e) : void 0;244 };245 MarkdownEditor.prototype.requireCodeblockEnd = function(text, selectionStart) {246 var innerCodeblock, line, pos;247 innerCodeblock = this.isInnerCodeblock(text, selectionStart);248 if (innerCodeblock) {249 return false;250 }251 pos = this.getPosBeginningOfLine(text, selectionStart);252 while (pos <= text.length) {253 line = this.getCurrentLine(text, pos);254 if (innerCodeblock && line.match(endCodeblockFormat)) {255 return false;256 } else if (!innerCodeblock && line.match(beginCodeblockFormat)) {257 innerCodeblock = true;258 }259 pos += line.length + 1;260 }261 return true;262 };263 MarkdownEditor.prototype.isInnerCodeblock = function(text, selectionStart) {264 var endPos, innerCodeblock, line, pos;265 if (selectionStart == null) {266 selectionStart = this.getSelectionStart();267 }268 innerCodeblock = false;269 pos = 0;270 endPos = this.getPosBeginningOfLine(text, selectionStart) - 1;271 while (pos < endPos) {272 line = this.getCurrentLine(text, pos);273 if (innerCodeblock && line.match(endCodeblockFormat)) {274 innerCodeblock = false;275 } else if (!innerCodeblock && line.match(beginCodeblockFormat)) {276 innerCodeblock = true;277 }278 pos += line.length + 1;279 }280 return innerCodeblock;281 };282 MarkdownEditor.prototype.makeTable = function(e, text, currentLine) {283 var alignLeft, alignRight, base, matches, pos, table;284 if (this.isSelectRange()) {285 return;286 }287 matches = currentLine.match(makingTableFormat);288 if (!matches) {289 return;290 }291 if (matches[2] <= 0 || matches[3] <= 0) {292 return;293 }294 e.preventDefault();295 alignLeft = !!matches[1].length;296 alignRight = !!matches[4].length;297 table = this.buildTable(matches[2], matches[3], {298 alignLeft: alignLeft,299 alignRight: alignRight300 });301 pos = this.getPosBeginningOfLine(text);302 this.replaceCurrentLine(text, pos, currentLine, table);303 this.setSelectionRange(pos + 2, pos + 2);304 return typeof (base = this.options).onMadeTable === "function" ? base.onMadeTable(e) : void 0;305 };306 MarkdownEditor.prototype.buildTable = function(rowsCount, colsCount, options) {307 var i, j, k, l, m, n, ref, ref1, ref2, ref3, separator, table;308 if (options == null) {309 options = {};310 }311 separator = "---";312 if (options.alignLeft) {313 separator = ":" + separator;314 }315 if (options.alignRight) {316 separator = separator + ":";317 }318 table = "|";319 for (i = k = 0, ref = rowsCount; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {320 table += ' |';321 }322 table += "\n|";323 for (i = l = 0, ref1 = rowsCount; 0 <= ref1 ? l < ref1 : l > ref1; i = 0 <= ref1 ? ++l : --l) {324 table += " " + separator + " |";325 }326 for (i = m = 0, ref2 = colsCount - 1; 0 <= ref2 ? m < ref2 : m > ref2; i = 0 <= ref2 ? ++m : --m) {327 table += "\n|";328 for (j = n = 0, ref3 = rowsCount; 0 <= ref3 ? n < ref3 : n > ref3; j = 0 <= ref3 ? ++n : --n) {329 table += " |";330 }331 }332 return table;333 };334 MarkdownEditor.prototype.csvToTable = function(csv, text, allowFlat) {335 if (text == null) {336 text = this.getTextArray();337 }338 if (allowFlat == null) {339 allowFlat = false;340 }341 return this.separatedStringToTable(csv, ',', text, allowFlat);342 };343 MarkdownEditor.prototype.tsvToTable = function(tsv, text, allowFlat) {344 if (text == null) {345 text = this.getTextArray();346 }347 if (allowFlat == null) {348 allowFlat = false;349 }350 return this.separatedStringToTable(tsv, "\t", text, allowFlat);351 };352 MarkdownEditor.prototype.separatedStringToTable = function(str, separator, text, allowFlat) {353 var c, cells, escape, i, inQuote, k, len, table, x, xMax, y;354 str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");355 inQuote = false;356 escape = false;357 cells = [['']];358 y = 0;359 x = 0;360 xMax = 0;361 for (i = k = 0, len = str.length; k < len; i = ++k) {362 c = str[i];363 if (inQuote) {364 if (escape) {365 escape = false;366 cells[y][x] += c;367 } else if (!escape && c === '"') {368 if (str[i + 1] === '"') {369 escape = true;370 } else {371 inQuote = false;372 }373 } else {374 cells[y][x] += c;375 }376 } else {377 if (c === '"') {378 inQuote = true;379 } else if (c === separator) {380 cells[y].push('');381 x += 1;382 if (xMax < x) {383 xMax = x;384 }385 } else if (c === "\n") {386 cells.push(['']);387 y += 1;388 x = 0;389 } else {390 cells[y][x] += c;391 }392 }393 }394 if (allowFlat && xMax <= 0 && y <= 0 || !allowFlat && xMax <= 0) {395 return false;396 }397 table = this.createTableFromArray(cells);398 this.replace(text, table, this.getSelectionStart(), this.getSelectionEnd());399 return true;400 };401 MarkdownEditor.prototype.createTableFromArray = function(csvLines) {402 var cell, i, j, k, l, len, len1, line, m, ref, table;403 table = '';404 for (i = k = 0, len = csvLines.length; k < len; i = ++k) {405 line = csvLines[i];406 if (line.length === 1 && line[0] === "") {407 continue;408 }409 table += "|";410 for (l = 0, len1 = line.length; l < len1; l++) {411 cell = line[l];412 table += " " + (this.trim(cell).replace(/\n/g, '<br>')) + " |";413 }414 table += "\n";415 if (i === 0) {416 table += "|";417 for (j = m = 0, ref = line.length; 0 <= ref ? m < ref : m > ref; j = 0 <= ref ? ++m : --m) {418 table += " " + this.options.tableSeparator + " |";419 }420 table += "\n";421 }422 }423 return table;424 };425 MarkdownEditor.prototype.getPastedString = function(item) {426 var type;427 type = item.type;428 return item.getAsString((function(_this) {429 return function(str) {430 return _this.onGetPastedString(type, str);431 };432 })(this));433 };434 MarkdownEditor.prototype.onGetPastedString = function(type, str) {435 var generator, generatorMatch, metaMatch;436 if (!str) {437 this.clearPastedStrings();438 return;439 }440 this.pastedStrings[type] = str;441 if (this.pastedStrings['text/plain'] && this.pastedStrings['text/html']) {442 metaMatch = this.pastedStrings['text/html'].match(requiredGeneratorMetaTagFormat);443 if (metaMatch) {444 generatorMatch = metaMatch[0].match(contentParser);445 if (generatorMatch) {446 generator = generatorMatch[1];447 if (!(tsv2tableGenerators.test(generator) && this.tsvToTable(this.pastedStrings['text/plain'], null, true))) {448 this.restorePlainText();449 }450 } else {451 this.restorePlainText();452 }453 } else {454 this.restorePlainText();455 }456 return this.clearPastedStrings();457 }458 };459 MarkdownEditor.prototype.restorePlainText = function() {460 return this.replace(this.getTextArray(), this.pastedStrings['text/plain'], this.getSelectionStart(), this.getSelectionEnd());461 };462 MarkdownEditor.prototype.tableFunction = function(e, text, currentLine) {463 var col, currentCellText, data, inCaseSensitiveFunction, inputFunction, k, len, match, result, row, tableFunction;464 if (this.isSelectRange()) {465 return;466 }467 col = this.getCurrentCol(text, currentLine) - 1;468 row = this.getCurrentRow(text);469 if (col < 0) {470 return;471 }472 if (row == null) {473 return;474 }475 e.preventDefault();476 data = this.getCurrentTableData(text);477 currentCellText = data.lines[row].values[col];478 if (typeof currentCellText !== 'string') {479 return;480 }481 match = currentCellText.match(functionFormat);482 if (!match) {483 return;484 }485 inputFunction = match[1];486 inCaseSensitiveFunction = new RegExp("^" + inputFunction + "$", 'i');487 for (k = 0, len = tableFunctions.length; k < len; k++) {488 tableFunction = tableFunctions[k];489 if (tableFunction.match(inCaseSensitiveFunction)) {490 result = this[tableFunction + "TableFunction"](data, col, row);491 if (result != null) {492 this.replaceCurrentCol(text, result);493 }494 return;495 }496 }497 };498 MarkdownEditor.prototype.countTableFunction = function(data, col, row) {499 return data.lines.length - 1;500 };501 MarkdownEditor.prototype.maxTableFunction = function(data, col, row) {502 var k, len, line, max, number, ref;503 max = -Infinity;504 ref = data.lines;505 for (k = 0, len = ref.length; k < len; k++) {506 line = ref[k];507 if (typeof line.values[col] === 'number' && max < line.values[col]) {508 max = line.values[col];509 } else {510 number = parseFloat(line.values[col]);511 if ((number != null) && !isNaN(number) && max < number) {512 max = number;513 }514 }515 }516 if (max === -Infinity) {517 return null;518 }519 return max;520 };521 MarkdownEditor.prototype.round = function(num) {522 var w;523 w = Math.pow(10, this.options.significantFigures);524 return Math.round(num * w) / w;525 };526 MarkdownEditor.prototype.minTableFunction = function(data, col, row) {527 var k, len, line, min, number, ref;528 min = Infinity;529 ref = data.lines;530 for (k = 0, len = ref.length; k < len; k++) {531 line = ref[k];532 if (typeof line.values[col] === 'number' && min > line.values[col]) {533 min = line.values[col];534 } else {535 number = parseFloat(line.values[col]);536 if ((number != null) && !isNaN(number) && min > number) {537 min = number;538 }539 }540 }541 if (min === Infinity) {542 return null;543 }544 return min;545 };546 MarkdownEditor.prototype.averageTableFunction = function(data, col, row) {547 return this.round(this.sumTableFunction(data, col, row) / this.countTableFunction(data, col, row));548 };549 MarkdownEditor.prototype.sumTableFunction = function(data, col, row) {550 var k, len, line, number, ref, sum;551 sum = 0.0;552 ref = data.lines;553 for (k = 0, len = ref.length; k < len; k++) {554 line = ref[k];555 if (typeof line.values[col] === 'number') {556 sum += line.values[col];557 } else {558 number = parseFloat(line.values[col]);559 if ((number != null) && !isNaN(number)) {560 sum += number;561 }562 }563 }564 return this.round(sum);565 };566 MarkdownEditor.prototype.replaceCurrentCol = function(text, str, pos) {567 var ep, sp;568 if (pos == null) {569 pos = this.getSelectionStart();570 }571 sp = pos;572 ep = pos;573 while (sp > 0 && text[sp - 1] !== '|') {574 sp--;575 }576 while (text[ep] && text[ep] !== '|') {577 ep++;578 }579 return this.replace(text, " " + str + " ", sp, ep, true);580 };581 MarkdownEditor.prototype.sortTable = function(e, text, currentLine) {582 var asc, base, body, col, data, i, k, l, len, line, prevPos, ref, ref1;583 if (this.isSelectRange() || !this.isTableHeader(text)) {584 return;585 }586 e.preventDefault();587 prevPos = this.getSelectionStart();588 col = this.getCurrentCol(text, currentLine) - 1;589 data = this.getCurrentTableData(text);590 asc = false;591 for (i = k = 1, ref = data.lines.length; 1 <= ref ? k < ref : k > ref; i = 1 <= ref ? ++k : --k) {592 if (0 < this.compare(data.lines[i - 1].values[col], data.lines[i].values[col])) {593 asc = true;594 break;595 }596 }597 data.lines.sort((function(_this) {598 return function(a, b) {599 return _this.compare(a.values[col], b.values[col], asc);600 };601 })(this));602 body = '';603 ref1 = data.lines;604 for (l = 0, len = ref1.length; l < len; l++) {605 line = ref1[l];606 body += line.text + "\n";607 }608 this.replace(text, body, data.bodyStart, data.bodyEnd);609 this.setSelectionRange(prevPos, prevPos);610 return typeof (base = this.options).onSortedTable === "function" ? base.onSortedTable(e) : void 0;611 };612 MarkdownEditor.prototype.compare = function(a, b, asc) {613 var x;614 if (asc == null) {615 asc = true;616 }617 x = asc ? 1 : -1;618 if (this.isEmpty(a)) {619 return -1 * x;620 }621 if (this.isEmpty(b)) {622 return 1 * x;623 }624 if (a === b) {625 return 0;626 }627 return (a < b ? -1 : 1) * x;628 };629 MarkdownEditor.prototype.getCurrentCol = function(text, currentLine) {630 var count, i, k, pos, ref, row;631 row = this.replaceEscapedPipe(currentLine);632 pos = this.getSelectionStart() - this.getPosBeginningOfLine(text, this.getSelectionStart());633 count = 0;634 for (i = k = 0, ref = Math.min(pos, row.length); 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {635 if (row[i] === '|') {636 count++;637 }638 }639 return count;640 };641 MarkdownEditor.prototype.getCurrentRow = function(text, pos) {642 var line, row;643 if (pos == null) {644 pos = this.getSelectionStart();645 }646 pos = this.getPosEndOfLine(text, pos) - 1;647 row = 0;648 line = this.getCurrentLine(text, pos);649 while (this.replaceEscapedPipe(line).match(rowFormat)) {650 pos -= line.length + 1;651 line = this.getCurrentLine(text, pos);652 row++;653 }654 if (row < 3) {655 return null;656 }657 return row - 3;658 };659 MarkdownEditor.prototype.isEmpty = function(v) {660 return v === null || v === void 0 || v === '';661 };662 MarkdownEditor.prototype.getTableStart = function(text, pos) {663 var line;664 if (pos == null) {665 pos = this.getSelectionStart();666 }667 pos = this.getPosEndOfLine(text, pos) - 1;668 line = this.getCurrentLine(text, pos);669 while (this.replaceEscapedPipe(line).match(rowFormat)) {670 pos -= line.length + 1;671 line = this.getCurrentLine(text, pos);672 }673 return pos + 2;674 };675 MarkdownEditor.prototype.isTableLine = function(text) {676 return text.match(rowFormat);677 };678 MarkdownEditor.prototype.getCurrentTableData = function(text, pos) {679 var base, data, i, k, len, line, newLineLeft, v, values;680 if (pos == null) {681 pos = this.getSelectionStart();682 }683 pos = this.getTableStart(text, pos);684 newLineLeft = 2;685 while (newLineLeft > 0 && (text[pos] != null)) {686 if (text[pos] === "\n") {687 newLineLeft--;688 }689 pos++;690 }691 data = {692 bodyStart: pos,693 lines: []694 };695 while ((text[pos] != null) && this.isTableBody(text, pos)) {696 line = this.getCurrentLine(text, pos - 1);697 if (line.length <= 0) {698 break;699 }700 values = this.replaceEscapedPipe(line.slice(1, -1)).split('|');701 for (i = k = 0, len = values.length; k < len; i = ++k) {702 v = values[i];703 values[i] = this.trim(v);704 if (typeof (base = values[i]).match === "function" ? base.match(numberFormat) : void 0) {705 values[i] = +values[i];706 }707 }708 data.lines.push({709 text: line,710 values: values711 });712 pos += line.length + 1;713 }714 data.bodyEnd = pos;715 return data;716 };717 MarkdownEditor.prototype.trim = function(str) {718 return str.replace(/^\s+/, '').replace(/\s+$/, '');719 };720 MarkdownEditor.prototype.isSelectRange = function() {721 return this.getSelectionStart() !== this.getSelectionEnd();722 };723 MarkdownEditor.prototype.getSelectedText = function() {724 return this.getText().slice(this.getSelectionStart(), this.getSelectionEnd());725 };726 MarkdownEditor.prototype.setSelectionRange = function(selectionBegin, selectionEnd1) {727 this.selectionBegin = selectionBegin;728 this.selectionEnd = selectionEnd1;729 return this.el.setSelectionRange(this.selectionBegin, this.selectionEnd);730 };731 MarkdownEditor.prototype.replaceEscapedPipe = function(text) {732 return text.replace(/\\\|/g, '..');733 };734 MarkdownEditor.prototype.isTableHeader = function(text, pos) {735 var line;736 if (text == null) {737 text = this.getTextArray();738 }739 if (pos == null) {740 pos = this.getSelectionStart();741 }742 pos = this.getPosEndOfLine(text, pos);743 line = this.getCurrentLine(text, pos);744 return !!line.match(rowSepFormat);745 };746 MarkdownEditor.prototype.isTableBody = function(textArray, pos) {747 var line;748 if (textArray == null) {749 textArray = this.getTextArray();750 }751 if (pos == null) {752 pos = this.getSelectionStart() - 1;753 }754 line = this.replaceEscapedPipe(this.getCurrentLine(textArray, pos));755 while (line.match(rowFormat) && pos > 0) {756 if (line.match(rowSepFormat)) {757 return true;758 }759 pos = this.getPosBeginningOfLine(textArray, pos) - 2;760 line = this.replaceEscapedPipe(this.getCurrentLine(textArray, pos));761 }762 return false;763 };764 MarkdownEditor.prototype.getPrevLine = function(textArray, pos) {765 if (pos == null) {766 pos = this.getSelectionStart() - 1;767 }768 pos = this.getPosBeginningOfLine(textArray, pos);769 return this.getCurrentLine(textArray, pos - 2);770 };771 MarkdownEditor.prototype.getPosEndOfLine = function(textArray, pos) {772 if (pos == null) {773 pos = this.getSelectionStart();774 }775 while (textArray[pos] && textArray[pos] !== "\n") {776 pos++;777 }778 return pos;779 };780 MarkdownEditor.prototype.getPosBeginningOfLine = function(textArray, pos) {781 if (pos == null) {782 pos = this.getSelectionStart();783 }784 while (textArray[pos - 1] && textArray[pos - 1] !== "\n") {785 pos--;786 }787 return pos;788 };789 MarkdownEditor.prototype.getPosBeginningOfLines = function(text, startPos, endPos) {790 var beginningPositions, k, pos, ref, ref1;791 if (startPos == null) {792 startPos = this.getSelectionStart();793 }794 if (endPos == null) {795 endPos = this.getSelectionEnd();796 }797 beginningPositions = [this.getPosBeginningOfLine(text, startPos)];798 startPos = this.getPosEndOfLine(startPos) + 1;799 if (startPos < endPos) {800 for (pos = k = ref = startPos, ref1 = endPos; ref <= ref1 ? k <= ref1 : k >= ref1; pos = ref <= ref1 ? ++k : --k) {801 if (!text[pos]) {802 break;803 }804 if (pos > 0 && text[pos - 1] === "\n") {805 beginningPositions.push(pos);806 }807 }808 }809 return beginningPositions;810 };811 MarkdownEditor.prototype.getCurrentLine = function(text, initPos) {812 var afterChars, beforeChars, pos;813 if (text == null) {814 text = this.getText();815 }816 if (initPos == null) {817 initPos = this.getSelectionStart() - 1;818 }819 pos = initPos;820 beforeChars = '';821 while (text[pos] && text[pos] !== "\n") {822 beforeChars = "" + text[pos] + beforeChars;823 pos--;824 }825 pos = initPos + 1;826 afterChars = '';827 while (text[pos] && text[pos] !== "\n") {828 afterChars = "" + afterChars + text[pos];829 pos++;830 }831 return "" + beforeChars + afterChars;832 };833 MarkdownEditor.prototype.removeCurrentLine = function(textArray) {834 var beginPos, endPos;835 endPos = this.getPosEndOfLine(textArray);836 beginPos = this.getPosBeginningOfLine(textArray);837 return this.replace(textArray, '', beginPos, endPos);838 };839 MarkdownEditor.prototype.onPressTab = function(e) {840 e.preventDefault();841 if (this.options.table && this.moveCursorOnTableCell(e)) {842 return;843 }844 if (this.options.tabToSpace) {845 return this.tabToSpace(e);846 }847 };848 MarkdownEditor.prototype.withCtrl = function(e) {849 var preventDefault;850 if (!this.options.fontDecorate) {851 return;852 }853 preventDefault = (function() {854 switch (e.which) {855 case KeyCodes.b:856 return this.wrap('**');857 case KeyCodes.i:858 return this.wrap('_');859 case KeyCodes.u:860 return this.wrap('~~');861 case KeyCodes.q:862 return this.wrap('`');863 }864 }).call(this);865 if (preventDefault != null) {866 return e.preventDefault();867 }868 };869 MarkdownEditor.prototype.wrap = function(wrapper) {870 var beginningOfLines, selectedText, selectionEnd, selectionStart, text;871 selectionStart = this.getSelectionStart();872 selectionEnd = this.getSelectionEnd();873 if (selectionStart === selectionEnd) {874 return;875 }876 text = this.getTextArray();877 beginningOfLines = this.getPosBeginningOfLines(text, selectionStart, selectionEnd);878 if (beginningOfLines.length > 1) {879 return false;880 }881 selectedText = text.slice(selectionStart, selectionEnd).join('');882 this.replace(text, "" + wrapper + selectedText + wrapper, selectionStart, selectionEnd);883 this.setSelectionRange(selectionStart + wrapper.length, selectionEnd + wrapper.length);884 return true;885 };886 MarkdownEditor.prototype.moveCursorOnTableCell = function(e) {887 var currentLine, text;888 text = this.replaceEscapedPipe(this.getText());889 currentLine = this.getCurrentLine(text);890 if (!currentLine.match(rowFormat)) {891 return false;892 }893 if (e.shiftKey) {894 this.moveToPrevCell(text);895 } else {896 this.moveToNextCell(text);897 }898 return true;899 };900 MarkdownEditor.prototype.tabToSpace = function(e) {901 var beginningOfLines, currentLine, currentPos, text;902 text = this.getTextArray();903 currentPos = this.getSelectionStart();904 beginningOfLines = this.getPosBeginningOfLines(text, currentPos);905 if (beginningOfLines.length <= 1) {906 currentLine = this.getCurrentLine(text, beginningOfLines[0]);907 if (this.options.list && currentLine.match(listFormat) && !currentLine.match(hrFormat)) {908 return this.insertSpacesToBeginningOfLines(text, currentPos, beginningOfLines, e.shiftKey);909 } else if (!e.shiftKey) {910 return this.insert(text, this.tabSpaces);911 }912 } else {913 return this.insertSpacesToBeginningOfLines(text, currentPos, beginningOfLines, e.shiftKey);914 }915 };916 MarkdownEditor.prototype.insertSpacesToBeginningOfLines = function(text, currentPos, beginningOfLines, isBack) {917 var beginPos, currentLine, dPos, i, k, l, len, listPositions, m, pos, ref, ref1;918 listPositions = [];919 dPos = 0;920 for (k = 0, len = beginningOfLines.length; k < len; k++) {921 pos = beginningOfLines[k];922 pos += dPos;923 currentLine = this.getCurrentLine(text, pos);924 listPositions.push(pos);925 if (isBack) {926 if (currentLine.indexOf(this.tabSpaces) === 0) {927 text.splice(pos, this.options.tabSize);928 dPos -= this.options.tabSize;929 }930 } else {931 for (i = l = 0, ref = this.options.tabSize; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {932 text.splice(pos, 0, ' ');933 }934 dPos += this.options.tabSize;935 }936 }937 this.el.value = text.join('');938 if (listPositions.length > 1) {939 return this.setSelectionRange(listPositions[0], this.getPosEndOfLine(text, listPositions[listPositions.length - 1]));940 } else {941 if (dPos < 0) {942 beginPos = this.getPosBeginningOfLine(text, currentPos + dPos);943 for (i = m = -1, ref1 = -this.options.tabSize; -1 <= ref1 ? m <= ref1 : m >= ref1; i = -1 <= ref1 ? ++m : --m) {944 if ((!text[currentPos + i] || text[currentPos + i] === "\n") && listPositions[0] > beginPos) {945 currentPos = listPositions[0] - dPos;946 break;947 }948 }949 }950 return this.setSelectionRange(currentPos + dPos, currentPos + dPos);951 }952 };953 MarkdownEditor.prototype.moveToPrevCell = function(text, pos) {954 var ep, epAdded, overSep, prevLine, sp, ssp;955 if (pos == null) {956 pos = this.getSelectionStart() - 1;957 }958 overSep = false;959 prevLine = false;960 ep = pos;961 while (text[ep]) {962 if (overSep && ep < 0 || !overSep && ep <= 0) {963 return false;964 }965 if (prevLine && text[ep] !== ' ' && text[ep] !== '|') {966 return false;967 }968 if (!overSep) {969 if (text[ep] === '|') {970 overSep = true;971 prevLine = false;972 }973 } else if (text[ep] !== ' ') {974 if (text[ep] === "\n") {975 overSep = false;976 prevLine = true;977 } else {978 if (text[ep] === '|') {979 ep++;980 }981 if (text[ep] === ' ') {982 ep++;983 }984 break;985 }986 }987 ep--;988 }989 if (ep < 0) {990 return false;991 }992 ssp = sp = ep;993 epAdded = false;994 while (text[sp] && text[sp] !== '|') {995 if (text[sp] !== ' ') {996 ssp = sp;997 if (!epAdded) {998 ep++;999 epAdded = true;1000 }1001 }1002 sp--;1003 }1004 this.setSelectionRange(ssp, ep);1005 return true;1006 };1007 MarkdownEditor.prototype.moveToNextCell = function(text, pos) {1008 var eep, ep, overSep, overSepSpace, sp;1009 if (pos == null) {1010 pos = this.getSelectionStart();1011 }1012 overSep = false;1013 overSepSpace = false;1014 eep = null;1015 sp = pos;1016 while (text[sp]) {1017 if (sp > 0 && text[sp - 1] === "\n" && text[sp] !== '|') {1018 sp--;1019 eep = sp;1020 break;1021 }1022 if (!overSep) {1023 if (text[sp] === '|') {1024 overSep = true;1025 }1026 } else if (text[sp] !== ' ') {1027 if (text[sp] === "\n") {1028 overSep = false;1029 } else {1030 break;1031 }1032 } else {1033 if (overSepSpace) {1034 break;1035 }1036 overSepSpace = true;1037 }1038 sp++;1039 }1040 if (!text[sp]) {1041 sp--;1042 eep = sp;1043 }1044 if (!eep) {1045 eep = ep = sp;1046 while (text[ep] && text[ep] !== '|') {1047 if (text[ep] !== ' ') {1048 eep = ep + 1;1049 }1050 ep++;1051 }1052 }1053 this.setSelectionRange(sp, eep);1054 return true;1055 };1056 MarkdownEditor.prototype.insert = function(textArray, insertText, pos) {1057 if (pos == null) {1058 pos = this.getSelectionStart();1059 }1060 return this.replace(textArray, insertText, pos, pos);1061 };1062 MarkdownEditor.prototype.replace = function(textArray, text, beginPos, endPos, select) {1063 var error1, result;1064 if (select == null) {1065 select = false;1066 }1067 this.setSelectionRange(beginPos, endPos);1068 try {1069 result = typeof document.execCommand === "function" ? document.execCommand('insertText', false, text) : void 0;1070 } catch (error1) {1071 result = false;1072 }1073 if (!result) {1074 this.replaceValue(textArray, text, beginPos, endPos);1075 }1076 if (select) {1077 return this.setSelectionRange(beginPos, beginPos + text.length);1078 }1079 };1080 MarkdownEditor.prototype.replaceValue = function(textArray, insertText, beginPos, endPos) {1081 var error, error1, error2, pos;1082 textArray.splice(beginPos, endPos - beginPos, insertText);1083 try {1084 document.execCommand('ms-beginUndoUnit');1085 } catch (error1) {1086 error = error1;1087 }1088 this.el.value = textArray.join('');1089 try {1090 document.execCommand('ms-endUndoUnit');1091 } catch (error2) {1092 error = error2;1093 }1094 pos = beginPos + insertText.length;1095 return this.setSelectionRange(pos, pos);1096 };1097 MarkdownEditor.prototype.getSelectionStart = function() {1098 return this.el.selectionStart;1099 };1100 MarkdownEditor.prototype.getSelectionEnd = function() {1101 return this.el.selectionEnd;1102 };1103 MarkdownEditor.prototype.destroy = function() {1104 this.el.removeEventListener('keydown');1105 this.el.dataset.markdownEditor = null;1106 return this.el = null;1107 };1108 MarkdownEditor.prototype.startUpload = function(name) {1109 var insertText, pos, text;1110 text = this.getTextArray();1111 pos = this.getSelectionStart();1112 insertText = this.buildUploadingText(name);1113 if (pos > 0 && text[pos - 1] !== "\n") {1114 insertText = "\n" + insertText;1115 }1116 if (pos < text.length - 1 && text[pos] !== "\n") {1117 insertText = insertText + "\n";1118 }1119 return this.replaceValue(text, insertText, pos, pos);1120 };1121 MarkdownEditor.prototype.cancelUpload = function(name) {1122 return this.el.value = this.getText().replace(this.buildUploadingText(name), '');1123 };1124 MarkdownEditor.prototype.buildUploadingText = function(name) {1125 return this.options.uploadingFormat(name);1126 };1127 MarkdownEditor.prototype.finishUpload = function(name, options) {1128 var finishedUploadText, pos, selectionEnd, selectionStart, text, uploadingText, uploadingTextPos;1129 if (options == null) {1130 options = {};1131 }1132 text = this.getText();1133 finishedUploadText = options.text || '';1134 if (finishedUploadText.length <= 0 && options.url || options.alt) {1135 finishedUploadText = "![" + (options.alt || '') + "](" + (options.url || '') + ")";1136 if (options.href != null) {1137 finishedUploadText = "[" + finishedUploadText + "](" + options.href + ")";1138 }1139 }1140 uploadingText = this.buildUploadingText(name);1141 uploadingTextPos = text.indexOf(uploadingText);1142 if (uploadingTextPos >= 0) {1143 selectionStart = this.getSelectionStart();1144 selectionEnd = this.getSelectionEnd();1145 return this.replaceValue(this.getTextArray(), finishedUploadText, uploadingTextPos, uploadingTextPos + uploadingText.length);1146 } else {1147 pos = this.getSelectionStart();1148 return this.replaceValue(this.getTextArray(), finishedUploadText, pos, pos);1149 }1150 };1151 return MarkdownEditor;1152 })();1153 defaultOptions = {1154 tabSize: 4,1155 onInsertedList: null,1156 onInsertedTable: null,1157 onInsertedCodeblock: null,1158 onSortedTable: null,1159 onMadeTable: null,1160 convertSheetToTable: true,1161 tabToSpace: true,...

Full Screen

Full Screen

jquery.textarea-markdown-editor.js

Source:jquery.textarea-markdown-editor.js Github

copy

Full Screen

...93 match = currentLine.match(listFormat);94 if (!match) {95 return;96 }97 pos = this.getSelectionStart();98 if (text[pos] && text[pos] !== "\n") {99 return;100 }101 if (match[5].length <= 0) {102 this.removeCurrentLine(text);103 return;104 }105 extSpace = e.ctrlKey ? this.tabSpaces : '';106 this.insert(text, "\n" + extSpace + match[1]);107 e.preventDefault();108 return typeof (base = this.options).onInsertedList === "function" ? base.onInsertedList(e) : void 0;109 };110 MarkdownEditor.prototype.toggleCheck = function(e, text, currentLine) {111 var line, matches, pos;112 matches = currentLine.match(listFormat);113 if (!matches) {114 return;115 }116 if (!matches[4]) {117 return;118 }119 line = '';120 if (matches[4] === 'x') {121 line = currentLine.replace('[x]', '[ ]');122 } else {123 line = currentLine.replace('[ ]', '[x]');124 }125 pos = this.getSelectionStart();126 this.replaceCurrentLine(text, pos, currentLine, line);127 return e.preventDefault();128 };129 MarkdownEditor.prototype.replaceCurrentLine = function(text, pos, oldLine, newLine) {130 var beginPos;131 beginPos = this.getPosBeginningOfLine(text, pos);132 text.splice(beginPos, oldLine.length, newLine);133 this.el.value = text.join('');134 return this.setSelectionRange(pos, pos);135 };136 MarkdownEditor.prototype.supportInputTableFormat = function(e) {137 var base, char, currentLine, i, k, l, len, m, match, pos, prevPos, ref, ref1, row, rows, selectionStart, sep, text;138 text = this.getTextArray();139 currentLine = this.replaceEscapedPipe(this.getCurrentLine(text));140 selectionStart = this.getSelectionStart();141 match = currentLine.match(rowFormat);142 if (!match) {143 return;144 }145 if (this.isTableHeader(text)) {146 return;147 }148 if (selectionStart === this.getPosBeginningOfLine(text, selectionStart)) {149 return;150 }151 if (currentLine.match(emptyRowFormat) && this.isTableBody(text)) {152 this.removeCurrentLine(text);153 return;154 }155 e.preventDefault();156 rows = -1;157 for (k = 0, len = currentLine.length; k < len; k++) {158 char = currentLine[k];159 if (char === '|') {160 rows++;161 }162 }163 prevPos = this.getPosEndOfLine(text);164 sep = '';165 if (!this.isTableBody(text)) {166 sep = "\n|";167 for (i = l = 0, ref = rows; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {168 sep += " " + this.options.tableSeparator + " |";169 }170 }171 row = "\n|";172 for (i = m = 0, ref1 = rows; 0 <= ref1 ? m < ref1 : m > ref1; i = 0 <= ref1 ? ++m : --m) {173 row += ' |';174 }175 text = this.insert(text, sep + row, prevPos);176 pos = prevPos + sep.length + row.length - rows * 3 + 1;177 this.setSelectionRange(pos, pos);178 return typeof (base = this.options).onInsertedTable === "function" ? base.onInsertedTable(e) : void 0;179 };180 MarkdownEditor.prototype.supportCodeblockFormat = function(e) {181 var base, currentLine, match, selectionStart, text;182 text = this.getTextArray();183 selectionStart = this.getSelectionStart();184 currentLine = this.getCurrentLine(text);185 match = currentLine.match(beginCodeblockFormat);186 if (text[selectionStart + 1] && text[selectionStart + 1] !== "\n") {187 return;188 }189 if (!match) {190 return;191 }192 if (!this.requireCodeblockEnd(text, selectionStart)) {193 return;194 }195 e.preventDefault();196 this.insert(text, "\n\n" + match[1]);197 this.setSelectionRange(selectionStart + 1, selectionStart + 1);198 return typeof (base = this.options).onInsertedCodeblock === "function" ? base.onInsertedCodeblock(e) : void 0;199 };200 MarkdownEditor.prototype.requireCodeblockEnd = function(text, selectionStart) {201 var innerCodeblock, line, pos;202 innerCodeblock = this.isInnerCodeblock(text, selectionStart);203 if (innerCodeblock) {204 return false;205 }206 pos = this.getPosBeginningOfLine(text, selectionStart);207 while (pos <= text.length) {208 line = this.getCurrentLine(text, pos);209 if (innerCodeblock && line.match(endCodeblockFormat)) {210 return false;211 } else if (!innerCodeblock && line.match(beginCodeblockFormat)) {212 innerCodeblock = true;213 }214 pos += line.length + 1;215 }216 return true;217 };218 MarkdownEditor.prototype.isInnerCodeblock = function(text, selectionStart) {219 var endPos, innerCodeblock, line, pos;220 if (selectionStart == null) {221 selectionStart = this.getSelectionStart();222 }223 innerCodeblock = false;224 pos = 0;225 endPos = this.getPosBeginningOfLine(text, selectionStart) - 1;226 while (pos < endPos) {227 line = this.getCurrentLine(text, pos);228 if (innerCodeblock && line.match(endCodeblockFormat)) {229 innerCodeblock = false;230 } else if (!innerCodeblock && line.match(beginCodeblockFormat)) {231 innerCodeblock = true;232 }233 pos += line.length + 1;234 }235 return innerCodeblock;236 };237 MarkdownEditor.prototype.makeTable = function(e, text, currentLine) {238 var alignLeft, alignRight, base, matches, pos, table;239 if (this.isSelectRange()) {240 return;241 }242 matches = currentLine.match(makingTableFormat);243 if (!matches) {244 return;245 }246 e.preventDefault();247 alignLeft = !!matches[1].length;248 alignRight = !!matches[4].length;249 table = this.buildTable(matches[2], matches[3], {250 alignLeft: alignLeft,251 alignRight: alignRight252 });253 pos = this.getPosBeginningOfLine(text);254 this.replaceCurrentLine(text, pos, currentLine, table);255 this.setSelectionRange(pos + 2, pos + 2);256 return typeof (base = this.options).onMadeTable === "function" ? base.onMadeTable(e) : void 0;257 };258 MarkdownEditor.prototype.buildTable = function(rowsCount, colsCount, options) {259 var i, j, k, l, m, n, ref, ref1, ref2, ref3, separator, table;260 if (options == null) {261 options = {};262 }263 separator = "---";264 if (options.alignLeft) {265 separator = ":" + separator;266 }267 if (options.alignRight) {268 separator = separator + ":";269 }270 table = "|";271 for (i = k = 0, ref = rowsCount; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {272 table += ' |';273 }274 table += "\n|";275 for (i = l = 0, ref1 = rowsCount; 0 <= ref1 ? l < ref1 : l > ref1; i = 0 <= ref1 ? ++l : --l) {276 table += " " + separator + " |";277 }278 for (i = m = 0, ref2 = colsCount - 1; 0 <= ref2 ? m < ref2 : m > ref2; i = 0 <= ref2 ? ++m : --m) {279 table += "\n|";280 for (j = n = 0, ref3 = rowsCount; 0 <= ref3 ? n < ref3 : n > ref3; j = 0 <= ref3 ? ++n : --n) {281 table += " |";282 }283 }284 return table;285 };286 MarkdownEditor.prototype.csvToTable = function(e, text, currentLine) {287 var base, cell, csvLines, endPos, i, j, k, l, len, len1, len2, line, lines, m, n, ref, rows, selectedText, startPos, table;288 selectedText = this.getSelectedText();289 lines = selectedText.split("\n");290 if (lines.length <= 1) {291 return;292 }293 startPos = null;294 endPos = this.getSelectionStart();295 csvLines = [];296 for (k = 0, len = lines.length; k < len; k++) {297 line = lines[k];298 rows = line.split(',');299 if (rows.length > 1) {300 csvLines.push(rows);301 if (startPos == null) {302 startPos = endPos;303 }304 } else if (csvLines.length > 0) {305 break;306 }307 endPos += line.length + 1;308 }309 if (csvLines <= 1) {310 return;311 }312 e.preventDefault();313 table = '';314 for (i = l = 0, len1 = csvLines.length; l < len1; i = ++l) {315 line = csvLines[i];316 table += "|";317 for (m = 0, len2 = line.length; m < len2; m++) {318 cell = line[m];319 table += " " + (this.trim(cell)) + " |";320 }321 table += "\n";322 if (i === 0) {323 table += "|";324 for (j = n = 0, ref = line.length; 0 <= ref ? n < ref : n > ref; j = 0 <= ref ? ++n : --n) {325 table += " " + this.options.tableSeparator + " |";326 }327 table += "\n";328 }329 }330 text.splice(startPos, endPos - startPos, table);331 this.el.value = text.join('');332 return typeof (base = this.options).onMadeTable === "function" ? base.onMadeTable(e) : void 0;333 };334 MarkdownEditor.prototype.tableFunction = function(e, text, currentLine) {335 var col, currentCellText, data, inCaseSensitiveFunction, inputFunction, k, len, match, result, row, tableFunction;336 if (this.isSelectRange()) {337 return;338 }339 col = this.getCurrentCol(text, currentLine) - 1;340 row = this.getCurrentRow(text);341 if (col < 0) {342 return;343 }344 if (row == null) {345 return;346 }347 e.preventDefault();348 data = this.getCurrentTableData(text);349 currentCellText = data.lines[row].values[col];350 if (typeof currentCellText !== 'string') {351 return;352 }353 match = currentCellText.match(functionFormat);354 if (!match) {355 return;356 }357 inputFunction = match[1];358 inCaseSensitiveFunction = new RegExp("^" + inputFunction + "$", 'i');359 for (k = 0, len = tableFunctions.length; k < len; k++) {360 tableFunction = tableFunctions[k];361 if (tableFunction.match(inCaseSensitiveFunction)) {362 result = this[tableFunction + "TableFunction"](data, col, row);363 if (result != null) {364 this.replaceCurrentCol(text, result);365 }366 return;367 }368 }369 };370 MarkdownEditor.prototype.countTableFunction = function(data, col, row) {371 return data.lines.length - 1;372 };373 MarkdownEditor.prototype.maxTableFunction = function(data, col, row) {374 var k, len, line, max, number, ref;375 max = -Infinity;376 ref = data.lines;377 for (k = 0, len = ref.length; k < len; k++) {378 line = ref[k];379 if (typeof line.values[col] === 'number' && max < line.values[col]) {380 max = line.values[col];381 } else {382 number = parseFloat(line.values[col]);383 if ((number != null) && !isNaN(number) && max < number) {384 max = number;385 }386 }387 }388 if (max === -Infinity) {389 return null;390 }391 return max;392 };393 MarkdownEditor.prototype.round = function(num) {394 var w;395 w = Math.pow(10, this.options.significantFigures);396 return Math.round(num * w) / w;397 };398 MarkdownEditor.prototype.minTableFunction = function(data, col, row) {399 var k, len, line, min, number, ref;400 min = Infinity;401 ref = data.lines;402 for (k = 0, len = ref.length; k < len; k++) {403 line = ref[k];404 if (typeof line.values[col] === 'number' && min > line.values[col]) {405 min = line.values[col];406 } else {407 number = parseFloat(line.values[col]);408 if ((number != null) && !isNaN(number) && min > number) {409 min = number;410 }411 }412 }413 if (min === Infinity) {414 return null;415 }416 return min;417 };418 MarkdownEditor.prototype.averageTableFunction = function(data, col, row) {419 return this.round(this.sumTableFunction(data, col, row) / this.countTableFunction(data, col, row));420 };421 MarkdownEditor.prototype.sumTableFunction = function(data, col, row) {422 var k, len, line, number, ref, sum;423 sum = 0.0;424 ref = data.lines;425 for (k = 0, len = ref.length; k < len; k++) {426 line = ref[k];427 if (typeof line.values[col] === 'number') {428 sum += line.values[col];429 } else {430 number = parseFloat(line.values[col]);431 if ((number != null) && !isNaN(number)) {432 sum += number;433 }434 }435 }436 return this.round(sum);437 };438 MarkdownEditor.prototype.replaceCurrentCol = function(text, str, pos) {439 var ep, sp;440 if (pos == null) {441 pos = this.getSelectionStart();442 }443 sp = pos;444 ep = pos;445 while (sp > 0 && text[sp - 1] !== '|') {446 sp--;447 }448 while (text[ep] && text[ep] !== '|') {449 ep++;450 }451 text.splice(sp, ep - sp, " " + str + " ");452 this.el.value = text.join('');453 return this.setSelectionRange(sp + 1, sp + ("" + str).length + 1);454 };455 MarkdownEditor.prototype.sortTable = function(e, text, currentLine) {456 var asc, base, body, col, data, i, k, l, len, line, prevPos, ref, ref1;457 if (this.isSelectRange() || !this.isTableHeader(text)) {458 return;459 }460 e.preventDefault();461 prevPos = this.getSelectionStart();462 col = this.getCurrentCol(text, currentLine) - 1;463 data = this.getCurrentTableData(text);464 asc = false;465 for (i = k = 1, ref = data.lines.length; 1 <= ref ? k < ref : k > ref; i = 1 <= ref ? ++k : --k) {466 if (0 < this.compare(data.lines[i - 1].values[col], data.lines[i].values[col])) {467 asc = true;468 break;469 }470 }471 data.lines.sort((function(_this) {472 return function(a, b) {473 return _this.compare(a.values[col], b.values[col], asc);474 };475 })(this));476 body = '';477 ref1 = data.lines;478 for (l = 0, len = ref1.length; l < len; l++) {479 line = ref1[l];480 body += line.text + "\n";481 }482 text.splice(data.bodyStart, body.length, body);483 this.el.value = text.join('');484 this.setSelectionRange(prevPos, prevPos);485 return typeof (base = this.options).onSortedTable === "function" ? base.onSortedTable(e) : void 0;486 };487 MarkdownEditor.prototype.compare = function(a, b, asc) {488 var x;489 if (asc == null) {490 asc = true;491 }492 x = asc ? 1 : -1;493 if (this.isEmpty(a)) {494 return -1 * x;495 }496 if (this.isEmpty(b)) {497 return 1 * x;498 }499 if (a === b) {500 return 0;501 }502 return (a < b ? -1 : 1) * x;503 };504 MarkdownEditor.prototype.getCurrentCol = function(text, currentLine) {505 var count, i, k, pos, ref, row;506 row = this.replaceEscapedPipe(currentLine);507 pos = this.getSelectionStart() - this.getPosBeginningOfLine(text, this.getSelectionStart());508 count = 0;509 for (i = k = 0, ref = Math.min(pos, row.length); 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {510 if (row[i] === '|') {511 count++;512 }513 }514 return count;515 };516 MarkdownEditor.prototype.getCurrentRow = function(text, pos) {517 var line, row;518 if (pos == null) {519 pos = this.getSelectionStart();520 }521 pos = this.getPosEndOfLine(text, pos) - 1;522 row = 0;523 line = this.getCurrentLine(text, pos);524 while (this.replaceEscapedPipe(line).match(rowFormat)) {525 pos -= line.length + 1;526 line = this.getCurrentLine(text, pos);527 row++;528 }529 if (row < 3) {530 return null;531 }532 return row - 3;533 };534 MarkdownEditor.prototype.isEmpty = function(v) {535 return v === null || v === void 0 || v === '';536 };537 MarkdownEditor.prototype.getTableStart = function(text, pos) {538 var line;539 if (pos == null) {540 pos = this.getSelectionStart();541 }542 pos = this.getPosEndOfLine(text, pos) - 1;543 line = this.getCurrentLine(text, pos);544 while (this.replaceEscapedPipe(line).match(rowFormat)) {545 pos -= line.length + 1;546 line = this.getCurrentLine(text, pos);547 }548 return pos + 2;549 };550 MarkdownEditor.prototype.isTableLine = function(text) {551 return text.match(rowFormat);552 };553 MarkdownEditor.prototype.getCurrentTableData = function(text, pos) {554 var base, data, i, k, len, line, newLineLeft, v, values;555 if (pos == null) {556 pos = this.getSelectionStart();557 }558 pos = this.getTableStart(text, pos);559 newLineLeft = 2;560 while (newLineLeft > 0 && (text[pos] != null)) {561 if (text[pos] === "\n") {562 newLineLeft--;563 }564 pos++;565 }566 data = {567 bodyStart: pos,568 lines: []569 };570 while ((text[pos] != null) && this.isTableBody(text, pos)) {571 line = this.getCurrentLine(text, pos - 1);572 if (line.length <= 0) {573 break;574 }575 values = this.replaceEscapedPipe(line.slice(1, -1)).split('|');576 for (i = k = 0, len = values.length; k < len; i = ++k) {577 v = values[i];578 values[i] = this.trim(v);579 if (typeof (base = values[i]).match === "function" ? base.match(numberFormat) : void 0) {580 values[i] = +values[i];581 }582 }583 data.lines.push({584 text: line,585 values: values586 });587 pos += line.length + 1;588 }589 data.bodyEnd = pos;590 return data;591 };592 MarkdownEditor.prototype.trim = function(str) {593 return str.replace(/^\s+/, '').replace(/\s+$/, '');594 };595 MarkdownEditor.prototype.isSelectRange = function() {596 return this.getSelectionStart() !== this.getSelectionEnd();597 };598 MarkdownEditor.prototype.getSelectedText = function() {599 return this.getText().slice(this.getSelectionStart(), this.getSelectionEnd());600 };601 MarkdownEditor.prototype.setSelectionRange = function(selectionBegin, selectionEnd1) {602 this.selectionBegin = selectionBegin;603 this.selectionEnd = selectionEnd1;604 return this.el.setSelectionRange(this.selectionBegin, this.selectionEnd);605 };606 MarkdownEditor.prototype.replaceEscapedPipe = function(text) {607 return text.replace(/\\\|/g, '..');608 };609 MarkdownEditor.prototype.isTableHeader = function(text, pos) {610 var line;611 if (text == null) {612 text = this.getTextArray();613 }614 if (pos == null) {615 pos = this.getSelectionStart();616 }617 pos = this.getPosEndOfLine(text, pos);618 line = this.getCurrentLine(text, pos);619 return !!line.match(rowSepFormat);620 };621 MarkdownEditor.prototype.isTableBody = function(textArray, pos) {622 var line;623 if (textArray == null) {624 textArray = this.getTextArray();625 }626 if (pos == null) {627 pos = this.getSelectionStart() - 1;628 }629 line = this.replaceEscapedPipe(this.getCurrentLine(textArray, pos));630 while (line.match(rowFormat) && pos > 0) {631 if (line.match(rowSepFormat)) {632 return true;633 }634 pos = this.getPosBeginningOfLine(textArray, pos) - 2;635 line = this.replaceEscapedPipe(this.getCurrentLine(textArray, pos));636 }637 return false;638 };639 MarkdownEditor.prototype.getPrevLine = function(textArray, pos) {640 if (pos == null) {641 pos = this.getSelectionStart() - 1;642 }643 pos = this.getPosBeginningOfLine(textArray, pos);644 return this.getCurrentLine(textArray, pos - 2);645 };646 MarkdownEditor.prototype.getPosEndOfLine = function(textArray, pos) {647 if (pos == null) {648 pos = this.getSelectionStart();649 }650 while (textArray[pos] && textArray[pos] !== "\n") {651 pos++;652 }653 return pos;654 };655 MarkdownEditor.prototype.getPosBeginningOfLine = function(textArray, pos) {656 if (pos == null) {657 pos = this.getSelectionStart();658 }659 while (textArray[pos - 1] && textArray[pos - 1] !== "\n") {660 pos--;661 }662 return pos;663 };664 MarkdownEditor.prototype.getPosBeginningOfLines = function(text, startPos, endPos) {665 var beginningPositions, k, pos, ref, ref1;666 if (startPos == null) {667 startPos = this.getSelectionStart();668 }669 if (endPos == null) {670 endPos = this.getSelectionEnd();671 }672 beginningPositions = [this.getPosBeginningOfLine(text, startPos)];673 startPos = this.getPosEndOfLine(startPos) + 1;674 if (startPos < endPos) {675 for (pos = k = ref = startPos, ref1 = endPos; ref <= ref1 ? k <= ref1 : k >= ref1; pos = ref <= ref1 ? ++k : --k) {676 if (!text[pos]) {677 break;678 }679 if (pos > 0 && text[pos - 1] === "\n") {680 beginningPositions.push(pos);681 }682 }683 }684 return beginningPositions;685 };686 MarkdownEditor.prototype.getCurrentLine = function(text, initPos) {687 var afterChars, beforeChars, pos;688 if (text == null) {689 text = this.getText();690 }691 if (initPos == null) {692 initPos = this.getSelectionStart() - 1;693 }694 pos = initPos;695 beforeChars = '';696 while (text[pos] && text[pos] !== "\n") {697 beforeChars = "" + text[pos] + beforeChars;698 pos--;699 }700 pos = initPos + 1;701 afterChars = '';702 while (text[pos] && text[pos] !== "\n") {703 afterChars = "" + afterChars + text[pos];704 pos++;705 }706 return "" + beforeChars + afterChars;707 };708 MarkdownEditor.prototype.removeCurrentLine = function(textArray) {709 var beginPos, endPos, removeLength;710 endPos = this.getPosEndOfLine(textArray);711 beginPos = this.getPosBeginningOfLine(textArray);712 removeLength = endPos - beginPos;713 textArray.splice(beginPos, removeLength);714 this.el.value = textArray.join('');715 return this.setSelectionRange(beginPos, beginPos);716 };717 MarkdownEditor.prototype.onPressTab = function(e) {718 e.preventDefault();719 if (this.options.table && this.moveCursorOnTableCell(e)) {720 return;721 }722 if (this.options.tabToSpace) {723 return this.tabToSpace(e);724 }725 };726 MarkdownEditor.prototype.withCtrl = function(e) {727 var preventDefault;728 if (!this.options.fontDecorate) {729 return;730 }731 preventDefault = (function() {732 switch (e.which) {733 case KeyCodes.b:734 return this.wrap('**');735 case KeyCodes.i:736 return this.wrap('_');737 case KeyCodes.u:738 return this.wrap('~~');739 case KeyCodes.q:740 return this.wrap('`');741 }742 }).call(this);743 if (preventDefault != null) {744 return e.preventDefault();745 }746 };747 MarkdownEditor.prototype.wrap = function(wrapper) {748 var beginningOfLines, selectionEnd, selectionStart, text;749 selectionStart = this.getSelectionStart();750 selectionEnd = this.getSelectionEnd();751 if (selectionStart === selectionEnd) {752 return;753 }754 text = this.getTextArray();755 beginningOfLines = this.getPosBeginningOfLines(text, selectionStart, selectionEnd);756 if (beginningOfLines.length > 1) {757 return false;758 }759 text.splice(selectionEnd, 0, wrapper);760 text.splice(selectionStart, 0, wrapper);761 this.el.value = text.join('');762 this.setSelectionRange(selectionStart + wrapper.length, selectionEnd + wrapper.length);763 return true;764 };765 MarkdownEditor.prototype.moveCursorOnTableCell = function(e) {766 var currentLine, text;767 text = this.replaceEscapedPipe(this.getText());768 currentLine = this.getCurrentLine(text);769 if (!currentLine.match(rowFormat)) {770 return false;771 }772 if (e.shiftKey) {773 this.moveToPrevCell(text);774 } else {775 this.moveToNextCell(text);776 }777 return true;778 };779 MarkdownEditor.prototype.tabToSpace = function(e) {780 var beginningOfLines, currentLine, currentPos, text;781 text = this.getTextArray();782 currentPos = this.getSelectionStart();783 beginningOfLines = this.getPosBeginningOfLines(text, currentPos);784 if (beginningOfLines.length <= 1) {785 currentLine = this.getCurrentLine(text, beginningOfLines[0]);786 if (this.options.list && currentLine.match(listFormat) && !currentLine.match(hrFormat)) {787 return this.insertSpacesToBeginningOfLines(text, currentPos, beginningOfLines, e.shiftKey);788 } else if (!e.shiftKey) {789 return this.insert(text, this.tabSpaces);790 }791 } else {792 return this.insertSpacesToBeginningOfLines(text, currentPos, beginningOfLines, e.shiftKey);793 }794 };795 MarkdownEditor.prototype.insertSpacesToBeginningOfLines = function(text, currentPos, beginningOfLines, isBack) {796 var beginPos, currentLine, dPos, i, k, l, len, listPositions, m, pos, ref, ref1;797 listPositions = [];798 dPos = 0;799 for (k = 0, len = beginningOfLines.length; k < len; k++) {800 pos = beginningOfLines[k];801 pos += dPos;802 currentLine = this.getCurrentLine(text, pos);803 listPositions.push(pos);804 if (isBack) {805 if (currentLine.indexOf(this.tabSpaces) === 0) {806 text.splice(pos, this.options.tabSize);807 dPos -= this.options.tabSize;808 }809 } else {810 for (i = l = 0, ref = this.options.tabSize; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {811 text.splice(pos, 0, ' ');812 }813 dPos += this.options.tabSize;814 }815 }816 this.el.value = text.join('');817 if (listPositions.length > 1) {818 return this.setSelectionRange(listPositions[0], this.getPosEndOfLine(text, listPositions[listPositions.length - 1]));819 } else {820 if (dPos < 0) {821 beginPos = this.getPosBeginningOfLine(text, currentPos + dPos);822 for (i = m = -1, ref1 = -this.options.tabSize; -1 <= ref1 ? m <= ref1 : m >= ref1; i = -1 <= ref1 ? ++m : --m) {823 if ((!text[currentPos + i] || text[currentPos + i] === "\n") && listPositions[0] > beginPos) {824 currentPos = listPositions[0] - dPos;825 break;826 }827 }828 }829 return this.setSelectionRange(currentPos + dPos, currentPos + dPos);830 }831 };832 MarkdownEditor.prototype.moveToPrevCell = function(text, pos) {833 var ep, epAdded, overSep, prevLine, sp, ssp;834 if (pos == null) {835 pos = this.getSelectionStart() - 1;836 }837 overSep = false;838 prevLine = false;839 ep = pos;840 while (text[ep]) {841 if (overSep && ep < 0 || !overSep && ep <= 0) {842 return false;843 }844 if (prevLine && text[ep] !== ' ' && text[ep] !== '|') {845 return false;846 }847 if (!overSep) {848 if (text[ep] === '|') {849 overSep = true;850 prevLine = false;851 }852 } else if (text[ep] !== ' ') {853 if (text[ep] === "\n") {854 overSep = false;855 prevLine = true;856 } else {857 if (text[ep] === '|') {858 ep++;859 }860 if (text[ep] === ' ') {861 ep++;862 }863 break;864 }865 }866 ep--;867 }868 if (ep < 0) {869 return false;870 }871 ssp = sp = ep;872 epAdded = false;873 while (text[sp] && text[sp] !== '|') {874 if (text[sp] !== ' ') {875 ssp = sp;876 if (!epAdded) {877 ep++;878 epAdded = true;879 }880 }881 sp--;882 }883 this.setSelectionRange(ssp, ep);884 return true;885 };886 MarkdownEditor.prototype.moveToNextCell = function(text, pos) {887 var eep, ep, overSep, overSepSpace, sp;888 if (pos == null) {889 pos = this.getSelectionStart();890 }891 overSep = false;892 overSepSpace = false;893 eep = null;894 sp = pos;895 while (text[sp]) {896 if (sp > 0 && text[sp - 1] === "\n" && text[sp] !== '|') {897 sp--;898 eep = sp;899 break;900 }901 if (!overSep) {902 if (text[sp] === '|') {903 overSep = true;904 }905 } else if (text[sp] !== ' ') {906 if (text[sp] === "\n") {907 overSep = false;908 } else {909 break;910 }911 } else {912 if (overSepSpace) {913 break;914 }915 overSepSpace = true;916 }917 sp++;918 }919 if (!text[sp]) {920 sp--;921 eep = sp;922 }923 if (!eep) {924 eep = ep = sp;925 while (text[ep] && text[ep] !== '|') {926 if (text[ep] !== ' ') {927 eep = ep + 1;928 }929 ep++;930 }931 }932 this.setSelectionRange(sp, eep);933 return true;934 };935 MarkdownEditor.prototype.insertSpaces = function(text, pos) {936 var nextPos;937 nextPos = this.getSelectionStart() + this.tabSpaces.length;938 this.insert(text, this.tabSpaces, pos);939 return this.setSelectionRange(nextPos, nextPos);940 };941 MarkdownEditor.prototype.insert = function(textArray, insertText, pos) {942 if (pos == null) {943 pos = this.getSelectionStart();944 }945 textArray.splice(pos, 0, insertText);946 this.el.value = textArray.join('');947 pos += insertText.length;948 return this.setSelectionRange(pos, pos);949 };950 MarkdownEditor.prototype.getSelectionStart = function() {951 return this.el.selectionStart;952 };953 MarkdownEditor.prototype.getSelectionEnd = function() {954 return this.el.selectionEnd;955 };956 MarkdownEditor.prototype.destroy = function() {957 this.$el.off('keydown.markdownEditor').data('markdownEditor', null);958 return this.$el = null;959 };960 MarkdownEditor.prototype.startUpload = function(name) {961 var insertText, pos, text;962 text = this.getTextArray();963 pos = this.getSelectionStart();964 insertText = this.buildUploadingText(name);965 if (pos > 0 && text[pos - 1] !== "\n") {966 insertText = "\n" + insertText;967 }968 if (pos < text.length - 1 && text[pos] !== "\n") {969 insertText = insertText + "\n";970 }971 return this.insert(text, insertText, pos);972 };973 MarkdownEditor.prototype.cancelUpload = function(name) {974 return this.el.value = this.getText().replace(this.buildUploadingText(name), '');975 };976 MarkdownEditor.prototype.buildUploadingText = function(name) {977 return this.options.uploadingFormat(name);978 };979 MarkdownEditor.prototype.finishUpload = function(name, options) {980 var finishedUploadText, pos, selectionEnd, selectionStart, text, uploadingText, uploadingTextPos;981 if (options == null) {982 options = {};983 }984 text = this.getText();985 finishedUploadText = options.text || '';986 if (finishedUploadText.length <= 0 && options.url || options.alt) {987 finishedUploadText = "![" + (options.alt || '') + "](" + (options.url || '') + ")";988 if (options.href != null) {989 finishedUploadText = "[" + finishedUploadText + "](" + options.href + ")";990 }991 }992 uploadingText = this.buildUploadingText(name);993 uploadingTextPos = text.indexOf(uploadingText);994 if (uploadingTextPos >= 0) {995 selectionStart = this.getSelectionStart();996 selectionEnd = this.getSelectionEnd();997 this.el.value = text.replace(uploadingText, finishedUploadText);998 pos = selectionStart + (finishedUploadText.length - uploadingText.length);999 return this.setSelectionRange(pos, pos);1000 } else {1001 return this.insert(this.getTextArray(), finishedUploadText);1002 }1003 };1004 return MarkdownEditor;1005 })();1006 $.fn.markdownEditor = function(options) {1007 var args, markdownEditor, ref;1008 if (options == null) {1009 options = {};...

Full Screen

Full Screen

zyMacUi.js

Source:zyMacUi.js Github

copy

Full Screen

...23 //firefox24 srcElement = e.target;25 }26 27 KeyPressIndexStart = getSelectionStart(srcElement);28 KeyPressIndexEnd = getSelectionEnd(srcElement);29}3031var nextfield = "str1";32var prevfield = "str1";33var macStrLength = 2;34function doMacStrKeyUp(e){35 with ( document.forms[0] ) {3637 var key;38 var srcElement;39 if(window.event){40 key = window.event.keyCode; //IE41 srcElement = window.event.srcElement;42 }43 else{44 key = e.which; //firefox45 srcElement = e.target;46 }4748 if(key == 37 || key == 38 || key == 39 || key ==40){49 //left, up, right, down50 51 if(key == 37 && getSelectionStart(srcElement) == 0 && KeyPressIndexEnd == 0 && KeyPressIndexStart == 0){52 var element=document.getElementsByName(prevfield)[0];53 eval(prevfield + '.focus();');5455 56 if(srcElement.name != "str1"){57 setSelectionStart(element, element.value.length);58 }59 }else if(key == 39 && getSelectionStart(srcElement) == srcElement.value.length && KeyPressIndexStart == srcElement.value.length){60 var element=document.getElementsByName(nextfield)[0];61 eval(nextfield + '.focus();');62 }6364 65 return true;66 }else if(key == 13){67 //enter68 69 var element=document.getElementsByName(nextfield)[0];70 eval(nextfield + '.focus();');71 element.select();72 return true;73 }else if(key == 46){74 //delete7576 //do nothing77 }else if(key == 35 || key == 36){78 //end, home7980 //do nothing81 }else if(srcElement.value.length == macStrLength && getSelectionStart(srcElement) == srcElement.value.length){82 //others, length = 28384 var element=document.getElementsByName(nextfield)[0];85 eval(nextfield + '.focus();');86 element.select();87 return true;88 89 }else if(srcElement.value.length == 0 && key == 8 && KeyPressIndexStart == 0){90 //backspace, length = 091 92 var element=document.getElementsByName(prevfield)[0];93 eval(prevfield + '.focus();');94 element.select();95 return true;96 97 }else{98 return true;99 }100101 102 }103}104105function getSelectionStart(o) {106 if (o.createTextRange) {107 var r = document.selection.createRange().duplicate()108 r.moveEnd('character', o.value.length)109 if (r.text == '') return o.value.length110 return o.value.lastIndexOf(r.text)111 } else return o.selectionStart112}113114function getSelectionEnd(o) {115 if (o.createTextRange) {116 var r = document.selection.createRange().duplicate()117 r.moveStart('character', -o.value.length)118 return r.text.length119 } else return o.selectionEnd120}121122function setSelectionStart(o, pos){123 if(o.createTextRange) {124 var range = o.createTextRange();125 range.move('character', pos);126 range.select();127 }128 else {129 if(o.selectionStart) {130 o.focus();131 o.setSelectionRange(pos, pos);132 }133 else134 o.focus();135 }136}137function disableEnterKey(e){138 var key;139 if(window.event)140 key = window.event.keyCode; //IE141 else142 key = e.which; //firefox143 if(key == 13)144 return false;145 else146 return true;147}148149var KeyPressIndexStart = "0";150var KeyPressIndexEnd = "0";151function doKeyDownEvent(e){152 var key;153 var srcElement;154 if(window.event){155 //IE156 srcElement = window.event.srcElement;157 }158 else{159 //firefox160 srcElement = e.target;161 }162 163 KeyPressIndexStart = getSelectionStart(srcElement);164 KeyPressIndexEnd = getSelectionEnd(srcElement);165}166167var nextfield = "str1";168var prevfield = "str1";169var macStrLength = 2;170function doMacStrKeyUp(e){171 with ( document.forms[0] ) {172173 var key;174 var srcElement;175 if(window.event){176 key = window.event.keyCode; //IE177 srcElement = window.event.srcElement;178 }179 else{180 key = e.which; //firefox181 srcElement = e.target;182 }183184 if(key == 37 || key == 38 || key == 39 || key ==40){185 //left, up, right, down186 187 if(key == 37 && getSelectionStart(srcElement) == 0 && KeyPressIndexEnd == 0 && KeyPressIndexStart == 0){188 var element=document.getElementsByName(prevfield)[0];189 eval(prevfield + '.focus();');190191 192 if(srcElement.name != "str1"){193 setSelectionStart(element, element.value.length);194 }195 }else if(key == 39 && getSelectionStart(srcElement) == srcElement.value.length && KeyPressIndexStart == srcElement.value.length){196 var element=document.getElementsByName(nextfield)[0];197 eval(nextfield + '.focus();');198 }199200 201 return true;202 }else if(key == 13){203 //enter204 205 var element=document.getElementsByName(nextfield)[0];206 eval(nextfield + '.focus();');207 element.select();208 return true;209 }else if(key == 46){210 //delete211212 //do nothing213 }else if(key == 35 || key == 36){214 //end, home215216 //do nothing217 }else if(srcElement.value.length == macStrLength && getSelectionStart(srcElement) == srcElement.value.length){218 //others, length = 2219220 var element=document.getElementsByName(nextfield)[0];221 eval(nextfield + '.focus();');222 element.select();223 return true;224 225 }else if(srcElement.value.length == 0 && key == 8 && KeyPressIndexStart == 0){226 //backspace, length = 0227 228 var element=document.getElementsByName(prevfield)[0];229 eval(prevfield + '.focus();');230 element.select();231 return true;232 233 }else{234 return true;235 }236237 238 }239}240241function getSelectionStart(o) {242 if (o.createTextRange) {243 var r = document.selection.createRange().duplicate()244 r.moveEnd('character', o.value.length)245 if (r.text == '') return o.value.length246 return o.value.lastIndexOf(r.text)247 } else return o.selectionStart248}249250function getSelectionEnd(o) {251 if (o.createTextRange) {252 var r = document.selection.createRange().duplicate()253 r.moveStart('character', -o.value.length)254 return r.text.length255 } else return o.selectionEnd ...

Full Screen

Full Screen

jquery.selection.js

Source:jquery.selection.js Github

copy

Full Screen

...11 }12 console.log(e);13 }14 // Start15 function getSelectionStart(node) {16 if('selectionStart' in node) {17 return node.selectionStart;18 } else if('getSelection' in document) {19 if(!node.ownerDocument.getSelection().rangeCount) {20 return node.innerText.length;21 } else {22 return node.ownerDocument.getSelection().getRangeAt(0).startOffset;23 }24 } else if('selection' in document) {25 console.log('IE');26 }27 }28 function setSelectionStart(node, start) {29 if('selectionStart' in node) {30 return node.selectionStart = start;31 } else if('getSelection' in document) {32 var selection = node.ownerDocument.getSelection(),33 range = document.createRange(),34 end = getSelectionEnd(node);35 selection.removeAllRanges();36 range.setStart(node.firstChild, start);37 range.setEnd(node.firstChild, end);38 selection.addRange(range);39 } else if('selection' in document) {40 console.log('IE');41 }42 }43 44 // End45 function getSelectionEnd(node) {46 if('selectionStart' in node) {47 return node.selectionEnd;48 } else if('getSelection' in document) {49 if(!node.ownerDocument.getSelection().rangeCount) {50 return node.innerText.length;51 } else {52 return node.ownerDocument.getSelection().getRangeAt(0).endOffset;53 }54 } else if('selection' in document) {55 console.log('IE');56 }57 }58 function setSelectionEnd(node, end) {59 if('selectionStart' in node) {60 return node.selectionEnd = end;61 } else if('getSelection' in document) {62 var selection = node.ownerDocument.getSelection(),63 range = document.createRange(),64 start = getSelectionStart(node);65 selection.removeAllRanges();66 range.setStart(node.firstChild, start);67 range.setEnd(node.firstChild, end);68 selection.addRange(range);69 } else if('selection' in document) {70 console.log('IE');71 }72 }73 74 // length75 function getSelectionLength(node) {76 return getSelectionEnd(node) - getSelectionStart(node);77 }78 function setSelectionLength(node, length) {79 setSelectionEnd(node, getSelectionStart(node) + length);80 }81 82 function set(node, start, n, end) {83 setSelectionStart(node, start);84 if(end) {85 setSelectionEnd(node, n);86 } else {87 setSelectionLength(node, n);88 }89 }90 91 function replace(node, replace) {92 var el = $(node),93 str;94 if(el.is('input,textarea')) {95 str = el.val();96 el.val( str.substring(0, getSelectionStart(node))97 + replace98 + str.substring(getSelectionEnd(node)));99 } else {100 str = el.text();101 console.log(getSelectionStart(node));102 el.text(str.substring(0, getSelectionStart(node))103 + replace104 + str.substring(getSelectionEnd(node)));105 }106 }107 108 $.fn.selection = function(length) {109 var node = this.jquery ? this.get(0) : this;110 return {111 start: function(start) {112 if(typeof start !== 'undefined') {113 setSelectionStart(node, start);114 return this;115 } else {116 return getSelectionStart(node);117 }118 },119 end: function(end) {120 if(typeof end !== 'undefined') {121 setSelectionEnd(node, end);122 return this;123 } else {124 return getSelectionEnd(node);125 }126 },127 length: function(length) {128 if(typeof length !== 'undefined') {129 setSelectionLength(node, length);130 return this;131 } else {132 return getSelectionLength(node);133 }134 },135 set: function(start, n, end) {136 set(node, start, n, end);137 return this;138 },139 clear: function() {140 this.replace('');141 },142 replace: function(string) {143 var start = getSelectionStart(node);144 replace(node, string);145 set(node, start + string.length, 0);146 return this;147 },148 before: function(string) {149 var start = getSelectionStart(node);150 setSelectionLength(node, 0);151 replace(node, string);152 set(node, start + string.length, 0);153 },154 after: function(string) {155 var start = getSelectionEnd(node);156 set(node, start, 0);157 replace(node, string);158 set(node, start + string.length, 0);159 }160 };161 }162163})(jQuery);

Full Screen

Full Screen

cursor.js

Source:cursor.js Github

copy

Full Screen

...11 query.fn.getCursorPosition = function () {12 if (this.length === 0) {13 return -1;14 }15 return query(this, this.context).getSelectionStart();16 };17 query.fn.setCursorPosition = function (position) {18 if (this.length === 0) {19 return this;20 }21 return query(this, this.context).setSelection(position, position);22 };23 query.fn.getSelection = function () {24 if (this.length === 0) {25 return -1;26 }27 var s = query(this, this.context).getSelectionStart();28 var e = query(this, this.context).getSelectionEnd();29 return this[0].value.substring(s, e);30 };31 query.fn.getSelectionStart = function () {32 if (this.length === 0) {33 return -1;34 }35 var input = this[0];36 var pos = input.value.length;37 if (input.createTextRange) {38 var r = document.selection.createRange().duplicate();39 r.moveEnd('character', input.value.length);40 if (r.text === '') {41 pos = input.value.length;...

Full Screen

Full Screen

Element.Forms.js

Source:Element.Forms.js Github

copy

Full Screen

...70 });71 });72 describe('Element.getSelectionStart', function(){73 it('should get the selection start', function(){74 expect(input.selectRange(2,5).getSelectionStart()).toEqual(2);75 });76 });77 describe('Element.getSelectionEnd', function(){78 it('should get the selection end', function(){79 expect(input.selectRange(2,5).getSelectionEnd()).toEqual(5);80 });81 });82 describe('Element.setCaretPosition, Element.getCaretPosition', function(){83 it('should set the caret position', function(){84 expect(input.setCaretPosition(3).getCaretPosition()).toEqual(3);85 });86 });87 describe('Element.getSelectionStart', function(){88 it('should compare the caret position to the selection start', function(){89 expect(input.setCaretPosition(3).getSelectionStart()).toEqual(3);90 });91 });92 describe('Element.insertAtCursor', function(){93 it('should insert at cursor', function(){94 expect(input.setCaretPosition(3).insertAtCursor('test').get('value')).toEqual('012test3456789');95 });96 });97 describe('Element.insertAroundCursor', function(){98 it('should insert around cursor', function(){99 expect(input.set('value', '0123456789').selectRange(2,5).insertAroundCursor({100 before: '{',101 after: '}'102 }).get('value')).toEqual('01{234}56789');103 });...

Full Screen

Full Screen

toolbars.js

Source:toolbars.js Github

copy

Full Screen

...58 selection.addRange(range);59 }60}61const headerIcon = (hnum) => {62 if (getSelectionStart().parentNode == editorContent) {63 switchBetweenElements(getSelectionStart(), document.createElement(`h${hnum}`));64 }65}66const paragraphIcon = () => {67 if (getSelectionStart().parentNode == editorContent) {68 switchBetweenElements(getSelectionStart(), document.createElement("p"));69 }70}71const textAlignIcon = (alignment) => {72 if (getSelectionStart().parentNode == editorContent) {73 getSelectionStart().style.textAlign = alignment;74 }75}76const listIcon = (ordered) => {77 if (ordered === true) {78 list = document.createElement("ol");79 } else {80 list = document.createElement("ul");81 }82 if (getSelectionStart().parentNode == editorContent) {83 switchBetweenElements(getSelectionStart(), list);84 list.innerHTML = `<li></li>`;85 list.focus();86 }87}88const codeIcon = (ordered) => {89 code = document.createElement("pre");90 if (getSelectionStart().parentNode == editorContent) {91 switchBetweenElements(getSelectionStart(), code);92 code.innerHTML = `<code></code>`;93 code.focus();94 }95}96const switchBetweenElements = (oldElement, newElement) => {97 for (let i = 0; i < oldElement.attributes.length; i++) {98 newElement.setAttribute(oldElement.attributes.item(i).nodeName, oldElement.attributes.item(i).nodeName);99 }100 newElement.innerHTML = oldElement.innerHTML;101 oldElement.parentNode.replaceChild(newElement, oldElement);...

Full Screen

Full Screen

select-out-of-floated-editable.js

Source:select-out-of-floated-editable.js Github

copy

Full Screen

...14 checkSelection();15} else {16 window.onmouseup = function() {17 window.setTimeout(function() {18 log('Input selection start: ' + getSelectionStart(floatedEditable) + ', end: ' +19 getSelectionEnd(floatedEditable));20 checkSelection();21 }, 0); // Without a timeout the selection is inaccurately printed22 }23}24function getSelectionStart(element) {25 return element.isContentEditable ? window.getSelection().baseOffset : element.selectionStart;26}27function getSelectionEnd(element) {28 return element.isContentEditable ? window.getSelection().extentOffset : element.selectionEnd;29}30function checkSelection() {31 var inputText = floatedEditable.isContentEditable ? floatedEditable.textContent : floatedEditable.value;32 var selectionStart = getSelectionStart(floatedEditable);33 var selectionEnd = getSelectionEnd(floatedEditable);34 var selectionStartsFromMiddle = selectionStart > 0 && selectionStart < inputText.length;35 var selectionGoesToEnd = selectionEnd == inputText.length;36 if (selectionStartsFromMiddle && selectionGoesToEnd)37 result.innerHTML = '<span style="padding: 5px; background-color: green">SUCCESS</span>';38 else39 result.innerHTML = '<span style="padding: 5px; background-color: red">FAIL</span>';...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button');5 const articleHeader = await Selector('.result-content').find('h1');6 let headerText = await articleHeader.innerText;7 console.log(headerText);8 let headerPosition = await articleHeader.getBoundingClientRectProperty('top');9 console.log(headerPosition);10 let headerId = await articleHeader.id;11 console.log(headerId);12 let headerVisible = await articleHeader.visible;13 console.log(headerVisible);14 let headerCount = await articleHeader.count;15 console.log(headerCount);16 let headerLang = await articleHeader.getAttribute('lang');17 console.log(headerLang);18 let headerWidth = await articleHeader.getStyleProperty('width');19 console.log(headerWidth);20 let headerHref = await articleHeader.getAttribute('href');21 console.log(headerHref);22 let headerTitle = await articleHeader.getProperty('title');23 console.log(headerTitle);24 let headerValue = await articleHeader.getAttribute('value');25 console.log(headerValue);26 let headerType = await articleHeader.getProperty('type');27 console.log(headerType);28 let headerSrc = await articleHeader.getAttribute('src');29 console.log(headerSrc);30 let headerAlt = await articleHeader.getProperty('alt');31 console.log(headerAlt);32 let headerHrefLang = await articleHeader.getAttribute('hreflang');33 console.log(headerHrefLang);34 let headerRel = await articleHeader.getProperty('rel');35 console.log(headerRel);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button')5 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');6});7test('My second test', async t => {8 .typeText('#developer-name', 'John Smith')9 .click('#submit-button')10 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');11});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('Getting Started', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button');5 const articleHeader = await Selector('.result-content').find('h1');6 let headerText = await articleHeader.innerText;7 let inputSelectionStart = await t.eval(() => document.getElementById('developer-name').selectionStart);8 let inputValue = await t.eval(() => document.getElementById('developer-name').value);9 console.log(headerText);10 console.log(inputSelectionStart);11 console.log(inputValue);12});

Full Screen

Using AI Code Generation

copy

Full Screen

1import {Selector} from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#macos')5 .click('#submit-button');6});7 Selector('textarea').getSelectionStart() is not a function8 TypeError: Selector('textarea').getSelectionStart() is not a function9 at Test.fn (/Users/xyz/Documents/testcafe-test/test.js:10:46)10 at Test._callee$ (/Users/xyz/Documents/testcafe-test/node_modules/testcafe/lib/runner/test.js:61:41)11 at tryCatch (/Users/xyz/Documents/testcafe-test/node_modules/regenerator-runtime/runtime.js:65:40)12 at GeneratorFunctionPrototype.invoke [as _invoke] (/Users/xyz/Documents/testcafe-test/node_modules/regenerator-runtime/runtime.js:303:22)13 at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/Users/xyz/Documents/testcafe-test/node_modules/regenerator-runtime/runtime.js:117:21)14 at GeneratorFunctionPrototype.invoke (/Users/xyz/Documents/testcafe-test/node_modules/regenerator-runtime/runtime.js:136:37)15 at run (/Users/xyz/Documents/testcafe-test/node_modules/core-js/library/modules/es6.promise.js:104:47)16 at flush (/Users/xyz/Documents/testcafe-test/node_modules/core-js/library/modules/_microtask.js:18:9)17 TypeError: Selector('textarea').getSelectionStart() is not a function18 at Test.fn (/Users/xyz/Documents/testcafe-test/test.js:10:46)19import {Selector} from 'testcafe';

Full Screen

Using AI Code Generation

copy

Full Screen

1import {Selector} from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#macos')5 .click('#submit-button');6});7 Selector('textarea').getSelectionStart() is not a function8 TypeError: Selector('textarea').getSelectionStart() is not a function9 at Test.fn (/Users/xyz/Documents/testcafe-test/test.js:10:46)10 at Test._callee$ (/Users/xyz/Documents/testcafe-test/node_modules/testcafe/lib/runner/test.js:61:41)11 at tryCatch (/Users/xyz/Documents/testcafe-test/node_modules/regenerator-runtime/runtime.js:65:40)12 at GeneratorFunctionPrototype.invoke [as _invoke] (/Users/xyz/Documents/testcafe-test/node_modules/regenerator-runtime/runtime.js:303:22)13 at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/Users/xyz/Documents/testcafe-test/node_modules/regenerator-runtime/runtime.js:117:21)14 at GeneratorFunctionPrototype.invoke (/Users/xyz/Documents/testcafe-test/node_modules/regenerator-runtime/runtime.js:136:37)15 at run (/Users/xyz/Documents/testcafe-test/node_modules/core-js/library/modules/es6.promise.js:104:47)16 at flush (/Users/xyz/Documents/testcafe-test/node_modules/core-js/library/modules/_microtask.js:18:9)17 TypeError: Selector('textarea').getSelectionStart() is not a function18 at Test.fn (/Users/xyz/Documents/testcafe-test/test.js:10:46)19import {Selector} from 'testcafe';20imltafM{fst'e ay >}rom't';21eaau('G csorition'asy=>{22costxtBx=Sc('#ls-ib');23import {p/cersrsPostMionst', asyntxtBoxSelecionSa24 const textarcuSsolPosition);25}ctor('#developer-name');26I'm=osrwhythcurso posionis0.I'myio cdurtocposioafrI typstxfinithextrxe box. I'vG tiigdSusinga`rted`wai1000` before `.pagt cursevPosifrost=s'w ix B.x.('#tried-test-caf();`ebuitdon' slcm ('swtk.Canyon/lesl m w ths?27OP 2017-10-25: I fund h oluion. Th rob=mwahIwasusing`o use getStixtBnxhhSTelrCafeme;`yxtsstad 't)`awi t.typeTSxltt;BxTestCafxt,u{ replcne:Strue(});`. I was using `return const el =tmxtBnxlecTe .Cafeon;` es;us}IPw.age spphnio'stcaCe/e'h is odext in tht ox But I ddn' rlzek'h#rt`e .cltxtBxTeCafe`des'cualy appnd 'TstCf'oth xiig xc getSelectiobnx.tIa mctualdy,raplscns at isng pect(gerext)b)x4w)h'TsCafe'.,`typTx(xox, TCfe'` ss tquielua se of`nectionStyptTx(xox, TstCf, { cm=sS t: r `. }, { dependencies: { selector } 28}29 let headerType = await articleHeader.getProperty('type');30 console.log(headerType);31schk g StlaceroS = awlm;dalue of an elemt = await articleHeader.getProperty('alt');32 console.log(headerAlt);33 console.log(headerHrefLang);34 let headerRel = await articleHeader.getProperty('rel');35exp rcofunloignhgRSlc ot valu(selector) {f an element attribute36rn ClnFuno(()37cons os = .slctitar;38fixture trdurn po;39 },.{pdependencies:a{gse`ets.r } }thub.io/testcafe/example/`;40test('My first test', async t => {41 .typeText('#developer-name', 'John Smith')42 .click('#submit-button')43 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');44});45test('My second test', async t => {46 .typeText('#developer-name', 'John Smith')47 .click('#submit-button')48 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');49});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('Getting Started', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button');5 const articleHeader = await Selector('.result-content').find('h1');6 let headerText = await articleHeader.innerText;7 let inputSelectionStart = await t.eval(() => document.getElementById('developer-name').selectionStart);8 let inputValue = await t.eval(() => document.getElementById('developer-name').value);9 console.log(headerText);10 console.log(inputSelectionStart);11 console.log(inputValue);12});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Selector } = require('testcafe');2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#tried-test-cafe')5 .click('#submit-button');6});7const { Selector } = require('testcafe');8test('My first test', async t => {9 .typeText('#developer-name', 'John Smith')10 .click('#tried-test-cafe')11 .click('#submit-button');12});

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testcafe automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful