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