Reoodle - Editing. Custom Var Badge
by joplomacedo
HTML
<div id="app">
<p class="field" contenteditable @input="handleInput" @keyup="handleKeyup" @mouseup="handleMouseUp" @paste="handleFieldPaste"></p>
<p>Last caret pos on record:</p>
<p>{{lastCaretPos}}</p>
<p>Value:</p>
<p>{{value}}</p>
</div>
CSS
body {
background: #fff;
padding: 20px;
font-family: Helvetica;
}
.field {
background: #eee;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
min-height: 20em;
border: 2px solid;
}
Vue
function getCaretCharacterOffsetWithin(element) {
let caretOffset = 0;
if (typeof window.getSelection != "undefined") {
const range = window.getSelection().getRangeAt(0);
const preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
} else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
const textRange = document.selection.createRange();
const preCaretTextRange = document.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
new Vue({
el: "#app",
data: {
value: '',
lastCaretPos: undefined
},
methods: {
insertVarBadge( varName ) {
},
handleInput(e) {
this.value = e.currentTarget.innerHTML;
},
handleKeyup( e ) {
this.lastCaretPos = getCaretCharacterOffsetWithin(e.currentTarget);
},
handleMouseUp(e) {
this.lastCaretPos = getCaretCharacterOffsetWithin(e.currentTarget);
},
handleFieldPaste (e) {
e.preventDefault();
// get text representation of clipboard
const text = (e.originalEvent || e).clipboardData.getData("text/plain");
// insert text manually
document.execCommand("inserttext", false, text);
}
}
})