autotagging
[redakcja.git] / redakcja / static / js / button_scripts.js
1 (function() {
2   var slice = Array.prototype.slice;
3
4   function update(array, args) {
5     var arrayLength = array.length, length = args.length;
6     while (length--) array[arrayLength + length] = args[length];
7     return array;
8   };
9
10   function merge(array, args) {
11     array = slice.call(array, 0);
12     return update(array, args);
13   };
14
15   Function.prototype.bind = function(context) {
16     if (arguments.length < 2 && typeof arguments[0] === 'undefined') {
17       return this;
18     }
19     var __method = this;
20     var args = slice.call(arguments, 1);
21     return function() {
22       var a = merge(args, arguments);
23       return __method.apply(context, a);
24     }
25   }
26
27 })();
28
29 function nblck_each(array, body, after) {
30         $.each(array, function(i) {
31                 body(this, i);
32         });
33
34         after();
35 };
36
37 function nblck_map(array, func, after) {
38         var acc = [];
39
40         nblck_each(array, function(elem, index) {
41                 acc.push(func(elem, index));
42         }, function(){
43                 after(acc);
44         });
45 };
46
47 function ScriptletCenter()
48 {
49     this.scriptlets = {};
50
51     this.scriptlets['insert_tag'] = function(context, params, text, move_forward, done)
52     {
53         var start_tag = '<'+params.tag;
54         var move_cursor = false;
55
56         for (var attr in params.attrs) {
57             start_tag += ' '+attr+'="' + params.attrs[attr] + '"';
58         }
59
60         start_tag += '>';
61         var end_tag = '</'+params.tag+'>';
62
63         if(text.length > 0) {
64             // tokenize
65             var output = '';
66             var token = '';
67             for(var index=0; index < text.length; index++)
68             {
69                 if (text[index].match(/\s/)) { // whitespace
70                     token += text[index];
71                 }
72                 else { // character
73                     output += token;
74                     if(output == token) output += start_tag;
75                     token = '';
76                     output += text[index];
77                 }
78             }
79
80             if( output[output.length-1] == '\\' ) {
81                 output = output.substr(0, output.length-1) + end_tag + '\\';
82             } else {
83                 output += end_tag;
84             }
85             output += token;
86         }
87         else {
88             if(params.nocontent) {
89                 output = "<"+params.tag +" />";
90             }
91             else {
92                 output = start_tag + end_tag;
93                 move_cursor = true;
94             }
95         }
96
97         if (move_cursor) {
98             move_forward -= params.tag.length+3;
99         }
100
101         done(output, move_forward);
102     }.bind(this);
103
104     this.scriptlets['lineregexp'] = function(context, params, text, move_forward, done) {
105                 var self = this;
106
107         var exprs = $.map(params.exprs, function(expr) {
108             var opts = "g";
109             if(expr.length > 2) {
110                 opts = expr[2];
111             } return {
112                 rx: new RegExp(expr[0], opts),
113                 repl: expr[1]
114                 };
115         });
116
117         if(!text) done(text, move_forward);
118
119         var changed = 0;
120         var lines = text.split('\n');
121
122                 nblck_map(lines, function(line, index) {
123             var old_line = line;
124             $(exprs).each(function() {
125                 var expr = this;
126                 line = line.replace(expr.rx, expr.repl);
127             });
128
129                         $progress.html(index);
130
131             if(old_line != line) changed += 1;
132             return line;
133         }, function(newlines) {
134             if(changed > 0) {
135                 text = newlines.join('\n');
136             };
137
138             done(text, move_forward);
139                 });
140     }.bind(this);
141
142     this.scriptlets['fulltextregexp'] = function(context, params, text, move_forward, done) {
143                 var self = this;
144
145         var exprs = $.map(params.exprs, function(expr) {
146             var opts = "mg";
147             if(expr.length > 2) {
148                 opts = expr[2];
149             }
150             return {
151                 rx: new RegExp(expr[0], opts),
152                 repl: expr[1]
153                 };
154         });
155
156         if(!text) done(text, move_forward);
157
158                 nblck_each(exprs, function(expr, index) {
159                         $progress.html(600 + index);
160             text = text.replace(expr.rx, expr.repl);
161         }, function() {
162                         done(text, move_forward);
163                 });
164     }.bind(this);
165
166     this.scriptlets['macro'] = function(context, params, text, move_forward, done) {
167         var self = this;
168                 var i = 0;
169
170                 function next(text, move_forward) {
171                 if (i < params.length) {
172                                 var e = params[i];
173                                 i = i + 1;
174                                 self.scriptlets[e[0]](context, e[1], text, move_forward, next);
175                         }
176                         else {
177                                 done(text, move_forward);
178                         }
179         };
180
181                 next(text, move_forward);
182     }.bind(this);
183
184     this.scriptlets['lowercase'] = function(context, params, text, move_forward, done)
185     {
186         if(!text) done(text, move_forward);
187         done(text.toLowerCase(), move_forward);
188     }.bind(this);
189
190
191     this.scriptlets["insert_stanza"] = function(context, params, text, move_forward, done) {
192         if(text) {
193             var verses = text.split('\n');
194             text = ''; var buf = ''; var ebuf = '';
195             var first = true;
196
197             for(var i=0;  i < verses.length; i++) {
198                 var verse = verses[i].replace(/^\s+/, "").replace(/\s+$/, "");
199                 if(verse) {
200                     text += (buf ? buf + '/\n' : '') + ebuf;
201                     buf = (first ? '<strofa>\n' : '') + verses[i];
202                     ebuf = '';
203                     first = false;
204                 } else {
205                     ebuf += '\n' + verses[i];
206                 }
207             }
208             text = text + buf + '\n</strofa>' + ebuf;
209         }
210         else {
211             text = "<strofa></strofa>"
212             move_forward -= "</strofa>".length;
213         }
214
215         done(text, move_forward);
216     }.bind(this);
217
218
219     this.scriptlets['autotag'] = function(context, params, text, move_forward, done)
220     {
221         if(!text.match(/^\n+$/)) done(text, move_forward);
222
223         function insert_done(output, mf) {
224             text += output;
225         }
226
227         if (!params.split) params.split = 2;
228         if (!params.padding) params.padding = 3;
229
230         chunks = text.replace(/^\n+|\n+$/, '').split(new RegExp("\\n{"+params.split+",}"));
231         text = text.match(/^\n+/);
232         if (!text)
233             text = '';
234         padding = '';
235         for(; params.padding; params.padding--) {
236             padding += "\n";
237         }
238
239         if (params.tag == 'strofa')
240             tagger = this.scriptlets['insert_stanza'];
241         else
242             tagger = this.scriptlets['insert_tag'];
243
244         for (i in chunks) {
245             if (chunks[i]) {
246                 if (params.tag == 'akap' && chunks[i].match(/^---/))
247                     tag = 'akap_dialog';
248                 else tag = params.tag;
249                 tagger(context, {tag: tag}, chunks[i], 0, insert_done);
250                 text += padding;
251             }
252         }
253
254         done(text, move_forward);
255     }.bind(this);
256
257 }
258
259 ScriptletCenter.prototype.callInteractive = function(opts) {
260         $progress = $('<span>Executing script</span>');
261         var self = this;
262
263         /* This won't work, 'cause the JS below might be synchronous :( */
264         /* var timer = setTimeout(function() {
265             $.blockUI({message: $progress});
266             timer = null;
267         }, 1000); */
268
269         $.blockUI({message: $progress, showOverlay: false});
270
271     var input = self.XMLEditorSelectedText(opts.context);
272         self.scriptlets[opts.action](opts.context, opts.extra, input, 0, function(output, move_forward){
273             /*if(timer)
274                 clearTimeout(timer);
275             else */
276         if (input != output) {
277             self.XMLEditorReplaceSelectedText(opts.context, output)
278         }
279         if (move_forward) {
280             try {
281                 self.XMLEditorMoveCursorForward(opts.context, move_forward)
282             }
283             catch(e) {}
284         }
285             $.unblockUI(); // done
286         });
287 }
288
289 ScriptletCenter.prototype.XMLEditorSelectedText = function(editor) {
290
291     return editor.selection();
292 };
293
294 ScriptletCenter.prototype.XMLEditorReplaceSelectedText = function(editor, replacement)
295 {
296         $progress.html("Replacing text");
297         editor.replaceSelection(replacement);
298 };
299
300 ScriptletCenter.prototype.XMLEditorMoveCursorForward = function(panel, n) {
301     var pos = panel.cursorPosition();
302     panel.selectLines(pos.line, pos.character + n);
303 };
304
305 var scriptletCenter;
306
307 $(function() {
308     scriptletCenter = new ScriptletCenter();
309 });