editor: refactoring canvas element state management
[fnpeditor.git] / src / editor / modules / documentCanvas / canvas / documentElement.js
1 define([
2 'libs/jquery',
3 'libs/underscore',
4 'modules/documentCanvas/canvas/utils'
5 ], function($, _, utils) {
6     
7 'use strict';
8 /* global Node:false */
9
10 // DocumentElement represents a text or an element node from WLXML document rendered inside Canvas
11 var DocumentElement = function(wlxmlNode, canvas) {
12     this.wlxmlNode = wlxmlNode;
13     this.canvas = canvas;
14     this.state = {
15         exposed: false,
16         active: false
17     };
18
19     this.dom = this.createDOM();
20     this.dom.data('canvas-element', this);
21 };
22
23 $.extend(DocumentElement.prototype, {
24     refreshPath: function() {
25         this.parents().forEach(function(parent) {
26             parent.refresh();
27         });
28         this.refresh();
29     },
30     refresh: function() {
31         // noop
32     },
33     updateState: function(toUpdate) {
34         var changes = {};
35         _.keys(toUpdate)
36             .filter(function(key) {
37                 return this.state.hasOwnProperty(key);
38             }.bind(this))
39             .forEach(function(key) {
40                 if(this.state !== toUpdate[key]) {
41                     this.state[key] = changes[key] = toUpdate[key];
42                 }
43             }.bind(this));
44         if(_.isFunction(this.onStateChange)) {
45             this.onStateChange(changes);
46         }
47     },
48     parent: function() {
49         var parents = this.dom.parents('[document-node-element]');
50         if(parents.length) {
51             return this.canvas.getDocumentElement(parents[0]);
52         }
53         return null;
54     },
55
56     parents: function() {
57         var parents = [],
58             parent = this.parent();
59         while(parent) {
60             parents.push(parent);
61             parent = parent.parent();
62         }
63         return parents;
64     },
65
66     sameNode: function(other) {
67         return other && (typeof other === typeof this) && other.dom[0] === this.dom[0];
68     },
69
70     trigger: function() {
71         this.canvas.eventBus.trigger.apply(this.canvas.eventBus, Array.prototype.slice.call(arguments, 0));
72     }
73
74
75 });
76
77
78 // DocumentNodeElement represents an element node from WLXML document rendered inside Canvas
79 var DocumentNodeElement = function(wlxmlNode, canvas) {
80     DocumentElement.call(this, wlxmlNode, canvas);
81     wlxmlNode.setData('canvasElement', this);
82     this.init(this.dom);
83 };
84
85
86 var manipulate = function(e, params, action) {
87     var element;
88     if(params instanceof DocumentElement) {
89         element = params;
90     } else {
91         element = e.canvas.createElement(params);
92     }
93     e.dom[action](element.dom);
94     e.refreshPath();
95     return element;
96 };
97
98 DocumentNodeElement.prototype = Object.create(DocumentElement.prototype);
99
100
101 $.extend(DocumentNodeElement.prototype, {
102     defaultDisplayStyle: 'block',
103     init: function() {},
104     addWidget: function(widget) {
105         this.dom.children('.canvas-widgets').append(widget.DOM ? widget.DOM : widget);
106     },
107     clearWidgets: function() {
108         this.dom.children('.canvas-widgets').empty();
109     },
110     handle: function(event) {
111         var method = 'on' + event.type[0].toUpperCase() + event.type.substr(1);
112         if(this[method]) {
113             this[method](event);
114         }
115     },
116     createDOM: function() {
117         var wrapper = $('<div>').attr('document-node-element', ''),
118             widgetsContainer = $('<div>')
119                 .addClass('canvas-widgets')
120                 .attr('contenteditable', false),
121             contentContainer = $('<div>')
122                 .attr('document-element-content', '');
123         
124         wrapper.append(contentContainer, widgetsContainer);
125         widgetsContainer.find('*').add(widgetsContainer).attr('tabindex', -1);
126         return wrapper;
127     },
128     _container: function() {
129         return this.dom.children('[document-element-content]');
130     },
131     detach: function() {
132         var parents = this.parents();
133         this.dom.detach();
134         if(parents[0]) {
135             parents[0].refreshPath();
136         }
137          return this;
138     },
139     before: function(params) {
140         return manipulate(this, params, 'before');
141
142     },
143     after: function(params) {
144         return manipulate(this, params, 'after');
145     },
146
147     isBlock: function() {
148         return this.dom.css('display') === 'block';
149     },
150
151     displayAsBlock: function() {
152         this.dom.css('display', 'block');
153         this._container().css('display', 'block');
154     },
155     displayInline: function() {
156         this.dom.css('display', 'inline');
157         this._container().css('display', 'inline');
158     },
159     displayAs: function(what) {
160         // [this.dom(), this._container()].forEach(e) {
161         //     var isBlock = window.getComputedStyle(e).display === 'block';
162         //     if(!isBlock && what === 'block') {
163         //         e.css('display', what);
164         //     } else if(isBlock && what === 'inline') {
165         //         e.css('display')
166         //     }
167         // })
168         this.dom.css('display', what);
169         this._container().css('display', what);
170     }
171 });
172
173
174 // DocumentNodeElement represents a text node from WLXML document rendered inside Canvas
175 var DocumentTextElement = function(wlxmlTextNode, canvas) {
176     DocumentElement.call(this, wlxmlTextNode, canvas);
177 };
178
179 $.extend(DocumentTextElement, {
180     isContentContainer: function(htmlElement) {
181         return htmlElement.nodeType === Node.TEXT_NODE && $(htmlElement).parent().is('[document-text-element]');
182     }
183 });
184
185 DocumentTextElement.prototype = Object.create(DocumentElement.prototype);
186
187 $.extend(DocumentTextElement.prototype, {
188     createDOM: function() {
189         var dom = $('<div>')
190             .attr('document-text-element', '')
191             .text(this.wlxmlNode.getText() || utils.unicode.ZWS);
192         return dom;
193     },
194     detach: function() {
195         this.dom.detach();
196         return this;
197     },
198     setText: function(text) {
199         if(text === '') {
200             text = utils.unicode.ZWS;
201         }
202         if(text !== this.getText()) {
203             this.dom.contents()[0].data = text;
204         }
205     },
206     getText: function(options) {
207         options = _.extend({raw: false}, options || {});
208         var toret = this.dom.text();
209         if(!options.raw) {
210             toret = toret.replace(utils.unicode.ZWS, '');
211         }
212         return toret;
213     },
214     isEmpty: function() {
215         // Having at least Zero Width Space is guaranteed be Content Observer
216         return this.dom.contents()[0].data === utils.unicode.ZWS;
217     },
218     after: function(params) {
219         if(params instanceof DocumentTextElement || params.text) {
220             return false;
221         }
222         var element;
223         if(params instanceof DocumentNodeElement) {
224             element = params;
225         } else {
226             element = this.canvas.createElement(params);
227         }
228         this.dom.wrap('<div>');
229         this.dom.parent().after(element.dom);
230         this.dom.unwrap();
231         this.refreshPath();
232         return element;
233     },
234     before: function(params) {
235         if(params instanceof DocumentTextElement || params.text) {
236             return false;
237         }
238         var element;
239         if(params instanceof DocumentNodeElement) {
240             element = params;
241         } else {
242             element = this.canvas.createElement(params);
243         }
244         this.dom.wrap('<div>');
245         this.dom.parent().before(element.dom);
246         this.dom.unwrap();
247         this.refreshPath();
248         return element;
249     },
250
251     children: function() {
252         return [];
253     }
254
255 });
256
257
258 return {
259     DocumentElement: DocumentElement,
260     DocumentNodeElement: DocumentNodeElement,
261     DocumentTextElement: DocumentTextElement
262 };
263
264 });