Roo/htmleditor/TidyWriter.js
[roojs1] / Roo / htmleditor / TidyWriter.js
1 /***
2  * This is based loosely on tinymce 
3  * @class Roo.htmleditor.TidyWriter
4  * https://github.com/thorn0/tinymce.html/blob/master/tinymce.html.js
5  *
6  * Known issues?
7  * - not tested much with 'PRE' formated elements.
8  * - long text inside of inline can be wrapped and clened?
9  *
10  *
11  */
12
13 Roo.htmleditor.TidyWriter = function(settings)
14 {
15     
16     // indent, indentBefore, indentAfter, encode, htmlOutput, html = [];
17     Roo.apply(this, settings);
18     this.html = [];
19     this.state = [];
20      
21     this.encode = Roo.htmleditor.TidyEntities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
22   
23 }
24 Roo.htmleditor.TidyWriter.prototype = {
25
26
27
28     makeMap : function (items, delim, map) {
29                 var i;
30                 items = items || [];
31                 delim = delim || ',';
32                 if (typeof items == "string") {
33                         items = items.split(delim);
34                 }
35                 map = map || {};
36                 i = items.length;
37                 while (i--) {
38                         map[items[i]] = {};
39                 }
40                 return map;
41         },
42
43     state : false,
44     
45     indent :  '  ',
46     
47     // part of state...
48     indentstr : '',
49     in_pre: false,
50     in_inline : false,
51     last_inline : false,
52     encode : false,
53      
54     
55             /**
56     * Writes the a start element such as <p id="a">.
57     *
58     * @method start
59     * @param {String} name Name of the element.
60     * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
61     * @param {Boolean} empty Optional empty state if the tag should end like <br />.
62     */
63     start: function(name, attrs, empty, node)
64     {
65         var i, l, attr, value;
66         
67         // there are some situations where adding line break && indentation will not work. will not work.
68         // <span / b / i ... formating?
69         
70         var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
71         var in_pre    = this.in_pre    || Roo.htmleditor.TidyWriter.whitespace_elements.indexOf(name) > -1;
72         
73         var is_short   = empty ? Roo.htmleditor.TidyWriter.shortend_elements.indexOf(name) > -1 : false;
74         
75         var add_lb = name == 'BR' ? false : in_inline;
76         
77         if (!add_lb && !this.in_pre && this.lastElementEndsWS()) {
78             i_inline = false;
79         }
80
81         var indentstr = i_inline || this.in_pre ? '' : this.indentstr;
82         
83         // e_inline = elements that can be inline, but still allow \n before and after?
84         // only 'BR' ??? any others?
85         var e_inline = name == 'BR' ? false : this.in_inline;
86         
87         // ADD LINE BEFORE tage
88         if (!this.in_pre) {
89             if (in_inline) {
90                 //code
91                 if (is_br) {
92                     this.addLine();
93                 } else if (this.lastElementEndsWS()) {
94                     this.addLine();
95                 }
96                 // otherwise - no new line.
97             } else {
98                 this.addLine();
99             }
100         }
101         
102         this.html.push(indentstr + '<', name.toLowerCase());
103         
104         if (attrs) {
105             for (i = 0, l = attrs.length; i < l; i++) {
106                 attr = attrs[i];
107                 this.html.push(' ', attr.name, '="', this.encode(attr.value, true), '"');
108             }
109         }
110      
111         if (empty) {
112             if (is_short) {
113                 this.html[this.html.length] = '/>';
114             } else {
115                 this.html[this.html.length] = '></' + name.toLowerCase() + '>';
116             }
117             var e_inline = name == 'BR' ? false : this.in_inline;
118             
119             if (!e_inline && !this.in_pre) {
120                 this.addLine();
121             }
122             return;
123         
124         }
125         // not empty..
126         this.html[this.html.length] = '>';
127         
128         // there is a special situation, where we need to turn on in_inline - if any of the imediate chidlren are one of these.
129         /*
130         if (!in_inline && !in_pre) {
131             var cn = node.firstChild;
132             while(cn) {
133                 if (Roo.htmleditor.TidyWriter.inline_elements.indexOf(cn.nodeName) > -1) {
134                     in_inline = true
135                     break;
136                 }
137                 cn = cn.nextSibling;
138             }
139              
140         }
141         */
142         
143         
144         this.pushState({
145             indentstr : in_pre || in_inline ? '' : (this.indentstr + this.indent),
146             in_pre : in_pre,
147             in_inline :  in_inline
148         });
149         // add a line after if we are not in a
150         
151         if (!in_inline && !in_pre) {
152             this.addLine();
153         }
154         
155             
156          
157         
158     },
159     
160     lastElementEndsWS : function()
161     {
162         var value = this.html.length > 0 ? this.html[this.html.length-1] : false;
163         if (value === false) {
164             return true;
165         }
166         return value.match(/\s+$/);
167         
168     },
169     
170     /**
171      * Writes the a end element such as </p>.
172      *
173      * @method end
174      * @param {String} name Name of the element.
175      */
176     end: function(name) {
177         var value;
178         this.popState();
179         var indentstr = '';
180         var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
181         
182         if (!this.in_pre && !in_inline) {
183             this.addLine();
184             indentstr  = this.indentstr;
185         }
186         this.html.push(indentstr + '</', name.toLowerCase(), '>');
187         this.last_inline = in_inline;
188         
189         // pop the indent state..
190     },
191     /**
192      * Writes a text node.
193      *
194      * In pre - we should not mess with the contents.
195      * 
196      *
197      * @method text
198      * @param {String} text String to write out.
199      * @param {Boolean} raw Optional raw state if true the contents wont get encoded.
200      */
201     text: function(text, node)
202     {
203         // if not in whitespace critical
204         if (text.length < 1) {
205             return;
206         }
207         if (this.in_pre || this.in_inline) {
208             this.html[this.html.length] =  text;
209             return;   
210         }
211         // see if last element was a inline element.
212         var indentstr = this.indentstr;
213         if (node.previousSibling &&
214             node.previousSibling.nodeType == 1 &&
215             Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.previousSibling.nodeName) > -1)
216         {
217             indentstr = '';
218         } else {
219             this.addLine();
220         }
221             
222         
223         
224         text = text.replace(/\s/g," ") // all line breaks to ' '
225                 .replace(/^\s+/,'')  // leding white space
226                 .replace(/\s+$/,''); // clean trailing white space
227         
228         if (text.length < 1) {
229             return;
230         }
231         if (!text.match(/\n/)) {
232             this.html.push(indentstr + text);
233             return;
234         }
235         
236         text = this.indentstr + text.replace(
237             /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
238         );
239         // remoeve the last whitespace / line break.
240         text = text.replace(/\s+$/,''); 
241         
242         this.html.push(text);
243         
244         // split and indent..
245         
246         
247     },
248     /**
249      * Writes a cdata node such as <![CDATA[data]]>.
250      *
251      * @method cdata
252      * @param {String} text String to write out inside the cdata.
253      */
254     cdata: function(text) {
255         this.html.push('<![CDATA[', text, ']]>');
256     },
257     /**
258     * Writes a comment node such as <!-- Comment -->.
259     *
260     * @method cdata
261     * @param {String} text String to write out inside the comment.
262     */
263    comment: function(text) {
264        this.html.push('<!--', text, '-->');
265    },
266     /**
267      * Writes a PI node such as <?xml attr="value" ?>.
268      *
269      * @method pi
270      * @param {String} name Name of the pi.
271      * @param {String} text String to write out inside the pi.
272      */
273     pi: function(name, text) {
274         text ? this.html.push('<?', name, ' ', this.encode(text), '?>') : this.html.push('<?', name, '?>');
275         this.indent != '' && this.html.push('\n');
276     },
277     /**
278      * Writes a doctype node such as <!DOCTYPE data>.
279      *
280      * @method doctype
281      * @param {String} text String to write out inside the doctype.
282      */
283     doctype: function(text) {
284         this.html.push('<!DOCTYPE', text, '>', this.indent != '' ? '\n' : '');
285     },
286     /**
287      * Resets the internal buffer if one wants to reuse the writer.
288      *
289      * @method reset
290      */
291     reset: function() {
292         this.html.length = 0;
293         this.state = [];
294         this.pushState({
295             indentstr : '',
296             in_pre : false, 
297             in_inline : false
298         })
299     },
300     /**
301      * Returns the contents that got serialized.
302      *
303      * @method getContent
304      * @return {String} HTML contents that got written down.
305      */
306     getContent: function() {
307         return this.html.join('').replace(/\n$/, '');
308     },
309     
310     pushState : function(cfg)
311     {
312         this.state.push(cfg);
313         Roo.apply(this, cfg);
314     },
315     
316     popState : function()
317     {
318         if (this.state.length < 1) {
319             return; // nothing to push
320         }
321         var cfg = {
322             in_pre: false,
323             indentstr : ''
324         };
325         this.state.pop();
326         if (this.state.length > 0) {
327             cfg = this.state[this.state.length-1]; 
328         }
329         Roo.apply(this, cfg);
330     },
331     
332     addLine: function()
333     {
334         if (this.html.length < 1) {
335             return;
336         }
337         
338         
339         var value = this.html[this.html.length - 1];
340         if (value.length > 0 && '\n' !== value) {
341             this.html.push('\n');
342         }
343     }
344     
345     
346 //'pre script noscript style textarea video audio iframe object code'
347 // shortended... 'area base basefont br col frame hr img input isindex link  meta param embed source wbr track');
348 // inline 
349 };
350
351 Roo.htmleditor.TidyWriter.inline_elements = [
352         'SPAN','STRONG','B','EM','I','FONT','STRIKE','U','VAR',
353         'CITE','DFN','CODE','MARK','Q','SUP','SUB','SAMP'
354 ];
355 Roo.htmleditor.TidyWriter.shortend_elements = [
356     'AREA','BASE','BASEFONT','BR','COL','FRAME','HR','IMG','INPUT',
357     'ISINDEX','LINK','','META','PARAM','EMBED','SOURCE','WBR','TRACK'
358 ];
359
360 Roo.htmleditor.TidyWriter.whitespace_elements = [
361     'PRE','SCRIPT','NOSCRIPT','STYLE','TEXTAREA','VIDEO','AUDIO','IFRAME','OBJECT','CODE'
362 ];