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