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(wlxml, publisher) {
13 this.eventBus = _.extend({}, Backbone.Events);
14 this.loadWlxmlDocument(wlxml);
15 this.publisher = publisher ? publisher : function() {};
18 $.extend(Canvas.prototype, {
20 loadWlxmlDocument: function(wlxmlDocument) {
21 var canvasDOM = this.generateCanvasDOM(wlxmlDocument.root);
23 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
24 this.wrapper.append(canvasDOM);
25 this.d = this.wrapper.children(0);
26 this.setupEventHandling();
29 generateCanvasDOM: function(wlxmlNode) {
30 // var element = this.createNodeElement2({
31 // tag: wlxmlNode.getTagName(),
32 // klass: wlxmlNode.getClass(), //currentTag.attr('class'),
33 // meta: wlxmlNode.getMetaAttributes(), //meta,
34 // others: wlxmlNode.getOtherAttributes(), // ~ //others,
35 // rawChildren: wlxmlNode.contents(),
36 // prepopulateOnEmpty: true
39 var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
42 ['orig-before', 'orig-after', 'orig-begin', 'orig-end'].forEach(function(attr) {
43 element.data(attr, '');
48 setupEventHandling: function() {
50 this.wrapper.on('keyup keydown keypress', function(e) {
51 keyboard.handleKey(e, this);
54 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
56 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
59 var observer = new MutationObserver(function(mutations) {
60 mutations.forEach(function(mutation) {
61 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
62 observer.disconnect();
63 if(mutation.target.data === '')
64 mutation.target.data = utils.unicode.ZWS;
65 else if(mutation.oldValue === utils.unicode.ZWS) {
66 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
67 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
69 observer.observe(canvas.d[0], config);
70 canvas.publisher('contentChanged');
74 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
75 observer.observe(this.d[0], config);
78 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
79 var el = canvas.getDocumentElement(e.currentTarget);
83 if(el instanceof documentElement.DocumentTextElement)
87 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
88 var el = canvas.getDocumentElement(e.currentTarget);
92 if(el instanceof documentElement.DocumentTextElement)
94 el.toggleLabel(false);
97 this.eventBus.on('elementToggled', function(toggle, element) {
99 canvas.setCurrentElement(element.getPreviousTextElement());
111 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
114 createNodeElement: function(params) {
115 return documentElement.DocumentNodeElement.create(params, this);
118 wrapText: function(params) {
119 params = _.extend({textNodeIdx: 0}, params);
120 if(typeof params.textNodeIdx === 'number')
121 params.textNodeIdx = [params.textNodeIdx];
123 var childrenInside = params.inside.children(),
124 idx1 = Math.min.apply(Math, params.textNodeIdx),
125 idx2 = Math.max.apply(Math, params.textNodeIdx),
126 textNode1 = childrenInside[idx1],
127 textNode2 = childrenInside[idx2],
128 sameNode = textNode1.sameNode(textNode2),
129 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
130 prefixInside = textNode1.getText().substr(params.offsetStart),
131 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
132 suffixOutside = textNode2.getText().substr(params.offsetEnd)
135 var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
136 textNode1.after(wrapperElement);
139 if(prefixOutside.length > 0)
140 wrapperElement.before({text:prefixOutside});
142 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
143 wrapperElement.append({text: core});
146 if(prefixInside.length > 0)
147 wrapperElement.append({text: prefixInside});
148 for(var i = idx1 + 1; i < idx2; i++) {
149 wrapperElement.append(childrenInside[i]);
151 if(suffixInside.length > 0)
152 wrapperElement.append({text: suffixInside});
154 if(suffixOutside.length > 0)
155 wrapperElement.after({text: suffixOutside});
156 return wrapperElement;
159 wrapElements: function(params) {
160 if(!(params.element1.parent().sameNode(params.element2.parent())))
163 var parent = params.element1.parent(),
164 parentChildren = parent.children(),
165 wrapper = this.createNodeElement({
166 tag: params._with.tag,
167 klass: params._with.klass}),
168 idx1 = parent.childIndex(params.element1),
169 idx2 = parent.childIndex(params.element2);
177 var insertingMethod, insertingTarget;
179 insertingMethod = 'prepend';
180 insertingTarget = parent;
182 insertingMethod = 'after';
183 insertingTarget = parentChildren[idx1-1];
186 for(var i = idx1; i <= idx2; i++) {
187 wrapper.append(parentChildren[i].detach());
190 insertingTarget[insertingMethod](wrapper);
194 getSiblingParents: function(params) {
195 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
196 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
197 noSiblingParents = null;
199 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
200 return noSiblingParents;
203 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
204 if(parents1[i].sameNode(parents2[i]))
208 return {element1: parents1[i], element2: parents2[i]};
211 getDocumentElement: function(from) {
212 if(from instanceof HTMLElement || from instanceof Text) {
213 return documentElement.DocumentElement.fromHTMLElement(from, this);
216 getCursor: function() {
217 return new Cursor(this);
223 getCurrentNodeElement: function() {
224 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
227 getCurrentTextElement: function() {
228 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
233 setCurrentElement: function(element, params) {
234 params = _.extend({caretTo: 'end'}, params);
235 var findFirstDirectTextChild = function(e, nodeToLand) {
236 var byBrowser = this.getCursor().getPosition().element;
237 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
239 var children = e.children();
240 for(var i = 0; i < children.length; i++) {
241 if(children[i] instanceof documentElement.DocumentTextElement)
246 var _markAsCurrent = function(element) {
247 if(element instanceof documentElement.DocumentTextElement) {
248 this.wrapper.find('.current-text-element').removeClass('current-text-element');
249 element.dom().addClass('current-text-element');
251 this.wrapper.find('.current-node-element').removeClass('current-node-element')
252 element._container().addClass('current-node-element');
253 this.publisher('currentElementChanged', element);
258 var isTextElement = element instanceof documentElement.DocumentTextElement,
259 nodeElementToLand = isTextElement ? element.parent() : element,
260 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
261 currentTextElement = this.getCurrentTextElement(),
262 currentNodeElement = this.getCurrentNodeElement();
264 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
265 this.wrapper.find('.current-text-element').removeClass('current-text-element');
267 if(textElementToLand) {
268 _markAsCurrent(textElementToLand);
269 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
270 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
271 if(!(textElementToLand.sameNode(currentTextElement)))
272 this.publisher('currentTextElementSet', textElementToLand);
274 document.getSelection().removeAllRanges();
277 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
278 _markAsCurrent(nodeElementToLand);
280 this.publisher('currentNodeElementSet', nodeElementToLand);
284 _moveCaretToTextElement: function(element, where) {
285 var range = document.createRange(),
286 node = element.dom().contents()[0];
288 if(typeof where !== 'number') {
289 range.selectNodeContents(node);
291 range.setStart(node, where);
294 var collapseArg = true;
297 range.collapse(collapseArg);
299 var selection = document.getSelection();
301 selection.removeAllRanges();
302 selection.addRange(range);
303 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
306 setCursorPosition: function(position) {
308 this._moveCaretToTextElement(position.element, position.offset);
312 var parent = $('<div>'),
313 parts = this.doc().toXML(0);
314 parent.append(parts);
315 return parent.html();
319 $.extend(Canvas.prototype.list, {
320 create: function(params) {
321 if(!(params.element1.parent().sameNode(params.element2.parent())))
324 var parent = params.element1.parent(),
325 canvas = params.element1.canvas;
327 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
328 var tmp = params.element1;
329 params.element1 = params.element2;
330 params.element2 = tmp;
333 var elementsToWrap = [];
335 var place = 'before';
336 parent.children().some(function(element) {
338 if(element.sameNode(params.element1))
340 if(place === 'inside') {
341 if(element instanceof documentElement.DocumentTextElement) {
342 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
343 if(element.children()[0].sameNode(params.element1))
344 params.element1 = element;
346 element.setWlxmlClass('item');
347 elementsToWrap.push(element);
349 if(_e.sameNode(params.element2))
353 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
355 if(parent.is('list')) {
356 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
357 item.exec('toggleBullet', false);
358 toret = listElement.parent();
363 params.element1.before(toret);
365 elementsToWrap.forEach(function(element) {
367 listElement.append(element);
370 extractItems: function(params) {
371 params = _.extend({merge: true}, params);
372 var list = params.element1.parent();
373 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
376 var idx1 = list.childIndex(params.element1),
377 idx2 = list.childIndex(params.element2),
380 succeedingItems = [],
381 items = list.children(),
382 listIsNested = list.parent().getWlxmlClass() === 'item',
383 canvas = params.element1.canvas,
387 var tmp = idx1; idx1 = idx2; idx2 = tmp;
390 items.forEach(function(item, idx) {
392 precedingItems.push(item);
393 else if(idx >= idx1 && idx <= idx2) {
394 extractedItems.push(item);
397 succeedingItems.push(item);
401 var reference = listIsNested ? list.parent() : list;
402 if(succeedingItems.length === 0) {
403 var reference_orig = reference;
404 extractedItems.forEach(function(item) {
405 reference.after(item);
408 item.setWlxmlClass(null);
410 if(precedingItems.length === 0)
411 reference_orig.detach();
412 } else if(precedingItems.length === 0) {
413 extractedItems.forEach(function(item) {
414 reference.before(item);
416 item.setWlxmlClass(null);
419 extractedItems.forEach(function(item) {
420 reference.after(item);
422 item.setWlxmlClass(null);
425 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
429 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
431 succeedingItems.forEach(function(item) {
432 secondList.append(item);
435 reference.after(toAdd);
437 if(!params.merge && listIsNested) {
438 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
442 areItemsOfTheSameList: function(params) {
443 var e1 = params.element1,
444 e2 = params.element2;
445 return e1.parent().sameNode(e2.parent())
446 && e1.parent().is('list');
451 var Cursor = function(canvas) {
452 this.canvas = canvas;
455 $.extend(Cursor.prototype, {
456 isSelecting: function() {
457 var selection = window.getSelection();
458 return !selection.isCollapsed;
460 isSelectingWithinElement: function() {
461 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
463 isSelectingSiblings: function() {
464 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
466 getPosition: function() {
467 return this.getSelectionAnchor();
469 getSelectionStart: function() {
470 return this.getSelectionBoundry('start');
472 getSelectionEnd: function() {
473 return this.getSelectionBoundry('end');
475 getSelectionAnchor: function() {
476 return this.getSelectionBoundry('anchor');
478 getSelectionFocus: function() {
479 return this.getSelectionBoundry('focus');
481 getSelectionBoundry: function(which) {
482 var selection = window.getSelection(),
483 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
484 focusElement = this.canvas.getDocumentElement(selection.focusNode);
486 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
489 if(which === 'anchor') {
491 element: anchorElement,
492 offset: selection.anchorOffset,
493 offsetAtBeginning: selection.anchorOffset === 0,
494 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
497 if(which === 'focus') {
499 element: focusElement,
500 offset: selection.focusOffset,
501 offsetAtBeginning: selection.focusOffset === 0,
502 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
509 if(anchorElement.parent().sameNode(focusElement.parent())) {
510 var parent = anchorElement.parent(),
511 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
513 if(which === 'start') {
514 element = anchorElement;
515 offset = selection.anchorOffset
517 else if(which === 'end') {
518 element = focusElement,
519 offset = selection.focusOffset
522 if(which === 'start') {
523 element = focusElement,
524 offset = selection.focusOffset
526 else if(which === 'end') {
527 element = anchorElement;
528 offset = selection.anchorOffset
532 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
533 if(which === 'start') {
534 element = anchorElement;
535 offset = selection.anchorOffset
537 element = focusElement;
538 offset = selection.focusOffset
542 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
546 offsetAtBeginning: offset === 0,
547 offsetAtEnd: nodeLen === offset
553 fromXML: function(wlxmlNode, publisher) {
554 return new Canvas(wlxmlNode, publisher);