Fixes #784: sexy error templates
[redakcja.git] / redakcja / static / js / wiki / xslt.js
1 /*
2  *
3  * XSLT STUFF
4  *
5  */
6 function createXSLT(xsl) {
7     var p = new XSLTProcessor();
8     p.importStylesheet(xsl);
9     return p;
10 }
11
12 var xml2htmlStylesheet = null;
13
14 // Wykonuje block z załadowanymi arkuszami stylów
15 function withStylesheets(code_block, onError)
16 {
17     if (!xml2htmlStylesheet) {
18         $.blockUI({message: 'Ładowanie arkuszy stylów...'});
19         $.ajax({
20                 url: STATIC_URL + 'xsl/wl2html_client.xsl',
21                 dataType: 'xml',
22                 success: function(data) {
23                 xml2htmlStylesheet = createXSLT(data);
24                 $.unblockUI();
25                                 code_block();
26
27             },
28                         error: onError
29         })
30     }
31         else {
32                 code_block();
33         }
34 }
35
36 var canonThemes = null;
37
38 // Wykonuje block z załadowanymi kanonicznymi motywami
39 function withThemes(code_block, onError)
40 {
41     if (!canonThemes) {
42         $.blockUI({message: 'Ładowanie motywów...'});
43         $.ajax({
44             url: '/themes',
45             dataType: 'text',
46             success: function(data) {
47                 canonThemes = {};
48                 themes = data.split('\n');
49                 for (i in themes) {
50                     canonThemes[themes[i]] = 1;
51                 }
52                 $.unblockUI();
53                 code_block();
54             },
55             error: onError
56         })
57     }
58     else {
59         code_block();
60     }
61 }
62
63
64
65 function xml2html(options) {
66     withStylesheets(function() {
67         withThemes(function() {
68             var xml = options.xml.replace(/\/\s+/g, '<br />');
69             var parser = new DOMParser();
70             var serializer = new XMLSerializer();
71             var doc = parser.parseFromString(xml, 'text/xml');
72             var error = $('parsererror', doc);
73
74             if (error.length == 0) {
75                 doc = xml2htmlStylesheet.transformToFragment(doc, document);
76                 console.log(doc.firstChild);
77
78                 if(doc.firstChild === null) {
79                     options.error("Błąd w przetwarzaniu XML.");
80                     return;
81                 }
82
83                 error = $('parsererror', doc);
84             }
85
86             if (error.length > 0 && options.error) {
87                 options.error(error.text());
88             } else {
89                 $('.theme-text-list', doc.firstChild).each(function(){
90                     var themes = $(this).html().split(',');
91                     for (i in themes) {
92                         themes[i] = $.trim(themes[i]);
93                         if (!(themes[i] in canonThemes))
94                             themes[i] = '<span x-pass-thru="true" class="noncanon">' + themes[i] + "</span>"
95                     }
96                     $(this).html(themes.join(', '));
97                 });
98                 options.success(doc.firstChild);
99             }
100         }, function() { options.error && options.error('Nie udało się załadować motywów'); });
101     }, function() { options.error && options.error('Nie udało się załadować XSLT'); });
102 }
103
104 /* USEFULL CONSTANTS */
105 const ELEMENT_NODE                                       = 1;
106 const ATTRIBUTE_NODE                 = 2;
107 const TEXT_NODE                      = 3;
108 const CDATA_SECTION_NODE             = 4;
109 const ENTITY_REFERENCE_NODE          = 5;
110 const ENTITY_NODE                    = 6;
111 const PROCESSING_INSTRUCTION_NODE    = 7;
112 const COMMENT_NODE                   = 8;
113 const DOCUMENT_NODE                  = 9;
114 const DOCUMENT_TYPE_NODE             = 10;
115 const DOCUMENT_FRAGMENT_NODE         = 11;
116 const NOTATION_NODE                  = 12;
117 const XATTR_RE = /^x-attr-name-(.*)$/;
118
119 const ELEM_START = 1;
120 const ELEM_END = 2;
121 const NS_END = 3;
122
123 const NAMESPACES = {
124         // namespaces not listed here will be assigned random names
125         "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
126         "http://purl.org/dc/elements/1.1/": "dc",
127         "http://www.w3.org/XML/1998/namespace": "xml"
128 };
129
130 /*
131  * PADDING for pretty-printing
132  */
133 const PADDING = {
134     dramat_wierszowany_l: 4,
135     dramat_wierszowany_lp: 4,
136     dramat_wspolczesny: 4,
137     wywiad: 4,
138     opowiadanie: 4,
139     powiesc: 4,
140     liryka_l: 4,
141     liryka_lp: 4,
142     naglowek_czesc: 4,
143     naglowek_akt: 4,
144     naglowek_rozdzial: 4,
145     naglowek_osoba: 4,
146     lista_osob: 4,
147
148     akap: 3,
149     akap_cd: 3,
150     akap_dialog: 3,
151     strofa: 3,
152     motto: 3,
153     miejsce_czas: 3,
154
155     autor_utworu: 2,
156     nazwa_utworu: 2,
157     dzielo_nadrzedne: 2,
158
159     didaskalia: 2,
160     motto_podpis: 2,
161     naglowek_listy: 2,
162     kwestia: 1,
163     lista_osoba: 1,
164
165         "podpis": 1,
166         "wers": 0,
167         "wers_cd": 0,
168         "wers_akap": 0,
169         "wers_wciety": 0,
170
171         "rdf:RDF": 3,
172         "rdf:Description": 1,
173 };
174
175 function getPadding(name) {
176
177         if(name.match(/^dc:.*$/))
178                 return -1;
179
180         if(PADDING[name])
181                 return PADDING[name];
182
183         return 0;
184 }
185
186 function HTMLSerializer() {
187         // empty constructor
188 }
189
190
191
192 HTMLSerializer.prototype._prepare = function() {
193         this.stack = [];
194
195         // XML namespace is implicit
196         this.nsMap = {"http://www.w3.org/XML/1998/namespace": "xml"};
197
198         this.result = "";
199         this.nsCounter = 1;
200 }
201
202 HTMLSerializer.prototype._pushElement = function(element) {
203         this.stack.push({
204                 "type": ELEM_START,
205                 "node": element
206         });
207 }
208
209 HTMLSerializer.prototype._pushChildren = function(element) {
210         for(var i = element.childNodes.length-1; i >= 0; i--)
211                 this._pushElement(element.childNodes.item(i));
212 }
213
214 HTMLSerializer.prototype._pushTagEnd = function(tagName) {
215         this.stack.push({
216                 "type": ELEM_END,
217                 "tagName": tagName
218         });
219 }
220
221 HTMLSerializer.prototype._verseBefore = function(node) {
222         var prev = node.previousSibling;
223
224         while((prev !== null) && (prev.nodeType != ELEMENT_NODE)) {
225                 prev = prev.previousSibling;
226         }
227
228         return (prev !== null) && prev.hasAttribute('x-verse');
229 }
230
231 HTMLSerializer.prototype.serialize = function(rootElement, stripOuter)
232 {
233         var self = this;
234         self._prepare();
235
236         if(!stripOuter)
237                 self._pushElement(rootElement);
238         else
239                 self._pushChildren(rootElement);
240
241         while(self.stack.length > 0) {
242                 var token = self.stack.pop();
243
244                 if(token.type === ELEM_END) {
245                         self.result += "</" + token.tagName + ">";
246                         for(var padding = getPadding(token.tagName); padding > 0; padding--) {
247                                 self.result += "\n";
248                         }
249                         continue;
250                 };
251
252                 if(token.type === NS_END) {
253                         self._unassignNamespace(token.namespace);
254                         continue;
255                 }
256
257
258                 switch(token.node.nodeType) {
259                         case ELEMENT_NODE:
260                                 if(token.node.hasAttribute('x-pass-thru')
261                                  || token.node.hasAttribute('data-pass-thru')) {
262                                         self._pushChildren(token.node);
263                                         break;
264                                 }
265
266                                 if(!token.node.hasAttribute('x-node'))
267                                         break;
268
269                                 var xnode = token.node.getAttribute('x-node');
270
271                                 if(xnode === 'wers') {
272                                         /* push children */
273                                         if(self._verseBefore(token.node))
274                                                 self.result += '/\n';
275                                         self._pushChildren(token.node);
276                                         break;
277                                 };
278
279                                 if(xnode === 'out-of-flow-text') {
280                                         self._pushChildren(token.node);
281                                         break;
282                                 }
283
284                                 if(token.node.hasAttribute('x-verse') && self._verseBefore(token.node)) {
285                                         self.result += '/\n';
286                                 };
287
288                                 self._serializeElement(token.node);
289                                 break;
290                         case TEXT_NODE:
291                                 self.result += token.node.nodeValue;
292                                 break;
293                 };
294         };
295
296         return this.result;
297 }
298
299 /*
300  * TODO: this doesn't support prefix redefinitions
301  */
302 HTMLSerializer.prototype._unassignNamespace = function(nsData) {
303         this.nsMap[nsData.uri] = undefined;
304 };
305
306 HTMLSerializer.prototype._assignNamespace = function(uri) {
307         if(uri === null) {
308                 // default namespace
309                 return ({"prefix": "", "uri": "", "fresh": false});
310         }
311
312         if(this.nsMap[uri] === undefined) {
313                 // this prefix hasn't been defined yet in current context
314                 var prefix = NAMESPACES[uri];
315
316                 if (prefix === undefined) { // not predefined
317                         prefix = "ns" + this.nsCounter;
318                         this.nsCounter += 1;
319                 }
320
321                 this.nsMap[uri] = prefix;
322                 return ({
323                         "prefix": prefix,
324                         "uri": uri,
325                         "fresh": true
326                 });
327         }
328
329         return ({"prefix": this.nsMap[uri], "uri": uri, "fresh": false});
330 };
331
332 HTMLSerializer.prototype._join = function(prefix, name) {
333         if(!!prefix)
334                 return prefix + ":" + name;
335         return name;
336 };
337
338 HTMLSerializer.prototype._rjoin = function(prefix, name) {
339         if(!!name)
340                 return prefix + ":" + name;
341         return prefix;
342 };
343
344 HTMLSerializer.prototype._serializeElement = function(node) {
345         var self = this;
346
347         var ns = node.getAttribute('x-ns');
348         var nsPrefix = null;
349         var newNamespaces = [];
350
351         var nsData = self._assignNamespace(node.getAttribute('x-ns'));
352
353         if(nsData.fresh) {
354                 newNamespaces.push(nsData);
355                 self.stack.push({
356                         "type": NS_END,
357                         "namespace": nsData
358                 });
359         }
360
361         var tagName = self._join(nsData.prefix, node.getAttribute('x-node'));
362
363         /* retrieve attributes */
364         var attributeIDs = [];
365         for (var i = 0; i < node.attributes.length; i++) {
366                 var attr = node.attributes.item(i);
367
368                 // check if name starts with "x-attr-name"
369                 var m = attr.name.match(XATTR_RE);
370                 if (m !== null)
371                         attributeIDs.push(m[1]);
372         };
373
374         /* print out */
375         if (getPadding(tagName))
376                 self.result += '\n';
377
378         self.result += '<' + tagName;
379
380         $.each(attributeIDs, function() {
381                 var nsData = self._assignNamespace(node.getAttribute('x-attr-ns-'+this));
382
383                 if(nsData.fresh) {
384                         newNamespaces.push(nsData);
385                         self.stack.push({
386                                 "type": NS_END,
387                                 "namespace": nsData
388                         });
389                 };
390
391                 self.result += ' ' + self._join(nsData.prefix, node.getAttribute('x-attr-name-'+this));
392                 self.result += '="'+node.getAttribute('x-attr-value-'+this) +'"';
393         });
394
395         /* print new namespace declarations */
396         $.each(newNamespaces, function() {
397                 self.result += " " + self._rjoin("xmlns", this.prefix);
398                 self.result += '="' + this.uri + '"';
399         });
400
401         if (node.childNodes.length > 0) {
402                 self.result += ">";
403                 self._pushTagEnd(tagName);
404                 self._pushChildren(node);
405         }
406         else {
407                 self.result += "/>";
408         };
409 };
410
411 function html2text(params) {
412         try {
413                 var s = new HTMLSerializer();
414                 params.success( s.serialize(params.element, params.stripOuter) );
415         } catch(e) {
416                 params.error("Nie udało się zserializować tekstu:" + e)
417         }
418 }