]> git.0d.be Git - chloro.git/blob - chloro/phyll/static/js/chloro.js
enable csrf for live-edit post
[chloro.git] / chloro / phyll / static / js / chloro.js
1 $(function() {
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];
9       }
10       var title_match = prev_p.innerText.match(/^(h[1-6]). /);
11       if (title_match) {
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);
16       }
17     }
18     return true;
19   });
20
21   $('#save').on('click', function() {
22     var text = $('div[contenteditable]')[0].innerHTML;
23     var csrf = $('[name=csrfmiddlewaretoken]').val();
24     $.post('api-save/',
25       { text: text, csrfmiddlewaretoken: csrf}
26     ).fail(function() {
27       $('#save').css('background', 'red');
28     });
29     return false;
30   });
31
32   var style_popup = null;
33   function update_style() {
34     var action = $(this).data('action');
35     var param = null;
36     if (action == 'code') {
37       action = 'insertHTML';
38       param = $('<code></code>', {text: window.getSelection().toString()})[0].outerHTML;
39     }
40     document.execCommand(action, false, param);
41   }
42
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>' +
50                       '</div>');
51       style_popup.hide();
52       style_popup.insertAfter($('div[contenteditable]'));
53       style_popup.find('button').on('click', update_style);
54     }
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);
59     style_popup.show();
60   };
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();
67     }
68   });
69 });