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);
38 generateCanvasDOM: function(wlxmlNode) {
39 var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
43 setupEventHandling: function() {
45 this.wrapper.on('keyup keydown keypress', function(e) {
46 keyboard.handleKey(e, this);
49 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
51 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
54 var observer = new MutationObserver(function(mutations) {
55 mutations.forEach(function(mutation) {
56 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
57 observer.disconnect();
58 if(mutation.target.data === '')
59 mutation.target.data = utils.unicode.ZWS;
60 else if(mutation.oldValue === utils.unicode.ZWS) {
61 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
62 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
64 observer.observe(canvas.d[0], config);
65 canvas.publisher('contentChanged');
67 var textElement = canvas.getDocumentElement(mutation.target);
68 textElement.data('wlxmlNode').setText(mutation.target.data);
72 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
73 observer.observe(this.d[0], config);
76 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
77 var el = canvas.getDocumentElement(e.currentTarget);
81 if(el instanceof documentElement.DocumentTextElement)
85 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
86 var el = canvas.getDocumentElement(e.currentTarget);
90 if(el instanceof documentElement.DocumentTextElement)
92 el.toggleLabel(false);
95 this.eventBus.on('elementToggled', function(toggle, element) {
97 canvas.setCurrentElement(element.getPreviousTextElement());
109 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
112 createNodeElement: function(params) {
113 return documentElement.DocumentNodeElement.create(params, this);
116 wrapText: function(params) {
117 params = _.extend({textNodeIdx: 0}, params);
118 if(typeof params.textNodeIdx === 'number')
119 params.textNodeIdx = [params.textNodeIdx];
121 var childrenInside = params.inside.children(),
122 idx1 = Math.min.apply(Math, params.textNodeIdx),
123 idx2 = Math.max.apply(Math, params.textNodeIdx),
124 textNode1 = childrenInside[idx1],
125 textNode2 = childrenInside[idx2],
126 sameNode = textNode1.sameNode(textNode2),
127 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
128 prefixInside = textNode1.getText().substr(params.offsetStart),
129 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
130 suffixOutside = textNode2.getText().substr(params.offsetEnd)
133 var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
134 textNode1.after(wrapperElement);
137 if(prefixOutside.length > 0)
138 wrapperElement.before({text:prefixOutside});
140 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
141 wrapperElement.append({text: core});
144 if(prefixInside.length > 0)
145 wrapperElement.append({text: prefixInside});
146 for(var i = idx1 + 1; i < idx2; i++) {
147 wrapperElement.append(childrenInside[i]);
149 if(suffixInside.length > 0)
150 wrapperElement.append({text: suffixInside});
152 if(suffixOutside.length > 0)
153 wrapperElement.after({text: suffixOutside});
154 return wrapperElement;
157 wrapElements: function(params) {
158 if(!(params.element1.parent().sameNode(params.element2.parent())))
161 var parent = params.element1.parent(),
162 parentChildren = parent.children(),
163 wrapper = this.createNodeElement({
164 tag: params._with.tag,
165 klass: params._with.klass}),
166 idx1 = parent.childIndex(params.element1),
167 idx2 = parent.childIndex(params.element2);
175 var insertingMethod, insertingTarget;
177 insertingMethod = 'prepend';
178 insertingTarget = parent;
180 insertingMethod = 'after';
181 insertingTarget = parentChildren[idx1-1];
184 for(var i = idx1; i <= idx2; i++) {
185 wrapper.append(parentChildren[i].detach());
188 insertingTarget[insertingMethod](wrapper);
192 getSiblingParents: function(params) {
193 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
194 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
195 noSiblingParents = null;
197 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
198 return noSiblingParents;
201 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
202 if(parents1[i].sameNode(parents2[i]))
206 return {element1: parents1[i], element2: parents2[i]};
209 getDocumentElement: function(from) {
210 if(from instanceof HTMLElement || from instanceof Text) {
211 return documentElement.DocumentElement.fromHTMLElement(from, this);
214 getCursor: function() {
215 return new Cursor(this);
221 getCurrentNodeElement: function() {
222 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
225 getCurrentTextElement: function() {
226 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
231 setCurrentElement: function(element, params) {
232 params = _.extend({caretTo: 'end'}, params);
233 var findFirstDirectTextChild = function(e, nodeToLand) {
234 var byBrowser = this.getCursor().getPosition().element;
235 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
237 var children = e.children();
238 for(var i = 0; i < children.length; i++) {
239 if(children[i] instanceof documentElement.DocumentTextElement)
244 var _markAsCurrent = function(element) {
245 if(element instanceof documentElement.DocumentTextElement) {
246 this.wrapper.find('.current-text-element').removeClass('current-text-element');
247 element.dom().addClass('current-text-element');
249 this.wrapper.find('.current-node-element').removeClass('current-node-element')
250 element._container().addClass('current-node-element');
251 this.publisher('currentElementChanged', element);
256 var isTextElement = element instanceof documentElement.DocumentTextElement,
257 nodeElementToLand = isTextElement ? element.parent() : element,
258 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
259 currentTextElement = this.getCurrentTextElement(),
260 currentNodeElement = this.getCurrentNodeElement();
262 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
263 this.wrapper.find('.current-text-element').removeClass('current-text-element');
265 if(textElementToLand) {
266 _markAsCurrent(textElementToLand);
267 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
268 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
269 if(!(textElementToLand.sameNode(currentTextElement)))
270 this.publisher('currentTextElementSet', textElementToLand);
272 document.getSelection().removeAllRanges();
275 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
276 _markAsCurrent(nodeElementToLand);
278 this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
282 _moveCaretToTextElement: function(element, where) {
283 var range = document.createRange(),
284 node = element.dom().contents()[0];
286 if(typeof where !== 'number') {
287 range.selectNodeContents(node);
289 range.setStart(node, where);
292 var collapseArg = true;
295 range.collapse(collapseArg);
297 var selection = document.getSelection();
299 selection.removeAllRanges();
300 selection.addRange(range);
301 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
304 setCursorPosition: function(position) {
306 this._moveCaretToTextElement(position.element, position.offset);
310 var parent = $('<div>'),
311 parts = this.doc().toXML(0);
312 parent.append(parts);
313 return parent.html();
317 $.extend(Canvas.prototype.list, {
318 create: function(params) {
319 if(!(params.element1.parent().sameNode(params.element2.parent())))
322 var parent = params.element1.parent(),
323 canvas = params.element1.canvas;
325 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
326 var tmp = params.element1;
327 params.element1 = params.element2;
328 params.element2 = tmp;
331 var elementsToWrap = [];
333 var place = 'before';
334 parent.children().some(function(element) {
336 if(element.sameNode(params.element1))
338 if(place === 'inside') {
339 if(element instanceof documentElement.DocumentTextElement) {
340 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
341 if(element.children()[0].sameNode(params.element1))
342 params.element1 = element;
344 element.setWlxmlClass('item');
345 elementsToWrap.push(element);
347 if(_e.sameNode(params.element2))
351 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
353 if(parent.is('list')) {
354 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
355 item.exec('toggleBullet', false);
356 toret = listElement.parent();
361 params.element1.before(toret);
363 elementsToWrap.forEach(function(element) {
365 listElement.append(element);
368 extractItems: function(params) {
369 params = _.extend({merge: true}, params);
370 var list = params.element1.parent();
371 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
374 var idx1 = list.childIndex(params.element1),
375 idx2 = list.childIndex(params.element2),
378 succeedingItems = [],
379 items = list.children(),
380 listIsNested = list.parent().getWlxmlClass() === 'item',
381 canvas = params.element1.canvas,
385 var tmp = idx1; idx1 = idx2; idx2 = tmp;
388 items.forEach(function(item, idx) {
390 precedingItems.push(item);
391 else if(idx >= idx1 && idx <= idx2) {
392 extractedItems.push(item);
395 succeedingItems.push(item);
399 var reference = listIsNested ? list.parent() : list;
400 if(succeedingItems.length === 0) {
401 var reference_orig = reference;
402 extractedItems.forEach(function(item) {
403 reference.after(item);
406 item.setWlxmlClass(null);
408 if(precedingItems.length === 0)
409 reference_orig.detach();
410 } else if(precedingItems.length === 0) {
411 extractedItems.forEach(function(item) {
412 reference.before(item);
414 item.setWlxmlClass(null);
417 extractedItems.forEach(function(item) {
418 reference.after(item);
420 item.setWlxmlClass(null);
423 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
427 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
429 succeedingItems.forEach(function(item) {
430 secondList.append(item);
433 reference.after(toAdd);
435 if(!params.merge && listIsNested) {
436 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
440 areItemsOfTheSameList: function(params) {
441 var e1 = params.element1,
442 e2 = params.element2;
443 return e1.parent().sameNode(e2.parent())
444 && e1.parent().is('list');
449 var Cursor = function(canvas) {
450 this.canvas = canvas;
453 $.extend(Cursor.prototype, {
454 isSelecting: function() {
455 var selection = window.getSelection();
456 return !selection.isCollapsed;
458 isSelectingWithinElement: function() {
459 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
461 isSelectingSiblings: function() {
462 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
464 getPosition: function() {
465 return this.getSelectionAnchor();
467 getSelectionStart: function() {
468 return this.getSelectionBoundry('start');
470 getSelectionEnd: function() {
471 return this.getSelectionBoundry('end');
473 getSelectionAnchor: function() {
474 return this.getSelectionBoundry('anchor');
476 getSelectionFocus: function() {
477 return this.getSelectionBoundry('focus');
479 getSelectionBoundry: function(which) {
480 var selection = window.getSelection(),
481 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
482 focusElement = this.canvas.getDocumentElement(selection.focusNode);
484 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
487 if(which === 'anchor') {
489 element: anchorElement,
490 offset: selection.anchorOffset,
491 offsetAtBeginning: selection.anchorOffset === 0,
492 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
495 if(which === 'focus') {
497 element: focusElement,
498 offset: selection.focusOffset,
499 offsetAtBeginning: selection.focusOffset === 0,
500 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
507 if(anchorElement.parent().sameNode(focusElement.parent())) {
508 var parent = anchorElement.parent(),
509 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
511 if(which === 'start') {
512 element = anchorElement;
513 offset = selection.anchorOffset
515 else if(which === 'end') {
516 element = focusElement,
517 offset = selection.focusOffset
520 if(which === 'start') {
521 element = focusElement,
522 offset = selection.focusOffset
524 else if(which === 'end') {
525 element = anchorElement;
526 offset = selection.anchorOffset
530 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
531 if(which === 'start') {
532 element = anchorElement;
533 offset = selection.anchorOffset
535 element = focusElement;
536 offset = selection.focusOffset
540 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
544 offsetAtBeginning: offset === 0,
545 offsetAtEnd: nodeLen === offset
551 fromXMLDocument: function(wlxmlDocument, publisher) {
552 return new Canvas(wlxmlDocument, publisher);