xref: /dokuwiki/lib/scripts/edit.js (revision c8317406a25628eef52169b2f15d7884cb36bf9c)
1/**
2 * Functions for text editing (toolbar stuff)
3 *
4 * @todo most of the stuff in here should be revamped and then moved to toolbar.js
5 * @author Andreas Gohr <andi@splitbrain.org>
6 */
7
8/**
9 * Creates a toolbar button through the DOM
10 *
11 * Style the buttons through the toolbutton class
12 *
13 * @author Andreas Gohr <andi@splitbrain.org>
14 */
15function createToolButton(icon,label,key,id){
16    var btn = document.createElement('button');
17    var ico = document.createElement('img');
18
19    // preapare the basic button stuff
20    btn.className = 'toolbutton';
21    btn.title = label;
22    if(key){
23        btn.title += ' ['+key.toUpperCase()+']';
24        btn.accessKey = key;
25    }
26
27    // set IDs if given
28    if(id){
29        btn.id = id;
30        ico.id = id+'_ico';
31    }
32
33    // create the icon and add it to the button
34    if(icon.substr(0,1) == '/'){
35        ico.src = icon;
36    }else{
37        ico.src = DOKU_BASE+'lib/images/toolbar/'+icon;
38    }
39    btn.appendChild(ico);
40
41    return btn;
42}
43
44/**
45 * Creates a picker window for inserting text
46 *
47 * The given list can be an associative array with text,icon pairs
48 * or a simple list of text. Style the picker window through the picker
49 * class or the picker buttons with the pickerbutton class. Picker
50 * windows are appended to the body and created invisible.
51 *
52 * @param  string id    the ID to assign to the picker
53 * @param  array  props the properties for the picker
54 * @param  string edid  the ID of the textarea
55 * @rteurn DOMobject    the created picker
56 * @author Andreas Gohr <andi@splitbrain.org>
57 */
58function createPicker(id,props,edid){
59    var icobase = props['icobase'];
60    var list    = props['list'];
61
62    // create the wrapping div
63    var picker            = document.createElement('div');
64    picker.className      = 'picker';
65    if(props['class']){
66        picker.className += ' '+props['class'];
67    }
68    picker.id               = id;
69    picker.style.position   = 'absolute';
70    picker.style.marginLeft = '-10000px'; // no display:none, to keep access keys working
71
72    for(var key in list){
73        if (!list.hasOwnProperty(key)) continue;
74
75        if(isNaN(key)){
76            // associative array -> treat as image/value pairs
77            var btn = document.createElement('button');
78            btn.className = 'pickerbutton';
79            var ico = document.createElement('img');
80            if(list[key].substr(0,1) == '/'){
81                ico.src = list[key];
82            }else{
83                ico.src = DOKU_BASE+'lib/images/'+icobase+'/'+list[key];
84            }
85            btn.title     = key;
86            btn.appendChild(ico);
87            addEvent(btn,'click',bind(pickerInsert,key,edid));
88            picker.appendChild(btn);
89        }else if(isString(list[key])){
90            // a list of text -> treat as text picker
91            var btn = document.createElement('button');
92            btn.className = 'pickerbutton';
93            var txt = document.createTextNode(list[key]);
94            btn.title     = list[key];
95            btn.appendChild(txt);
96            addEvent(btn,'click',bind(pickerInsert,list[key],edid));
97            picker.appendChild(btn);
98        }else{
99            // a list of lists -> treat it as subtoolbar
100            initToolbar(picker,edid,list);
101            break; // all buttons handled already
102        }
103
104    }
105    var body = document.getElementsByTagName('body')[0];
106    body.appendChild(picker);
107    return picker;
108}
109
110/**
111 * Called by picker buttons to insert Text and close the picker again
112 *
113 * @author Andreas Gohr <andi@splitbrain.org>
114 */
115function pickerInsert(text,edid){
116    insertAtCarret(edid,text);
117    pickerClose();
118}
119
120/**
121 * Add button action for signature button
122 *
123 * @param  DOMElement btn   Button element to add the action to
124 * @param  array      props Associative array of button properties
125 * @param  string     edid  ID of the editor textarea
126 * @return boolean    If button should be appended
127 * @author Gabriel Birke <birke@d-scribe.de>
128 */
129function addBtnActionSignature(btn, props, edid) {
130    if(typeof(SIG) != 'undefined' && SIG != ''){
131        addEvent(btn,'click',bind(insertAtCarret,edid,SIG));
132        return true;
133    }
134    return false;
135}
136
137/**
138 * Make intended formattings easier to handle
139 *
140 * Listens to all key inputs and handle indentions
141 * of lists and code blocks
142 *
143 * Currently handles space, backspce and enter presses
144 *
145 * @author Andreas Gohr <andi@splitbrain.org>
146 * @fixme handle tabs
147 */
148function keyHandler(e){
149    if(e.keyCode != 13 &&
150       e.keyCode != 8  &&
151       e.keyCode != 32) return;
152    var field     = e.target;
153    var selection = getSelection(field);
154    var search    = "\n"+field.value.substr(0,selection.start);
155    var linestart = Math.max(search.lastIndexOf("\n"),
156                             search.lastIndexOf("\r")); //IE workaround
157    search = search.substr(linestart);
158
159    if(e.keyCode == 13){ // Enter
160        // keep current indention for lists and code
161        var match = search.match(/(\n  +([\*-] ?)?)/);
162        if(match){
163            insertAtCarret(field.id,match[1]);
164            e.preventDefault(); // prevent enter key
165        }
166    }else if(e.keyCode == 8){ // Backspace
167        // unindent lists
168        var match = search.match(/(\n  +)([*-] ?)$/);
169        if(match){
170            var spaces = match[1].length-1;
171
172            if(spaces > 3){ // unindent one level
173                field.value = field.value.substr(0,linestart)+
174                              field.value.substr(linestart+2);
175                selection.start = selection.start - 2;
176                selection.end   = selection.start;
177            }else{ // delete list point
178                field.value = field.value.substr(0,linestart)+
179                              field.value.substr(selection.start);
180                selection.start = linestart;
181                selection.end   = linestart;
182            }
183            setSelection(selection);
184            e.preventDefault(); // prevent backspace
185        }
186    }else if(e.keyCode == 32){ // Space
187        // intend list item
188        var match = search.match(/(\n  +)([*-] )$/);
189        if(match){
190            field.value = field.value.substr(0,linestart)+'  '+
191                          field.value.substr(linestart);
192            selection.start = selection.start + 2;
193            selection.end   = selection.start;
194            setSelection(selection);
195            e.preventDefault(); // prevent space
196        }
197    }
198}
199
200//FIXME consolidate somewhere else
201addInitEvent(function(){
202    var field = $('wiki__text');
203    if(!field) return;
204    addEvent(field,'keydown',keyHandler);
205});
206
207/**
208 * Determine the current section level while editing
209 *
210 * @author Andreas Gohr <gohr@cosmocode.de>
211 */
212function currentHeadlineLevel(textboxId){
213    var field     = $(textboxId);
214    var selection = getSelection(field);
215    var search    = "\n"+field.value.substr(0,selection.start);
216    var lasthl    = search.lastIndexOf("\n==");
217    if(lasthl == -1 && field.form.prefix){
218        // we need to look in prefix context
219        search = field.form.prefix.value;
220        lasthl    = search.lastIndexOf("\n==");
221    }
222    search    = search.substr(lasthl+1,6);
223
224    if(search == '======') return 1;
225    if(search.substr(0,5) == '=====') return 2;
226    if(search.substr(0,4) == '====') return 3;
227    if(search.substr(0,3) == '===') return 4;
228    if(search.substr(0,2) == '==') return 5;
229
230    return 0;
231}
232
233
234/**
235 * global var used for not saved yet warning
236 */
237var textChanged = false;
238
239/**
240 * Check for changes before leaving the page
241 */
242function changeCheck(msg){
243  if(textChanged){
244    var ok = confirm(msg);
245    if(ok){
246        // remove a possibly saved draft using ajax
247        var dwform = $('dw__editform');
248        if(dwform){
249            var params = 'call=draftdel';
250            params += '&id='+encodeURIComponent(dwform.elements.id.value);
251
252            var sackobj = new sack(DOKU_BASE + 'lib/exe/ajax.php');
253            sackobj.AjaxFailedAlert = '';
254            sackobj.encodeURIString = false;
255            sackobj.runAJAX(params);
256            // we send this request blind without waiting for
257            // and handling the returned data
258        }
259    }
260    return ok;
261  }else{
262    return true;
263  }
264}
265
266/**
267 * Add changeCheck to all Links and Forms (except those with a
268 * JSnocheck class), add handlers to monitor changes
269 *
270 * Sets focus to the editbox as well
271 *
272 * @fixme this is old and crappy code. needs to be redone
273 */
274function initChangeCheck(msg){
275    var edit_text   = document.getElementById('wiki__text');
276    if(!edit_text) return;
277
278    // add change check for links
279    var links = document.getElementsByTagName('a');
280    for(var i=0; i < links.length; i++){
281        if(links[i].className.indexOf('JSnocheck') == -1){
282            links[i].onclick = function(){
283                                    var rc = changeCheck(msg);
284                                    if(window.event) window.event.returnValue = rc;
285                                    return rc;
286                               };
287        }
288    }
289    // add change check for forms
290    var forms = document.forms;
291    for(i=0; i < forms.length; i++){
292        if(forms[i].className.indexOf('JSnocheck') == -1){
293            forms[i].onsubmit = function(){
294                                    var rc = changeCheck(msg);
295                                    if(window.event) window.event.returnValue = rc;
296                                    return rc;
297                               };
298        }
299    }
300
301    // reset change memory var on submit
302    var btn_save        = document.getElementById('edbtn__save');
303    btn_save.onclick    = function(){ textChanged = false; };
304    var btn_prev        = document.getElementById('edbtn__preview');
305    btn_prev.onclick    = function(){ textChanged = false; };
306
307    // add change memory setter
308    edit_text.onchange = function(){
309        textChanged = true; //global var
310        summaryCheck();
311    };
312    var summary = document.getElementById('edit__summary');
313    addEvent(summary, 'change', summaryCheck);
314    addEvent(summary, 'keyup', summaryCheck);
315    if (textChanged) summaryCheck();
316
317    // set focus
318    edit_text.focus();
319}
320
321/**
322 * Checks if a summary was entered - if not the style is changed
323 *
324 * @author Andreas Gohr <andi@splitbrain.org>
325 */
326function summaryCheck(){
327    var sum = document.getElementById('edit__summary');
328    if(sum.value === ''){
329        sum.className='missing';
330    }else{
331        sum.className='edit';
332    }
333}
334
335
336/**
337 * Class managing the timer to display a warning on a expiring lock
338 */
339function locktimer_class(){
340        this.sack     = null;
341        this.timeout  = 0;
342        this.timerID  = null;
343        this.lasttime = null;
344        this.msg      = '';
345        this.pageid   = '';
346};
347var locktimer = new locktimer_class();
348    locktimer.init = function(timeout,msg,draft){
349        // init values
350        locktimer.timeout  = timeout*1000;
351        locktimer.msg      = msg;
352        locktimer.draft    = draft;
353        locktimer.lasttime = new Date();
354
355        if(!$('dw__editform')) return;
356        locktimer.pageid = $('dw__editform').elements.id.value;
357        if(!locktimer.pageid) return;
358
359        // init ajax component
360        locktimer.sack = new sack(DOKU_BASE + 'lib/exe/ajax.php');
361        locktimer.sack.AjaxFailedAlert = '';
362        locktimer.sack.encodeURIString = false;
363        locktimer.sack.onCompletion = locktimer.refreshed;
364
365        // register refresh event
366        addEvent($('dw__editform').elements.wikitext,'keypress',function(){locktimer.refresh();});
367
368        // start timer
369        locktimer.reset();
370    };
371
372    /**
373     * (Re)start the warning timer
374     */
375    locktimer.reset = function(){
376        locktimer.clear();
377        locktimer.timerID = window.setTimeout("locktimer.warning()", locktimer.timeout);
378    };
379
380    /**
381     * Display the warning about the expiring lock
382     */
383    locktimer.warning = function(){
384        locktimer.clear();
385        alert(locktimer.msg);
386    };
387
388    /**
389     * Remove the current warning timer
390     */
391    locktimer.clear = function(){
392        if(locktimer.timerID !== null){
393            window.clearTimeout(locktimer.timerID);
394            locktimer.timerID = null;
395        }
396    };
397
398    /**
399     * Refresh the lock via AJAX
400     *
401     * Called on keypresses in the edit area
402     */
403    locktimer.refresh = function(){
404        var now = new Date();
405        // refresh every minute only
406        if(now.getTime() - locktimer.lasttime.getTime() > 30*1000){ //FIXME decide on time
407            var params = 'call=lock&id='+encodeURIComponent(locktimer.pageid);
408            if(locktimer.draft){
409                var dwform = $('dw__editform');
410                params += '&prefix='+encodeURIComponent(dwform.elements.prefix.value);
411                params += '&wikitext='+encodeURIComponent(dwform.elements.wikitext.value);
412                params += '&suffix='+encodeURIComponent(dwform.elements.suffix.value);
413                params += '&date='+encodeURIComponent(dwform.elements.date.value);
414            }
415            locktimer.sack.runAJAX(params);
416            locktimer.lasttime = now;
417        }
418    };
419
420
421    /**
422     * Callback. Resets the warning timer
423     */
424    locktimer.refreshed = function(){
425        var data  = this.response;
426        var error = data.charAt(0);
427            data  = data.substring(1);
428
429        $('draft__status').innerHTML=data;
430        if(error != '1') return; // locking failed
431        locktimer.reset();
432    };
433// end of locktimer class functions
434
435