shuji
shuji

Reputation: 7527

How should I change elements content on ace editor?

I am trying to change the text in some elements on ace editor with an input type=range but when I try to write again, the editor returns to a previous value before it was modified with javascript

var editordiv = document.getElementById("editor");
var editor = ace.edit("editor");
editor.getSession().setMode("ace/mode/javascript");
var elem;
editordiv.onmousedown=function(e){
    if(e.target.classList.contains("ace_numeric")) elem=e.target;
}
function changeElement(range){
    if(elem) elem.textContent=range.value; //not changing correctly editor content
}
#editor{
    position:absolute;
    width:100%;
    height:100%;
}
.ace_constant {
    pointer-events:auto !important;
}
#range{
    position:absolute;
    right:0;
}
<script src="https://cdn.jsdelivr.net/ace/1.2.3/noconflict/ace.js"></script>
<div id="editor">var i=30;
var j=70;</div>
<input type="range" id="range" oninput="changeElement(this)">

How can I change the value correctly of a number and keep the history in ace editor?

Upvotes: 1

Views: 1028

Answers (2)

shuji
shuji

Reputation: 7527

Ok, the solution I found is a little more complicated than expected:

var elem = undefined;
var rn = undefined;
function changeElement(range){
    if(rn) editor.session.replace(rn,range.value); //input value into range text
}
editor.on("mousemove",function(e){
    if(e.domEvent.target.classList.contains("ace_numeric")){
        elem = e.domEvent.target;
        var position = e.getDocumentPosition();
        var token = editor.session.getTokenAt(position.row, position.column+1);
        if(token.value.match(/^[+-]?[.\d]+$/)) //token value is a number
            rn = new Range(position.row, token.start, position.row, token.start+elem.textContent.length); //range of text in editor
    }
});

Instead of replacing the dom element, save the range position onmousedown and replace the text when the input range changes.

Upvotes: 2

Nick Tomlin
Nick Tomlin

Reputation: 29221

You need to change the contents of the editor through the editors interface, not by modifying the dom within the editor. One, slightly messy, way to do this is with editor.replace. You can tweak the regex/parameters as you see fit:

var editordiv = document.getElementById("editor");
var editor = ace.edit("editor");
editor.getSession().setMode("ace/mode/javascript");

function changeElement (range) {
  editor.replace('=' + range.value + ';', {needle: /=\d+;/});
}
#editor{
    position:absolute;
    width:100%;
    height:100%;
}
.ace_constant {
    pointer-events:auto !important;
}
#range{
    position:absolute;
    right:0;
}
<script src="https://cdn.jsdelivr.net/ace/1.2.3/noconflict/ace.js"></script>
<div id="editor">var i=80;</div>
<input type="range" id="range" oninput="changeElement(this)">

Upvotes: 1

Related Questions