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  * - BR insined inline?
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
76         var indentstr = in_inline || this.in_pre ? '' : this.indentstr;
77         
78         // if this element is inline - then don't add stuff beforehand..
79         if (!in_inline && !this.in_pre) {
80             this.addLine();
81         }
82         
83         this.html.push(indentstr + '<', name.toLowerCase());
84         
85         if (attrs) {
86             for (i = 0, l = attrs.length; i < l; i++) {
87                 attr = attrs[i];
88                 this.html.push(' ', attr.name, '="', this.encode(attr.value, true), '"');
89             }
90         }
91      
92         if (empty) {
93             if (is_short) {
94                 this.html[this.html.length] = '/>';
95             } else {
96                 this.html[this.html.length] = '></' + name.toLowerCase() + '>';
97             }
98             
99             if (!this.in_inline && !this.in_pre) {
100                 this.addLine();
101             }
102             return;
103         
104         }
105         // not empty..
106         this.html[this.html.length] = '>';
107         
108         // there is a special situation, where we need to turn on in_inline - if any of the imediate chidlren are one of these.
109         /*
110         if (!in_inline && !in_pre) {
111             var cn = node.firstChild;
112             while(cn) {
113                 if (Roo.htmleditor.TidyWriter.inline_elements.indexOf(cn.nodeName) > -1) {
114                     in_inline = true
115                     break;
116                 }
117                 cn = cn.nextSibling;
118             }
119              
120         }
121         */
122         
123         
124         this.pushState({
125             indentstr : in_pre || in_inline ? '' : (this.indentstr + this.indent),
126             in_pre : in_pre,
127             in_inline :  in_inline
128         });
129         // add a line after if we are not in a
130         
131         if (!in_inline && !in_pre) {
132             this.addLine();
133         }
134         
135             
136          
137         
138     },
139     /**
140      * Writes the a end element such as </p>.
141      *
142      * @method end
143      * @param {String} name Name of the element.
144      */
145     end: function(name) {
146         var value;
147         this.popState();
148         var indentstr = '';
149         var in_inline = this.in_inline || Roo.htmleditor.TidyWriter.inline_elements.indexOf(name) > -1;
150         
151         if (!this.in_pre && !in_inline) {
152             this.addLine();
153             indentstr  = this.indentstr;
154         }
155         this.html.push(indentstr + '</', name.toLowerCase(), '>');
156         this.last_inline = in_inline;
157         
158         // pop the indent state..
159     },
160     /**
161      * Writes a text node.
162      *
163      * In pre - we should not mess with the contents.
164      * 
165      *
166      * @method text
167      * @param {String} text String to write out.
168      * @param {Boolean} raw Optional raw state if true the contents wont get encoded.
169      */
170     text: function(text, node)
171     {
172         // if not in whitespace critical
173         if (text.length < 1) {
174             return;
175         }
176         if (this.in_pre || this.in_inline) {
177             this.html[this.html.length] =  text;
178             return;   
179         }
180         // see if last element was a inline element.
181         var indentstr = this.indentstr;
182         if (node.previousSibling &&
183             node.previousSibling.nodeType == 1 &&
184             Roo.htmleditor.TidyWriter.inline_elements.indexOf(node.previousSibling.nodeName) > -1)
185         {
186             indentstr = '';
187         } else {
188             this.addLine();
189         }
190             
191         
192         
193         text = text.replace(/\s/g," ") // all line breaks to ' '
194                 .replace(/^\s+/,'')  // leding white space
195                 .replace(/\s+$/,''); // clean trailing white space
196         
197         if (text.length < 1) {
198             return;
199         }
200         if (!text.match(/\n/)) {
201             this.html.push(indentstr + text);
202             return;
203         }
204         
205         text = this.indentstr + text.replace(
206             /(?![^\n]{1,64}$)([^\n]{1,64})\s/g, '$1\n' + this.indentstr
207         );
208         // remoeve the last whitespace / line break.
209         text = text.replace(/\s+$/,''); 
210         
211         this.html.push(text);
212         
213         // split and indent..
214         
215         
216     },
217     /**
218      * Writes a cdata node such as <![CDATA[data]]>.
219      *
220      * @method cdata
221      * @param {String} text String to write out inside the cdata.
222      */
223     cdata: function(text) {
224         this.html.push('<![CDATA[', text, ']]>');
225     },
226     /**
227     * Writes a comment node such as <!-- Comment -->.
228     *
229     * @method cdata
230     * @param {String} text String to write out inside the comment.
231     */
232    comment: function(text) {
233        this.html.push('<!--', text, '-->');
234    },
235     /**
236      * Writes a PI node such as <?xml attr="value" ?>.
237      *
238      * @method pi
239      * @param {String} name Name of the pi.
240      * @param {String} text String to write out inside the pi.
241      */
242     pi: function(name, text) {
243         text ? this.html.push('<?', name, ' ', this.encode(text), '?>') : this.html.push('<?', name, '?>');
244         this.indent != '' && this.html.push('\n');
245     },
246     /**
247      * Writes a doctype node such as <!DOCTYPE data>.
248      *
249      * @method doctype
250      * @param {String} text String to write out inside the doctype.
251      */
252     doctype: function(text) {
253         this.html.push('<!DOCTYPE', text, '>', this.indent != '' ? '\n' : '');
254     },
255     /**
256      * Resets the internal buffer if one wants to reuse the writer.
257      *
258      * @method reset
259      */
260     reset: function() {
261         this.html.length = 0;
262         this.state = [];
263         this.pushState({
264             indentstr : '',
265             in_pre : false, 
266             in_inline : false
267         })
268     },
269     /**
270      * Returns the contents that got serialized.
271      *
272      * @method getContent
273      * @return {String} HTML contents that got written down.
274      */
275     getContent: function() {
276         return this.html.join('').replace(/\n$/, '');
277     },
278     
279     pushState : function(cfg)
280     {
281         this.state.push(cfg);
282         Roo.apply(this, cfg);
283     },
284     
285     popState : function()
286     {
287         if (this.state.length < 1) {
288             return; // nothing to push
289         }
290         var cfg = {
291             in_pre: false,
292             indentstr : ''
293         };
294         this.state.pop();
295         if (this.state.length > 0) {
296             cfg = this.state[this.state.length-1]; 
297         }
298         Roo.apply(this, cfg);
299     },
300     
301     addLine: function()
302     {
303         if (this.html.length < 1) {
304             return;
305         }
306         
307         
308         var value = this.html[this.html.length - 1];
309         if (value.length > 0 && '\n' !== value) {
310             this.html.push('\n');
311         }
312     }
313     
314     
315 //'pre script noscript style textarea video audio iframe object code'
316 // shortended... 'area base basefont br col frame hr img input isindex link  meta param embed source wbr track');
317 // inline 
318 };
319
320 Roo.htmleditor.TidyWriter.inline_elements = [
321         'SPAN','STRONG','B','EM','I','FONT','STRIKE','U','VAR',
322         'CITE','DFN','CODE','MARK','Q','SUP','SUB','SAMP'
323 ];
324 Roo.htmleditor.TidyWriter.shortend_elements = [
325     'AREA','BASE','BASEFONT','BR','COL','FRAME','HR','IMG','INPUT',
326     'ISINDEX','LINK','','META','PARAM','EMBED','SOURCE','WBR','TRACK'
327 ];
328
329 Roo.htmleditor.TidyWriter.whitespace_elements = [
330     'PRE','SCRIPT','NOSCRIPT','STYLE','TEXTAREA','VIDEO','AUDIO','IFRAME','OBJECT','CODE'
331 ];