+class Editor {
+ constructor(parent) {
+ this.parent = $(parent);
+
+ // Get the textarea
+ this.textarea = this.parent.find("textarea");
+
+ // Make the textarea magic
+ this.activateTextArea();
+
+ // Bind all keys
+ this.bindKeys();
+
+ console.log("Editor initialised for " + this.parent);
+ }
+
+ activateTextArea() {
+ var editor = this;
+
+ // Remember any selected text
+ this.textarea.select(function() {
+ editor.selection = {
+ start : this.selectionStart,
+ end : this.selectionEnd,
+ text : this.value.slice(this.selectionStart, this.selectionEnd)
+ };
+
+ console.debug("Something got selected:");
+ console.debug(editor.selection);
+ })
+ }
+
+ bindKeys() {
+ this.parent.find("#bold").click(this.bold.bind(this));
+ this.parent.find("#italic").click(this.italic.bind(this));
+ }
+
+ // Functions to modify the text
+
+ replaceSelection(replacement) {
+ var text = this.textarea.val();
+
+ text = text.slice(0, this.selection.start) + replacement + text.slice(this.selection.end);
+
+ // Write text to textarea
+ this.textarea.val(text);
+ }
+
+ bold() {
+ console.debug("Converting into bold: " + this.selection.text);
+ this.replaceSelection("**" + this.selection.text + "**");
+ }
+
+ italic() {
+ console.debug("Converting into italic: " + this.selection.text);
+ this.replaceSelection("*" + this.selection.text + "*");
+ }
+}
+
+$(document).ready(function() {
+ // Initialise all editors
+ $(".editor").each(function(i, e) {
+ new Editor(e);
+ });
+});