f5af909b6630a5c356b3f83a70b8b078fc546139
[redakcja.git] / platforma / static / js / 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
37 function xml2html(options) {
38     withStylesheets(function() {
39         var xml = options.xml.replace(/\/\s+/g, '<br />');                              
40         var parser = new DOMParser();
41         var serializer = new XMLSerializer();
42         var doc = parser.parseFromString(xml, 'text/xml');              
43         var error = $('parsererror', doc);
44         
45         if (error.length == 0) {
46             doc = xml2htmlStylesheet.transformToFragment(doc, document);
47                         console.log(doc.firstChild);
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             options.error(error.text());
59         } else {                        
60             options.success(doc.firstChild);
61         }
62     }, function() { options.error && options.error('Nie udało się załadować XSLT'); });
63 }
64
65 /* USEFULL CONSTANTS */
66 const ELEMENT_NODE                                       = 1;
67 const ATTRIBUTE_NODE                 = 2;
68 const TEXT_NODE                      = 3;
69 const CDATA_SECTION_NODE             = 4;
70 const ENTITY_REFERENCE_NODE          = 5;
71 const ENTITY_NODE                    = 6;
72 const PROCESSING_INSTRUCTION_NODE    = 7;
73 const COMMENT_NODE                   = 8;
74 const DOCUMENT_NODE                  = 9;
75 const DOCUMENT_TYPE_NODE             = 10;
76 const DOCUMENT_FRAGMENT_NODE         = 11;
77 const NOTATION_NODE                  = 12;
78 const XATTR_RE = /^x-attr-name-(.*)$/;
79
80 const ELEM_START = 1;
81 const ELEM_END = 2;
82 const NS_END = 3;
83
84 const NAMESPACES = {
85         // namespaces not listed here will be assigned random names
86         "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
87         "http://purl.org/dc/elements/1.1/": "dc",
88         "http://www.w3.org/XML/1998/namespace": "xml"
89 };
90
91 /*
92  * PADDING for pretty-printing
93  */
94 const PADDING = {
95     dramat_wierszowany_l: 4,
96     dramat_wierszowany_lp: 4,
97     dramat_wspolczesny: 4,
98     wywiad: 4,
99     opowiadanie: 4,
100     powiesc: 4,
101     liryka_l: 4,
102     liryka_lp: 4,
103     naglowek_czesc: 4,
104     naglowek_akt: 4,
105     naglowek_rozdzial: 4,
106     naglowek_osoba: 4,
107     lista_osob: 4,
108     
109     akap: 3,
110     akap_cd: 3,
111     akap_dialog: 3,
112     strofa: 3,
113     motto: 3, 
114     miejsce_czas: 3,
115         
116     autor_utworu: 2,
117     nazwa_utworu: 2,
118     dzielo_nadrzedne: 2,
119         
120     didaskalia: 2,
121     motto_podpis: 2,
122     naglowek_listy: 2,
123     kwestia: 1,
124     lista_osoba: 1,
125         
126         "podpis": 1,    
127         "wers": 0,
128         "wers_cd": 0,
129         "wers_akap": 0,
130         "wers_wciety": 0,       
131         
132         "rdf:RDF": 3,
133         "rdf:Description": 1,   
134 };
135
136 function getPadding(name) {
137         
138         if(name.match(/^dc:.*$/))
139                 return -1;
140         
141         if(PADDING[name])
142                 return PADDING[name];
143                 
144         return 0;
145 }
146
147 function HTMLSerializer() {     
148         // empty constructor
149 }
150
151
152
153 HTMLSerializer.prototype._prepare = function() {
154         this.stack = [];
155         
156         // XML namespace is implicit
157         this.nsMap = {"http://www.w3.org/XML/1998/namespace": "xml"};
158                 
159         this.result = "";
160         this.nsCounter = 1;     
161 }
162
163 HTMLSerializer.prototype._pushElement = function(element) {
164         this.stack.push({
165                 "type": ELEM_START,
166                 "node": element
167         });     
168 }
169
170 HTMLSerializer.prototype._pushChildren = function(element) {
171         for(var i = element.childNodes.length-1; i >= 0; i--)
172                 this._pushElement(element.childNodes.item(i));                                  
173 }
174
175 HTMLSerializer.prototype._pushTagEnd = function(tagName) {
176         this.stack.push({
177                 "type": ELEM_END,
178                 "tagName": tagName
179         });     
180 }
181
182 HTMLSerializer.prototype._verseBefore = function(node) {
183         var prev = node.previousSibling;
184         
185         while((prev !== null) && (prev.nodeType != ELEMENT_NODE)) {
186                 prev = prev.previousSibling;
187         }       
188                 
189         return (prev !== null) && prev.hasAttribute('x-verse');
190 }
191
192 HTMLSerializer.prototype.serialize = function(rootElement, stripOuter) 
193 {
194         var self = this;
195         self._prepare();
196         
197         if(!stripOuter)
198                 self._pushElement(rootElement);
199         else    
200                 self._pushChildren(rootElement);
201         
202         while(self.stack.length > 0) {
203                 var token = self.stack.pop();
204                                                 
205                 if(token.type === ELEM_END) {
206                         self.result += "</" + token.tagName + ">";                                      
207                         for(var padding = getPadding(token.tagName); padding > 0; padding--) {                  
208                                 self.result += "\n";                    
209                         }
210                         continue;
211                 };
212                 
213                 if(token.type === NS_END) {
214                         self._unassignNamespace(token.namespace);
215                         continue;
216                 } 
217                 
218                 
219                 switch(token.node.nodeType) {
220                         case ELEMENT_NODE:
221                                 if(token.node.hasAttribute('x-pass-thru')) {
222                                         self._pushChildren(token.node);
223                                         break;
224                                 }
225                                 
226                                 if(!token.node.hasAttribute('x-node'))
227                                         break;
228                                         
229                                 var xnode = token.node.getAttribute('x-node');
230                                 
231                                 if(xnode === 'wers') {
232                                         /* push children */
233                                         if(self._verseBefore(token.node))
234                                                 self.result += '/\n';
235                                         self._pushChildren(token.node);
236                                         break;                                  
237                                 };                                      
238                                 
239                                 if(token.node.hasAttribute('x-verse') && self._verseBefore(token.node)) {
240                                         self.result += '/\n';                                   
241                                 };
242                                         
243                                 self._serializeElement(token.node);
244                                 break;
245                         case TEXT_NODE:
246                                 self.result += token.node.nodeValue;
247                                 break;
248                 };
249         };
250         
251         return this.result;
252 }
253
254 /*
255  * TODO: this doesn't support prefix redefinitions
256  */
257 HTMLSerializer.prototype._unassignNamespace = function(nsData) {
258         this.nsMap[nsData.uri] = undefined;
259 };
260         
261 HTMLSerializer.prototype._assignNamespace = function(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 HTMLSerializer.prototype._join = function(prefix, name) {
288         if(!!prefix) 
289                 return prefix + ":" + name;
290         return name;    
291 };
292
293 HTMLSerializer.prototype._rjoin = function(prefix, name) {
294         if(!!name) 
295                 return prefix + ":" + name;
296         return prefix;  
297 };
298                                         
299 HTMLSerializer.prototype._serializeElement = function(node) {
300         var self = this;
301                 
302         var ns = node.getAttribute('x-ns');
303         var nsPrefix = null;
304         var newNamespaces = [];
305         
306         var nsData = self._assignNamespace(node.getAttribute('x-ns'));
307         
308         if(nsData.fresh) {
309                 newNamespaces.push(nsData);
310                 self.stack.push({
311                         "type": NS_END,
312                         "namespace": nsData
313                 });
314         }                                       
315         
316         var tagName = self._join(nsData.prefix, node.getAttribute('x-node'));
317                                 
318         /* retrieve attributes */
319         var attributeIDs = [];
320         for (var i = 0; i < node.attributes.length; i++) {
321                 var attr = node.attributes.item(i);
322                 
323                 // check if name starts with "x-attr-name"
324                 var m = attr.name.match(XATTR_RE);
325                 if (m !== null) 
326                         attributeIDs.push(m[1]);                                
327         };
328                                 
329         /* print out */
330         if (getPadding(tagName))
331                 self.result += '\n';
332                 
333         self.result += '<' + tagName;   
334                                         
335         $.each(attributeIDs, function() {
336                 var nsData = self._assignNamespace(node.getAttribute('x-attr-ns-'+this));
337         
338                 if(nsData.fresh) {
339                         newNamespaces.push(nsData);
340                         self.stack.push({
341                                 "type": NS_END,
342                                 "namespace": nsData
343                         });
344                 };
345                                                                                                                         
346                 self.result += ' ' + self._join(nsData.prefix, node.getAttribute('x-attr-name-'+this));
347                 self.result += '="'+node.getAttribute('x-attr-value-'+this) +'"';
348         });
349         
350         /* print new namespace declarations */
351         $.each(newNamespaces, function() {
352                 self.result += " " + self._rjoin("xmlns", this.prefix);
353                 self.result += '="' + this.uri + '"';           
354         });                                     
355         
356         if (node.childNodes.length > 0) {
357                 self.result += ">";
358                 self._pushTagEnd(tagName);
359                 self._pushChildren(node);
360         }
361         else {
362                 self.result += "/>";
363         };
364 };
365
366 function html2text(params) {    
367         try {
368                 var s = new HTMLSerializer();
369                 params.success( s.serialize(params.element, params.stripOuter) );
370         } catch(e) {
371                 params.error("Nie udało się zserializować tekstu:" + e)
372         }       
373 }