Skip to content
This repository was archived by the owner on Sep 30, 2020. It is now read-only.

Added a live code editor based on Ace.js and rust-playpen. #26

Merged
merged 1 commit into from
Jun 4, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 46 additions & 1 deletion css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,51 @@ ul.laundry-list {
}
}

#editor {
padding: none;
margin: none;
width: 100%;
height: 340px;
font-size: 13px;
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
}

#active-code {
position: relative;
display: none;
padding: 10px;
border-radius: 4px;
background-color: #FDFDFD;
border: 1px solid #CCC;
}

#run-code {
position: absolute;
z-index: 10;
float: right;
right: 8px;
top: 8px;
outline: none;
}

#result {
background-color: #E2EEF6;
margin-top: 10px;
padding: 10px;
display: none;
border-radius: 4px;
}

.ace-error-text {
background-color: #e9abab;
position: absolute;
}

.ace-error-line {
background-color: #F6E2E2;
position: absolute;
}

pre { background-color: #FDFDFD; }

/* Code highlighting */
Expand All @@ -261,4 +306,4 @@ pre.rust .attribute, pre.rust .attribute .ident { color: #C82829; }
pre.rust .comment { color: #8E908C; }
pre.rust .doccomment { color: #4D4D4C; }
pre.rust .macro, pre.rust .macro-nonterminal { color: #3E999F; }
pre.rust .lifetime { color: #B76514; }
pre.rust .lifetime { color: #B76514; }
31 changes: 31 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,33 @@ <h2>Featuring</h2>
</ul>
</div>
<div class="col-md-8">
<div id="active-code">
<button type="button" class="btn btn-primary btn-sm" id="run-code">Run</button>
<div id="editor">// This code is editable and runnable!
fn main() {
// A simple integer calculator:
// `+` or `-` means add/sub by 1
// `*` or `/` means mul/div by 2

let program = "+ + * - /";
let mut accumulator = 0;

for token in program.chars() {
match token {
'+' => accumulator += 1,
'-' => accumulator -= 1,
'*' => accumulator *= 2,
'/' => accumulator /= 2,
_ => { /* ignore everything else */ }
}
}

println!("The program \"{}\" calculates the value {}",
program, accumulator);
}</div>
<div id="result"></div>
</div>
<div id="static-code">
<pre class='rust'>
<span class='kw'>fn</span> main() {
<span class='comment'>// A simple integer calculator:
Expand All @@ -67,6 +94,7 @@ <h2>Featuring</h2>
program, accumulator);
}
</pre>
</div>
</div>
</div>

Expand Down Expand Up @@ -123,3 +151,6 @@ <h2>Featuring</h2>
rec_inst_link.setAttribute("href", rec_dl_addy);

</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/ace.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/mode-rust.js"></script>
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't this be also using https?

<script type="text/javascript" charset="utf-8" src="/js/editor.js"></script>
151 changes: 151 additions & 0 deletions js/editor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
// ECMAScript 6 Backwards compatability
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function(str) {
return this.slice(0, str.length) == str;
};
}

// Fetching DOM items
var activeCode = document.getElementById("active-code");
var staticCode = document.getElementById("static-code");
var runButton = document.getElementById("run-code");
var resultDiv = document.getElementById("result");

// Background colors for program result on success/error
var successColor = "#E2EEF6";
var errorColor = "#F6E2E2";

// Error message to return when there's a server failure
var errMsg = "The server encountered an error while running the program.";

// Stores ACE editor markers (highights) for errors
var markers = [];

// JS exists, display ACE editor
staticCode.style.display = "none";
activeCode.style.display = "block";

// Setting up ace editor
var editor = ace.edit("editor");
var Range = ace.require('ace/range').Range;
editor.setTheme("ace/theme/chrome");
editor.getSession().setMode("ace/mode/rust");
editor.setShowPrintMargin(false);
editor.renderer.setShowGutter(false);

// Dispatches a XMLHttpRequest to the Rust playpen, running the program, and
// issues a callback to `callback` with the result (or null on error)
function runProgram(program, callback) {
var req = new XMLHttpRequest();
var data = JSON.stringify({
version: "master",
optimize: "2",
code: program
});

<!-- console.log("Sending", data); -->
req.open('POST', "http://playtest.rust-lang.org/evaluate.json", true);
req.onload = function(e) {
if (req.readyState === 4 && req.status === 200) {
var result = JSON.parse(req.response).result;
// Need server support to get an accurate version of this.
var isSuccess = (result.indexOf("error:") === -1);
callback(isSuccess, result);
} else {
callback(false, null);
}
};

req.onerror = function(e) {
callback(false, null);
}

req.setRequestHeader("Content-Type", "application/json");
req.send(data);
}

// The callback to runProgram
function handleResult(success, message) {
var message = message.replace(/<anon>/g, '');
var message = message.replace(/(?:\r\n|\r|\n)/g, '<br />');

// Dispatch depending on result type
if (result == null) {
resultDiv.style.backgroundColor = errorColor;
resultDiv.innerHTML = errMsg;
} else if (success) {
handleSuccess(message);
} else {
handleError(message);
}
}

// Called on successful program run
function handleSuccess(message) {
resultDiv.style.backgroundColor = successColor;
resultDiv.innerHTML = message;
}

// Called on unsuccessful program run. Detects and prints errors in program
// output and highlights relevant lines and text in the code.
function handleError(message) {
resultDiv.style.backgroundColor = errorColor;

// Getting list of ranges with errors
var lines = message.split("<br />");
var ranges = parseError(lines);

// Cleaning up the message: keeps only relevant error output
var cleanMessage = lines.map(function(line) {
var errIndex = line.indexOf("error: ");
if (errIndex !== -1) {
return line.slice(errIndex);
}
return "";
}).filter(function(line) {
return line !== "";
}).join("<br />");

// Setting message
resultDiv.innerHTML = cleanMessage;

// Highlighting the lines
markers = ranges.map(function(range) {
return editor.getSession().addMarker(range, "ace-error-line", "fullLine", false);
});

// Highlighting the specific text
markers = markers.concat(ranges.map(function(range) {
return editor.getSession().addMarker(range, "ace-error-text", "text", false);
}));
}

// Parses an error message returning a list of ranges (row:col, row:col) where
// erors in the code have occured.
function parseError(lines) {
var ranges = [];
for (var i in lines) {
var line = lines[i];
if (line.startsWith(":") && line.indexOf(": ") !== -1) {
var parts = line.split(/:\s?|\s+/, 5).slice(1, 5);
var ip = parts.map(function(p) { return parseInt(p, 10) - 1; });
<!-- console.log("line:", line, parts, ip); -->
ranges.push(new Range(ip[0], ip[1], ip[2], ip[3]));
}
}

return ranges;
}

// Registering handler for run button click
runButton.addEventListener("click", function(ev) {
resultDiv.style.display = "block";
resultDiv.innerHTML = "Running...";

// clear previous markers, if any
markers.map(function(id) { editor.getSession().removeMarker(id); });

// Get the code, run the program
var program = editor.getValue();
runProgram(program, handleResult);
});