]> git.ipfire.org Git - ipfire.org.git/blame - src/static/js/editor.js
wiki: Add a little JS editor for highlighting text
[ipfire.org.git] / src / static / js / editor.js
CommitLineData
feeace6e
MT
1class Editor {
2 constructor(parent) {
3 this.parent = $(parent);
4
5 // Get the textarea
6 this.textarea = this.parent.find("textarea");
7
8 // Make the textarea magic
9 this.activateTextArea();
10
11 // Bind all keys
12 this.bindKeys();
13
14 console.log("Editor initialised for " + this.parent);
15 }
16
17 activateTextArea() {
18 var editor = this;
19
20 // Remember any selected text
21 this.textarea.select(function() {
22 editor.selection = {
23 start : this.selectionStart,
24 end : this.selectionEnd,
25 text : this.value.slice(this.selectionStart, this.selectionEnd)
26 };
27
28 console.debug("Something got selected:");
29 console.debug(editor.selection);
30 })
31 }
32
33 bindKeys() {
34 this.parent.find("#bold").click(this.bold.bind(this));
35 this.parent.find("#italic").click(this.italic.bind(this));
36 }
37
38 // Functions to modify the text
39
40 replaceSelection(replacement) {
41 var text = this.textarea.val();
42
43 text = text.slice(0, this.selection.start) + replacement + text.slice(this.selection.end);
44
45 // Write text to textarea
46 this.textarea.val(text);
47 }
48
49 bold() {
50 console.debug("Converting into bold: " + this.selection.text);
51 this.replaceSelection("**" + this.selection.text + "**");
52 }
53
54 italic() {
55 console.debug("Converting into italic: " + this.selection.text);
56 this.replaceSelection("*" + this.selection.text + "*");
57 }
58}
59
60$(document).ready(function() {
61 // Initialise all editors
62 $(".editor").each(function(i, e) {
63 new Editor(e);
64 });
65});