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