5 'modules/documentCanvas/canvas/documentElement',
6 'modules/documentCanvas/canvas/keyboard',
7 'modules/documentCanvas/canvas/utils'
8 ], function($, _, Backbone, documentElement, keyboard, utils) {
12 var Canvas = function(wlxmlDocument, publisher) {
13 this.eventBus = _.extend({}, Backbone.Events);
14 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
15 this.loadWlxmlDocument(wlxmlDocument);
16 this.publisher = publisher ? publisher : function() {};
19 $.extend(Canvas.prototype, {
21 loadWlxmlDocument: function(wlxmlDocument) {
25 var canvasDOM = this.generateCanvasDOM(wlxmlDocument.root);
28 this.wrapper.append(canvasDOM);
29 this.d = this.wrapper.children(0);
30 this.setupEventHandling();
33 generateCanvasDOM: function(wlxmlNode) {
35 var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
41 setupEventHandling: function() {
43 this.wrapper.on('keyup keydown keypress', function(e) {
44 keyboard.handleKey(e, this);
47 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
49 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
52 var observer = new MutationObserver(function(mutations) {
53 mutations.forEach(function(mutation) {
54 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
55 observer.disconnect();
56 if(mutation.target.data === '')
57 mutation.target.data = utils.unicode.ZWS;
58 else if(mutation.oldValue === utils.unicode.ZWS) {
59 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
60 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
62 observer.observe(canvas.d[0], config);
63 canvas.publisher('contentChanged');
67 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
68 observer.observe(this.d[0], config);
71 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
72 var el = canvas.getDocumentElement(e.currentTarget);
76 if(el instanceof documentElement.DocumentTextElement)
80 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
81 var el = canvas.getDocumentElement(e.currentTarget);
85 if(el instanceof documentElement.DocumentTextElement)
87 el.toggleLabel(false);
90 this.eventBus.on('elementToggled', function(toggle, element) {
92 canvas.setCurrentElement(element.getPreviousTextElement());
104 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
107 createNodeElement: function(params) {
108 return documentElement.DocumentNodeElement.create(params, this);
111 wrapText: function(params) {
112 params = _.extend({textNodeIdx: 0}, params);
113 if(typeof params.textNodeIdx === 'number')
114 params.textNodeIdx = [params.textNodeIdx];
116 var childrenInside = params.inside.children(),
117 idx1 = Math.min.apply(Math, params.textNodeIdx),
118 idx2 = Math.max.apply(Math, params.textNodeIdx),
119 textNode1 = childrenInside[idx1],
120 textNode2 = childrenInside[idx2],
121 sameNode = textNode1.sameNode(textNode2),
122 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
123 prefixInside = textNode1.getText().substr(params.offsetStart),
124 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
125 suffixOutside = textNode2.getText().substr(params.offsetEnd)
128 var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
129 textNode1.after(wrapperElement);
132 if(prefixOutside.length > 0)
133 wrapperElement.before({text:prefixOutside});
135 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
136 wrapperElement.append({text: core});
139 if(prefixInside.length > 0)
140 wrapperElement.append({text: prefixInside});
141 for(var i = idx1 + 1; i < idx2; i++) {
142 wrapperElement.append(childrenInside[i]);
144 if(suffixInside.length > 0)
145 wrapperElement.append({text: suffixInside});
147 if(suffixOutside.length > 0)
148 wrapperElement.after({text: suffixOutside});
149 return wrapperElement;
152 wrapElements: function(params) {
153 if(!(params.element1.parent().sameNode(params.element2.parent())))
156 var parent = params.element1.parent(),
157 parentChildren = parent.children(),
158 wrapper = this.createNodeElement({
159 tag: params._with.tag,
160 klass: params._with.klass}),
161 idx1 = parent.childIndex(params.element1),
162 idx2 = parent.childIndex(params.element2);
170 var insertingMethod, insertingTarget;
172 insertingMethod = 'prepend';
173 insertingTarget = parent;
175 insertingMethod = 'after';
176 insertingTarget = parentChildren[idx1-1];
179 for(var i = idx1; i <= idx2; i++) {
180 wrapper.append(parentChildren[i].detach());
183 insertingTarget[insertingMethod](wrapper);
187 getSiblingParents: function(params) {
188 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
189 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
190 noSiblingParents = null;
192 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
193 return noSiblingParents;
196 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
197 if(parents1[i].sameNode(parents2[i]))
201 return {element1: parents1[i], element2: parents2[i]};
204 getDocumentElement: function(from) {
205 if(from instanceof HTMLElement || from instanceof Text) {
206 return documentElement.DocumentElement.fromHTMLElement(from, this);
209 getCursor: function() {
210 return new Cursor(this);
216 getCurrentNodeElement: function() {
217 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
220 getCurrentTextElement: function() {
221 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
226 setCurrentElement: function(element, params) {
227 params = _.extend({caretTo: 'end'}, params);
228 var findFirstDirectTextChild = function(e, nodeToLand) {
229 var byBrowser = this.getCursor().getPosition().element;
230 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
232 var children = e.children();
233 for(var i = 0; i < children.length; i++) {
234 if(children[i] instanceof documentElement.DocumentTextElement)
239 var _markAsCurrent = function(element) {
240 if(element instanceof documentElement.DocumentTextElement) {
241 this.wrapper.find('.current-text-element').removeClass('current-text-element');
242 element.dom().addClass('current-text-element');
244 this.wrapper.find('.current-node-element').removeClass('current-node-element')
245 element._container().addClass('current-node-element');
246 this.publisher('currentElementChanged', element);
251 var isTextElement = element instanceof documentElement.DocumentTextElement,
252 nodeElementToLand = isTextElement ? element.parent() : element,
253 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
254 currentTextElement = this.getCurrentTextElement(),
255 currentNodeElement = this.getCurrentNodeElement();
257 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
258 this.wrapper.find('.current-text-element').removeClass('current-text-element');
260 if(textElementToLand) {
261 _markAsCurrent(textElementToLand);
262 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
263 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
264 if(!(textElementToLand.sameNode(currentTextElement)))
265 this.publisher('currentTextElementSet', textElementToLand);
267 document.getSelection().removeAllRanges();
270 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
271 _markAsCurrent(nodeElementToLand);
273 this.publisher('currentNodeElementSet', nodeElementToLand);
277 _moveCaretToTextElement: function(element, where) {
278 var range = document.createRange(),
279 node = element.dom().contents()[0];
281 if(typeof where !== 'number') {
282 range.selectNodeContents(node);
284 range.setStart(node, where);
287 var collapseArg = true;
290 range.collapse(collapseArg);
292 var selection = document.getSelection();
294 selection.removeAllRanges();
295 selection.addRange(range);
296 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
299 setCursorPosition: function(position) {
301 this._moveCaretToTextElement(position.element, position.offset);
305 var parent = $('<div>'),
306 parts = this.doc().toXML(0);
307 parent.append(parts);
308 return parent.html();
312 $.extend(Canvas.prototype.list, {
313 create: function(params) {
314 if(!(params.element1.parent().sameNode(params.element2.parent())))
317 var parent = params.element1.parent(),
318 canvas = params.element1.canvas;
320 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
321 var tmp = params.element1;
322 params.element1 = params.element2;
323 params.element2 = tmp;
326 var elementsToWrap = [];
328 var place = 'before';
329 parent.children().some(function(element) {
331 if(element.sameNode(params.element1))
333 if(place === 'inside') {
334 if(element instanceof documentElement.DocumentTextElement) {
335 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
336 if(element.children()[0].sameNode(params.element1))
337 params.element1 = element;
339 element.setWlxmlClass('item');
340 elementsToWrap.push(element);
342 if(_e.sameNode(params.element2))
346 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
348 if(parent.is('list')) {
349 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
350 item.exec('toggleBullet', false);
351 toret = listElement.parent();
356 params.element1.before(toret);
358 elementsToWrap.forEach(function(element) {
360 listElement.append(element);
363 extractItems: function(params) {
364 params = _.extend({merge: true}, params);
365 var list = params.element1.parent();
366 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
369 var idx1 = list.childIndex(params.element1),
370 idx2 = list.childIndex(params.element2),
373 succeedingItems = [],
374 items = list.children(),
375 listIsNested = list.parent().getWlxmlClass() === 'item',
376 canvas = params.element1.canvas,
380 var tmp = idx1; idx1 = idx2; idx2 = tmp;
383 items.forEach(function(item, idx) {
385 precedingItems.push(item);
386 else if(idx >= idx1 && idx <= idx2) {
387 extractedItems.push(item);
390 succeedingItems.push(item);
394 var reference = listIsNested ? list.parent() : list;
395 if(succeedingItems.length === 0) {
396 var reference_orig = reference;
397 extractedItems.forEach(function(item) {
398 reference.after(item);
401 item.setWlxmlClass(null);
403 if(precedingItems.length === 0)
404 reference_orig.detach();
405 } else if(precedingItems.length === 0) {
406 extractedItems.forEach(function(item) {
407 reference.before(item);
409 item.setWlxmlClass(null);
412 extractedItems.forEach(function(item) {
413 reference.after(item);
415 item.setWlxmlClass(null);
418 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
422 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
424 succeedingItems.forEach(function(item) {
425 secondList.append(item);
428 reference.after(toAdd);
430 if(!params.merge && listIsNested) {
431 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
435 areItemsOfTheSameList: function(params) {
436 var e1 = params.element1,
437 e2 = params.element2;
438 return e1.parent().sameNode(e2.parent())
439 && e1.parent().is('list');
444 var Cursor = function(canvas) {
445 this.canvas = canvas;
448 $.extend(Cursor.prototype, {
449 isSelecting: function() {
450 var selection = window.getSelection();
451 return !selection.isCollapsed;
453 isSelectingWithinElement: function() {
454 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
456 isSelectingSiblings: function() {
457 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
459 getPosition: function() {
460 return this.getSelectionAnchor();
462 getSelectionStart: function() {
463 return this.getSelectionBoundry('start');
465 getSelectionEnd: function() {
466 return this.getSelectionBoundry('end');
468 getSelectionAnchor: function() {
469 return this.getSelectionBoundry('anchor');
471 getSelectionFocus: function() {
472 return this.getSelectionBoundry('focus');
474 getSelectionBoundry: function(which) {
475 var selection = window.getSelection(),
476 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
477 focusElement = this.canvas.getDocumentElement(selection.focusNode);
479 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
482 if(which === 'anchor') {
484 element: anchorElement,
485 offset: selection.anchorOffset,
486 offsetAtBeginning: selection.anchorOffset === 0,
487 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
490 if(which === 'focus') {
492 element: focusElement,
493 offset: selection.focusOffset,
494 offsetAtBeginning: selection.focusOffset === 0,
495 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
502 if(anchorElement.parent().sameNode(focusElement.parent())) {
503 var parent = anchorElement.parent(),
504 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
506 if(which === 'start') {
507 element = anchorElement;
508 offset = selection.anchorOffset
510 else if(which === 'end') {
511 element = focusElement,
512 offset = selection.focusOffset
515 if(which === 'start') {
516 element = focusElement,
517 offset = selection.focusOffset
519 else if(which === 'end') {
520 element = anchorElement;
521 offset = selection.anchorOffset
525 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
526 if(which === 'start') {
527 element = anchorElement;
528 offset = selection.anchorOffset
530 element = focusElement;
531 offset = selection.focusOffset
535 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
539 offsetAtBeginning: offset === 0,
540 offsetAtEnd: nodeLen === offset
546 fromXMLDocument: function(wlxmlDocument, publisher) {
547 return new Canvas(wlxmlDocument, publisher);