5 'modules/documentCanvas/canvas/documentElement',
6 'modules/documentCanvas/canvas/keyboard',
7 'modules/documentCanvas/canvas/utils',
8 'modules/documentCanvas/canvas/wlxmlListener'
9 ], function($, _, Backbone, documentElement, keyboard, utils, wlxmlListener) {
13 var Canvas = function(wlxmlDocument, publisher) {
14 this.eventBus = _.extend({}, Backbone.Events);
15 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
16 this.wlxmlListener = wlxmlListener.create(this);
17 this.loadWlxmlDocument(wlxmlDocument);
18 this.publisher = publisher ? publisher : function() {};
21 $.extend(Canvas.prototype, {
23 loadWlxmlDocument: function(wlxmlDocument) {
28 var canvasDOM = this.generateCanvasDOM(wlxmlDocument.root);
31 this.wrapper.append(canvasDOM);
32 this.d = this.wrapper.children(0);
33 this.setupEventHandling();
35 this.wlxmlListener.listenTo(wlxmlDocument);
36 this.wlxmlDocument = wlxmlDocument;
39 generateCanvasDOM: function(wlxmlNode) {
40 var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
44 setupEventHandling: function() {
46 this.wrapper.on('keyup keydown keypress', function(e) {
47 keyboard.handleKey(e, this);
50 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
52 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
55 var observer = new MutationObserver(function(mutations) {
56 mutations.forEach(function(mutation) {
57 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
58 observer.disconnect();
59 if(mutation.target.data === '')
60 mutation.target.data = utils.unicode.ZWS;
61 else if(mutation.oldValue === utils.unicode.ZWS) {
62 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
63 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
65 observer.observe(canvas.d[0], config);
66 canvas.publisher('contentChanged');
68 var textElement = canvas.getDocumentElement(mutation.target),
69 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
71 textElement.data('wlxmlNode').setText(toSet);
75 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
76 observer.observe(this.d[0], config);
79 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
80 var el = canvas.getDocumentElement(e.currentTarget);
84 if(el instanceof documentElement.DocumentTextElement)
88 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
89 var el = canvas.getDocumentElement(e.currentTarget);
93 if(el instanceof documentElement.DocumentTextElement)
95 el.toggleLabel(false);
98 this.eventBus.on('elementToggled', function(toggle, element) {
100 canvas.setCurrentElement(element.getPreviousTextElement());
112 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
115 toggleElementHighlight: function(node, toggle) {
116 var element = utils.findCanvasElement(node);
117 element.toggleHighlight(toggle);
120 createNodeElement: function(params) {
121 return documentElement.DocumentNodeElement.create(params, this);
124 getDocumentElement: function(from) {
125 if(from instanceof HTMLElement || from instanceof Text) {
126 return documentElement.DocumentElement.fromHTMLElement(from, this);
129 getCursor: function() {
130 return new Cursor(this);
136 getCurrentNodeElement: function() {
137 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
140 getCurrentTextElement: function() {
141 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
146 setCurrentElement: function(element, params) {
147 if(!(element instanceof documentElement.DocumentElement)) {
148 element = utils.findCanvasElement(element);
151 params = _.extend({caretTo: 'end'}, params);
152 var findFirstDirectTextChild = function(e, nodeToLand) {
153 var byBrowser = this.getCursor().getPosition().element;
154 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
156 var children = e.children();
157 for(var i = 0; i < children.length; i++) {
158 if(children[i] instanceof documentElement.DocumentTextElement)
163 var _markAsCurrent = function(element) {
164 if(element instanceof documentElement.DocumentTextElement) {
165 this.wrapper.find('.current-text-element').removeClass('current-text-element');
166 element.dom().addClass('current-text-element');
168 this.wrapper.find('.current-node-element').removeClass('current-node-element')
169 element._container().addClass('current-node-element');
170 this.publisher('currentElementChanged', element);
175 var isTextElement = element instanceof documentElement.DocumentTextElement,
176 nodeElementToLand = isTextElement ? element.parent() : element,
177 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
178 currentTextElement = this.getCurrentTextElement(),
179 currentNodeElement = this.getCurrentNodeElement();
181 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
182 this.wrapper.find('.current-text-element').removeClass('current-text-element');
184 if(textElementToLand) {
185 _markAsCurrent(textElementToLand);
186 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
187 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
188 if(!(textElementToLand.sameNode(currentTextElement)))
189 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
191 document.getSelection().removeAllRanges();
194 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
195 _markAsCurrent(nodeElementToLand);
197 this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
201 _moveCaretToTextElement: function(element, where) {
202 var range = document.createRange(),
203 node = element.dom().contents()[0];
205 if(typeof where !== 'number') {
206 range.selectNodeContents(node);
208 range.setStart(node, where);
211 var collapseArg = true;
214 range.collapse(collapseArg);
216 var selection = document.getSelection();
218 selection.removeAllRanges();
219 selection.addRange(range);
220 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
223 setCursorPosition: function(position) {
225 this._moveCaretToTextElement(position.element, position.offset);
229 $.extend(Canvas.prototype.list, {
230 create: function(params) {
231 if(!(params.element1.parent().sameNode(params.element2.parent())))
234 var parent = params.element1.parent(),
235 canvas = params.element1.canvas;
237 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
238 var tmp = params.element1;
239 params.element1 = params.element2;
240 params.element2 = tmp;
243 var elementsToWrap = [];
245 var place = 'before';
246 parent.children().some(function(element) {
248 if(element.sameNode(params.element1))
250 if(place === 'inside') {
251 if(element instanceof documentElement.DocumentTextElement) {
252 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
253 if(element.children()[0].sameNode(params.element1))
254 params.element1 = element;
256 element.setWlxmlClass('item');
257 elementsToWrap.push(element);
259 if(_e.sameNode(params.element2))
263 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
265 if(parent.is('list')) {
266 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
267 item.exec('toggleBullet', false);
268 toret = listElement.parent();
273 params.element1.before(toret);
275 elementsToWrap.forEach(function(element) {
277 listElement.append(element);
280 extractItems: function(params) {
281 params = _.extend({merge: true}, params);
282 var list = params.element1.parent();
283 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
286 var idx1 = list.childIndex(params.element1),
287 idx2 = list.childIndex(params.element2),
290 succeedingItems = [],
291 items = list.children(),
292 listIsNested = list.parent().getWlxmlClass() === 'item',
293 canvas = params.element1.canvas,
297 var tmp = idx1; idx1 = idx2; idx2 = tmp;
300 items.forEach(function(item, idx) {
302 precedingItems.push(item);
303 else if(idx >= idx1 && idx <= idx2) {
304 extractedItems.push(item);
307 succeedingItems.push(item);
311 var reference = listIsNested ? list.parent() : list;
312 if(succeedingItems.length === 0) {
313 var reference_orig = reference;
314 extractedItems.forEach(function(item) {
315 reference.after(item);
318 item.setWlxmlClass(null);
320 if(precedingItems.length === 0)
321 reference_orig.detach();
322 } else if(precedingItems.length === 0) {
323 extractedItems.forEach(function(item) {
324 reference.before(item);
326 item.setWlxmlClass(null);
329 extractedItems.forEach(function(item) {
330 reference.after(item);
332 item.setWlxmlClass(null);
335 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
339 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
341 succeedingItems.forEach(function(item) {
342 secondList.append(item);
345 reference.after(toAdd);
347 if(!params.merge && listIsNested) {
348 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
352 areItemsOfTheSameList: function(params) {
353 var e1 = params.element1,
354 e2 = params.element2;
355 return e1.parent().sameNode(e2.parent())
356 && e1.parent().is('list');
361 var Cursor = function(canvas) {
362 this.canvas = canvas;
365 $.extend(Cursor.prototype, {
366 isSelecting: function() {
367 var selection = window.getSelection();
368 return !selection.isCollapsed;
370 isSelectingWithinElement: function() {
371 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
373 isSelectingSiblings: function() {
374 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
376 getPosition: function() {
377 return this.getSelectionAnchor();
379 getSelectionStart: function() {
380 return this.getSelectionBoundry('start');
382 getSelectionEnd: function() {
383 return this.getSelectionBoundry('end');
385 getSelectionAnchor: function() {
386 return this.getSelectionBoundry('anchor');
388 getSelectionFocus: function() {
389 return this.getSelectionBoundry('focus');
391 getSelectionBoundry: function(which) {
392 var selection = window.getSelection(),
393 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
394 focusElement = this.canvas.getDocumentElement(selection.focusNode);
396 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
399 if(which === 'anchor') {
401 element: anchorElement,
402 offset: selection.anchorOffset,
403 offsetAtBeginning: selection.anchorOffset === 0,
404 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
407 if(which === 'focus') {
409 element: focusElement,
410 offset: selection.focusOffset,
411 offsetAtBeginning: selection.focusOffset === 0,
412 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
419 if(anchorElement.parent().sameNode(focusElement.parent())) {
420 var parent = anchorElement.parent(),
421 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
423 if(which === 'start') {
424 element = anchorElement;
425 offset = selection.anchorOffset
427 else if(which === 'end') {
428 element = focusElement,
429 offset = selection.focusOffset
432 if(which === 'start') {
433 element = focusElement,
434 offset = selection.focusOffset
436 else if(which === 'end') {
437 element = anchorElement;
438 offset = selection.anchorOffset
442 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
443 if(which === 'start') {
444 element = anchorElement;
445 offset = selection.anchorOffset
447 element = focusElement;
448 offset = selection.focusOffset
452 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
456 offsetAtBeginning: offset === 0,
457 offsetAtEnd: nodeLen === offset
463 fromXMLDocument: function(wlxmlDocument, publisher) {
464 return new Canvas(wlxmlDocument, publisher);