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