]> git.0d.be Git - panikdb.git/blob - panikdb/static/js/combo.wiki.js
wiki: add button to link to wiki page
[panikdb.git] / panikdb / static / js / combo.wiki.js
1 // from django/contrib/admin/static/admin/js/urlify.js
2 var LATIN_MAP = {
3     'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A', 'Æ': 'AE',
4     'Ç': 'C', 'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', 'Ì': 'I', 'Í': 'I',
5     'Î': 'I', 'Ï': 'I', 'Ð': 'D', 'Ñ': 'N', 'Ò': 'O', 'Ó': 'O', 'Ô': 'O',
6     'Õ': 'O', 'Ö': 'O', 'Ő': 'O', 'Ø': 'O', 'Ù': 'U', 'Ú': 'U', 'Û': 'U',
7     'Ü': 'U', 'Ű': 'U', 'Ý': 'Y', 'Þ': 'TH', 'Ÿ': 'Y', 'ß': 'ss', 'à': 'a',
8     'á': 'a', 'â': 'a', 'ã': 'a', 'ä': 'a', 'å': 'a', 'æ': 'ae', 'ç': 'c',
9     'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e', 'ì': 'i', 'í': 'i', 'î': 'i',
10     'ï': 'i', 'ð': 'd', 'ñ': 'n', 'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o',
11     'ö': 'o', 'ő': 'o', 'ø': 'o', 'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u',
12     'ű': 'u', 'ý': 'y', 'þ': 'th', 'ÿ': 'y'
13 };
14
15 function downcode(string) {
16   return string.toLowerCase().replace(/[^A-Za-z0-9\[\] ]/g,function(a){ return LATIN_MAP[a]||a }).replace(/[^-\w\s]/g, '').replace(/^\s+|\s+$/g, '').replace(/[-\s]+/g, '-');
17 };
18
19 function remove_auto_anchors() {
20   $('div#main-content .wiki-anchor-auto').each(function(idx, anchor) {
21           $(anchor).parent().removeAttr('id');
22           $(anchor).remove();
23   });
24 }
25
26 function auto_anchors() {
27   $('div#main-content div.textcell h1, div#main-content div.textcell h2, div#main-content div.textcell h3').each(function(idx, elem) {
28     var $elem = $(elem);
29     if ($elem.attr('id')) return;
30     if ($elem.find('.wiki-anchor').length) return;
31     $elem.attr('id', downcode($elem.text()));
32     $('<a class="wiki-anchor wiki-anchor-auto" href="#' + $elem.attr('id') + '">¶</a>').appendTo($elem);
33   });
34 }
35
36 (function(window, document, undefined) {
37   var Phylly = {
38     BLOCKS: [
39           {name: 'intertitre', tag: 'h4', klass: 'intertitle'},
40           {name: 'code', tag: 'PRE', klass: 'code'},
41           {name: 'note', tag: 'DIV', subtag: true, klass: 'note'},
42     ],
43     input_event: function(event) {
44       if (event.originalEvent.inputType != "insertParagraph") return true;
45       var sel = document.getSelection();
46       var anchorNode = sel.anchorNode;
47       var prev_p = sel.anchorNode.previousSibling;
48       if (! prev_p) return;
49       if (prev_p.tagName != 'P') {
50         prev_p = $(prev_p).parents('p')[0];
51       }
52       var title_match = prev_p.innerText.match(/^(h[1-6]). /);
53       if (title_match) {
54         var title = document.createElement(title_match[1]);
55         title.innerHTML = prev_p.innerHTML;
56         title.textContent = title.textContent.slice(4);
57         prev_p.replaceWith(title);
58       }
59       return true;
60     },
61
62     init: function() {
63       $(document).on('selectionchange', function(event) {
64         if ($('input[name=link-target].shown').length) {
65           return;
66         }
67         var sel = window.getSelection();
68         if ($(sel.anchorNode).parents('div[contenteditable]').length && sel.toString()) {
69           show_style_popup(sel);
70         } else if (style_popup) {
71           $(style_popup).hide();
72         }
73       });
74     },
75
76     off: function() {
77       $(document).off('selectionchange');
78     },
79
80     bind_events: function(elem) {
81       $(elem).on('input', Phylly.input_event);
82       $(elem).on('keyup click', update_block_style_popup);
83     },
84
85     unbind_events: function(elem) {
86       $(elem).off('input');
87       $(elem).off('keyup click');
88     },
89
90   }
91   window.Phylly = Phylly;
92
93   function get_contenteditable_subnode(node) {
94     if (node === null) return null;
95     if (node.parentNode.contentEditable === 'true') return node;
96     return get_contenteditable_subnode(node.parentNode);
97   }
98   function get_active_block(node) {
99     var main_node = get_contenteditable_subnode(node);
100     if (main_node === null) return null;
101     for (const block of Phylly.BLOCKS) {
102       if (main_node.tagName === block.tag && main_node.classList.contains(block.klass))
103         return block;
104     }
105     return null;
106   }
107
108   var block_style_popup = null;
109   function block_style() {
110     var sel = window.getSelection();
111     var current_anchor = sel.anchorNode;
112     if (this.classList.contains('on')) { // toggle off
113       if (this.action_block.subtag) {
114         // unwrap
115         var main_node = get_contenteditable_subnode(current_anchor);
116         $(current_anchor).detach().insertAfter(main_node);
117       } else {
118         document.execCommand('formatBlock', false, 'p');
119         current_anchor = sel.anchorNode;
120       }
121     } else {
122       action = this.action_block.subtag || this.action_block.tag;
123       if (this.action_block.subtag) {
124         // enclose current tag into a new parent;
125         var new_parent = document.createElement(this.action_block.tag);
126         new_parent.className = this.action_block.klass;
127         $(current_anchor).wrap(new_parent);
128       } else {
129         document.execCommand('formatBlock', false, this.action_block.tag);
130         sel.anchorNode.className = this.action_block.klass;
131         current_anchor = sel.anchorNode;
132       }
133     }
134     var range = document.createRange();
135     range.setStart(current_anchor, 0);
136     sel.removeAllRanges();
137     sel.addRange(range);
138     update_block_style_popup();
139   }
140   function update_block_style_popup() {
141     var sel = window.getSelection();
142     if (! ((sel.anchorNode instanceof Element && (sel.anchorOffset == 0 && sel.isCollapsed)) || get_active_block(sel.anchorNode))) {
143       if (block_style_popup) {
144         $(block_style_popup).hide();
145       }
146       return true;
147     }
148     if (block_style_popup === null) {
149       block_style_popup = $('<div class="block-style-popup"></div>');
150       for (const block of Phylly.BLOCKS) {
151         var button = document.createElement('button');
152         button.action_block = block;
153         button.dataset.action = block.name;
154         button.textContent = block.name;
155         block_style_popup.append(button);
156       }
157       block_style_popup.hide();
158       block_style_popup.insertAfter(document.body);
159       block_style_popup.find('button').on('click', block_style);
160     }
161     block_style_popup.css('position', 'absolute');
162     var block = get_active_block(sel.anchorNode);
163     block_style_popup.find('button').removeClass('on');
164     if (block) {
165       block_style_popup.find('[data-action=' + block.name + ']').addClass('on');
166       block_style_popup.addClass('selected');
167     } else {
168       block_style_popup.removeClass('selected');
169     }
170     var anchor = get_contenteditable_subnode(sel.anchorNode);
171     var pos = $(anchor).offset();
172     block_style_popup.css('top', pos.top - 33);
173     block_style_popup.css('left', pos.left);
174     block_style_popup.show();
175     return true;
176   }
177
178   var style_popup = null;
179   function update_style() {
180     var action = $(this).data('action');
181     var param = null;
182     if (action == 'code') {
183       action = 'insertHTML';
184       param = $('<code></code>', {text: window.getSelection().toString()})[0].outerHTML;
185     }
186     if (action == 'wiki') {
187       action = 'insertHTML';
188       var text = window.getSelection().toString();
189       var $new_link = $('<a></a>', {text: text, href: '#tbd'});
190       var request_id = Math.floor(Math.random() * 10000);
191       $new_link.attr('data-request-id', request_id);
192       var params = {};
193       params.title = text;
194       params.request_id = request_id;
195       $.post('/wiki/ajax/newpage/', params).success(function(data) {
196         $('a[data-request-id=' + data.request_id + ']').attr('href', data.url).removeAttr('data-request-id');
197       });
198       param = $new_link[0].outerHTML;
199     }
200     if (action == 'createLink') {
201       var sel = window.getSelection();
202       var $input = $('input[name=link-target]');
203       $input[0]._range = sel.getRangeAt(0);
204       if (sel.anchorNode instanceof Element) {
205         var elem = sel.anchorNode.childNodes[sel.anchorOffset];
206         if (elem.tagName == 'A') {
207           $input.val(elem.href);
208         }
209       }
210       $input.addClass('shown');
211       $input.focus();
212       return;
213     }
214     document.execCommand(action, false, param);
215   }
216   function validate_link(ev) {
217     var charCode = typeof ev.which == "number" ? ev.which : ev.keyCode;
218     if (ev.key == "Enter") {
219       var $input = $(this);
220       var range = this._range;
221       var url = $input.val();
222       $input.removeClass('shown');
223       var sel = window.getSelection();
224       sel.addRange(this._range);
225       if (url) {
226         document.execCommand('createLink', false, url);
227       } else {
228         document.execCommand('unlink', false, null);
229       }
230       sel.empty();
231       $input.val('');
232     }
233   }
234   function focusout_link(ev) {
235     var $input = $(this);
236     $input.removeClass('shown');
237     var range = this._range;
238     var sel = window.getSelection();
239     sel.addRange(this._range);
240   }
241
242   function show_style_popup(sel) {
243     if (style_popup === null) {
244       style_popup = $('<div class="inline-style-popup">' +
245                       '<button data-action="italic"><i>i</i></button>' +
246                       '<button data-action="bold"><b>b</b></button>' +
247                       '<button data-action="code">&lt;&gt;</button>' +
248                       '<button data-action="removeFormat">×</button>' +
249                       '<button data-action="wiki">W</button>' +
250                       '<button data-action="createLink">a</button>' +
251                       '<input name="link-target"/>' +
252                       '</div>');
253       style_popup.hide();
254       style_popup.insertAfter(document.body);
255       style_popup.find('button').on('click', update_style);
256       style_popup.find('[name=link-target]').on('keypress', validate_link).on('focusout', focusout_link);
257     }
258     style_popup.css('position', 'absolute');
259     var pos = sel.getRangeAt(0).getClientRects()[0];
260     style_popup.css('top', pos.top + window.scrollY - 33);
261     style_popup.css('left', pos.left + window.scrollX);
262     style_popup.show();
263   };
264 }(window, document));
265
266 $(function() {
267   $('#quickedit input').on('change', function() {
268     var enable = $(this).is(':checked');
269     if (enable) {
270       remove_auto_anchors();
271       $('div[data-edit-url] > div').each(function(i, elem) {
272         $(elem).attr('contenteditable', 'true');
273         var $button = $('<button class="save">Enregistrer</button>');
274         $button[0].div_zone = elem;
275         elem.edit_url = $(elem).parents('[data-edit-url]').data('edit-url');
276         $button.insertAfter(elem);
277       });
278       Phylly.init(),
279       $('div[data-edit-url] > div').each(function(i, elem) {
280         Phylly.bind_events(elem);
281       });
282       $('.save').on('click', function() {
283         var csrf = $('[name=csrfmiddlewaretoken]').val();
284         attr = this.div_zone.edit_url.replace(/^.*(data_textcell.*)\//, 'c$1-text');
285         var params = {};
286         params[attr] = this.div_zone.innerHTML;
287         params['csrfmiddlewaretoken'] = csrf;
288         $.post(this.div_zone.edit_url, params).fail(function() {
289           $(this).css('background', 'red');
290         });
291         return false;
292       });
293     } else {
294       auto_anchors();
295       Phylly.off(),
296       $('button.save').remove();
297       $('div[data-edit-url] > div').each(function(i, elem) {
298         $(elem).attr('contenteditable', 'false');
299         Phylly.unbind_events(elem);
300       });
301     }
302   });
303   $('#quickedit input').trigger('change');
304 });