2 $('div[contenteditable]').on('input', function(event) {
3 if (event.originalEvent.inputType == "insertParagraph") {
4 var sel = document.getSelection();
5 var anchorNode = sel.anchorNode;
6 var prev_p = sel.anchorNode.previousSibling;
7 if (prev_p.tagName != 'P') {
8 prev_p = $(prev_p).parents('p')[0];
10 var title_match = prev_p.innerText.match(/^(h[1-6]). /);
12 var title = document.createElement(title_match[1]);
13 title.innerHTML = prev_p.innerHTML;
14 title.textContent = title.textContent.slice(4);
15 prev_p.replaceWith(title);
21 $('#save').on('click', function() {
22 var text = $('div[contenteditable]')[0].innerHTML;
23 var csrf = $('[name=csrfmiddlewaretoken]').val();
25 { text: text, csrfmiddlewaretoken: csrf}
27 $('#save').css('background', 'red');
32 var style_popup = null;
33 function update_style() {
34 var action = $(this).data('action');
36 if (action == 'code') {
37 action = 'insertHTML';
38 param = $('<code></code>', {text: window.getSelection().toString()})[0].outerHTML;
40 document.execCommand(action, false, param);
43 function show_style_popup(sel) {
44 if (style_popup === null) {
45 style_popup = $('<div id="style-popup">' +
46 '<button data-action="italic"><i>i</i></button>' +
47 '<button data-action="bold"><b>b</b></button>' +
48 '<button data-action="code">#</button>' +
49 '<button data-action="removeFormat">×</button>' +
52 style_popup.insertAfter($('div[contenteditable]'));
53 style_popup.find('button').on('click', update_style);
55 style_popup.css('position', 'absolute');
56 var pos = sel.getRangeAt(0).getClientRects()[0];
57 style_popup.css('top', pos.top + window.scrollY - $('main').offset().top - 33);
58 style_popup.css('left', pos.left + window.scrollX - $('main').offset().left);
61 $(document).on('selectionchange', function(event) {
62 var sel = window.getSelection();
63 if ($(sel.anchorNode).parents('div[contenteditable]').length && sel.toString()) {
64 show_style_popup(sel);
65 } else if (style_popup) {
66 $(style_popup).hide();