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 textElement.data('wlxmlNode').setText(mutation.target.data);
73 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
74 observer.observe(this.d[0], config);
77 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
78 var el = canvas.getDocumentElement(e.currentTarget);
82 if(el instanceof documentElement.DocumentTextElement)
86 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
87 var el = canvas.getDocumentElement(e.currentTarget);
91 if(el instanceof documentElement.DocumentTextElement)
93 el.toggleLabel(false);
96 this.eventBus.on('elementToggled', function(toggle, element) {
98 canvas.setCurrentElement(element.getPreviousTextElement());
110 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
113 toggleElementHighlight: function(node, toggle) {
114 var element = utils.findCanvasElement(node);
115 element.toggleHighlight(toggle);
118 createNodeElement: function(params) {
119 return documentElement.DocumentNodeElement.create(params, this);
122 wrapText: function(params) {
123 params = _.extend({textNodeIdx: 0}, params);
124 if(typeof params.textNodeIdx === 'number')
125 params.textNodeIdx = [params.textNodeIdx];
127 var childrenInside = params.inside.children(),
128 idx1 = Math.min.apply(Math, params.textNodeIdx),
129 idx2 = Math.max.apply(Math, params.textNodeIdx),
130 textNode1 = childrenInside[idx1],
131 textNode2 = childrenInside[idx2],
132 sameNode = textNode1.sameNode(textNode2),
133 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
134 prefixInside = textNode1.getText().substr(params.offsetStart),
135 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
136 suffixOutside = textNode2.getText().substr(params.offsetEnd)
139 var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
140 textNode1.after(wrapperElement);
143 if(prefixOutside.length > 0)
144 wrapperElement.before({text:prefixOutside});
146 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
147 wrapperElement.append({text: core});
150 if(prefixInside.length > 0)
151 wrapperElement.append({text: prefixInside});
152 for(var i = idx1 + 1; i < idx2; i++) {
153 wrapperElement.append(childrenInside[i]);
155 if(suffixInside.length > 0)
156 wrapperElement.append({text: suffixInside});
158 if(suffixOutside.length > 0)
159 wrapperElement.after({text: suffixOutside});
160 return wrapperElement;
163 wrapElements: function(params) {
164 if(!(params.element1.parent().sameNode(params.element2.parent())))
167 var parent = params.element1.parent(),
168 parentChildren = parent.children(),
169 wrapper = this.createNodeElement({
170 tag: params._with.tag,
171 klass: params._with.klass}),
172 idx1 = parent.childIndex(params.element1),
173 idx2 = parent.childIndex(params.element2);
181 var insertingMethod, insertingTarget;
183 insertingMethod = 'prepend';
184 insertingTarget = parent;
186 insertingMethod = 'after';
187 insertingTarget = parentChildren[idx1-1];
190 for(var i = idx1; i <= idx2; i++) {
191 wrapper.append(parentChildren[i].detach());
194 insertingTarget[insertingMethod](wrapper);
198 getSiblingParents: function(params) {
199 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
200 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
201 noSiblingParents = null;
203 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
204 return noSiblingParents;
207 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
208 if(parents1[i].sameNode(parents2[i]))
212 return {element1: parents1[i], element2: parents2[i]};
215 getDocumentElement: function(from) {
216 if(from instanceof HTMLElement || from instanceof Text) {
217 return documentElement.DocumentElement.fromHTMLElement(from, this);
220 getCursor: function() {
221 return new Cursor(this);
227 getCurrentNodeElement: function() {
228 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
231 getCurrentTextElement: function() {
232 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
237 setCurrentElement: function(element, params) {
238 if(!(element instanceof documentElement.DocumentElement)) {
239 element = utils.findCanvasElement(element);
242 params = _.extend({caretTo: 'end'}, params);
243 var findFirstDirectTextChild = function(e, nodeToLand) {
244 var byBrowser = this.getCursor().getPosition().element;
245 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
247 var children = e.children();
248 for(var i = 0; i < children.length; i++) {
249 if(children[i] instanceof documentElement.DocumentTextElement)
254 var _markAsCurrent = function(element) {
255 if(element instanceof documentElement.DocumentTextElement) {
256 this.wrapper.find('.current-text-element').removeClass('current-text-element');
257 element.dom().addClass('current-text-element');
259 this.wrapper.find('.current-node-element').removeClass('current-node-element')
260 element._container().addClass('current-node-element');
261 this.publisher('currentElementChanged', element);
266 var isTextElement = element instanceof documentElement.DocumentTextElement,
267 nodeElementToLand = isTextElement ? element.parent() : element,
268 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
269 currentTextElement = this.getCurrentTextElement(),
270 currentNodeElement = this.getCurrentNodeElement();
272 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
273 this.wrapper.find('.current-text-element').removeClass('current-text-element');
275 if(textElementToLand) {
276 _markAsCurrent(textElementToLand);
277 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
278 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
279 if(!(textElementToLand.sameNode(currentTextElement)))
280 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
282 document.getSelection().removeAllRanges();
285 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
286 _markAsCurrent(nodeElementToLand);
288 this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
292 _moveCaretToTextElement: function(element, where) {
293 var range = document.createRange(),
294 node = element.dom().contents()[0];
296 if(typeof where !== 'number') {
297 range.selectNodeContents(node);
299 range.setStart(node, where);
302 var collapseArg = true;
305 range.collapse(collapseArg);
307 var selection = document.getSelection();
309 selection.removeAllRanges();
310 selection.addRange(range);
311 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
314 setCursorPosition: function(position) {
316 this._moveCaretToTextElement(position.element, position.offset);
320 var parent = $('<div>'),
321 parts = this.doc().toXML(0);
322 parent.append(parts);
323 return parent.html();
327 $.extend(Canvas.prototype.list, {
328 create: function(params) {
329 if(!(params.element1.parent().sameNode(params.element2.parent())))
332 var parent = params.element1.parent(),
333 canvas = params.element1.canvas;
335 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
336 var tmp = params.element1;
337 params.element1 = params.element2;
338 params.element2 = tmp;
341 var elementsToWrap = [];
343 var place = 'before';
344 parent.children().some(function(element) {
346 if(element.sameNode(params.element1))
348 if(place === 'inside') {
349 if(element instanceof documentElement.DocumentTextElement) {
350 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
351 if(element.children()[0].sameNode(params.element1))
352 params.element1 = element;
354 element.setWlxmlClass('item');
355 elementsToWrap.push(element);
357 if(_e.sameNode(params.element2))
361 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
363 if(parent.is('list')) {
364 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
365 item.exec('toggleBullet', false);
366 toret = listElement.parent();
371 params.element1.before(toret);
373 elementsToWrap.forEach(function(element) {
375 listElement.append(element);
378 extractItems: function(params) {
379 params = _.extend({merge: true}, params);
380 var list = params.element1.parent();
381 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
384 var idx1 = list.childIndex(params.element1),
385 idx2 = list.childIndex(params.element2),
388 succeedingItems = [],
389 items = list.children(),
390 listIsNested = list.parent().getWlxmlClass() === 'item',
391 canvas = params.element1.canvas,
395 var tmp = idx1; idx1 = idx2; idx2 = tmp;
398 items.forEach(function(item, idx) {
400 precedingItems.push(item);
401 else if(idx >= idx1 && idx <= idx2) {
402 extractedItems.push(item);
405 succeedingItems.push(item);
409 var reference = listIsNested ? list.parent() : list;
410 if(succeedingItems.length === 0) {
411 var reference_orig = reference;
412 extractedItems.forEach(function(item) {
413 reference.after(item);
416 item.setWlxmlClass(null);
418 if(precedingItems.length === 0)
419 reference_orig.detach();
420 } else if(precedingItems.length === 0) {
421 extractedItems.forEach(function(item) {
422 reference.before(item);
424 item.setWlxmlClass(null);
427 extractedItems.forEach(function(item) {
428 reference.after(item);
430 item.setWlxmlClass(null);
433 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
437 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
439 succeedingItems.forEach(function(item) {
440 secondList.append(item);
443 reference.after(toAdd);
445 if(!params.merge && listIsNested) {
446 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
450 areItemsOfTheSameList: function(params) {
451 var e1 = params.element1,
452 e2 = params.element2;
453 return e1.parent().sameNode(e2.parent())
454 && e1.parent().is('list');
459 var Cursor = function(canvas) {
460 this.canvas = canvas;
463 $.extend(Cursor.prototype, {
464 isSelecting: function() {
465 var selection = window.getSelection();
466 return !selection.isCollapsed;
468 isSelectingWithinElement: function() {
469 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
471 isSelectingSiblings: function() {
472 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
474 getPosition: function() {
475 return this.getSelectionAnchor();
477 getSelectionStart: function() {
478 return this.getSelectionBoundry('start');
480 getSelectionEnd: function() {
481 return this.getSelectionBoundry('end');
483 getSelectionAnchor: function() {
484 return this.getSelectionBoundry('anchor');
486 getSelectionFocus: function() {
487 return this.getSelectionBoundry('focus');
489 getSelectionBoundry: function(which) {
490 var selection = window.getSelection(),
491 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
492 focusElement = this.canvas.getDocumentElement(selection.focusNode);
494 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
497 if(which === 'anchor') {
499 element: anchorElement,
500 offset: selection.anchorOffset,
501 offsetAtBeginning: selection.anchorOffset === 0,
502 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
505 if(which === 'focus') {
507 element: focusElement,
508 offset: selection.focusOffset,
509 offsetAtBeginning: selection.focusOffset === 0,
510 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
517 if(anchorElement.parent().sameNode(focusElement.parent())) {
518 var parent = anchorElement.parent(),
519 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
521 if(which === 'start') {
522 element = anchorElement;
523 offset = selection.anchorOffset
525 else if(which === 'end') {
526 element = focusElement,
527 offset = selection.focusOffset
530 if(which === 'start') {
531 element = focusElement,
532 offset = selection.focusOffset
534 else if(which === 'end') {
535 element = anchorElement;
536 offset = selection.anchorOffset
540 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
541 if(which === 'start') {
542 element = anchorElement;
543 offset = selection.anchorOffset
545 element = focusElement;
546 offset = selection.focusOffset
550 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
554 offsetAtBeginning: offset === 0,
555 offsetAtEnd: nodeLen === offset
561 fromXMLDocument: function(wlxmlDocument, publisher) {
562 return new Canvas(wlxmlDocument, publisher);