JSFiddle - React, Tailwind, and code Playground

by kotsoft

HTML

<textarea class="poetry-text"></textarea>

CSS

.poetry-text {
    height: 500px;
}

JavaScript

var moveKeyCodes = [8,13,37,38,39,40];

absoluteLine = 0;
adjustedLine = 0;

if(!Array.prototype.last) {
    Array.prototype.last = function() {
        return this[this.length - 1];
    }
}

function getCaret(el) { 
  if (el.selectionStart) {
    return el.selectionStart;
  } else if (document.selection) {
    el.focus();

    var r = document.selection.createRange();
    if (r == null) {
      return 0;
    }
    var re = el.createTextRange(),
        rc = re.duplicate();
    re.moveToBookmark(r.getBookmark());
    rc.setEndPoint('EndToStart', re);

    return rc.text.length;
  }
  return 0;
}

function getLine(sel) {
    var split = sel.val().substr(0, getCaret(sel[0])).replace(/\r\n/g, "\n").split("\n");
    var currLine = -2;
    for (i in split) {
        if (split[i]) {
            currLine++;
        }
    }
    if (!split.last()) {
        currLine++;
    }
    absoluteLine = split.length-1;
    adjustedLine = currLine;

    console.log(adjustedLine);
}

function inOrderedArray(val, arr) {
    var i = 0;
    while (arr[i] < val) {i++;}
    return arr[i] == val;
}

$(document).ready(function(){
    $('.poetry-text').val("Your poem goes here\nNo more need you fear");
    $('.poetry-text').keyup(function(e) {
        if (inOrderedArray(e.keyCode, moveKeyCodes)) {
            //need to recalculate line
            getLine($(this));
        }
    });
    $('.poetry-text').mouseup(function(e) {
        if (e.button == 0) {
            getLine($(this));
        }
    });
});