e0c821341895436c70ff61e19c9c792d25409d5c
[fnpeditor.git] / modules / documentCanvas / canvas / canvas.js
1 define([
2 'libs/jquery-1.9.1.min',
3 'libs/underscore-min',
4 'modules/documentCanvas/canvas/documentElement'
5 ], function($, _, documentElement) {
6     
7 'use strict';
8
9 var Canvas = function(xml) {
10     xml = $.parseXML(xml);
11     this.d = xml !== null ? $(xml.childNodes[0]) : null;
12 };
13
14 $.extend(Canvas.prototype, {
15
16     doc: function() {
17         if(this.d === null)
18             return null;
19         return documentElement.wrap(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
20     },
21
22     wrapText: function(params) {
23         params = _.extend({textNodeIdx: 0}, params);
24         if(typeof params.textNodeIdx === 'number')
25             params.textNodeIdx = [params.textNodeIdx];
26         
27         var childrenInside = params.inside.children(),
28             idx1 = Math.min.apply(Math, params.textNodeIdx),
29             idx2 = Math.max.apply(Math, params.textNodeIdx),
30             textNode1 = childrenInside[idx1],
31             textNode2 = childrenInside[idx2],
32             sameNode = textNode1.sameNode(textNode2),
33             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
34             prefixInside = textNode1.getText().substr(params.offsetStart),
35             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
36             suffixOutside = textNode2.getText().substr(params.offsetEnd)
37         ;
38         
39         var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
40         textNode1.after(wrapperElement);
41         textNode1.detach();
42         
43         if(prefixOutside.length > 0)
44             wrapperElement.before({text:prefixOutside});
45         if(sameNode) {
46             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
47             wrapperElement.append({text: core});
48         } else {
49             textNode2.detach();
50             if(prefixInside.length > 0)
51                 wrapperElement.append({text: prefixInside});
52             for(var i = idx1 + 1; i < idx2; i++) {
53                 wrapperElement.append(childrenInside[i]);
54             }
55             if(suffixInside.length > 0)
56                 wrapperElement.append({text: suffixInside});
57         }
58         if(suffixOutside.length > 0)
59             wrapperElement.after({text: suffixOutside});
60         return wrapperElement;
61     }
62
63 });
64
65 return {
66     fromXML: function(xml) {
67         return new Canvas(xml);
68     }
69 };
70
71 });