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